Skip to content

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

chore: stable fix, add tutorbot

Bingxi Zhao (Frank)c15e22a4b39f
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 1b225af06..213526d5e 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -48,7 +48,7 @@ jobs:
uses: actions/cache@v4
with:
path: ~/.cache/pip
- key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements/server.txt', 'requirements/core.txt') }}
+ key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements/server.txt', 'requirements/cli.txt') }}
restore-keys: |
${{ runner.os }}-pip-${{ matrix.python-version }}-
@@ -88,7 +88,7 @@ jobs:
uses: actions/cache@v4
with:
path: ~/.cache/pip
- key: ${{ runner.os }}-pip-3.11-${{ hashFiles('requirements/server.txt', 'requirements/core.txt') }}
+ key: ${{ runner.os }}-pip-3.11-${{ hashFiles('requirements/server.txt', 'requirements/cli.txt') }}
restore-keys: |
${{ runner.os }}-pip-3.11-
diff --git a/.gitignore b/.gitignore
index 1cc620069..efe6797e0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,14 +5,24 @@
# ============================================
# User Generated Data and Outputs
# ============================================
-# User data directory (migrated to data/user/)
-data/user/
-data/knowledge_bases/
+# Runtime data (knowledge bases, tutorbot workspaces, memory, etc.)
+data/
run_code_workspace/
deeptutor/agents/question/reference_papers/
deeptutor/services/rag/eg_only_for_analysis/
paper/
+# LaTeX build artifacts
+*.aux
+*.bbl
+*.blg
+*.fdb_latexmk
+*.fls
+*.out
+*.synctex.gz
+*.pdf
+!demo/*.pdf
+
# ============================================
# Python Related
# ============================================
diff --git a/AGENTS.md b/AGENTS.md
index 5e511eba4..599f9ac13 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -58,24 +58,26 @@ Extended features in `deeptutor/plugins/`:
## CLI Usage
```bash
-# Install (CLI only, ~80MB)
-pip install -r requirements/core.txt
+# Install CLI
+pip install -r requirements/cli.txt && pip install -e .
-# Chat
+# Run any capability (agent-first entry point)
+deeptutor run chat "Explain Fourier transform"
+deeptutor run deep_solve "Solve x^2=4" -t rag --kb my-kb
+deeptutor run deep_question "Linear algebra" --config num_questions=5
+
+# Interactive REPL
deeptutor chat
-deeptutor chat --once "Solve x^2=4" --capability deep-solve --tool rag
# Knowledge bases
deeptutor kb list
deeptutor kb create my-kb --doc textbook.pdf
-# Memory
-deeptutor memory show
-
-# Plugins
+# Plugins & memory
deeptutor plugin list
+deeptutor memory show
-# API server (requires requirements/server.txt)
+# API server (requires server.txt)
deeptutor serve --port 8001
```
@@ -139,10 +141,8 @@ class MyPlugin(BaseCapability):
## Dependency Layers
```
-requirements/core.txt — CLI minimum (~80MB)
-requirements/server.txt — + FastAPI/uvicorn
-requirements/rag-lite.txt — + LlamaIndex RAG
-requirements/rag-full.txt — compatibility alias of rag-lite (LlamaIndex-only)
-requirements/providers.txt — + native LLM SDKs
-requirements/dev.txt — + test/lint tools
+requirements/cli.txt — CLI full (LLM + RAG + providers + tools)
+requirements/server.txt — CLI + FastAPI/uvicorn (for Web/API)
+requirements/math-animator.txt — Manim addon (for `deeptutor animate`)
+requirements/dev.txt — Server + test/lint tools
```
diff --git a/Dockerfile b/Dockerfile
index acc45bc47..4f21bfdff 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -143,6 +143,7 @@ COPY requirements.txt ./
# Create necessary directories (these will be overwritten by volume mounts)
RUN mkdir -p \
data/user/settings \
+ data/memory \
data/user/workspace/memory \
data/user/workspace/notebook \
data/user/workspace/co-writer/audio \
diff --git a/README.md b/README.md
index aad1fa603..b43c4eab6 100644
--- a/README.md
+++ b/README.md
@@ -1091,8 +1091,8 @@ tools:
**Checklist**
- Confirm Python version >= 3.10
- Confirm dependencies installed for your mode:
- - CLI only: `pip install -r requirements/core.txt`
- - Web/API: `pip install -r requirements/server.txt`
+ - CLI only: `pip install -r requirements/cli.txt && pip install -e .`
+ - Web/API: `pip install -r requirements/server.txt && pip install -e .`
- Check if port 8001 is in use
- Check `.env` file configuration
diff --git a/deeptutor/agents/base_agent.py b/deeptutor/agents/base_agent.py
index c6b8b3f11..bf09c3744 100644
--- a/deeptutor/agents/base_agent.py
+++ b/deeptutor/agents/base_agent.py
@@ -512,6 +512,7 @@ class BaseAgent(ABC):
temperature: float | None = None,
max_tokens: int | None = None,
model: str | None = None,
+ response_format: dict[str, Any] | None = None,
stage: str | None = None,
attachments: list[Any] | None = None,
trace_meta: dict[str, Any] | None = None,
@@ -529,6 +530,7 @@ class BaseAgent(ABC):
temperature: Temperature parameter (optional, uses config by default)
max_tokens: Maximum tokens (optional, uses config by default)
model: Model name (optional, uses config by default)
+ response_format: JSON schema for structured output (optional)
stage: Stage marker for logging
attachments: Image/file attachments for multimodal input (optional)
@@ -548,6 +550,19 @@ class BaseAgent(ABC):
if max_tokens:
kwargs.update(get_token_limit_kwargs(model, max_tokens))
+ # Handle response_format with capability check
+ if response_format:
+ try:
+ config = get_llm_config()
+ binding = getattr(config, "binding", None) or "openai"
+ except Exception:
+ binding = "openai"
+
+ if supports_response_format(binding, model):
+ kwargs["response_format"] = response_format
+ else:
+ self.logger.debug(f"response_format not supported for {binding}/{model}, skipping")
+
# Inject image attachments into messages when provided
if messages and attachments:
mm_result = prepare_multimodal_messages(
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index cd53bdf48..1ff27d46c 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -66,6 +66,24 @@ class AgenticChatPipeline:
self.base_url = getattr(self.llm_config, "base_url", None)
self.api_version = getattr(self.llm_config, "api_version", None)
self.registry = get_tool_registry()
+ self._usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "calls": 0}
+
+ def _accumulate_usage(self, response: Any) -> None:
+ usage = getattr(response, "usage", None)
+ if usage:
+ self._usage["prompt_tokens"] += getattr(usage, "prompt_tokens", 0) or 0
+ self._usage["completion_tokens"] += getattr(usage, "completion_tokens", 0) or 0
+ self._usage["total_tokens"] += getattr(usage, "total_tokens", 0) or 0
+ 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"],
+ }
async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
answer_now_context = self._extract_answer_now_context(context)
@@ -75,14 +93,15 @@ class AgenticChatPipeline:
answer_now_context=answer_now_context,
stream=stream,
)
- await stream.result(
- {
- "response": final_response,
- "answer_now": True,
- "source_trace": trace_meta.get("label", "Answer now"),
- },
- source="chat",
- )
+ result_payload: dict[str, Any] = {
+ "response": final_response,
+ "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")
return
enabled_tools = self._normalize_enabled_tools(context.enabled_tools)
@@ -123,14 +142,15 @@ class AgenticChatPipeline:
),
)
- await stream.result(
- {
- "response": final_response,
- "observation": observation,
- "tool_traces": [asdict(trace) for trace in tool_traces],
- },
- source="chat",
- )
+ result_payload: dict[str, Any] = {
+ "response": final_response,
+ "observation": observation,
+ "tool_traces": [asdict(trace) for trace in tool_traces],
+ }
+ cs = self._get_cost_summary()
+ if cs:
+ result_payload["metadata"] = {"cost_summary": cs}
+ await stream.result(result_payload, source="chat")
async def _stage_thinking(
self,
@@ -496,6 +516,7 @@ class AgenticChatPipeline:
tool_choice="auto",
**self._completion_kwargs(max_tokens=1500),
)
+ self._accumulate_usage(response)
if not response.choices:
return tool_traces
@@ -683,9 +704,12 @@ class AgenticChatPipeline:
{"trace_kind": "call_status", "call_state": "running"},
),
)
- response = await llm_complete(
- prompt=self._acting_user_prompt(context, thinking_text),
- system_prompt=self._react_fallback_system_prompt(tool_table),
+ _fb_prompt = self._acting_user_prompt(context, thinking_text)
+ _fb_system = self._react_fallback_system_prompt(tool_table)
+ _chunks: list[str] = []
+ async for _c in llm_stream(
+ prompt=_fb_prompt,
+ system_prompt=_fb_system,
model=self.model,
api_key=self.api_key,
base_url=self.base_url,
@@ -695,7 +719,15 @@ class AgenticChatPipeline:
if supports_response_format(self.binding, self.model)
else None,
**self._completion_kwargs(max_tokens=800),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
+ _fb_in = int((len(_fb_prompt) + len(_fb_system)) / 3.5)
+ _fb_out = int(len(response) / 3.5)
+ self._usage["prompt_tokens"] += _fb_in
+ self._usage["completion_tokens"] += _fb_out
+ self._usage["total_tokens"] += _fb_in + _fb_out
+ self._usage["calls"] += 1
payload = parse_json_response(response, logger_instance=logger, fallback={})
if not isinstance(payload, dict):
@@ -848,6 +880,7 @@ class AgenticChatPipeline:
messages: list[dict[str, Any]],
max_tokens: int,
):
+ output_chars = 0
async for chunk in llm_stream(
prompt="",
system_prompt="",
@@ -859,7 +892,15 @@ class AgenticChatPipeline:
messages=messages,
**self._completion_kwargs(max_tokens=max_tokens),
):
+ 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
def _build_openai_client(self):
http_client = None
diff --git a/deeptutor/agents/chat/chat_agent.py b/deeptutor/agents/chat/chat_agent.py
index ee7cc98cf..7d31a72dd 100644
--- a/deeptutor/agents/chat/chat_agent.py
+++ b/deeptutor/agents/chat/chat_agent.py
@@ -334,12 +334,10 @@ class ChatAgent(BaseAgent):
user_prompt = msg.get("content", "")
break
- # Use BaseAgent's call_llm which routes through the factory
- # Note: call_llm expects simple prompt/system_prompt, but for multi-turn
- # we need to use the factory directly with messages
- from deeptutor.services.llm import complete as llm_complete
+ from deeptutor.services.llm import stream as llm_stream
- response = await llm_complete(
+ _chunks: list[str] = []
+ async for _c in llm_stream(
prompt=user_prompt,
system_prompt=system_prompt,
model=self.get_model(),
@@ -347,7 +345,9 @@ class ChatAgent(BaseAgent):
base_url=self.base_url,
messages=messages,
temperature=self.get_temperature(),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Track token usage
self._track_tokens(
diff --git a/deeptutor/agents/co_writer/edit_agent.py b/deeptutor/agents/co_writer/edit_agent.py
index a9ae8c34e..2ab5de69f 100644
--- a/deeptutor/agents/co_writer/edit_agent.py
+++ b/deeptutor/agents/co_writer/edit_agent.py
@@ -124,7 +124,7 @@ class EditAgent(BaseAgent):
self.logger.info(f"Searching RAG in KB: {kb_name} for: {instruction}")
try:
search_result = await rag_search(
- query=instruction, kb_name=kb_name, mode="naive", only_need_context=True
+ query=instruction, kb_name=kb_name, only_need_context=True
)
context = search_result.get("answer", "")
self.logger.info(f"RAG context found: {len(context)} chars")
@@ -201,11 +201,14 @@ class EditAgent(BaseAgent):
# Call LLM using inherited method
self.logger.info(f"Calling LLM for {action}...")
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage=f"edit_{action}",
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Record operation history
history = load_history()
@@ -245,11 +248,14 @@ class EditAgent(BaseAgent):
user_prompt = user_template.format(text=text)
self.logger.info("Calling LLM for auto-mark...")
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="auto_mark",
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Record operation history
history = load_history()
diff --git a/deeptutor/agents/guide/agents/chat_agent.py b/deeptutor/agents/guide/agents/chat_agent.py
index 60c4d912e..4c6595034 100644
--- a/deeptutor/agents/guide/agents/chat_agent.py
+++ b/deeptutor/agents/guide/agents/chat_agent.py
@@ -98,10 +98,13 @@ class ChatAgent(BaseAgent):
)
try:
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return {"success": True, "answer": response.strip()}
diff --git a/deeptutor/agents/guide/agents/design_agent.py b/deeptutor/agents/guide/agents/design_agent.py
index f530514b8..9d52d82ca 100644
--- a/deeptutor/agents/guide/agents/design_agent.py
+++ b/deeptutor/agents/guide/agents/design_agent.py
@@ -63,11 +63,14 @@ class DesignAgent(BaseAgent):
user_prompt = user_template.format(user_input=user_input.strip())
try:
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
try:
result = json.loads(response)
diff --git a/deeptutor/agents/guide/agents/interactive_agent.py b/deeptutor/agents/guide/agents/interactive_agent.py
index 755c6862f..56f9be6c3 100644
--- a/deeptutor/agents/guide/agents/interactive_agent.py
+++ b/deeptutor/agents/guide/agents/interactive_agent.py
@@ -208,10 +208,13 @@ Original knowledge point information:
)
try:
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
html_code = self._extract_html(response)
diff --git a/deeptutor/agents/guide/agents/summary_agent.py b/deeptutor/agents/guide/agents/summary_agent.py
index 4c7cc7ecf..86c2a135c 100644
--- a/deeptutor/agents/guide/agents/summary_agent.py
+++ b/deeptutor/agents/guide/agents/summary_agent.py
@@ -110,10 +110,13 @@ class SummaryAgent(BaseAgent):
)
try:
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
cleaned_summary = response.strip()
diff --git a/deeptutor/agents/math_animator/agents/code_generator_agent.py b/deeptutor/agents/math_animator/agents/code_generator_agent.py
index 70a05c26e..a87299322 100644
--- a/deeptutor/agents/math_animator/agents/code_generator_agent.py
+++ b/deeptutor/agents/math_animator/agents/code_generator_agent.py
@@ -63,7 +63,8 @@ class CodeGeneratorAgent(BaseAgent):
analysis_json=json.dumps(analysis.model_dump(), ensure_ascii=False, indent=2),
design_json=json.dumps(design.model_dump(), ensure_ascii=False, indent=2),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
@@ -76,7 +77,9 @@ class CodeGeneratorAgent(BaseAgent):
trace_role="generate",
trace_kind="llm_output",
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return GeneratedCode.model_validate(extract_json_object(response))
async def repair(
@@ -100,7 +103,8 @@ class CodeGeneratorAgent(BaseAgent):
error_message=build_repair_error_message(error_message),
current_code=current_code,
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
@@ -114,5 +118,7 @@ class CodeGeneratorAgent(BaseAgent):
trace_kind="llm_output",
attempt=attempt,
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return GeneratedCode.model_validate(extract_json_object(response))
diff --git a/deeptutor/agents/math_animator/agents/concept_analysis_agent.py b/deeptutor/agents/math_animator/agents/concept_analysis_agent.py
index f3b6735c3..a2f75778e 100644
--- a/deeptutor/agents/math_animator/agents/concept_analysis_agent.py
+++ b/deeptutor/agents/math_animator/agents/concept_analysis_agent.py
@@ -53,7 +53,8 @@ class ConceptAnalysisAgent(BaseAgent):
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
messages=messages,
@@ -68,5 +69,7 @@ class ConceptAnalysisAgent(BaseAgent):
trace_role="analyze",
trace_kind="llm_output",
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return ConceptAnalysis.model_validate(extract_json_object(response))
diff --git a/deeptutor/agents/math_animator/agents/concept_design_agent.py b/deeptutor/agents/math_animator/agents/concept_design_agent.py
index 15d563e99..e16e82605 100644
--- a/deeptutor/agents/math_animator/agents/concept_design_agent.py
+++ b/deeptutor/agents/math_animator/agents/concept_design_agent.py
@@ -47,7 +47,8 @@ class ConceptDesignAgent(BaseAgent):
style_hint=style_hint.strip() or "(none)",
analysis_json=json.dumps(analysis.model_dump(), ensure_ascii=False, indent=2),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
@@ -60,5 +61,7 @@ class ConceptDesignAgent(BaseAgent):
trace_role="design",
trace_kind="llm_output",
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return SceneDesign.model_validate(extract_json_object(response))
diff --git a/deeptutor/agents/math_animator/agents/summary_agent.py b/deeptutor/agents/math_animator/agents/summary_agent.py
index 6507cb365..fdfe34ae7 100644
--- a/deeptutor/agents/math_animator/agents/summary_agent.py
+++ b/deeptutor/agents/math_animator/agents/summary_agent.py
@@ -49,7 +49,8 @@ class SummaryAgent(BaseAgent):
design_json=json.dumps(design.model_dump(), ensure_ascii=False, indent=2),
render_json=json.dumps(render_result.model_dump(), ensure_ascii=False, indent=2),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
response_format={"type": "json_object"},
@@ -62,5 +63,7 @@ class SummaryAgent(BaseAgent):
trace_role="summarize",
trace_kind="llm_output",
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return SummaryPayload.model_validate(extract_json_object(response))
diff --git a/deeptutor/agents/math_animator/agents/visual_review_agent.py b/deeptutor/agents/math_animator/agents/visual_review_agent.py
index 139605095..404153c56 100644
--- a/deeptutor/agents/math_animator/agents/visual_review_agent.py
+++ b/deeptutor/agents/math_animator/agents/visual_review_agent.py
@@ -70,7 +70,8 @@ class VisualReviewAgent(BaseAgent):
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
messages=messages,
@@ -86,7 +87,9 @@ class VisualReviewAgent(BaseAgent):
trace_role="review",
trace_kind="llm_output",
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
payload = extract_json_object(response)
payload.setdefault("reviewed_frames", len(attachments))
return VisualReviewResult.model_validate(payload)
diff --git a/deeptutor/agents/notebook/analysis_agent.py b/deeptutor/agents/notebook/analysis_agent.py
index d1bb53e26..3df08cae3 100644
--- a/deeptutor/agents/notebook/analysis_agent.py
+++ b/deeptutor/agents/notebook/analysis_agent.py
@@ -8,7 +8,7 @@ from typing import Any, Awaitable, Callable
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.trace import build_trace_metadata, derive_trace_metadata, new_call_id
from deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargs
-from deeptutor.services.llm import complete as llm_complete
+from deeptutor.services.llm import complete as llm_complete, stream as llm_stream
from deeptutor.services.llm import stream as llm_stream
from deeptutor.utils.json_parser import parse_json_response
@@ -133,7 +133,8 @@ class NotebookAnalysisAgent:
trace_group="tool_call",
)
await self._emit_stage_start("notebook_acting", trace_meta, emit)
- raw = await llm_complete(
+ _chunks: list[str] = []
+ async for _c in llm_stream(
prompt=self._acting_prompt(user_question, thinking_text, records),
system_prompt=self._acting_system_prompt(),
model=self.model,
@@ -143,7 +144,9 @@ class NotebookAnalysisAgent:
binding=self.binding,
temperature=0.1,
**self._token_kwargs(500),
- )
+ ):
+ _chunks.append(_c)
+ raw = "".join(_chunks)
payload = parse_json_response(raw, logger_instance=logger, fallback={})
selected_ids = payload.get("selected_record_ids") if isinstance(payload, dict) else []
if not isinstance(selected_ids, list):
diff --git a/deeptutor/agents/question/agents/followup_agent.py b/deeptutor/agents/question/agents/followup_agent.py
index 5453e0e9d..ca034a4f3 100644
--- a/deeptutor/agents/question/agents/followup_agent.py
+++ b/deeptutor/agents/question/agents/followup_agent.py
@@ -44,7 +44,8 @@ class FollowupAgent(BaseAgent):
user_message=user_message.strip() or "(empty)",
)
- return await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
stage="followup_answer",
@@ -58,7 +59,9 @@ class FollowupAgent(BaseAgent):
trace_id=str(question_context.get("question_id", "question")),
question_id=str(question_context.get("question_id", "")),
),
- )
+ ):
+ _chunks.append(_c)
+ return "".join(_chunks)
@staticmethod
def _humanize_question_id(question_id: Any) -> str:
diff --git a/deeptutor/agents/question/agents/generator.py b/deeptutor/agents/question/agents/generator.py
index 5a2ba35bb..8bcd42437 100644
--- a/deeptutor/agents/question/agents/generator.py
+++ b/deeptutor/agents/question/agents/generator.py
@@ -26,7 +26,6 @@ class Generator(BaseAgent):
def __init__(
self,
kb_name: str | None = None,
- rag_mode: str = "naive",
language: str = "en",
tool_flags: dict[str, bool] | None = None,
**kwargs: Any,
@@ -38,7 +37,6 @@ class Generator(BaseAgent):
**kwargs,
)
self.kb_name = kb_name
- self.rag_mode = rag_mode
self.tool_flags = tool_flags or {}
self._tool_registry = get_tool_registry()
@@ -137,7 +135,8 @@ class Generator(BaseAgent):
available_tools=available_tools,
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
response_format={"type": "json_object"},
@@ -150,7 +149,9 @@ class Generator(BaseAgent):
trace_id=template.question_id,
question_id=template.question_id,
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
payload = self._parse_json_like(response)
if "question" not in payload or not str(payload.get("question", "")).strip():
@@ -242,7 +243,8 @@ class Generator(BaseAgent):
"- Return JSON only with keys: question_type, question, options, correct_answer, explanation.\n"
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=repair_prompt,
system_prompt="You fix malformed quiz payloads and return valid JSON only.",
response_format={"type": "json_object"},
@@ -255,7 +257,9 @@ class Generator(BaseAgent):
trace_id=template.question_id,
question_id=template.question_id,
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return self._parse_json_like(response)
@classmethod
diff --git a/deeptutor/agents/question/agents/idea_agent.py b/deeptutor/agents/question/agents/idea_agent.py
index 8b8aab3f8..23d8cf41e 100644
--- a/deeptutor/agents/question/agents/idea_agent.py
+++ b/deeptutor/agents/question/agents/idea_agent.py
@@ -25,7 +25,6 @@ class IdeaAgent(BaseAgent):
def __init__(
self,
kb_name: str | None = None,
- rag_mode: str = "naive",
enable_rag: bool = True,
language: str = "en",
**kwargs: Any,
@@ -37,7 +36,6 @@ class IdeaAgent(BaseAgent):
**kwargs,
)
self.kb_name = kb_name
- self.rag_mode = rag_mode
self.enable_rag = enable_rag
async def process(
@@ -116,7 +114,6 @@ class IdeaAgent(BaseAgent):
"tool_args": {
"query": user_topic,
"kb_name": self.kb_name,
- "mode": self.rag_mode,
"only_need_context": True,
},
**trace_meta,
@@ -125,7 +122,6 @@ class IdeaAgent(BaseAgent):
result = await rag_search(
query=user_topic,
kb_name=self.kb_name,
- mode=self.rag_mode,
only_need_context=True,
)
await self._emit_trace_event(
@@ -141,7 +137,7 @@ class IdeaAgent(BaseAgent):
{
"query": user_topic,
"answer": result.get("answer", ""),
- "mode": result.get("mode", self.rag_mode),
+ "provider": result.get("provider", ""),
}
)
except Exception as exc:
@@ -210,7 +206,8 @@ class IdeaAgent(BaseAgent):
existing_concentrations=json.dumps(existing_concentrations or [], ensure_ascii=False, indent=2),
)
try:
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt or "",
response_format={"type": "json_object"},
@@ -227,7 +224,9 @@ class IdeaAgent(BaseAgent):
trace_id=trace_id,
batch=batch_number,
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
payload = json.loads(response)
ideas_raw = payload.get("ideas", [])
if not isinstance(ideas_raw, list):
diff --git a/deeptutor/agents/question/coordinator.py b/deeptutor/agents/question/coordinator.py
index 8ef5ee8c3..a9180077c 100644
--- a/deeptutor/agents/question/coordinator.py
+++ b/deeptutor/agents/question/coordinator.py
@@ -56,7 +56,6 @@ class AgentCoordinator:
self.logger: Logger = get_logger("QuestionCoordinator", log_dir=log_dir)
question_cfg = self.config.get("capabilities", {}).get("question", {})
- self.rag_mode = question_cfg.get("rag_mode", "naive")
generation_cfg = question_cfg.get("generation", {})
default_tool_flags = generation_cfg.get(
"tools",
@@ -85,7 +84,6 @@ class AgentCoordinator:
def _create_idea_agent(self) -> IdeaAgent:
agent = IdeaAgent(
kb_name=self.kb_name,
- rag_mode=self.rag_mode,
enable_rag=self.enable_idea_rag,
language=self.language,
api_key=self._api_key,
@@ -98,7 +96,6 @@ class AgentCoordinator:
def _create_generator(self) -> Generator:
agent = Generator(
kb_name=self.kb_name,
- rag_mode=self.rag_mode,
language=self.language,
tool_flags=self.tool_flags,
api_key=self._api_key,
diff --git a/deeptutor/agents/research/agents/decompose_agent.py b/deeptutor/agents/research/agents/decompose_agent.py
index 838889e37..b3fa50a6c 100644
--- a/deeptutor/agents/research/agents/decompose_agent.py
+++ b/deeptutor/agents/research/agents/decompose_agent.py
@@ -56,18 +56,14 @@ class DecomposeAgent(BaseAgent):
language=language,
config=config,
)
- # Load KB and RAG mode from config, no hardcoding
rag_cfg = config.get("rag", {})
self.kb_name = rag_cfg.get("kb_name", kb_name or "ai_textbook")
- self.rag_mode = rag_cfg.get("default_mode", "hybrid")
- # Check if RAG is enabled (from researching config)
researching_cfg = config.get("researching", {})
- self.enable_rag = researching_cfg.get("enable_rag_hybrid", True) or researching_cfg.get(
- "enable_rag_naive", True
- )
+ self.enable_rag = researching_cfg.get("enable_rag", True)
+
+ self.conversation_history: list[dict[str, Any]] = config.get("conversation_history", [])
- # Citation manager (will be set during process)
self.citation_manager = None
intent_mode = str(config.get("intent", {}).get("mode", "") or "")
reporting_style = str(config.get("reporting", {}).get("style", "") or "")
@@ -77,6 +73,28 @@ class DecomposeAgent(BaseAgent):
"""Set citation manager"""
self.citation_manager = citation_manager
+ def _format_conversation_context(self) -> str:
+ """Format conversation history into a context block for the LLM."""
+ if not self.conversation_history:
+ return ""
+ parts: list[str] = []
+ for msg in self.conversation_history:
+ role = msg.get("role", "user")
+ content = str(msg.get("content", "")).strip()
+ if not content:
+ continue
+ parts.append(f"[{role}]: {content}")
+ if not parts:
+ return ""
+ return (
+ "\n<conversation_history>\n"
+ "The following is the conversation history of this session. "
+ "If the user's current request references or modifies a previous outline, "
+ "use this history as context.\n\n"
+ + "\n\n".join(parts)
+ + "\n</conversation_history>\n"
+ )
+
def _get_mode_contract(self, stage: str) -> str:
return (
self.get_prompt("mode_contracts", f"{self._research_style}_{stage}", "")
@@ -157,13 +175,13 @@ class DecomposeAgent(BaseAgent):
return "", ""
try:
- result = await rag_search(query=source_query, kb_name=self.kb_name, mode=self.rag_mode)
+ result = await rag_search(query=source_query, kb_name=self.kb_name)
rag_context = result.get("answer", "")
print(f" ✓ Retrieved background knowledge ({len(rag_context)} characters)")
if self.citation_manager:
citation_id = self.citation_manager.get_next_citation_id(stage="planning")
- tool_type = f"rag_{self.rag_mode}" if self.rag_mode else "rag_hybrid"
+ tool_type = "rag"
import time
@@ -211,6 +229,7 @@ class DecomposeAgent(BaseAgent):
"role",
"You are a research planning expert. Your task is to decompose complex topics into clear subtopics.",
)
+ system_prompt += self._format_conversation_context()
user_prompt_template = self.get_prompt("process", "decompose_without_rag")
if not user_prompt_template:
@@ -239,12 +258,15 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics
mode_instruction=self._get_mode_contract("decompose"),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="decompose_no_rag",
trace_meta=self._build_trace_meta(mode),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Parse JSON output
from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text
@@ -298,6 +320,7 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics
raise ValueError(
"DecomposeAgent missing system prompt, please configure system.role in prompts/{lang}/decompose_agent.yaml"
)
+ system_prompt += self._format_conversation_context()
user_prompt_template = self.get_prompt("process", "decompose")
if not user_prompt_template:
@@ -321,12 +344,15 @@ Dynamically generate no more than {max_subtopics} subtopics. Please carefully an
mode_instruction=self._get_mode_contract("decompose"),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="decompose",
trace_meta=self._build_trace_meta("auto"),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Parse JSON output (strict validation)
from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text
@@ -369,6 +395,7 @@ Dynamically generate no more than {max_subtopics} subtopics. Please carefully an
raise ValueError(
"DecomposeAgent missing system prompt, please configure system.role in prompts/{lang}/decompose_agent.yaml"
)
+ system_prompt += self._format_conversation_context()
user_prompt_template = self.get_prompt("process", "decompose")
if not user_prompt_template:
@@ -389,12 +416,15 @@ Explicitly generate {num_subtopics} subtopics. Please ensure exactly {num_subtop
mode_instruction=self._get_mode_contract("decompose"),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="decompose",
trace_meta=self._build_trace_meta("manual"),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Parse JSON output (strict validation)
from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text
diff --git a/deeptutor/agents/research/agents/note_agent.py b/deeptutor/agents/research/agents/note_agent.py
index bba9acd8a..fca86cdd4 100644
--- a/deeptutor/agents/research/agents/note_agent.py
+++ b/deeptutor/agents/research/agents/note_agent.py
@@ -165,7 +165,7 @@ class NoteAgent(BaseAgent):
tool_type = (tool_type or "").lower()
- if tool_type in {"rag_hybrid", "rag_naive", "rag"}:
+ if tool_type in {"rag_hybrid", "rag_naive", "rag"}: # aliases kept for backward compat
answer = data.get("answer") or data.get("content") or ""
return self._truncate_text(answer)
@@ -270,13 +270,15 @@ class NoteAgent(BaseAgent):
mode_instruction=self._get_mode_instruction_text("note"),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="generate_summary",
- verbose=False,
trace_meta=self._build_trace_meta(tool_type, query),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Parse JSON output (strict validation)
from ..utils.json_utils import ensure_json_dict, ensure_keys
diff --git a/deeptutor/agents/research/agents/rephrase_agent.py b/deeptutor/agents/research/agents/rephrase_agent.py
index c2ed08ec6..5847b96df 100644
--- a/deeptutor/agents/research/agents/rephrase_agent.py
+++ b/deeptutor/agents/research/agents/rephrase_agent.py
@@ -51,8 +51,8 @@ class RephraseAgent(BaseAgent):
language=language,
config=config,
)
- # Store complete conversation history for multi-turn optimization
self.conversation_history: list[dict[str, Any]] = []
+ self.session_history: list[dict[str, Any]] = config.get("conversation_history", [])
intent_mode = str(config.get("intent", {}).get("mode", "") or "")
reporting_style = str(config.get("reporting", {}).get("style", "") or "")
self._research_style = reporting_style or self._MODE_TO_STYLE.get(intent_mode, "report")
@@ -128,12 +128,26 @@ class RephraseAgent(BaseAgent):
}
)
- # Get system prompt
system_prompt = self.get_prompt("system", "role")
if not system_prompt:
raise ValueError(
"RephraseAgent missing system prompt, please configure system.role in prompts/{lang}/rephrase_agent.yaml"
)
+ if self.session_history:
+ ctx_parts = []
+ for msg in self.session_history:
+ role = msg.get("role", "user")
+ content = str(msg.get("content", "")).strip()
+ if content:
+ ctx_parts.append(f"[{role}]: {content}")
+ if ctx_parts:
+ system_prompt += (
+ "\n\n<session_history>\n"
+ "The following is the earlier conversation in this session. "
+ "Use it to understand what the user previously discussed or planned.\n\n"
+ + "\n\n".join(ctx_parts)
+ + "\n</session_history>"
+ )
# Get user prompt template
user_prompt_template = self.get_prompt("process", "rephrase")
@@ -154,13 +168,15 @@ class RephraseAgent(BaseAgent):
mode_instruction=self._get_mode_contract("rephrase"),
)
- # Call LLM
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="rephrase",
trace_meta=self._build_trace_meta(iteration),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
# Parse JSON output
data = extract_json_from_text(response)
diff --git a/deeptutor/agents/research/agents/reporting_agent.py b/deeptutor/agents/research/agents/reporting_agent.py
index c11afd164..a1ab7a315 100644
--- a/deeptutor/agents/research/agents/reporting_agent.py
+++ b/deeptutor/agents/research/agents/reporting_agent.py
@@ -229,13 +229,15 @@ class ReportingAgent(BaseAgent):
[f"{i + 1}. {b.sub_topic}: {b.overview[:200]}" for i, b in enumerate(blocks)]
)
filled = self._safe_format(user_prompt, topics=topics_text, total_topics=len(blocks))
- resp = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
filled,
system_prompt,
stage="deduplicate",
- verbose=False,
trace_meta=self._build_trace_meta("Deduplicate topics"),
- )
+ ):
+ _chunks.append(_c)
+ resp = "".join(_chunks)
data = extract_json_from_text(resp)
try:
obj = ensure_json_dict(data)
@@ -291,13 +293,15 @@ class ReportingAgent(BaseAgent):
self._get_mode_contract("outline"),
)
- resp = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
filled,
system_prompt,
stage="generate_outline",
- verbose=False,
trace_meta=self._build_trace_meta("Generate outline"),
- )
+ ):
+ _chunks.append(_c)
+ resp = "".join(_chunks)
data = extract_json_from_text(resp)
try:
obj = ensure_json_dict(data)
@@ -500,8 +504,7 @@ class ReportingAgent(BaseAgent):
# Truncate query for readability
query_preview = trace.query[:60] + "..." if len(trace.query) > 60 else trace.query
tool_display = {
- "rag_naive": "RAG",
- "rag_hybrid": "Hybrid RAG",
+ "rag": "RAG",
"paper_search": "Paper",
"web_search": "Web",
"run_code": "Code",
@@ -559,13 +562,15 @@ class ReportingAgent(BaseAgent):
self._get_mode_contract("introduction"),
)
- resp = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
filled,
system_prompt,
stage="write_introduction",
- verbose=False,
trace_meta=self._build_trace_meta("Write introduction"),
- )
+ ):
+ _chunks.append(_c)
+ resp = "".join(_chunks)
data = extract_json_from_text(resp)
try:
@@ -633,13 +638,15 @@ class ReportingAgent(BaseAgent):
self._get_mode_contract("section"),
)
- resp = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
filled,
system_prompt,
stage="write_section_body",
- verbose=False,
trace_meta=self._build_trace_meta("Write section"),
- )
+ ):
+ _chunks.append(_c)
+ resp = "".join(_chunks)
data = extract_json_from_text(resp)
try:
@@ -703,13 +710,15 @@ class ReportingAgent(BaseAgent):
self._get_mode_contract("conclusion"),
)
- resp = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
filled,
system_prompt,
stage="write_conclusion",
- verbose=False,
trace_meta=self._build_trace_meta("Write conclusion"),
- )
+ ):
+ _chunks.append(_c)
+ resp = "".join(_chunks)
data = extract_json_from_text(resp)
try:
@@ -885,7 +894,7 @@ class ReportingAgent(BaseAgent):
elif tool_type == "web_search":
formatted = self._format_web_search_citation(citation)
parts.append(formatted)
- elif tool_type in ("rag_naive", "rag_hybrid"):
+ elif tool_type in ("rag", "rag_naive", "rag_hybrid"):
formatted = self._format_rag_citation(citation)
parts.append(formatted)
elif tool_type == "run_code":
@@ -999,12 +1008,7 @@ class ReportingAgent(BaseAgent):
sources = citation.get("sources", [])
# Tool name display
- tool_display = {
- "rag_naive": "RAG Retrieval",
- "rag_hybrid": "Hybrid RAG Retrieval",
- }.get(tool_type, tool_type)
-
- result = f"**{tool_display}**"
+ result = f"**RAG**"
if kb_name:
result += f" (KB: {kb_name})"
result += "\n\n"
@@ -1138,8 +1142,7 @@ class ReportingAgent(BaseAgent):
# Tool name display
tool_display = {
- "rag_naive": "RAG Retrieval",
- "rag_hybrid": "Hybrid RAG Retrieval",
+ "rag": "RAG",
"paper_search": "Paper Search",
"web_search": "Web Search",
"run_code": "Code Execution",
@@ -1438,13 +1441,15 @@ class ReportingAgent(BaseAgent):
self._get_mode_contract("single_pass"),
)
- resp = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
filled,
system_prompt,
stage="write_full_report",
- verbose=False,
trace_meta=self._build_trace_meta("Write full report"),
- )
+ ):
+ _chunks.append(_c)
+ resp = "".join(_chunks)
data = extract_json_from_text(resp)
try:
@@ -1453,14 +1458,71 @@ class ReportingAgent(BaseAgent):
report = obj.get("report", "")
if not isinstance(report, str) or not report.strip():
raise ValueError("LLM returned empty report field")
- except Exception as e:
- raise ValueError(f"Unable to parse single-pass report content: {e!s}.") from e
+ except Exception:
+ if isinstance(data, dict) and ("sections" in data or "title" in data):
+ report = self._assemble_markdown_from_structured(data)
+ else:
+ stripped = resp.strip()
+ if stripped and stripped.startswith("#"):
+ report = stripped
+ else:
+ report = self._strip_json_wrapper(resp)
if self.enable_citation_list:
report = report.rstrip() + "\n\n" + self._generate_references(blocks)
return report
+ @staticmethod
+ def _assemble_markdown_from_structured(obj: dict[str, Any]) -> str:
+ """Reconstruct markdown from a structured JSON report the LLM returned
+ instead of the expected {report: "..."} wrapper."""
+ parts: list[str] = []
+ if obj.get("title"):
+ parts.append(str(obj["title"]))
+ if obj.get("introduction"):
+ parts.append(str(obj["introduction"]))
+ for section in obj.get("sections", []):
+ if isinstance(section, str):
+ parts.append(section)
+ continue
+ if not isinstance(section, dict):
+ continue
+ if section.get("title"):
+ parts.append(str(section["title"]))
+ if section.get("content"):
+ parts.append(str(section["content"]))
+ for sub in section.get("subsections", []):
+ if isinstance(sub, str):
+ parts.append(sub)
+ elif isinstance(sub, dict):
+ if sub.get("title"):
+ parts.append(str(sub["title"]))
+ if sub.get("content"):
+ parts.append(str(sub["content"]))
+ if obj.get("conclusion"):
+ parts.append(str(obj["conclusion"]))
+ return "\n\n".join(parts)
+
+ @staticmethod
+ def _strip_json_wrapper(resp: str) -> str:
+ """Best-effort extraction of readable text from a JSON response."""
+ import json as _json
+ try:
+ obj = _json.loads(resp.strip())
+ if isinstance(obj, dict):
+ for key in ("report", "content", "text", "markdown", "output"):
+ if key in obj and isinstance(obj[key], str):
+ return obj[key]
+ except (ValueError, TypeError):
+ pass
+ stripped = resp.strip()
+ if stripped.startswith("{") or stripped.startswith("["):
+ for line in stripped.split("\\n"):
+ if line.strip().startswith("#"):
+ return stripped.replace("\\n", "\n")
+ return stripped
+
async def _write_section_with_subsections(
self,
topic: str,
@@ -1550,13 +1612,15 @@ class ReportingAgent(BaseAgent):
)
# TODO Implement retry logic for LLM calls when JSON parsing or post-processing fails (e.g., malformed output, schema violations).
- resp = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
filled,
system_prompt,
stage="write_section_with_subsections",
- verbose=False,
trace_meta=self._build_trace_meta("Write section"),
- )
+ ):
+ _chunks.append(_c)
+ resp = "".join(_chunks)
data = extract_json_from_text(resp)
try:
diff --git a/deeptutor/agents/research/agents/research_agent.py b/deeptutor/agents/research/agents/research_agent.py
index 4cd2ecb82..a585f23c0 100644
--- a/deeptutor/agents/research/agents/research_agent.py
+++ b/deeptutor/agents/research/agents/research_agent.py
@@ -71,10 +71,7 @@ class ResearchAgent(BaseAgent):
# In "fixed" mode, agent should be more conservative about declaring knowledge sufficient
# In "flexible" mode (auto), agent can stop early when knowledge is truly sufficient
self.iteration_mode = self.researching_config.get("iteration_mode", "fixed")
- # Tool availability configuration
- self.enable_rag = self.researching_config.get(
- "enable_rag_hybrid", True
- ) or self.researching_config.get("enable_rag_naive", True)
+ self.enable_rag = self.researching_config.get("enable_rag", True)
# Web search: global switch (tools.web_search.enabled) has higher priority
# Only enabled when both global switch and module switch are True
tools_web_search_enabled = (
@@ -250,17 +247,19 @@ Only output JSON:
mode_instruction=self._get_mode_contract("research") or "(no extra mode instruction)",
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="llm_self_research",
- verbose=False,
trace_meta=self._build_trace_meta(
label="LLM self research",
iteration=iteration,
block_id=block_id,
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
try:
data = extract_json_from_text(response)
@@ -304,8 +303,8 @@ Only output JSON:
# Tool diversity analysis
unique_tools = set(used_tools)
available_tools = []
- if self.enable_rag and not any(t in unique_tools for t in ["rag_hybrid", "rag_naive", "rag"]):
- available_tools.append("RAG tools (rag_hybrid/rag_naive)")
+ if self.enable_rag and "rag" not in unique_tools:
+ available_tools.append("rag")
if self.enable_paper_search and "paper_search" not in unique_tools:
available_tools.append("paper_search")
if self.enable_web_search and "web_search" not in unique_tools:
@@ -441,17 +440,19 @@ Tools already used: {", ".join(used_tools) if used_tools else "None"}
iteration_mode_criteria=iteration_mode_criteria,
mode_instruction=self._get_mode_contract("research"),
)
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
stage="plan_next_step",
- verbose=False,
trace_meta=self._build_trace_meta(
label="Plan next step",
iteration=iteration,
trace_role="plan",
),
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
from ..utils.json_utils import ensure_json_dict, ensure_keys
@@ -603,7 +604,7 @@ Tools already used: {", ".join(used_tools) if used_tools else "None"}
print(f"{block_id_prefix} Reason: {new_topic_reason}")
query = plan.get("query", "").strip()
- tool_type = "llm_self_research" if llm_only_mode else plan.get("tool_type", "rag_hybrid")
+ tool_type = "llm_self_research" if llm_only_mode else plan.get("tool_type", "rag")
rationale = plan.get("rationale", "")
if not query:
diff --git a/deeptutor/agents/research/data_structures.py b/deeptutor/agents/research/data_structures.py
index 66a5e2b43..0fc242639 100644
--- a/deeptutor/agents/research/data_structures.py
+++ b/deeptutor/agents/research/data_structures.py
@@ -24,8 +24,7 @@ class TopicStatus(Enum):
class ToolType(Enum):
"""Tool type enumeration"""
- RAG_NAIVE = "rag_naive"
- RAG_HYBRID = "rag_hybrid"
+ RAG = "rag"
PAPER_SEARCH = "paper_search"
RUN_CODE = "run_code"
WEB_SEARCH = "web_search"
@@ -43,7 +42,7 @@ class ToolTrace:
tool_id: str # Unique identifier (e.g., "tool_1", "tool_2")
citation_id: str # Citation ID (for report citations and anchors, e.g., CIT-1-01)
- tool_type: str # Tool type (rag_naive, web_search, etc.)
+ tool_type: str # Tool type (rag, web_search, etc.)
query: str # Query statement issued
raw_answer: str # Raw detailed result returned by tool (may be truncated)
summary: str # Core summary generated by Note Agent
diff --git a/deeptutor/agents/research/mode_strategy.py b/deeptutor/agents/research/mode_strategy.py
new file mode 100644
index 000000000..2f85ff340
--- /dev/null
+++ b/deeptutor/agents/research/mode_strategy.py
@@ -0,0 +1,141 @@
+"""Mode strategy abstraction for deep research.
+
+Each research mode (notes, report, comparison, learning_path) is represented
+as a ``ModeStrategy`` dataclass. ``STRATEGIES`` acts as the single source of
+truth that ``request_config._build_mode_policy`` delegates to.
+
+``validate_output`` provides lightweight post-generation checks so callers can
+surface warnings when the LLM drifted away from the mode contract.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Literal
+
+ResearchMode = Literal["notes", "report", "comparison", "learning_path"]
+ResearchDepth = Literal["quick", "standard", "deep", "manual"]
+
+_MANUAL_SUBTOPICS: dict[str, int] = {"quick": 2, "standard": 3, "deep": 4}
+_AUTO_SUBTOPICS: dict[str, int] = {"quick": 2, "standard": 4, "deep": 6}
+
+
+@dataclass(frozen=True)
+class ModeStrategy:
+ name: ResearchMode
+ style: str
+ rephrase_enabled: bool
+ decompose_mode: str # "auto" | "manual"
+ single_pass_threshold: int
+ min_section_length: int
+ enable_citation_list: bool = True
+ enable_inline_citations: bool = True
+ deduplicate_enabled: bool = False
+ allow_code_execution_on_deep: bool = False
+ _rephrase_iterations_by_depth: dict[str, int] = field(default_factory=lambda: {
+ "quick": 1, "standard": 1, "deep": 1, "manual": 1,
+ })
+
+ def rephrase_iterations(self, depth: str) -> int:
+ return self._rephrase_iterations_by_depth.get(depth, 1)
+
+ def subtopic_count(self, depth: str) -> int:
+ table = _AUTO_SUBTOPICS if self.decompose_mode == "auto" else _MANUAL_SUBTOPICS
+ return table.get(depth, 3)
+
+ def build_policy(self, depth: str) -> dict[str, object]:
+ if self.decompose_mode == "auto":
+ initial = None
+ auto_max = _AUTO_SUBTOPICS.get(depth, 4)
+ else:
+ initial = _MANUAL_SUBTOPICS.get(depth, 3)
+ if self.name == "comparison":
+ initial = max(2, initial)
+ auto_max = None
+
+ return {
+ "rephrase_enabled": self.rephrase_enabled,
+ "rephrase_iterations": self.rephrase_iterations(depth),
+ "decompose_mode": self.decompose_mode,
+ "initial_subtopics": initial,
+ "auto_max_subtopics": auto_max,
+ "min_section_length": self.min_section_length,
+ "report_single_pass_threshold": self.single_pass_threshold,
+ "enable_citation_list": self.enable_citation_list,
+ "enable_inline_citations": self.enable_inline_citations,
+ "deduplicate_enabled": self.deduplicate_enabled,
+ "style": self.style,
+ }
+
+ def validate_output(self, report: str) -> list[str]:
+ """Return a list of warnings if the report deviates from mode expectations."""
+ warnings: list[str] = []
+ if not report or not report.strip():
+ warnings.append("Report is empty.")
+ return warnings
+
+ if self.name == "notes":
+ if not re.search(r">\s*\*\*Definition", report):
+ warnings.append("Study notes: missing Definition box (> **Definition — ...).")
+ if not re.search(r"Key Takeaway", report, re.IGNORECASE):
+ warnings.append("Study notes: missing Key Takeaway block.")
+ elif self.name == "comparison":
+ if not re.search(r"\|.*\|.*\|", report):
+ warnings.append("Comparison: no Markdown table detected.")
+ elif self.name == "learning_path":
+ if not re.search(r"Checkpoint", report, re.IGNORECASE):
+ warnings.append("Learning path: missing Checkpoint block.")
+
+ return warnings
+
+
+STRATEGIES: dict[ResearchMode, ModeStrategy] = {
+ "notes": ModeStrategy(
+ name="notes",
+ style="study_notes",
+ rephrase_enabled=False,
+ decompose_mode="manual",
+ single_pass_threshold=99,
+ min_section_length=260,
+ ),
+ "report": ModeStrategy(
+ name="report",
+ style="report",
+ rephrase_enabled=False,
+ decompose_mode="auto",
+ single_pass_threshold=2,
+ min_section_length=650,
+ ),
+ "comparison": ModeStrategy(
+ name="comparison",
+ style="comparison",
+ rephrase_enabled=True,
+ decompose_mode="manual",
+ single_pass_threshold=2,
+ min_section_length=520,
+ allow_code_execution_on_deep=True,
+ _rephrase_iterations_by_depth={
+ "quick": 1, "standard": 1, "deep": 2, "manual": 1,
+ },
+ ),
+ "learning_path": ModeStrategy(
+ name="learning_path",
+ style="learning_path",
+ rephrase_enabled=True,
+ decompose_mode="auto",
+ single_pass_threshold=99,
+ min_section_length=420,
+ ),
+}
+
+
+def get_strategy(mode: str) -> ModeStrategy:
+ return STRATEGIES[mode] # type: ignore[index]
+
+
+__all__ = [
+ "ModeStrategy",
+ "STRATEGIES",
+ "get_strategy",
+]
diff --git a/deeptutor/agents/research/prompts/en/reporting_agent.yaml b/deeptutor/agents/research/prompts/en/reporting_agent.yaml
index b866ba1e2..c8f14c565 100644
--- a/deeptutor/agents/research/prompts/en/reporting_agent.yaml
+++ b/deeptutor/agents/research/prompts/en/reporting_agent.yaml
@@ -53,13 +53,19 @@ mode_contracts:
- Write like a high-quality study sheet.
- Prefer bullets, short explanation bursts, worked mini-examples, pitfall lists, and key-takeaway blocks.
- Never let the section read like a long formal essay.
+ - For every major concept, include a definition box: `> **Definition — <Term>**: <concise definition>`
+ - End each section with a "Test Yourself" micro-question: `> 💡 **Test Yourself**: Can you explain <concept> without looking at the notes?`
+ - Where appropriate, add a memory anchor: `> 🧠 **Memory Anchor**: <mnemonic, analogy, or visual cue to aid recall>`
study_notes_conclusion: |
- End with a recap checklist or takeaway block.
- Include key takeaways and optional common mistakes.
+ - Add a **Self-Test Checklist**: a numbered list of core claims/concepts the learner should be able to explain from memory.
- Do not write a formal conclusion with limitations or future work.
study_notes_single_pass: |
- The full output must read like revision notes prepared for a learner.
- It should be compact, scannable, memorable, and clearly segmented for review.
+ - Include definition boxes, "Test Yourself" micro-questions, and memory anchors throughout.
+ - End with a Self-Test Checklist of core concepts to verify recall.
- The finished artifact should feel optimized for understanding, recall, and quick revision.
report_outline: |
@@ -90,12 +96,18 @@ mode_contracts:
- Every main section must compare alternatives side by side.
- Use dimension-based analysis, explicit contrasts, tables, and scenario-based judgments.
- Do not drift into isolated topic summaries.
+ - For each comparison dimension, assign a quantitative score (1-5) to every option. Present scores in a mini table.
+ - Format: `| Criterion | Option A | Option B | ... |` with numeric scores.
comparison_conclusion: |
- End with a verdict and recommendation by scenario, constraint, or priority.
- Make selection guidance explicit.
+ - Include a **Scoring Summary Table** that aggregates all per-dimension scores into one table:
+ `| Dimension | Option A | Option B | ... | (with numeric 1-5 scores)`
+ - Below the table, state overall weighted impressions and scenario-based recommendations.
comparison_single_pass: |
- The whole output must be dimension-first, trade-off-heavy, and recommendation-oriented.
- It should feel unmistakably like a comparison document.
+ - Include quantitative 1-5 scores per dimension per option, and a scoring summary table in the conclusion.
- The finished artifact should help a reader make a decision under explicit scenarios or constraints.
learning_path_outline: |
@@ -109,10 +121,21 @@ mode_contracts:
- Write as a study roadmap, not a report.
- Make sequence, prerequisites, exercises, checkpoints, milestones, and what-to-study-next explicit.
- Every section should help the learner act, not just understand.
+ - Start each stage with metadata: `> ⏱️ **Estimated Time**: X hours` and `> 📊 **Difficulty**: Foundation / Intermediate / Advanced`
+ - Include a **Recommended Resources** block: `> 📚 **Resources**: [books, courses, tools, or links]`
learning_path_conclusion: |
- End with milestone checks, next-step advice, and how to continue after completing the path.
+ - Include a Mermaid roadmap diagram showing the stage progression:
+ ```mermaid
+ graph LR
+ A[Stage 1: ...] --> B[Stage 2: ...]
+ B --> C[Stage 3: ...]
+ ```
+ - Below the diagram, summarize total estimated time and a final competency checklist.
learning_path_single_pass: |
- The final output must read like a staged study plan with progression logic, checkpoints, exercises, and sequence.
+ - Each stage must include estimated time, difficulty label, and recommended resources.
+ - End with a Mermaid roadmap diagram and total time estimate.
- The finished artifact should help a learner decide what to do first, next, and how to judge progress.
process:
@@ -587,13 +610,21 @@ process:
```
6. **Tables**: Use comparison tables for contrasting concepts, parameter summaries, or method comparisons.
7. **Formulas**: Preserve LaTeX. Inline: `$...$`. Block: `$$...$$`.
- 8. **NEVER** write like a report: no "In this section, we examine…", no lengthy analytical prose, no formal transitions.
+ 8. **Test Yourself**: End with a micro-question that tests recall:
+ ```
+ > 💡 **Test Yourself**: Can you explain <concept> without looking at the notes?
+ ```
+ 9. **Memory Anchor**: Where helpful, provide a mnemonic, analogy, or visual cue:
+ ```
+ > 🧠 **Memory Anchor**: <mnemonic or analogy to aid recall>
+ ```
+ 10. **NEVER** write like a report: no "In this section, we examine…", no lengthy analytical prose, no formal transitions.
{citation_instruction}
Output:
{{
- "section_content": "## Section Title\n\n> **Definition — X**: ...\n\n- Point 1\n- Point 2\n\n**Example**:\n...\n\n> ⚠️ **Common Mistake**: ...\n\n> 🔑 **Key Takeaway**: ...{citation_output_hint}"
+ "section_content": "## Section Title\n\n> **Definition — X**: ...\n\n- Point 1\n- Point 2\n\n**Example**:\n...\n\n> ⚠️ **Common Mistake**: ...\n\n> 🧠 **Memory Anchor**: ...\n\n> 🔑 **Key Takeaway**: ...\n\n> 💡 **Test Yourself**: ...{citation_output_hint}"
}}
**Word Count**: 400-700 words. Prioritize clarity over length.
@@ -616,11 +647,12 @@ process:
1. **Key Terms Table**: Term | Definition (one row per key concept)
2. **Top Takeaways**: Numbered list of the 3-5 most important points
3. **Common Pitfalls**: Bullet list of mistakes to avoid
+ 4. **Self-Test Checklist**: Numbered list of core claims/concepts the learner should be able to explain from memory. Format: `✅ 1. Can you explain ...?`
- Keep it compact and scannable — this is a cheat sheet, not a summary essay.
Output:
{{
- "conclusion": "| Term | Definition |\n|---|---|\n| ... | ... |\n\n**Top Takeaways**\n1. ...\n2. ...\n\n**Pitfalls to Avoid**\n- ..."
+ "conclusion": "| Term | Definition |\n|---|---|\n| ... | ... |\n\n**Top Takeaways**\n1. ...\n2. ...\n\n**Pitfalls to Avoid**\n- ...\n\n**Self-Test Checklist**\n✅ 1. Can you explain ...?\n✅ 2. ..."
}}
**Now directly output the JSON object.**
@@ -649,8 +681,10 @@ process:
- Mini-examples with code/math/steps
- Pitfall alerts: `> ⚠️ **Common Mistake**: ...`
- Key takeaway blocks: `> 🔑 **Key Takeaway**: ...`
+ - Test Yourself micro-questions: `> 💡 **Test Yourself**: Can you explain ...?`
+ - Memory anchors: `> 🧠 **Memory Anchor**: <mnemonic or analogy>`
- Comparison tables where relevant
- - A Quick Reference section at the end with a terms table + top takeaways + pitfalls list
+ - A Quick Reference section at the end with a terms table + top takeaways + pitfalls list + Self-Test Checklist
- Short paragraphs and bullet lists — NO long prose
Output:
@@ -750,15 +784,16 @@ process:
```
2. **Dimension Analysis**: After the table, discuss the key trade-offs, nuances, and edge cases for this dimension.
3. **Strengths & Weaknesses**: Use explicit `**Strengths**:` and `**Weaknesses**:` sub-blocks for each option.
- 4. **Scenario-Fit Judgment**: End with a clear statement: "For scenario X, Option Y is preferable because…"
- 5. **NEVER** write isolated option profiles. Every paragraph must compare.
- 6. Use bold labels, tables, and structured lists. Minimize long prose.
+ 4. **Quantitative Score**: For this dimension, assign each option a score from 1-5 (1=poor, 5=excellent).
+ 5. **Scenario-Fit Judgment**: End with a clear statement: "For scenario X, Option Y is preferable because…"
+ 6. **NEVER** write isolated option profiles. Every paragraph must compare.
+ 7. Use bold labels, tables, and structured lists. Minimize long prose.
{citation_instruction}
Output:
{{
- "section_content": "## Dimension Title\n\n| Criterion | A | B |\n|---|---|---|\n| ... | ... | ... |\n\n**Analysis**: ...\n\n**Strengths & Weaknesses**:\n- Option A: ...\n- Option B: ...\n\n**Best fit**: For scenario X, prefer ...{citation_output_hint}"
+ "section_content": "## Dimension Title\n\n| Criterion | A | B | Score A | Score B |\n|---|---|---|---|---|\n| ... | ... | ... | 4 | 3 |\n\n**Analysis**: ...\n\n**Strengths & Weaknesses**:\n- Option A: ...\n- Option B: ...\n\n**Best fit**: For scenario X, prefer ...{citation_output_hint}"
}}
**Word Count**: 500-800 words per dimension section.
@@ -776,20 +811,28 @@ process:
Total Topics: {total_topics}
**Rules** (MANDATORY):
- - **Decision Matrix Table**: MUST include a table mapping scenarios/priorities to recommended options:
+ - **Scoring Summary Table**: MUST include an aggregate scoring table with 1-5 scores per dimension per option:
+ ```
+ | Dimension | Option A | Option B | Option C |
+ |-------------|----------|----------|----------|
+ | Dim 1 | 4 | 3 | 5 |
+ | Dim 2 | 3 | 5 | 2 |
+ | **Average** | **3.5** | **4.0** | **3.5** |
+ ```
+ - **Decision Matrix Table**: Include a table mapping scenarios/priorities to recommended options:
```
| If you prioritize… | Recommended | Why |
|---------------------|-------------|-----|
| Performance | Option A | ... |
| Cost | Option B | ... |
```
- - **Per-Scenario Recommendations**: After the table, write 2-3 sentences per scenario explaining the recommendation.
+ - **Per-Scenario Recommendations**: After the tables, write 2-3 sentences per scenario explaining the recommendation.
- **NEVER** write a vague "it depends" conclusion. Be specific and opinionated.
- No formal "limitations and future work" section.
Output:
{{
- "conclusion": "| If you prioritize… | Recommended | Why |\n|---|---|---|\n| ... | ... | ... |\n\n**Scenario 1**: ...\n\n**Scenario 2**: ..."
+ "conclusion": "**Scoring Summary**\n\n| Dimension | A | B |\n|---|---|---|\n| ... | 4 | 3 |\n| **Average** | **3.5** | **4.0** |\n\n**Recommendation by Scenario**\n\n| If you prioritize… | Recommended | Why |\n|---|---|---|\n| ... | ... | ... |\n\n**Scenario 1**: ...\n\n**Scenario 2**: ..."
}}
**Now directly output the JSON object.**
@@ -911,27 +954,36 @@ process:
**Learning Path Stage Rules** (MANDATORY):
- 1. **Learning Objectives**: Start with a bulleted list: "After this stage you will be able to: …"
- 2. **Why Now**: Briefly explain the prerequisite chain — why this stage comes at this point.
- 3. **Core Content**: Teach the key concepts. Use definition boxes, examples, diagrams, and code as appropriate. Keep explanations clear and progressive.
- 4. **Practice Plan**: Include specific exercises, mini-projects, or problems to solve:
+ 1. **Stage Metadata**: Start each stage with:
+ ```
+ > ⏱️ **Estimated Time**: X hours
+ > 📊 **Difficulty**: Foundation / Intermediate / Advanced
+ ```
+ 2. **Learning Objectives**: A bulleted list: "After this stage you will be able to: …"
+ 3. **Why Now**: Briefly explain the prerequisite chain — why this stage comes at this point.
+ 4. **Core Content**: Teach the key concepts. Use definition boxes, examples, diagrams, and code as appropriate. Keep explanations clear and progressive.
+ 5. **Practice Plan**: Include specific exercises, mini-projects, or problems to solve:
```
> 📝 **Exercise**: Description of what to do, expected outcome, and how to check your answer.
```
- 5. **Checkpoint**: End with a self-assessment block:
+ 6. **Recommended Resources**: Suggest books, courses, tools, or links:
+ ```
+ > 📚 **Resources**: [list of recommended materials]
+ ```
+ 7. **Checkpoint**: End with a self-assessment block:
```
> ✅ **Checkpoint — Ready for Stage N+1?**
> - Can you explain X?
> - Can you implement Y?
> - Can you identify when Z applies?
```
- 6. **NEVER** write like a report section. Every paragraph should help the learner ACT, not just understand.
+ 8. **NEVER** write like a report section. Every paragraph should help the learner ACT, not just understand.
{citation_instruction}
Output:
{{
- "section_content": "## Stage N. Title\n\n**Learning Objectives**:\n- ...\n\n**Why Now**: ...\n\n### Core Content\n...\n\n> 📝 **Exercise**: ...\n\n> ✅ **Checkpoint — Ready for Stage N+1?**\n> - ...{citation_output_hint}"
+ "section_content": "## Stage N. Title\n\n> ⏱️ **Estimated Time**: X hours\n> 📊 **Difficulty**: Intermediate\n\n**Learning Objectives**:\n- ...\n\n**Why Now**: ...\n\n### Core Content\n...\n\n> 📝 **Exercise**: ...\n\n> 📚 **Resources**: ...\n\n> ✅ **Checkpoint — Ready for Stage N+1?**\n> - ...{citation_output_hint}"
}}
**Word Count**: 500-800 words per stage.
@@ -949,19 +1001,26 @@ process:
Total Topics: {total_topics}
**Rules** (MANDATORY):
- - **Milestone Checklist**: A table or checklist covering all stages:
+ - **Roadmap Diagram**: Include a Mermaid flowchart showing stage progression:
+ ```mermaid
+ graph LR
+ A["Stage 1: ..."] --> B["Stage 2: ..."]
+ B --> C["Stage 3: ..."]
+ ```
+ - **Milestone Checklist**: A table covering all stages with time estimates:
```
- | Stage | Milestone | Self-Check |
- |-------|-----------|------------|
- | 1 | ... | Can you…? |
+ | Stage | Milestone | Est. Time | Self-Check |
+ |-------|-----------|-----------|------------|
+ | 1 | ... | X hours | Can you…? |
```
+ - **Total Time Estimate**: Sum up all stage times for the full path.
- **Self-Assessment**: Help the learner judge their overall readiness.
- **What's Next**: Concrete advice on where to go after completing this path — advanced topics, projects, communities, resources.
- **NEVER** write a formal conclusion with "limitations". This is forward-looking and action-oriented.
Output:
{{
- "conclusion": "**Milestone Checklist**\n\n| Stage | Milestone | Self-Check |\n|---|---|---|\n| ... | ... | ... |\n\n**Self-Assessment**: ...\n\n**What's Next**: ..."
+ "conclusion": "**Learning Roadmap**\n\n```mermaid\ngraph LR\n A[Stage 1] --> B[Stage 2]\n B --> C[Stage 3]\n```\n\n**Milestone Checklist**\n\n| Stage | Milestone | Est. Time | Self-Check |\n|---|---|---|---|\n| ... | ... | X hours | ... |\n\n**Total Estimated Time**: X hours\n\n**Self-Assessment**: ...\n\n**What's Next**: ..."
}}
**Now directly output the JSON object.**
@@ -987,10 +1046,13 @@ process:
**Mandatory elements**:
- "Who This Path Is For" section with learner profile, prerequisites, end goal
- - Sequential stages (Stage 1 → 2 → 3…), each with: objectives, why-now, core content, practice, checkpoint
+ - Sequential stages (Stage 1 → 2 → 3…), each with:
+ - Stage metadata: `> ⏱️ **Estimated Time**: X hours` and `> 📊 **Difficulty**: Foundation/Intermediate/Advanced`
+ - Objectives, why-now, core content, practice, recommended resources, checkpoint
- Exercise blocks: `> 📝 **Exercise**: ...`
+ - Resource blocks: `> 📚 **Resources**: ...`
- Checkpoint blocks: `> ✅ **Checkpoint**: ...`
- - "Milestones & What's Next" section with milestone table + continuation advice
+ - "Milestones & What's Next" section with Mermaid roadmap diagram + milestone table + total time estimate + continuation advice
- Clear prerequisite chain visible throughout
- NEVER write as a flat topical report
diff --git a/deeptutor/agents/research/prompts/en/research_agent.yaml b/deeptutor/agents/research/prompts/en/research_agent.yaml
index 4f271fb0e..d583e8a9a 100644
--- a/deeptutor/agents/research/prompts/en/research_agent.yaml
+++ b/deeptutor/agents/research/prompts/en/research_agent.yaml
@@ -172,7 +172,6 @@ process:
"target_dimension": "Knowledge dimension targeted by this query, empty string if sufficient",
"rationale": "Tool selection reason and query objective, empty string if sufficient",
"parallel": false,
- "fallback": ["rag_hybrid", "rag_naive"],
"should_add_new_topic": false,
"new_sub_topic": null,
"new_overview": null,
@@ -257,7 +256,6 @@ process:
"target_dimension": "Knowledge dimension targeted by this query",
"rationale": "Tool selection reason and query objective",
"parallel": false,
- "fallback": ["rag_hybrid", "rag_naive"],
"should_add_new_topic": false,
"new_sub_topic": null,
"new_overview": null,
diff --git a/deeptutor/agents/research/prompts/zh/reporting_agent.yaml b/deeptutor/agents/research/prompts/zh/reporting_agent.yaml
index 6f0be0aa1..71206978e 100644
--- a/deeptutor/agents/research/prompts/zh/reporting_agent.yaml
+++ b/deeptutor/agents/research/prompts/zh/reporting_agent.yaml
@@ -53,13 +53,19 @@ mode_contracts:
- 要写成高质量学习笔记,而不是长篇文章。
- 优先使用要点、短段解释、迷你例子、易错点列表、takeaway 块。
- 不要让章节读起来像正式论文或综述报告。
+ - 每个核心概念都要有定义框:`> **定义 — <术语>**: <简洁定义>`
+ - 每节末尾加一个自测微问题:`> 💡 **自测**: 你能不看笔记解释<概念>吗?`
+ - 在合适的地方加记忆锚点:`> 🧠 **记忆锚点**: <助记符、类比或视觉线索>`
study_notes_conclusion: |
- 结尾应是回顾清单或关键结论块。
- 包含重点结论,可附常见误区。
+ - 加一个**自测清单**:列出学习者应该能够凭记忆解释的核心概念。格式:`✅ 1. 你能解释...吗?`
- 不要写正式“结论/局限/未来工作”。
study_notes_single_pass: |
- 最终整体必须像给学习者准备的复习笔记。
- 要紧凑、可扫读、便于记忆和回顾。
+ - 全文包含定义框、自测微问题和记忆锚点。
+ - 结尾附自测清单以检验记忆。
- 成品应明显服务于理解、记忆与快速复习。
report_outline: |
@@ -90,12 +96,16 @@ mode_contracts:
- 每个主章节都必须把对象放在同一维度下并列比较。
- 强调维度分析、显式对照、表格和场景判断。
- 不要漂移成各讲各的主题综述。
+ - 每个比较维度为各选项分配 1-5 分量化评分,以迷你表格呈现。
comparison_conclusion: |
- 结尾必须给出“按场景/约束/优先级”的推荐判断。
- 选择建议要明确,不要模糊。
+ - 包含**评分汇总表**,汇总所有维度评分:`| 维度 | 选项A | 选项B | ... |`(1-5 分)
+ - 汇总表下方给出综合加权印象和按场景推荐。
comparison_single_pass: |
- 最终整体必须是维度优先、trade-off 明显、推荐导向的对比文档。
- 读感上必须一眼就是 comparison,不是 report。
+ - 包含每维度每选项的 1-5 量化评分,结论部分有评分汇总表。
- 成品应帮助读者在明确场景或约束下做出选择。
learning_path_outline: |
@@ -109,10 +119,21 @@ mode_contracts:
- 必须写成学习路线,而不是报告。
- 把顺序、先修、练习、checkpoint、里程碑、下一步学什么写清楚。
- 每个章节都应帮助学习者行动,而不只是理解。
+ - 每个阶段开头标注:`> ⏱️ **预计时间**: X 小时` 和 `> 📊 **难度**: 基础 / 中级 / 高级`
+ - 包含**推荐资源**块:`> 📚 **推荐资源**: [书籍、课程、工具或链接]`
learning_path_conclusion: |
- 结尾应包含里程碑检查、下一步建议,以及完成后如何继续推进。
+ - 包含 Mermaid 路线图:
+ ```mermaid
+ graph LR
+ A["阶段 1: ..."] --> B["阶段 2: ..."]
+ B --> C["阶段 3: ..."]
+ ```
+ - 图下方汇总总预计时间和最终能力检查清单。
learning_path_single_pass: |
- 最终整体必须像一份阶段化学习计划,突出顺序、checkpoint、练习与进阶逻辑。
+ - 每个阶段必须标注预计时间、难度标签和推荐资源。
+ - 结尾包含 Mermaid 路线图和总时间估算。
- 成品应帮助学习者明确先做什么、接着做什么、如何判断自己是否过关。
process:
@@ -587,13 +608,21 @@ process:
```
6. **表格**:对比性概念、参数汇总或方法比较时使用对照表。
7. **公式**:保留 LaTeX。行内:`$...$`。独立块:`$$...$$`。
- 8. **绝不**写成报告风格:不要"在本节中,我们将…",不要长段分析性散文,不要正式过渡句。
+ 8. **自测微问题**:每节末尾加一个自测题:
+ ```
+ > 💡 **自测**:你能不看笔记解释<概念>吗?
+ ```
+ 9. **记忆锚点**:在适当位置加入助记或类比:
+ ```
+ > 🧠 **记忆锚点**:<助记符或类比>
+ ```
+ 10. **绝不**写成报告风格:不要"在本节中,我们将…",不要长段分析性散文,不要正式过渡句。
{citation_instruction}
输出:
{{
- "section_content": "## 章节标题\n\n> **定义 — X**:...\n\n- 要点 1\n- 要点 2\n\n**例子**:\n...\n\n> ⚠️ **常见误区**:...\n\n> 🔑 **核心要点**:...{citation_output_hint}"
+ "section_content": "## 章节标题\n\n> **定义 — X**:...\n\n- 要点 1\n- 要点 2\n\n**例子**:\n...\n\n> ⚠️ **常见误区**:...\n\n> 🧠 **记忆锚点**:...\n\n> 🔑 **核心要点**:...\n\n> 💡 **自测**:...{citation_output_hint}"
}}
**字数要求**:400-700字。优先保证清晰度,而非长度。
@@ -616,11 +645,12 @@ process:
1. **关键术语表**:术语 | 定义(每个核心概念一行)
2. **重点提炼**:3-5条最重要的编号要点
3. **易错清单**:要避免的错误的要点列表
+ 4. **自测清单**:列出学习者应凭记忆解释的核心概念。格式:`✅ 1. 你能解释...吗?`
- 保持紧凑、可扫读——这是备忘录,不是总结性文章。
输出:
{{
- "conclusion": "| 术语 | 定义 |\n|---|---|\n| ... | ... |\n\n**重点提炼**\n1. ...\n2. ...\n\n**易错清单**\n- ..."
+ "conclusion": "| 术语 | 定义 |\n|---|---|\n| ... | ... |\n\n**重点提炼**\n1. ...\n2. ...\n\n**易错清单**\n- ...\n\n**自测清单**\n✅ 1. 你能解释...吗?\n✅ 2. ..."
}}
**现在请直接输出 JSON 对象。**
@@ -649,8 +679,10 @@ process:
- 迷你例子(代码/数学/步骤)
- 易错提醒:`> ⚠️ **常见误区**:...`
- 核心要点块:`> 🔑 **核心要点**:...`
+ - 自测微问题:`> 💡 **自测**:你能不看笔记解释...吗?`
+ - 记忆锚点:`> 🧠 **记忆锚点**:<助记符或类比>`
- 适当使用对照表
- - 结尾的速查表(术语表 + 重点提炼 + 易错清单)
+ - 结尾的速查表(术语表 + 重点提炼 + 易错清单 + 自测清单)
- 短段落和要点列表——绝不要长段散文
输出:
@@ -750,15 +782,16 @@ process:
```
2. **维度分析**:表格之后,讨论该维度的关键权衡、细微差别和边缘情况。
3. **优缺点**:使用明确的 `**优点**:` 和 `**缺点**:` 子块来分析每个选项。
- 4. **适用场景判断**:以明确声明结尾:"对于场景X,选项Y更合适,因为…"
- 5. **绝不**写孤立的选项介绍。每个段落都必须在比较。
- 6. 使用加粗标签、表格和结构化列表。减少长段散文。
+ 4. **量化评分**:为该维度下每个选项给出 1-5 分评分(1=差,5=优秀)。
+ 5. **适用场景判断**:以明确声明结尾:"对于场景X,选项Y更合适,因为…"
+ 6. **绝不**写孤立的选项介绍。每个段落都必须在比较。
+ 7. 使用加粗标签、表格和结构化列表。减少长段散文。
{citation_instruction}
输出:
{{
- "section_content": "## 维度标题\n\n| 指标 | A | B |\n|---|---|---|\n| ... | ... | ... |\n\n**分析**:...\n\n**优缺点**:\n- 选项A:...\n- 选项B:...\n\n**最佳适用**:对于场景X,推荐...{citation_output_hint}"
+ "section_content": "## 维度标题\n\n| 指标 | A | B | 评分A | 评分B |\n|---|---|---|---|---|\n| ... | ... | ... | 4 | 3 |\n\n**分析**:...\n\n**优缺点**:\n- 选项A:...\n- 选项B:...\n\n**最佳适用**:对于场景X,推荐...{citation_output_hint}"
}}
**字数要求**:每个维度章节500-800字。
@@ -776,7 +809,15 @@ process:
总话题数:{total_topics}
**规则**(强制):
- - **决策矩阵表**:必须包含将场景/优先级映射到推荐选项的表格:
+ - **评分汇总表**:必须包含汇总所有维度评分的表格(1-5分):
+ ```
+ | 维度 | 选项 A | 选项 B | 选项 C |
+ |----------|--------|--------|--------|
+ | 维度 1 | 4 | 3 | 5 |
+ | 维度 2 | 3 | 5 | 2 |
+ | **平均** | **3.5**| **4.0**| **3.5**|
+ ```
+ - **决策矩阵表**:包含将场景/优先级映射到推荐选项的表格:
```
| 如果你优先考虑… | 推荐选项 | 原因 |
|------------------|----------|------|
@@ -789,7 +830,7 @@ process:
输出:
{{
- "conclusion": "| 如果你优先考虑… | 推荐选项 | 原因 |\n|---|---|---|\n| ... | ... | ... |\n\n**场景 1**:...\n\n**场景 2**:..."
+ "conclusion": "**评分汇总**\n\n| 维度 | A | B |\n|---|---|---|\n| ... | 4 | 3 |\n| **平均** | **3.5** | **4.0** |\n\n**按场景推荐**\n\n| 如果你优先考虑… | 推荐选项 | 原因 |\n|---|---|---|\n| ... | ... | ... |\n\n**场景 1**:...\n\n**场景 2**:..."
}}
**现在请直接输出 JSON 对象。**
@@ -815,10 +856,10 @@ process:
**强制元素**:
- 比较设定章节(定义比较什么/为什么/标准)
- - 每个主章节 = 一个比较维度 + 对照表
+ - 每个主章节 = 一个比较维度 + 对照表 + 每选项 1-5 量化评分
- 每个维度的优缺点分析
- 每个章节的适用场景判断
- - 结论章节包含决策矩阵表 + 按场景推荐
+ - 结论章节包含评分汇总表 + 决策矩阵表 + 按场景推荐
- 绝不孤立地描述各选项
输出:
@@ -911,27 +952,36 @@ process:
**学习路径阶段规则**(强制):
- 1. **学习目标**:以要点列表开头:"完成本阶段后你将能够:…"
- 2. **为什么是现在**:简要解释先修链——为什么这个阶段在这个位置。
- 3. **核心内容**:教授关键概念。适当使用定义框、例子、图表和代码。保持解释清晰、渐进。
- 4. **练习计划**:包含具体的练习题、小项目或待解决的问题:
+ 1. **阶段元数据**:每个阶段开头标注:
+ ```
+ > ⏱️ **预计时间**:X 小时
+ > 📊 **难度**:基础 / 中级 / 高级
+ ```
+ 2. **学习目标**:以要点列表开头:"完成本阶段后你将能够:…"
+ 3. **为什么是现在**:简要解释先修链——为什么这个阶段在这个位置。
+ 4. **核心内容**:教授关键概念。适当使用定义框、例子、图表和代码。保持解释清晰、渐进。
+ 5. **练习计划**:包含具体的练习题、小项目或待解决的问题:
```
> 📝 **练习**:做什么、预期结果、如何检验答案。
```
- 5. **检查站**:以自评块结尾:
+ 6. **推荐资源**:建议相关书籍、课程、工具或链接:
+ ```
+ > 📚 **推荐资源**:[推荐材料列表]
+ ```
+ 7. **检查站**:以自评块结尾:
```
> ✅ **检查站 — 准备好进入阶段 N+1 了吗?**
> - 你能解释 X 吗?
> - 你能实现 Y 吗?
> - 你能判断 Z 什么时候适用吗?
```
- 6. **绝不**写成报告章节。每个段落都应帮助学习者**行动**,而不只是理解。
+ 8. **绝不**写成报告章节。每个段落都应帮助学习者**行动**,而不只是理解。
{citation_instruction}
输出:
{{
- "section_content": "## 阶段 N. 标题\n\n**学习目标**:\n- ...\n\n**为什么是现在**:...\n\n### 核心内容\n...\n\n> 📝 **练习**:...\n\n> ✅ **检查站 — 准备好进入阶段 N+1 了吗?**\n> - ...{citation_output_hint}"
+ "section_content": "## 阶段 N. 标题\n\n> ⏱️ **预计时间**:X 小时\n> 📊 **难度**:中级\n\n**学习目标**:\n- ...\n\n**为什么是现在**:...\n\n### 核心内容\n...\n\n> 📝 **练习**:...\n\n> 📚 **推荐资源**:...\n\n> ✅ **检查站 — 准备好进入阶段 N+1 了吗?**\n> - ...{citation_output_hint}"
}}
**字数要求**:每个阶段500-800字。
@@ -949,19 +999,26 @@ process:
总话题数:{total_topics}
**规则**(强制):
- - **里程碑检查表**:覆盖所有阶段的表格或清单:
+ - **路线图**:包含 Mermaid 流程图展示阶段进阶:
+ ```mermaid
+ graph LR
+ A["阶段 1: ..."] --> B["阶段 2: ..."]
+ B --> C["阶段 3: ..."]
+ ```
+ - **里程碑检查表**:覆盖所有阶段的表格(含时间估算):
```
- | 阶段 | 里程碑 | 自检 |
- |------|--------|------|
- | 1 | ... | 你能…? |
+ | 阶段 | 里程碑 | 预计时间 | 自检 |
+ |------|--------|----------|------|
+ | 1 | ... | X 小时 | 你能…? |
```
+ - **总时间估算**:汇总所有阶段时间。
- **自我评估**:帮助学习者判断整体准备度。
- **下一步**:完成路径后的具体建议——进阶主题、项目、社区、资源。
- **绝不**写正式结论(不要"局限性")。这是面向未来的、行动导向的。
输出:
{{
- "conclusion": "**里程碑检查表**\n\n| 阶段 | 里程碑 | 自检 |\n|---|---|---|\n| ... | ... | ... |\n\n**自我评估**:...\n\n**下一步**:..."
+ "conclusion": "**学习路线图**\n\n```mermaid\ngraph LR\n A[阶段 1] --> B[阶段 2]\n B --> C[阶段 3]\n```\n\n**里程碑检查表**\n\n| 阶段 | 里程碑 | 预计时间 | 自检 |\n|---|---|---|---|\n| ... | ... | X 小时 | ... |\n\n**总预计时间**:X 小时\n\n**自我评估**:...\n\n**下一步**:..."
}}
**现在请直接输出 JSON 对象。**
@@ -987,10 +1044,13 @@ process:
**强制元素**:
- "适用人群"章节(学习者画像、前置知识、最终目标)
- - 顺序阶段(阶段1 → 2 → 3…),每个包含:目标、为什么现在、核心内容、练习、检查站
+ - 顺序阶段(阶段1 → 2 → 3…),每个包含:
+ - 阶段元数据:`> ⏱️ **预计时间**:X 小时` 和 `> 📊 **难度**:基础/中级/高级`
+ - 目标、为什么现在、核心内容、练习、推荐资源、检查站
- 练习块:`> 📝 **练习**:...`
+ - 推荐资源块:`> 📚 **推荐资源**:...`
- 检查站块:`> ✅ **检查站**:...`
- - "里程碑与下一步"章节(里程碑表 + 后续建议)
+ - "里程碑与下一步"章节(Mermaid 路线图 + 里程碑表 + 总时间估算 + 后续建议)
- 全文可见的先修依赖链
- 绝不写成平铺的主题报告
diff --git a/deeptutor/agents/research/prompts/zh/research_agent.yaml b/deeptutor/agents/research/prompts/zh/research_agent.yaml
index 79ef2369b..6de706045 100644
--- a/deeptutor/agents/research/prompts/zh/research_agent.yaml
+++ b/deeptutor/agents/research/prompts/zh/research_agent.yaml
@@ -172,7 +172,6 @@ process:
"target_dimension": "本次查询针对的知识维度;如果已充足则为空字符串",
"rationale": "工具选择理由与查询目标;如果已充足则为空字符串",
"parallel": false,
- "fallback": ["rag_hybrid", "rag_naive"],
"should_add_new_topic": false,
"new_sub_topic": null,
"new_overview": null,
@@ -257,7 +256,6 @@ process:
"target_dimension": "本次查询针对的知识维度",
"rationale": "工具选择理由和查询目标",
"parallel": false,
- "fallback": ["rag_hybrid", "rag_naive"],
"should_add_new_topic": false,
"new_sub_topic": null,
"new_overview": null,
diff --git a/deeptutor/agents/research/request_config.py b/deeptutor/agents/research/request_config.py
index e5de51862..11dea1037 100644
--- a/deeptutor/agents/research/request_config.py
+++ b/deeptutor/agents/research/request_config.py
@@ -8,10 +8,15 @@ from pydantic import BaseModel, ConfigDict, ValidationError, field_validator
ResearchMode = Literal["notes", "report", "comparison", "learning_path"]
-ResearchDepth = Literal["quick", "standard", "deep"]
+ResearchDepth = Literal["quick", "standard", "deep", "manual"]
ResearchSource = Literal["kb", "web", "papers"]
+class OutlineItem(BaseModel):
+ title: str
+ overview: str = ""
+
+
class DeepResearchRequestConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
@@ -19,12 +24,31 @@ class DeepResearchRequestConfig(BaseModel):
depth: ResearchDepth
sources: list[ResearchSource]
+ manual_subtopics: int | None = None
+ manual_max_iterations: int | None = None
+
+ confirmed_outline: list[OutlineItem] | None = None
+
@field_validator("sources")
@classmethod
def validate_sources(cls, value: list[ResearchSource]) -> list[ResearchSource]:
deduped = list(dict.fromkeys(value))
return deduped
+ @field_validator("manual_subtopics")
+ @classmethod
+ def validate_manual_subtopics(cls, value: int | None) -> int | None:
+ if value is not None:
+ return max(1, min(value, 10))
+ return value
+
+ @field_validator("manual_max_iterations")
+ @classmethod
+ def validate_manual_max_iterations(cls, value: int | None) -> int | None:
+ if value is not None:
+ return max(1, min(value, 10))
+ return value
+
def validate_research_request_config(raw_config: dict[str, Any] | None) -> DeepResearchRequestConfig:
if not isinstance(raw_config, dict):
@@ -44,9 +68,20 @@ def build_research_execution_policy(
request_config: DeepResearchRequestConfig,
enabled_tools: set[str],
) -> dict[str, Any]:
- depth_policy = _build_depth_policy(request_config.depth)
+ depth_policy = _build_depth_policy(
+ request_config.depth,
+ manual_max_iterations=request_config.manual_max_iterations,
+ manual_subtopics=request_config.manual_subtopics,
+ )
mode_policy = _build_mode_policy(request_config.mode, request_config.depth)
+ if request_config.depth == "manual" and request_config.manual_subtopics is not None:
+ n = request_config.manual_subtopics
+ if mode_policy.get("decompose_mode") == "auto":
+ mode_policy["auto_max_subtopics"] = n
+ else:
+ mode_policy["initial_subtopics"] = n
+
source_tools: set[str] = set()
if "kb" in request_config.sources:
source_tools.add("rag")
@@ -80,8 +115,7 @@ def build_research_execution_policy(
"execution_mode": depth_policy["execution_mode"],
"max_parallel_topics": depth_policy["max_parallel_topics"],
"new_topic_min_score": depth_policy["new_topic_min_score"],
- "enable_rag_hybrid": "rag" in source_tools,
- "enable_rag_naive": "rag" in source_tools,
+ "enable_rag": "rag" in source_tools,
"enable_web_search": "web_search" in source_tools,
"enable_paper_search": "paper_search" in source_tools,
"enable_run_code": allow_code_execution,
@@ -187,8 +221,13 @@ def build_research_runtime_config(
return runtime_config
-def _build_depth_policy(depth: ResearchDepth) -> dict[str, Any]:
- policies: dict[ResearchDepth, dict[str, Any]] = {
+def _build_depth_policy(
+ depth: ResearchDepth,
+ *,
+ manual_max_iterations: int | None = None,
+ manual_subtopics: int | None = None,
+) -> dict[str, Any]:
+ presets: dict[str, dict[str, Any]] = {
"quick": {
"max_iterations": 1,
"iteration_mode": "fixed",
@@ -214,75 +253,27 @@ def _build_depth_policy(depth: ResearchDepth) -> dict[str, Any]:
"queue_max_length": 8,
},
}
- return dict(policies[depth])
+
+ if depth == "manual":
+ iters = manual_max_iterations or 3
+ subtopics = manual_subtopics or 3
+ return {
+ "max_iterations": iters,
+ "iteration_mode": "fixed",
+ "execution_mode": "series" if subtopics <= 3 else "parallel",
+ "max_parallel_topics": min(subtopics, 3),
+ "new_topic_min_score": 0.88,
+ "queue_max_length": subtopics + 2,
+ }
+
+ return dict(presets[depth])
def _build_mode_policy(mode: ResearchMode, depth: ResearchDepth) -> dict[str, Any]:
- manual_subtopics_by_depth: dict[ResearchDepth, int] = {
- "quick": 2,
- "standard": 3,
- "deep": 4,
- }
- auto_subtopics_by_depth: dict[ResearchDepth, int] = {
- "quick": 2,
- "standard": 4,
- "deep": 6,
- }
- policies: dict[ResearchMode, dict[str, Any]] = {
- "notes": {
- "rephrase_enabled": False,
- "rephrase_iterations": 1,
- "decompose_mode": "manual",
- "initial_subtopics": manual_subtopics_by_depth[depth],
- "auto_max_subtopics": None,
- "min_section_length": 260,
- "report_single_pass_threshold": 99,
- "enable_citation_list": True,
- "enable_inline_citations": False,
- "deduplicate_enabled": False,
- "style": "study_notes",
- },
- "report": {
- "rephrase_enabled": False,
- "rephrase_iterations": 1,
- "decompose_mode": "auto",
- "initial_subtopics": None,
- "auto_max_subtopics": auto_subtopics_by_depth[depth],
- "min_section_length": 650,
- "report_single_pass_threshold": 2,
- "enable_citation_list": True,
- "enable_inline_citations": False,
- "deduplicate_enabled": False,
- "style": "report",
- },
- "comparison": {
- "rephrase_enabled": True,
- "rephrase_iterations": 1 if depth != "deep" else 2,
- "decompose_mode": "manual",
- "initial_subtopics": max(2, manual_subtopics_by_depth[depth]),
- "auto_max_subtopics": None,
- "min_section_length": 520,
- "report_single_pass_threshold": 2,
- "enable_citation_list": True,
- "enable_inline_citations": False,
- "deduplicate_enabled": False,
- "style": "comparison",
- },
- "learning_path": {
- "rephrase_enabled": True,
- "rephrase_iterations": 1,
- "decompose_mode": "auto",
- "initial_subtopics": None,
- "auto_max_subtopics": auto_subtopics_by_depth[depth],
- "min_section_length": 420,
- "report_single_pass_threshold": 99,
- "enable_citation_list": True,
- "enable_inline_citations": False,
- "deduplicate_enabled": False,
- "style": "learning_path",
- },
- }
- return dict(policies[mode])
+ from deeptutor.agents.research.mode_strategy import get_strategy
+
+ strategy = get_strategy(mode)
+ return dict(strategy.build_policy(depth))
__all__ = [
diff --git a/deeptutor/agents/research/research_pipeline.py b/deeptutor/agents/research/research_pipeline.py
index 1817ea2eb..a74244ae5 100644
--- a/deeptutor/agents/research/research_pipeline.py
+++ b/deeptutor/agents/research/research_pipeline.py
@@ -41,6 +41,7 @@ class ResearchPipeline:
kb_name: str | None = None,
progress_callback: Callable | None = None,
trace_callback: Callable[[dict[str, Any]], Any] | None = None,
+ pre_confirmed_outline: list[dict[str, str]] | None = None,
):
"""
Initialize research workflow
@@ -53,10 +54,12 @@ class ResearchPipeline:
research_id: Research task ID (optional)
kb_name: Knowledge base name (optional, if provided overrides config file setting)
progress_callback: Progress callback function (optional), signature: callback(event: Dict[str, Any])
+ pre_confirmed_outline: Pre-confirmed sub-topics from outline preview (skips decompose)
"""
self.config = config
self.progress_callback = progress_callback
self.trace_callback = trace_callback
+ self.pre_confirmed_outline = pre_confirmed_outline
# If kb_name is provided, override config
if kb_name is not None:
@@ -292,36 +295,15 @@ class ResearchPipeline:
if tool_type in ("rag_hybrid", "rag_naive", "rag"):
rag_cfg = self.config.get("rag", {})
kb_name = rag_cfg.get("kb_name", "DE-all")
- default_mode = rag_cfg.get("default_mode", "hybrid")
- fallback_mode = rag_cfg.get("fallback_mode", "naive")
- if tool_type == "rag_hybrid":
- mode = "hybrid"
- elif tool_type == "rag_naive":
- mode = "naive"
- else:
- mode = default_mode
- try:
- result = await self._call_tool_with_retry(
- self._tool_registry.execute,
- tool_type,
- query=query,
- kb_name=kb_name,
- mode=mode,
- max_retries=max_retries,
- timeout=default_timeout,
- tool_name=f"{tool_type}({mode})",
- )
- except Exception:
- result = await self._call_tool_with_retry(
- self._tool_registry.execute,
- tool_type,
- query=query,
- kb_name=kb_name,
- mode=fallback_mode,
- max_retries=1,
- timeout=default_timeout,
- tool_name=f"{tool_type}({fallback_mode})",
- )
+ result = await self._call_tool_with_retry(
+ self._tool_registry.execute,
+ "rag",
+ query=query,
+ kb_name=kb_name,
+ max_retries=max_retries,
+ timeout=default_timeout,
+ tool_name="rag",
+ )
elif tool_type == "web_search":
result = await self._call_tool_with_retry(
self._tool_registry.execute,
@@ -356,16 +338,16 @@ class ResearchPipeline:
tool_name="run_code",
)
else:
- kb_name = self.config.get("rag", {}).get("kb_name", "ai_textbook")
+ rag_cfg = self.config.get("rag", {})
+ kb_name = rag_cfg.get("kb_name", "DE-all")
result = await self._call_tool_with_retry(
self._tool_registry.execute,
"rag",
query=query,
kb_name=kb_name,
- mode="hybrid",
max_retries=max_retries,
timeout=default_timeout,
- tool_name="rag(hybrid)",
+ tool_name="rag",
)
except Exception as e:
failure = json.dumps(
@@ -409,7 +391,10 @@ class ResearchPipeline:
if "content" not in payload:
payload["content"] = result.content
if result.sources:
- payload["sources"] = result.sources
+ if "sources" not in payload:
+ payload["sources"] = result.sources
+ else:
+ payload["tool_sources"] = result.sources
payload.setdefault("success", result.success)
return json.dumps(payload, ensure_ascii=False)
@@ -493,11 +478,18 @@ class ResearchPipeline:
from deeptutor.agents.research.utils.token_tracker import get_token_tracker
tracker = get_token_tracker()
- cost_summary = tracker.format_summary()
- self.logger.info(cost_summary)
+ cost_summary_text = tracker.format_summary()
+ self.logger.info(cost_summary_text)
cost_file = self.cache_dir / "token_cost_summary.json"
tracker.save(str(cost_file))
self.logger.success(f"Cost statistics saved: {cost_file}")
+ t_summary = tracker.get_summary()
+ if t_summary.get("total_calls", 0) > 0:
+ metadata["cost_summary"] = {
+ "total_cost_usd": t_summary.get("total_cost_usd", 0),
+ "total_tokens": t_summary.get("total_tokens", 0),
+ "total_calls": t_summary.get("total_calls", 0),
+ }
except Exception as _e:
self.logger.warning(f"Cost statistics failed: {_e}")
@@ -541,7 +533,44 @@ class ResearchPipeline:
"""
self._log_progress("planning", "planning_started", user_topic=topic)
- # Check if topic rephrasing is enabled
+ if self.pre_confirmed_outline:
+ self.logger.info("\n【Step 1-2】Using pre-confirmed outline (skipping rephrase + decompose)...")
+ optimized_topic = topic
+ self.optimized_topic = optimized_topic
+ self._log_progress(
+ "planning",
+ "rephrase_skipped",
+ optimized_topic=optimized_topic,
+ reason="pre-confirmed outline provided",
+ )
+
+ self.logger.info("\n【Step 3】Initializing Queue from confirmed outline...")
+ for item in self.pre_confirmed_outline:
+ title = (item.get("title") or "").strip()
+ overview = item.get("overview", "")
+ if not title:
+ continue
+ try:
+ block = self.queue.add_block(sub_topic=title, overview=overview)
+ self._log_progress(
+ "planning",
+ "queue_seeded",
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ total_blocks=len(self.queue.blocks),
+ )
+ except RuntimeError as err:
+ self.logger.warning(f"Queue reached capacity limit: {err}")
+ break
+
+ stats = self.queue.get_statistics()
+ self._log_progress("planning", "planning_completed", total_blocks=stats["total_blocks"])
+ self.logger.success("\nPhase 1 Completed (from confirmed outline):")
+ self.logger.info(f" - Topic: {optimized_topic}")
+ self.logger.info(f" - Subtopic Count: {stats['total_blocks']}")
+ self.agents["manager"].set_primary_topic(optimized_topic)
+ return optimized_topic
+
rephrase_config = self.config.get("planning", {}).get("rephrase", {})
rephrase_enabled = rephrase_config.get("enabled", True)
@@ -588,18 +617,15 @@ class ResearchPipeline:
self.logger.info("\n【Step 2】Topic Decomposition...")
- # Use DecomposeAgent to decompose topic
decompose_config = self.config.get("planning", {}).get("decompose", {})
mode = decompose_config.get("mode", "manual")
if mode == "auto":
- # Auto mode: use auto_max_subtopics as limit
num_subtopics = decompose_config.get(
"auto_max_subtopics", decompose_config.get("initial_subtopics", 5)
)
self.logger.info(f"📌 Using Auto mode, max subtopics: {num_subtopics}")
else:
- # Manual mode: use initial_subtopics
num_subtopics = decompose_config.get("initial_subtopics", 5)
self.logger.info(f"📌 Using Manual mode, expected subtopics: {num_subtopics}")
@@ -607,7 +633,6 @@ class ResearchPipeline:
"planning", "decompose_started", requested_subtopics=num_subtopics, mode=mode
)
- # Set citation manager to DecomposeAgent
self.agents["decompose"].set_citation_manager(self.citation_manager)
decompose_result = await self.agents["decompose"].process(
@@ -620,7 +645,6 @@ class ResearchPipeline:
rag_context_length=len(decompose_result.get("rag_context", "") or ""),
)
- # Save Planning stage results (includes sub_queries / rag_context / sub_topics)
try:
step1_path = self.cache_dir / "step1_planning.json"
with open(step1_path, "w", encoding="utf-8") as f:
@@ -641,7 +665,6 @@ class ResearchPipeline:
except Exception as _e:
self.logger.warning(f"Failed to save Planning stage data: {_e}")
- # Add subtopics to queue
self.logger.info("\n【Step 3】Initializing Queue...")
for sub_topic_data in decompose_result.get("sub_topics", []):
title = (sub_topic_data.get("title") or "").strip()
diff --git a/deeptutor/agents/research/utils/citation_manager.py b/deeptutor/agents/research/utils/citation_manager.py
index bf9b753ff..8b0f00fad 100644
--- a/deeptutor/agents/research/utils/citation_manager.py
+++ b/deeptutor/agents/research/utils/citation_manager.py
@@ -251,9 +251,9 @@ class CitationManager:
try:
tool_type_lower = tool_type.lower()
- if tool_type_lower in ("rag_naive", "rag_hybrid"):
+ if tool_type_lower in ("rag", "rag_naive", "rag_hybrid"):
citation_info = self._extract_rag_citation(
- citation_id, tool_type, raw_answer, tool_trace
+ citation_id, "rag", raw_answer, tool_trace
)
elif tool_type_lower == "web_search":
citation_info = self._extract_web_citation(
@@ -523,18 +523,12 @@ class CitationManager:
return " ".join(parts) if parts else None
- if tool_type in ("rag_naive", "rag_hybrid"):
- # RAG citation with source info
+ if tool_type in ("rag", "rag_naive", "rag_hybrid"):
query = citation.get("query", "")
kb_name = citation.get("kb_name", "")
sources = citation.get("sources", [])
- tool_type_display = {
- "rag_naive": "RAG Retrieval",
- "rag_hybrid": "Hybrid RAG Retrieval",
- }.get(tool_type, tool_type)
-
- parts = [f"{tool_type_display}: {query}"]
+ parts = [f"RAG: {query}"]
if kb_name:
parts.append(f"[KB: {kb_name}]")
if sources:
diff --git a/deeptutor/agents/solve/agents/planner_agent.py b/deeptutor/agents/solve/agents/planner_agent.py
index 84042b17b..3c31a954a 100644
--- a/deeptutor/agents/solve/agents/planner_agent.py
+++ b/deeptutor/agents/solve/agents/planner_agent.py
@@ -135,7 +135,10 @@ class PlannerAgent(BaseAgent):
system_prompt, user_prompt, image_url,
)
- response = await self.call_llm(**llm_kwargs)
+ chunks: list[str] = []
+ async for chunk in self.stream_llm(**llm_kwargs):
+ chunks.append(chunk)
+ response = "".join(chunks)
return self._parse_plan(response, scratchpad if replan else None)
@@ -193,7 +196,8 @@ class PlannerAgent(BaseAgent):
question=question, num_queries=num_queries,
)
try:
- response = await self.call_llm(
+ parts: list[str] = []
+ async for chunk in self.stream_llm(
user_prompt=user_prompt,
system_prompt="",
response_format={"type": "json_object"},
@@ -207,7 +211,9 @@ class PlannerAgent(BaseAgent):
trace_role="plan",
trace_group="plan",
),
- )
+ ):
+ parts.append(chunk)
+ response = "".join(parts)
payload = json.loads(response)
queries = payload.get("queries", [])
if not isinstance(queries, list):
@@ -358,7 +364,8 @@ class PlannerAgent(BaseAgent):
user_prompt = prompt_template.format(raw_retrieval_text=raw_text)
try:
- result = await self.call_llm(
+ parts: list[str] = []
+ async for chunk in self.stream_llm(
user_prompt=user_prompt,
system_prompt="You are a knowledge organizer. Consolidate the provided passages into a clean, structured summary.",
stage="plan_aggregate_context",
@@ -371,7 +378,9 @@ class PlannerAgent(BaseAgent):
trace_role="plan",
trace_group="plan",
),
- )
+ ):
+ parts.append(chunk)
+ result = "".join(parts)
logger.info("Aggregated retrieved context: %d chars", len(result))
return result.strip() or raw_text
except Exception as exc:
diff --git a/deeptutor/agents/solve/agents/solver_agent.py b/deeptutor/agents/solve/agents/solver_agent.py
index eabe2a4d7..2eecffce3 100644
--- a/deeptutor/agents/solve/agents/solver_agent.py
+++ b/deeptutor/agents/solve/agents/solver_agent.py
@@ -127,7 +127,10 @@ class SolverAgent(BaseAgent):
system_prompt, user_prompt, image_url,
)
- response = await self.call_llm(**llm_kwargs)
+ chunks: list[str] = []
+ async for chunk in self.stream_llm(**llm_kwargs):
+ chunks.append(chunk)
+ response = "".join(chunks)
decision = self._parse_decision(response)
decision["_trace"] = trace_meta
diff --git a/deeptutor/agents/solve/agents/writer_agent.py b/deeptutor/agents/solve/agents/writer_agent.py
index 347b6f497..660532369 100644
--- a/deeptutor/agents/solve/agents/writer_agent.py
+++ b/deeptutor/agents/solve/agents/writer_agent.py
@@ -9,6 +9,7 @@ Supports two modes:
from __future__ import annotations
+from collections.abc import Awaitable, Callable
from typing import Any
from deeptutor.agents.base_agent import BaseAgent
@@ -16,6 +17,8 @@ from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..memory.scratchpad import Scratchpad
+ContentChunkCallback = Callable[[str], Awaitable[None]]
+
class WriterAgent(BaseAgent):
"""Produces the final answer from accumulated evidence."""
@@ -52,36 +55,54 @@ class WriterAgent(BaseAgent):
scratchpad: Scratchpad,
language: str = "en",
preference: str = "",
+ on_content_chunk: ContentChunkCallback | None = None,
) -> str:
"""Generate the final Markdown answer in a single LLM call.
- Args:
- question: Original user question.
- scratchpad: Completed scratchpad with all evidence.
- language: Output language hint (e.g. "en", "zh").
- preference: Optional personalisation context.
-
- Returns:
- Markdown-formatted answer string.
+ When *on_content_chunk* is provided the LLM response is streamed
+ token-by-token; each chunk is forwarded via the callback so the
+ caller can push it to the frontend in real time.
"""
system_prompt = self._build_system_prompt()
user_prompt = self._build_user_prompt(question, scratchpad, language, preference)
- response = await self.call_llm(
- user_prompt=user_prompt,
- system_prompt=system_prompt,
- max_tokens=self.get_max_tokens() or 8192,
- stage="write",
- trace_meta=build_trace_metadata(
- call_id=new_call_id("write"),
- phase="writing",
- label="Write answer",
- call_kind="llm_generation",
- trace_id="write",
- ),
+ trace_meta = build_trace_metadata(
+ call_id=new_call_id("write"),
+ phase="writing",
+ label="Write answer",
+ call_kind="llm_final_answer",
+ trace_id="write",
)
- return response.strip()
+ if on_content_chunk is not None:
+ chunks: list[str] = []
+ async for chunk in self.stream_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ max_tokens=self.get_max_tokens() or 8192,
+ stage="write",
+ trace_meta=trace_meta,
+ ):
+ chunks.append(chunk)
+ await on_content_chunk(chunk)
+ response = "".join(chunks)
+ else:
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ max_tokens=self.get_max_tokens() or 8192,
+ stage="write",
+ trace_meta=trace_meta,
+ )
+
+ full_answer = self._ensure_references(response.strip(), scratchpad)
+
+ if on_content_chunk is not None:
+ suffix = full_answer[len(response.strip()):]
+ if suffix:
+ await on_content_chunk(suffix)
+
+ return full_answer
# ==================================================================
# Detailed / Iterative mode
@@ -93,6 +114,7 @@ class WriterAgent(BaseAgent):
scratchpad: Scratchpad,
language: str = "en",
preference: str = "",
+ on_content_chunk: ContentChunkCallback | None = None,
) -> str:
"""Generate a detailed answer through iterative step-by-step writing.
@@ -103,18 +125,14 @@ class WriterAgent(BaseAgent):
Final : draft_N → concise_answer
Output : concise_answer + "---" + draft_N
- Args:
- question: Original user question.
- scratchpad: Completed scratchpad with all evidence.
- language: Output language hint.
- preference: Optional personalisation context.
-
- Returns:
- Combined Markdown string: concise answer + detailed answer.
+ Individual draft/concise LLM calls stream via trace panel.
+ The assembled final answer is sent to *on_content_chunk* if provided.
"""
if scratchpad.plan is None:
- # Fallback: no plan, use simple mode
- return await self.process(question, scratchpad, language, preference)
+ return await self.process(
+ question, scratchpad, language, preference,
+ on_content_chunk=on_content_chunk,
+ )
# Collect completed/in_progress steps that have entries
steps_with_evidence = []
@@ -176,7 +194,12 @@ class WriterAgent(BaseAgent):
# --- Assemble final output ---
final = f"## Summary\n\n{concise}\n\n---\n\n{draft}"
- return final
+ full_answer = self._ensure_references(final, scratchpad)
+
+ if on_content_chunk is not None:
+ await on_content_chunk(full_answer)
+
+ return full_answer
# ------------------------------------------------------------------
# Internal helpers for iterative mode
@@ -215,7 +238,8 @@ class WriterAgent(BaseAgent):
f"## Language\n{language}"
)
- response = await self.call_llm(
+ chunks: list[str] = []
+ async for chunk in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
max_tokens=self.get_max_tokens() or 8192,
@@ -228,8 +252,9 @@ class WriterAgent(BaseAgent):
trace_id=f"write-draft-{iteration}",
iteration=iteration,
),
- )
- return response.strip()
+ ):
+ chunks.append(chunk)
+ return "".join(chunks).strip()
async def _write_concise(
self,
@@ -255,7 +280,8 @@ class WriterAgent(BaseAgent):
f"## Language\n{language}"
)
- response = await self.call_llm(
+ chunks: list[str] = []
+ async for chunk in self.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
max_tokens=1024,
@@ -267,8 +293,9 @@ class WriterAgent(BaseAgent):
call_kind="llm_summary",
trace_id="write-concise",
),
- )
- return response.strip()
+ ):
+ chunks.append(chunk)
+ return "".join(chunks).strip()
@staticmethod
def _format_step_evidence(step, entries) -> str:
@@ -282,6 +309,23 @@ class WriterAgent(BaseAgent):
parts.append(block)
return "\n\n".join(parts)
+ # ------------------------------------------------------------------
+ # Post-processing
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _ensure_references(answer: str, scratchpad: Scratchpad) -> str:
+ """Append a References section if the LLM omitted one."""
+ if not answer:
+ return answer
+ has_refs = ("## References" in answer or "## 参考文献" in answer)
+ if has_refs:
+ return answer
+ refs = scratchpad.format_sources_markdown()
+ if not refs:
+ return answer
+ return f"{answer}\n\n---\n\n{refs}"
+
# ------------------------------------------------------------------
# Prompt construction
# ------------------------------------------------------------------
diff --git a/deeptutor/agents/solve/main_solver.py b/deeptutor/agents/solve/main_solver.py
index e4290ded4..de0bcdd06 100644
--- a/deeptutor/agents/solve/main_solver.py
+++ b/deeptutor/agents/solve/main_solver.py
@@ -318,6 +318,11 @@ class MainSolver:
self.logger.info(f"\n{self.token_tracker.format_summary()}")
cost_file = os.path.join(output_dir, "cost_report.json")
self.token_tracker.save(cost_file)
+ result["metadata"]["cost_summary"] = {
+ "total_cost_usd": summary.get("total_cost_usd", 0),
+ "total_tokens": summary.get("total_tokens", 0),
+ "total_calls": summary.get("total_calls", 0),
+ }
self.token_tracker.reset()
self.logger.success("Problem solving completed")
@@ -590,12 +595,15 @@ class MainSolver:
preference = "" if self.disable_memory else self._get_user_preference()
+ content_cb = getattr(self, "_content_callback", None)
+
if detailed:
final_answer = await self.writer_agent.process_iterative(
question=question,
scratchpad=scratchpad,
language=lang_code,
preference=preference,
+ on_content_chunk=content_cb,
)
else:
final_answer = await self.writer_agent.process(
@@ -603,6 +611,7 @@ class MainSolver:
scratchpad=scratchpad,
language=lang_code,
preference=preference,
+ on_content_chunk=content_cb,
)
if self.logger.display_manager:
diff --git a/deeptutor/agents/solve/memory/scratchpad.py b/deeptutor/agents/solve/memory/scratchpad.py
index 90428fa41..acdfad8f4 100644
--- a/deeptutor/agents/solve/memory/scratchpad.py
+++ b/deeptutor/agents/solve/memory/scratchpad.py
@@ -356,13 +356,18 @@ class Scratchpad:
# ------------------------------------------------------------------
def get_all_sources(self) -> list[dict[str, Any]]:
- """Return deduplicated list of all sources with IDs."""
+ """Return deduplicated list of all sources with IDs.
+
+ Each distinct (type, file, url, chunk_id) tuple is a unique source.
+ For RAG sources this means different queries produce separate citations
+ even when they target the same knowledge base.
+ """
seen: set[str] = set()
result: list[dict[str, Any]] = []
counter: dict[str, int] = {}
for entry in self.entries:
for src in entry.sources:
- key = f"{src.type}:{src.file or src.url or src.chunk_id}"
+ key = f"{src.type}|{src.file or ''}|{src.url or ''}|{src.chunk_id or ''}"
if key not in seen:
seen.add(key)
prefix = src.type if src.type in ("rag", "web", "code") else "src"
@@ -374,16 +379,33 @@ class Scratchpad:
return result
def format_sources_markdown(self) -> str:
- """Format sources as a Markdown references section."""
+ """Format sources as a Markdown references section with clickable URLs."""
sources = self.get_all_sources()
if not sources:
return ""
lines = ["## References\n"]
for s in sources:
- label = s.get("file") or s.get("url") or s.get("chunk_id") or "unknown"
- lines.append(f"- **[{s['id']}]** {label}")
+ label = self._source_label(s)
+ url = s.get("url", "")
+ if url:
+ lines.append(f"- **[{s['id']}]** [{label}]({url})")
+ else:
+ lines.append(f"- **[{s['id']}]** {label}")
return "\n".join(lines)
+ @staticmethod
+ def _source_label(s: dict[str, Any]) -> str:
+ """Build a human-readable label for a source entry.
+
+ RAG sources use the query text as primary label with the knowledge-base
+ name as qualifier, so different queries are visually distinguishable.
+ """
+ if s.get("type") == "rag" and s.get("chunk_id"):
+ query_text = s["chunk_id"]
+ kb = s.get("file")
+ return f"{query_text} ({kb})" if kb else query_text
+ return s.get("file") or s.get("url") or s.get("chunk_id") or "unknown"
+
# ------------------------------------------------------------------
# Persistence
# ------------------------------------------------------------------
diff --git a/deeptutor/agents/solve/prompts/en/writer_agent.yaml b/deeptutor/agents/solve/prompts/en/writer_agent.yaml
index a9884ba5f..38228628b 100644
--- a/deeptutor/agents/solve/prompts/en/writer_agent.yaml
+++ b/deeptutor/agents/solve/prompts/en/writer_agent.yaml
@@ -1,6 +1,6 @@
system: |
# Role
- You are an **Expert Answer Writer**. Your task is to compose a clear, well-structured answer based on the evidence gathered during the solving process.
+ You are an **Expert Answer Writer**. Your task is to compose a clear, well-structured, and visually rich answer based on the evidence gathered during the solving process.
# Formatting Rules
- Use **Markdown** with appropriate headings (`##`, `###`).
@@ -11,19 +11,43 @@ system: |
- Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.
- If code execution produced images that appear in the evidence as actual artifacts (with real file paths), embed them using the path from the evidence. **Never invent or guess image file names** — only reference artifacts that explicitly exist in the gathered evidence.
- For code results, show only the key logic or result — not the full script.
- - Use tables where they improve clarity.
+ - Use tables where they improve clarity (e.g. comparisons, parameter lists, categorical summaries).
+ - **Visual enhancement**: When content involves processes, architectures, taxonomies, timelines, or decision logic, use Mermaid diagrams to present them visually:
+ - Processes / steps → `flowchart` or `graph`
+ - Timelines / phases → `timeline`
+ - Hierarchies / taxonomies → `mindmap`
+ - Interactions / call sequences → `sequenceDiagram`
+ - State transitions → `stateDiagram-v2`
+ - Example:
+ ```mermaid
+ flowchart LR
+ A[Input] --> B[Process] --> C[Output]
+ ```
+ Mermaid diagrams should be woven naturally into the text to help readers grasp complex relationships — they supplement rather than replace written explanations. Do not force them — only include a diagram when it genuinely improves understanding.
+ - Use **blockquotes** (`>`) to highlight core conclusions, key insights, or important caveats.
+ - Leverage nested ordered and unordered lists for multi-level points.
+
+ # Writing Style
+ - **Elaborate sufficiently**: Do not merely list bullet points — expand each key concept with 2–4 sentences of explanation or analysis. Avoid overly terse, telegraphic writing.
+ - **Smooth transitions**: Bridge paragraphs and sections with connecting sentences that guide the reader through the logical progression, rather than jumping abruptly to the next topic.
+ - **Explain the "why", not just the "what"**: Go beyond stating facts — illuminate the underlying reasons, motivations, or significance to help readers build deeper understanding.
+ - **Use analogies and concrete examples**: For abstract or technical concepts, offer everyday analogies or specific scenarios to make the material more accessible and engaging.
+ - **Professional yet approachable tone**: Maintain academic rigour while avoiding stiff, mechanical phrasing. Write as a patient, knowledgeable teacher explaining to an eager learner.
+ - **Balance depth and brevity**: Give core arguments rich, detailed treatment; supporting details can be more concise — this creates a natural reading rhythm.
# Structure
1. Open with a concise summary (1–3 sentences) if the question warrants it.
- 2. Provide a thorough explanation organised by logical sections.
- 3. Include relevant derivations, examples, or calculations.
- 4. End with a **## References** section listing all cited sources.
+ 2. Provide a thorough explanation organised by logical sections, with smooth transitions between them.
+ 3. Include relevant derivations, examples, or calculations, accompanied by sufficient context.
+ 4. Where complex concepts or multi-step processes arise, consider supplementing with visuals (tables, Mermaid diagrams).
+ 5. End with a **## References** section listing all cited sources.
# Important
- Base your answer **only** on the provided evidence. Do not fabricate information.
- **Never reference images or files that do not appear in the evidence.** If no code execution artifact exists, do not embed any image.
- If the evidence is insufficient, state what is missing rather than guessing.
- Write in the language requested by the user (see the Language field).
+ - Mermaid diagram labels should also use the same language as the rest of the answer.
user_template: |
## Question
@@ -58,13 +82,22 @@ iterative_system: |
- Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.
- If code execution produced images that appear in the evidence as actual artifacts (with real file paths), embed them using the path from the evidence. **Never invent or guess image file names.**
- Use tables where they improve clarity.
+ - **Visual enhancement**: When content involves processes, architectures, taxonomies, or decision logic, use Mermaid diagrams (`flowchart`, `sequenceDiagram`, `mindmap`, etc.) to supplement the explanation. Only include a diagram when it genuinely improves understanding — do not force them.
+ - Use blockquotes (`>`) to highlight core conclusions or key insights.
+
+ # Writing Style
+ - Elaborate each key concept with 2–4 sentences rather than terse bullet points.
+ - Use smooth transitions between paragraphs and sections to guide the reader through the logical flow.
+ - Explain not just "what" but "why" — illuminate underlying reasons and significance.
+ - Write in a professional yet approachable tone, like a patient teacher explaining to an eager learner.
# Guidelines
- - When a previous draft is provided, **expand and refine it** with the new evidence — do not discard prior content.
- - Reorganise sections if the new evidence changes the logical flow.
+ - When a previous draft is provided, **expand and refine it** with the new evidence — do not discard prior content. Also polish existing prose to improve overall fluency.
+ - Reorganise sections if the new evidence changes the logical flow, but ensure transitions remain natural.
+ - As evidence accumulates, consider whether to add or update visual elements (tables, Mermaid diagrams) to better present the overall structure.
- Base your answer **only** on the provided evidence and prior draft. Do not fabricate information.
- **Never reference images or files that do not appear in the evidence.** If no code execution artifact exists, do not embed any image.
- - Write in the language specified.
+ - Write in the language specified. Mermaid diagram labels should also use the same language as the answer.
iterative_user_template: |
## Question
diff --git a/deeptutor/agents/solve/prompts/zh/writer_agent.yaml b/deeptutor/agents/solve/prompts/zh/writer_agent.yaml
index 11521ed63..340f3d071 100644
--- a/deeptutor/agents/solve/prompts/zh/writer_agent.yaml
+++ b/deeptutor/agents/solve/prompts/zh/writer_agent.yaml
@@ -1,6 +1,6 @@
system: |
# 角色
- 你是一个**专业的解答撰写者**。你的任务是根据求解过程中收集的证据,撰写一篇清晰、结构良好的解答。
+ 你是一个**专业的解答撰写者**。你的任务是根据求解过程中收集的证据,撰写一篇清晰、结构良好、视觉丰富的解答。
# 格式规则
- 使用 **Markdown** 和适当的标题(`##`、`###`)。
@@ -11,19 +11,43 @@ system: |
- 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。
- 如果代码执行生成了图片,且这些图片作为实际 artifact(带有真实文件路径)出现在证据中,则使用证据中的路径嵌入图片。**绝对不要捏造或猜测图片文件名** — 只引用证据中明确存在的 artifact。
- 对于代码结果,只展示关键逻辑或结果 — 不要展示完整脚本。
- - 在表格能提高清晰度时使用表格。
+ - 在表格能提高清晰度时使用表格(如对比、参数列表、分类汇总等)。
+ - **可视化增强**:当内容涉及流程、架构、分类关系、时间线或决策逻辑时,使用 Mermaid 图表来直观呈现:
+ - 流程/步骤 → `flowchart` 或 `graph`
+ - 时间线/阶段 → `timeline`
+ - 层次/分类 → `mindmap`
+ - 交互/调用 → `sequenceDiagram`
+ - 状态转换 → `stateDiagram-v2`
+ - 例如:
+ ```mermaid
+ flowchart LR
+ A[输入] --> B[处理] --> C[输出]
+ ```
+ Mermaid 图应作为辅助手段自然穿插在文本中,帮助读者理解复杂关系,而非替代文字解释。不必强行使用 — 仅在图表确实能增强理解时才加入。
+ - 善用 **引用块**(`>`)来突出核心结论、关键洞察或重要提醒。
+ - 对于多层次的要点,灵活运用有序列表和无序列表的嵌套。
+
+ # 写作风格
+ - **充分展开论述**:不要只罗列要点,每个关键概念都应有 2–4 句话的解释或分析。避免过于简短、电报式的表达。
+ - **自然流畅的过渡**:段落与段落之间、章节与章节之间应有衔接语句,引导读者理解内容的逻辑推进,而非生硬地跳跃到下一个话题。
+ - **解释"为什么"而非仅仅"是什么"**:不要只陈述事实,还要说明背后的原因、动机或意义,帮助读者建立深层理解。
+ - **善用类比与具体示例**:对于抽象或专业的概念,尝试用日常类比或具体场景来辅助说明,让内容更易理解。
+ - **语气专业但亲切**:保持学术严谨性的同时,避免过于生硬刻板的措辞。像一位有耐心的老师在给学生讲解一样。
+ - **详略得当**:核心论点要浓墨重彩地展开,辅助信息可以适当精简,形成节奏感。
# 结构
1. 如果问题需要,以简洁的摘要开头(1–3 句话)。
- 2. 按逻辑章节提供详尽的解释。
- 3. 包含相关的推导、示例或计算。
- 4. 以 **## 参考文献** 部分结束,列出所有引用的来源。
+ 2. 按逻辑章节提供详尽的解释,章节之间有过渡和衔接。
+ 3. 包含相关的推导、示例或计算,并附上必要的上下文说明。
+ 4. 在涉及复杂概念或多步流程时,考虑用可视化(表格、Mermaid 图)辅助说明。
+ 5. 以 **## 参考文献** 部分结束,列出所有引用的来源。
# 重要提示
- 你的回答**只能**基于提供的证据。不要编造信息。
- **绝对不要引用证据中不存在的图片或文件。** 如果不存在代码执行 artifact,不要嵌入任何图片。
- 如果证据不足,说明缺少什么,而不是猜测。
- 使用用户要求的语言撰写(参见"语言"字段)。
+ - Mermaid 图中的内容也应使用与正文一致的语言。
user_template: |
## 问题
@@ -58,13 +82,22 @@ iterative_system: |
- 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。
- 如果代码执行生成了图片,且这些图片作为实际 artifact(带有真实文件路径)出现在证据中,则使用证据中的路径嵌入图片。**绝对不要捏造或猜测图片文件名。**
- 在表格能提高清晰度时使用表格。
+ - **可视化增强**:当内容涉及流程、架构、分类关系或决策逻辑时,可使用 Mermaid 图表(`flowchart`、`sequenceDiagram`、`mindmap` 等)来辅助说明。仅在图表确实能增强理解时才加入,不要强行使用。
+ - 善用引用块(`>`)来突出核心结论或关键洞察。
+
+ # 写作风格
+ - 充分展开每个关键概念(2–4 句解释),避免过于简短的罗列。
+ - 段落和章节之间要有自然的过渡衔接,引导读者理解逻辑推进。
+ - 不仅陈述"是什么",还要说明"为什么",帮助读者建立深层理解。
+ - 语气专业但亲切,像一位耐心的老师在讲解。
# 指导原则
- - 当提供了上一轮草稿时,**在其基础上扩展和完善** — 不要丢弃之前的内容。
- - 如果新证据改变了逻辑流程,可以重新组织章节。
+ - 当提供了上一轮草稿时,**在其基础上扩展和完善** — 不要丢弃之前的内容。同时润色已有文字,使整体行文更流畅。
+ - 如果新证据改变了逻辑流程,可以重新组织章节,但要确保过渡自然。
+ - 随着证据的积累,考虑是否需要添加或更新可视化元素(表格、Mermaid 图)来更好地呈现整体结构。
- 你的回答**只能**基于提供的证据和之前的草稿。不要编造信息。
- **绝对不要引用证据中不存在的图片或文件。** 如果不存在代码执行 artifact,不要嵌入任何图片。
- - 使用指定的语言撰写。
+ - 使用指定的语言撰写。Mermaid 图中的内容也应使用与正文一致的语言。
iterative_user_template: |
## 问题
diff --git a/deeptutor/agents/vision_solver/vision_solver_agent.py b/deeptutor/agents/vision_solver/vision_solver_agent.py
index fdd5be60c..7612dfd2f 100644
--- a/deeptutor/agents/vision_solver/vision_solver_agent.py
+++ b/deeptutor/agents/vision_solver/vision_solver_agent.py
@@ -163,14 +163,17 @@ class VisionSolverAgent(BaseAgent):
}
]
- response = await self.call_llm(
+ _chunks: list[str] = []
+ async for _c in self.stream_llm(
user_prompt="",
system_prompt="",
messages=messages,
temperature=temperature,
model=self.vision_model or self.get_model(),
verbose=False,
- )
+ ):
+ _chunks.append(_c)
+ response = "".join(_chunks)
return response
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index 7d539705e..fdc5b9b46 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -1,3 +1,4 @@
+import logging
from contextlib import asynccontextmanager
from pathlib import Path
@@ -21,6 +22,7 @@ from deeptutor.api.routers import (
settings,
solve,
system,
+ tutorbot,
unified_ws,
vision_solver,
)
@@ -30,6 +32,25 @@ from deeptutor.services.path_service import get_path_service
# Note: Don't set service_prefix here - start_web.py already adds [Backend] prefix
logger = get_logger("API")
+
+class _ProgressWsAccessFilter(logging.Filter):
+ """Suppress noisy uvicorn access logs for progress WebSocket endpoints.
+
+ These endpoints are polled every few seconds by the frontend for every KB,
+ generating hundreds of ``connection open`` / ``connection closed`` lines
+ that drown out useful output.
+ """
+
+ _SUPPRESSED_FRAGMENTS = ("progress/ws", "connection open", "connection closed")
+
+ def filter(self, record: logging.LogRecord) -> bool:
+ msg = record.getMessage()
+ return not any(f in msg for f in self._SUPPRESSED_FRAGMENTS)
+
+
+for _uv_name in ("uvicorn.access", "uvicorn.error"):
+ logging.getLogger(_uv_name).addFilter(_ProgressWsAccessFilter())
+
CONFIG_DRIFT_ERROR_TEMPLATE = (
"Configuration Drift Detected: Capability tool references {drift} are not "
"registered in the runtime tool registry. Register the missing tools or "
@@ -109,11 +130,25 @@ async def lifespan(app: FastAPI):
except Exception as e:
logger.warning(f"Failed to start EventBus: {e}")
+ try:
+ from deeptutor.services.tutorbot import get_tutorbot_manager
+ await get_tutorbot_manager().auto_start_bots()
+ except Exception as e:
+ logger.warning(f"Failed to auto-start TutorBots: {e}")
+
yield
# Execute on shutdown
logger.info("Application shutdown")
+ # Stop TutorBots
+ try:
+ from deeptutor.services.tutorbot import get_tutorbot_manager
+ await get_tutorbot_manager().stop_all()
+ logger.info("TutorBots stopped")
+ except Exception as e:
+ logger.warning(f"Failed to stop TutorBots: {e}")
+
# Stop EventBus
try:
from deeptutor.events.event_bus import get_event_bus
@@ -182,6 +217,7 @@ app.include_router(system.router, prefix="/api/v1/system", tags=["system"])
app.include_router(plugins_api.router, prefix="/api/v1/plugins", tags=["plugins"])
app.include_router(agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"])
app.include_router(vision_solver.router, prefix="/api/v1", tags=["vision-solver"])
+app.include_router(tutorbot.router, prefix="/api/v1/tutorbot", tags=["tutorbot"])
# Unified WebSocket endpoint
app.include_router(unified_ws.router, prefix="/api/v1", tags=["unified-ws"])
diff --git a/deeptutor/api/routers/co_writer.py b/deeptutor/api/routers/co_writer.py
index 1dc5545b3..6c3d2223b 100644
--- a/deeptutor/api/routers/co_writer.py
+++ b/deeptutor/api/routers/co_writer.py
@@ -271,13 +271,13 @@ async def _run_react_edit(
response_chunks: list[str] = []
if stream is None:
- response_chunks.append(
- await agent.call_llm(
- user_prompt=final_prompt,
- system_prompt=system_prompt,
- stage=f"react_edit_{request.mode}",
- )
- )
+ async for _c in agent.stream_llm(
+ user_prompt=final_prompt,
+ system_prompt=system_prompt,
+ stage=f"react_edit_{request.mode}",
+ ):
+ if _c:
+ response_chunks.append(_c)
else:
async with active_stream.stage("responding", source="co_writer_react_edit"):
await active_stream.progress(
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 6e6ae0863..d5818726d 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -235,6 +235,21 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
ProgressStage.COMPLETED, "Knowledge base initialization complete!", current=1, total=1
)
+ manager = get_kb_manager()
+ manager.update_kb_status(
+ name=initializer.kb_name,
+ status="ready",
+ progress={
+ "stage": "completed",
+ "message": "Knowledge base initialization complete!",
+ "percent": 100,
+ "current": 1,
+ "total": 1,
+ "task_id": task_id,
+ "timestamp": datetime.now().isoformat(),
+ },
+ )
+
_task_log(task_id, f"Knowledge base '{initializer.kb_name}' initialized", level="success")
task_manager.update_task_status(task_id, "completed")
task_stream_manager.emit_complete(
@@ -247,6 +262,20 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
task_manager.update_task_status(task_id, "error", error=error_msg)
+ manager = get_kb_manager()
+ manager.update_kb_status(
+ name=initializer.kb_name,
+ status="error",
+ progress={
+ "stage": "error",
+ "message": f"Initialization failed: {error_msg}",
+ "percent": 0,
+ "error": error_msg,
+ "task_id": task_id,
+ "timestamp": datetime.now().isoformat(),
+ },
+ )
+
if initializer.progress_tracker:
initializer.progress_tracker.update(
ProgressStage.ERROR, f"Initialization failed: {error_msg}", error=error_msg
@@ -788,11 +817,46 @@ async def websocket_progress(websocket: WebSocket, kb_name: str):
initial_progress = progress_tracker.get_progress()
expected_task_id = websocket.query_params.get("task_id")
- # Check if KB is already ready (has llamaindex storage)
kb_dir = _kb_base_dir / kb_name
llamaindex_storage_dir = kb_dir / "llamaindex_storage"
kb_is_ready = llamaindex_storage_dir.exists() and llamaindex_storage_dir.is_dir()
+ # Fast path: no active task — send current state and close immediately
+ # This prevents infinite polling loops for ready or legacy KBs.
+ has_active_task = False
+ if initial_progress:
+ stage = initial_progress.get("stage")
+ if stage not in ("completed", "error", None):
+ ts = initial_progress.get("timestamp")
+ if ts:
+ try:
+ age = (datetime.now() - datetime.fromisoformat(ts)).total_seconds()
+ has_active_task = age < 120
+ except Exception:
+ pass
+
+ if not has_active_task and not expected_task_id:
+ if kb_is_ready:
+ await websocket.send_json({
+ "type": "progress",
+ "data": {
+ "stage": "completed",
+ "message": "Knowledge base is ready.",
+ "percent": 100,
+ "current": 1,
+ "total": 1,
+ },
+ })
+ else:
+ await websocket.send_json({
+ "type": "progress",
+ "data": initial_progress or {
+ "stage": "error",
+ "message": "Knowledge base needs reindex or initialization.",
+ },
+ })
+ return
+
if initial_progress:
stage = initial_progress.get("stage")
timestamp = initial_progress.get("timestamp")
@@ -810,7 +874,7 @@ async def websocket_progress(websocket: WebSocket, kb_name: str):
age_seconds = (now - progress_time).total_seconds()
if age_seconds < 300:
should_send = True
- except:
+ except Exception:
pass
if should_send:
@@ -851,13 +915,13 @@ async def websocket_progress(websocket: WebSocket, kb_name: str):
logger.debug(f"Progress WS error: {e}")
try:
await websocket.send_json({"type": "error", "message": str(e)})
- except:
+ except Exception:
pass
finally:
await broadcaster.disconnect(kb_name, websocket)
try:
await websocket.close()
- except:
+ except Exception:
pass
diff --git a/deeptutor/api/routers/memory.py b/deeptutor/api/routers/memory.py
index 52a17e8e4..9d645801f 100644
--- a/deeptutor/api/routers/memory.py
+++ b/deeptutor/api/routers/memory.py
@@ -1,5 +1,5 @@
"""
-Lightweight memory API router.
+Two-file public memory API: SUMMARY and PROFILE.
"""
from __future__ import annotations
@@ -7,40 +7,48 @@ from __future__ import annotations
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
-from deeptutor.services.memory import get_memory_service
+from deeptutor.services.memory import MemoryFile, get_memory_service
from deeptutor.services.session import get_sqlite_session_store
router = APIRouter()
+_VALID_FILES: set[MemoryFile] = {"summary", "profile"}
+
+
+def _snap_dict(snap) -> dict:
+ return {
+ "summary": snap.summary,
+ "profile": snap.profile,
+ "summary_updated_at": snap.summary_updated_at,
+ "profile_updated_at": snap.profile_updated_at,
+ }
+
+
+class FileUpdateRequest(BaseModel):
+ file: MemoryFile
+ content: str = ""
+
class MemoryRefreshRequest(BaseModel):
session_id: str | None = None
language: str = "en"
-class MemoryUpdateRequest(BaseModel):
- content: str = ""
+class MemoryClearRequest(BaseModel):
+ file: MemoryFile | None = None
@router.get("")
async def get_memory():
- snapshot = get_memory_service().read_snapshot()
- return {
- "content": snapshot.content,
- "exists": snapshot.exists,
- "updated_at": snapshot.updated_at,
- }
+ return _snap_dict(get_memory_service().read_snapshot())
@router.put("")
-async def update_memory(payload: MemoryUpdateRequest):
- snapshot = get_memory_service().write_memory(payload.content)
- return {
- "content": snapshot.content,
- "exists": snapshot.exists,
- "updated_at": snapshot.updated_at,
- "saved": True,
- }
+async def update_memory(payload: FileUpdateRequest):
+ if payload.file not in _VALID_FILES:
+ raise HTTPException(status_code=400, detail=f"Invalid file: {payload.file}")
+ snap = get_memory_service().write_file(payload.file, payload.content)
+ return {**_snap_dict(snap), "saved": True}
@router.post("/refresh")
@@ -56,20 +64,19 @@ async def refresh_memory(payload: MemoryRefreshRequest):
session_id or None,
language=payload.language,
)
- return {
- "content": result.content,
- "exists": bool(result.content.strip()),
- "updated_at": result.updated_at,
- "changed": result.changed,
- }
+ snap = get_memory_service().read_snapshot()
+ return {**_snap_dict(snap), "changed": result.changed}
@router.post("/clear")
-async def clear_memory():
- snapshot = get_memory_service().clear_memory()
- return {
- "content": snapshot.content,
- "exists": snapshot.exists,
- "updated_at": snapshot.updated_at,
- "cleared": True,
- }
+async def clear_memory(payload: MemoryClearRequest | None = None):
+ svc = get_memory_service()
+ target = payload.file if payload else None
+ if target and target not in _VALID_FILES:
+ raise HTTPException(status_code=400, detail=f"Invalid file: {target}")
+
+ if target:
+ snap = svc.clear_file(target)
+ else:
+ snap = svc.clear_memory()
+ return {**_snap_dict(snap), "cleared": True}
diff --git a/deeptutor/api/routers/tutorbot.py b/deeptutor/api/routers/tutorbot.py
new file mode 100644
index 000000000..c4d65f303
--- /dev/null
+++ b/deeptutor/api/routers/tutorbot.py
@@ -0,0 +1,269 @@
+"""
+TutorBot management API.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+
+from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
+from pydantic import BaseModel
+
+from deeptutor.services.tutorbot import get_tutorbot_manager
+from deeptutor.services.tutorbot.manager import BotConfig
+
+logger = logging.getLogger(__name__)
+router = APIRouter()
+
+
+class CreateBotRequest(BaseModel):
+ bot_id: str
+ name: str | None = None
+ description: str = ""
+ persona: str = ""
+ channels: dict = {}
+ model: str | None = None
+
+
+class UpdateBotRequest(BaseModel):
+ name: str | None = None
+ description: str | None = None
+ persona: str | None = None
+ channels: dict | None = None
+ model: str | None = None
+
+
+class FileUpdateRequest(BaseModel):
+ content: str
+
+
+class SoulCreateRequest(BaseModel):
+ id: str
+ name: str
+ content: str
+
+
+class SoulUpdateRequest(BaseModel):
+ name: str | None = None
+ content: str | None = None
+
+
+# ── Soul template library (must be before /{bot_id} routes) ───
+
+async def list_souls():
+ return get_tutorbot_manager().list_souls()
+
+
+async def create_soul(payload: SoulCreateRequest):
+ mgr = get_tutorbot_manager()
+ if mgr.get_soul(payload.id):
+ raise HTTPException(status_code=409, detail=f"Soul '{payload.id}' already exists")
+ return mgr.create_soul(payload.id, payload.name, payload.content)
+
+
[email protected]("/souls/{soul_id}")
+async def get_soul(soul_id: str):
+ soul = get_tutorbot_manager().get_soul(soul_id)
+ if not soul:
+ raise HTTPException(status_code=404, detail="Soul not found")
+ return soul
+
+
[email protected]("/souls/{soul_id}")
+async def update_soul(soul_id: str, payload: SoulUpdateRequest):
+ result = get_tutorbot_manager().update_soul(soul_id, payload.name, payload.content)
+ if not result:
+ raise HTTPException(status_code=404, detail="Soul not found")
+ return result
+
+
[email protected]("/souls/{soul_id}")
+async def delete_soul(soul_id: str):
+ if not get_tutorbot_manager().delete_soul(soul_id):
+ raise HTTPException(status_code=404, detail="Soul not found")
+ return {"id": soul_id, "deleted": True}
+
+
+# ── Bot management (static paths before /{bot_id} parameterized routes) ──
+
+async def list_bots():
+ return get_tutorbot_manager().list_bots()
+
+
+async def recent_bots(limit: int = 3):
+ """Return the most recently active bots with their last message preview."""
+ return get_tutorbot_manager().get_recent_active_bots(limit=limit)
+
+
+async def create_and_start_bot(payload: CreateBotRequest):
+ mgr = get_tutorbot_manager()
+ config = BotConfig(
+ name=payload.name or payload.bot_id,
+ description=payload.description,
+ persona=payload.persona,
+ channels=payload.channels,
+ model=payload.model,
+ )
+ try:
+ instance = await mgr.start_bot(payload.bot_id, config)
+ except RuntimeError as e:
+ raise HTTPException(status_code=500, detail=str(e))
+ return instance.to_dict()
+
+
[email protected]("/{bot_id}")
+async def get_bot(bot_id: str):
+ mgr = get_tutorbot_manager()
+ instance = mgr.get_bot(bot_id)
+ if instance:
+ return instance.to_dict()
+ cfg = mgr._load_bot_config(bot_id)
+ if cfg:
+ return {
+ "bot_id": bot_id, "name": cfg.name, "description": cfg.description,
+ "persona": cfg.persona, "channels": list(cfg.channels.keys()),
+ "model": cfg.model, "running": False, "started_at": None,
+ }
+ raise HTTPException(status_code=404, detail="Bot not found")
+
+
[email protected]("/{bot_id}")
+async def stop_bot(bot_id: str):
+ stopped = await get_tutorbot_manager().stop_bot(bot_id)
+ if not stopped:
+ raise HTTPException(status_code=404, detail="Bot not found or not running")
+ return {"bot_id": bot_id, "stopped": True}
+
+
[email protected]("/{bot_id}/destroy")
+async def destroy_bot(bot_id: str):
+ destroyed = await get_tutorbot_manager().destroy_bot(bot_id)
+ if not destroyed:
+ raise HTTPException(status_code=404, detail="Bot not found")
+ return {"bot_id": bot_id, "destroyed": True}
+
+
[email protected]("/{bot_id}")
+async def update_bot(bot_id: str, payload: UpdateBotRequest):
+ mgr = get_tutorbot_manager()
+ instance = mgr.get_bot(bot_id)
+ if not instance:
+ raise HTTPException(status_code=404, detail="Bot not found")
+
+ if payload.name is not None:
+ instance.config.name = payload.name
+ if payload.description is not None:
+ instance.config.description = payload.description
+ if payload.persona is not None:
+ instance.config.persona = payload.persona
+ if payload.channels is not None:
+ instance.config.channels = payload.channels
+ if payload.model is not None:
+ instance.config.model = payload.model
+
+ mgr._save_bot_config(bot_id, instance.config)
+ return instance.to_dict()
+
+
+# ── Workspace file endpoints ──────────────────────────────────
+
[email protected]("/{bot_id}/files")
+async def list_bot_files(bot_id: str):
+ return get_tutorbot_manager().read_all_bot_files(bot_id)
+
+
[email protected]("/{bot_id}/files/{filename}")
+async def read_bot_file(bot_id: str, filename: str):
+ content = get_tutorbot_manager().read_bot_file(bot_id, filename)
+ if content is None:
+ raise HTTPException(status_code=400, detail=f"Not an editable file: {filename}")
+ return {"filename": filename, "content": content}
+
+
[email protected]("/{bot_id}/files/{filename}")
+async def write_bot_file(bot_id: str, filename: str, payload: FileUpdateRequest):
+ ok = get_tutorbot_manager().write_bot_file(bot_id, filename, payload.content)
+ if not ok:
+ raise HTTPException(status_code=400, detail=f"Not an editable file: {filename}")
+ return {"filename": filename, "saved": True}
+
+
+# ── Chat history & WebSocket ──────────────────────────────────
+
[email protected]("/{bot_id}/history")
+async def get_bot_history(bot_id: str, limit: int = 100):
+ """Read chat history from the bot's per-bot JSONL session files."""
+ return get_tutorbot_manager().get_bot_history(bot_id, limit=limit)
+
+
[email protected]("/{bot_id}/ws")
+async def bot_chat_ws(ws: WebSocket, bot_id: str):
+ import asyncio
+
+ mgr = get_tutorbot_manager()
+ instance = mgr.get_bot(bot_id)
+ if not instance or not instance.running:
+ await ws.close(code=4004, reason="Bot not found or not running")
+ return
+
+ await ws.accept()
+ logger.info("WebSocket connected for bot '%s'", bot_id)
+
+ async def _handle_user_messages():
+ while True:
+ raw = await ws.receive_text()
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ await ws.send_json({"type": "error", "content": "Invalid JSON"})
+ continue
+
+ content = data.get("content", "").strip()
+ if not content:
+ continue
+
+ async def on_progress(text: str) -> None:
+ await ws.send_json({"type": "thinking", "content": text})
+
+ try:
+ response = await mgr.send_message(
+ bot_id, content, chat_id=data.get("chat_id", "web"),
+ on_progress=on_progress,
+ )
+ await ws.send_json({"type": "content", "content": response})
+ await ws.send_json({"type": "done"})
+ except RuntimeError as exc:
+ await ws.send_json({"type": "error", "content": str(exc)})
+ except Exception:
+ logger.exception("Error processing message for bot '%s'", bot_id)
+ await ws.send_json({"type": "error", "content": "Internal error"})
+
+ async def _handle_notifications():
+ while True:
+ content = await instance.notify_queue.get()
+ try:
+ await ws.send_json({"type": "proactive", "content": content})
+ except Exception:
+ break
+
+ user_task = asyncio.create_task(_handle_user_messages())
+ notify_task = asyncio.create_task(_handle_notifications())
+ try:
+ done, pending = await asyncio.wait(
+ [user_task, notify_task], return_when=asyncio.FIRST_COMPLETED,
+ )
+ for t in pending:
+ t.cancel()
+ for t in done:
+ if t.exception() and not isinstance(t.exception(), WebSocketDisconnect):
+ logger.exception("WebSocket task error for bot '%s'", bot_id, exc_info=t.exception())
+ except Exception:
+ user_task.cancel()
+ notify_task.cancel()
+ logger.info("WebSocket closed for bot '%s'", bot_id)
diff --git a/deeptutor/api/utils/task_log_stream.py b/deeptutor/api/utils/task_log_stream.py
index e41932060..59f765522 100644
--- a/deeptutor/api/utils/task_log_stream.py
+++ b/deeptutor/api/utils/task_log_stream.py
@@ -1,6 +1,7 @@
import asyncio
import contextlib
import json
+import logging
import threading
from collections import deque
from collections.abc import AsyncGenerator
@@ -11,6 +12,29 @@ def _format_sse(event: str, payload: dict[str, Any]) -> str:
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
+_PIPELINE_LOGGER_NAMES = [
+ "deeptutor.LlamaIndexPipeline",
+ "deeptutor.CustomEmbedding",
+ "deeptutor.EmbeddingClient",
+ "deeptutor.KnowledgeInit",
+]
+
+
+class _TaskStreamHandler(logging.Handler):
+ """Forwards log records from pipeline loggers into a task's SSE stream."""
+
+ def __init__(self, task_id: str, manager: "KnowledgeTaskStreamManager"):
+ super().__init__(level=logging.INFO)
+ self._task_id = task_id
+ self._manager = manager
+
+ def emit(self, record: logging.LogRecord) -> None:
+ try:
+ self._manager.emit_log(self._task_id, record.getMessage())
+ except Exception:
+ pass
+
+
class KnowledgeTaskStreamManager:
_instance: "KnowledgeTaskStreamManager | None" = None
_instance_lock = threading.Lock()
@@ -101,16 +125,29 @@ class KnowledgeTaskStreamManager:
@contextlib.contextmanager
def capture_task_logs(task_id: str):
- """Compatibility context manager.
+ """Capture logs from pipeline loggers and forward them to the task's SSE stream.
- We intentionally avoid capturing global stdout/stderr or root loggers here
- to prevent unrelated concurrent request logs from leaking into a task's SSE
- stream. Task producers should emit task logs explicitly through
- ``KnowledgeTaskStreamManager.emit_log``.
+ Only loggers in ``_PIPELINE_LOGGER_NAMES`` are tapped so that unrelated
+ concurrent request logs do not leak into the stream. The handler is also
+ safe to call from ``run_in_executor`` threads because Python logging
+ handlers are global and ``emit_log`` uses ``call_soon_threadsafe``.
"""
manager = KnowledgeTaskStreamManager.get_instance()
manager.ensure_task(task_id)
- yield
+
+ handler = _TaskStreamHandler(task_id, manager)
+ attached: list[logging.Logger] = []
+
+ for name in _PIPELINE_LOGGER_NAMES:
+ lg = logging.getLogger(name)
+ lg.addHandler(handler)
+ attached.append(lg)
+
+ try:
+ yield
+ finally:
+ for lg in attached:
+ lg.removeHandler(handler)
def get_task_stream_manager() -> KnowledgeTaskStreamManager:
diff --git a/deeptutor/capabilities/deep_question.py b/deeptutor/capabilities/deep_question.py
index db1afcc8d..0fd5ea03f 100644
--- a/deeptutor/capabilities/deep_question.py
+++ b/deeptutor/capabilities/deep_question.py
@@ -66,14 +66,15 @@ class DeepQuestionCapability(BaseCapability):
)
if answer:
await stream.content(answer, source=self.name, stage="generation")
- await stream.result(
- {
- "response": answer or "",
- "mode": "followup",
- "question_id": followup_question_context.get("question_id", ""),
- },
- source=self.name,
- )
+ followup_payload: dict[str, Any] = {
+ "response": answer or "",
+ "mode": "followup",
+ "question_id": followup_question_context.get("question_id", ""),
+ }
+ cost_meta = self._collect_cost_summary("question")
+ if cost_meta:
+ followup_payload["metadata"] = {"cost_summary": cost_meta}
+ await stream.result(followup_payload, source=self.name)
return
mode = str(overrides.get("mode", "custom") or "custom").strip().lower()
@@ -177,14 +178,29 @@ class DeepQuestionCapability(BaseCapability):
if content:
await stream.content(content, source=self.name, stage="generation")
- await stream.result(
- {
- "response": content or "No questions generated.",
- "summary": result,
- "mode": mode,
- },
- source=self.name,
- )
+ result_payload: dict[str, Any] = {
+ "response": content or "No questions generated.",
+ "summary": result,
+ "mode": mode,
+ }
+ cost_meta = self._collect_cost_summary("question")
+ if cost_meta:
+ result_payload["metadata"] = {"cost_summary": cost_meta}
+ await stream.result(result_payload, source=self.name)
+
+ @staticmethod
+ def _collect_cost_summary(module_name: str) -> dict[str, Any] | None:
+ from deeptutor.agents.base_agent import BaseAgent
+ stats = BaseAgent._shared_stats.get(module_name)
+ if not stats or not stats.calls:
+ return None
+ s = stats.get_summary()
+ stats.reset()
+ return {
+ "total_cost_usd": s.get("cost_usd", 0),
+ "total_tokens": s.get("total_tokens", 0),
+ "total_calls": s.get("calls", 0),
+ }
async def _run_mimic_mode(
self,
@@ -382,17 +398,19 @@ class DeepQuestionCapability(BaseCapability):
)
return
if state == "complete":
- response = str(update.get("response", "") or "")
- if response:
- await stream.thinking(
- response,
- source=self.name,
- stage=stage,
- metadata=merge_trace_metadata(
- base_metadata,
- {"trace_kind": "llm_output"},
- ),
- )
+ was_streaming = update.get("streaming", False)
+ if not was_streaming:
+ response = str(update.get("response", "") or "")
+ if response:
+ await stream.thinking(
+ response,
+ source=self.name,
+ stage=stage,
+ metadata=merge_trace_metadata(
+ base_metadata,
+ {"trace_kind": "llm_output"},
+ ),
+ )
await stream.progress(
message="",
source=self.name,
diff --git a/deeptutor/capabilities/deep_research.py b/deeptutor/capabilities/deep_research.py
index c22e7e334..e5a40e6fc 100644
--- a/deeptutor/capabilities/deep_research.py
+++ b/deeptutor/capabilities/deep_research.py
@@ -199,17 +199,19 @@ class DeepResearchCapability(BaseCapability):
)
return
if state == "complete":
- response = str(update.get("response", "") or "")
- if response:
- await stream.thinking(
- response,
- source=self.name,
- stage=stage,
- metadata=merge_trace_metadata(
- base_metadata,
- {"trace_kind": "llm_output"},
- ),
- )
+ was_streaming = update.get("streaming", False)
+ if not was_streaming:
+ response = str(update.get("response", "") or "")
+ if response:
+ await stream.thinking(
+ response,
+ source=self.name,
+ stage=stage,
+ metadata=merge_trace_metadata(
+ base_metadata,
+ {"trace_kind": "llm_output"},
+ ),
+ )
await stream.progress(
message=label,
source=self.name,
@@ -274,6 +276,51 @@ class DeepResearchCapability(BaseCapability):
)
return
+ confirmed_outline = request_config.confirmed_outline
+ conversation_history = context.conversation_history or []
+
+ if confirmed_outline is None:
+ outline_items = await self._generate_outline_preview(
+ config=config,
+ llm_config=llm_config,
+ kb_name=kb_name,
+ topic=topic,
+ stream=stream,
+ progress_callback=_progress_cb,
+ trace_callback=_trace_cb,
+ conversation_history=conversation_history,
+ )
+ sub_topics_data = (
+ [item.model_dump() for item in outline_items]
+ if hasattr(outline_items[0], "model_dump")
+ else outline_items
+ )
+
+ outline_md = self._outline_to_markdown(topic, sub_topics_data)
+ await stream.content(outline_md, source=self.name, stage="decomposing")
+
+ await stream.result(
+ {
+ "outline_preview": True,
+ "sub_topics": sub_topics_data,
+ "topic": topic,
+ "research_config": {
+ "mode": request_config.mode,
+ "depth": request_config.depth,
+ "sources": list(request_config.sources),
+ **({"manual_subtopics": request_config.manual_subtopics} if request_config.manual_subtopics is not None else {}),
+ **({"manual_max_iterations": request_config.manual_max_iterations} if request_config.manual_max_iterations is not None else {}),
+ },
+ },
+ source=self.name,
+ )
+ return
+
+ pre_outline = [
+ {"title": item.title, "overview": item.overview}
+ for item in confirmed_outline
+ ]
+
pipeline = ResearchPipeline(
config=config,
api_key=llm_config.api_key,
@@ -282,6 +329,7 @@ class DeepResearchCapability(BaseCapability):
kb_name=kb_name,
progress_callback=_progress_cb,
trace_callback=_trace_cb,
+ pre_confirmed_outline=pre_outline,
)
async with stream.stage("researching", source=self.name):
@@ -297,3 +345,58 @@ class DeepResearchCapability(BaseCapability):
{"response": report, "metadata": result.get("metadata", {})},
source=self.name,
)
+
+ @staticmethod
+ def _outline_to_markdown(
+ topic: str, sub_topics: list[dict[str, str]]
+ ) -> str:
+ """Serialize an outline to Markdown so it is persisted in session history."""
+ lines = [f"**Research Outline — {topic}**\n"]
+ for i, item in enumerate(sub_topics, 1):
+ lines.append(f"{i}. **{item.get('title', '')}**")
+ overview = item.get("overview", "")
+ if overview:
+ lines.append(f" {overview}")
+ return "\n".join(lines)
+
+ async def _generate_outline_preview(
+ self,
+ *,
+ config: dict[str, Any],
+ llm_config: Any,
+ kb_name: str | None,
+ topic: str,
+ stream: StreamBus,
+ progress_callback: Any,
+ trace_callback: Any,
+ conversation_history: list[dict[str, Any]] | None = None,
+ ) -> list[dict[str, str]]:
+ """Run only the planning phase (rephrase + decompose) and return sub-topics."""
+ from deeptutor.agents.research.research_pipeline import ResearchPipeline
+
+ if conversation_history:
+ config = {**config, "conversation_history": conversation_history}
+
+ pipeline = ResearchPipeline(
+ config=config,
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ api_version=llm_config.api_version,
+ kb_name=kb_name,
+ progress_callback=progress_callback,
+ trace_callback=trace_callback,
+ )
+
+ async with stream.stage("decomposing", source=self.name):
+ await stream.thinking(
+ f"Generating research outline for: {topic}",
+ source=self.name,
+ stage="decomposing",
+ )
+ optimized_topic = await pipeline._phase1_planning(topic)
+
+ sub_topics = []
+ for block in pipeline.queue.blocks:
+ sub_topics.append({"title": block.sub_topic, "overview": block.overview})
+
+ return sub_topics
diff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.py
index aa16a259e..a70583ecc 100644
--- a/deeptutor/capabilities/deep_solve.py
+++ b/deeptutor/capabilities/deep_solve.py
@@ -107,17 +107,19 @@ class DeepSolveCapability(BaseCapability):
)
return
if state == "complete":
- response = str(update.get("response", "") or "")
- if response:
- await stream.thinking(
- response,
- source=self.name,
- stage=stage,
- metadata=merge_trace_metadata(
- base_metadata,
- {"trace_kind": "llm_output"},
- ),
- )
+ was_streaming = update.get("streaming", False)
+ if not was_streaming:
+ response = str(update.get("response", "") or "")
+ if response:
+ await stream.thinking(
+ response,
+ source=self.name,
+ stage=stage,
+ metadata=merge_trace_metadata(
+ base_metadata,
+ {"trace_kind": "llm_output"},
+ ),
+ )
await stream.progress(
message="",
source=self.name,
@@ -226,6 +228,20 @@ class DeepSolveCapability(BaseCapability):
if hasattr(solver, "set_trace_callback"):
solver.set_trace_callback(_trace_bridge)
+ # Content callback — streams writer tokens to the main chat area
+ content_streamed = False
+
+ async def _content_sink(chunk: str) -> None:
+ nonlocal content_streamed
+ content_streamed = True
+ await stream.content(
+ chunk,
+ source=self.name,
+ stage="writing",
+ )
+
+ solver._content_callback = _content_sink
+
result = await solver.solve(
question=context.user_message,
verbose=False,
@@ -236,7 +252,8 @@ class DeepSolveCapability(BaseCapability):
)
final_answer = result.get("final_answer", "")
- if final_answer:
+
+ if final_answer and not content_streamed:
async with stream.stage("writing", source=self.name):
await stream.content(final_answer, source=self.name, stage="writing")
diff --git a/deeptutor/capabilities/math_animator.py b/deeptutor/capabilities/math_animator.py
index d5687b059..c8ce7981a 100644
--- a/deeptutor/capabilities/math_animator.py
+++ b/deeptutor/capabilities/math_animator.py
@@ -242,17 +242,19 @@ class MathAnimatorCapability(BaseCapability):
)
return
if state == "complete":
- response = str(update.get("response", "") or "")
- if response:
- await stream.thinking(
- response,
- source=self.name,
- stage=stage,
- metadata=merge_trace_metadata(
- base_metadata,
- {"trace_kind": "llm_output"},
- ),
- )
+ was_streaming = update.get("streaming", False)
+ if not was_streaming:
+ response = str(update.get("response", "") or "")
+ if response:
+ await stream.thinking(
+ response,
+ source=self.name,
+ stage=stage,
+ metadata=merge_trace_metadata(
+ base_metadata,
+ {"trace_kind": "llm_output"},
+ ),
+ )
await stream.progress(
message=label,
source=self.name,
diff --git a/deeptutor/config/constants.py b/deeptutor/config/constants.py
index 461228530..9ef83d7c7 100644
--- a/deeptutor/config/constants.py
+++ b/deeptutor/config/constants.py
@@ -9,14 +9,13 @@ from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
# Valid tools for investigate agent
-VALID_INVESTIGATE_TOOLS = ["rag_naive", "rag_hybrid", "web_search", "none"]
+VALID_INVESTIGATE_TOOLS = ["rag", "web_search", "none"]
# Valid tools for solve agent
VALID_SOLVE_TOOLS = [
"web_search",
"code_execution",
- "rag_naive",
- "rag_hybrid",
+ "rag",
"none",
"finish",
]
diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.py
index 636230655..1f8599170 100644
--- a/deeptutor/knowledge/add_documents.py
+++ b/deeptutor/knowledge/add_documents.py
@@ -44,8 +44,6 @@ class DocumentAdder:
raise ValueError(f"Knowledge base does not exist: {kb_name}")
self.raw_dir = self.kb_dir / "raw"
- self.images_dir = self.kb_dir / "images"
- self.content_list_dir = self.kb_dir / "content_list"
self.llamaindex_storage_dir = self.kb_dir / "llamaindex_storage"
self.legacy_rag_storage_dir = self.kb_dir / "rag_storage"
self.metadata_file = self.kb_dir / "metadata.json"
@@ -68,8 +66,6 @@ class DocumentAdder:
self.progress_tracker = progress_tracker
self.raw_dir.mkdir(parents=True, exist_ok=True)
- self.images_dir.mkdir(parents=True, exist_ok=True)
- self.content_list_dir.mkdir(parents=True, exist_ok=True)
def _get_file_hash(self, file_path: Path) -> str:
sha256_hash = hashlib.sha256()
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.py
index 187cdcfb7..79f3a008a 100644
--- a/deeptutor/knowledge/initializer.py
+++ b/deeptutor/knowledge/initializer.py
@@ -39,8 +39,6 @@ class KnowledgeBaseInitializer:
self.kb_dir = self.base_dir / kb_name
self.raw_dir = self.kb_dir / "raw"
- self.images_dir = self.kb_dir / "images"
- self.content_list_dir = self.kb_dir / "content_list"
self.llamaindex_storage_dir = self.kb_dir / "llamaindex_storage"
self.api_key = api_key
@@ -108,8 +106,6 @@ class KnowledgeBaseInitializer:
for dir_path in [
self.raw_dir,
- self.images_dir,
- self.content_list_dir,
self.llamaindex_storage_dir,
]:
dir_path.mkdir(parents=True, exist_ok=True)
@@ -223,15 +219,11 @@ class KnowledgeBaseInitializer:
async def display_statistics_generic(self) -> None:
"""Display basic statistics."""
raw_files = list(self.raw_dir.glob("*")) if self.raw_dir.exists() else []
- image_files = list(self.images_dir.glob("*")) if self.images_dir.exists() else []
- content_files = list(self.content_list_dir.glob("*.json")) if self.content_list_dir.exists() else []
logger.info("=" * 50)
logger.info("Knowledge Base Statistics")
logger.info("=" * 50)
logger.info(f"Raw documents: {len(raw_files)}")
- logger.info(f"Extracted images: {len(image_files)}")
- logger.info(f"Content lists: {len(content_files)}")
logger.info(f"LlamaIndex storage exists: {self.llamaindex_storage_dir.exists()}")
logger.info(f"Provider used: {DEFAULT_PROVIDER}")
logger.info("=" * 50)
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index 3654b7532..bca6ea132 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -286,7 +286,7 @@ def resolve_llm_runtime_config(
env_store: EnvStore | None = None,
service: ModelCatalogService | None = None,
) -> ResolvedLLMConfig:
- """Resolve active LLM config with nanobot-style provider matching."""
+ """Resolve active LLM config with TutorBot-style provider matching."""
env = env_store or get_env_store()
catalog_service = service or get_model_catalog_service()
loaded = _load_catalog(catalog)
@@ -553,7 +553,7 @@ def resolve_search_runtime_config(
env_store: EnvStore | None = None,
service: ModelCatalogService | None = None,
) -> ResolvedSearchConfig:
- """Resolve active web-search config with nanobot-style fallback behavior."""
+ """Resolve active web-search config with TutorBot-style fallback behavior."""
env = env_store or get_env_store()
catalog_service = service or get_model_catalog_service()
loaded = _load_catalog(catalog)
diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.py
index ca8e26ce0..389fb6a50 100644
--- a/deeptutor/services/llm/config.py
+++ b/deeptutor/services/llm/config.py
@@ -183,7 +183,7 @@ def _get_llm_config_from_env() -> LLMConfig:
def _get_llm_config_from_resolver() -> LLMConfig:
- """Resolve LLM config from the nanobot-style runtime adapter."""
+ """Resolve LLM config from the TutorBot-style runtime adapter."""
resolved = resolve_llm_runtime_config()
if not resolved.model:
raise LLMConfigError(
diff --git a/deeptutor/services/llm/executors.py b/deeptutor/services/llm/executors.py
index 0b3ae45a7..4add109be 100644
--- a/deeptutor/services/llm/executors.py
+++ b/deeptutor/services/llm/executors.py
@@ -157,6 +157,11 @@ async def litellm_stream(
delta = choice.get("delta")
if delta is None:
continue
+ # Skip stop-chunks where content is explicitly None (avoids
+ # extract_response_content converting the delta repr to string).
+ raw_content = getattr(delta, "content", None) if not isinstance(delta, dict) else delta.get("content")
+ if raw_content is None:
+ continue
content = extract_response_content(delta)
if content:
yield content
diff --git a/deeptutor/services/llm/utils.py b/deeptutor/services/llm/utils.py
index 4b8aa5789..581353c0a 100644
--- a/deeptutor/services/llm/utils.py
+++ b/deeptutor/services/llm/utils.py
@@ -215,7 +215,14 @@ def _extract_content_field(content: object) -> str:
def extract_response_content(message: object) -> str:
- """Extract textual content from response payloads."""
+ """Extract textual content from response payloads.
+
+ Returns empty string when the message carries no meaningful text
+ (e.g. a streaming delta with ``content=None``). Never falls back
+ to ``str(message)`` for complex objects — that would inject garbage
+ like ``"{'provider_specific_fields': None, ...}"`` into the response
+ stream and corrupt downstream JSON parsing.
+ """
if message is None:
return ""
@@ -228,6 +235,7 @@ def extract_response_content(message: object) -> str:
return content
if "text" in message and message["text"] is not None:
return str(message["text"])
+ return ""
# LiteLLM/OpenAI SDK response models often expose attributes instead of dict keys.
if hasattr(message, "content"):
@@ -247,7 +255,11 @@ def extract_response_content(message: object) -> str:
if dumped is not None and dumped is not message:
return extract_response_content(dumped)
- return str(message)
+ # Only stringify simple/primitive values; complex SDK objects with no
+ # extractable content should yield empty string, not their repr.
+ if isinstance(message, (int, float, bool)):
+ return str(message)
+ return ""
def _normalize_model_name(entry: object) -> str | None:
diff --git a/deeptutor/services/memory/__init__.py b/deeptutor/services/memory/__init__.py
index f1e6437e9..1efea6dc0 100644
--- a/deeptutor/services/memory/__init__.py
+++ b/deeptutor/services/memory/__init__.py
@@ -1,4 +1,5 @@
from .service import (
+ MemoryFile,
MemoryService,
MemorySnapshot,
MemoryUpdateResult,
@@ -6,6 +7,7 @@ from .service import (
)
__all__ = [
+ "MemoryFile",
"MemoryService",
"MemorySnapshot",
"MemoryUpdateResult",
diff --git a/deeptutor/services/memory/service.py b/deeptutor/services/memory/service.py
index b86b3e229..db133c999 100644
--- a/deeptutor/services/memory/service.py
+++ b/deeptutor/services/memory/service.py
@@ -1,24 +1,42 @@
+"""
+Two-file public memory system: SUMMARY.md and PROFILE.md.
+
+- SUMMARY: Running summary of the user's learning journey (auto-updated).
+- PROFILE: User identity, preferences, knowledge levels (auto-updated).
+
+Per-bot files (SOUL.md, TOOLS.md, USER.md, etc.) live in each bot's
+workspace directory, not in the shared memory dir.
+"""
+
from __future__ import annotations
+import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
-import re
-from typing import Any
+from typing import Literal
-from deeptutor.services.llm import complete as llm_complete
+from deeptutor.services.llm import stream as llm_stream
from deeptutor.services.path_service import PathService, get_path_service
from deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store
+MemoryFile = Literal["summary", "profile"]
+MEMORY_FILES: list[MemoryFile] = ["summary", "profile"]
+
+_NO_CHANGE = "NO_CHANGE"
-_NO_CHANGE_SENTINEL = "NO_CHANGE"
+_FILENAMES: dict[MemoryFile, str] = {
+ "summary": "SUMMARY.md",
+ "profile": "PROFILE.md",
+}
@dataclass
class MemorySnapshot:
- content: str
- exists: bool
- updated_at: str | None
+ summary: str
+ profile: str
+ summary_updated_at: str | None
+ profile_updated_at: str | None
@dataclass
@@ -29,7 +47,7 @@ class MemoryUpdateResult:
class MemoryService:
- """Lightweight Nanobot-style long-term memory for preferences and context."""
+ """Two-file public memory: SUMMARY + PROFILE."""
def __init__(
self,
@@ -38,13 +56,44 @@ class MemoryService:
) -> None:
self._path_service = path_service or get_path_service()
self._store = store or get_sqlite_session_store()
+ self._migrate_legacy()
@property
- def memory_path(self) -> Path:
- return self._path_service.get_memory_dir() / "memory.md"
+ def _memory_dir(self) -> Path:
+ return self._path_service.get_memory_dir()
+
+ def _path(self, which: MemoryFile) -> Path:
+ return self._memory_dir / _FILENAMES[which]
- def read_memory(self) -> str:
- path = self.memory_path
+ def _migrate_legacy(self) -> None:
+ """One-time migration from old memory.md to the two-file system."""
+ legacy = self._memory_dir / "memory.md"
+ if not legacy.exists():
+ return
+ if self._path("profile").exists() or self._path("summary").exists():
+ return
+
+ content = legacy.read_text(encoding="utf-8").strip()
+ if not content:
+ legacy.rename(legacy.with_suffix(".md.bak"))
+ return
+
+ preferences, context = self._extract_legacy_sections(content)
+ self._memory_dir.mkdir(parents=True, exist_ok=True)
+ if preferences:
+ self._path("profile").write_text(
+ f"## Preferences\n{preferences}", encoding="utf-8",
+ )
+ if context:
+ self._path("summary").write_text(
+ f"## Learning Journey\n{context}", encoding="utf-8",
+ )
+ legacy.rename(legacy.with_suffix(".md.bak"))
+
+ # ── Read ──────────────────────────────────────────────────────────
+
+ def read_file(self, which: MemoryFile) -> str:
+ path = self._path(which)
if not path.exists():
return ""
try:
@@ -52,54 +101,87 @@ class MemoryService:
except Exception:
return ""
+ def read_summary(self) -> str:
+ return self.read_file("summary")
+
+ def read_profile(self) -> str:
+ return self.read_file("profile")
+
+ def _file_updated_at(self, which: MemoryFile) -> str | None:
+ path = self._path(which)
+ if not path.exists():
+ return None
+ try:
+ return datetime.fromtimestamp(path.stat().st_mtime).astimezone().isoformat()
+ except Exception:
+ return None
+
def read_snapshot(self) -> MemorySnapshot:
- path = self.memory_path
- content = self.read_memory()
- updated_at = None
- if path.exists():
- try:
- updated_at = datetime.fromtimestamp(path.stat().st_mtime).astimezone().isoformat()
- except Exception:
- updated_at = None
return MemorySnapshot(
- content=content,
- exists=bool(content) and path.exists(),
- updated_at=updated_at,
+ summary=self.read_summary(),
+ profile=self.read_profile(),
+ summary_updated_at=self._file_updated_at("summary"),
+ profile_updated_at=self._file_updated_at("profile"),
)
+ # ── Write ─────────────────────────────────────────────────────────
+
+ def write_file(self, which: MemoryFile, content: str) -> MemorySnapshot:
+ normalized = str(content or "").strip()
+ path = self._path(which)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if not normalized:
+ if path.exists():
+ path.unlink()
+ else:
+ path.write_text(normalized, encoding="utf-8")
+ return self.read_snapshot()
+
+ def write_memory(self, content: str) -> MemorySnapshot:
+ """Legacy compat: write to profile (primary editable file)."""
+ return self.write_file("profile", content)
+
+ def clear_file(self, which: MemoryFile) -> MemorySnapshot:
+ return self.write_file(which, "")
+
+ def clear_memory(self) -> MemorySnapshot:
+ for f in MEMORY_FILES:
+ path = self._path(f)
+ if path.exists():
+ path.unlink()
+ return self.read_snapshot()
+
+ # ── Context building (injected into LLM prompts) ─────────────────
+
def build_memory_context(self, max_chars: int = 4000) -> str:
- content = self.read_memory()
- if not content:
+ parts: list[str] = []
+
+ profile = self.read_profile()
+ if profile:
+ parts.append(f"### User Profile\n{profile}")
+
+ summary = self.read_summary()
+ if summary:
+ parts.append(f"### Learning Context\n{summary}")
+
+ if not parts:
return ""
- if len(content) > max_chars:
- content = content[:max_chars].rstrip() + "\n...[truncated]"
+
+ combined = "\n\n".join(parts)
+ if len(combined) > max_chars:
+ combined = combined[:max_chars].rstrip() + "\n...[truncated]"
+
return (
"## Background Memory\n"
- "Use this memory sparingly.\n"
- "- Only use it when it is directly relevant to the user's current request.\n"
- "- Do not proactively mention, summarize, or connect the request to memory unless that clearly improves the answer.\n"
- "- If the memory is not relevant, ignore it.\n\n"
- f"{content}"
+ "Use this memory sparingly — only when directly relevant.\n\n"
+ f"{combined}"
)
def get_preferences_text(self) -> str:
- preferences, _context = self._extract_sections(self.read_memory())
- if not preferences:
- return ""
- return "## Preferences\n" + preferences
+ profile = self.read_profile()
+ return f"## User Profile\n{profile}" if profile else ""
- def clear_memory(self) -> MemorySnapshot:
- path = self.memory_path
- if path.exists():
- path.unlink()
- return self.read_snapshot()
-
- def write_memory(self, content: str) -> MemorySnapshot:
- normalized = str(content or "").strip()
- if not normalized:
- return self.clear_memory()
- self._write_memory(normalized)
- return self.read_snapshot()
+ # ── Auto-refresh from conversation ────────────────────────────────
async def refresh_from_turn(
self,
@@ -112,21 +194,25 @@ class MemoryService:
timestamp: str = "",
) -> MemoryUpdateResult:
if not user_message.strip() or not assistant_message.strip():
- snapshot = self.read_snapshot()
- return MemoryUpdateResult(
- content=snapshot.content,
- changed=False,
- updated_at=snapshot.updated_at,
- )
+ return MemoryUpdateResult(content="", changed=False, updated_at=None)
- source_text = (
- f"[Session]\n{session_id or '(unknown)'}\n\n"
- f"[Capability]\n{capability or 'chat'}\n\n"
- f"[Timestamp]\n{timestamp or datetime.now().isoformat()}\n\n"
+ source = (
+ f"[Session] {session_id or '(unknown)'}\n"
+ f"[Capability] {capability or 'chat'}\n"
+ f"[Timestamp] {timestamp or datetime.now().isoformat()}\n\n"
f"[User]\n{user_message.strip()}\n\n"
f"[Assistant]\n{assistant_message.strip()}"
)
- return await self._rewrite_memory(source_text=source_text, language=language)
+
+ p_changed = await self._rewrite_one("profile", source, language)
+ s_changed = await self._rewrite_one("summary", source, language)
+
+ snap = self.read_snapshot()
+ return MemoryUpdateResult(
+ content=snap.profile,
+ changed=p_changed or s_changed,
+ updated_at=snap.profile_updated_at,
+ )
async def refresh_from_session(
self,
@@ -135,166 +221,143 @@ class MemoryService:
language: str = "en",
max_messages: int = 10,
) -> MemoryUpdateResult:
- target_session_id = (session_id or "").strip()
- if not target_session_id:
+ target = (session_id or "").strip()
+ if not target:
sessions = await self._store.list_sessions(limit=1)
if sessions:
- target_session_id = str(sessions[0].get("session_id", "") or "")
-
- if not target_session_id:
- snapshot = self.read_snapshot()
- return MemoryUpdateResult(
- content=snapshot.content,
- changed=False,
- updated_at=snapshot.updated_at,
- )
+ target = str(sessions[0].get("session_id", "") or "")
+
+ if not target:
+ return MemoryUpdateResult(content="", changed=False, updated_at=None)
- messages = await self._store.get_messages_for_context(target_session_id)
+ messages = await self._store.get_messages_for_context(target)
relevant = [
- item for item in messages
- if str(item.get("role", "") or "") in {"user", "assistant"}
- and str(item.get("content", "") or "").strip()
- ]
- relevant = relevant[-max_messages:]
+ m for m in messages
+ if str(m.get("role", "")) in {"user", "assistant"}
+ and str(m.get("content", "") or "").strip()
+ ][-max_messages:]
+
if not relevant:
- snapshot = self.read_snapshot()
- return MemoryUpdateResult(
- content=snapshot.content,
- changed=False,
- updated_at=snapshot.updated_at,
- )
+ return MemoryUpdateResult(content="", changed=False, updated_at=None)
- transcript = []
- for item in relevant:
- role = "User" if item.get("role") == "user" else "Assistant"
- transcript.append(f"{role}: {str(item.get('content', '') or '').strip()}")
+ transcript = "\n\n".join(
+ f"{'User' if m.get('role') == 'user' else 'Assistant'}: "
+ f"{str(m.get('content', '') or '').strip()}"
+ for m in relevant
+ )
- capability = ""
- session = await self._store.get_session(target_session_id)
- if session is not None:
- capability = str(session.get("capability", "") or "")
+ cap = ""
+ sess = await self._store.get_session(target)
+ if sess:
+ cap = str(sess.get("capability", "") or "")
- source_text = (
- f"[Session]\n{target_session_id}\n\n"
- f"[Capability]\n{capability or 'chat'}\n\n"
- f"[Recent Transcript]\n" + "\n\n".join(transcript)
+ source = (
+ f"[Session] {target}\n"
+ f"[Capability] {cap or 'chat'}\n\n"
+ f"[Recent Transcript]\n{transcript}"
)
- return await self._rewrite_memory(source_text=source_text, language=language)
- async def _rewrite_memory(
- self,
- *,
- source_text: str,
- language: str,
- ) -> MemoryUpdateResult:
- current_memory = self.read_memory()
- system_prompt = (
- "You maintain a lightweight long-term memory document for an AI assistant. "
- "Only preserve stable user preferences and durable ongoing context. "
- "Do not store transient chatter, one-off questions, or exhaustive history. "
- f"If nothing should change, return exactly { _NO_CHANGE_SENTINEL }."
- )
- if str(language).lower().startswith("zh"):
- system_prompt = (
- "你负责维护一份轻量长期记忆文档。"
- "只保留稳定的用户偏好和持续性的上下文。"
- "不要记录瞬时闲聊、一次性问题或完整流水账。"
- f"如果无需修改,请只返回 {_NO_CHANGE_SENTINEL}。"
- )
+ p_changed = await self._rewrite_one("profile", source, language)
+ s_changed = await self._rewrite_one("summary", source, language)
- user_prompt = (
- "Rewrite the full memory document when needed using exactly these sections:\n"
- "## Preferences\n"
- "- ...\n\n"
- "## Context\n"
- "- ...\n\n"
- "Rules:\n"
- "- Keep it short and readable.\n"
- "- Preferences: stable habits, format preferences, recurring ways of working.\n"
- "- Context: ongoing projects, repeated focus areas, open loops that remain relevant.\n"
- "- Remove stale or contradicted items.\n"
- "- If the new interaction adds nothing durable, return NO_CHANGE.\n\n"
- f"[Current memory]\n{current_memory or '(empty)'}\n\n"
- f"[New material]\n{source_text}"
+ snap = self.read_snapshot()
+ return MemoryUpdateResult(
+ content=snap.profile,
+ changed=p_changed or s_changed,
+ updated_at=snap.profile_updated_at,
)
- if str(language).lower().startswith("zh"):
- user_prompt = (
- "如果需要更新,请重写整份 memory 文档,并严格使用下面两个标题:\n"
- "## Preferences\n"
- "- ...\n\n"
- "## Context\n"
- "- ...\n\n"
- "规则:\n"
- "- 文档保持简短、清晰。\n"
- "- Preferences 只写稳定偏好、习惯、长期工作方式。\n"
- "- Context 只写持续性的项目、关注主题、仍然相关的待继续事项。\n"
- "- 过时或被新信息推翻的内容要删除。\n"
- f"- 如果这次没有新增持久信息,请只返回 {_NO_CHANGE_SENTINEL}。\n\n"
- f"[当前 memory]\n{current_memory or '(empty)'}\n\n"
- f"[新增材料]\n{source_text}"
- )
- response = await llm_complete(
+ # ── LLM rewrite for individual files ──────────────────────────────
+
+ async def _rewrite_one(self, which: MemoryFile, source: str, language: str) -> bool:
+ """Rewrite a single memory file. Returns True if changed."""
+ current = self.read_file(which)
+ zh = str(language).lower().startswith("zh")
+
+ if which == "profile":
+ sys_prompt, user_prompt = self._profile_prompts(current, source, zh)
+ else:
+ sys_prompt, user_prompt = self._summary_prompts(current, source, zh)
+
+ chunks: list[str] = []
+ async for c in llm_stream(
prompt=user_prompt,
- system_prompt=system_prompt,
+ system_prompt=sys_prompt,
temperature=0.2,
max_tokens=900,
- )
- normalized = self._normalize_memory_response(response, current_memory)
- changed = normalized != current_memory
- if changed:
- self._write_memory(normalized)
- snapshot = self.read_snapshot()
- return MemoryUpdateResult(
- content=snapshot.content,
- changed=changed,
- updated_at=snapshot.updated_at,
- )
+ ):
+ chunks.append(c)
- def _write_memory(self, content: str) -> None:
- path = self.memory_path
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(content.strip(), encoding="utf-8")
+ raw = _strip_code_fence("".join(chunks)).strip()
+ if not raw or raw == _NO_CHANGE:
+ return False
- def _normalize_memory_response(self, response: str, current_memory: str) -> str:
- cleaned = self._strip_code_fence(response).strip()
- if not cleaned or cleaned == _NO_CHANGE_SENTINEL:
- return current_memory
+ if raw == current:
+ return False
- preferences, context = self._extract_sections(cleaned)
- if not preferences and not context:
- return current_memory
+ self.write_file(which, raw)
+ return True
- parts = ["## Preferences"]
- parts.append(preferences or "- None recorded yet.")
- parts.append("")
- parts.append("## Context")
- parts.append(context or "- None recorded yet.")
- return "\n".join(parts).strip()
+ @staticmethod
+ def _profile_prompts(current: str, source: str, zh: bool) -> tuple[str, str]:
+ if zh:
+ return (
+ "你负责维护一份用户画像文档。只保留稳定的用户身份、偏好、知识水平。"
+ f"如果无需修改,请只返回 {_NO_CHANGE}。",
+ "如果需要更新,请重写用户画像,可使用以下标题:\n"
+ "## Identity\n## Learning Style\n## Knowledge Level\n## Preferences\n\n"
+ "规则:保持简短,删除过时内容,不要记录临时对话。\n\n"
+ f"[当前画像]\n{current or '(empty)'}\n\n"
+ f"[新增材料]\n{source}"
+ )
+ return (
+ "You maintain a user profile document. Only keep stable identity, "
+ "preferences, and knowledge levels. "
+ f"If nothing should change, return exactly {_NO_CHANGE}.",
+ "Rewrite the user profile if needed. Suggested sections:\n"
+ "## Identity\n## Learning Style\n## Knowledge Level\n## Preferences\n\n"
+ "Rules: keep it short, remove stale items, no transient chatter.\n\n"
+ f"[Current profile]\n{current or '(empty)'}\n\n"
+ f"[New material]\n{source}"
+ )
@staticmethod
- def _strip_code_fence(content: str) -> str:
- cleaned = str(content or "").strip()
- if cleaned.startswith("```"):
- cleaned = re.sub(r"^```[a-zA-Z0-9_-]*\n?", "", cleaned)
- cleaned = re.sub(r"\n?```$", "", cleaned)
- return cleaned.strip()
+ def _summary_prompts(current: str, source: str, zh: bool) -> tuple[str, str]:
+ if zh:
+ return (
+ "你负责维护一份学习旅程摘要。记录用户正在学什么、完成了什么、有哪些待解决的问题。"
+ f"如果无需修改,请只返回 {_NO_CHANGE}。",
+ "如果需要更新,请重写学习旅程摘要,可使用以下标题:\n"
+ "## Current Focus\n## Accomplishments\n## Open Questions\n\n"
+ "规则:保持简短,删除已完成或过时的条目。\n\n"
+ f"[当前摘要]\n{current or '(empty)'}\n\n"
+ f"[新增材料]\n{source}"
+ )
+ return (
+ "You maintain a learning journey summary. Track what the user is studying, "
+ "what they've accomplished, and what open questions remain. "
+ f"If nothing should change, return exactly {_NO_CHANGE}.",
+ "Rewrite the learning summary if needed. Suggested sections:\n"
+ "## Current Focus\n## Accomplishments\n## Open Questions\n\n"
+ "Rules: keep it short, remove completed/stale items.\n\n"
+ f"[Current summary]\n{current or '(empty)'}\n\n"
+ f"[New material]\n{source}"
+ )
+
+ # ── Helpers ───────────────────────────────────────────────────────
@staticmethod
- def _extract_sections(content: str) -> tuple[str, str]:
- text = str(content or "").replace("\r\n", "\n").strip()
+ def _extract_legacy_sections(content: str) -> tuple[str, str]:
+ text = content.replace("\r\n", "\n").strip()
preferences = ""
context = ""
-
pref_match = re.search(
r"##\s*Preferences\s*(.*?)(?=\n##\s*Context\b|\Z)",
- text,
- flags=re.IGNORECASE | re.DOTALL,
+ text, flags=re.IGNORECASE | re.DOTALL,
)
ctx_match = re.search(
r"##\s*Context\s*(.*)$",
- text,
- flags=re.IGNORECASE | re.DOTALL,
+ text, flags=re.IGNORECASE | re.DOTALL,
)
if pref_match:
preferences = pref_match.group(1).strip()
@@ -303,6 +366,14 @@ class MemoryService:
return preferences, context
+def _strip_code_fence(content: str) -> str:
+ cleaned = str(content or "").strip()
+ if cleaned.startswith("```"):
+ cleaned = re.sub(r"^```[a-zA-Z0-9_-]*\n?", "", cleaned)
+ cleaned = re.sub(r"\n?```$", "", cleaned)
+ return cleaned.strip()
+
+
_memory_service: MemoryService | None = None
@@ -314,6 +385,7 @@ def get_memory_service() -> MemoryService:
__all__ = [
+ "MemoryFile",
"MemoryService",
"MemorySnapshot",
"MemoryUpdateResult",
diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.py
index 64c724d32..c3f7cd2b4 100644
--- a/deeptutor/services/path_service.py
+++ b/deeptutor/services/path_service.py
@@ -215,7 +215,17 @@ class PathService:
return self.get_notebook_dir() / "notebooks_index.json"
def get_memory_dir(self) -> Path:
- return self.get_workspace_feature_dir("memory")
+ new_dir = self.project_root / "data" / "memory"
+ old_dir = self.get_workspace_feature_dir("memory")
+ if old_dir.exists() and not new_dir.exists():
+ new_dir.mkdir(parents=True, exist_ok=True)
+ for f in old_dir.iterdir():
+ if f.is_file() and f.suffix == ".md":
+ target = new_dir / f.name
+ if not target.exists():
+ import shutil
+ shutil.copy2(f, target)
+ return new_dir
def get_solve_dir(self) -> Path:
return self.get_chat_feature_dir("deep_solve")
diff --git a/deeptutor/services/rag/pipelines/llamaindex.py b/deeptutor/services/rag/pipelines/llamaindex.py
index 046fada13..fac75eded 100644
--- a/deeptutor/services/rag/pipelines/llamaindex.py
+++ b/deeptutor/services/rag/pipelines/llamaindex.py
@@ -41,15 +41,29 @@ class CustomEmbedding(BaseEmbedding):
"""
_client: Any = PrivateAttr()
+ _logger: Any = PrivateAttr()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._client = get_embedding_client()
+ self._logger = get_logger("CustomEmbedding")
@classmethod
def class_name(cls) -> str:
return "custom_embedding"
+ def _run_in_new_loop(self, coro):
+ """Run an async coroutine from sync context using a fresh event loop.
+
+ Avoids nest_asyncio which can deadlock when called from thread pools
+ inside a running server event loop.
+ """
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
async def _aget_query_embedding(self, query: str) -> List[float]:
"""Get embedding for a query."""
embeddings = await self._client.embed([query])
@@ -60,25 +74,24 @@ class CustomEmbedding(BaseEmbedding):
embeddings = await self._client.embed([text])
return embeddings[0]
+ async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:
+ """Get embeddings for multiple texts."""
+ return await self._client.embed(texts)
+
def _get_query_embedding(self, query: str) -> List[float]:
"""Sync version - called by LlamaIndex sync API."""
- # Use nest_asyncio to allow nested event loops
- import nest_asyncio
-
- nest_asyncio.apply()
- return asyncio.run(self._aget_query_embedding(query))
+ return self._run_in_new_loop(self._aget_query_embedding(query))
def _get_text_embedding(self, text: str) -> List[float]:
"""Sync version - called by LlamaIndex sync API."""
- # Use nest_asyncio to allow nested event loops
- import nest_asyncio
+ return self._run_in_new_loop(self._aget_text_embedding(text))
- nest_asyncio.apply()
- return asyncio.run(self._aget_text_embedding(text))
-
- async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:
- """Get embeddings for multiple texts."""
- return await self._client.embed(texts)
+ def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
+ """Sync batch version - called by LlamaIndex for bulk embedding."""
+ self._logger.info(f"Embedding batch of {len(texts)} texts...")
+ result = self._run_in_new_loop(self._aget_text_embeddings(texts))
+ self._logger.info(f"Batch embedding complete: {len(result)} vectors")
+ return result
class LlamaIndexPipeline:
@@ -105,13 +118,9 @@ class LlamaIndexPipeline:
def _configure_settings(self):
"""Configure LlamaIndex global settings."""
- # Get embedding config
embedding_cfg = get_embedding_config()
- # Configure custom embedding that works with any OpenAI-compatible API
Settings.embed_model = CustomEmbedding()
-
- # Configure chunking
Settings.chunk_size = 512
Settings.chunk_overlap = 50
@@ -120,6 +129,23 @@ class LlamaIndexPipeline:
f"({embedding_cfg.dim}D, {embedding_cfg.binding}), chunk_size=512"
)
+ async def _verify_embedding_connectivity(self) -> None:
+ """Quick smoke-test: embed a single token to catch config/network issues early."""
+ self.logger.info("Verifying embedding API connectivity...")
+ try:
+ client = get_embedding_client()
+ result = await client.embed(["connectivity test"])
+ if not result or not result[0]:
+ raise RuntimeError("Embedding API returned empty result")
+ self.logger.info(
+ f"Embedding API OK (returned {len(result[0])}-dim vector)"
+ )
+ except Exception as e:
+ self.logger.error(f"Embedding API connectivity check failed: {e}")
+ raise RuntimeError(
+ f"Cannot reach embedding API. Please check your embedding configuration. Error: {e}"
+ ) from e
+
async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
"""
Initialize KB using real LlamaIndex components.
@@ -141,6 +167,9 @@ class LlamaIndexPipeline:
storage_dir.mkdir(parents=True, exist_ok=True)
try:
+ # Verify embedding API is reachable before doing any heavy work
+ await self._verify_embedding_connectivity()
+
# Parse documents with centralized file routing
documents = []
classification = FileTypeRouter.classify_files(file_paths)
@@ -188,14 +217,15 @@ class LlamaIndexPipeline:
self.logger.error("No valid documents found")
return False
- # Create index with LlamaIndex (run sync code in thread pool to avoid blocking)
- self.logger.info(f"Creating VectorStoreIndex with {len(documents)} documents...")
+ self.logger.info(
+ f"Creating VectorStoreIndex with {len(documents)} documents "
+ f"(chunking + embedding)..."
+ )
- # Run sync LlamaIndex code in thread pool to avoid blocking async event loop
loop = asyncio.get_event_loop()
index = await loop.run_in_executor(
- None, # Use default ThreadPoolExecutor
- lambda: VectorStoreIndex.from_documents(documents, show_progress=False),
+ None,
+ lambda: VectorStoreIndex.from_documents(documents, show_progress=True),
)
# Persist index
@@ -234,33 +264,32 @@ class LlamaIndexPipeline:
self,
query: str,
kb_name: str,
- mode: str = "hybrid",
**kwargs,
) -> Dict[str, Any]:
"""
- Search using LlamaIndex query engine.
+ Search using LlamaIndex retriever.
Args:
query: Search query
kb_name: Knowledge base name
- mode: Search mode (ignored, LlamaIndex uses similarity)
**kwargs: Additional arguments (top_k, etc.)
Returns:
- Search results dictionary
+ Search results dictionary with answer, content, and sources
"""
+ kwargs.pop("mode", None)
self.logger.info(f"Searching KB '{kb_name}' with query: {query[:50]}...")
kb_dir = Path(self.kb_base_dir) / kb_name
storage_dir = kb_dir / "llamaindex_storage"
- if not storage_dir.exists():
+ docstore_path = storage_dir / "docstore.json"
+ if not storage_dir.exists() or not docstore_path.exists():
self.logger.warning(f"No LlamaIndex storage found at {storage_dir}")
return {
"query": query,
"answer": "No documents indexed. Please upload documents first.",
"content": "",
- "mode": mode,
"provider": "llamaindex",
}
@@ -281,18 +310,27 @@ class LlamaIndexPipeline:
# Execute retrieval in thread pool to avoid blocking
nodes = await loop.run_in_executor(None, load_and_retrieve)
- # Extract text from retrieved nodes
context_parts = []
- for node in nodes:
+ sources = []
+ for i, node in enumerate(nodes):
context_parts.append(node.node.text)
+ meta = node.node.metadata or {}
+ sources.append({
+ "title": meta.get("file_name", meta.get("title", f"Document {i + 1}")),
+ "content": node.node.text[:200],
+ "source": meta.get("file_path", meta.get("file_name", "")),
+ "page": meta.get("page_label", meta.get("page", "")),
+ "chunk_id": node.node.node_id or str(i),
+ "score": round(node.score, 4) if node.score is not None else "",
+ })
content = "\n\n".join(context_parts) if context_parts else ""
return {
"query": query,
- "answer": content, # Return context for ChatAgent to use
+ "answer": content,
"content": content,
- "mode": mode,
+ "sources": sources,
"provider": "llamaindex",
}
@@ -305,7 +343,6 @@ class LlamaIndexPipeline:
"query": query,
"answer": f"Search failed: {str(e)}",
"content": "",
- "mode": mode,
"provider": "llamaindex",
}
@@ -330,6 +367,8 @@ class LlamaIndexPipeline:
storage_dir = kb_dir / "llamaindex_storage"
try:
+ await self._verify_embedding_connectivity()
+
# Parse new documents with centralized file routing
documents = []
classification = FileTypeRouter.classify_files(file_paths)
@@ -380,30 +419,30 @@ class LlamaIndexPipeline:
loop = asyncio.get_event_loop()
if storage_dir.exists():
- # Load existing index and insert new documents
self.logger.info(f"Loading existing index from {storage_dir}...")
def load_and_insert():
storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))
index = load_index_from_storage(storage_context)
- # Insert new documents
- for doc in documents:
+ for i, doc in enumerate(documents, 1):
+ self.logger.info(
+ f"Inserting document {i}/{len(documents)}: "
+ f"{doc.metadata.get('file_name', 'unknown')}"
+ )
index.insert(doc)
- # Persist updated index
index.storage_context.persist(persist_dir=str(storage_dir))
return len(documents)
num_added = await loop.run_in_executor(None, load_and_insert)
self.logger.info(f"Added {num_added} documents to existing index")
else:
- # Create new index (first time)
self.logger.info(f"Creating new index with {len(documents)} documents...")
storage_dir.mkdir(parents=True, exist_ok=True)
def create_index():
- index = VectorStoreIndex.from_documents(documents, show_progress=False)
+ index = VectorStoreIndex.from_documents(documents, show_progress=True)
index.storage_context.persist(persist_dir=str(storage_dir))
return len(documents)
diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.py
index d5e87239c..e06fae9f3 100644
--- a/deeptutor/services/rag/service.py
+++ b/deeptutor/services/rag/service.py
@@ -93,17 +93,17 @@ class RAGService:
self,
query: str,
kb_name: str,
- mode: str = "hybrid",
event_sink=None,
**kwargs,
) -> Dict[str, Any]:
+ kwargs.pop("mode", None)
provider = self._get_provider_for_kb(kb_name)
with self._capture_raw_logs(event_sink, provider):
await self._emit_tool_event(
event_sink,
"status",
f"Query: {query}",
- {"query": query, "kb_name": kb_name, "mode": mode, "trace_layer": "summary"},
+ {"query": query, "kb_name": kb_name, "trace_layer": "summary"},
)
await self._emit_tool_event(
event_sink,
@@ -121,10 +121,10 @@ class RAGService:
event_sink,
"status",
f"Retrieving from knowledge base '{kb_name}'...",
- {"provider": provider, "mode": mode, "trace_layer": "summary"},
+ {"provider": provider, "trace_layer": "summary"},
)
- result = await pipeline.search(query=query, kb_name=kb_name, mode=mode, **kwargs)
+ result = await pipeline.search(query=query, kb_name=kb_name, **kwargs)
if "query" not in result:
result["query"] = query
@@ -133,8 +133,6 @@ class RAGService:
if "content" not in result and "answer" in result:
result["content"] = result["answer"]
result["provider"] = normalize_provider_name(result.get("provider") or provider)
- if "mode" not in result:
- result["mode"] = mode
answer = result.get("answer") or result.get("content") or ""
await self._emit_tool_event(
@@ -143,7 +141,6 @@ class RAGService:
f"Retrieved {len(answer)} characters of grounded context.",
{
"provider": result["provider"],
- "mode": mode,
"kb_name": kb_name,
"trace_layer": "summary",
},
@@ -234,14 +231,13 @@ class RAGService:
context: str,
kb_name: str,
query_hints: Optional[List[str]] = None,
- mode: str = "hybrid",
max_queries: int = 3,
) -> Dict[str, Any]:
import asyncio
queries = query_hints if query_hints else await self._generate_queries(context, max_queries)
- tasks = [self.search(query=q, kb_name=kb_name, mode=mode) for q in queries]
+ tasks = [self.search(query=q, kb_name=kb_name) for q in queries]
results = await asyncio.gather(*tasks, return_exceptions=True)
passages: list[str] = []
diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.py
index 4613f00e9..9463e3b16 100644
--- a/deeptutor/services/search/__init__.py
+++ b/deeptutor/services/search/__init__.py
@@ -1,4 +1,4 @@
-"""Web Search Service with nanobot-style provider selection."""
+"""Web Search Service with TutorBot-style provider selection."""
from __future__ import annotations
diff --git a/deeptutor/services/search/providers/__init__.py b/deeptutor/services/search/providers/__init__.py
index a42c66967..c2a2121b5 100644
--- a/deeptutor/services/search/providers/__init__.py
+++ b/deeptutor/services/search/providers/__init__.py
@@ -12,10 +12,10 @@ from ..base import BaseSearchProvider
_PROVIDERS: dict[str, Type[BaseSearchProvider]] = {}
_DEPRECATED_UNSUPPORTED: dict[str, str] = {
- "exa": "Deprecated in nanobot migration; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
- "serper": "Deprecated in nanobot migration; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
- "baidu": "Deprecated in nanobot migration; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
- "openrouter": "Deprecated in nanobot migration; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
+ "exa": "Deprecated; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
+ "serper": "Deprecated; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
+ "baidu": "Deprecated; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
+ "openrouter": "Deprecated; use brave/tavily/jina/searxng/duckduckgo/perplexity.",
}
diff --git a/deeptutor/services/session/context_builder.py b/deeptutor/services/session/context_builder.py
index 8c9862eda..68c2f7b81 100644
--- a/deeptutor/services/session/context_builder.py
+++ b/deeptutor/services/session/context_builder.py
@@ -272,13 +272,16 @@ class ContextBuilder:
f"{source_text}"
)
try:
- summary = await agent.call_llm(
+ _chunks: list[str] = []
+ async for _c in agent.stream_llm(
user_prompt=user_prompt,
system_prompt=system_prompt,
max_tokens=summary_budget,
stage="summarize_context",
trace_meta=trace_meta,
- )
+ ):
+ _chunks.append(_c)
+ summary = "".join(_chunks)
return summary.strip(), events
finally:
await self._append_event(
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 88dbe583d..3897c1ece 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -206,9 +206,10 @@ class TurnRuntimeManager:
async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
capability = str(payload.get("capability") or "chat")
raw_config = dict(payload.get("config", {}) or {})
+ runtime_only_keys = ("_persist_user_message", "followup_question_context")
runtime_only_config = {
- key: raw_config[key]
- for key in ("_persist_user_message", "followup_question_context")
+ key: raw_config.pop(key)
+ for key in runtime_only_keys
if key in raw_config
}
try:
diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.py
index 97028b683..12c3cdc95 100644
--- a/deeptutor/services/setup/init.py
+++ b/deeptutor/services/setup/init.py
@@ -58,7 +58,6 @@ DEFAULT_MAIN_SETTINGS = {
"question": {
"rag_query_count": 3,
"max_parallel_questions": 1,
- "rag_mode": "naive",
"idea_loop": {"max_rounds": 3, "ideas_per_round": 5},
"generation": {"max_retries": 2},
},
@@ -78,7 +77,7 @@ DEFAULT_MAIN_SETTINGS = {
"tool_max_retries": 2,
"paper_search_years_limit": 3,
},
- "rag": {"default_mode": "hybrid", "fallback_mode": "naive"},
+ "rag": {},
},
},
}
diff --git a/deeptutor/services/tutorbot/__init__.py b/deeptutor/services/tutorbot/__init__.py
new file mode 100644
index 000000000..b4df63b4f
--- /dev/null
+++ b/deeptutor/services/tutorbot/__init__.py
@@ -0,0 +1,3 @@
+from .manager import TutorBotManager, get_tutorbot_manager
+
+__all__ = ["TutorBotManager", "get_tutorbot_manager"]
diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.py
new file mode 100644
index 000000000..21d455082
--- /dev/null
+++ b/deeptutor/services/tutorbot/manager.py
@@ -0,0 +1,678 @@
+"""
+TutorBot Manager — spawn / stop / manage in-process TutorBot instances.
+
+Each TutorBot instance runs as a set of asyncio tasks within the DeepTutor
+server process. Every bot gets its own isolated workspace under
+``data/tutorbot/{bot_id}/`` containing workspace, cron, logs, and media.
+Memory is shared across all bots via ``data/memory/``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+import sys
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+from deeptutor.services.path_service import get_path_service
+
+logger = logging.getLogger(__name__)
+
+_PACKAGE_TUTORBOT = Path(__file__).resolve().parent.parent.parent / "tutorbot"
+_BUILTIN_SKILLS_DIR = _PACKAGE_TUTORBOT / "skills"
+_BUILTIN_TEMPLATES_DIR = _PACKAGE_TUTORBOT / "templates"
+
+_RESERVED_NAMES = {"workspace", "media", "cron", "logs", "sessions", "_souls"}
+
+
+@dataclass
+class BotConfig:
+ """Configuration for a single TutorBot instance."""
+
+ name: str
+ description: str = ""
+ persona: str = ""
+ channels: dict[str, Any] = field(default_factory=dict)
+ model: str | None = None
+
+
+@dataclass
+class TutorBotInstance:
+ """A running TutorBot and its metadata."""
+
+ bot_id: str
+ config: BotConfig
+ started_at: datetime = field(default_factory=datetime.now)
+ tasks: list[asyncio.Task] = field(default_factory=list, repr=False)
+ agent_loop: Any = None
+ channel_manager: Any = None
+ heartbeat: Any = None
+ notify_queue: asyncio.Queue = field(default_factory=asyncio.Queue)
+
+ @property
+ def running(self) -> bool:
+ return any(not t.done() for t in self.tasks)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "bot_id": self.bot_id,
+ "name": self.config.name,
+ "description": self.config.description,
+ "persona": self.config.persona,
+ "channels": list(self.config.channels.keys()),
+ "model": self.config.model,
+ "running": self.running,
+ "started_at": self.started_at.isoformat(),
+ }
+
+
+class TutorBotManager:
+ """Manage TutorBot instances running in-process."""
+
+ def __init__(self) -> None:
+ self._bots: dict[str, TutorBotInstance] = {}
+ self._path_service = get_path_service()
+
+ # ── Path helpers ──────────────────────────────────────────────
+
+ @property
+ def _tutorbot_dir(self) -> Path:
+ return self._path_service.project_root / "data" / "tutorbot"
+
+ @property
+ def _shared_memory_dir(self) -> Path:
+ """Public memory shared by DeepTutor and all bots."""
+ return self._path_service.get_memory_dir()
+
+ def _bot_dir(self, bot_id: str) -> Path:
+ return self._tutorbot_dir / bot_id
+
+ def _bot_workspace(self, bot_id: str) -> Path:
+ return self._bot_dir(bot_id) / "workspace"
+
+ # ── Per-bot directory setup ───────────────────────────────────
+
+ def _ensure_bot_dirs(self, bot_id: str) -> None:
+ """Create the per-bot directory tree and seed skills/templates."""
+ self._maybe_migrate_legacy(bot_id)
+
+ for sub in ("workspace/skills", "workspace/memory", "cron", "logs", "media"):
+ (self._bot_dir(bot_id) / sub).mkdir(parents=True, exist_ok=True)
+
+ self._seed_skills(bot_id)
+ self._seed_templates(bot_id)
+
+ def _seed_skills(self, bot_id: str) -> None:
+ """Copy built-in skill templates into the bot's workspace if absent."""
+ if not _BUILTIN_SKILLS_DIR.exists():
+ logger.warning("Builtin skills dir not found: %s", _BUILTIN_SKILLS_DIR)
+ return
+ dst = self._bot_workspace(bot_id) / "skills"
+ dst.mkdir(parents=True, exist_ok=True)
+ copied = 0
+ for skill_dir in _BUILTIN_SKILLS_DIR.iterdir():
+ if not skill_dir.is_dir():
+ continue
+ target = dst / skill_dir.name
+ if not target.exists():
+ try:
+ shutil.copytree(skill_dir, target)
+ copied += 1
+ except Exception:
+ logger.exception("Failed to copy skill '%s' for bot '%s'", skill_dir.name, bot_id)
+ if copied:
+ logger.info("Seeded %d skills for bot '%s' from %s", copied, bot_id, _BUILTIN_SKILLS_DIR)
+
+ def _seed_templates(self, bot_id: str) -> None:
+ """Copy per-bot template files into the bot's workspace if absent."""
+ if not _BUILTIN_TEMPLATES_DIR.exists():
+ return
+ ws = self._bot_workspace(bot_id)
+ for tpl in ("SOUL.md", "TOOLS.md", "USER.md", "HEARTBEAT.md", "AGENTS.md"):
+ src = _BUILTIN_TEMPLATES_DIR / tpl
+ dst = ws / tpl
+ if src.exists() and not dst.exists():
+ shutil.copy2(src, dst)
+
+ # ── Legacy data migration ─────────────────────────────────────
+
+ def _maybe_migrate_legacy(self, bot_id: str) -> None:
+ """Migrate from the old bots/ sub-directory layout.
+
+ Old layout:
+ data/tutorbot/bots/{bot_id}/config.yaml
+ data/tutorbot/bots/{bot_id}/workspace/
+ data/tutorbot/bots/{bot_id}/memory/
+
+ New layout:
+ data/tutorbot/{bot_id}/config.yaml
+ data/tutorbot/{bot_id}/workspace/
+ data/memory/ (shared)
+ """
+ new_config = self._bot_dir(bot_id) / "config.yaml"
+ if new_config.exists():
+ return
+
+ legacy_bots = self._tutorbot_dir / "bots"
+
+ # Migrate from bots/{id}/ to {id}/
+ legacy_bot_dir = legacy_bots / bot_id
+ if legacy_bot_dir.is_dir() and (legacy_bot_dir / "config.yaml").exists():
+ target = self._bot_dir(bot_id)
+ target.mkdir(parents=True, exist_ok=True)
+ for item in legacy_bot_dir.iterdir():
+ if item.name == "memory":
+ continue
+ dest = target / item.name
+ if not dest.exists():
+ shutil.move(str(item), str(dest))
+ logger.info("Migrated bot '%s' from bots/ sub-directory", bot_id)
+
+ # Migrate legacy bots/{id}.yaml
+ legacy_yaml = legacy_bots / f"{bot_id}.yaml"
+ if legacy_yaml.is_file() and not new_config.exists():
+ self._bot_dir(bot_id).mkdir(parents=True, exist_ok=True)
+ shutil.move(str(legacy_yaml), str(new_config))
+ logger.info("Migrated bot config %s.yaml", bot_id)
+
+ # ── Config persistence ────────────────────────────────────────
+
+ def _load_bot_config(self, bot_id: str) -> BotConfig | None:
+ path = self._bot_dir(bot_id) / "config.yaml"
+ if not path.exists():
+ return None
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ return BotConfig(
+ name=data.get("name", bot_id),
+ description=data.get("description", ""),
+ persona=data.get("persona", ""),
+ channels=data.get("channels", {}),
+ model=data.get("model"),
+ )
+ except Exception:
+ logger.exception("Failed to load bot config %s", bot_id)
+ return None
+
+ def _save_bot_config(self, bot_id: str, config: BotConfig, *, auto_start: bool = True) -> None:
+ bot_dir = self._bot_dir(bot_id)
+ bot_dir.mkdir(parents=True, exist_ok=True)
+ path = bot_dir / "config.yaml"
+ data: dict[str, Any] = {
+ "name": config.name,
+ "description": config.description,
+ "persona": config.persona,
+ "channels": config.channels,
+ "auto_start": auto_start,
+ }
+ if config.model:
+ data["model"] = config.model
+ path.write_text(yaml.dump(data, allow_unicode=True), encoding="utf-8")
+
+ # ── Bot lifecycle ─────────────────────────────────────────────
+
+ async def start_bot(self, bot_id: str, config: BotConfig | None = None) -> TutorBotInstance:
+ """Start a TutorBot instance with its own isolated workspace."""
+ if bot_id in self._bots and self._bots[bot_id].running:
+ return self._bots[bot_id]
+
+ self._ensure_bot_dirs(bot_id)
+
+ if config is None:
+ config = self._load_bot_config(bot_id)
+ if config is None:
+ config = BotConfig(name=bot_id)
+ self._save_bot_config(bot_id, config)
+
+ from deeptutor.tutorbot.providers.deeptutor_adapter import create_deeptutor_provider
+ from deeptutor.tutorbot.bus.queue import MessageBus
+ from deeptutor.tutorbot.agent.loop import AgentLoop
+ from deeptutor.tutorbot.config.schema import ExecToolConfig
+ from deeptutor.tutorbot.session.manager import SessionManager
+
+ provider = create_deeptutor_provider()
+ bus = MessageBus()
+
+ workspace = self._bot_workspace(bot_id)
+ session_adapter = SessionManager(workspace)
+
+ if config.persona:
+ soul_path = workspace / "SOUL.md"
+ soul_path.write_text(config.persona, encoding="utf-8")
+
+ venv_bin = str(Path(sys.executable).parent)
+ exec_config = ExecToolConfig(timeout=300, path_append=venv_bin)
+
+ agent_loop = AgentLoop(
+ bus=bus,
+ provider=provider,
+ workspace=workspace,
+ model=config.model,
+ exec_config=exec_config,
+ session_manager=session_adapter,
+ shared_memory_dir=None,
+ restrict_to_workspace=False,
+ )
+
+ instance = TutorBotInstance(
+ bot_id=bot_id,
+ config=config,
+ agent_loop=agent_loop,
+ channel_manager=None,
+ )
+
+ loop_task = asyncio.create_task(
+ agent_loop.run(), name=f"tutorbot:{bot_id}:loop",
+ )
+ bridge_task = asyncio.create_task(
+ self._bridge_events(bot_id, bus), name=f"tutorbot:{bot_id}:events",
+ )
+ instance.tasks.extend([loop_task, bridge_task])
+
+ from deeptutor.tutorbot.heartbeat import HeartbeatService
+
+ session_key = f"web:{bot_id}:web"
+
+ async def _hb_execute(tasks_summary: str) -> str:
+ return await agent_loop.process_direct(
+ tasks_summary, session_key=session_key,
+ channel="web", chat_id="web",
+ )
+
+ async def _hb_notify(response: str) -> None:
+ await instance.notify_queue.put(response)
+
+ heartbeat = HeartbeatService(
+ workspace=workspace,
+ provider=provider,
+ model=agent_loop.model,
+ on_execute=_hb_execute,
+ on_notify=_hb_notify,
+ interval_s=30 * 60,
+ )
+ instance.heartbeat = heartbeat
+ await heartbeat.start()
+
+ self._bots[bot_id] = instance
+ logger.info("TutorBot '%s' started (workspace=%s)", bot_id, workspace)
+ return instance
+
+ async def _bridge_events(self, bot_id: str, bus: Any) -> None:
+ """Forward outbound messages from TutorBot's MessageBus to DeepTutor's EventBus."""
+ try:
+ from deeptutor.events.event_bus import Event, EventType, get_event_bus
+
+ event_bus = get_event_bus()
+ while True:
+ msg = await bus.consume_outbound()
+ if msg.metadata and msg.metadata.get("_progress"):
+ continue
+ await event_bus.publish(Event(
+ type=EventType.CAPABILITY_COMPLETE,
+ task_id=f"tutorbot:{bot_id}:{msg.channel}:{msg.chat_id}",
+ user_input="",
+ agent_output=msg.content or "",
+ metadata={
+ "source": "tutorbot",
+ "bot_id": bot_id,
+ "channel": msg.channel,
+ "chat_id": msg.chat_id,
+ },
+ ))
+ except asyncio.CancelledError:
+ return
+ except Exception:
+ logger.exception("Event bridge failed for bot %s", bot_id)
+
+ async def stop_bot(self, bot_id: str) -> bool:
+ """Stop a running TutorBot instance."""
+ instance = self._bots.get(bot_id)
+ if not instance:
+ return False
+
+ for task in instance.tasks:
+ if not task.done():
+ task.cancel()
+ for task in instance.tasks:
+ try:
+ await asyncio.wait_for(asyncio.shield(task), timeout=5.0)
+ except (asyncio.CancelledError, asyncio.TimeoutError):
+ pass
+
+ if instance.heartbeat:
+ instance.heartbeat.stop()
+
+ if instance.agent_loop:
+ try:
+ await instance.agent_loop.stop()
+ except Exception:
+ pass
+
+ self._save_bot_config(bot_id, instance.config, auto_start=False)
+ del self._bots[bot_id]
+ logger.info("TutorBot '%s' stopped", bot_id)
+ return True
+
+ # ── Listing & discovery ───────────────────────────────────────
+
+ def _discover_bot_ids(self) -> set[str]:
+ """Return all bot IDs found on disk."""
+ ids: set[str] = set()
+ if not self._tutorbot_dir.exists():
+ return ids
+
+ for entry in self._tutorbot_dir.iterdir():
+ if entry.name in _RESERVED_NAMES:
+ continue
+ if entry.is_dir() and (entry / "config.yaml").exists():
+ ids.add(entry.name)
+ return ids
+
+ def list_bots(self) -> list[dict[str, Any]]:
+ """List all known bots (running + configured on disk)."""
+ result: dict[str, dict[str, Any]] = {}
+
+ for inst in self._bots.values():
+ result[inst.bot_id] = inst.to_dict()
+
+ for bid in self._discover_bot_ids():
+ if bid in result:
+ continue
+ self._maybe_migrate_legacy(bid)
+ cfg = self._load_bot_config(bid)
+ result[bid] = {
+ "bot_id": bid,
+ "name": cfg.name if cfg else bid,
+ "description": cfg.description if cfg else "",
+ "persona": cfg.persona if cfg else "",
+ "channels": list(cfg.channels.keys()) if cfg else [],
+ "model": cfg.model if cfg else None,
+ "running": False,
+ "started_at": None,
+ }
+
+ return list(result.values())
+
+ def get_bot(self, bot_id: str) -> TutorBotInstance | None:
+ return self._bots.get(bot_id)
+
+ def get_bot_history(self, bot_id: str, limit: int = 100) -> list[dict[str, Any]]:
+ """Read chat messages from a bot's JSONL session files."""
+ import json as _json
+
+ sessions_dir = self._bot_workspace(bot_id) / "sessions"
+ if not sessions_dir.exists():
+ return []
+
+ all_messages: list[dict[str, Any]] = []
+ for path in sorted(sessions_dir.glob("*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True):
+ try:
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ data = _json.loads(line)
+ if data.get("_type") == "metadata":
+ continue
+ if data.get("role") in ("user", "assistant") and data.get("content"):
+ all_messages.append(data)
+ except Exception:
+ continue
+ if len(all_messages) >= limit:
+ break
+
+ return all_messages[-limit:]
+
+ def get_recent_active_bots(self, limit: int = 3) -> list[dict[str, Any]]:
+ """Return the most recently active bots with their last message preview."""
+ import json as _json
+
+ bot_activity: list[tuple[float, str, dict[str, Any]]] = []
+
+ for bid in self._discover_bot_ids():
+ sessions_dir = self._bot_workspace(bid) / "sessions"
+ if not sessions_dir.is_dir():
+ continue
+
+ jsonl_files = list(sessions_dir.glob("*.jsonl"))
+ if not jsonl_files:
+ continue
+
+ newest = max(jsonl_files, key=lambda p: p.stat().st_mtime)
+ mtime = newest.stat().st_mtime
+
+ last_msg = ""
+ try:
+ with open(newest, encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ data = _json.loads(line)
+ if data.get("_type") == "metadata":
+ continue
+ if data.get("role") in ("user", "assistant") and data.get("content"):
+ last_msg = data["content"]
+ except Exception:
+ pass
+
+ cfg = self._load_bot_config(bid)
+ instance = self._bots.get(bid)
+ bot_activity.append((mtime, bid, {
+ "bot_id": bid,
+ "name": cfg.name if cfg else bid,
+ "running": instance.running if instance else False,
+ "last_message": last_msg[:200] if last_msg else "",
+ "updated_at": datetime.fromtimestamp(mtime).isoformat(),
+ }))
+
+ bot_activity.sort(key=lambda x: x[0], reverse=True)
+ return [item[2] for item in bot_activity[:limit]]
+
+ async def send_message(
+ self,
+ bot_id: str,
+ content: str,
+ chat_id: str = "web",
+ on_progress: Callable[[str], Awaitable[None]] | None = None,
+ ) -> str:
+ """Send a message to a running bot and return the response."""
+ instance = self._bots.get(bot_id)
+ if not instance or not instance.running:
+ raise RuntimeError(f"Bot '{bot_id}' is not running")
+
+ async def _progress(text: str, *, tool_hint: bool = False) -> None:
+ if on_progress:
+ await on_progress(text)
+
+ return await instance.agent_loop.process_direct(
+ content,
+ session_key=f"web:{bot_id}:{chat_id}",
+ channel="web",
+ chat_id=chat_id,
+ on_progress=_progress,
+ )
+
+ async def auto_start_bots(self) -> None:
+ """Scan persisted configs and start bots marked with auto_start: true."""
+ for bid in self._discover_bot_ids():
+ if bid in self._bots and self._bots[bid].running:
+ continue
+ try:
+ self._maybe_migrate_legacy(bid)
+ path = self._bot_dir(bid) / "config.yaml"
+ if not path.exists():
+ continue
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ if not data.get("auto_start", False):
+ continue
+ config = BotConfig(
+ name=data.get("name", bid),
+ description=data.get("description", ""),
+ persona=data.get("persona", ""),
+ channels=data.get("channels", {}),
+ model=data.get("model"),
+ )
+ await self.start_bot(bid, config)
+ logger.info("Auto-started bot '%s'", bid)
+ except Exception:
+ logger.exception("Failed to auto-start bot '%s'", bid)
+
+ async def destroy_bot(self, bot_id: str) -> bool:
+ """Stop a bot (if running) and permanently delete its data from disk."""
+ await self.stop_bot(bot_id)
+ bot_dir = self._bot_dir(bot_id)
+ if not bot_dir.exists():
+ return False
+ shutil.rmtree(bot_dir)
+ logger.info("TutorBot '%s' destroyed (data deleted)", bot_id)
+ return True
+
+ # ── Workspace file helpers ────────────────────────────────────
+
+ _EDITABLE_FILES = {"SOUL.md", "USER.md", "TOOLS.md", "AGENTS.md", "HEARTBEAT.md"}
+
+ def read_bot_file(self, bot_id: str, filename: str) -> str | None:
+ if filename not in self._EDITABLE_FILES:
+ return None
+ path = self._bot_workspace(bot_id) / filename
+ if not path.exists():
+ return ""
+ return path.read_text(encoding="utf-8")
+
+ def write_bot_file(self, bot_id: str, filename: str, content: str) -> bool:
+ if filename not in self._EDITABLE_FILES:
+ return False
+ path = self._bot_workspace(bot_id) / filename
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content, encoding="utf-8")
+ return True
+
+ def read_all_bot_files(self, bot_id: str) -> dict[str, str]:
+ result: dict[str, str] = {}
+ ws = self._bot_workspace(bot_id)
+ for fn in self._EDITABLE_FILES:
+ path = ws / fn
+ result[fn] = path.read_text(encoding="utf-8") if path.exists() else ""
+ return result
+
+ async def stop_all(self) -> None:
+ """Stop all running bots."""
+ for bot_id in list(self._bots.keys()):
+ await self.stop_bot(bot_id)
+
+ # ── Soul template library ─────────────────────────────────────
+
+ @property
+ def _souls_file(self) -> Path:
+ return self._tutorbot_dir / "_souls.yaml"
+
+ def _load_souls(self) -> list[dict[str, str]]:
+ path = self._souls_file
+ if not path.exists():
+ self._seed_default_souls()
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
+ return data if isinstance(data, list) else []
+ except Exception:
+ return []
+
+ def _save_souls(self, souls: list[dict[str, str]]) -> None:
+ self._tutorbot_dir.mkdir(parents=True, exist_ok=True)
+ self._souls_file.write_text(
+ yaml.dump(souls, allow_unicode=True, default_flow_style=False),
+ encoding="utf-8",
+ )
+
+ def _seed_default_souls(self) -> None:
+ defaults = [
+ {"id": "default-tutorbot", "name": "Default TutorBot", "content": (
+ "# Soul\n\nI am TutorBot, a personal learning companion.\n\n"
+ "## Personality\n\n- Helpful and friendly\n- Clear, encouraging, and patient\n"
+ "- Adapts explanations to the user's level\n\n"
+ "## Values\n\n- Accuracy over speed\n- User privacy and safety\n- Transparency in actions"
+ )},
+ {"id": "math-tutor", "name": "Math Tutor", "content": (
+ "# Soul\n\nI am a math tutor specializing in clear, step-by-step problem solving.\n\n"
+ "## Personality\n\n- Patient and methodical\n- Encourages showing work\n"
+ "- Celebrates progress on hard problems\n\n"
+ "## Teaching Style\n\n- Break complex problems into small steps\n"
+ "- Use visual representations when possible\n- Always verify final answers"
+ )},
+ {"id": "coding-assistant", "name": "Coding Assistant", "content": (
+ "# Soul\n\nI am a coding assistant focused on helping developers write better software.\n\n"
+ "## Personality\n\n- Precise and detail-oriented\n"
+ "- Pragmatic — working code over perfect code\n- Explains trade-offs clearly\n\n"
+ "## Approach\n\n- Read before writing; understand context first\n"
+ "- Suggest tests alongside implementations\n- Prefer standard patterns over clever tricks"
+ )},
+ {"id": "research-helper", "name": "Research Helper", "content": (
+ "# Soul\n\nI am a research assistant helping users explore academic topics in depth.\n\n"
+ "## Personality\n\n- Curious and thorough\n"
+ "- Balanced — presents multiple perspectives\n- Cites sources when possible\n\n"
+ "## Approach\n\n- Decompose broad questions into focused sub-questions\n"
+ "- Distinguish established facts from open questions\n- Suggest further reading"
+ )},
+ {"id": "language-tutor", "name": "Language Tutor", "content": (
+ "# Soul\n\nI am a language learning companion helping users practice and improve.\n\n"
+ "## Personality\n\n- Encouraging and patient\n"
+ "- Adapts difficulty to learner level\n- Makes learning fun with examples\n\n"
+ "## Teaching Style\n\n- Correct mistakes gently with explanations\n"
+ "- Use contextual examples over abstract rules\n- Encourage speaking/writing practice"
+ )},
+ ]
+ self._save_souls(defaults)
+
+ def list_souls(self) -> list[dict[str, str]]:
+ return self._load_souls()
+
+ def get_soul(self, soul_id: str) -> dict[str, str] | None:
+ for s in self._load_souls():
+ if s.get("id") == soul_id:
+ return s
+ return None
+
+ def create_soul(self, soul_id: str, name: str, content: str) -> dict[str, str]:
+ souls = self._load_souls()
+ entry = {"id": soul_id, "name": name, "content": content}
+ souls.append(entry)
+ self._save_souls(souls)
+ return entry
+
+ def update_soul(self, soul_id: str, name: str | None, content: str | None) -> dict[str, str] | None:
+ souls = self._load_souls()
+ for s in souls:
+ if s.get("id") == soul_id:
+ if name is not None:
+ s["name"] = name
+ if content is not None:
+ s["content"] = content
+ self._save_souls(souls)
+ return s
+ return None
+
+ def delete_soul(self, soul_id: str) -> bool:
+ souls = self._load_souls()
+ new = [s for s in souls if s.get("id") != soul_id]
+ if len(new) == len(souls):
+ return False
+ self._save_souls(new)
+ return True
+
+
+_manager: TutorBotManager | None = None
+
+
+def get_tutorbot_manager() -> TutorBotManager:
+ global _manager
+ if _manager is None:
+ _manager = TutorBotManager()
+ return _manager
diff --git a/deeptutor/tools/brainstorm.py b/deeptutor/tools/brainstorm.py
index f0b2d6b9e..71868ad7d 100644
--- a/deeptutor/tools/brainstorm.py
+++ b/deeptutor/tools/brainstorm.py
@@ -53,7 +53,7 @@ async def brainstorm(
) -> dict[str, Any]:
"""Generate breadth-first ideas for a topic via one LLM call."""
from deeptutor.services.config import get_agent_params
- from deeptutor.services.llm import complete as llm_complete
+ from deeptutor.services.llm import complete as llm_complete, stream as llm_stream
from deeptutor.services.llm import get_token_limit_kwargs
from deeptutor.services.llm.config import get_llm_config
@@ -85,14 +85,17 @@ async def brainstorm(
logger.debug("brainstorm tool: model=%s, topic=%s...", model, topic[:80])
- answer = await llm_complete(
+ _chunks: list[str] = []
+ async for _c in llm_stream(
prompt=user_prompt,
system_prompt=_SYSTEM_PROMPT,
model=model,
api_key=api_key,
base_url=base_url,
**kwargs,
- )
+ ):
+ _chunks.append(_c)
+ answer = "".join(_chunks)
return {
"topic": topic,
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index cf626245e..14ab42ab0 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -71,14 +71,6 @@ class RAGTool(_PromptHintsMixin, BaseTool):
description="Knowledge base to search.",
required=False,
),
- ToolParameter(
- name="mode",
- type="string",
- description="Search mode.",
- required=False,
- default="hybrid",
- enum=["naive", "local", "global", "hybrid"],
- ),
],
)
@@ -87,7 +79,6 @@ class RAGTool(_PromptHintsMixin, BaseTool):
query = kwargs.get("query", "")
kb_name = kwargs.get("kb_name")
- mode = kwargs.get("mode", "hybrid")
event_sink = kwargs.get("event_sink")
extra_kwargs = {
key: value
@@ -98,14 +89,13 @@ class RAGTool(_PromptHintsMixin, BaseTool):
result = await rag_search(
query=query,
kb_name=kb_name,
- mode=mode,
event_sink=event_sink,
**extra_kwargs,
)
content = result.get("answer") or result.get("content", "")
return ToolResult(
content=content,
- sources=[{"type": "rag", "query": query, "kb_name": kb_name, "mode": mode}],
+ sources=[{"type": "rag", "query": query, "kb_name": kb_name}],
metadata=result,
)
@@ -514,8 +504,8 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
BUILTIN_TOOL_NAMES: tuple[str, ...] = tuple(tool_type().name for tool_type in BUILTIN_TOOL_TYPES)
TOOL_ALIASES: dict[str, tuple[str, dict[str, Any]]] = {
- "rag_hybrid": ("rag", {"mode": "hybrid"}),
- "rag_naive": ("rag", {"mode": "naive"}),
+ "rag_hybrid": ("rag", {}),
+ "rag_naive": ("rag", {}),
"rag_search": ("rag", {}),
"code_execute": ("code_execution", {}),
"run_code": ("code_execution", {}),
diff --git a/deeptutor/tools/prompting/hints/en/rag.yaml b/deeptutor/tools/prompting/hints/en/rag.yaml
index e06060a13..322bc9348 100644
--- a/deeptutor/tools/prompting/hints/en/rag.yaml
+++ b/deeptutor/tools/prompting/hints/en/rag.yaml
@@ -4,14 +4,3 @@ input_format: "Natural-language query."
guideline: "Prefer RAG before external search when the task is course-aligned or knowledge-base-specific."
note: "If the first retrieval is weak, revise the query from another angle instead of giving up immediately."
phase: "exploration"
-aliases:
- - name: rag_hybrid
- description: "Comprehensive retrieval across the knowledge base."
- input_format: "Natural-language query."
- when_to_use: "Use for broad exploration, relationships, or concept synthesis."
- phase: "exploration"
- - name: rag_naive
- description: "Direct retrieval for precise definitions or facts."
- input_format: "Natural-language query."
- when_to_use: "Use for targeted lookups such as a definition, formula, or exact concept."
- phase: "verification"
diff --git a/deeptutor/tools/prompting/hints/zh/rag.yaml b/deeptutor/tools/prompting/hints/zh/rag.yaml
index 8fe12837f..c82963d34 100644
--- a/deeptutor/tools/prompting/hints/zh/rag.yaml
+++ b/deeptutor/tools/prompting/hints/zh/rag.yaml
@@ -4,14 +4,3 @@ input_format: "自然语言查询。"
guideline: "如果任务与课程材料强相关,优先使用 RAG,而不是直接转向外部搜索。"
note: "第一次检索效果不佳时,应先换一个查询角度再判断是否无结果。"
phase: "exploration"
-aliases:
- - name: rag_hybrid
- description: "面向知识库的综合检索。"
- input_format: "自然语言查询。"
- when_to_use: "适合概念探索、关系分析或综合性检索。"
- phase: "exploration"
- - name: rag_naive
- description: "面向精确事实的直接检索。"
- input_format: "自然语言查询。"
- when_to_use: "适合查询具体定义、公式或精确知识点。"
- phase: "verification"
diff --git a/deeptutor/tools/rag_tool.py b/deeptutor/tools/rag_tool.py
index 06e888975..f6971c4ca 100644
--- a/deeptutor/tools/rag_tool.py
+++ b/deeptutor/tools/rag_tool.py
@@ -17,19 +17,17 @@ from deeptutor.services.rag.factory import DEFAULT_PROVIDER as DEFAULT_RAG_PROVI
async def rag_search(
query: str,
kb_name: Optional[str] = None,
- mode: str = "hybrid",
provider: Optional[str] = None,
kb_base_dir: Optional[str] = None,
event_sink=None,
**kwargs,
) -> dict:
"""
- Query knowledge base using configurable RAG pipeline.
+ Query knowledge base using LlamaIndex RAG pipeline.
Args:
query: Query question
kb_name: Knowledge base name (optional, defaults to default knowledge base)
- mode: Query mode (e.g., "hybrid", "local", "global", "naive")
provider: RAG pipeline to use (defaults to configured provider or "llamaindex")
kb_base_dir: Base directory for knowledge bases (for testing)
**kwargs: Additional parameters passed to the RAG pipeline
@@ -40,20 +38,9 @@ async def rag_search(
"query": str,
"answer": str,
"content": str,
- "mode": str,
+ "sources": list,
"provider": str
}
-
- Raises:
- ValueError: If the specified RAG pipeline is not found
- Exception: If the query fails
-
- Example:
- # Use default provider (from .env)
- result = await rag_search("What is machine learning?", kb_name="textbook")
-
- # Override provider
- result = await rag_search("What is ML?", kb_name="textbook", provider="llamaindex")
"""
service = RAGService(kb_base_dir=kb_base_dir, provider=provider)
@@ -61,7 +48,6 @@ async def rag_search(
return await service.search(
query=query,
kb_name=kb_name,
- mode=mode,
event_sink=event_sink,
**kwargs,
)
@@ -164,7 +150,6 @@ if __name__ == "__main__":
rag_search(
"What is the lookup table (LUT) in FPGA?",
kb_name="DE-all",
- mode="naive",
)
)
diff --git a/deeptutor/tools/reason.py b/deeptutor/tools/reason.py
index 0c0915397..32083000e 100644
--- a/deeptutor/tools/reason.py
+++ b/deeptutor/tools/reason.py
@@ -63,7 +63,7 @@ async def reason(
Returns:
dict with keys ``query``, ``answer``, ``model``.
"""
- from deeptutor.services.llm import complete as llm_complete
+ from deeptutor.services.llm import complete as llm_complete, stream as llm_stream
from deeptutor.services.llm.config import get_llm_config
from deeptutor.services.llm import get_token_limit_kwargs
from deeptutor.services.config import get_agent_params
@@ -100,14 +100,17 @@ async def reason(
logger.debug("reason tool: model=%s, query=%s...", model, query[:80])
- answer = await llm_complete(
+ _chunks: list[str] = []
+ async for _c in llm_stream(
prompt=user_prompt,
system_prompt=_SYSTEM_PROMPT,
model=model,
api_key=api_key,
base_url=base_url,
**kwargs,
- )
+ ):
+ _chunks.append(_c)
+ answer = "".join(_chunks)
return {
"query": query,
diff --git a/deeptutor/tutorbot/__init__.py b/deeptutor/tutorbot/__init__.py
new file mode 100644
index 000000000..900145123
--- /dev/null
+++ b/deeptutor/tutorbot/__init__.py
@@ -0,0 +1,3 @@
+"""TutorBot — Agent engine for DeepTutor (migrated from nanobot)."""
+
+__version__ = "1.0.0"
diff --git a/deeptutor/tutorbot/agent/__init__.py b/deeptutor/tutorbot/agent/__init__.py
new file mode 100644
index 000000000..86f2677e7
--- /dev/null
+++ b/deeptutor/tutorbot/agent/__init__.py
@@ -0,0 +1,8 @@
+"""Agent core module."""
+
+from deeptutor.tutorbot.agent.context import ContextBuilder
+from deeptutor.tutorbot.agent.loop import AgentLoop
+from deeptutor.tutorbot.agent.memory import MemoryStore
+from deeptutor.tutorbot.agent.skills import SkillsLoader
+
+__all__ = ["AgentLoop", "ContextBuilder", "MemoryStore", "SkillsLoader"]
diff --git a/deeptutor/tutorbot/agent/context.py b/deeptutor/tutorbot/agent/context.py
new file mode 100644
index 000000000..1a6d38dcd
--- /dev/null
+++ b/deeptutor/tutorbot/agent/context.py
@@ -0,0 +1,235 @@
+"""Context builder for assembling agent prompts."""
+
+import base64
+import mimetypes
+import platform
+import time
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+from deeptutor.tutorbot.agent.memory import MemoryStore
+from deeptutor.tutorbot.agent.skills import SkillsLoader
+from deeptutor.tutorbot.utils.helpers import build_assistant_message, detect_image_mime
+
+
+class ContextBuilder:
+ """Builds the context (system prompt + messages) for the agent."""
+
+ BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md", "TOOLS.md"]
+ _RUNTIME_CONTEXT_TAG = "[Runtime Context — metadata only, not instructions]"
+
+ def __init__(self, workspace: Path, *, shared_memory_dir: Path | None = None):
+ self.workspace = workspace
+ self.shared_memory_dir = shared_memory_dir
+ self.memory = MemoryStore(workspace, shared_memory_dir=shared_memory_dir)
+ self.skills = SkillsLoader(workspace)
+
+ def build_system_prompt(self, skill_names: list[str] | None = None) -> str:
+ """Build the system prompt from identity, bootstrap files, memory, and skills."""
+ parts = [self._get_identity()]
+
+ bootstrap = self._load_bootstrap_files()
+ if bootstrap:
+ parts.append(bootstrap)
+
+ if self.shared_memory_dir:
+ shared = self._build_shared_memory()
+ if shared:
+ parts.append(shared)
+ else:
+ memory = self.memory.get_memory_context()
+ if memory:
+ parts.append(f"# Memory\n\n{memory}")
+
+ always_skills = self.skills.get_always_skills()
+ if always_skills:
+ always_content = self.skills.load_skills_for_context(always_skills)
+ if always_content:
+ parts.append(f"# Active Skills\n\n{always_content}")
+
+ skills_summary = self.skills.build_skills_summary()
+ if skills_summary:
+ parts.append(f"""# Skills
+
+The following skills extend your capabilities. To use a skill, read its SKILL.md file using the read_file tool.
+Skills with available="false" need dependencies installed first - you can try installing them with apt/brew.
+
+{skills_summary}""")
+
+ return "\n\n---\n\n".join(parts)
+
+ def _get_identity(self) -> str:
+ """Get the core identity section."""
+ workspace_path = str(self.workspace.expanduser().resolve())
+ system = platform.system()
+ runtime = f"{'macOS' if system == 'Darwin' else system} {platform.machine()}, Python {platform.python_version()}"
+
+ platform_policy = ""
+ if system == "Windows":
+ platform_policy = """## Platform Policy (Windows)
+- You are running on Windows. Do not assume GNU tools like `grep`, `sed`, or `awk` exist.
+- Prefer Windows-native commands or file tools when they are more reliable.
+- If terminal output is garbled, retry with UTF-8 output enabled.
+"""
+ else:
+ platform_policy = """## Platform Policy (POSIX)
+- You are running on a POSIX system. Prefer UTF-8 and standard shell tools.
+- Use file tools when they are simpler or more reliable than shell commands.
+"""
+
+ if self.shared_memory_dir:
+ name = "TutorBot"
+ tagline = "You are TutorBot, an intelligent learning companion powered by DeepTutor."
+ else:
+ name = "TutorBot"
+ tagline = "You are TutorBot, a helpful AI assistant."
+
+ return f"""# {name}
+
+{tagline}
+
+## Runtime
+{runtime}
+
+## Workspace
+Your workspace is at: {workspace_path}
+- Custom skills: {workspace_path}/skills/{{skill-name}}/SKILL.md
+
+{platform_policy}
+
+## Guidelines
+- State intent before tool calls, but NEVER predict or claim results before receiving them.
+- Before modifying a file, read it first. Do not assume files or directories exist.
+- After writing or editing a file, re-read it if accuracy matters.
+- If a tool call fails, analyze the error before retrying with a different approach.
+- Ask for clarification when the request is ambiguous.
+
+Reply directly with text for conversations. Only use the 'message' tool to send to a specific chat channel."""
+
+ def _build_shared_memory(self) -> str:
+ """Build memory context from DeepTutor's shared memory (PROFILE + SUMMARY).
+
+ SOUL.md and other per-bot files are loaded from the workspace via
+ BOOTSTRAP_FILES, so they are NOT read from the shared memory dir.
+ """
+ if not self.shared_memory_dir:
+ return ""
+ parts: list[str] = []
+
+ profile = self._read_shared_file("PROFILE.md")
+ if profile:
+ parts.append(f"## User Profile\n{profile}")
+
+ summary = self._read_shared_file("SUMMARY.md")
+ if summary:
+ parts.append(f"## Learning Context\n{summary}")
+
+ if not parts:
+ return ""
+ return "# Memory\n\n" + "\n\n".join(parts)
+
+ def _read_shared_file(self, filename: str) -> str:
+ if not self.shared_memory_dir:
+ return ""
+ path = self.shared_memory_dir / filename
+ if not path.exists():
+ return ""
+ try:
+ return path.read_text(encoding="utf-8").strip()
+ except Exception:
+ return ""
+
+ @staticmethod
+ def _build_runtime_context(channel: str | None, chat_id: str | None) -> str:
+ """Build untrusted runtime metadata block for injection before the user message."""
+ now = datetime.now().strftime("%Y-%m-%d %H:%M (%A)")
+ tz = time.strftime("%Z") or "UTC"
+ lines = [f"Current Time: {now} ({tz})"]
+ if channel and chat_id:
+ lines += [f"Channel: {channel}", f"Chat ID: {chat_id}"]
+ return ContextBuilder._RUNTIME_CONTEXT_TAG + "\n" + "\n".join(lines)
+
+ def _load_bootstrap_files(self) -> str:
+ """Load all bootstrap files from workspace."""
+ parts = []
+
+ for filename in self.BOOTSTRAP_FILES:
+ file_path = self.workspace / filename
+ if file_path.exists():
+ content = file_path.read_text(encoding="utf-8")
+ parts.append(f"## {filename}\n\n{content}")
+
+ return "\n\n".join(parts) if parts else ""
+
+ def build_messages(
+ self,
+ history: list[dict[str, Any]],
+ current_message: str,
+ skill_names: list[str] | None = None,
+ media: list[str] | None = None,
+ channel: str | None = None,
+ chat_id: str | None = None,
+ ) -> list[dict[str, Any]]:
+ """Build the complete message list for an LLM call."""
+ runtime_ctx = self._build_runtime_context(channel, chat_id)
+ user_content = self._build_user_content(current_message, media)
+
+ # Merge runtime context and user content into a single user message
+ # to avoid consecutive same-role messages that some providers reject.
+ if isinstance(user_content, str):
+ merged = f"{runtime_ctx}\n\n{user_content}"
+ else:
+ merged = [{"type": "text", "text": runtime_ctx}] + user_content
+
+ return [
+ {"role": "system", "content": self.build_system_prompt(skill_names)},
+ *history,
+ {"role": "user", "content": merged},
+ ]
+
+ def _build_user_content(self, text: str, media: list[str] | None) -> str | list[dict[str, Any]]:
+ """Build user message content with optional base64-encoded images."""
+ if not media:
+ return text
+
+ images = []
+ for path in media:
+ p = Path(path)
+ if not p.is_file():
+ continue
+ raw = p.read_bytes()
+ # Detect real MIME type from magic bytes; fallback to filename guess
+ mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]
+ if not mime or not mime.startswith("image/"):
+ continue
+ b64 = base64.b64encode(raw).decode()
+ images.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}})
+
+ if not images:
+ return text
+ return images + [{"type": "text", "text": text}]
+
+ def add_tool_result(
+ self, messages: list[dict[str, Any]],
+ tool_call_id: str, tool_name: str, result: str,
+ ) -> list[dict[str, Any]]:
+ """Add a tool result to the message list."""
+ messages.append({"role": "tool", "tool_call_id": tool_call_id, "name": tool_name, "content": result})
+ return messages
+
+ def add_assistant_message(
+ self, messages: list[dict[str, Any]],
+ content: str | None,
+ tool_calls: list[dict[str, Any]] | None = None,
+ reasoning_content: str | None = None,
+ thinking_blocks: list[dict] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Add an assistant message to the message list."""
+ messages.append(build_assistant_message(
+ content,
+ tool_calls=tool_calls,
+ reasoning_content=reasoning_content,
+ thinking_blocks=thinking_blocks,
+ ))
+ return messages
diff --git a/deeptutor/tutorbot/agent/loop.py b/deeptutor/tutorbot/agent/loop.py
new file mode 100644
index 000000000..a9bfb8491
--- /dev/null
+++ b/deeptutor/tutorbot/agent/loop.py
@@ -0,0 +1,700 @@
+"""Agent loop: the core processing engine."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import re
+import sys
+from contextlib import AsyncExitStack
+from datetime import datetime
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Awaitable, Callable
+
+from loguru import logger
+
+from deeptutor.tutorbot.agent.context import ContextBuilder
+from deeptutor.tutorbot.agent.memory import MemoryConsolidator
+from deeptutor.tutorbot.agent.team import TeamManager
+from deeptutor.tutorbot.agent.team.tools import TeamTool
+from deeptutor.tutorbot.agent.subagent import SubagentManager
+from deeptutor.tutorbot.agent.tools.cron import CronTool
+from deeptutor.tutorbot.agent.tools.message import MessageTool
+from deeptutor.tutorbot.agent.tools.registry import ToolRegistry, build_base_tools
+from deeptutor.tutorbot.agent.tools.spawn import SpawnTool
+from deeptutor.tutorbot.bus.events import InboundMessage, OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.providers.base import LLMProvider
+from deeptutor.tutorbot.session.manager import Session, SessionManager
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.config.schema import ChannelsConfig, ExecToolConfig, WebSearchConfig
+ from deeptutor.tutorbot.cron.service import CronService
+
+
+class AgentLoop:
+ """
+ The agent loop is the core processing engine.
+
+ It:
+ 1. Receives messages from the bus
+ 2. Builds context with history, memory, skills
+ 3. Calls the LLM
+ 4. Executes tool calls
+ 5. Sends responses back
+ """
+
+ _TOOL_RESULT_MAX_CHARS = 16_000
+
+ def __init__(
+ self,
+ bus: MessageBus,
+ provider: LLMProvider,
+ workspace: Path,
+ model: str | None = None,
+ max_iterations: int = 40,
+ context_window_tokens: int = 65_536,
+ web_search_config: WebSearchConfig | None = None,
+ web_proxy: str | None = None,
+ exec_config: ExecToolConfig | None = None,
+ team_max_workers: int = 5,
+ team_worker_max_iterations: int = 25,
+ cron_service: CronService | None = None,
+ restrict_to_workspace: bool = False,
+ session_manager: SessionManager | None = None,
+ mcp_servers: dict | None = None,
+ channels_config: ChannelsConfig | None = None,
+ shared_memory_dir: Path | None = None,
+ ):
+ from deeptutor.tutorbot.config.schema import ExecToolConfig, WebSearchConfig
+
+ self.bus = bus
+ self.channels_config = channels_config
+ self.provider = provider
+ self.workspace = workspace
+ self.model = model or provider.get_default_model()
+ self.max_iterations = max_iterations
+ self.context_window_tokens = context_window_tokens
+ self.web_search_config = web_search_config or WebSearchConfig()
+ self.web_proxy = web_proxy
+ self.exec_config = exec_config or ExecToolConfig()
+ self.cron_service = cron_service
+ self.restrict_to_workspace = restrict_to_workspace
+ self._shared_memory_dir = shared_memory_dir
+
+ self.context = ContextBuilder(workspace, shared_memory_dir=shared_memory_dir)
+ self.sessions = session_manager or SessionManager(workspace)
+ self.tools = ToolRegistry()
+ self.subagents = SubagentManager(
+ provider=provider,
+ workspace=workspace,
+ bus=bus,
+ model=self.model,
+ web_search_config=self.web_search_config,
+ web_proxy=web_proxy,
+ exec_config=self.exec_config,
+ restrict_to_workspace=restrict_to_workspace,
+ )
+ self.team = TeamManager(
+ provider=provider,
+ workspace=workspace,
+ bus=bus,
+ sessions=self.sessions,
+ model=self.model,
+ temperature=provider.generation.temperature,
+ max_tokens=provider.generation.max_tokens,
+ reasoning_effort=provider.generation.reasoning_effort,
+ web_search_config=self.web_search_config,
+ web_proxy=web_proxy,
+ exec_config=self.exec_config,
+ restrict_to_workspace=restrict_to_workspace,
+ max_workers=team_max_workers,
+ worker_max_iterations=team_worker_max_iterations,
+ )
+
+ self._running = False
+ self._mcp_servers = mcp_servers or {}
+ self._mcp_stack: AsyncExitStack | None = None
+ self._mcp_connected = False
+ self._mcp_connecting = False
+ self._active_tasks: dict[str, list[asyncio.Task]] = {} # session_key -> tasks
+ self._processing_lock = asyncio.Lock()
+ self.memory_consolidator = MemoryConsolidator(
+ workspace=workspace,
+ provider=provider,
+ model=self.model,
+ sessions=self.sessions,
+ context_window_tokens=context_window_tokens,
+ build_messages=self.context.build_messages,
+ get_tool_definitions=self.tools.get_definitions,
+ shared_memory_dir=shared_memory_dir,
+ )
+ self._register_default_tools()
+
+ def _register_default_tools(self) -> None:
+ """Register the default set of tools."""
+ self.tools = build_base_tools(
+ workspace=self.workspace,
+ exec_config=self.exec_config,
+ web_search_config=self.web_search_config,
+ web_proxy=self.web_proxy,
+ restrict_to_workspace=self.restrict_to_workspace,
+ )
+ self.tools.register(MessageTool(send_callback=self.bus.publish_outbound))
+ self.tools.register(SpawnTool(manager=self.subagents))
+ self.tools.register(TeamTool(manager=self.team))
+ if self.cron_service:
+ self.tools.register(CronTool(self.cron_service))
+
+ from deeptutor.tutorbot.agent.tools.deeptutor_tools import (
+ BrainstormAdapterTool,
+ CodeExecutionAdapterTool,
+ PaperSearchAdapterTool,
+ RAGAdapterTool,
+ ReasonAdapterTool,
+ )
+ for tool_cls in (BrainstormAdapterTool, RAGAdapterTool,
+ CodeExecutionAdapterTool, ReasonAdapterTool,
+ PaperSearchAdapterTool):
+ self.tools.register(tool_cls())
+
+ async def _connect_mcp(self) -> None:
+ """Connect to configured MCP servers (one-time, lazy)."""
+ if self._mcp_connected or self._mcp_connecting or not self._mcp_servers:
+ return
+ self._mcp_connecting = True
+ from deeptutor.tutorbot.agent.tools.mcp import connect_mcp_servers
+ try:
+ self._mcp_stack = AsyncExitStack()
+ await self._mcp_stack.__aenter__()
+ await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack)
+ self._mcp_connected = True
+ except BaseException as e:
+ logger.error("Failed to connect MCP servers (will retry next message): {}", e)
+ if self._mcp_stack:
+ try:
+ await self._mcp_stack.aclose()
+ except Exception:
+ pass
+ self._mcp_stack = None
+ finally:
+ self._mcp_connecting = False
+
+ def _set_tool_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None:
+ """Update context for all tools that need routing info."""
+ for name in ("message", "spawn", "cron", "team"):
+ if tool := self.tools.get(name):
+ if hasattr(tool, "set_context"):
+ tool.set_context(channel, chat_id, *([message_id] if name == "message" else []))
+
+ @staticmethod
+ def _strip_think(text: str | None) -> str | None:
+ """Remove <think>…</think> blocks that some models embed in content."""
+ if not text:
+ return None
+ return re.sub(r"<think>[\s\S]*?</think>", "", text).strip() or None
+
+ @staticmethod
+ def _tool_hint(tool_calls: list) -> str:
+ """Format tool calls as concise hint, e.g. 'web_search("query")'."""
+ def _fmt(tc):
+ args = (tc.arguments[0] if isinstance(tc.arguments, list) else tc.arguments) or {}
+ val = next(iter(args.values()), None) if isinstance(args, dict) else None
+ if not isinstance(val, str):
+ return tc.name
+ return f'{tc.name}("{val[:40]}…")' if len(val) > 40 else f'{tc.name}("{val}")'
+ return ", ".join(_fmt(tc) for tc in tool_calls)
+
+ async def _run_agent_loop(
+ self,
+ initial_messages: list[dict],
+ on_progress: Callable[..., Awaitable[None]] | None = None,
+ ) -> tuple[str | None, list[str], list[dict]]:
+ """Run the agent iteration loop."""
+ messages = initial_messages
+ iteration = 0
+ final_content = None
+ tools_used: list[str] = []
+
+ while iteration < self.max_iterations:
+ iteration += 1
+
+ tool_defs = self.tools.get_definitions()
+
+ response = await self.provider.chat_with_retry(
+ messages=messages,
+ tools=tool_defs,
+ model=self.model,
+ )
+
+ if response.has_tool_calls:
+ if on_progress:
+ thought = self._strip_think(response.content)
+ if thought:
+ await on_progress(thought)
+ await on_progress(self._tool_hint(response.tool_calls), tool_hint=True)
+
+ tool_call_dicts = [
+ tc.to_openai_tool_call()
+ for tc in response.tool_calls
+ ]
+ messages = self.context.add_assistant_message(
+ messages, response.content, tool_call_dicts,
+ reasoning_content=response.reasoning_content,
+ thinking_blocks=response.thinking_blocks,
+ )
+
+ for tool_call in response.tool_calls:
+ tools_used.append(tool_call.name)
+ args_str = json.dumps(tool_call.arguments, ensure_ascii=False)
+ logger.info("Tool call: {}({})", tool_call.name, args_str[:200])
+ result = await self.tools.execute(tool_call.name, tool_call.arguments)
+ messages = self.context.add_tool_result(
+ messages, tool_call.id, tool_call.name, result
+ )
+ else:
+ clean = self._strip_think(response.content)
+ # Don't persist error responses to session history — they can
+ # poison the context and cause permanent 400 loops (#1303).
+ if response.finish_reason == "error":
+ logger.error("LLM returned error: {}", (clean or "")[:200])
+ final_content = clean or "Sorry, I encountered an error calling the AI model."
+ break
+ messages = self.context.add_assistant_message(
+ messages, clean, reasoning_content=response.reasoning_content,
+ thinking_blocks=response.thinking_blocks,
+ )
+ final_content = clean
+ break
+
+ if final_content is None and iteration >= self.max_iterations:
+ logger.warning("Max iterations ({}) reached", self.max_iterations)
+ final_content = (
+ f"I reached the maximum number of tool call iterations ({self.max_iterations}) "
+ "without completing the task. You can try breaking the task into smaller steps."
+ )
+
+ return final_content, tools_used, messages
+
+ async def run(self) -> None:
+ """Run the agent loop, dispatching messages as tasks to stay responsive to /stop."""
+ self._running = True
+ await self._connect_mcp()
+ logger.info("Agent loop started")
+
+ while self._running:
+ try:
+ msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
+ except asyncio.TimeoutError:
+ continue
+ except Exception as e:
+ logger.warning("Error consuming inbound message: {}, continuing...", e)
+ continue
+
+ cmd = msg.content.strip().lower()
+ if cmd == "/stop":
+ await self._handle_stop(msg)
+ elif cmd == "/restart":
+ await self._handle_restart(msg)
+ else:
+ task = asyncio.create_task(self._dispatch(msg))
+ self._active_tasks.setdefault(msg.session_key, []).append(task)
+ task.add_done_callback(lambda t, k=msg.session_key: self._active_tasks.get(k, []) and self._active_tasks[k].remove(t) if t in self._active_tasks.get(k, []) else None)
+
+ async def _handle_stop(self, msg: InboundMessage) -> None:
+ """Cancel all active tasks and subagents for the session."""
+ tasks = self._active_tasks.pop(msg.session_key, [])
+ cancelled = sum(1 for t in tasks if not t.done() and t.cancel())
+ for t in tasks:
+ try:
+ await t
+ except (asyncio.CancelledError, Exception):
+ pass
+ sub_cancelled = await self.subagents.cancel_by_session(msg.session_key)
+ team_cancelled = await self.team.cancel_by_session(msg.session_key)
+ if team_cancelled:
+ session = self.sessions.get_or_create(msg.session_key)
+ session.metadata.pop("nano_team_active", None)
+ self.sessions.save(session)
+ total = cancelled + sub_cancelled + team_cancelled
+ content = f"Stopped {total} task(s)." if total else "No active task to stop."
+ await self.bus.publish_outbound(OutboundMessage(
+ channel=msg.channel, chat_id=msg.chat_id, content=content,
+ ))
+
+ async def _handle_restart(self, msg: InboundMessage) -> None:
+ """Restart the process in-place via os.execv."""
+ await self.bus.publish_outbound(OutboundMessage(
+ channel=msg.channel, chat_id=msg.chat_id, content="Restarting...",
+ ))
+
+ async def _do_restart():
+ await asyncio.sleep(1)
+ # Use original sys.argv to preserve entry point (tutorbot runs in-process)
+ os.execv(sys.executable, [sys.executable] + sys.argv)
+
+ asyncio.create_task(_do_restart())
+
+ async def _dispatch(self, msg: InboundMessage) -> None:
+ """Process a message under the global lock."""
+ async with self._processing_lock:
+ try:
+ response = await self._process_message(msg)
+ if response is not None:
+ await self.bus.publish_outbound(response)
+ elif msg.channel == "cli":
+ await self.bus.publish_outbound(OutboundMessage(
+ channel=msg.channel, chat_id=msg.chat_id,
+ content="", metadata=msg.metadata or {},
+ ))
+ except asyncio.CancelledError:
+ logger.info("Task cancelled for session {}", msg.session_key)
+ raise
+ except Exception:
+ logger.exception("Error processing message for session {}", msg.session_key)
+ await self.bus.publish_outbound(OutboundMessage(
+ channel=msg.channel, chat_id=msg.chat_id,
+ content="Sorry, I encountered an error.",
+ ))
+
+ async def close_mcp(self) -> None:
+ """Close MCP connections."""
+ if self._mcp_stack:
+ try:
+ await self._mcp_stack.aclose()
+ except (RuntimeError, BaseExceptionGroup):
+ pass # MCP SDK cancel scope cleanup is noisy but harmless
+ self._mcp_stack = None
+
+ def stop(self) -> None:
+ """Stop the agent loop."""
+ self._running = False
+ logger.info("Agent loop stopping")
+
+ async def _process_message(
+ self,
+ msg: InboundMessage,
+ session_key: str | None = None,
+ on_progress: Callable[[str], Awaitable[None]] | None = None,
+ ) -> OutboundMessage | None:
+ """Process a single inbound message and return the response."""
+ # System messages: parse origin from chat_id ("channel:chat_id")
+ if msg.channel == "system":
+ channel, chat_id = (msg.chat_id.split(":", 1) if ":" in msg.chat_id
+ else ("cli", msg.chat_id))
+ logger.info("Processing system message from {}", msg.sender_id)
+ key = f"{channel}:{chat_id}"
+ session = self.sessions.get_or_create(key)
+ await self.memory_consolidator.maybe_consolidate_by_tokens(session)
+ self._set_tool_context(channel, chat_id, msg.metadata.get("message_id"))
+ history = session.get_history(max_messages=0)
+ messages = self.context.build_messages(
+ history=history,
+ current_message=msg.content, channel=channel, chat_id=chat_id,
+ )
+ final_content, _, all_msgs = await self._run_agent_loop(messages)
+ self._save_turn(session, all_msgs, 1 + len(history))
+ self.sessions.save(session)
+ await self.memory_consolidator.maybe_consolidate_by_tokens(session)
+ return OutboundMessage(channel=channel, chat_id=chat_id,
+ content=final_content or "Background task completed.")
+
+ preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content
+ logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview)
+
+ key = session_key or msg.session_key
+ session = self.sessions.get_or_create(key)
+
+ # Slash commands
+ raw = msg.content.strip()
+ cmd = raw.lower()
+ if cmd == "/new":
+ try:
+ if not await self.memory_consolidator.archive_unconsolidated(session):
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content="Memory archival failed, session not cleared. Please try again.",
+ )
+ except Exception:
+ logger.exception("/new archival failed for {}", session.key)
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content="Memory archival failed, session not cleared. Please try again.",
+ )
+
+ session.clear()
+ session.metadata.pop("nano_team_active", None)
+ self.sessions.save(session)
+ self.sessions.invalidate(session.key)
+ return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id,
+ content="New session started.")
+ if cmd == "/help":
+ lines = [
+ "🐈 TutorBot commands:",
+ "/new — Start a new conversation",
+ "/stop — Stop the current task",
+ "/restart — Restart the bot",
+ "/team <goal> — Start or instruct nano team mode",
+ "/team status — Show nano team state",
+ "/team log [n] — Show detailed collaboration logs (default 20)",
+ "/team approve <task_id> — Approve a pending task",
+ "/team reject <task_id> <reason> — Reject a pending task",
+ "/team manual <task_id> <instruction> — Send change request",
+ "/team stop — Stop nano team mode",
+ "/btw <instruction> — Async side task via single subagent",
+ "/help — Show available commands",
+ ]
+ return OutboundMessage(
+ channel=msg.channel, chat_id=msg.chat_id, content="\n".join(lines),
+ )
+ current_message = msg.content
+ if cmd.startswith("/btw"):
+ arg = raw[4:].strip()
+ if not arg:
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content="Usage: /btw <instruction>",
+ )
+ started = await self.subagents.spawn(
+ task=arg,
+ label="btw",
+ origin_channel=msg.channel,
+ origin_chat_id=msg.chat_id,
+ session_key=key,
+ )
+ return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content=started)
+
+ if cmd == "/team":
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=(
+ "Usage:\n"
+ "/team <goal>\n"
+ "/team status\n"
+ "/team log [n]\n"
+ "/team approve <task_id>\n"
+ "/team reject <task_id> <reason>\n"
+ "/team manual <task_id> <instruction>\n"
+ "/team stop"
+ ),
+ )
+
+ if cmd.startswith("/teams "):
+ cmd = "/team " + raw[7:].strip().lower()
+ raw = "/team " + raw[7:].strip()
+
+ if cmd.startswith("/team "):
+ instruction = raw[6:].strip()
+ parts = instruction.split(maxsplit=2)
+ lowered = (parts[0] if parts else "").lower()
+ if lowered == "status":
+ content = self.team.status_text(key)
+ session.metadata["nano_team_active"] = bool(self.team.has_unfinished_run(key))
+ self.sessions.save(session)
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=content,
+ metadata={"team_text": True},
+ )
+ if lowered == "log":
+ n = 20
+ if len(parts) > 1:
+ try:
+ n = max(1, min(200, int(parts[1])))
+ except (TypeError, ValueError):
+ n = 20
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=self.team.log_text(key, n=n),
+ metadata={"team_text": True},
+ )
+ if lowered == "stop":
+ if msg.channel == "cli":
+ content = await self.team.stop_mode(key, with_snapshot=True)
+ else:
+ content = await self.team.stop_mode(key)
+ session.metadata.pop("nano_team_active", None)
+ self.sessions.save(session)
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=content,
+ metadata={"team_text": True},
+ )
+ if lowered == "approve":
+ task_id = parts[1] if len(parts) > 1 else ""
+ if not task_id:
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content="Usage: /team approve <task_id>",
+ )
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=self.team.approve_for_session(key, task_id),
+ metadata={"team_text": True},
+ )
+ if lowered == "reject":
+ task_id = parts[1] if len(parts) > 1 else ""
+ reason = parts[2] if len(parts) > 2 else ""
+ if not task_id or not reason.strip():
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content="Usage: /team reject <task_id> <reason>",
+ )
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=self.team.reject_for_session(key, task_id, reason.strip()),
+ metadata={"team_text": True},
+ )
+ if lowered == "manual":
+ task_id = parts[1] if len(parts) > 1 else ""
+ instruction_text = parts[2] if len(parts) > 2 else ""
+ if not task_id or not instruction_text.strip():
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content="Usage: /team manual <task_id> <instruction>",
+ )
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=self.team.request_changes_for_session(key, task_id, instruction_text.strip()),
+ metadata={"team_text": True},
+ )
+
+ content = await self.team.start_or_route_goal(key, instruction)
+ session.metadata["nano_team_active"] = self.team.is_active(key)
+ self.sessions.save(session)
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=content,
+ metadata={"team_text": True},
+ )
+
+ if session.metadata.get("nano_team_active"):
+ if not self.team.is_active(key):
+ session.metadata.pop("nano_team_active", None)
+ self.sessions.save(session)
+ else:
+ if msg.channel != "cli" and self.team.has_pending_approval(key):
+ approval_reply = self.team.handle_approval_reply(key, raw)
+ if approval_reply:
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=approval_reply,
+ metadata={"team_text": True},
+ )
+ return OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=(
+ "Team mode is active. Supported input:\n"
+ "- /team <instruction|status|log|approve|reject|manual|stop>\n"
+ "- /btw <instruction>"
+ ),
+ )
+
+ await self.memory_consolidator.maybe_consolidate_by_tokens(session)
+
+ self._set_tool_context(msg.channel, msg.chat_id, msg.metadata.get("message_id"))
+ if message_tool := self.tools.get("message"):
+ if isinstance(message_tool, MessageTool):
+ message_tool.start_turn()
+
+ history = session.get_history(max_messages=0)
+ initial_messages = self.context.build_messages(
+ history=history,
+ current_message=current_message,
+ media=msg.media if msg.media else None,
+ channel=msg.channel, chat_id=msg.chat_id,
+ )
+
+ async def _bus_progress(content: str, *, tool_hint: bool = False) -> None:
+ meta = dict(msg.metadata or {})
+ meta["_progress"] = True
+ meta["_tool_hint"] = tool_hint
+ await self.bus.publish_outbound(OutboundMessage(
+ channel=msg.channel, chat_id=msg.chat_id, content=content, metadata=meta,
+ ))
+
+ final_content, _, all_msgs = await self._run_agent_loop(
+ initial_messages, on_progress=on_progress or _bus_progress,
+ )
+
+ if final_content is None:
+ final_content = "I've completed processing but have no response to give."
+
+ self._save_turn(session, all_msgs, 1 + len(history))
+ self.sessions.save(session)
+ await self.memory_consolidator.maybe_consolidate_by_tokens(session)
+
+ if (mt := self.tools.get("message")) and isinstance(mt, MessageTool) and mt._sent_in_turn:
+ return None
+
+ preview = final_content[:120] + "..." if len(final_content) > 120 else final_content
+ logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview)
+ return OutboundMessage(
+ channel=msg.channel, chat_id=msg.chat_id, content=final_content,
+ metadata=msg.metadata or {},
+ )
+
+ def _save_turn(self, session: Session, messages: list[dict], skip: int) -> None:
+ """Save new-turn messages into session, truncating large tool results."""
+ for m in messages[skip:]:
+ entry = dict(m)
+ role, content = entry.get("role"), entry.get("content")
+ if role == "assistant" and not content and not entry.get("tool_calls"):
+ continue # skip empty assistant messages — they poison session context
+ if role == "tool" and isinstance(content, str) and len(content) > self._TOOL_RESULT_MAX_CHARS:
+ entry["content"] = content[:self._TOOL_RESULT_MAX_CHARS] + "\n... (truncated)"
+ elif role == "user":
+ if isinstance(content, str) and content.startswith(ContextBuilder._RUNTIME_CONTEXT_TAG):
+ # Strip the runtime-context prefix, keep only the user text.
+ parts = content.split("\n\n", 1)
+ if len(parts) > 1 and parts[1].strip():
+ entry["content"] = parts[1]
+ else:
+ continue
+ if isinstance(content, list):
+ filtered = []
+ for c in content:
+ if c.get("type") == "text" and isinstance(c.get("text"), str) and c["text"].startswith(ContextBuilder._RUNTIME_CONTEXT_TAG):
+ continue # Strip runtime context from multimodal messages
+ if (c.get("type") == "image_url"
+ and c.get("image_url", {}).get("url", "").startswith("data:image/")):
+ filtered.append({"type": "text", "text": "[image]"})
+ else:
+ filtered.append(c)
+ if not filtered:
+ continue
+ entry["content"] = filtered
+ entry.setdefault("timestamp", datetime.now().isoformat())
+ session.messages.append(entry)
+ session.updated_at = datetime.now()
+
+ async def process_direct(
+ self,
+ content: str,
+ session_key: str = "cli:direct",
+ channel: str = "cli",
+ chat_id: str = "direct",
+ on_progress: Callable[[str], Awaitable[None]] | None = None,
+ ) -> str:
+ """Process a message directly (for CLI or cron usage)."""
+ await self._connect_mcp()
+ msg = InboundMessage(channel=channel, sender_id="user", chat_id=chat_id, content=content)
+ response = await self._process_message(msg, session_key=session_key, on_progress=on_progress)
+ return response.content if response else ""
diff --git a/deeptutor/tutorbot/agent/memory.py b/deeptutor/tutorbot/agent/memory.py
new file mode 100644
index 000000000..e3f8054de
--- /dev/null
+++ b/deeptutor/tutorbot/agent/memory.py
@@ -0,0 +1,368 @@
+"""Memory system for persistent agent memory."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import weakref
+from datetime import datetime
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Callable
+
+from loguru import logger
+
+from deeptutor.tutorbot.utils.helpers import ensure_dir, estimate_message_tokens, estimate_prompt_tokens_chain
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.providers.base import LLMProvider
+ from deeptutor.tutorbot.session.manager import Session, SessionManager
+
+
+_SAVE_MEMORY_TOOL = [
+ {
+ "type": "function",
+ "function": {
+ "name": "save_memory",
+ "description": "Save the memory consolidation result to persistent storage.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "history_entry": {
+ "type": "string",
+ "description": "A paragraph summarizing key events/decisions/topics. "
+ "Start with [YYYY-MM-DD HH:MM]. Include detail useful for grep search.",
+ },
+ "memory_update": {
+ "type": "string",
+ "description": "Full updated long-term memory as markdown. Include all existing "
+ "facts plus new ones. Return unchanged if nothing new.",
+ },
+ },
+ "required": ["history_entry", "memory_update"],
+ },
+ },
+ }
+]
+
+
+def _ensure_text(value: Any) -> str:
+ """Normalize tool-call payload values to text for file storage."""
+ return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
+
+
+def _normalize_save_memory_args(args: Any) -> dict[str, Any] | None:
+ """Normalize provider tool-call arguments to the expected dict shape."""
+ if isinstance(args, str):
+ args = json.loads(args)
+ if isinstance(args, list):
+ return args[0] if args and isinstance(args[0], dict) else None
+ return args if isinstance(args, dict) else None
+
+_TOOL_CHOICE_ERROR_MARKERS = (
+ "tool_choice",
+ "toolchoice",
+ "does not support",
+ 'should be ["none", "auto"]',
+)
+
+
+def _is_tool_choice_unsupported(content: str | None) -> bool:
+ """Detect provider errors caused by forced tool_choice being unsupported."""
+ text = (content or "").lower()
+ return any(m in text for m in _TOOL_CHOICE_ERROR_MARKERS)
+
+
+class MemoryStore:
+ """Two-layer memory: long-term facts + grep-searchable history log.
+
+ Reads/writes go to ``data/memory/`` (shared with DeepTutor) — PROFILE.md
+ for long-term facts, SUMMARY.md for history. Standalone fallback uses
+ workspace/memory/MEMORY.md + HISTORY.md when no shared dir is given.
+ """
+
+ _MAX_FAILURES_BEFORE_RAW_ARCHIVE = 3
+
+ def __init__(self, workspace: Path, *, shared_memory_dir: Path | None = None):
+ if shared_memory_dir:
+ self.memory_dir = ensure_dir(shared_memory_dir)
+ self.memory_file = self.memory_dir / "PROFILE.md"
+ self.history_file = self.memory_dir / "SUMMARY.md"
+ else:
+ self.memory_dir = ensure_dir(workspace / "memory")
+ self.memory_file = self.memory_dir / "MEMORY.md"
+ self.history_file = self.memory_dir / "HISTORY.md"
+ self._consecutive_failures = 0
+
+ def read_long_term(self) -> str:
+ if self.memory_file.exists():
+ return self.memory_file.read_text(encoding="utf-8")
+ return ""
+
+ def write_long_term(self, content: str) -> None:
+ self.memory_file.write_text(content, encoding="utf-8")
+
+ def append_history(self, entry: str) -> None:
+ with open(self.history_file, "a", encoding="utf-8") as f:
+ f.write(entry.rstrip() + "\n\n")
+
+ def get_memory_context(self) -> str:
+ long_term = self.read_long_term()
+ return f"## Long-term Memory\n{long_term}" if long_term else ""
+
+ @staticmethod
+ def _format_messages(messages: list[dict]) -> str:
+ lines = []
+ for message in messages:
+ if not message.get("content"):
+ continue
+ tools = f" [tools: {', '.join(message['tools_used'])}]" if message.get("tools_used") else ""
+ lines.append(
+ f"[{message.get('timestamp', '?')[:16]}] {message['role'].upper()}{tools}: {message['content']}"
+ )
+ return "\n".join(lines)
+
+ async def consolidate(
+ self,
+ messages: list[dict],
+ provider: LLMProvider,
+ model: str,
+ ) -> bool:
+ """Consolidate the provided message chunk into MEMORY.md + HISTORY.md."""
+ if not messages:
+ return True
+
+ current_memory = self.read_long_term()
+ prompt = f"""Process this conversation and call the save_memory tool with your consolidation.
+
+## Current Long-term Memory
+{current_memory or "(empty)"}
+
+## Conversation to Process
+{self._format_messages(messages)}"""
+
+ chat_messages = [
+ {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."},
+ {"role": "user", "content": prompt},
+ ]
+
+ try:
+ forced = {"type": "function", "function": {"name": "save_memory"}}
+ response = await provider.chat_with_retry(
+ messages=chat_messages,
+ tools=_SAVE_MEMORY_TOOL,
+ model=model,
+ tool_choice=forced,
+ )
+
+ if response.finish_reason == "error" and _is_tool_choice_unsupported(
+ response.content
+ ):
+ logger.warning("Forced tool_choice unsupported, retrying with auto")
+ response = await provider.chat_with_retry(
+ messages=chat_messages,
+ tools=_SAVE_MEMORY_TOOL,
+ model=model,
+ tool_choice="auto",
+ )
+
+ if not response.has_tool_calls:
+ logger.warning(
+ "Memory consolidation: LLM did not call save_memory "
+ "(finish_reason={}, content_len={}, content_preview={})",
+ response.finish_reason,
+ len(response.content or ""),
+ (response.content or "")[:200],
+ )
+ return self._fail_or_raw_archive(messages)
+
+ args = _normalize_save_memory_args(response.tool_calls[0].arguments)
+ if args is None:
+ logger.warning("Memory consolidation: unexpected save_memory arguments")
+ return self._fail_or_raw_archive(messages)
+
+ if "history_entry" not in args or "memory_update" not in args:
+ logger.warning("Memory consolidation: save_memory payload missing required fields")
+ return self._fail_or_raw_archive(messages)
+
+ entry = args["history_entry"]
+ update = args["memory_update"]
+
+ if entry is None or update is None:
+ logger.warning("Memory consolidation: save_memory payload contains null required fields")
+ return self._fail_or_raw_archive(messages)
+
+ entry = _ensure_text(entry).strip()
+ if not entry:
+ logger.warning("Memory consolidation: history_entry is empty after normalization")
+ return self._fail_or_raw_archive(messages)
+
+ self.append_history(entry)
+ update = _ensure_text(update)
+ if update != current_memory:
+ self.write_long_term(update)
+
+ self._consecutive_failures = 0
+ logger.info("Memory consolidation done for {} messages", len(messages))
+ return True
+ except Exception:
+ logger.exception("Memory consolidation failed")
+ return self._fail_or_raw_archive(messages)
+
+ def _fail_or_raw_archive(self, messages: list[dict]) -> bool:
+ """Increment failure count; after threshold, raw-archive messages and return True."""
+ self._consecutive_failures += 1
+ if self._consecutive_failures < self._MAX_FAILURES_BEFORE_RAW_ARCHIVE:
+ return False
+ self._raw_archive(messages)
+ self._consecutive_failures = 0
+ return True
+
+ def _raw_archive(self, messages: list[dict]) -> None:
+ """Fallback: dump raw messages to HISTORY.md without LLM summarization."""
+ ts = datetime.now().strftime("%Y-%m-%d %H:%M")
+ self.append_history(
+ f"[{ts}] [RAW] {len(messages)} messages\n"
+ f"{self._format_messages(messages)}"
+ )
+ logger.warning(
+ "Memory consolidation degraded: raw-archived {} messages", len(messages)
+ )
+
+
+class MemoryConsolidator:
+ """Owns consolidation policy, locking, and session offset updates."""
+
+ _MAX_CONSOLIDATION_ROUNDS = 5
+
+ def __init__(
+ self,
+ workspace: Path,
+ provider: LLMProvider,
+ model: str,
+ sessions: SessionManager,
+ context_window_tokens: int,
+ build_messages: Callable[..., list[dict[str, Any]]],
+ get_tool_definitions: Callable[[], list[dict[str, Any]]],
+ shared_memory_dir: Path | None = None,
+ ):
+ self.store = MemoryStore(workspace, shared_memory_dir=shared_memory_dir)
+ self.provider = provider
+ self.model = model
+ self.sessions = sessions
+ self.context_window_tokens = context_window_tokens
+ self._build_messages = build_messages
+ self._get_tool_definitions = get_tool_definitions
+ self._locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
+
+ def get_lock(self, session_key: str) -> asyncio.Lock:
+ """Return the shared consolidation lock for one session."""
+ return self._locks.setdefault(session_key, asyncio.Lock())
+
+ async def consolidate_messages(self, messages: list[dict[str, object]]) -> bool:
+ """Archive a selected message chunk into persistent memory."""
+ return await self.store.consolidate(messages, self.provider, self.model)
+
+ def pick_consolidation_boundary(
+ self,
+ session: Session,
+ tokens_to_remove: int,
+ ) -> tuple[int, int] | None:
+ """Pick a user-turn boundary that removes enough old prompt tokens."""
+ start = session.last_consolidated
+ if start >= len(session.messages) or tokens_to_remove <= 0:
+ return None
+
+ removed_tokens = 0
+ last_boundary: tuple[int, int] | None = None
+ for idx in range(start, len(session.messages)):
+ message = session.messages[idx]
+ if idx > start and message.get("role") == "user":
+ last_boundary = (idx, removed_tokens)
+ if removed_tokens >= tokens_to_remove:
+ return last_boundary
+ removed_tokens += estimate_message_tokens(message)
+
+ return last_boundary
+
+ def estimate_session_prompt_tokens(self, session: Session) -> tuple[int, str]:
+ """Estimate current prompt size for the normal session history view."""
+ history = session.get_history(max_messages=0)
+ channel, chat_id = (session.key.split(":", 1) if ":" in session.key else (None, None))
+ probe_messages = self._build_messages(
+ history=history,
+ current_message="[token-probe]",
+ channel=channel,
+ chat_id=chat_id,
+ )
+ return estimate_prompt_tokens_chain(
+ self.provider,
+ self.model,
+ probe_messages,
+ self._get_tool_definitions(),
+ )
+
+ async def archive_unconsolidated(self, session: Session) -> bool:
+ """Archive the full unconsolidated tail for /new-style session rollover."""
+ lock = self.get_lock(session.key)
+ async with lock:
+ snapshot = session.messages[session.last_consolidated:]
+ if not snapshot:
+ return True
+ return await self.consolidate_messages(snapshot)
+
+ async def maybe_consolidate_by_tokens(self, session: Session) -> None:
+ """Loop: archive old messages until prompt fits within half the context window."""
+ if not session.messages or self.context_window_tokens <= 0:
+ return
+
+ lock = self.get_lock(session.key)
+ async with lock:
+ target = self.context_window_tokens // 2
+ estimated, source = self.estimate_session_prompt_tokens(session)
+ if estimated <= 0:
+ return
+ if estimated < self.context_window_tokens:
+ logger.debug(
+ "Token consolidation idle {}: {}/{} via {}",
+ session.key,
+ estimated,
+ self.context_window_tokens,
+ source,
+ )
+ return
+
+ for round_num in range(self._MAX_CONSOLIDATION_ROUNDS):
+ if estimated <= target:
+ return
+
+ boundary = self.pick_consolidation_boundary(session, max(1, estimated - target))
+ if boundary is None:
+ logger.debug(
+ "Token consolidation: no safe boundary for {} (round {})",
+ session.key,
+ round_num,
+ )
+ return
+
+ end_idx = boundary[0]
+ chunk = session.messages[session.last_consolidated:end_idx]
+ if not chunk:
+ return
+
+ logger.info(
+ "Token consolidation round {} for {}: {}/{} via {}, chunk={} msgs",
+ round_num,
+ session.key,
+ estimated,
+ self.context_window_tokens,
+ source,
+ len(chunk),
+ )
+ if not await self.consolidate_messages(chunk):
+ return
+ session.last_consolidated = end_idx
+ self.sessions.save(session)
+
+ estimated, source = self.estimate_session_prompt_tokens(session)
+ if estimated <= 0:
+ return
diff --git a/deeptutor/tutorbot/agent/skills.py b/deeptutor/tutorbot/agent/skills.py
new file mode 100644
index 000000000..4077f653d
--- /dev/null
+++ b/deeptutor/tutorbot/agent/skills.py
@@ -0,0 +1,228 @@
+"""Skills loader for agent capabilities."""
+
+import json
+import os
+import re
+import shutil
+from pathlib import Path
+
+# Default builtin skills directory (relative to this file)
+BUILTIN_SKILLS_DIR = Path(__file__).parent.parent / "skills"
+
+
+class SkillsLoader:
+ """
+ Loader for agent skills.
+
+ Skills are markdown files (SKILL.md) that teach the agent how to use
+ specific tools or perform certain tasks.
+ """
+
+ def __init__(self, workspace: Path, builtin_skills_dir: Path | None = None):
+ self.workspace = workspace
+ self.workspace_skills = workspace / "skills"
+ self.builtin_skills = builtin_skills_dir
+
+ def list_skills(self, filter_unavailable: bool = True) -> list[dict[str, str]]:
+ """
+ List all available skills.
+
+ Args:
+ filter_unavailable: If True, filter out skills with unmet requirements.
+
+ Returns:
+ List of skill info dicts with 'name', 'path', 'source'.
+ """
+ skills = []
+
+ # Workspace skills (highest priority)
+ if self.workspace_skills.exists():
+ for skill_dir in self.workspace_skills.iterdir():
+ if skill_dir.is_dir():
+ skill_file = skill_dir / "SKILL.md"
+ if skill_file.exists():
+ skills.append({"name": skill_dir.name, "path": str(skill_file), "source": "workspace"})
+
+ # Built-in skills
+ if self.builtin_skills and self.builtin_skills.exists():
+ for skill_dir in self.builtin_skills.iterdir():
+ if skill_dir.is_dir():
+ skill_file = skill_dir / "SKILL.md"
+ if skill_file.exists() and not any(s["name"] == skill_dir.name for s in skills):
+ skills.append({"name": skill_dir.name, "path": str(skill_file), "source": "builtin"})
+
+ # Filter by requirements
+ if filter_unavailable:
+ return [s for s in skills if self._check_requirements(self._get_skill_meta(s["name"]))]
+ return skills
+
+ def load_skill(self, name: str) -> str | None:
+ """
+ Load a skill by name.
+
+ Args:
+ name: Skill name (directory name).
+
+ Returns:
+ Skill content or None if not found.
+ """
+ # Check workspace first
+ workspace_skill = self.workspace_skills / name / "SKILL.md"
+ if workspace_skill.exists():
+ return workspace_skill.read_text(encoding="utf-8")
+
+ # Check built-in
+ if self.builtin_skills:
+ builtin_skill = self.builtin_skills / name / "SKILL.md"
+ if builtin_skill.exists():
+ return builtin_skill.read_text(encoding="utf-8")
+
+ return None
+
+ def load_skills_for_context(self, skill_names: list[str]) -> str:
+ """
+ Load specific skills for inclusion in agent context.
+
+ Args:
+ skill_names: List of skill names to load.
+
+ Returns:
+ Formatted skills content.
+ """
+ parts = []
+ for name in skill_names:
+ content = self.load_skill(name)
+ if content:
+ content = self._strip_frontmatter(content)
+ parts.append(f"### Skill: {name}\n\n{content}")
+
+ return "\n\n---\n\n".join(parts) if parts else ""
+
+ def build_skills_summary(self) -> str:
+ """
+ Build a summary of all skills (name, description, path, availability).
+
+ This is used for progressive loading - the agent can read the full
+ skill content using read_file when needed.
+
+ Returns:
+ XML-formatted skills summary.
+ """
+ all_skills = self.list_skills(filter_unavailable=False)
+ if not all_skills:
+ return ""
+
+ def escape_xml(s: str) -> str:
+ return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+ lines = ["<skills>"]
+ for s in all_skills:
+ name = escape_xml(s["name"])
+ path = s["path"]
+ desc = escape_xml(self._get_skill_description(s["name"]))
+ skill_meta = self._get_skill_meta(s["name"])
+ available = self._check_requirements(skill_meta)
+
+ lines.append(f" <skill available=\"{str(available).lower()}\">")
+ lines.append(f" <name>{name}</name>")
+ lines.append(f" <description>{desc}</description>")
+ lines.append(f" <location>{path}</location>")
+
+ # Show missing requirements for unavailable skills
+ if not available:
+ missing = self._get_missing_requirements(skill_meta)
+ if missing:
+ lines.append(f" <requires>{escape_xml(missing)}</requires>")
+
+ lines.append(" </skill>")
+ lines.append("</skills>")
+
+ return "\n".join(lines)
+
+ def _get_missing_requirements(self, skill_meta: dict) -> str:
+ """Get a description of missing requirements."""
+ missing = []
+ requires = skill_meta.get("requires", {})
+ for b in requires.get("bins", []):
+ if not shutil.which(b):
+ missing.append(f"CLI: {b}")
+ for env in requires.get("env", []):
+ if not os.environ.get(env):
+ missing.append(f"ENV: {env}")
+ return ", ".join(missing)
+
+ def _get_skill_description(self, name: str) -> str:
+ """Get the description of a skill from its frontmatter."""
+ meta = self.get_skill_metadata(name)
+ if meta and meta.get("description"):
+ return meta["description"]
+ return name # Fallback to skill name
+
+ def _strip_frontmatter(self, content: str) -> str:
+ """Remove YAML frontmatter from markdown content."""
+ if content.startswith("---"):
+ match = re.match(r"^---\n.*?\n---\n", content, re.DOTALL)
+ if match:
+ return content[match.end():].strip()
+ return content
+
+ def _parse_nanobot_metadata(self, raw: str) -> dict:
+ """Parse skill metadata JSON from frontmatter (supports nanobot and openclaw keys for backward compatibility)."""
+ try:
+ data = json.loads(raw)
+ return data.get("nanobot", data.get("openclaw", {})) if isinstance(data, dict) else {}
+ except (json.JSONDecodeError, TypeError):
+ return {}
+
+ def _check_requirements(self, skill_meta: dict) -> bool:
+ """Check if skill requirements are met (bins, env vars)."""
+ requires = skill_meta.get("requires", {})
+ for b in requires.get("bins", []):
+ if not shutil.which(b):
+ return False
+ for env in requires.get("env", []):
+ if not os.environ.get(env):
+ return False
+ return True
+
+ def _get_skill_meta(self, name: str) -> dict:
+ """Get TutorBot metadata for a skill (cached in frontmatter)."""
+ meta = self.get_skill_metadata(name) or {}
+ return self._parse_nanobot_metadata(meta.get("metadata", ""))
+
+ def get_always_skills(self) -> list[str]:
+ """Get skills marked as always=true that meet requirements."""
+ result = []
+ for s in self.list_skills(filter_unavailable=True):
+ meta = self.get_skill_metadata(s["name"]) or {}
+ skill_meta = self._parse_nanobot_metadata(meta.get("metadata", ""))
+ if skill_meta.get("always") or meta.get("always"):
+ result.append(s["name"])
+ return result
+
+ def get_skill_metadata(self, name: str) -> dict | None:
+ """
+ Get metadata from a skill's frontmatter.
+
+ Args:
+ name: Skill name.
+
+ Returns:
+ Metadata dict or None.
+ """
+ content = self.load_skill(name)
+ if not content:
+ return None
+
+ if content.startswith("---"):
+ match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
+ if match:
+ # Simple YAML parsing
+ metadata = {}
+ for line in match.group(1).split("\n"):
+ if ":" in line:
+ key, value = line.split(":", 1)
+ metadata[key.strip()] = value.strip().strip('"\'')
+ return metadata
+
+ return None
diff --git a/deeptutor/tutorbot/agent/subagent.py b/deeptutor/tutorbot/agent/subagent.py
new file mode 100644
index 000000000..cd88d0c69
--- /dev/null
+++ b/deeptutor/tutorbot/agent/subagent.py
@@ -0,0 +1,223 @@
+"""Subagent manager for background task execution."""
+
+import asyncio
+import json
+import uuid
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from deeptutor.tutorbot.agent.tools.registry import build_base_tools
+from deeptutor.tutorbot.bus.events import InboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.config.schema import ExecToolConfig
+from deeptutor.tutorbot.providers.base import LLMProvider
+from deeptutor.tutorbot.utils.helpers import build_assistant_message
+
+
+class SubagentManager:
+ """Manages background subagent execution."""
+
+ def __init__(
+ self,
+ provider: LLMProvider,
+ workspace: Path,
+ bus: MessageBus,
+ model: str | None = None,
+ web_search_config: "WebSearchConfig | None" = None,
+ web_proxy: str | None = None,
+ exec_config: "ExecToolConfig | None" = None,
+ restrict_to_workspace: bool = False,
+ ):
+ from deeptutor.tutorbot.config.schema import ExecToolConfig, WebSearchConfig
+
+ self.provider = provider
+ self.workspace = workspace
+ self.bus = bus
+ self.model = model or provider.get_default_model()
+ self.web_search_config = web_search_config or WebSearchConfig()
+ self.web_proxy = web_proxy
+ self.exec_config = exec_config or ExecToolConfig()
+ self.restrict_to_workspace = restrict_to_workspace
+ self._running_tasks: dict[str, asyncio.Task[None]] = {}
+ self._session_tasks: dict[str, set[str]] = {} # session_key -> {task_id, ...}
+
+ async def spawn(
+ self,
+ task: str,
+ label: str | None = None,
+ origin_channel: str = "cli",
+ origin_chat_id: str = "direct",
+ session_key: str | None = None,
+ ) -> str:
+ """Spawn a subagent to execute a task in the background."""
+ task_id = str(uuid.uuid4())[:8]
+ display_label = label or task[:30] + ("..." if len(task) > 30 else "")
+ origin = {"channel": origin_channel, "chat_id": origin_chat_id}
+
+ bg_task = asyncio.create_task(
+ self._run_subagent(task_id, task, display_label, origin)
+ )
+ self._running_tasks[task_id] = bg_task
+ if session_key:
+ self._session_tasks.setdefault(session_key, set()).add(task_id)
+
+ def _cleanup(_: asyncio.Task) -> None:
+ self._running_tasks.pop(task_id, None)
+ if session_key and (ids := self._session_tasks.get(session_key)):
+ ids.discard(task_id)
+ if not ids:
+ del self._session_tasks[session_key]
+
+ bg_task.add_done_callback(_cleanup)
+
+ logger.info("Spawned subagent [{}]: {}", task_id, display_label)
+ if label == "btw":
+ return f"BTW accepted (id: {task_id}). I'll send the result when it finishes."
+ return f"Task accepted (id: {task_id}). I'll notify you when it completes."
+
+ async def _run_subagent(
+ self,
+ task_id: str,
+ task: str,
+ label: str,
+ origin: dict[str, str],
+ ) -> None:
+ """Execute the subagent task and announce the result."""
+ logger.info("Subagent [{}] starting task: {}", task_id, label)
+
+ try:
+ tools = build_base_tools(
+ workspace=self.workspace,
+ exec_config=self.exec_config,
+ web_search_config=self.web_search_config,
+ web_proxy=self.web_proxy,
+ restrict_to_workspace=self.restrict_to_workspace,
+ )
+
+ system_prompt = self._build_subagent_prompt()
+ messages: list[dict[str, Any]] = [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": task},
+ ]
+
+ # Run agent loop (limited iterations)
+ max_iterations = 15
+ iteration = 0
+ final_result: str | None = None
+
+ while iteration < max_iterations:
+ iteration += 1
+
+ response = await self.provider.chat_with_retry(
+ messages=messages,
+ tools=tools.get_definitions(),
+ model=self.model,
+ )
+
+ if response.has_tool_calls:
+ tool_call_dicts = [
+ tc.to_openai_tool_call()
+ for tc in response.tool_calls
+ ]
+ messages.append(build_assistant_message(
+ response.content or "",
+ tool_calls=tool_call_dicts,
+ reasoning_content=response.reasoning_content,
+ thinking_blocks=response.thinking_blocks,
+ ))
+
+ # Execute tools
+ for tool_call in response.tool_calls:
+ args_str = json.dumps(tool_call.arguments, ensure_ascii=False)
+ logger.debug("Subagent [{}] executing: {} with arguments: {}", task_id, tool_call.name, args_str)
+ result = await tools.execute(tool_call.name, tool_call.arguments)
+ messages.append({
+ "role": "tool",
+ "tool_call_id": tool_call.id,
+ "name": tool_call.name,
+ "content": result,
+ })
+ else:
+ final_result = response.content
+ break
+
+ if final_result is None:
+ final_result = "Task completed but no final response was generated."
+
+ logger.info("Subagent [{}] completed successfully", task_id)
+ await self._announce_result(task_id, label, task, final_result, origin, "ok")
+
+ except Exception as e:
+ error_msg = f"Error: {str(e)}"
+ logger.error("Subagent [{}] failed: {}", task_id, e)
+ await self._announce_result(task_id, label, task, error_msg, origin, "error")
+
+ async def _announce_result(
+ self,
+ task_id: str,
+ label: str,
+ task: str,
+ result: str,
+ origin: dict[str, str],
+ status: str,
+ ) -> None:
+ """Announce the subagent result to the main agent via the message bus."""
+ status_text = "completed successfully" if status == "ok" else "failed"
+
+ announce_content = f"""[Subagent '{label}' {status_text}]
+
+Task: {task}
+
+Result:
+{result}
+
+Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not mention technical details like "subagent" or task IDs."""
+
+ # Inject as system message to trigger main agent
+ msg = InboundMessage(
+ channel="system",
+ sender_id="subagent",
+ chat_id=f"{origin['channel']}:{origin['chat_id']}",
+ content=announce_content,
+ )
+
+ await self.bus.publish_inbound(msg)
+ logger.debug("Subagent [{}] announced result to {}:{}", task_id, origin['channel'], origin['chat_id'])
+
+ def _build_subagent_prompt(self) -> str:
+ """Build a focused system prompt for the subagent."""
+ from deeptutor.tutorbot.agent.context import ContextBuilder
+ from deeptutor.tutorbot.agent.skills import SkillsLoader
+
+ time_ctx = ContextBuilder._build_runtime_context(None, None)
+ parts = [f"""# Subagent
+
+{time_ctx}
+
+You are a subagent spawned by the main agent to complete a specific task.
+Stay focused on the assigned task. Your final response will be reported back to the main agent.
+
+## Workspace
+{self.workspace}"""]
+
+ skills_summary = SkillsLoader(self.workspace).build_skills_summary()
+ if skills_summary:
+ parts.append(f"## Skills\n\nRead SKILL.md with read_file to use a skill.\n\n{skills_summary}")
+
+ return "\n\n".join(parts)
+
+ async def cancel_by_session(self, session_key: str) -> int:
+ """Cancel all subagents for the given session. Returns count cancelled."""
+ tasks = [self._running_tasks[tid] for tid in self._session_tasks.get(session_key, [])
+ if tid in self._running_tasks and not self._running_tasks[tid].done()]
+ for t in tasks:
+ t.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ return len(tasks)
+
+ def get_running_count(self) -> int:
+ """Return the number of currently running subagents."""
+ return len(self._running_tasks)
diff --git a/deeptutor/tutorbot/agent/team/INTRO.md b/deeptutor/tutorbot/agent/team/INTRO.md
new file mode 100644
index 000000000..88c5cd55c
--- /dev/null
+++ b/deeptutor/tutorbot/agent/team/INTRO.md
@@ -0,0 +1,142 @@
+# Nano Team Mode
+
+用一句话描述:用户给出一个目标,LLM 自动规划出 2-3 人的微型团队,每个成员作为独立 worker 异步执行任务,通过共享看板和邮箱协作,用户可以随时审批、追加指令或停止。
+
+## 架构总览
+
+```
+用户指令
+ │
+ ▼
+AgentLoop ──/team <goal>──► TeamManager.start_or_route_goal()
+ │ │
+ │ LLM 生成计划(mission / members / tasks)
+ │ │
+ │ 创建 TeamRuntime(磁盘持久化)
+ │ │
+ │ 为每个 member 启动 asyncio worker
+ │ │
+ │ ┌────────────────────┼────────────────────┐
+ │ ▼ ▼ ▼
+ │ Worker A Worker B Worker C
+ │ (researcher) (builder) (...)
+ │ │ │ │
+ │ ├─ board: claim/complete tasks │
+ │ ├─ mailbox: send/read messages │
+ │ └─ file/shell/web tools │
+ │ │
+ │ ◄────── events.jsonl / tasks.json ───────►
+ │
+ ▼
+用户查看状态 (/team status)、审批 (/team approve)、停止 (/team stop)
+```
+
+## 模块职责
+
+```
+team/
+├── __init__.py TeamManager — 运行时生命周期、LLM 规划、worker 调度
+├── state.py 纯数据结构:Task, Teammate, Mail, TeamState
+├── board.py 任务看板:claim / complete / approve / reject(文件锁保证并发安全)
+├── mailbox.py 消息邮箱:send / broadcast / read_unread(JSONL 追加写,自动截断到 200 条)
+├── tools.py 暴露给 LLM 的工具:TeamTool(管理端)、TeamWorkerTool(worker 端)
+└── _filelock.py 跨平台文件锁(Unix fcntl / Windows msvcrt)
+```
+
+### 数据流
+
+- **state.py** 定义所有数据结构,不含业务逻辑,纯 dataclass + JSON 序列化。
+- **board.py** 管理 `tasks.json`——所有对任务状态的变更都经过 `_locked_update()`,通过文件锁保证多个 worker 并发写入安全。
+- **mailbox.py** 管理 `mailbox.jsonl`——worker 之间、lead 与 worker 之间的消息通信。同样使用文件锁。每次写入后自动截断保留最近 200 条,防止文件无限增长。
+- **tools.py** 包含两个 Tool 类:
+ - `TeamTool`:暴露给主 agent 的管理接口(create / shutdown / approve / reject / board / message / add_task)
+ - `TeamWorkerTool`:暴露给每个 worker 的协作接口(board / claim / complete / submit_plan / mail_send / mail_read)
+
+### TeamManager 核心流程
+
+1. **start_or_route_goal(session_key, goal)**
+ - 如果当前 session 已有活跃团队 → 将指令路由为增量任务
+ - 否则 → 调用 LLM 生成初始计划(mission + members + tasks),校验后创建 runtime,启动 workers
+
+2. **Worker 执行循环** (`_run_worker`)
+ - 每轮:检查邮箱 → 调用 LLM → 执行工具调用 → 检查任务状态
+ - Worker 自主通过 `team_worker` tool 操作看板:claim 任务 → 执行 → complete
+ - 如果任务 `requires_approval`,worker 提交 plan 后暂停等待用户审批
+
+3. **审批流程**
+ - worker `submit_plan` → 任务进入 `awaiting_approval`
+ - 非 CLI 渠道(如 Telegram):自动推送审批提示给用户
+ - 用户可通过 `/team approve <id>` / `/team reject <id> <reason>` / `/team manual <id> <instruction>` 操作
+ - 也支持自然语言审批(中英文关键词匹配)
+
+4. **风险门控**
+ - 包含 `rm -rf` / `drop table` 等危险关键词的指令会被暂停
+ - 用户需 `/team confirm <instruction>` 确认后才继续执行
+
+### 磁盘持久化结构
+
+```
+workspace/teams/<session_key>/<run_id>/
+├── config.json TeamState(team_id, mission, members, status)
+├── tasks.json 所有 Task 的状态
+├── mailbox.jsonl 消息记录
+├── events.jsonl 事件日志(team_started, task_added, worker_update, ...)
+├── NOTES.md 共享笔记
+└── workers/
+ ├── researcher/ worker 工作目录
+ └── builder/
+```
+
+团队状态持久化到磁盘。进程重启后,`_auto_attach()` 会自动发现未完成的 run 并恢复执行。
+
+## 使用方式
+
+### CLI 交互模式
+
+```bash
+nanobot agent # 进入交互模式
+> /team 帮我调研 Rust async 生态 # 启动团队
+> /team status # 查看当前状态
+> /team log # 查看详细事件日志
+> /team log 50 # 查看最近 50 条日志
+> /team 补充:重点关注 tokio 生态 # 追加指令(自动拆解为增量任务)
+> /team approve t3 # 审批任务
+> /team reject t3 需要更多细节 # 拒绝任务
+> /team manual t3 请增加性能对比 # 要求修改
+> /team stop # 停止团队(CLI 会输出最终看板快照)
+```
+
+CLI 模式下,团队看板会嵌入到 prompt 中实时刷新,支持 `Shift+↑↓` 导航成员、`Enter` 查看详情、`Esc` 返回。
+
+### Telegram / 其他渠道
+
+```
+/team 写一份技术方案 # 启动
+/team status # 状态
+# (worker 完成需要审批的任务时,bot 会主动推送审批提示)
+批准 t1 # 自然语言审批
+拒绝 t2 缺少测试计划 # 自然语言拒绝
+/team stop # 停止
+```
+
+### 通过 LLM Tool 调用(TeamTool)
+
+主 agent 也可以通过 `team` tool 自主创建和管理团队:
+
+```json
+{"action": "create", "team_id": "research", "members": [...], "tasks": [...], "mission": "..."}
+{"action": "board"}
+{"action": "approve", "task_id": "t1"}
+{"action": "message", "to": "researcher", "content": "请优先完成 t2"}
+{"action": "shutdown"}
+```
+
+## 测试覆盖
+
+测试文件位于 `tests/` 目录:
+
+| 文件 | 覆盖范围 |
+|------|----------|
+| `test_team_mode.py` | TeamManager 核心逻辑:计划校验(重复成员/空任务/循环依赖)、fallback 计划、会话隔离、生命周期(start → route → stop with snapshot)、自然语言审批(approve / reject / manual change) |
+| `test_team_routing.py` | AgentLoop 层的命令路由:`/team status` / `/team log` / `/team <goal>` / `/teams` 别名 / `/team approve` / `/team reject` / `/team manual` / `/team stop`(CLI 快照)/ `/btw` 子任务、Telegram 自然语言审批拦截、team mode 下普通消息被阻断 |
+| `test_cli_input.py` | CLI 团队视图:`_sync_team_view` / `_prompt_message` 的看板渲染和 suppress 逻辑 |
diff --git a/deeptutor/tutorbot/agent/team/__init__.py b/deeptutor/tutorbot/agent/team/__init__.py
new file mode 100644
index 000000000..faadaaf67
--- /dev/null
+++ b/deeptutor/tutorbot/agent/team/__init__.py
@@ -0,0 +1,1099 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from . import board, mailbox
+from .state import Task, TeamState, Teammate
+from .tools import TeamWorkerTool
+from deeptutor.tutorbot.agent.tools.registry import build_base_tools
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.config.schema import ExecToolConfig, WebSearchConfig
+from deeptutor.tutorbot.providers.base import LLMProvider
+from deeptutor.tutorbot.session.manager import Session, SessionManager
+from deeptutor.tutorbot.utils.helpers import ensure_dir, parse_json_from_llm, safe_filename, timestamp
+
+
+@dataclass
+class TeamRuntime:
+ session_key: str
+ run_dir: Path
+ state: TeamState
+ worker_tasks: dict[str, asyncio.Task[None]] = field(default_factory=dict)
+ prompted_approvals: set[str] = field(default_factory=set)
+
+ @property
+ def events_path(self) -> Path:
+ return self.run_dir / "events.jsonl"
+
+
+class TeamManager:
+ """Session-scoped nano team runtime."""
+
+ def __init__(
+ self,
+ provider: LLMProvider,
+ workspace: Path,
+ bus: MessageBus,
+ sessions: SessionManager,
+ model: str | None = None,
+ temperature: float = 0.1,
+ max_tokens: int = 4096,
+ reasoning_effort: str | None = None,
+ web_search_config: "WebSearchConfig | None" = None,
+ web_proxy: str | None = None,
+ exec_config: ExecToolConfig | None = None,
+ restrict_to_workspace: bool = False,
+ max_workers: int = 5,
+ worker_max_iterations: int = 25,
+ ):
+ self.provider = provider
+ self.workspace = workspace
+ self.bus = bus
+ self.sessions = sessions
+ self.model = model or provider.get_default_model()
+ self.temperature = temperature
+ self.max_tokens = max_tokens
+ self.reasoning_effort = reasoning_effort
+ self.web_search_config = web_search_config or WebSearchConfig()
+ self.web_proxy = web_proxy
+ self.exec_config = exec_config or ExecToolConfig()
+ self.restrict_to_workspace = restrict_to_workspace
+ self.max_workers = max_workers
+ self.worker_max_iterations = worker_max_iterations
+ self.teams_dir = ensure_dir(workspace / "teams")
+
+ self._active_by_session: dict[str, TeamRuntime] = {}
+ self._runtime_lock = asyncio.Lock()
+
+ # ------------------------------------------------------------------
+ # Context/session helpers
+ # ------------------------------------------------------------------
+ def is_active(self, session_key: str) -> bool:
+ rt = self._active_by_session.get(session_key)
+ return rt is not None and rt.state.status != "completed"
+
+ def has_unfinished_run(self, session_key: str) -> bool:
+ if self.is_active(session_key):
+ return True
+ latest = self._latest_unfinished_dir(session_key)
+ return latest is not None
+
+ def has_active_team(self, session_key: str) -> bool:
+ return self._runtime(session_key) is not None
+
+ def active_team_id(self, session_key: str) -> str | None:
+ runtime = self._runtime(session_key)
+ return runtime.state.team_id if runtime else None
+
+ def get_team_dir(self, session_key: str) -> Path | None:
+ runtime = self._runtime(session_key)
+ return runtime.run_dir if runtime else None
+
+ def get_team_state(self, session_key: str) -> TeamState | None:
+ runtime = self._runtime(session_key)
+ return runtime.state if runtime else None
+
+ def _session_dir(self, session_key: str) -> Path:
+ return ensure_dir(self.teams_dir / safe_filename(session_key))
+
+ def _runtime(self, session_key: str, auto_attach: bool = False) -> TeamRuntime | None:
+ runtime = self._active_by_session.get(session_key)
+ if runtime and runtime.state.status != "completed":
+ return runtime
+ if auto_attach:
+ return self._auto_attach(session_key)
+ return None
+
+ def _latest_unfinished_dir(self, session_key: str) -> Path | None:
+ base = self._session_dir(session_key)
+ runs = [p for p in base.iterdir() if p.is_dir()]
+ runs.sort(key=lambda p: p.name, reverse=True)
+ for run_dir in runs:
+ cfg = run_dir / "config.json"
+ if not cfg.exists():
+ continue
+ try:
+ state = TeamState.load(cfg)
+ except Exception:
+ continue
+ if state.status != "completed":
+ return run_dir
+ return None
+
+ def _auto_attach(self, session_key: str) -> TeamRuntime | None:
+ if session_key in self._active_by_session:
+ return self._active_by_session[session_key]
+ run_dir = self._latest_unfinished_dir(session_key)
+ if not run_dir:
+ return None
+ state = TeamState.load(run_dir / "config.json")
+ if state.status == "completed":
+ return None
+ state.status = "active"
+ state.save(run_dir / "config.json")
+ runtime = TeamRuntime(session_key=session_key, run_dir=run_dir, state=state)
+ self._active_by_session[session_key] = runtime
+ for mate in state.members:
+ if mate.status != "stopped":
+ self._ensure_worker(runtime, mate.name)
+ self._append_event(runtime, "team_auto_attach", f"Auto-attached run {state.run_id}")
+ return runtime
+
+ # ------------------------------------------------------------------
+ # Event helpers
+ # ------------------------------------------------------------------
+ def _append_event(self, runtime: TeamRuntime, kind: str, message: str, **extra: Any) -> None:
+ ensure_dir(runtime.run_dir)
+ record = {
+ "ts": timestamp(),
+ "kind": kind,
+ "message": message,
+ }
+ if extra:
+ record["data"] = extra
+ with open(runtime.events_path, "a", encoding="utf-8") as f:
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
+
+ async def _emit_lead_update(self, runtime: TeamRuntime, text: str) -> None:
+ channel, chat_id = runtime.session_key.split(":", 1) if ":" in runtime.session_key else ("cli", runtime.session_key)
+ if channel == "cli":
+ # In CLI team mode, keep team updates inside the board/event stream.
+ self._append_event(runtime, "lead_user_sync", text)
+ return
+ await self.bus.publish_outbound(OutboundMessage(
+ channel=channel,
+ chat_id=chat_id,
+ content=text,
+ metadata={"team_event": True},
+ ))
+
+ def log_text(self, session_key: str, n: int = 20) -> str:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return "No team logs."
+ if not runtime.events_path.exists():
+ return "No team logs."
+ lines = runtime.events_path.read_text(encoding="utf-8").splitlines()[-n:]
+ rendered: list[str] = []
+ for line in lines:
+ try:
+ row = json.loads(line)
+ except Exception:
+ continue
+ rendered.append(f"- [{row.get('ts', '?')}] {row.get('kind', 'event')}: {row.get('message', '')}")
+ return "\n".join(rendered) or "No team logs."
+
+ def status_text(self, session_key: str) -> str:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return "No active nano team. Start with `/team <goal>`."
+ tasks = board.load(runtime.run_dir)
+ members = board.member_rows(tasks, runtime.state.members)
+ completed = sum(1 for t in tasks if t.status == "completed")
+ active = sum(1 for t in tasks if t.status in {"planning", "in_progress"})
+ pending_approval = sum(1 for t in tasks if t.status == "awaiting_approval")
+ recent = self._recent_updates(runtime, n=2)
+ member_text = ", ".join(f"{m['name']}={m['status']}" for m in members) or "none"
+ approvals = [a["id"] for a in board.approval_rows(tasks)]
+ lines = [
+ f"Team `{runtime.state.team_id}` · {runtime.state.status}",
+ f"Mission: {runtime.state.mission or '(none)'}",
+ f"Members: {member_text}",
+ f"Tasks: {completed}/{len(tasks)} completed · {active} active · {pending_approval} awaiting approval",
+ ]
+ if approvals:
+ lines.append(f"Approval queue: {', '.join(approvals[:5])}")
+ lines.append("Approve with `/team approve <id>` or `/team reject <id> <reason>`.")
+ if recent:
+ lines.append(f"Recent: {recent[-1]}")
+ return "\n".join(lines)
+
+ def _snapshot_text(self, runtime: TeamRuntime) -> str:
+ tasks = board.load(runtime.run_dir)
+ members = board.member_rows(tasks, runtime.state.members)
+ header = (
+ f"## Team: {runtime.state.team_id}\n"
+ f"- Mission: {runtime.state.mission or '(none)'}\n"
+ f"- Run ID: {runtime.state.run_id}\n"
+ f"- Status: {runtime.state.status}\n"
+ )
+ member_lines = "\n".join(
+ f"- {m['name']} ({m['role']}): {m['status']} | {m['task']}"
+ for m in members
+ ) or "- none"
+ return f"{header}\n### Members\n{member_lines}\n\n{board.render_text(tasks, runtime.state.members)}"
+
+ # ------------------------------------------------------------------
+ # Public nano-team mode API
+ # ------------------------------------------------------------------
+ async def start_or_route_goal(self, session_key: str, goal: str) -> str:
+ async with self._runtime_lock:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if runtime:
+ return await self._route_instruction(runtime, goal, source="team_command")
+
+ normalized = await self._build_initial_plan(goal)
+ runtime = self._create_runtime_from_plan(session_key, normalized)
+ self._active_by_session[session_key] = runtime
+ self._append_event(runtime, "team_started", f"Started nano team for goal: {goal}")
+ for mate in runtime.state.members:
+ self._ensure_worker(runtime, mate.name)
+ await self._emit_lead_update(
+ runtime,
+ f"Team lead: started `{runtime.state.team_id}` with {len(runtime.state.members)} workers for `{goal}`.",
+ )
+ return (
+ f"Nano team started: `{runtime.state.team_id}` ({len(runtime.state.members)} workers).\n"
+ f"Use `/team status`, `/team log`, `/team stop`."
+ )
+
+ async def route_user_message(self, session_key: str, message: str) -> str:
+ async with self._runtime_lock:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return "No active nano team. Start with `/team <goal>`."
+ return await self._route_instruction(runtime, message, source="plain_message")
+
+ async def stop_mode(self, session_key: str, *, with_snapshot: bool = False) -> str:
+ async with self._runtime_lock:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return "No active team."
+ if with_snapshot:
+ tasks = board.load(runtime.run_dir)
+ completed = sum(1 for t in tasks if t.status == "completed")
+ total = len(tasks)
+ awaiting = sum(1 for t in tasks if t.status == "awaiting_approval")
+ in_progress = sum(1 for t in tasks if t.status in {"planning", "in_progress"})
+ summary = (
+ f"Completed {completed}/{total} tasks, "
+ f"{in_progress} in progress, {awaiting} awaiting approval."
+ )
+ self._append_event(runtime, "team_final_summary", summary)
+ await self._stop_runtime(runtime)
+ self._active_by_session.pop(session_key, None)
+ if not with_snapshot:
+ return f"Team `{runtime.state.team_id}` stopped."
+ snapshot = self._snapshot_text(runtime)
+ updates = self._recent_updates(runtime, n=6)
+ update_lines = "\n".join(f"- {u}" for u in updates) or "- (no recent updates)"
+ return (
+ f"{snapshot}\n\n"
+ "### Team Lead Final Summary\n"
+ f"- {summary}\n\n"
+ "### Recent Updates\n"
+ f"{update_lines}"
+ )
+
+ # ------------------------------------------------------------------
+ # Compatibility API for TeamTool / CLI panel
+ # ------------------------------------------------------------------
+ async def create(
+ self,
+ session_key: str,
+ team_id: str,
+ members: list[dict],
+ tasks: list[dict],
+ notes: str = "",
+ mission: str = "",
+ ) -> str:
+ async with self._runtime_lock:
+ if self._runtime(session_key):
+ return "Error: active team already exists for this session"
+ payload = {
+ "mission": mission or team_id,
+ "members": members,
+ "tasks": tasks,
+ "notes": notes,
+ }
+ normalized, err = self._validate_plan_payload(payload, mission or team_id)
+ if err:
+ return f"Error: {err}"
+ runtime = self._create_runtime_from_plan(session_key, normalized, team_id=team_id)
+ self._active_by_session[session_key] = runtime
+ self._append_event(runtime, "team_created", "Created team via internal tool")
+ for mate in runtime.state.members:
+ self._ensure_worker(runtime, mate.name)
+ return f"Team '{runtime.state.team_id}' started with {len(runtime.state.members)} teammates."
+
+ async def resume(self, session_key: str, team_id: str) -> str:
+ async with self._runtime_lock:
+ if self._runtime(session_key):
+ return "Error: active team already exists for this session"
+ base = self._session_dir(session_key)
+ for run_dir in sorted([p for p in base.iterdir() if p.is_dir()], key=lambda p: p.name, reverse=True):
+ cfg = run_dir / "config.json"
+ if not cfg.exists():
+ continue
+ state = TeamState.load(cfg)
+ if state.team_id == team_id or state.run_id == team_id:
+ state.status = "active"
+ state.save(cfg)
+ runtime = TeamRuntime(session_key=session_key, run_dir=run_dir, state=state)
+ self._active_by_session[session_key] = runtime
+ for mate in state.members:
+ if mate.status != "stopped":
+ self._ensure_worker(runtime, mate.name)
+ self._append_event(runtime, "team_resumed", f"Resumed team {team_id}")
+ return f"Resumed team '{state.team_id}'."
+ return f"Error: team '{team_id}' not found"
+
+ async def shutdown(self, session_key: str) -> str:
+ return await self.stop_mode(session_key)
+
+ async def cancel_by_session(self, session_key: str) -> int:
+ async with self._runtime_lock:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return 0
+ count = await self._cancel_worker_tasks(runtime)
+ runtime.state.status = "paused"
+ runtime.state.save(runtime.run_dir / "config.json")
+ self._append_event(runtime, "team_cancelled", f"Cancelled {count} worker tasks")
+ self._active_by_session.pop(session_key, None)
+ return count
+
+ async def message_worker(self, session_key: str, to: str, content: str) -> str:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return "Error: no active team"
+ result = mailbox.send(runtime.run_dir, "lead", to, content)
+ self._append_event(runtime, "lead_message", f"Lead -> {to}: {content[:120]}")
+ self._ensure_worker(runtime, to)
+ return result
+
+ def render_board(self, session_key: str) -> str:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return "No active team."
+ tasks = board.load(runtime.run_dir)
+ text = board.render_text(tasks, runtime.state.members)
+ recent = mailbox.render_recent(runtime.run_dir)
+ return f"## Team: {runtime.state.team_id}\n\n{text}\n\n## Recent Messages\n{recent}"
+
+ def list_members(self, session_key: str) -> list[str]:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return []
+ return [runtime.state.lead] + [m.name for m in runtime.state.members]
+
+ def get_member_snapshot(self, session_key: str, name: str) -> dict[str, Any] | None:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return None
+ if name == runtime.state.lead:
+ return {
+ "name": runtime.state.lead,
+ "role": "team leader",
+ "status": "active",
+ "task": None,
+ "recent_messages": mailbox.recent_for(runtime.run_dir, runtime.state.lead),
+ }
+ mate = next((m for m in runtime.state.members if m.name == name), None)
+ if not mate:
+ return None
+ current = board.get_current(runtime.run_dir, name)
+ task = None if not current else {
+ "id": current.id,
+ "title": current.title,
+ "status": current.status,
+ "plan": current.plan or "",
+ "result": current.result or "",
+ }
+ return {
+ "name": mate.name,
+ "role": mate.role,
+ "status": mate.status,
+ "task": task,
+ "recent_messages": mailbox.recent_for(runtime.run_dir, name),
+ }
+
+ def get_board_snapshot(self, session_key: str) -> dict[str, Any] | None:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return None
+ tasks = board.load(runtime.run_dir)
+ worker_rows = board.member_rows(tasks, runtime.state.members)
+ approval_rows = board.approval_rows(tasks)
+ recent_lead = mailbox.recent_for(runtime.run_dir, runtime.state.lead, n=1)
+ lead_action = f"msg -> {recent_lead[-1].to_agent}" if recent_lead else "coordinating"
+ lead_row = {"name": runtime.state.lead, "role": "team leader", "status": "active", "task": lead_action}
+ return {
+ "team_id": runtime.state.team_id,
+ "status": runtime.state.status,
+ "members": [lead_row] + worker_rows,
+ "tasks": board.task_rows(tasks),
+ "approvals": approval_rows,
+ "approval_focus": approval_rows[0] if approval_rows else None,
+ "recent_messages": mailbox.recent(runtime.run_dir),
+ "recent_updates": self._recent_updates(runtime),
+ }
+
+ def add_task(self, session_key: str, task: dict[str, Any]) -> str:
+ runtime = self._runtime(session_key)
+ if not runtime:
+ return "Error: no active team"
+ task = dict(task)
+ task.setdefault("id", self._next_task_id(runtime))
+ result = board.add_task(runtime.run_dir, Task(**task))
+ self._append_event(runtime, "task_added", f"Added task {task['id']}: {task.get('title', '')}")
+ if owner := task.get("owner"):
+ self._ensure_worker(runtime, owner)
+ return result
+
+ def has_pending_approval(self, session_key: str) -> bool:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return False
+ return any(t.status == "awaiting_approval" for t in board.load(runtime.run_dir))
+
+ def approve_for_session(self, session_key: str, task_id: str) -> str:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return "Error: no active team"
+ result = board.approve(runtime.run_dir, task_id)
+ if result.startswith("Error:"):
+ return result
+ task = next((t for t in board.load(runtime.run_dir) if t.id == task_id), None)
+ if task and task.owner:
+ self._ensure_worker(runtime, task.owner)
+ runtime.prompted_approvals.discard(task_id)
+ self._append_event(runtime, "task_approved", f"Approved task {task_id}")
+ return result
+
+ def reject_for_session(self, session_key: str, task_id: str, reason: str) -> str:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return "Error: no active team"
+ result = board.reject(runtime.run_dir, task_id, reason)
+ if result.startswith("Error:"):
+ return result
+ runtime.prompted_approvals.discard(task_id)
+ self._append_event(runtime, "task_rejected", f"Rejected task {task_id}: {reason[:100]}")
+ return result
+
+ def request_changes_for_session(self, session_key: str, task_id: str, instruction: str) -> str:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return "Error: no active team"
+ result = board.reject(runtime.run_dir, task_id, instruction)
+ if result.startswith("Error:"):
+ return result
+ task = next((t for t in board.load(runtime.run_dir) if t.id == task_id), None)
+ if task and task.owner:
+ mailbox.send(runtime.run_dir, runtime.state.lead, task.owner, f"Please revise {task_id}: {instruction}")
+ self._ensure_worker(runtime, task.owner)
+ runtime.prompted_approvals.discard(task_id)
+ self._append_event(runtime, "task_change_requested", f"Requested changes on {task_id}: {instruction[:100]}")
+ return f"Requested changes for {task_id}."
+
+ @staticmethod
+ def _extract_task_id(text: str, pending_ids: list[str]) -> str | None:
+ matched = re.search(r"\b[tT]\d+\b", text)
+ if matched and matched.group(0).lower() in {p.lower() for p in pending_ids}:
+ candidate = matched.group(0).lower()
+ for tid in pending_ids:
+ if tid.lower() == candidate:
+ return tid
+ if len(pending_ids) == 1:
+ return pending_ids[0]
+ return None
+
+ @staticmethod
+ def _clean_feedback(text: str, task_id: str) -> str:
+ cleaned = text
+ cleaned = re.sub(rf"\b{re.escape(task_id)}\b", "", cleaned, flags=re.IGNORECASE)
+ for token in (
+ "批准", "同意", "通过", "approve", "approved",
+ "拒绝", "驳回", "reject", "decline",
+ "补充", "调整", "修改", "指示", "manual", "change",
+ ):
+ cleaned = re.sub(token, "", cleaned, flags=re.IGNORECASE)
+ return cleaned.strip(" \t\r\n::,,.。")
+
+ def handle_approval_reply(self, session_key: str, text: str) -> str | None:
+ runtime = self._runtime(session_key, auto_attach=True)
+ if not runtime:
+ return None
+ tasks = board.load(runtime.run_dir)
+ pending = [t for t in tasks if t.status == "awaiting_approval"]
+ if not pending:
+ return None
+ pending_ids = [t.id for t in pending]
+ task_id = self._extract_task_id(text, pending_ids)
+ if not task_id:
+ return (
+ "I found pending approvals but couldn't map your reply to a task. "
+ f"Pending: {', '.join(pending_ids)}. Please mention the task id in natural language."
+ )
+ lowered = text.lower()
+ approve_hit = any(k in lowered for k in ("批准", "同意", "通过", "approve", "approved", "accept", "ok"))
+ reject_hit = any(k in lowered for k in ("拒绝", "驳回", "reject", "decline"))
+ manual_hit = any(k in lowered for k in ("补充", "调整", "修改", "指示", "manual", "change", "revise"))
+ if approve_hit and not reject_hit:
+ return self.approve_for_session(session_key, task_id)
+ feedback = self._clean_feedback(text, task_id)
+ if reject_hit and not manual_hit:
+ if not feedback:
+ return "I can reject it, but I still need a reason in natural language."
+ return self.reject_for_session(session_key, task_id, feedback)
+ if manual_hit or reject_hit:
+ if not feedback:
+ return "I can send change instructions, but I still need your guidance text."
+ return self.request_changes_for_session(session_key, task_id, feedback)
+ return (
+ "I detected approval context but couldn't infer intent. "
+ "Reply naturally with approve/reject/change + task id."
+ )
+
+ # ------------------------------------------------------------------
+ # Planning and instruction routing
+ # ------------------------------------------------------------------
+ async def _route_instruction(self, runtime: TeamRuntime, instruction: str, source: str) -> str:
+ normalized = instruction.strip()
+ if not normalized:
+ return "Please provide an instruction."
+
+ if self._looks_risky(normalized) and not normalized.lower().startswith("confirm "):
+ runtime.state.status = "paused"
+ runtime.state.save(runtime.run_dir / "config.json")
+ self._append_event(runtime, "risk_gate", f"Paused risky instruction: {normalized[:140]}")
+ return (
+ "Risk gate paused this instruction because it may be destructive.\n"
+ "Re-send with `/team confirm <instruction>` to continue."
+ )
+
+ if normalized.lower().startswith("confirm "):
+ normalized = normalized[8:].strip()
+ runtime.state.status = "active"
+ runtime.state.save(runtime.run_dir / "config.json")
+
+ task_specs = await self._build_incremental_tasks(runtime, normalized)
+ created: list[str] = []
+ for spec in task_specs:
+ task = Task(
+ id=self._next_task_id(runtime),
+ title=spec["title"],
+ description=spec.get("description", ""),
+ owner=spec.get("owner"),
+ depends_on=spec.get("depends_on", []),
+ requires_approval=False,
+ )
+ board.add_task(runtime.run_dir, task)
+ created.append(task.id)
+ self._append_event(runtime, "task_added", f"{task.id}: {task.title}", source=source)
+ if task.owner:
+ self._ensure_worker(runtime, task.owner)
+
+ mailbox.broadcast(runtime.run_dir, runtime.state.lead, f"New instruction: {normalized}")
+ for mate in runtime.state.members:
+ self._ensure_worker(runtime, mate.name)
+
+ self._append_lead_session(runtime, normalized, f"Queued {len(created)} tasks: {', '.join(created)}")
+ await self._emit_lead_update(
+ runtime,
+ f"Team lead: queued {len(created)} task(s) from your instruction.",
+ )
+ return f"Queued {len(created)} task(s): {', '.join(created)}."
+
+ async def _build_initial_plan(self, goal: str) -> dict[str, Any]:
+ prompt = (
+ "You are planning a tiny execution team. Return strict JSON only.\n"
+ "Schema:\n"
+ "{"
+ "\"mission\": string,"
+ "\"members\": [{\"name\": string, \"role\": string, \"model\": string?}],"
+ "\"tasks\": [{\"id\": string, \"title\": string, \"description\": string, \"owner\": string?, \"depends_on\": [string]?, \"requires_approval\": boolean?}],"
+ "\"notes\": string"
+ "}\n"
+ "Rules: 2-3 members only. Tasks must be actionable and coherent."
+ )
+ repair_error = ""
+ for _ in range(2):
+ user = f"Goal:\n{goal}"
+ if repair_error:
+ user += f"\n\nPrevious output error: {repair_error}\nFix and output valid JSON only."
+ response = await self.provider.chat_with_retry(
+ messages=[{"role": "system", "content": prompt}, {"role": "user", "content": user}],
+ model=self.model,
+ max_tokens=min(self.max_tokens, 1400),
+ temperature=0.1,
+ reasoning_effort=self.reasoning_effort,
+ )
+ payload = parse_json_from_llm(response.content or "")
+ if payload is None:
+ repair_error = "Malformed JSON."
+ continue
+ normalized, err = self._validate_plan_payload(payload, goal)
+ if not err:
+ return normalized
+ repair_error = err
+ return self._fallback_plan(goal)
+
+ async def _build_incremental_tasks(self, runtime: TeamRuntime, instruction: str) -> list[dict[str, Any]]:
+ member_lines = "\n".join(f"- {m.name}: {m.role}" for m in runtime.state.members)
+ current_tasks = board.task_rows(board.load(runtime.run_dir))
+ prompt = (
+ "You are a pragmatic team lead. Return strict JSON only.\n"
+ "Schema: {\"tasks\": [{\"title\": string, \"description\": string, \"owner\": string?, \"depends_on\": [string]?}]}\n"
+ "Keep it compact (1-3 tasks). Owner must be one of the listed members when provided."
+ )
+ user = (
+ f"Mission: {runtime.state.mission}\n"
+ f"Members:\n{member_lines}\n\n"
+ f"Current tasks: {json.dumps(current_tasks[-12:], ensure_ascii=False)}\n\n"
+ f"New instruction: {instruction}"
+ )
+ response = await self.provider.chat_with_retry(
+ messages=[{"role": "system", "content": prompt}, {"role": "user", "content": user}],
+ model=self.model,
+ max_tokens=min(self.max_tokens, 1000),
+ temperature=0.1,
+ reasoning_effort=self.reasoning_effort,
+ )
+ payload = parse_json_from_llm(response.content or "")
+ members = {m.name for m in runtime.state.members}
+ if not isinstance(payload, dict):
+ return [{"title": instruction[:80], "description": instruction, "owner": None, "depends_on": []}]
+ raw_tasks = payload.get("tasks")
+ if not isinstance(raw_tasks, list) or not raw_tasks:
+ return [{"title": instruction[:80], "description": instruction, "owner": None, "depends_on": []}]
+ out: list[dict[str, Any]] = []
+ for t in raw_tasks[:3]:
+ if not isinstance(t, dict):
+ continue
+ title = str(t.get("title", "")).strip()
+ if not title:
+ continue
+ owner = str(t.get("owner", "")).strip() or None
+ if owner and owner not in members:
+ owner = None
+ deps = t.get("depends_on")
+ if not isinstance(deps, list):
+ deps = []
+ out.append({
+ "title": title,
+ "description": str(t.get("description", "")).strip(),
+ "owner": owner,
+ "depends_on": [str(d).strip() for d in deps if str(d).strip()],
+ })
+ return out or [{"title": instruction[:80], "description": instruction, "owner": None, "depends_on": []}]
+
+ def _create_runtime_from_plan(
+ self,
+ session_key: str,
+ plan: dict[str, Any],
+ team_id: str | None = None,
+ ) -> TeamRuntime:
+ session_dir = self._session_dir(session_key)
+ run_id = datetime.now().strftime("%Y%m%d_%H%M%S")
+ while (session_dir / run_id).exists():
+ run_id = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
+ run_dir = ensure_dir(session_dir / run_id)
+ state = TeamState(
+ team_id=team_id or f"nano-{run_id[-6:]}",
+ run_id=run_id,
+ mission=plan.get("mission", ""),
+ members=[Teammate(**m) for m in plan["members"]],
+ status="active",
+ session_key=session_key,
+ )
+ state.save(run_dir / "config.json")
+ board.save(run_dir, [Task(**t) for t in plan["tasks"]])
+ (run_dir / "NOTES.md").write_text(plan.get("notes", "# Team Notes\n"), encoding="utf-8")
+ ensure_dir(run_dir / "workers")
+ for m in state.members:
+ ensure_dir(run_dir / "workers" / safe_filename(m.name))
+ (run_dir / "events.jsonl").touch(exist_ok=True)
+ return TeamRuntime(session_key=session_key, run_dir=run_dir, state=state)
+
+ def _next_task_id(self, runtime: TeamRuntime) -> str:
+ tasks = board.load(runtime.run_dir)
+ max_idx = 0
+ for t in tasks:
+ m = re.match(r"t(\d+)$", t.id)
+ if m:
+ max_idx = max(max_idx, int(m.group(1)))
+ return f"t{max_idx + 1}"
+
+ def _validate_plan_payload(self, payload: dict[str, Any], goal: str = "") -> tuple[dict[str, Any] | None, str | None]:
+ members_raw = payload.get("members")
+ if not isinstance(members_raw, list):
+ return None, "members must be a list"
+ members: list[dict[str, Any]] = []
+ seen_members: set[str] = set()
+ for item in members_raw:
+ if not isinstance(item, dict):
+ continue
+ name = str(item.get("name", "")).strip()
+ role = str(item.get("role", "")).strip()
+ if not name or not role:
+ continue
+ key = name.lower()
+ if key in seen_members:
+ return None, "duplicate member names"
+ seen_members.add(key)
+ members.append({"name": name, "role": role, "model": item.get("model")})
+ if len(members) < 2:
+ return None, "at least 2 members are required"
+ if len(members) > 3:
+ members = members[:3]
+
+ tasks_raw = payload.get("tasks")
+ if not isinstance(tasks_raw, list) or not tasks_raw:
+ return None, "tasks must be a non-empty list"
+ member_names = {m["name"] for m in members}
+ tasks: list[dict[str, Any]] = []
+ seen_task_ids: set[str] = set()
+ for idx, item in enumerate(tasks_raw, start=1):
+ if not isinstance(item, dict):
+ continue
+ title = str(item.get("title", "")).strip()
+ if not title:
+ continue
+ task_id = str(item.get("id", f"t{idx}")).strip() or f"t{idx}"
+ if task_id in seen_task_ids:
+ return None, "duplicate task ids"
+ seen_task_ids.add(task_id)
+ owner = str(item.get("owner", "")).strip() or None
+ if owner and owner not in member_names:
+ owner = None
+ deps_raw = item.get("depends_on")
+ deps = [str(d).strip() for d in deps_raw] if isinstance(deps_raw, list) else []
+ tasks.append({
+ "id": task_id,
+ "title": title,
+ "description": str(item.get("description", "")).strip(),
+ "owner": owner,
+ "depends_on": [d for d in deps if d],
+ "requires_approval": bool(item.get("requires_approval", False)),
+ })
+ if not tasks:
+ return None, "no valid tasks found"
+ task_ids = {t["id"] for t in tasks}
+ for t in tasks:
+ t["depends_on"] = [d for d in t["depends_on"] if d in task_ids]
+ if self._has_cycle(tasks):
+ return None, "task dependency graph has a cycle"
+ mission = str(payload.get("mission", "")).strip() or goal or "Complete the requested mission."
+ notes = str(payload.get("notes", "")).strip() or "# Team Notes\n"
+ return {
+ "mission": mission,
+ "members": members,
+ "tasks": tasks,
+ "notes": notes,
+ }, None
+
+ @staticmethod
+ def _has_cycle(tasks: list[dict[str, Any]]) -> bool:
+ graph = {t["id"]: list(t.get("depends_on", [])) for t in tasks}
+ visiting: set[str] = set()
+ visited: set[str] = set()
+
+ def dfs(node: str) -> bool:
+ if node in visited:
+ return False
+ if node in visiting:
+ return True
+ visiting.add(node)
+ for dep in graph.get(node, []):
+ if dep in graph and dfs(dep):
+ return True
+ visiting.remove(node)
+ visited.add(node)
+ return False
+
+ return any(dfs(node) for node in graph)
+
+ def _fallback_plan(self, goal: str) -> dict[str, Any]:
+ return {
+ "mission": goal,
+ "members": [
+ {"name": "researcher", "role": "research and analysis", "model": None},
+ {"name": "builder", "role": "execution and synthesis", "model": None},
+ ],
+ "tasks": [
+ {
+ "id": "t1",
+ "title": "Analyze the request",
+ "description": f"Break down the objective: {goal}",
+ "owner": "researcher",
+ "depends_on": [],
+ "requires_approval": False,
+ },
+ {
+ "id": "t2",
+ "title": "Execute and report",
+ "description": "Implement the solution and summarize concrete outcomes.",
+ "owner": "builder",
+ "depends_on": ["t1"],
+ "requires_approval": False,
+ },
+ ],
+ "notes": "# Team Notes\n- Keep changes minimal and reliable.\n",
+ }
+
+ def _recent_updates(self, runtime: TeamRuntime, n: int = 4) -> list[str]:
+ if not runtime.events_path.exists():
+ return []
+ lines = runtime.events_path.read_text(encoding="utf-8").splitlines()
+ out: list[str] = []
+ for line in reversed(lines):
+ try:
+ row = json.loads(line)
+ except Exception:
+ continue
+ kind = str(row.get("kind", ""))
+ if kind not in {
+ "lead_user_sync",
+ "worker_update",
+ "risk_gate",
+ "team_started",
+ "team_stopped",
+ "task_approved",
+ "task_rejected",
+ "task_change_requested",
+ }:
+ continue
+ msg = str(row.get("message", "")).strip()
+ if msg:
+ out.append(msg)
+ if len(out) >= n:
+ break
+ out.reverse()
+ return out
+
+ @staticmethod
+ def _looks_risky(text: str) -> bool:
+ lowered = text.lower()
+ tokens = (
+ "rm -rf",
+ "delete",
+ "drop table",
+ "truncate",
+ "reset --hard",
+ "format disk",
+ "wipe",
+ "shutdown",
+ "destroy",
+ )
+ return any(t in lowered for t in tokens)
+
+ # ------------------------------------------------------------------
+ # Worker runtime
+ # ------------------------------------------------------------------
+ def _set_member_status(self, runtime: TeamRuntime, name: str, status: str) -> None:
+ for mate in runtime.state.members:
+ if mate.name == name:
+ mate.status = status
+ break
+ runtime.state.save(runtime.run_dir / "config.json")
+
+ def _ensure_worker(self, runtime: TeamRuntime, name: str) -> None:
+ running = runtime.worker_tasks.get(name)
+ if running and not running.done():
+ return
+ mate = next((m for m in runtime.state.members if m.name == name), None)
+ if not mate:
+ return
+ task = asyncio.create_task(self._run_worker(runtime.session_key, mate.name))
+ runtime.worker_tasks[name] = task
+ task.add_done_callback(lambda _t, key=runtime.session_key, worker=name: self._cleanup_worker(key, worker))
+
+ def _cleanup_worker(self, session_key: str, worker: str) -> None:
+ runtime = self._active_by_session.get(session_key)
+ if not runtime:
+ return
+ runtime.worker_tasks.pop(worker, None)
+
+ async def _cancel_worker_tasks(self, runtime: TeamRuntime) -> int:
+ tasks = [t for t in runtime.worker_tasks.values() if not t.done()]
+ for t in tasks:
+ t.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ runtime.worker_tasks.clear()
+ return len(tasks)
+
+ async def _stop_runtime(self, runtime: TeamRuntime) -> None:
+ await self._cancel_worker_tasks(runtime)
+ current_tasks = board.load(runtime.run_dir)
+ completed = bool(current_tasks) and all(t.status == "completed" for t in current_tasks)
+ runtime.state.status = "completed" if completed else "paused"
+ for mate in runtime.state.members:
+ mate.status = "stopped" if completed else "idle"
+ runtime.state.save(runtime.run_dir / "config.json")
+ self._append_event(runtime, "team_stopped", f"Stopped team with status {runtime.state.status}")
+
+ def _build_worker_tools(self, runtime: TeamRuntime, mate: Teammate) -> "ToolRegistry":
+ tools = build_base_tools(
+ workspace=self.workspace,
+ exec_config=self.exec_config,
+ web_search_config=self.web_search_config,
+ web_proxy=self.web_proxy,
+ restrict_to_workspace=self.restrict_to_workspace,
+ )
+ tools.register(TeamWorkerTool(manager=self, worker_name=mate.name, session_key=runtime.session_key))
+ return tools
+
+ def _build_worker_prompt(self, runtime: TeamRuntime, mate: Teammate) -> str:
+ notes = (runtime.run_dir / "NOTES.md").read_text(encoding="utf-8") if (runtime.run_dir / "NOTES.md").exists() else ""
+ roster = "\n".join(f"- {m.name}: {m.role}" for m in runtime.state.members)
+ current = board.get_current(runtime.run_dir, mate.name)
+ current_text = f"{current.id} - {current.title} ({current.status})" if current else "No current task."
+ return f"""# Team Worker
+
+You are teammate '{mate.name}'.
+Role: {mate.role}
+
+## Team Members
+{roster}
+
+## Shared Notes
+{notes or "(empty)"}
+
+## Current Task
+{current_text}
+
+Use the `team_worker` tool to inspect the board, claim tasks, submit plans, complete tasks, and message teammates.
+Work autonomously and coordinate through the board and mailbox."""
+
+ def _save_worker_session(self, session: Session, messages: list[dict], skip: int) -> None:
+ for m in messages[skip:]:
+ entry = dict(m)
+ if entry.get("role") == "assistant" and not entry.get("content") and not entry.get("tool_calls"):
+ continue
+ if entry.get("role") == "tool" and isinstance(entry.get("content"), str) and len(entry["content"]) > 500:
+ entry["content"] = entry["content"][:500] + "\n... (truncated)"
+ entry.setdefault("timestamp", timestamp())
+ session.messages.append(entry)
+ session.updated_at = datetime.now()
+
+ def _append_lead_session(self, runtime: TeamRuntime, user_text: str, assistant_text: str) -> None:
+ session = self.sessions.get_or_create(f"team:{runtime.state.run_id}:lead")
+ session.add_message("user", user_text)
+ session.add_message("assistant", assistant_text)
+ self.sessions.save(session)
+
+ async def _maybe_emit_approval_prompt(self, runtime: TeamRuntime, task: Task | None) -> None:
+ if not task or task.status != "awaiting_approval":
+ return
+ if task.id in runtime.prompted_approvals:
+ return
+ channel, chat_id = runtime.session_key.split(":", 1) if ":" in runtime.session_key else ("cli", runtime.session_key)
+ if channel == "cli":
+ return
+ runtime.prompted_approvals.add(task.id)
+ plan = (task.plan or "").strip() or "No plan submitted."
+ text = (
+ f"Approval needed for `{task.id}: {task.title}` by `{task.owner or 'unknown'}`.\n"
+ f"Plan: {plan[:260]}\n\n"
+ "Reply naturally with your decision (approve / reject / change) and include the task id."
+ )
+ await self.bus.publish_outbound(OutboundMessage(
+ channel=channel,
+ chat_id=chat_id,
+ content=text,
+ metadata={"team_text": True, "team_event": True},
+ ))
+
+ async def _notify_lead(self, runtime: TeamRuntime, mate: Teammate, task: Task | None, result: str, status: str) -> None:
+ task_text = f"{task.id}: {task.title}" if task else "No active task"
+ compact = (result or "").strip().replace("\n", " ")
+ compact = compact[:220] + ("..." if len(compact) > 220 else "")
+ self._append_event(runtime, "worker_update", f"{mate.name} {status} | {task_text}", result=compact)
+ await self._emit_lead_update(runtime, f"Team lead: {mate.name} {status}. Task `{task_text}`. {compact}")
+ await self._maybe_emit_approval_prompt(runtime, task)
+
+ async def _run_worker(self, session_key: str, worker_name: str) -> None:
+ runtime = self._active_by_session.get(session_key)
+ if not runtime:
+ return
+ mate = next((m for m in runtime.state.members if m.name == worker_name), None)
+ if not mate:
+ return
+ logger.info("Team worker [{}] starting for session {}", mate.name, session_key)
+ self._set_member_status(runtime, mate.name, "working")
+ session = self.sessions.get_or_create(f"team:{runtime.state.run_id}:{mate.name}")
+ history = session.get_history(max_messages=60)
+ messages: list[dict[str, Any]] = [{"role": "system", "content": self._build_worker_prompt(runtime, mate)}]
+ if history:
+ messages.extend(history)
+ else:
+ messages.append({"role": "user", "content": "Inspect the board, claim a task if appropriate, and start working."})
+ tools = self._build_worker_tools(runtime, mate)
+ final_result = "No result."
+ skip = 1 + len(history)
+
+ try:
+ for _ in range(self.worker_max_iterations):
+ if runtime.session_key not in self._active_by_session:
+ final_result = "Team runtime ended."
+ break
+
+ unread = mailbox.read_unread(runtime.run_dir, mate.name)
+ if unread:
+ mail_text = "\n".join(f"[{m.from_agent}]: {m.content}" for m in unread)
+ messages.append({"role": "user", "content": f"New messages:\n{mail_text}"})
+
+ response = await self.provider.chat(
+ messages=messages,
+ tools=tools.get_definitions(),
+ model=mate.model or self.model,
+ temperature=self.temperature,
+ max_tokens=self.max_tokens,
+ reasoning_effort=self.reasoning_effort,
+ )
+ if response.has_tool_calls:
+ tool_calls = [{
+ "id": tc.id,
+ "type": "function",
+ "function": {"name": tc.name, "arguments": json.dumps(tc.arguments, ensure_ascii=False)},
+ } for tc in response.tool_calls]
+ messages.append({"role": "assistant", "content": response.content or "", "tool_calls": tool_calls})
+ for tool_call in response.tool_calls:
+ result = await tools.execute(tool_call.name, tool_call.arguments)
+ messages.append({
+ "role": "tool",
+ "tool_call_id": tool_call.id,
+ "name": tool_call.name,
+ "content": result,
+ })
+ else:
+ final_result = response.content or "Worker completed."
+ break
+
+ current = board.get_current(runtime.run_dir, mate.name)
+ if current and current.status == "awaiting_approval":
+ final_result = current.plan or "Awaiting plan approval."
+ self._set_member_status(runtime, mate.name, "waiting_approval")
+ break
+ if not current and not board.get_claimable(runtime.run_dir, mate.name):
+ final_result = "No more claimable tasks."
+ self._set_member_status(runtime, mate.name, "idle")
+ break
+ else:
+ final_result = f"Reached worker max iterations ({self.worker_max_iterations})."
+
+ self._save_worker_session(session, messages, skip)
+ self.sessions.save(session)
+ current = board.get_current(runtime.run_dir, mate.name)
+ if not current:
+ self._set_member_status(runtime, mate.name, "idle")
+ await self._notify_lead(runtime, mate, current, final_result, "status update")
+ except asyncio.CancelledError:
+ self._set_member_status(runtime, mate.name, "stopped")
+ raise
+ except Exception as e:
+ logger.exception("Team worker [{}] failed", mate.name)
+ self._set_member_status(runtime, mate.name, "stopped")
+ await self._notify_lead(runtime, mate, board.get_current(runtime.run_dir, mate.name), f"Error: {e}", "failed")
diff --git a/deeptutor/tutorbot/agent/team/_filelock.py b/deeptutor/tutorbot/agent/team/_filelock.py
new file mode 100644
index 000000000..392453172
--- /dev/null
+++ b/deeptutor/tutorbot/agent/team/_filelock.py
@@ -0,0 +1,23 @@
+"""Cross-platform file locking for board and mailbox."""
+
+from __future__ import annotations
+
+import sys
+
+if sys.platform == "win32":
+ import msvcrt
+
+ def lock(f) -> None:
+ msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 1)
+
+ def unlock(f) -> None:
+ f.seek(0)
+ msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
+else:
+ import fcntl
+
+ def lock(f) -> None:
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
+
+ def unlock(f) -> None:
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
diff --git a/deeptutor/tutorbot/agent/team/board.py b/deeptutor/tutorbot/agent/team/board.py
new file mode 100644
index 000000000..df0a42e9e
--- /dev/null
+++ b/deeptutor/tutorbot/agent/team/board.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from deeptutor.tutorbot.agent.team._filelock import lock, unlock
+from deeptutor.tutorbot.agent.team.state import Task, Teammate
+from deeptutor.tutorbot.utils.helpers import ensure_dir
+
+
+def _path(team_dir: Path) -> Path:
+ return ensure_dir(team_dir) / "tasks.json"
+
+
+def load(team_dir: Path) -> list[Task]:
+ path = _path(team_dir)
+ if not path.exists():
+ return []
+ return [Task.from_dict(item) for item in json.loads(path.read_text(encoding="utf-8") or "[]")]
+
+
+def save(team_dir: Path, tasks: list[Task]) -> None:
+ _path(team_dir).write_text(
+ json.dumps([t.__dict__ for t in tasks], ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+
+
+def _locked_update(team_dir: Path, update) -> Any:
+ path = _path(team_dir)
+ with open(path, "a+", encoding="utf-8") as f:
+ lock(f)
+ try:
+ f.seek(0)
+ raw = f.read().strip()
+ tasks = [Task.from_dict(item) for item in json.loads(raw or "[]")]
+ result = update(tasks)
+ f.seek(0)
+ f.truncate()
+ f.write(json.dumps([t.__dict__ for t in tasks], ensure_ascii=False, indent=2))
+ f.flush()
+ finally:
+ unlock(f)
+ return result
+
+
+def _deps_met(task: Task, tasks: list[Task]) -> bool:
+ done = {t.id for t in tasks if t.status == "completed"}
+ return all(dep in done for dep in task.depends_on)
+
+
+def claim(team_dir: Path, task_id: str, worker: str) -> str:
+ def _update(tasks: list[Task]) -> str:
+ for task in tasks:
+ if task.id != task_id:
+ continue
+ if task.owner and task.owner != worker:
+ return f"Error: task {task_id} is already owned by {task.owner}"
+ if task.status not in {"pending", "planning"}:
+ return f"Error: task {task_id} is not claimable (status: {task.status})"
+ if not _deps_met(task, tasks):
+ return f"Error: task {task_id} is blocked by dependencies"
+ task.owner = worker
+ task.status = "planning" if task.requires_approval else "in_progress"
+ return f"Claimed task {task_id}"
+ return f"Error: task {task_id} not found"
+
+ return _locked_update(team_dir, _update)
+
+
+def update_status(team_dir: Path, task_id: str, status: str, **fields: Any) -> str:
+ def _update(tasks: list[Task]) -> str:
+ for task in tasks:
+ if task.id == task_id:
+ task.status = status
+ for key, value in fields.items():
+ if hasattr(task, key):
+ setattr(task, key, value)
+ return f"Updated task {task_id} to {status}"
+ return f"Error: task {task_id} not found"
+
+ return _locked_update(team_dir, _update)
+
+
+def submit_plan(team_dir: Path, task_id: str, plan_text: str) -> str:
+ return update_status(team_dir, task_id, "awaiting_approval", plan=plan_text)
+
+
+def approve(team_dir: Path, task_id: str) -> str:
+ return update_status(team_dir, task_id, "in_progress")
+
+
+def reject(team_dir: Path, task_id: str, reason: str) -> str:
+ return update_status(team_dir, task_id, "planning", result=reason)
+
+
+def get_claimable(team_dir: Path, worker: str) -> list[Task]:
+ tasks = load(team_dir)
+ return [t for t in tasks if not t.owner and t.status == "pending" and _deps_met(t, tasks)]
+
+
+def get_current(team_dir: Path, worker: str) -> Task | None:
+ for task in load(team_dir):
+ if task.owner == worker and task.status in {"planning", "awaiting_approval", "in_progress"}:
+ return task
+ return None
+
+
+def add_task(team_dir: Path, task: Task) -> str:
+ return _locked_update(team_dir, lambda tasks: (tasks.append(task), f"Added task {task.id}")[1])
+
+
+def task_rows(tasks: list[Task]) -> list[dict[str, str]]:
+ return [{
+ "id": t.id,
+ "title": t.title,
+ "owner": t.owner or "—",
+ "status": t.status,
+ "depends": ", ".join(t.depends_on) or "—",
+ } for t in tasks]
+
+
+def member_rows(tasks: list[Task], members: list[Teammate]) -> list[dict[str, str]]:
+ current_by_owner = {t.owner: t for t in tasks if t.owner and t.status in {"planning", "awaiting_approval", "in_progress"}}
+ rows = []
+ for m in members:
+ current = current_by_owner.get(m.name)
+ rows.append({
+ "name": m.name,
+ "role": m.role,
+ "status": m.status,
+ "task": f"{current.id}: {current.title}" if current else "—",
+ })
+ return rows
+
+
+def approval_rows(tasks: list[Task]) -> list[dict[str, str]]:
+ return [{
+ "id": t.id,
+ "title": t.title,
+ "owner": t.owner or "—",
+ "plan": (t.plan or "").strip() or "No plan submitted.",
+ } for t in tasks if t.status == "awaiting_approval"]
+
+
+def render_text(tasks: list[Task], members: list[Teammate]) -> str:
+ if not tasks:
+ return "No team tasks."
+ member_text = "\n".join(
+ f"- {row['name']}: {row['role']} ({row['status']}) [{row['task']}]"
+ for row in member_rows(tasks, members)
+ ) or "- none"
+ task_text = "\n".join(
+ f"| {row['id']} | {row['title']} | {row['owner']} | {row['status']} | {row['depends']} |"
+ for row in task_rows(tasks)
+ )
+ return (
+ "## Members\n"
+ f"{member_text}\n\n"
+ "## Tasks\n"
+ "| ID | Title | Owner | Status | Depends |\n"
+ "| --- | --- | --- | --- | --- |\n"
+ f"{task_text}"
+ )
\ No newline at end of file
diff --git a/deeptutor/tutorbot/agent/team/mailbox.py b/deeptutor/tutorbot/agent/team/mailbox.py
new file mode 100644
index 000000000..cb3690ec7
--- /dev/null
+++ b/deeptutor/tutorbot/agent/team/mailbox.py
@@ -0,0 +1,92 @@
+from __future__ import annotations
+
+import json
+import uuid
+from pathlib import Path
+
+from deeptutor.tutorbot.agent.team._filelock import lock, unlock
+from deeptutor.tutorbot.agent.team.state import Mail
+from deeptutor.tutorbot.utils.helpers import ensure_dir, timestamp
+
+
+def _path(team_dir: Path) -> Path:
+ return ensure_dir(team_dir) / "mailbox.jsonl"
+
+
+def _load(team_dir: Path) -> list[Mail]:
+ path = _path(team_dir)
+ if not path.exists():
+ return []
+ return [
+ Mail.from_dict(json.loads(line))
+ for line in path.read_text(encoding="utf-8").splitlines()
+ if line.strip()
+ ]
+
+
+def _locked_update(team_dir: Path, update):
+ path = _path(team_dir)
+ with open(path, "a+", encoding="utf-8") as f:
+ lock(f)
+ try:
+ f.seek(0)
+ mails = [Mail.from_dict(json.loads(line)) for line in f if line.strip()]
+ result = update(mails)
+ del mails[:-200]
+ f.seek(0)
+ f.truncate()
+ if mails:
+ f.write("\n".join(json.dumps(m.__dict__, ensure_ascii=False) for m in mails) + "\n")
+ f.flush()
+ finally:
+ unlock(f)
+ return result
+
+
+def send(team_dir: Path, from_agent: str, to_agent: str, content: str) -> str:
+ def _update(mails: list[Mail]) -> str:
+ mails.append(Mail(
+ id=str(uuid.uuid4())[:8],
+ from_agent=from_agent,
+ to_agent=to_agent,
+ content=content,
+ timestamp=timestamp(),
+ ))
+ return f"Sent message to {to_agent}"
+
+ return _locked_update(team_dir, _update)
+
+
+def broadcast(team_dir: Path, from_agent: str, content: str) -> str:
+ return send(team_dir, from_agent, "*", content)
+
+
+def read_unread(team_dir: Path, agent_name: str) -> list[Mail]:
+ def _update(mails: list[Mail]) -> list[Mail]:
+ unread: list[Mail] = []
+ for mail in mails:
+ if mail.to_agent not in {agent_name, "*"} or agent_name in mail.read_by:
+ continue
+ mail.read_by.append(agent_name)
+ unread.append(mail)
+ return unread
+
+ return _locked_update(team_dir, _update)
+
+
+def recent_for(team_dir: Path, agent_name: str, n: int = 5) -> list[Mail]:
+ return [
+ m for m in _load(team_dir)
+ if m.to_agent in {agent_name, "*"} or m.from_agent == agent_name
+ ][-n:]
+
+
+def recent(team_dir: Path, n: int = 5) -> list[Mail]:
+ return _load(team_dir)[-n:]
+
+
+def render_recent(team_dir: Path, n: int = 5) -> str:
+ mails = recent(team_dir, n)
+ if not mails:
+ return "No recent messages."
+ return "\n".join(f"- [{m.from_agent} -> {m.to_agent}] {m.content}" for m in mails)
diff --git a/deeptutor/tutorbot/agent/team/state.py b/deeptutor/tutorbot/agent/team/state.py
new file mode 100644
index 000000000..a9e80c493
--- /dev/null
+++ b/deeptutor/tutorbot/agent/team/state.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+
+from deeptutor.tutorbot.utils.helpers import timestamp
+
+
+@dataclass
+class Task:
+ id: str
+ title: str
+ description: str = ""
+ owner: str | None = None
+ status: str = "pending"
+ depends_on: list[str] = field(default_factory=list)
+ plan: str | None = None
+ result: str | None = None
+ requires_approval: bool = False
+
+ @classmethod
+ def from_dict(cls, data: dict) -> "Task":
+ return cls(**data)
+
+
+@dataclass
+class Teammate:
+ name: str
+ role: str
+ model: str | None = None
+ status: str = "idle"
+
+ @classmethod
+ def from_dict(cls, data: dict) -> "Teammate":
+ return cls(**data)
+
+
+@dataclass
+class Mail:
+ id: str
+ from_agent: str
+ to_agent: str
+ content: str
+ timestamp: str
+ read_by: list[str] = field(default_factory=list)
+
+ @classmethod
+ def from_dict(cls, data: dict) -> "Mail":
+ return cls(**data)
+
+
+@dataclass
+class TeamState:
+ team_id: str
+ run_id: str = ""
+ mission: str = ""
+ lead: str = "lead"
+ members: list[Teammate] = field(default_factory=list)
+ status: str = "active"
+ created_at: str = field(default_factory=timestamp)
+ session_key: str = "cli:direct"
+
+ def to_dict(self) -> dict:
+ return asdict(self)
+
+ def save(self, path: Path) -> None:
+ path.write_text(json.dumps(self.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
+
+ @classmethod
+ def from_dict(cls, data: dict) -> "TeamState":
+ return cls(
+ team_id=data["team_id"],
+ run_id=data.get("run_id", data.get("team_id", "")),
+ mission=data.get("mission", ""),
+ lead=data.get("lead", "lead"),
+ members=[Teammate.from_dict(m) for m in data.get("members", [])],
+ status=data.get("status", "active"),
+ created_at=data.get("created_at", timestamp()),
+ session_key=data.get("session_key", "cli:direct"),
+ )
+
+ @classmethod
+ def load(cls, path: Path) -> "TeamState":
+ return cls.from_dict(json.loads(path.read_text(encoding="utf-8")))
diff --git a/deeptutor/tutorbot/agent/team/tools.py b/deeptutor/tutorbot/agent/team/tools.py
new file mode 100644
index 000000000..d6db11208
--- /dev/null
+++ b/deeptutor/tutorbot/agent/team/tools.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+from . import board, mailbox
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.agent.team import TeamManager
+
+
+class TeamTool(Tool):
+ def __init__(self, manager: "TeamManager"):
+ self._manager = manager
+ self._session_key = "cli:direct"
+
+ def set_context(self, channel: str, chat_id: str) -> None:
+ self._session_key = f"{channel}:{chat_id}"
+
+ @property
+ def name(self) -> str:
+ return "team"
+
+ @property
+ def description(self) -> str:
+ return "Internal team orchestration API."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": [
+ "create",
+ "resume",
+ "shutdown",
+ "board",
+ "approve",
+ "reject",
+ "message",
+ "add_task",
+ ],
+ },
+ "team_id": {"type": "string"},
+ "members": {"type": "array", "items": {"type": "object"}},
+ "tasks": {"type": "array", "items": {"type": "object"}},
+ "notes": {"type": "string"},
+ "mission": {"type": "string"},
+ "task_id": {"type": "string"},
+ "reason": {"type": "string"},
+ "to": {"type": "string"},
+ "content": {"type": "string"},
+ "task": {"type": "object"},
+ },
+ "required": ["action"],
+ }
+
+ async def execute(self, action: str, **kwargs: Any) -> str:
+ sk = self._session_key
+ if action == "create":
+ return await self._manager.create(
+ sk,
+ kwargs.get("team_id") or "team",
+ kwargs.get("members") or [],
+ kwargs.get("tasks") or [],
+ kwargs.get("notes") or "",
+ mission=kwargs.get("mission") or "",
+ )
+ if action == "resume":
+ return await self._manager.resume(sk, kwargs.get("team_id") or "")
+ if action == "shutdown":
+ return await self._manager.shutdown(sk)
+ if action == "board":
+ return self._manager.render_board(sk)
+ if action == "approve":
+ return self._manager.approve_for_session(sk, kwargs.get("task_id") or "")
+ if action == "reject":
+ return self._manager.reject_for_session(sk, kwargs.get("task_id") or "", kwargs.get("reason") or "Rejected")
+ if action == "message":
+ return await self._manager.message_worker(sk, kwargs.get("to") or "", kwargs.get("content") or "")
+ if action == "add_task":
+ return self._manager.add_task(sk, kwargs.get("task") or {})
+ return f"Error: unknown action '{action}'"
+
+
+class TeamWorkerTool(Tool):
+ def __init__(self, manager: "TeamManager", worker_name: str, session_key: str):
+ self._manager = manager
+ self._worker_name = worker_name
+ self._session_key = session_key
+
+ @property
+ def name(self) -> str:
+ return "team_worker"
+
+ @property
+ def description(self) -> str:
+ return "Team coordination. Actions: board, claim, complete, submit_plan, mail_send, mail_read, mail_broadcast."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["board", "claim", "complete", "submit_plan", "mail_send", "mail_read", "mail_broadcast"],
+ },
+ "task_id": {"type": "string"},
+ "result": {"type": "string"},
+ "plan": {"type": "string"},
+ "to": {"type": "string"},
+ "content": {"type": "string"},
+ },
+ "required": ["action"],
+ }
+
+ async def execute(self, action: str, **kwargs: Any) -> str:
+ team_dir = self._manager.get_team_dir(self._session_key)
+ state = self._manager.get_team_state(self._session_key)
+ if not team_dir or not state:
+ return "Error: no active team"
+
+ if action == "board":
+ return board.render_text(board.load(team_dir), state.members)
+ if action == "claim":
+ return board.claim(team_dir, kwargs.get("task_id") or "", self._worker_name)
+ if action == "complete":
+ return board.update_status(team_dir, kwargs.get("task_id") or "", "completed", result=kwargs.get("result"))
+ if action == "submit_plan":
+ return board.submit_plan(team_dir, kwargs.get("task_id") or "", kwargs.get("plan") or "")
+ if action == "mail_send":
+ return mailbox.send(team_dir, self._worker_name, kwargs.get("to") or "", kwargs.get("content") or "")
+ if action == "mail_read":
+ unread = mailbox.read_unread(team_dir, self._worker_name)
+ return "\n".join(f"- [{m.from_agent}] {m.content}" for m in unread) or "No unread messages."
+ if action == "mail_broadcast":
+ return mailbox.broadcast(team_dir, self._worker_name, kwargs.get("content") or "")
+ return f"Error: unknown action '{action}'"
diff --git a/deeptutor/tutorbot/agent/tools/__init__.py b/deeptutor/tutorbot/agent/tools/__init__.py
new file mode 100644
index 000000000..b3e893e8b
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/__init__.py
@@ -0,0 +1,6 @@
+"""Agent tools module."""
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+from deeptutor.tutorbot.agent.tools.registry import ToolRegistry
+
+__all__ = ["Tool", "ToolRegistry"]
diff --git a/deeptutor/tutorbot/agent/tools/base.py b/deeptutor/tutorbot/agent/tools/base.py
new file mode 100644
index 000000000..06f5bddac
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/base.py
@@ -0,0 +1,181 @@
+"""Base class for agent tools."""
+
+from abc import ABC, abstractmethod
+from typing import Any
+
+
+class Tool(ABC):
+ """
+ Abstract base class for agent tools.
+
+ Tools are capabilities that the agent can use to interact with
+ the environment, such as reading files, executing commands, etc.
+ """
+
+ _TYPE_MAP = {
+ "string": str,
+ "integer": int,
+ "number": (int, float),
+ "boolean": bool,
+ "array": list,
+ "object": dict,
+ }
+
+ @property
+ @abstractmethod
+ def name(self) -> str:
+ """Tool name used in function calls."""
+ pass
+
+ @property
+ @abstractmethod
+ def description(self) -> str:
+ """Description of what the tool does."""
+ pass
+
+ @property
+ @abstractmethod
+ def parameters(self) -> dict[str, Any]:
+ """JSON Schema for tool parameters."""
+ pass
+
+ @abstractmethod
+ async def execute(self, **kwargs: Any) -> str:
+ """
+ Execute the tool with given parameters.
+
+ Args:
+ **kwargs: Tool-specific parameters.
+
+ Returns:
+ String result of the tool execution.
+ """
+ pass
+
+ def cast_params(self, params: dict[str, Any]) -> dict[str, Any]:
+ """Apply safe schema-driven casts before validation."""
+ schema = self.parameters or {}
+ if schema.get("type", "object") != "object":
+ return params
+
+ return self._cast_object(params, schema)
+
+ def _cast_object(self, obj: Any, schema: dict[str, Any]) -> dict[str, Any]:
+ """Cast an object (dict) according to schema."""
+ if not isinstance(obj, dict):
+ return obj
+
+ props = schema.get("properties", {})
+ result = {}
+
+ for key, value in obj.items():
+ if key in props:
+ result[key] = self._cast_value(value, props[key])
+ else:
+ result[key] = value
+
+ return result
+
+ def _cast_value(self, val: Any, schema: dict[str, Any]) -> Any:
+ """Cast a single value according to schema."""
+ target_type = schema.get("type")
+
+ if target_type == "boolean" and isinstance(val, bool):
+ return val
+ if target_type == "integer" and isinstance(val, int) and not isinstance(val, bool):
+ return val
+ if target_type in self._TYPE_MAP and target_type not in ("boolean", "integer", "array", "object"):
+ expected = self._TYPE_MAP[target_type]
+ if isinstance(val, expected):
+ return val
+
+ if target_type == "integer" and isinstance(val, str):
+ try:
+ return int(val)
+ except ValueError:
+ return val
+
+ if target_type == "number" and isinstance(val, str):
+ try:
+ return float(val)
+ except ValueError:
+ return val
+
+ if target_type == "string":
+ return val if val is None else str(val)
+
+ if target_type == "boolean" and isinstance(val, str):
+ val_lower = val.lower()
+ if val_lower in ("true", "1", "yes"):
+ return True
+ if val_lower in ("false", "0", "no"):
+ return False
+ return val
+
+ if target_type == "array" and isinstance(val, list):
+ item_schema = schema.get("items")
+ return [self._cast_value(item, item_schema) for item in val] if item_schema else val
+
+ if target_type == "object" and isinstance(val, dict):
+ return self._cast_object(val, schema)
+
+ return val
+
+ def validate_params(self, params: dict[str, Any]) -> list[str]:
+ """Validate tool parameters against JSON schema. Returns error list (empty if valid)."""
+ if not isinstance(params, dict):
+ return [f"parameters must be an object, got {type(params).__name__}"]
+ schema = self.parameters or {}
+ if schema.get("type", "object") != "object":
+ raise ValueError(f"Schema must be object type, got {schema.get('type')!r}")
+ return self._validate(params, {**schema, "type": "object"}, "")
+
+ def _validate(self, val: Any, schema: dict[str, Any], path: str) -> list[str]:
+ t, label = schema.get("type"), path or "parameter"
+ if t == "integer" and (not isinstance(val, int) or isinstance(val, bool)):
+ return [f"{label} should be integer"]
+ if t == "number" and (
+ not isinstance(val, self._TYPE_MAP[t]) or isinstance(val, bool)
+ ):
+ return [f"{label} should be number"]
+ if t in self._TYPE_MAP and t not in ("integer", "number") and not isinstance(val, self._TYPE_MAP[t]):
+ return [f"{label} should be {t}"]
+
+ errors = []
+ if "enum" in schema and val not in schema["enum"]:
+ errors.append(f"{label} must be one of {schema['enum']}")
+ if t in ("integer", "number"):
+ if "minimum" in schema and val < schema["minimum"]:
+ errors.append(f"{label} must be >= {schema['minimum']}")
+ if "maximum" in schema and val > schema["maximum"]:
+ errors.append(f"{label} must be <= {schema['maximum']}")
+ if t == "string":
+ if "minLength" in schema and len(val) < schema["minLength"]:
+ errors.append(f"{label} must be at least {schema['minLength']} chars")
+ if "maxLength" in schema and len(val) > schema["maxLength"]:
+ errors.append(f"{label} must be at most {schema['maxLength']} chars")
+ if t == "object":
+ props = schema.get("properties", {})
+ for k in schema.get("required", []):
+ if k not in val:
+ errors.append(f"missing required {path + '.' + k if path else k}")
+ for k, v in val.items():
+ if k in props:
+ errors.extend(self._validate(v, props[k], path + "." + k if path else k))
+ if t == "array" and "items" in schema:
+ for i, item in enumerate(val):
+ errors.extend(
+ self._validate(item, schema["items"], f"{path}[{i}]" if path else f"[{i}]")
+ )
+ return errors
+
+ def to_schema(self) -> dict[str, Any]:
+ """Convert tool to OpenAI function schema format."""
+ return {
+ "type": "function",
+ "function": {
+ "name": self.name,
+ "description": self.description,
+ "parameters": self.parameters,
+ },
+ }
diff --git a/deeptutor/tutorbot/agent/tools/cron.py b/deeptutor/tutorbot/agent/tools/cron.py
new file mode 100644
index 000000000..ee16e8dab
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/cron.py
@@ -0,0 +1,158 @@
+"""Cron tool for scheduling reminders and tasks."""
+
+from contextvars import ContextVar
+from typing import Any
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+from deeptutor.tutorbot.cron.service import CronService
+from deeptutor.tutorbot.cron.types import CronSchedule
+
+
+class CronTool(Tool):
+ """Tool to schedule reminders and recurring tasks."""
+
+ def __init__(self, cron_service: CronService):
+ self._cron = cron_service
+ self._channel = ""
+ self._chat_id = ""
+ self._in_cron_context: ContextVar[bool] = ContextVar("cron_in_context", default=False)
+
+ def set_context(self, channel: str, chat_id: str) -> None:
+ """Set the current session context for delivery."""
+ self._channel = channel
+ self._chat_id = chat_id
+
+ def set_cron_context(self, active: bool):
+ """Mark whether the tool is executing inside a cron job callback."""
+ return self._in_cron_context.set(active)
+
+ def reset_cron_context(self, token) -> None:
+ """Restore previous cron context."""
+ self._in_cron_context.reset(token)
+
+ @property
+ def name(self) -> str:
+ return "cron"
+
+ @property
+ def description(self) -> str:
+ return "Schedule reminders and recurring tasks. Actions: add, list, remove."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["add", "list", "remove"],
+ "description": "Action to perform",
+ },
+ "message": {"type": "string", "description": "Reminder message (for add)"},
+ "every_seconds": {
+ "type": "integer",
+ "description": "Interval in seconds (for recurring tasks)",
+ },
+ "cron_expr": {
+ "type": "string",
+ "description": "Cron expression like '0 9 * * *' (for scheduled tasks)",
+ },
+ "tz": {
+ "type": "string",
+ "description": "IANA timezone for cron expressions (e.g. 'America/Vancouver')",
+ },
+ "at": {
+ "type": "string",
+ "description": "ISO datetime for one-time execution (e.g. '2026-02-12T10:30:00')",
+ },
+ "job_id": {"type": "string", "description": "Job ID (for remove)"},
+ },
+ "required": ["action"],
+ }
+
+ async def execute(
+ self,
+ action: str,
+ message: str = "",
+ every_seconds: int | None = None,
+ cron_expr: str | None = None,
+ tz: str | None = None,
+ at: str | None = None,
+ job_id: str | None = None,
+ **kwargs: Any,
+ ) -> str:
+ if action == "add":
+ if self._in_cron_context.get():
+ return "Error: cannot schedule new jobs from within a cron job execution"
+ return self._add_job(message, every_seconds, cron_expr, tz, at)
+ elif action == "list":
+ return self._list_jobs()
+ elif action == "remove":
+ return self._remove_job(job_id)
+ return f"Unknown action: {action}"
+
+ def _add_job(
+ self,
+ message: str,
+ every_seconds: int | None,
+ cron_expr: str | None,
+ tz: str | None,
+ at: str | None,
+ ) -> str:
+ if not message:
+ return "Error: message is required for add"
+ if not self._channel or not self._chat_id:
+ return "Error: no session context (channel/chat_id)"
+ if tz and not cron_expr:
+ return "Error: tz can only be used with cron_expr"
+ if tz:
+ from zoneinfo import ZoneInfo
+
+ try:
+ ZoneInfo(tz)
+ except (KeyError, Exception):
+ return f"Error: unknown timezone '{tz}'"
+
+ # Build schedule
+ delete_after = False
+ if every_seconds:
+ schedule = CronSchedule(kind="every", every_ms=every_seconds * 1000)
+ elif cron_expr:
+ schedule = CronSchedule(kind="cron", expr=cron_expr, tz=tz)
+ elif at:
+ from datetime import datetime
+
+ try:
+ dt = datetime.fromisoformat(at)
+ except ValueError:
+ return f"Error: invalid ISO datetime format '{at}'. Expected format: YYYY-MM-DDTHH:MM:SS"
+ at_ms = int(dt.timestamp() * 1000)
+ schedule = CronSchedule(kind="at", at_ms=at_ms)
+ delete_after = True
+ else:
+ return "Error: either every_seconds, cron_expr, or at is required"
+
+ job = self._cron.add_job(
+ name=message[:30],
+ schedule=schedule,
+ message=message,
+ deliver=True,
+ channel=self._channel,
+ to=self._chat_id,
+ delete_after_run=delete_after,
+ )
+ return f"Created job '{job.name}' (id: {job.id})"
+
+ def _list_jobs(self) -> str:
+ jobs = self._cron.list_jobs()
+ if not jobs:
+ return "No scheduled jobs."
+ lines = [f"- {j.name} (id: {j.id}, {j.schedule.kind})" for j in jobs]
+ return "Scheduled jobs:\n" + "\n".join(lines)
+
+ def _remove_job(self, job_id: str | None) -> str:
+ if not job_id:
+ return "Error: job_id is required for remove"
+ if self._cron.remove_job(job_id):
+ return f"Removed job {job_id}"
+ return f"Job {job_id} not found"
diff --git a/deeptutor/tutorbot/agent/tools/deeptutor_tools.py b/deeptutor/tutorbot/agent/tools/deeptutor_tools.py
new file mode 100644
index 000000000..d987cde85
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/deeptutor_tools.py
@@ -0,0 +1,276 @@
+"""Adapter tools that expose DeepTutor capabilities as TutorBot function-calling tools."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+
+
+class BrainstormAdapterTool(Tool):
+ @property
+ def name(self) -> str:
+ return "brainstorm"
+
+ @property
+ def description(self) -> str:
+ return "Broadly explore multiple possibilities for a topic and give a short rationale for each."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "topic": {
+ "type": "string",
+ "description": "The topic, goal, or problem to brainstorm about.",
+ },
+ "context": {
+ "type": "string",
+ "description": "Optional supporting context, constraints, or background.",
+ },
+ },
+ "required": ["topic"],
+ }
+
+ async def execute(self, **kwargs: Any) -> str:
+ from deeptutor.tools.brainstorm import brainstorm
+
+ result = await brainstorm(
+ topic=kwargs.get("topic", ""),
+ context=kwargs.get("context", ""),
+ )
+ return result.get("answer", "")
+
+
+class RAGAdapterTool(Tool):
+ @property
+ def name(self) -> str:
+ return "rag"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Search a knowledge base using Retrieval-Augmented Generation. "
+ "Returns relevant passages and an LLM-synthesised answer."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query."},
+ "kb_name": {
+ "type": "string",
+ "description": "Knowledge base to search.",
+ },
+ "mode": {
+ "type": "string",
+ "description": "Search mode.",
+ "enum": ["naive", "local", "global", "hybrid"],
+ },
+ },
+ "required": ["query"],
+ }
+
+ async def execute(self, **kwargs: Any) -> str:
+ from deeptutor.tools.rag_tool import rag_search
+
+ result = await rag_search(
+ query=kwargs.get("query", ""),
+ kb_name=kwargs.get("kb_name"),
+ )
+ return result.get("answer") or result.get("content", "")
+
+
+class CodeExecutionAdapterTool(Tool):
+ _CODEGEN_SYSTEM_PROMPT = (
+ "You are a Python code generator.\n"
+ "Convert the user's natural-language request into executable Python code only.\n"
+ "Rules:\n"
+ "- Output only Python code, with no markdown fences or explanation.\n"
+ "- Prefer standard library plus common packages: math, numpy, pandas, matplotlib, scipy, sympy.\n"
+ "- Print the final answer to stdout.\n"
+ "- Keep the code focused on the requested computation."
+ )
+
+ @property
+ def name(self) -> str:
+ return "code_execution"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Turn a natural-language computation request into Python, "
+ "run it in a sandboxed worker, and return the result."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "intent": {
+ "type": "string",
+ "description": "Natural-language description of the computation or verification task.",
+ },
+ "code": {
+ "type": "string",
+ "description": "Optional raw Python code to execute directly.",
+ },
+ "timeout": {
+ "type": "integer",
+ "description": "Max execution time in seconds.",
+ },
+ },
+ "required": ["intent"],
+ }
+
+ async def execute(self, **kwargs: Any) -> str:
+ from deeptutor.tools.code_executor import run_code
+
+ code = str(kwargs.get("code") or "").strip()
+ intent = str(kwargs.get("intent") or "").strip()
+ timeout = int(kwargs.get("timeout", 30) or 30)
+
+ if not code:
+ if not intent:
+ return "Error: code_execution requires either 'intent' or 'code'."
+ code = await self._generate_code(intent)
+
+ result = await run_code(language="python", code=code, timeout=timeout)
+ stdout = result.get("stdout", "")
+ stderr = result.get("stderr", "")
+ exit_code = result.get("exit_code", 1)
+
+ parts: list[str] = []
+ if stdout:
+ parts.append(stdout.strip())
+ if stderr:
+ label = "Error" if exit_code else "Stderr"
+ parts.append(f"{label}:\n{stderr.strip()}")
+ return "\n\n".join(parts) if parts else "Execution completed with no output."
+
+ async def _generate_code(self, intent: str) -> str:
+ from deeptutor.services.llm import complete, get_token_limit_kwargs
+ from deeptutor.services.llm.config import get_llm_config
+
+ cfg = get_llm_config()
+ extra: dict[str, Any] = {"temperature": 0.0}
+ if cfg.model:
+ extra.update(get_token_limit_kwargs(cfg.model, 1200))
+
+ response = await complete(
+ prompt=intent,
+ system_prompt=self._CODEGEN_SYSTEM_PROMPT,
+ model=cfg.model,
+ api_key=cfg.api_key,
+ base_url=cfg.base_url,
+ api_version=getattr(cfg, "api_version", None),
+ binding=getattr(cfg, "binding", None),
+ **extra,
+ )
+ cleaned = response.strip()
+ if cleaned.startswith("```"):
+ lines = cleaned.splitlines()
+ lines = lines[1:] if lines[0].startswith("```") else lines
+ if lines and lines[-1].strip() == "```":
+ lines = lines[:-1]
+ cleaned = "\n".join(lines).strip()
+ if not cleaned:
+ raise ValueError("LLM returned empty code for code_execution")
+ return cleaned
+
+
+class ReasonAdapterTool(Tool):
+ @property
+ def name(self) -> str:
+ return "reason"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Perform deep reasoning on a complex sub-problem using a dedicated LLM call. "
+ "Use when the current context is insufficient for a confident answer."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "The sub-problem to reason about.",
+ },
+ "context": {
+ "type": "string",
+ "description": "Supporting context for reasoning.",
+ },
+ },
+ "required": ["query"],
+ }
+
+ async def execute(self, **kwargs: Any) -> str:
+ from deeptutor.tools.reason import reason
+
+ result = await reason(
+ query=kwargs.get("query", ""),
+ context=kwargs.get("context", ""),
+ )
+ return result.get("answer", "")
+
+
+class PaperSearchAdapterTool(Tool):
+ @property
+ def name(self) -> str:
+ return "paper_search"
+
+ @property
+ def description(self) -> str:
+ return "Search arXiv preprints by keyword and return concise metadata."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query."},
+ "max_results": {
+ "type": "integer",
+ "description": "Maximum papers to return.",
+ },
+ "years_limit": {
+ "type": "integer",
+ "description": "Only include preprints from the last N years.",
+ },
+ "sort_by": {
+ "type": "string",
+ "description": "Sort by relevance or submission date.",
+ "enum": ["relevance", "date"],
+ },
+ },
+ "required": ["query"],
+ }
+
+ async def execute(self, **kwargs: Any) -> str:
+ from deeptutor.tools.paper_search_tool import ArxivSearchTool
+
+ papers = await ArxivSearchTool().search_papers(
+ query=kwargs.get("query", ""),
+ max_results=kwargs.get("max_results", 3),
+ years_limit=kwargs.get("years_limit", 3),
+ sort_by=kwargs.get("sort_by", "relevance"),
+ )
+ if not papers:
+ return "No arXiv preprints found for this query."
+
+ lines: list[str] = []
+ for p in papers:
+ lines.append(f"**{p['title']}** ({p.get('year', '?')})")
+ lines.append(f"Authors: {', '.join(p.get('authors', []))}")
+ lines.append(f"arXiv: {p.get('arxiv_id', '')} URL: {p.get('url', '')}")
+ lines.append(f"Abstract: {p.get('abstract', '')[:400]}")
+ lines.append("")
+ return "\n".join(lines)
diff --git a/deeptutor/tutorbot/agent/tools/filesystem.py b/deeptutor/tutorbot/agent/tools/filesystem.py
new file mode 100644
index 000000000..84938455a
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/filesystem.py
@@ -0,0 +1,365 @@
+"""File system tools: read, write, edit, list."""
+
+import difflib
+from pathlib import Path
+from typing import Any
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+
+
+def _resolve_path(
+ path: str, workspace: Path | None = None, allowed_dir: Path | None = None
+) -> Path:
+ """Resolve path against workspace (if relative) and enforce directory restriction."""
+ p = Path(path).expanduser()
+ if not p.is_absolute() and workspace:
+ p = workspace / p
+ resolved = p.resolve()
+ if allowed_dir:
+ try:
+ resolved.relative_to(allowed_dir.resolve())
+ except ValueError:
+ raise PermissionError(f"Path {path} is outside allowed directory {allowed_dir}")
+ return resolved
+
+
+class _FsTool(Tool):
+ """Shared base for filesystem tools — common init and path resolution."""
+
+ def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None):
+ self._workspace = workspace
+ self._allowed_dir = allowed_dir
+
+ def _resolve(self, path: str) -> Path:
+ return _resolve_path(path, self._workspace, self._allowed_dir)
+
+
+# ---------------------------------------------------------------------------
+# read_file
+# ---------------------------------------------------------------------------
+
+class ReadFileTool(_FsTool):
+ """Read file contents with optional line-based pagination."""
+
+ _MAX_CHARS = 128_000
+ _DEFAULT_LIMIT = 2000
+
+ @property
+ def name(self) -> str:
+ return "read_file"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Read the contents of a file. Returns numbered lines. "
+ "Use offset and limit to paginate through large files."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {"type": "string", "description": "The file path to read"},
+ "offset": {
+ "type": "integer",
+ "description": "Line number to start reading from (1-indexed, default 1)",
+ "minimum": 1,
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Maximum number of lines to read (default 2000)",
+ "minimum": 1,
+ },
+ },
+ "required": ["path"],
+ }
+
+ async def execute(self, path: str, offset: int = 1, limit: int | None = None, **kwargs: Any) -> str:
+ try:
+ fp = self._resolve(path)
+ if not fp.exists():
+ return f"Error: File not found: {path}"
+ if not fp.is_file():
+ return f"Error: Not a file: {path}"
+
+ all_lines = fp.read_text(encoding="utf-8").splitlines()
+ total = len(all_lines)
+
+ if offset < 1:
+ offset = 1
+ if total == 0:
+ return f"(Empty file: {path})"
+ if offset > total:
+ return f"Error: offset {offset} is beyond end of file ({total} lines)"
+
+ start = offset - 1
+ end = min(start + (limit or self._DEFAULT_LIMIT), total)
+ numbered = [f"{start + i + 1}| {line}" for i, line in enumerate(all_lines[start:end])]
+ result = "\n".join(numbered)
+
+ if len(result) > self._MAX_CHARS:
+ trimmed, chars = [], 0
+ for line in numbered:
+ chars += len(line) + 1
+ if chars > self._MAX_CHARS:
+ break
+ trimmed.append(line)
+ end = start + len(trimmed)
+ result = "\n".join(trimmed)
+
+ if end < total:
+ result += f"\n\n(Showing lines {offset}-{end} of {total}. Use offset={end + 1} to continue.)"
+ else:
+ result += f"\n\n(End of file — {total} lines total)"
+ return result
+ except PermissionError as e:
+ return f"Error: {e}"
+ except Exception as e:
+ return f"Error reading file: {e}"
+
+
+# ---------------------------------------------------------------------------
+# write_file
+# ---------------------------------------------------------------------------
+
+class WriteFileTool(_FsTool):
+ """Write content to a file."""
+
+ @property
+ def name(self) -> str:
+ return "write_file"
+
+ @property
+ def description(self) -> str:
+ return "Write content to a file at the given path. Creates parent directories if needed."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {"type": "string", "description": "The file path to write to"},
+ "content": {"type": "string", "description": "The content to write"},
+ },
+ "required": ["path", "content"],
+ }
+
+ async def execute(self, path: str, content: str, **kwargs: Any) -> str:
+ try:
+ fp = self._resolve(path)
+ fp.parent.mkdir(parents=True, exist_ok=True)
+ fp.write_text(content, encoding="utf-8")
+ return f"Successfully wrote {len(content)} bytes to {fp}"
+ except PermissionError as e:
+ return f"Error: {e}"
+ except Exception as e:
+ return f"Error writing file: {e}"
+
+
+# ---------------------------------------------------------------------------
+# edit_file
+# ---------------------------------------------------------------------------
+
+def _find_match(content: str, old_text: str) -> tuple[str | None, int]:
+ """Locate old_text in content: exact first, then line-trimmed sliding window.
+
+ Both inputs should use LF line endings (caller normalises CRLF).
+ Returns (matched_fragment, count) or (None, 0).
+ """
+ if old_text in content:
+ return old_text, content.count(old_text)
+
+ old_lines = old_text.splitlines()
+ if not old_lines:
+ return None, 0
+ stripped_old = [l.strip() for l in old_lines]
+ content_lines = content.splitlines()
+
+ candidates = []
+ for i in range(len(content_lines) - len(stripped_old) + 1):
+ window = content_lines[i : i + len(stripped_old)]
+ if [l.strip() for l in window] == stripped_old:
+ candidates.append("\n".join(window))
+
+ if candidates:
+ return candidates[0], len(candidates)
+ return None, 0
+
+
+class EditFileTool(_FsTool):
+ """Edit a file by replacing text with fallback matching."""
+
+ @property
+ def name(self) -> str:
+ return "edit_file"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Edit a file by replacing old_text with new_text. "
+ "Supports minor whitespace/line-ending differences. "
+ "Set replace_all=true to replace every occurrence."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {"type": "string", "description": "The file path to edit"},
+ "old_text": {"type": "string", "description": "The text to find and replace"},
+ "new_text": {"type": "string", "description": "The text to replace with"},
+ "replace_all": {
+ "type": "boolean",
+ "description": "Replace all occurrences (default false)",
+ },
+ },
+ "required": ["path", "old_text", "new_text"],
+ }
+
+ async def execute(
+ self, path: str, old_text: str, new_text: str,
+ replace_all: bool = False, **kwargs: Any,
+ ) -> str:
+ try:
+ fp = self._resolve(path)
+ if not fp.exists():
+ return f"Error: File not found: {path}"
+
+ raw = fp.read_bytes()
+ uses_crlf = b"\r\n" in raw
+ content = raw.decode("utf-8").replace("\r\n", "\n")
+ match, count = _find_match(content, old_text.replace("\r\n", "\n"))
+
+ if match is None:
+ return self._not_found_msg(old_text, content, path)
+ if count > 1 and not replace_all:
+ return (
+ f"Warning: old_text appears {count} times. "
+ "Provide more context to make it unique, or set replace_all=true."
+ )
+
+ norm_new = new_text.replace("\r\n", "\n")
+ new_content = content.replace(match, norm_new) if replace_all else content.replace(match, norm_new, 1)
+ if uses_crlf:
+ new_content = new_content.replace("\n", "\r\n")
+
+ fp.write_bytes(new_content.encode("utf-8"))
+ return f"Successfully edited {fp}"
+ except PermissionError as e:
+ return f"Error: {e}"
+ except Exception as e:
+ return f"Error editing file: {e}"
+
+ @staticmethod
+ def _not_found_msg(old_text: str, content: str, path: str) -> str:
+ lines = content.splitlines(keepends=True)
+ old_lines = old_text.splitlines(keepends=True)
+ window = len(old_lines)
+
+ best_ratio, best_start = 0.0, 0
+ for i in range(max(1, len(lines) - window + 1)):
+ ratio = difflib.SequenceMatcher(None, old_lines, lines[i : i + window]).ratio()
+ if ratio > best_ratio:
+ best_ratio, best_start = ratio, i
+
+ if best_ratio > 0.5:
+ diff = "\n".join(difflib.unified_diff(
+ old_lines, lines[best_start : best_start + window],
+ fromfile="old_text (provided)",
+ tofile=f"{path} (actual, line {best_start + 1})",
+ lineterm="",
+ ))
+ return f"Error: old_text not found in {path}.\nBest match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff}"
+ return f"Error: old_text not found in {path}. No similar text found. Verify the file content."
+
+
+# ---------------------------------------------------------------------------
+# list_dir
+# ---------------------------------------------------------------------------
+
+class ListDirTool(_FsTool):
+ """List directory contents with optional recursion."""
+
+ _DEFAULT_MAX = 200
+ _IGNORE_DIRS = {
+ ".git", "node_modules", "__pycache__", ".venv", "venv",
+ "dist", "build", ".tox", ".mypy_cache", ".pytest_cache",
+ ".ruff_cache", ".coverage", "htmlcov",
+ }
+
+ @property
+ def name(self) -> str:
+ return "list_dir"
+
+ @property
+ def description(self) -> str:
+ return (
+ "List the contents of a directory. "
+ "Set recursive=true to explore nested structure. "
+ "Common noise directories (.git, node_modules, __pycache__, etc.) are auto-ignored."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "path": {"type": "string", "description": "The directory path to list"},
+ "recursive": {
+ "type": "boolean",
+ "description": "Recursively list all files (default false)",
+ },
+ "max_entries": {
+ "type": "integer",
+ "description": "Maximum entries to return (default 200)",
+ "minimum": 1,
+ },
+ },
+ "required": ["path"],
+ }
+
+ async def execute(
+ self, path: str, recursive: bool = False,
+ max_entries: int | None = None, **kwargs: Any,
+ ) -> str:
+ try:
+ dp = self._resolve(path)
+ if not dp.exists():
+ return f"Error: Directory not found: {path}"
+ if not dp.is_dir():
+ return f"Error: Not a directory: {path}"
+
+ cap = max_entries or self._DEFAULT_MAX
+ items: list[str] = []
+ total = 0
+
+ if recursive:
+ for item in sorted(dp.rglob("*")):
+ if any(p in self._IGNORE_DIRS for p in item.parts):
+ continue
+ total += 1
+ if len(items) < cap:
+ rel = item.relative_to(dp)
+ items.append(f"{rel}/" if item.is_dir() else str(rel))
+ else:
+ for item in sorted(dp.iterdir()):
+ if item.name in self._IGNORE_DIRS:
+ continue
+ total += 1
+ if len(items) < cap:
+ pfx = "📁 " if item.is_dir() else "📄 "
+ items.append(f"{pfx}{item.name}")
+
+ if not items and total == 0:
+ return f"Directory {path} is empty"
+
+ result = "\n".join(items)
+ if total > cap:
+ result += f"\n\n(truncated, showing first {cap} of {total} entries)"
+ return result
+ except PermissionError as e:
+ return f"Error: {e}"
+ except Exception as e:
+ return f"Error listing directory: {e}"
diff --git a/deeptutor/tutorbot/agent/tools/mcp.py b/deeptutor/tutorbot/agent/tools/mcp.py
new file mode 100644
index 000000000..4dedd93f9
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/mcp.py
@@ -0,0 +1,184 @@
+"""MCP client: connects to MCP servers and wraps their tools as native TutorBot tools."""
+
+import asyncio
+from contextlib import AsyncExitStack
+from typing import Any
+
+import httpx
+from loguru import logger
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+from deeptutor.tutorbot.agent.tools.registry import ToolRegistry
+
+
+class MCPToolWrapper(Tool):
+ """Wraps a single MCP server tool as a TutorBot Tool."""
+
+ def __init__(self, session, server_name: str, tool_def, tool_timeout: int = 30):
+ self._session = session
+ self._original_name = tool_def.name
+ self._name = f"mcp_{server_name}_{tool_def.name}"
+ self._description = tool_def.description or tool_def.name
+ self._parameters = tool_def.inputSchema or {"type": "object", "properties": {}}
+ self._tool_timeout = tool_timeout
+
+ @property
+ def name(self) -> str:
+ return self._name
+
+ @property
+ def description(self) -> str:
+ return self._description
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return self._parameters
+
+ async def execute(self, **kwargs: Any) -> str:
+ from mcp import types
+
+ try:
+ result = await asyncio.wait_for(
+ self._session.call_tool(self._original_name, arguments=kwargs),
+ timeout=self._tool_timeout,
+ )
+ except asyncio.TimeoutError:
+ logger.warning("MCP tool '{}' timed out after {}s", self._name, self._tool_timeout)
+ return f"(MCP tool call timed out after {self._tool_timeout}s)"
+ except asyncio.CancelledError:
+ # MCP SDK's anyio cancel scopes can leak CancelledError on timeout/failure.
+ # Re-raise only if our task was externally cancelled (e.g. /stop).
+ task = asyncio.current_task()
+ if task is not None and task.cancelling() > 0:
+ raise
+ logger.warning("MCP tool '{}' was cancelled by server/SDK", self._name)
+ return "(MCP tool call was cancelled)"
+ except Exception as exc:
+ logger.exception(
+ "MCP tool '{}' failed: {}: {}",
+ self._name,
+ type(exc).__name__,
+ exc,
+ )
+ return f"(MCP tool call failed: {type(exc).__name__})"
+
+ parts = []
+ for block in result.content:
+ if isinstance(block, types.TextContent):
+ parts.append(block.text)
+ else:
+ parts.append(str(block))
+ return "\n".join(parts) or "(no output)"
+
+
+async def connect_mcp_servers(
+ mcp_servers: dict, registry: ToolRegistry, stack: AsyncExitStack
+) -> None:
+ """Connect to configured MCP servers and register their tools."""
+ from mcp import ClientSession, StdioServerParameters
+ from mcp.client.sse import sse_client
+ from mcp.client.stdio import stdio_client
+ from mcp.client.streamable_http import streamable_http_client
+
+ for name, cfg in mcp_servers.items():
+ try:
+ transport_type = cfg.type
+ if not transport_type:
+ if cfg.command:
+ transport_type = "stdio"
+ elif cfg.url:
+ # Convention: URLs ending with /sse use SSE transport; others use streamableHttp
+ transport_type = (
+ "sse" if cfg.url.rstrip("/").endswith("/sse") else "streamableHttp"
+ )
+ else:
+ logger.warning("MCP server '{}': no command or url configured, skipping", name)
+ continue
+
+ if transport_type == "stdio":
+ params = StdioServerParameters(
+ command=cfg.command, args=cfg.args, env=cfg.env or None
+ )
+ read, write = await stack.enter_async_context(stdio_client(params))
+ elif transport_type == "sse":
+ def httpx_client_factory(
+ headers: dict[str, str] | None = None,
+ timeout: httpx.Timeout | None = None,
+ auth: httpx.Auth | None = None,
+ ) -> httpx.AsyncClient:
+ merged_headers = {**(cfg.headers or {}), **(headers or {})}
+ return httpx.AsyncClient(
+ headers=merged_headers or None,
+ follow_redirects=True,
+ timeout=timeout,
+ auth=auth,
+ )
+
+ read, write = await stack.enter_async_context(
+ sse_client(cfg.url, httpx_client_factory=httpx_client_factory)
+ )
+ elif transport_type == "streamableHttp":
+ # Always provide an explicit httpx client so MCP HTTP transport does not
+ # inherit httpx's default 5s timeout and preempt the higher-level tool timeout.
+ http_client = await stack.enter_async_context(
+ httpx.AsyncClient(
+ headers=cfg.headers or None,
+ follow_redirects=True,
+ timeout=None,
+ )
+ )
+ read, write, _ = await stack.enter_async_context(
+ streamable_http_client(cfg.url, http_client=http_client)
+ )
+ else:
+ logger.warning("MCP server '{}': unknown transport type '{}'", name, transport_type)
+ continue
+
+ session = await stack.enter_async_context(ClientSession(read, write))
+ await session.initialize()
+
+ tools = await session.list_tools()
+ enabled_tools = set(cfg.enabled_tools)
+ allow_all_tools = "*" in enabled_tools
+ registered_count = 0
+ matched_enabled_tools: set[str] = set()
+ available_raw_names = [tool_def.name for tool_def in tools.tools]
+ available_wrapped_names = [f"mcp_{name}_{tool_def.name}" for tool_def in tools.tools]
+ for tool_def in tools.tools:
+ wrapped_name = f"mcp_{name}_{tool_def.name}"
+ if (
+ not allow_all_tools
+ and tool_def.name not in enabled_tools
+ and wrapped_name not in enabled_tools
+ ):
+ logger.debug(
+ "MCP: skipping tool '{}' from server '{}' (not in enabledTools)",
+ wrapped_name,
+ name,
+ )
+ continue
+ wrapper = MCPToolWrapper(session, name, tool_def, tool_timeout=cfg.tool_timeout)
+ registry.register(wrapper)
+ logger.debug("MCP: registered tool '{}' from server '{}'", wrapper.name, name)
+ registered_count += 1
+ if enabled_tools:
+ if tool_def.name in enabled_tools:
+ matched_enabled_tools.add(tool_def.name)
+ if wrapped_name in enabled_tools:
+ matched_enabled_tools.add(wrapped_name)
+
+ if enabled_tools and not allow_all_tools:
+ unmatched_enabled_tools = sorted(enabled_tools - matched_enabled_tools)
+ if unmatched_enabled_tools:
+ logger.warning(
+ "MCP server '{}': enabledTools entries not found: {}. Available raw names: {}. "
+ "Available wrapped names: {}",
+ name,
+ ", ".join(unmatched_enabled_tools),
+ ", ".join(available_raw_names) or "(none)",
+ ", ".join(available_wrapped_names) or "(none)",
+ )
+
+ logger.info("MCP server '{}': connected, {} tools registered", name, registered_count)
+ except Exception as e:
+ logger.error("MCP server '{}': failed to connect: {}", name, e)
diff --git a/deeptutor/tutorbot/agent/tools/message.py b/deeptutor/tutorbot/agent/tools/message.py
new file mode 100644
index 000000000..4684cffa4
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/message.py
@@ -0,0 +1,109 @@
+"""Message tool for sending messages to users."""
+
+from typing import Any, Awaitable, Callable
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+from deeptutor.tutorbot.bus.events import OutboundMessage
+
+
+class MessageTool(Tool):
+ """Tool to send messages to users on chat channels."""
+
+ def __init__(
+ self,
+ send_callback: Callable[[OutboundMessage], Awaitable[None]] | None = None,
+ default_channel: str = "",
+ default_chat_id: str = "",
+ default_message_id: str | None = None,
+ ):
+ self._send_callback = send_callback
+ self._default_channel = default_channel
+ self._default_chat_id = default_chat_id
+ self._default_message_id = default_message_id
+ self._sent_in_turn: bool = False
+
+ def set_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None:
+ """Set the current message context."""
+ self._default_channel = channel
+ self._default_chat_id = chat_id
+ self._default_message_id = message_id
+
+ def set_send_callback(self, callback: Callable[[OutboundMessage], Awaitable[None]]) -> None:
+ """Set the callback for sending messages."""
+ self._send_callback = callback
+
+ def start_turn(self) -> None:
+ """Reset per-turn send tracking."""
+ self._sent_in_turn = False
+
+ @property
+ def name(self) -> str:
+ return "message"
+
+ @property
+ def description(self) -> str:
+ return "Send a message to the user. Use this when you want to communicate something."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "The message content to send"
+ },
+ "channel": {
+ "type": "string",
+ "description": "Optional: target channel (telegram, discord, etc.)"
+ },
+ "chat_id": {
+ "type": "string",
+ "description": "Optional: target chat/user ID"
+ },
+ "media": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Optional: list of file paths to attach (images, audio, documents)"
+ }
+ },
+ "required": ["content"]
+ }
+
+ async def execute(
+ self,
+ content: str,
+ channel: str | None = None,
+ chat_id: str | None = None,
+ message_id: str | None = None,
+ media: list[str] | None = None,
+ **kwargs: Any
+ ) -> str:
+ channel = channel or self._default_channel
+ chat_id = chat_id or self._default_chat_id
+ message_id = message_id or self._default_message_id
+
+ if not channel or not chat_id:
+ return "Error: No target channel/chat specified"
+
+ if not self._send_callback:
+ return "Error: Message sending not configured"
+
+ msg = OutboundMessage(
+ channel=channel,
+ chat_id=chat_id,
+ content=content,
+ media=media or [],
+ metadata={
+ "message_id": message_id,
+ },
+ )
+
+ try:
+ await self._send_callback(msg)
+ if channel == self._default_channel and chat_id == self._default_chat_id:
+ self._sent_in_turn = True
+ media_info = f" with {len(media)} attachments" if media else ""
+ return f"Message sent to {channel}:{chat_id}{media_info}"
+ except Exception as e:
+ return f"Error sending message: {str(e)}"
diff --git a/deeptutor/tutorbot/agent/tools/registry.py b/deeptutor/tutorbot/agent/tools/registry.py
new file mode 100644
index 000000000..61fb4a01f
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/registry.py
@@ -0,0 +1,103 @@
+"""Tool registry for dynamic tool management."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.config.schema import ExecToolConfig, WebSearchConfig
+
+
+class ToolRegistry:
+ """
+ Registry for agent tools.
+
+ Allows dynamic registration and execution of tools.
+ """
+
+ def __init__(self):
+ self._tools: dict[str, Tool] = {}
+
+ def register(self, tool: Tool) -> None:
+ """Register a tool."""
+ self._tools[tool.name] = tool
+
+ def unregister(self, name: str) -> None:
+ """Unregister a tool by name."""
+ self._tools.pop(name, None)
+
+ def get(self, name: str) -> Tool | None:
+ """Get a tool by name."""
+ return self._tools.get(name)
+
+ def has(self, name: str) -> bool:
+ """Check if a tool is registered."""
+ return name in self._tools
+
+ def get_definitions(self) -> list[dict[str, Any]]:
+ """Get all tool definitions in OpenAI format."""
+ return [tool.to_schema() for tool in self._tools.values()]
+
+ async def execute(self, name: str, params: dict[str, Any]) -> str:
+ """Execute a tool by name with given parameters."""
+ _HINT = "\n\n[Analyze the error above and try a different approach.]"
+
+ tool = self._tools.get(name)
+ if not tool:
+ return f"Error: Tool '{name}' not found. Available: {', '.join(self.tool_names)}"
+
+ try:
+ # Attempt to cast parameters to match schema types
+ params = tool.cast_params(params)
+
+ # Validate parameters
+ errors = tool.validate_params(params)
+ if errors:
+ return f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors) + _HINT
+ result = await tool.execute(**params)
+ if isinstance(result, str) and result.startswith("Error"):
+ return result + _HINT
+ return result
+ except Exception as e:
+ return f"Error executing {name}: {str(e)}" + _HINT
+
+ @property
+ def tool_names(self) -> list[str]:
+ """Get list of registered tool names."""
+ return list(self._tools.keys())
+
+ def __len__(self) -> int:
+ return len(self._tools)
+
+ def __contains__(self, name: str) -> bool:
+ return name in self._tools
+
+
+def build_base_tools(
+ workspace: Path,
+ exec_config: "ExecToolConfig",
+ web_search_config: "WebSearchConfig | None" = None,
+ web_proxy: str | None = None,
+ restrict_to_workspace: bool = False,
+) -> ToolRegistry:
+ """Build a ToolRegistry pre-loaded with filesystem, shell, and web tools."""
+ from deeptutor.tutorbot.agent.tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool
+ from deeptutor.tutorbot.agent.tools.shell import ExecTool
+ from deeptutor.tutorbot.agent.tools.web import WebFetchTool, WebSearchTool
+
+ tools = ToolRegistry()
+ allowed_dir = workspace if restrict_to_workspace else None
+ for cls in (ReadFileTool, WriteFileTool, EditFileTool, ListDirTool):
+ tools.register(cls(workspace=workspace, allowed_dir=allowed_dir))
+ tools.register(ExecTool(
+ working_dir=str(workspace),
+ timeout=exec_config.timeout,
+ restrict_to_workspace=restrict_to_workspace,
+ path_append=exec_config.path_append,
+ ))
+ tools.register(WebSearchTool(config=web_search_config, proxy=web_proxy))
+ tools.register(WebFetchTool(proxy=web_proxy))
+ return tools
diff --git a/deeptutor/tutorbot/agent/tools/shell.py b/deeptutor/tutorbot/agent/tools/shell.py
new file mode 100644
index 000000000..abeef6ff7
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/shell.py
@@ -0,0 +1,190 @@
+"""Shell execution tool."""
+
+import asyncio
+import os
+import re
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+
+
+class ExecTool(Tool):
+ """Tool to execute shell commands."""
+
+ def __init__(
+ self,
+ timeout: int = 60,
+ working_dir: str | None = None,
+ deny_patterns: list[str] | None = None,
+ allow_patterns: list[str] | None = None,
+ restrict_to_workspace: bool = False,
+ path_append: str = "",
+ forward_logs: bool = True,
+ ):
+ self.timeout = timeout
+ self.working_dir = working_dir
+ self.forward_logs = forward_logs
+ self.deny_patterns = deny_patterns or [
+ r"\brm\s+-[rf]{1,2}\b", # rm -r, rm -rf, rm -fr
+ r"\bdel\s+/[fq]\b", # del /f, del /q
+ r"\brmdir\s+/s\b", # rmdir /s
+ r"(?:^|[;&|]\s*)format\b", # format (as standalone command only)
+ r"\b(mkfs|diskpart)\b", # disk operations
+ r"\bdd\s+if=", # dd
+ r">\s*/dev/sd", # write to disk
+ r"\b(shutdown|reboot|poweroff)\b", # system power
+ r":\(\)\s*\{.*\};\s*:", # fork bomb
+ ]
+ self.allow_patterns = allow_patterns or []
+ self.restrict_to_workspace = restrict_to_workspace
+ self.path_append = path_append
+
+ @property
+ def name(self) -> str:
+ return "exec"
+
+ _MAX_TIMEOUT = 600
+ _MAX_OUTPUT = 10_000
+
+ @property
+ def description(self) -> str:
+ return "Execute a shell command and return its output. Use with caution."
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "description": "The shell command to execute",
+ },
+ "working_dir": {
+ "type": "string",
+ "description": "Optional working directory for the command",
+ },
+ "timeout": {
+ "type": "integer",
+ "description": (
+ "Timeout in seconds. Increase for long-running commands "
+ "like compilation or installation (default 60, max 600)."
+ ),
+ "minimum": 1,
+ "maximum": 600,
+ },
+ },
+ "required": ["command"],
+ }
+
+ async def execute(
+ self, command: str, working_dir: str | None = None,
+ timeout: int | None = None, **kwargs: Any,
+ ) -> str:
+ cwd = working_dir or self.working_dir or os.getcwd()
+ guard_error = self._guard_command(command, cwd)
+ if guard_error:
+ return guard_error
+
+ effective_timeout = min(timeout or self.timeout, self._MAX_TIMEOUT)
+
+ env = os.environ.copy()
+ if self.path_append:
+ env["PATH"] = env.get("PATH", "") + os.pathsep + self.path_append
+
+ try:
+ process = await asyncio.create_subprocess_shell(
+ command,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ cwd=cwd,
+ env=env,
+ )
+
+ try:
+ stdout, stderr = await asyncio.wait_for(
+ process.communicate(),
+ timeout=effective_timeout,
+ )
+ except asyncio.TimeoutError:
+ process.kill()
+ try:
+ await asyncio.wait_for(process.wait(), timeout=5.0)
+ except asyncio.TimeoutError:
+ pass
+ return f"Error: Command timed out after {effective_timeout} seconds"
+
+ output_parts = []
+
+ if stdout:
+ output_parts.append(stdout.decode("utf-8", errors="replace"))
+
+ stderr_text = ""
+ if stderr:
+ stderr_text = stderr.decode("utf-8", errors="replace")
+ if stderr_text.strip():
+ output_parts.append(f"STDERR:\n{stderr_text}")
+
+ if self.forward_logs and stderr_text.strip():
+ for line in stderr_text.strip().splitlines():
+ line = line.strip()
+ if line:
+ logger.info("[exec] {}", line)
+
+ output_parts.append(f"\nExit code: {process.returncode}")
+
+ result = "\n".join(output_parts) if output_parts else "(no output)"
+
+ # Head + tail truncation to preserve both start and end of output
+ max_len = self._MAX_OUTPUT
+ if len(result) > max_len:
+ half = max_len // 2
+ result = (
+ result[:half]
+ + f"\n\n... ({len(result) - max_len:,} chars truncated) ...\n\n"
+ + result[-half:]
+ )
+
+ return result
+
+ except Exception as e:
+ return f"Error executing command: {str(e)}"
+
+ def _guard_command(self, command: str, cwd: str) -> str | None:
+ """Best-effort safety guard for potentially destructive commands."""
+ cmd = command.strip()
+ lower = cmd.lower()
+
+ for pattern in self.deny_patterns:
+ if re.search(pattern, lower):
+ return "Error: Command blocked by safety guard (dangerous pattern detected)"
+
+ if self.allow_patterns:
+ if not any(re.search(p, lower) for p in self.allow_patterns):
+ return "Error: Command blocked by safety guard (not in allowlist)"
+
+ if self.restrict_to_workspace:
+ if "..\\" in cmd or "../" in cmd:
+ return "Error: Command blocked by safety guard (path traversal detected)"
+
+ cwd_path = Path(cwd).resolve()
+
+ for raw in self._extract_absolute_paths(cmd):
+ try:
+ expanded = os.path.expandvars(raw.strip())
+ p = Path(expanded).expanduser().resolve()
+ except Exception:
+ continue
+ if p.is_absolute() and cwd_path not in p.parents and p != cwd_path:
+ return "Error: Command blocked by safety guard (path outside working dir)"
+
+ return None
+
+ @staticmethod
+ def _extract_absolute_paths(command: str) -> list[str]:
+ win_paths = re.findall(r"[A-Za-z]:\\[^\s\"'|><;]+", command) # Windows: C:\...
+ posix_paths = re.findall(r"(?:^|[\s|>'\"])(/[^\s\"'>;|<]+)", command) # POSIX: /absolute only
+ home_paths = re.findall(r"(?:^|[\s|>'\"])(~[^\s\"'>;|<]*)", command) # POSIX/Windows home shortcut: ~
+ return win_paths + posix_paths + home_paths
diff --git a/deeptutor/tutorbot/agent/tools/spawn.py b/deeptutor/tutorbot/agent/tools/spawn.py
new file mode 100644
index 000000000..551f55141
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/spawn.py
@@ -0,0 +1,63 @@
+"""Spawn tool for creating background subagents."""
+
+from typing import TYPE_CHECKING, Any
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.agent.subagent import SubagentManager
+
+
+class SpawnTool(Tool):
+ """Tool to spawn a subagent for background task execution."""
+
+ def __init__(self, manager: "SubagentManager"):
+ self._manager = manager
+ self._origin_channel = "cli"
+ self._origin_chat_id = "direct"
+ self._session_key = "cli:direct"
+
+ def set_context(self, channel: str, chat_id: str) -> None:
+ """Set the origin context for subagent announcements."""
+ self._origin_channel = channel
+ self._origin_chat_id = chat_id
+ self._session_key = f"{channel}:{chat_id}"
+
+ @property
+ def name(self) -> str:
+ return "spawn"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Spawn a subagent to handle a task in the background. "
+ "Use this for complex or time-consuming tasks that can run independently. "
+ "The subagent will complete the task and report back when done."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "task": {
+ "type": "string",
+ "description": "The task for the subagent to complete",
+ },
+ "label": {
+ "type": "string",
+ "description": "Optional short label for the task (for display)",
+ },
+ },
+ "required": ["task"],
+ }
+
+ async def execute(self, task: str, label: str | None = None, **kwargs: Any) -> str:
+ """Spawn a subagent to execute the given task."""
+ return await self._manager.spawn(
+ task=task,
+ label=label,
+ origin_channel=self._origin_channel,
+ origin_chat_id=self._origin_chat_id,
+ session_key=self._session_key,
+ )
diff --git a/deeptutor/tutorbot/agent/tools/web.py b/deeptutor/tutorbot/agent/tools/web.py
new file mode 100644
index 000000000..86c213b16
--- /dev/null
+++ b/deeptutor/tutorbot/agent/tools/web.py
@@ -0,0 +1,322 @@
+"""Web tools: web_search and web_fetch."""
+
+from __future__ import annotations
+
+import asyncio
+import html
+import json
+import os
+import re
+from typing import TYPE_CHECKING, Any
+from urllib.parse import urlparse
+
+import httpx
+from loguru import logger
+
+from deeptutor.tutorbot.agent.tools.base import Tool
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.config.schema import WebSearchConfig
+
+# Shared constants
+USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36"
+MAX_REDIRECTS = 5 # Limit redirects to prevent DoS attacks
+
+
+def _strip_tags(text: str) -> str:
+ """Remove HTML tags and decode entities."""
+ text = re.sub(r'<script[\s\S]*?</script>', '', text, flags=re.I)
+ text = re.sub(r'<style[\s\S]*?</style>', '', text, flags=re.I)
+ text = re.sub(r'<[^>]+>', '', text)
+ return html.unescape(text).strip()
+
+
+def _normalize(text: str) -> str:
+ """Normalize whitespace."""
+ text = re.sub(r'[ \t]+', ' ', text)
+ return re.sub(r'\n{3,}', '\n\n', text).strip()
+
+
+def _validate_url(url: str) -> tuple[bool, str]:
+ """Validate URL: must be http(s) with valid domain."""
+ try:
+ p = urlparse(url)
+ if p.scheme not in ('http', 'https'):
+ return False, f"Only http/https allowed, got '{p.scheme or 'none'}'"
+ if not p.netloc:
+ return False, "Missing domain"
+ return True, ""
+ except Exception as e:
+ return False, str(e)
+
+
+def _format_results(query: str, items: list[dict[str, Any]], n: int) -> str:
+ """Format provider results into shared plaintext output."""
+ if not items:
+ return f"No results for: {query}"
+ lines = [f"Results for: {query}\n"]
+ for i, item in enumerate(items[:n], 1):
+ title = _normalize(_strip_tags(item.get("title", "")))
+ snippet = _normalize(_strip_tags(item.get("content", "")))
+ lines.append(f"{i}. {title}\n {item.get('url', '')}")
+ if snippet:
+ lines.append(f" {snippet}")
+ return "\n".join(lines)
+
+
+class WebSearchTool(Tool):
+ """Search the web using configured provider."""
+
+ name = "web_search"
+ description = "Search the web. Returns titles, URLs, and snippets."
+ parameters = {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query"},
+ "count": {"type": "integer", "description": "Results (1-10)", "minimum": 1, "maximum": 10},
+ },
+ "required": ["query"],
+ }
+
+ def __init__(self, config: WebSearchConfig | None = None, proxy: str | None = None):
+ from deeptutor.tutorbot.config.schema import WebSearchConfig
+
+ self.config = config if config is not None else WebSearchConfig()
+ self.proxy = proxy
+
+ async def execute(self, query: str, count: int | None = None, **kwargs: Any) -> str:
+ provider = self.config.provider.strip().lower() or "brave"
+ n = min(max(count or self.config.max_results, 1), 10)
+
+ if provider == "duckduckgo":
+ return await self._search_duckduckgo(query, n)
+ elif provider == "tavily":
+ return await self._search_tavily(query, n)
+ elif provider == "searxng":
+ return await self._search_searxng(query, n)
+ elif provider == "jina":
+ return await self._search_jina(query, n)
+ elif provider == "brave":
+ return await self._search_brave(query, n)
+ else:
+ return f"Error: unknown search provider '{provider}'"
+
+ async def _search_brave(self, query: str, n: int) -> str:
+ api_key = self.config.api_key or os.environ.get("BRAVE_API_KEY", "")
+ if not api_key:
+ logger.warning("BRAVE_API_KEY not set, falling back to DuckDuckGo")
+ return await self._search_duckduckgo(query, n)
+ try:
+ async with httpx.AsyncClient(proxy=self.proxy) as client:
+ r = await client.get(
+ "https://api.search.brave.com/res/v1/web/search",
+ params={"q": query, "count": n},
+ headers={"Accept": "application/json", "X-Subscription-Token": api_key},
+ timeout=10.0,
+ )
+ r.raise_for_status()
+ items = [
+ {"title": x.get("title", ""), "url": x.get("url", ""), "content": x.get("description", "")}
+ for x in r.json().get("web", {}).get("results", [])
+ ]
+ return _format_results(query, items, n)
+ except Exception as e:
+ return f"Error: {e}"
+
+ async def _search_tavily(self, query: str, n: int) -> str:
+ api_key = self.config.api_key or os.environ.get("TAVILY_API_KEY", "")
+ if not api_key:
+ logger.warning("TAVILY_API_KEY not set, falling back to DuckDuckGo")
+ return await self._search_duckduckgo(query, n)
+ try:
+ async with httpx.AsyncClient(proxy=self.proxy) as client:
+ r = await client.post(
+ "https://api.tavily.com/search",
+ headers={"Authorization": f"Bearer {api_key}"},
+ json={"query": query, "max_results": n},
+ timeout=15.0,
+ )
+ r.raise_for_status()
+ return _format_results(query, r.json().get("results", []), n)
+ except Exception as e:
+ return f"Error: {e}"
+
+ async def _search_searxng(self, query: str, n: int) -> str:
+ base_url = (self.config.base_url or os.environ.get("SEARXNG_BASE_URL", "")).strip()
+ if not base_url:
+ logger.warning("SEARXNG_BASE_URL not set, falling back to DuckDuckGo")
+ return await self._search_duckduckgo(query, n)
+ endpoint = f"{base_url.rstrip('/')}/search"
+ is_valid, error_msg = _validate_url(endpoint)
+ if not is_valid:
+ return f"Error: invalid SearXNG URL: {error_msg}"
+ try:
+ async with httpx.AsyncClient(proxy=self.proxy) as client:
+ r = await client.get(
+ endpoint,
+ params={"q": query, "format": "json"},
+ headers={"User-Agent": USER_AGENT},
+ timeout=10.0,
+ )
+ r.raise_for_status()
+ return _format_results(query, r.json().get("results", []), n)
+ except Exception as e:
+ return f"Error: {e}"
+
+ async def _search_jina(self, query: str, n: int) -> str:
+ api_key = self.config.api_key or os.environ.get("JINA_API_KEY", "")
+ if not api_key:
+ logger.warning("JINA_API_KEY not set, falling back to DuckDuckGo")
+ return await self._search_duckduckgo(query, n)
+ try:
+ headers = {"Accept": "application/json", "Authorization": f"Bearer {api_key}"}
+ async with httpx.AsyncClient(proxy=self.proxy) as client:
+ r = await client.get(
+ f"https://s.jina.ai/",
+ params={"q": query},
+ headers=headers,
+ timeout=15.0,
+ )
+ r.raise_for_status()
+ data = r.json().get("data", [])[:n]
+ items = [
+ {"title": d.get("title", ""), "url": d.get("url", ""), "content": d.get("content", "")[:500]}
+ for d in data
+ ]
+ return _format_results(query, items, n)
+ except Exception as e:
+ return f"Error: {e}"
+
+ async def _search_duckduckgo(self, query: str, n: int) -> str:
+ try:
+ from ddgs import DDGS
+
+ ddgs = DDGS(timeout=10)
+ raw = await asyncio.to_thread(ddgs.text, query, max_results=n)
+ if not raw:
+ return f"No results for: {query}"
+ items = [
+ {"title": r.get("title", ""), "url": r.get("href", ""), "content": r.get("body", "")}
+ for r in raw
+ ]
+ return _format_results(query, items, n)
+ except Exception as e:
+ logger.warning("DuckDuckGo search failed: {}", e)
+ return f"Error: DuckDuckGo search failed ({e})"
+
+
+class WebFetchTool(Tool):
+ """Fetch and extract content from a URL."""
+
+ name = "web_fetch"
+ description = "Fetch URL and extract readable content (HTML → markdown/text)."
+ parameters = {
+ "type": "object",
+ "properties": {
+ "url": {"type": "string", "description": "URL to fetch"},
+ "extractMode": {"type": "string", "enum": ["markdown", "text"], "default": "markdown"},
+ "maxChars": {"type": "integer", "minimum": 100},
+ },
+ "required": ["url"],
+ }
+
+ def __init__(self, max_chars: int = 50000, proxy: str | None = None):
+ self.max_chars = max_chars
+ self.proxy = proxy
+
+ async def execute(self, url: str, extractMode: str = "markdown", maxChars: int | None = None, **kwargs: Any) -> str:
+ max_chars = maxChars or self.max_chars
+ is_valid, error_msg = _validate_url(url)
+ if not is_valid:
+ return json.dumps({"error": f"URL validation failed: {error_msg}", "url": url}, ensure_ascii=False)
+
+ result = await self._fetch_jina(url, max_chars)
+ if result is None:
+ result = await self._fetch_readability(url, extractMode, max_chars)
+ return result
+
+ async def _fetch_jina(self, url: str, max_chars: int) -> str | None:
+ """Try fetching via Jina Reader API. Returns None on failure."""
+ try:
+ headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
+ jina_key = os.environ.get("JINA_API_KEY", "")
+ if jina_key:
+ headers["Authorization"] = f"Bearer {jina_key}"
+ async with httpx.AsyncClient(proxy=self.proxy, timeout=20.0) as client:
+ r = await client.get(f"https://r.jina.ai/{url}", headers=headers)
+ if r.status_code == 429:
+ logger.debug("Jina Reader rate limited, falling back to readability")
+ return None
+ r.raise_for_status()
+
+ data = r.json().get("data", {})
+ title = data.get("title", "")
+ text = data.get("content", "")
+ if not text:
+ return None
+
+ if title:
+ text = f"# {title}\n\n{text}"
+ truncated = len(text) > max_chars
+ if truncated:
+ text = text[:max_chars]
+
+ return json.dumps({
+ "url": url, "finalUrl": data.get("url", url), "status": r.status_code,
+ "extractor": "jina", "truncated": truncated, "length": len(text), "text": text,
+ }, ensure_ascii=False)
+ except Exception as e:
+ logger.debug("Jina Reader failed for {}, falling back to readability: {}", url, e)
+ return None
+
+ async def _fetch_readability(self, url: str, extract_mode: str, max_chars: int) -> str:
+ """Local fallback using readability-lxml."""
+ from readability import Document
+
+ try:
+ async with httpx.AsyncClient(
+ follow_redirects=True,
+ max_redirects=MAX_REDIRECTS,
+ timeout=30.0,
+ proxy=self.proxy,
+ ) as client:
+ r = await client.get(url, headers={"User-Agent": USER_AGENT})
+ r.raise_for_status()
+
+ ctype = r.headers.get("content-type", "")
+
+ if "application/json" in ctype:
+ text, extractor = json.dumps(r.json(), indent=2, ensure_ascii=False), "json"
+ elif "text/html" in ctype or r.text[:256].lower().startswith(("<!doctype", "<html")):
+ doc = Document(r.text)
+ content = self._to_markdown(doc.summary()) if extract_mode == "markdown" else _strip_tags(doc.summary())
+ text = f"# {doc.title()}\n\n{content}" if doc.title() else content
+ extractor = "readability"
+ else:
+ text, extractor = r.text, "raw"
+
+ truncated = len(text) > max_chars
+ if truncated:
+ text = text[:max_chars]
+
+ return json.dumps({
+ "url": url, "finalUrl": str(r.url), "status": r.status_code,
+ "extractor": extractor, "truncated": truncated, "length": len(text), "text": text,
+ }, ensure_ascii=False)
+ except httpx.ProxyError as e:
+ logger.error("WebFetch proxy error for {}: {}", url, e)
+ return json.dumps({"error": f"Proxy error: {e}", "url": url}, ensure_ascii=False)
+ except Exception as e:
+ logger.error("WebFetch error for {}: {}", url, e)
+ return json.dumps({"error": str(e), "url": url}, ensure_ascii=False)
+
+ def _to_markdown(self, html_content: str) -> str:
+ """Convert HTML to markdown."""
+ text = re.sub(r'<a\s+[^>]*href=["\']([^"\']+)["\'][^>]*>([\s\S]*?)</a>',
+ lambda m: f'[{_strip_tags(m[2])}]({m[1]})', html_content, flags=re.I)
+ text = re.sub(r'<h([1-6])[^>]*>([\s\S]*?)</h\1>',
+ lambda m: f'\n{"#" * int(m[1])} {_strip_tags(m[2])}\n', text, flags=re.I)
+ text = re.sub(r'<li[^>]*>([\s\S]*?)</li>', lambda m: f'\n- {_strip_tags(m[1])}', text, flags=re.I)
+ text = re.sub(r'</(p|div|section|article)>', '\n\n', text, flags=re.I)
+ text = re.sub(r'<(br|hr)\s*/?>', '\n', text, flags=re.I)
+ return _normalize(_strip_tags(text))
diff --git a/deeptutor/tutorbot/bus/__init__.py b/deeptutor/tutorbot/bus/__init__.py
new file mode 100644
index 000000000..0d482a7b7
--- /dev/null
+++ b/deeptutor/tutorbot/bus/__init__.py
@@ -0,0 +1,6 @@
+"""Message bus module for decoupled channel-agent communication."""
+
+from deeptutor.tutorbot.bus.events import InboundMessage, OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+
+__all__ = ["MessageBus", "InboundMessage", "OutboundMessage"]
diff --git a/deeptutor/tutorbot/bus/events.py b/deeptutor/tutorbot/bus/events.py
new file mode 100644
index 000000000..018c25b3d
--- /dev/null
+++ b/deeptutor/tutorbot/bus/events.py
@@ -0,0 +1,38 @@
+"""Event types for the message bus."""
+
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+
+@dataclass
+class InboundMessage:
+ """Message received from a chat channel."""
+
+ channel: str # telegram, discord, slack, whatsapp
+ sender_id: str # User identifier
+ chat_id: str # Chat/channel identifier
+ content: str # Message text
+ timestamp: datetime = field(default_factory=datetime.now)
+ media: list[str] = field(default_factory=list) # Media URLs
+ metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data
+ session_key_override: str | None = None # Optional override for thread-scoped sessions
+
+ @property
+ def session_key(self) -> str:
+ """Unique key for session identification."""
+ return self.session_key_override or f"{self.channel}:{self.chat_id}"
+
+
+@dataclass
+class OutboundMessage:
+ """Message to send to a chat channel."""
+
+ channel: str
+ chat_id: str
+ content: str
+ reply_to: str | None = None
+ media: list[str] = field(default_factory=list)
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
diff --git a/deeptutor/tutorbot/bus/queue.py b/deeptutor/tutorbot/bus/queue.py
new file mode 100644
index 000000000..17fba816e
--- /dev/null
+++ b/deeptutor/tutorbot/bus/queue.py
@@ -0,0 +1,44 @@
+"""Async message queue for decoupled channel-agent communication."""
+
+import asyncio
+
+from deeptutor.tutorbot.bus.events import InboundMessage, OutboundMessage
+
+
+class MessageBus:
+ """
+ Async message bus that decouples chat channels from the agent core.
+
+ Channels push messages to the inbound queue, and the agent processes
+ them and pushes responses to the outbound queue.
+ """
+
+ def __init__(self):
+ self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue()
+ self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()
+
+ async def publish_inbound(self, msg: InboundMessage) -> None:
+ """Publish a message from a channel to the agent."""
+ await self.inbound.put(msg)
+
+ async def consume_inbound(self) -> InboundMessage:
+ """Consume the next inbound message (blocks until available)."""
+ return await self.inbound.get()
+
+ async def publish_outbound(self, msg: OutboundMessage) -> None:
+ """Publish a response from the agent to channels."""
+ await self.outbound.put(msg)
+
+ async def consume_outbound(self) -> OutboundMessage:
+ """Consume the next outbound message (blocks until available)."""
+ return await self.outbound.get()
+
+ @property
+ def inbound_size(self) -> int:
+ """Number of pending inbound messages."""
+ return self.inbound.qsize()
+
+ @property
+ def outbound_size(self) -> int:
+ """Number of pending outbound messages."""
+ return self.outbound.qsize()
diff --git a/deeptutor/tutorbot/channels/__init__.py b/deeptutor/tutorbot/channels/__init__.py
new file mode 100644
index 000000000..a3cb485ae
--- /dev/null
+++ b/deeptutor/tutorbot/channels/__init__.py
@@ -0,0 +1,6 @@
+"""Chat channels module with plugin architecture."""
+
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.channels.manager import ChannelManager
+
+__all__ = ["BaseChannel", "ChannelManager"]
diff --git a/deeptutor/tutorbot/channels/base.py b/deeptutor/tutorbot/channels/base.py
new file mode 100644
index 000000000..e6c52f53c
--- /dev/null
+++ b/deeptutor/tutorbot/channels/base.py
@@ -0,0 +1,139 @@
+"""Base channel interface for chat platforms."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from deeptutor.tutorbot.bus.events import InboundMessage, OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+
+
+class BaseChannel(ABC):
+ """
+ Abstract base class for chat channel implementations.
+
+ Each channel (Telegram, Discord, etc.) should implement this interface
+ to integrate with the TutorBot message bus.
+ """
+
+ name: str = "base"
+ display_name: str = "Base"
+ transcription_api_key: str = ""
+
+ def __init__(self, config: Any, bus: MessageBus):
+ """
+ Initialize the channel.
+
+ Args:
+ config: Channel-specific configuration.
+ bus: The message bus for communication.
+ """
+ self.config = config
+ self.bus = bus
+ self._running = False
+
+ async def transcribe_audio(self, file_path: str | Path) -> str:
+ """Transcribe an audio file via Groq Whisper. Returns empty string on failure."""
+ if not self.transcription_api_key:
+ return ""
+ try:
+ from deeptutor.tutorbot.providers.transcription import GroqTranscriptionProvider
+
+ provider = GroqTranscriptionProvider(api_key=self.transcription_api_key)
+ return await provider.transcribe(file_path)
+ except Exception as e:
+ logger.warning("{}: audio transcription failed: {}", self.name, e)
+ return ""
+
+ @abstractmethod
+ async def start(self) -> None:
+ """
+ Start the channel and begin listening for messages.
+
+ This should be a long-running async task that:
+ 1. Connects to the chat platform
+ 2. Listens for incoming messages
+ 3. Forwards messages to the bus via _handle_message()
+ """
+ pass
+
+ @abstractmethod
+ async def stop(self) -> None:
+ """Stop the channel and clean up resources."""
+ pass
+
+ @abstractmethod
+ async def send(self, msg: OutboundMessage) -> None:
+ """
+ Send a message through this channel.
+
+ Args:
+ msg: The message to send.
+ """
+ pass
+
+ def is_allowed(self, sender_id: str) -> bool:
+ """Check if *sender_id* is permitted. Empty list → deny all; ``"*"`` → allow all."""
+ allow_list = getattr(self.config, "allow_from", [])
+ if not allow_list:
+ logger.warning("{}: allow_from is empty — all access denied", self.name)
+ return False
+ if "*" in allow_list:
+ return True
+ return str(sender_id) in allow_list
+
+ async def _handle_message(
+ self,
+ sender_id: str,
+ chat_id: str,
+ content: str,
+ media: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ session_key: str | None = None,
+ ) -> None:
+ """
+ Handle an incoming message from the chat platform.
+
+ This method checks permissions and forwards to the bus.
+
+ Args:
+ sender_id: The sender's identifier.
+ chat_id: The chat/channel identifier.
+ content: Message text content.
+ media: Optional list of media URLs.
+ metadata: Optional channel-specific metadata.
+ session_key: Optional session key override (e.g. thread-scoped sessions).
+ """
+ if not self.is_allowed(sender_id):
+ logger.warning(
+ "Access denied for sender {} on channel {}. "
+ "Add them to allowFrom list in config to grant access.",
+ sender_id, self.name,
+ )
+ return
+
+ msg = InboundMessage(
+ channel=self.name,
+ sender_id=str(sender_id),
+ chat_id=str(chat_id),
+ content=content,
+ media=media or [],
+ metadata=metadata or {},
+ session_key_override=session_key,
+ )
+
+ await self.bus.publish_inbound(msg)
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ """Return default config for onboard. Override in plugins to auto-populate config.json."""
+ return {"enabled": False}
+
+ @property
+ def is_running(self) -> bool:
+ """Check if the channel is running."""
+ return self._running
diff --git a/deeptutor/tutorbot/channels/dingtalk.py b/deeptutor/tutorbot/channels/dingtalk.py
new file mode 100644
index 000000000..109e7c218
--- /dev/null
+++ b/deeptutor/tutorbot/channels/dingtalk.py
@@ -0,0 +1,490 @@
+"""DingTalk/DingDing channel implementation using Stream Mode."""
+
+import asyncio
+import json
+import mimetypes
+import os
+import time
+from pathlib import Path
+from typing import Any
+from urllib.parse import unquote, urlparse
+
+import httpx
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.schema import Base
+
+try:
+ from dingtalk_stream import (
+ AckMessage,
+ CallbackHandler,
+ CallbackMessage,
+ Credential,
+ DingTalkStreamClient,
+ )
+ from dingtalk_stream.chatbot import ChatbotMessage
+
+ DINGTALK_AVAILABLE = True
+except ImportError:
+ DINGTALK_AVAILABLE = False
+ # Fallback so class definitions don't crash at module level
+ CallbackHandler = object # type: ignore[assignment,misc]
+ CallbackMessage = None # type: ignore[assignment,misc]
+ AckMessage = None # type: ignore[assignment,misc]
+ ChatbotMessage = None # type: ignore[assignment,misc]
+
+
+class NanobotDingTalkHandler(CallbackHandler):
+ """
+ Standard DingTalk Stream SDK Callback Handler.
+ Parses incoming messages and forwards them to the Nanobot channel.
+ """
+
+ def __init__(self, channel: "DingTalkChannel"):
+ super().__init__()
+ self.channel = channel
+
+ async def process(self, message: CallbackMessage):
+ """Process incoming stream message."""
+ try:
+ # Parse using SDK's ChatbotMessage for robust handling
+ chatbot_msg = ChatbotMessage.from_dict(message.data)
+
+ # Extract text content; fall back to raw dict if SDK object is empty
+ content = ""
+ if chatbot_msg.text:
+ content = chatbot_msg.text.content.strip()
+ elif chatbot_msg.extensions.get("content", {}).get("recognition"):
+ content = chatbot_msg.extensions["content"]["recognition"].strip()
+ if not content:
+ content = message.data.get("text", {}).get("content", "").strip()
+
+ if not content:
+ logger.warning(
+ "Received empty or unsupported message type: {}",
+ chatbot_msg.message_type,
+ )
+ return AckMessage.STATUS_OK, "OK"
+
+ sender_id = chatbot_msg.sender_staff_id or chatbot_msg.sender_id
+ sender_name = chatbot_msg.sender_nick or "Unknown"
+
+ conversation_type = message.data.get("conversationType")
+ conversation_id = (
+ message.data.get("conversationId")
+ or message.data.get("openConversationId")
+ )
+
+ logger.info("Received DingTalk message from {} ({}): {}", sender_name, sender_id, content)
+
+ # Forward to Nanobot via _on_message (non-blocking).
+ # Store reference to prevent GC before task completes.
+ task = asyncio.create_task(
+ self.channel._on_message(
+ content,
+ sender_id,
+ sender_name,
+ conversation_type,
+ conversation_id,
+ )
+ )
+ self.channel._background_tasks.add(task)
+ task.add_done_callback(self.channel._background_tasks.discard)
+
+ return AckMessage.STATUS_OK, "OK"
+
+ except Exception as e:
+ logger.error("Error processing DingTalk message: {}", e)
+ # Return OK to avoid retry loop from DingTalk server
+ return AckMessage.STATUS_OK, "Error"
+
+
+class DingTalkConfig(Base):
+ """DingTalk channel configuration using Stream mode."""
+
+ enabled: bool = False
+ client_id: str = ""
+ client_secret: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class DingTalkChannel(BaseChannel):
+ """
+ DingTalk channel using Stream Mode.
+
+ Uses WebSocket to receive events via `dingtalk-stream` SDK.
+ Uses direct HTTP API to send messages (SDK is mainly for receiving).
+
+ Supports both private (1:1) and group chats.
+ Group chat_id is stored with a "group:" prefix to route replies back.
+ """
+
+ name = "dingtalk"
+ display_name = "DingTalk"
+ _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
+ _AUDIO_EXTS = {".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac"}
+ _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return DingTalkConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = DingTalkConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: DingTalkConfig = config
+ self._client: Any = None
+ self._http: httpx.AsyncClient | None = None
+
+ # Access Token management for sending messages
+ self._access_token: str | None = None
+ self._token_expiry: float = 0
+
+ # Hold references to background tasks to prevent GC
+ self._background_tasks: set[asyncio.Task] = set()
+
+ async def start(self) -> None:
+ """Start the DingTalk bot with Stream Mode."""
+ try:
+ if not DINGTALK_AVAILABLE:
+ logger.error(
+ "DingTalk Stream SDK not installed. Run: pip install dingtalk-stream"
+ )
+ return
+
+ if not self.config.client_id or not self.config.client_secret:
+ logger.error("DingTalk client_id and client_secret not configured")
+ return
+
+ self._running = True
+ self._http = httpx.AsyncClient()
+
+ logger.info(
+ "Initializing DingTalk Stream Client with Client ID: {}...",
+ self.config.client_id,
+ )
+ credential = Credential(self.config.client_id, self.config.client_secret)
+ self._client = DingTalkStreamClient(credential)
+
+ # Register standard handler
+ handler = NanobotDingTalkHandler(self)
+ self._client.register_callback_handler(ChatbotMessage.TOPIC, handler)
+
+ logger.info("DingTalk bot started with Stream Mode")
+
+ # Reconnect loop: restart stream if SDK exits or crashes
+ while self._running:
+ try:
+ await self._client.start()
+ except Exception as e:
+ logger.warning("DingTalk stream error: {}", e)
+ if self._running:
+ logger.info("Reconnecting DingTalk stream in 5 seconds...")
+ await asyncio.sleep(5)
+
+ except Exception as e:
+ logger.exception("Failed to start DingTalk channel: {}", e)
+
+ async def stop(self) -> None:
+ """Stop the DingTalk bot."""
+ self._running = False
+ # Close the shared HTTP client
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+ # Cancel outstanding background tasks
+ for task in self._background_tasks:
+ task.cancel()
+ self._background_tasks.clear()
+
+ async def _get_access_token(self) -> str | None:
+ """Get or refresh Access Token."""
+ if self._access_token and time.time() < self._token_expiry:
+ return self._access_token
+
+ url = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
+ data = {
+ "appKey": self.config.client_id,
+ "appSecret": self.config.client_secret,
+ }
+
+ if not self._http:
+ logger.warning("DingTalk HTTP client not initialized, cannot refresh token")
+ return None
+
+ try:
+ resp = await self._http.post(url, json=data)
+ resp.raise_for_status()
+ res_data = resp.json()
+ self._access_token = res_data.get("accessToken")
+ # Expire 60s early to be safe
+ self._token_expiry = time.time() + int(res_data.get("expireIn", 7200)) - 60
+ return self._access_token
+ except Exception as e:
+ logger.error("Failed to get DingTalk access token: {}", e)
+ return None
+
+ @staticmethod
+ def _is_http_url(value: str) -> bool:
+ return urlparse(value).scheme in ("http", "https")
+
+ def _guess_upload_type(self, media_ref: str) -> str:
+ ext = Path(urlparse(media_ref).path).suffix.lower()
+ if ext in self._IMAGE_EXTS: return "image"
+ if ext in self._AUDIO_EXTS: return "voice"
+ if ext in self._VIDEO_EXTS: return "video"
+ return "file"
+
+ def _guess_filename(self, media_ref: str, upload_type: str) -> str:
+ name = os.path.basename(urlparse(media_ref).path)
+ return name or {"image": "image.jpg", "voice": "audio.amr", "video": "video.mp4"}.get(upload_type, "file.bin")
+
+ async def _read_media_bytes(
+ self,
+ media_ref: str,
+ ) -> tuple[bytes | None, str | None, str | None]:
+ if not media_ref:
+ return None, None, None
+
+ if self._is_http_url(media_ref):
+ if not self._http:
+ return None, None, None
+ try:
+ resp = await self._http.get(media_ref, follow_redirects=True)
+ if resp.status_code >= 400:
+ logger.warning(
+ "DingTalk media download failed status={} ref={}",
+ resp.status_code,
+ media_ref,
+ )
+ return None, None, None
+ content_type = (resp.headers.get("content-type") or "").split(";")[0].strip()
+ filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))
+ return resp.content, filename, content_type or None
+ except Exception as e:
+ logger.error("DingTalk media download error ref={} err={}", media_ref, e)
+ return None, None, None
+
+ try:
+ if media_ref.startswith("file://"):
+ parsed = urlparse(media_ref)
+ local_path = Path(unquote(parsed.path))
+ else:
+ local_path = Path(os.path.expanduser(media_ref))
+ if not local_path.is_file():
+ logger.warning("DingTalk media file not found: {}", local_path)
+ return None, None, None
+ data = await asyncio.to_thread(local_path.read_bytes)
+ content_type = mimetypes.guess_type(local_path.name)[0]
+ return data, local_path.name, content_type
+ except Exception as e:
+ logger.error("DingTalk media read error ref={} err={}", media_ref, e)
+ return None, None, None
+
+ async def _upload_media(
+ self,
+ token: str,
+ data: bytes,
+ media_type: str,
+ filename: str,
+ content_type: str | None,
+ ) -> str | None:
+ if not self._http:
+ return None
+ url = f"https://oapi.dingtalk.com/media/upload?access_token={token}&type={media_type}"
+ mime = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
+ files = {"media": (filename, data, mime)}
+
+ try:
+ resp = await self._http.post(url, files=files)
+ text = resp.text
+ result = resp.json() if resp.headers.get("content-type", "").startswith("application/json") else {}
+ if resp.status_code >= 400:
+ logger.error("DingTalk media upload failed status={} type={} body={}", resp.status_code, media_type, text[:500])
+ return None
+ errcode = result.get("errcode", 0)
+ if errcode != 0:
+ logger.error("DingTalk media upload api error type={} errcode={} body={}", media_type, errcode, text[:500])
+ return None
+ sub = result.get("result") or {}
+ media_id = result.get("media_id") or result.get("mediaId") or sub.get("media_id") or sub.get("mediaId")
+ if not media_id:
+ logger.error("DingTalk media upload missing media_id body={}", text[:500])
+ return None
+ return str(media_id)
+ except Exception as e:
+ logger.error("DingTalk media upload error type={} err={}", media_type, e)
+ return None
+
+ async def _send_batch_message(
+ self,
+ token: str,
+ chat_id: str,
+ msg_key: str,
+ msg_param: dict[str, Any],
+ ) -> bool:
+ if not self._http:
+ logger.warning("DingTalk HTTP client not initialized, cannot send")
+ return False
+
+ headers = {"x-acs-dingtalk-access-token": token}
+ if chat_id.startswith("group:"):
+ # Group chat
+ url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
+ payload = {
+ "robotCode": self.config.client_id,
+ "openConversationId": chat_id[6:], # Remove "group:" prefix,
+ "msgKey": msg_key,
+ "msgParam": json.dumps(msg_param, ensure_ascii=False),
+ }
+ else:
+ # Private chat
+ url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
+ payload = {
+ "robotCode": self.config.client_id,
+ "userIds": [chat_id],
+ "msgKey": msg_key,
+ "msgParam": json.dumps(msg_param, ensure_ascii=False),
+ }
+
+ try:
+ resp = await self._http.post(url, json=payload, headers=headers)
+ body = resp.text
+ if resp.status_code != 200:
+ logger.error("DingTalk send failed msgKey={} status={} body={}", msg_key, resp.status_code, body[:500])
+ return False
+ try: result = resp.json()
+ except Exception: result = {}
+ errcode = result.get("errcode")
+ if errcode not in (None, 0):
+ logger.error("DingTalk send api error msgKey={} errcode={} body={}", msg_key, errcode, body[:500])
+ return False
+ logger.debug("DingTalk message sent to {} with msgKey={}", chat_id, msg_key)
+ return True
+ except Exception as e:
+ logger.error("Error sending DingTalk message msgKey={} err={}", msg_key, e)
+ return False
+
+ async def _send_markdown_text(self, token: str, chat_id: str, content: str) -> bool:
+ return await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleMarkdown",
+ {"text": content, "title": "Nanobot Reply"},
+ )
+
+ async def _send_media_ref(self, token: str, chat_id: str, media_ref: str) -> bool:
+ media_ref = (media_ref or "").strip()
+ if not media_ref:
+ return True
+
+ upload_type = self._guess_upload_type(media_ref)
+ if upload_type == "image" and self._is_http_url(media_ref):
+ ok = await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleImageMsg",
+ {"photoURL": media_ref},
+ )
+ if ok:
+ return True
+ logger.warning("DingTalk image url send failed, trying upload fallback: {}", media_ref)
+
+ data, filename, content_type = await self._read_media_bytes(media_ref)
+ if not data:
+ logger.error("DingTalk media read failed: {}", media_ref)
+ return False
+
+ filename = filename or self._guess_filename(media_ref, upload_type)
+ file_type = Path(filename).suffix.lower().lstrip(".")
+ if not file_type:
+ guessed = mimetypes.guess_extension(content_type or "")
+ file_type = (guessed or ".bin").lstrip(".")
+ if file_type == "jpeg":
+ file_type = "jpg"
+
+ media_id = await self._upload_media(
+ token=token,
+ data=data,
+ media_type=upload_type,
+ filename=filename,
+ content_type=content_type,
+ )
+ if not media_id:
+ return False
+
+ if upload_type == "image":
+ # Verified in production: sampleImageMsg accepts media_id in photoURL.
+ ok = await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleImageMsg",
+ {"photoURL": media_id},
+ )
+ if ok:
+ return True
+ logger.warning("DingTalk image media_id send failed, falling back to file: {}", media_ref)
+
+ return await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleFile",
+ {"mediaId": media_id, "fileName": filename, "fileType": file_type},
+ )
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through DingTalk."""
+ token = await self._get_access_token()
+ if not token:
+ return
+
+ if msg.content and msg.content.strip():
+ await self._send_markdown_text(token, msg.chat_id, msg.content.strip())
+
+ for media_ref in msg.media or []:
+ ok = await self._send_media_ref(token, msg.chat_id, media_ref)
+ if ok:
+ continue
+ logger.error("DingTalk media send failed for {}", media_ref)
+ # Send visible fallback so failures are observable by the user.
+ filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))
+ await self._send_markdown_text(
+ token,
+ msg.chat_id,
+ f"[Attachment send failed: {filename}]",
+ )
+
+ async def _on_message(
+ self,
+ content: str,
+ sender_id: str,
+ sender_name: str,
+ conversation_type: str | None = None,
+ conversation_id: str | None = None,
+ ) -> None:
+ """Handle incoming message (called by NanobotDingTalkHandler).
+
+ Delegates to BaseChannel._handle_message() which enforces allow_from
+ permission checks before publishing to the bus.
+ """
+ try:
+ logger.info("DingTalk inbound: {} from {}", content, sender_name)
+ is_group = conversation_type == "2" and conversation_id
+ chat_id = f"group:{conversation_id}" if is_group else sender_id
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=chat_id,
+ content=str(content),
+ metadata={
+ "sender_name": sender_name,
+ "platform": "dingtalk",
+ "conversation_type": conversation_type,
+ },
+ )
+ except Exception as e:
+ logger.error("Error publishing DingTalk message: {}", e)
diff --git a/deeptutor/tutorbot/channels/discord.py b/deeptutor/tutorbot/channels/discord.py
new file mode 100644
index 000000000..b3bf01037
--- /dev/null
+++ b/deeptutor/tutorbot/channels/discord.py
@@ -0,0 +1,395 @@
+"""Discord channel implementation using Discord Gateway websocket."""
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any, Literal
+
+import httpx
+from pydantic import Field
+import websockets
+from loguru import logger
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.paths import get_media_dir
+from deeptutor.tutorbot.config.schema import Base
+from deeptutor.tutorbot.utils.helpers import split_message
+
+DISCORD_API_BASE = "https://discord.com/api/v10"
+MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # 20MB
+MAX_MESSAGE_LEN = 2000 # Discord message character limit
+
+
+class DiscordConfig(Base):
+ """Discord channel configuration."""
+
+ enabled: bool = False
+ token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ gateway_url: str = "wss://gateway.discord.gg/?v=10&encoding=json"
+ intents: int = 37377
+ group_policy: Literal["mention", "open"] = "mention"
+
+
+class DiscordChannel(BaseChannel):
+ """Discord channel using Gateway websocket."""
+
+ name = "discord"
+ display_name = "Discord"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return DiscordConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = DiscordConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: DiscordConfig = config
+ self._ws: websockets.WebSocketClientProtocol | None = None
+ self._seq: int | None = None
+ self._heartbeat_task: asyncio.Task | None = None
+ self._typing_tasks: dict[str, asyncio.Task] = {}
+ self._http: httpx.AsyncClient | None = None
+ self._bot_user_id: str | None = None
+
+ async def start(self) -> None:
+ """Start the Discord gateway connection."""
+ if not self.config.token:
+ logger.error("Discord bot token not configured")
+ return
+
+ self._running = True
+ self._http = httpx.AsyncClient(timeout=30.0)
+
+ while self._running:
+ try:
+ logger.info("Connecting to Discord gateway...")
+ async with websockets.connect(self.config.gateway_url) as ws:
+ self._ws = ws
+ await self._gateway_loop()
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.warning("Discord gateway error: {}", e)
+ if self._running:
+ logger.info("Reconnecting to Discord gateway in 5 seconds...")
+ await asyncio.sleep(5)
+
+ async def stop(self) -> None:
+ """Stop the Discord channel."""
+ self._running = False
+ if self._heartbeat_task:
+ self._heartbeat_task.cancel()
+ self._heartbeat_task = None
+ for task in self._typing_tasks.values():
+ task.cancel()
+ self._typing_tasks.clear()
+ if self._ws:
+ await self._ws.close()
+ self._ws = None
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Discord REST API, including file attachments."""
+ if not self._http:
+ logger.warning("Discord HTTP client not initialized")
+ return
+
+ url = f"{DISCORD_API_BASE}/channels/{msg.chat_id}/messages"
+ headers = {"Authorization": f"Bot {self.config.token}"}
+
+ try:
+ sent_media = False
+ failed_media: list[str] = []
+
+ # Send file attachments first
+ for media_path in msg.media or []:
+ if await self._send_file(url, headers, media_path, reply_to=msg.reply_to):
+ sent_media = True
+ else:
+ failed_media.append(Path(media_path).name)
+
+ # Send text content
+ chunks = split_message(msg.content or "", MAX_MESSAGE_LEN)
+ if not chunks and failed_media and not sent_media:
+ chunks = split_message(
+ "\n".join(f"[attachment: {name} - send failed]" for name in failed_media),
+ MAX_MESSAGE_LEN,
+ )
+ if not chunks:
+ return
+
+ for i, chunk in enumerate(chunks):
+ payload: dict[str, Any] = {"content": chunk}
+
+ # Let the first successful attachment carry the reply if present.
+ if i == 0 and msg.reply_to and not sent_media:
+ payload["message_reference"] = {"message_id": msg.reply_to}
+ payload["allowed_mentions"] = {"replied_user": False}
+
+ if not await self._send_payload(url, headers, payload):
+ break # Abort remaining chunks on failure
+ finally:
+ await self._stop_typing(msg.chat_id)
+
+ async def _send_payload(
+ self, url: str, headers: dict[str, str], payload: dict[str, Any]
+ ) -> bool:
+ """Send a single Discord API payload with retry on rate-limit. Returns True on success."""
+ for attempt in range(3):
+ try:
+ response = await self._http.post(url, headers=headers, json=payload)
+ if response.status_code == 429:
+ data = response.json()
+ retry_after = float(data.get("retry_after", 1.0))
+ logger.warning("Discord rate limited, retrying in {}s", retry_after)
+ await asyncio.sleep(retry_after)
+ continue
+ response.raise_for_status()
+ return True
+ except Exception as e:
+ if attempt == 2:
+ logger.error("Error sending Discord message: {}", e)
+ else:
+ await asyncio.sleep(1)
+ return False
+
+ async def _send_file(
+ self,
+ url: str,
+ headers: dict[str, str],
+ file_path: str,
+ reply_to: str | None = None,
+ ) -> bool:
+ """Send a file attachment via Discord REST API using multipart/form-data."""
+ path = Path(file_path)
+ if not path.is_file():
+ logger.warning("Discord file not found, skipping: {}", file_path)
+ return False
+
+ if path.stat().st_size > MAX_ATTACHMENT_BYTES:
+ logger.warning("Discord file too large (>20MB), skipping: {}", path.name)
+ return False
+
+ payload_json: dict[str, Any] = {}
+ if reply_to:
+ payload_json["message_reference"] = {"message_id": reply_to}
+ payload_json["allowed_mentions"] = {"replied_user": False}
+
+ for attempt in range(3):
+ try:
+ with open(path, "rb") as f:
+ files = {"files[0]": (path.name, f, "application/octet-stream")}
+ data: dict[str, Any] = {}
+ if payload_json:
+ data["payload_json"] = json.dumps(payload_json)
+ response = await self._http.post(
+ url, headers=headers, files=files, data=data
+ )
+ if response.status_code == 429:
+ resp_data = response.json()
+ retry_after = float(resp_data.get("retry_after", 1.0))
+ logger.warning("Discord rate limited, retrying in {}s", retry_after)
+ await asyncio.sleep(retry_after)
+ continue
+ response.raise_for_status()
+ logger.info("Discord file sent: {}", path.name)
+ return True
+ except Exception as e:
+ if attempt == 2:
+ logger.error("Error sending Discord file {}: {}", path.name, e)
+ else:
+ await asyncio.sleep(1)
+ return False
+
+ async def _gateway_loop(self) -> None:
+ """Main gateway loop: identify, heartbeat, dispatch events."""
+ if not self._ws:
+ return
+
+ async for raw in self._ws:
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ logger.warning("Invalid JSON from Discord gateway: {}", raw[:100])
+ continue
+
+ op = data.get("op")
+ event_type = data.get("t")
+ seq = data.get("s")
+ payload = data.get("d")
+
+ if seq is not None:
+ self._seq = seq
+
+ if op == 10:
+ # HELLO: start heartbeat and identify
+ interval_ms = payload.get("heartbeat_interval", 45000)
+ await self._start_heartbeat(interval_ms / 1000)
+ await self._identify()
+ elif op == 0 and event_type == "READY":
+ logger.info("Discord gateway READY")
+ # Capture bot user ID for mention detection
+ user_data = payload.get("user") or {}
+ self._bot_user_id = user_data.get("id")
+ logger.info("Discord bot connected as user {}", self._bot_user_id)
+ elif op == 0 and event_type == "MESSAGE_CREATE":
+ await self._handle_message_create(payload)
+ elif op == 7:
+ # RECONNECT: exit loop to reconnect
+ logger.info("Discord gateway requested reconnect")
+ break
+ elif op == 9:
+ # INVALID_SESSION: reconnect
+ logger.warning("Discord gateway invalid session")
+ break
+
+ async def _identify(self) -> None:
+ """Send IDENTIFY payload."""
+ if not self._ws:
+ return
+
+ identify = {
+ "op": 2,
+ "d": {
+ "token": self.config.token,
+ "intents": self.config.intents,
+ "properties": {
+ "os": "tutorbot",
+ "browser": "tutorbot",
+ "device": "tutorbot",
+ },
+ },
+ }
+ await self._ws.send(json.dumps(identify))
+
+ async def _start_heartbeat(self, interval_s: float) -> None:
+ """Start or restart the heartbeat loop."""
+ if self._heartbeat_task:
+ self._heartbeat_task.cancel()
+
+ async def heartbeat_loop() -> None:
+ while self._running and self._ws:
+ payload = {"op": 1, "d": self._seq}
+ try:
+ await self._ws.send(json.dumps(payload))
+ except Exception as e:
+ logger.warning("Discord heartbeat failed: {}", e)
+ break
+ await asyncio.sleep(interval_s)
+
+ self._heartbeat_task = asyncio.create_task(heartbeat_loop())
+
+ async def _handle_message_create(self, payload: dict[str, Any]) -> None:
+ """Handle incoming Discord messages."""
+ author = payload.get("author") or {}
+ if author.get("bot"):
+ return
+
+ sender_id = str(author.get("id", ""))
+ channel_id = str(payload.get("channel_id", ""))
+ content = payload.get("content") or ""
+ guild_id = payload.get("guild_id")
+
+ if not sender_id or not channel_id:
+ return
+
+ if not self.is_allowed(sender_id):
+ return
+
+ # Check group channel policy (DMs always respond if is_allowed passes)
+ if guild_id is not None:
+ if not self._should_respond_in_group(payload, content):
+ return
+
+ content_parts = [content] if content else []
+ media_paths: list[str] = []
+ media_dir = get_media_dir("discord")
+
+ for attachment in payload.get("attachments") or []:
+ url = attachment.get("url")
+ filename = attachment.get("filename") or "attachment"
+ size = attachment.get("size") or 0
+ if not url or not self._http:
+ continue
+ if size and size > MAX_ATTACHMENT_BYTES:
+ content_parts.append(f"[attachment: {filename} - too large]")
+ continue
+ try:
+ media_dir.mkdir(parents=True, exist_ok=True)
+ file_path = media_dir / f"{attachment.get('id', 'file')}_{filename.replace('/', '_')}"
+ resp = await self._http.get(url)
+ resp.raise_for_status()
+ file_path.write_bytes(resp.content)
+ media_paths.append(str(file_path))
+ content_parts.append(f"[attachment: {file_path}]")
+ except Exception as e:
+ logger.warning("Failed to download Discord attachment: {}", e)
+ content_parts.append(f"[attachment: {filename} - download failed]")
+
+ reply_to = (payload.get("referenced_message") or {}).get("id")
+
+ await self._start_typing(channel_id)
+
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=channel_id,
+ content="\n".join(p for p in content_parts if p) or "[empty message]",
+ media=media_paths,
+ metadata={
+ "message_id": str(payload.get("id", "")),
+ "guild_id": guild_id,
+ "reply_to": reply_to,
+ },
+ )
+
+ def _should_respond_in_group(self, payload: dict[str, Any], content: str) -> bool:
+ """Check if bot should respond in a group channel based on policy."""
+ if self.config.group_policy == "open":
+ return True
+
+ if self.config.group_policy == "mention":
+ # Check if bot was mentioned in the message
+ if self._bot_user_id:
+ # Check mentions array
+ mentions = payload.get("mentions") or []
+ for mention in mentions:
+ if str(mention.get("id")) == self._bot_user_id:
+ return True
+ # Also check content for mention format <@USER_ID>
+ if f"<@{self._bot_user_id}>" in content or f"<@!{self._bot_user_id}>" in content:
+ return True
+ logger.debug("Discord message in {} ignored (bot not mentioned)", payload.get("channel_id"))
+ return False
+
+ return True
+
+ async def _start_typing(self, channel_id: str) -> None:
+ """Start periodic typing indicator for a channel."""
+ await self._stop_typing(channel_id)
+
+ async def typing_loop() -> None:
+ url = f"{DISCORD_API_BASE}/channels/{channel_id}/typing"
+ headers = {"Authorization": f"Bot {self.config.token}"}
+ while self._running:
+ try:
+ await self._http.post(url, headers=headers)
+ except asyncio.CancelledError:
+ return
+ except Exception as e:
+ logger.debug("Discord typing indicator failed for {}: {}", channel_id, e)
+ return
+ await asyncio.sleep(8)
+
+ self._typing_tasks[channel_id] = asyncio.create_task(typing_loop())
+
+ async def _stop_typing(self, channel_id: str) -> None:
+ """Stop typing indicator for a channel."""
+ task = self._typing_tasks.pop(channel_id, None)
+ if task:
+ task.cancel()
diff --git a/deeptutor/tutorbot/channels/email.py b/deeptutor/tutorbot/channels/email.py
new file mode 100644
index 000000000..c4e1e6bfd
--- /dev/null
+++ b/deeptutor/tutorbot/channels/email.py
@@ -0,0 +1,445 @@
+"""Email channel implementation using IMAP polling + SMTP replies."""
+
+import asyncio
+import html
+import imaplib
+import re
+import smtplib
+import ssl
+from datetime import date
+from email import policy
+from email.header import decode_header, make_header
+from email.message import EmailMessage
+from email.parser import BytesParser
+from email.utils import parseaddr
+from typing import Any
+
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.schema import Base
+
+
+class EmailConfig(Base):
+ """Email channel configuration (IMAP inbound + SMTP outbound)."""
+
+ enabled: bool = False
+ consent_granted: bool = False
+
+ imap_host: str = ""
+ imap_port: int = 993
+ imap_username: str = ""
+ imap_password: str = ""
+ imap_mailbox: str = "INBOX"
+ imap_use_ssl: bool = True
+
+ smtp_host: str = ""
+ smtp_port: int = 587
+ smtp_username: str = ""
+ smtp_password: str = ""
+ smtp_use_tls: bool = True
+ smtp_use_ssl: bool = False
+ from_address: str = ""
+
+ auto_reply_enabled: bool = True
+ poll_interval_seconds: int = 30
+ mark_seen: bool = True
+ max_body_chars: int = 12000
+ subject_prefix: str = "Re: "
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class EmailChannel(BaseChannel):
+ """
+ Email channel.
+
+ Inbound:
+ - Poll IMAP mailbox for unread messages.
+ - Convert each message into an inbound event.
+
+ Outbound:
+ - Send responses via SMTP back to the sender address.
+ """
+
+ name = "email"
+ display_name = "Email"
+ _IMAP_MONTHS = (
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec",
+ )
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return EmailConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = EmailConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: EmailConfig = config
+ self._last_subject_by_chat: dict[str, str] = {}
+ self._last_message_id_by_chat: dict[str, str] = {}
+ self._processed_uids: set[str] = set() # Capped to prevent unbounded growth
+ self._MAX_PROCESSED_UIDS = 100000
+
+ async def start(self) -> None:
+ """Start polling IMAP for inbound emails."""
+ if not self.config.consent_granted:
+ logger.warning(
+ "Email channel disabled: consent_granted is false. "
+ "Set channels.email.consentGranted=true after explicit user permission."
+ )
+ return
+
+ if not self._validate_config():
+ return
+
+ self._running = True
+ logger.info("Starting Email channel (IMAP polling mode)...")
+
+ poll_seconds = max(5, int(self.config.poll_interval_seconds))
+ while self._running:
+ try:
+ inbound_items = await asyncio.to_thread(self._fetch_new_messages)
+ for item in inbound_items:
+ sender = item["sender"]
+ subject = item.get("subject", "")
+ message_id = item.get("message_id", "")
+
+ if subject:
+ self._last_subject_by_chat[sender] = subject
+ if message_id:
+ self._last_message_id_by_chat[sender] = message_id
+
+ await self._handle_message(
+ sender_id=sender,
+ chat_id=sender,
+ content=item["content"],
+ metadata=item.get("metadata", {}),
+ )
+ except Exception as e:
+ logger.error("Email polling error: {}", e)
+
+ await asyncio.sleep(poll_seconds)
+
+ async def stop(self) -> None:
+ """Stop polling loop."""
+ self._running = False
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send email via SMTP."""
+ if not self.config.consent_granted:
+ logger.warning("Skip email send: consent_granted is false")
+ return
+
+ if not self.config.smtp_host:
+ logger.warning("Email channel SMTP host not configured")
+ return
+
+ to_addr = msg.chat_id.strip()
+ if not to_addr:
+ logger.warning("Email channel missing recipient address")
+ return
+
+ # Determine if this is a reply (recipient has sent us an email before)
+ is_reply = to_addr in self._last_subject_by_chat
+ force_send = bool((msg.metadata or {}).get("force_send"))
+
+ # autoReplyEnabled only controls automatic replies, not proactive sends
+ if is_reply and not self.config.auto_reply_enabled and not force_send:
+ logger.info("Skip automatic email reply to {}: auto_reply_enabled is false", to_addr)
+ return
+
+ base_subject = self._last_subject_by_chat.get(to_addr, "TutorBot reply")
+ subject = self._reply_subject(base_subject)
+ if msg.metadata and isinstance(msg.metadata.get("subject"), str):
+ override = msg.metadata["subject"].strip()
+ if override:
+ subject = override
+
+ email_msg = EmailMessage()
+ email_msg["From"] = self.config.from_address or self.config.smtp_username or self.config.imap_username
+ email_msg["To"] = to_addr
+ email_msg["Subject"] = subject
+ email_msg.set_content(msg.content or "")
+
+ in_reply_to = self._last_message_id_by_chat.get(to_addr)
+ if in_reply_to:
+ email_msg["In-Reply-To"] = in_reply_to
+ email_msg["References"] = in_reply_to
+
+ try:
+ await asyncio.to_thread(self._smtp_send, email_msg)
+ except Exception as e:
+ logger.error("Error sending email to {}: {}", to_addr, e)
+ raise
+
+ def _validate_config(self) -> bool:
+ missing = []
+ if not self.config.imap_host:
+ missing.append("imap_host")
+ if not self.config.imap_username:
+ missing.append("imap_username")
+ if not self.config.imap_password:
+ missing.append("imap_password")
+ if not self.config.smtp_host:
+ missing.append("smtp_host")
+ if not self.config.smtp_username:
+ missing.append("smtp_username")
+ if not self.config.smtp_password:
+ missing.append("smtp_password")
+
+ if missing:
+ logger.error("Email channel not configured, missing: {}", ', '.join(missing))
+ return False
+ return True
+
+ def _smtp_send(self, msg: EmailMessage) -> None:
+ timeout = 30
+ if self.config.smtp_use_ssl:
+ with smtplib.SMTP_SSL(
+ self.config.smtp_host,
+ self.config.smtp_port,
+ timeout=timeout,
+ ) as smtp:
+ smtp.login(self.config.smtp_username, self.config.smtp_password)
+ smtp.send_message(msg)
+ return
+
+ with smtplib.SMTP(self.config.smtp_host, self.config.smtp_port, timeout=timeout) as smtp:
+ if self.config.smtp_use_tls:
+ smtp.starttls(context=ssl.create_default_context())
+ smtp.login(self.config.smtp_username, self.config.smtp_password)
+ smtp.send_message(msg)
+
+ def _fetch_new_messages(self) -> list[dict[str, Any]]:
+ """Poll IMAP and return parsed unread messages."""
+ return self._fetch_messages(
+ search_criteria=("UNSEEN",),
+ mark_seen=self.config.mark_seen,
+ dedupe=True,
+ limit=0,
+ )
+
+ def fetch_messages_between_dates(
+ self,
+ start_date: date,
+ end_date: date,
+ limit: int = 20,
+ ) -> list[dict[str, Any]]:
+ """
+ Fetch messages in [start_date, end_date) by IMAP date search.
+
+ This is used for historical summarization tasks (e.g. "yesterday").
+ """
+ if end_date <= start_date:
+ return []
+
+ return self._fetch_messages(
+ search_criteria=(
+ "SINCE",
+ self._format_imap_date(start_date),
+ "BEFORE",
+ self._format_imap_date(end_date),
+ ),
+ mark_seen=False,
+ dedupe=False,
+ limit=max(1, int(limit)),
+ )
+
+ def _fetch_messages(
+ self,
+ search_criteria: tuple[str, ...],
+ mark_seen: bool,
+ dedupe: bool,
+ limit: int,
+ ) -> list[dict[str, Any]]:
+ """Fetch messages by arbitrary IMAP search criteria."""
+ messages: list[dict[str, Any]] = []
+ mailbox = self.config.imap_mailbox or "INBOX"
+
+ if self.config.imap_use_ssl:
+ client = imaplib.IMAP4_SSL(self.config.imap_host, self.config.imap_port)
+ else:
+ client = imaplib.IMAP4(self.config.imap_host, self.config.imap_port)
+
+ try:
+ client.login(self.config.imap_username, self.config.imap_password)
+ status, _ = client.select(mailbox)
+ if status != "OK":
+ return messages
+
+ status, data = client.search(None, *search_criteria)
+ if status != "OK" or not data:
+ return messages
+
+ ids = data[0].split()
+ if limit > 0 and len(ids) > limit:
+ ids = ids[-limit:]
+ for imap_id in ids:
+ status, fetched = client.fetch(imap_id, "(BODY.PEEK[] UID)")
+ if status != "OK" or not fetched:
+ continue
+
+ raw_bytes = self._extract_message_bytes(fetched)
+ if raw_bytes is None:
+ continue
+
+ uid = self._extract_uid(fetched)
+ if dedupe and uid and uid in self._processed_uids:
+ continue
+
+ parsed = BytesParser(policy=policy.default).parsebytes(raw_bytes)
+ sender = parseaddr(parsed.get("From", ""))[1].strip().lower()
+ if not sender:
+ continue
+
+ subject = self._decode_header_value(parsed.get("Subject", ""))
+ date_value = parsed.get("Date", "")
+ message_id = parsed.get("Message-ID", "").strip()
+ body = self._extract_text_body(parsed)
+
+ if not body:
+ body = "(empty email body)"
+
+ body = body[: self.config.max_body_chars]
+ content = (
+ f"Email received.\n"
+ f"From: {sender}\n"
+ f"Subject: {subject}\n"
+ f"Date: {date_value}\n\n"
+ f"{body}"
+ )
+
+ metadata = {
+ "message_id": message_id,
+ "subject": subject,
+ "date": date_value,
+ "sender_email": sender,
+ "uid": uid,
+ }
+ messages.append(
+ {
+ "sender": sender,
+ "subject": subject,
+ "message_id": message_id,
+ "content": content,
+ "metadata": metadata,
+ }
+ )
+
+ if dedupe and uid:
+ self._processed_uids.add(uid)
+ # mark_seen is the primary dedup; this set is a safety net
+ if len(self._processed_uids) > self._MAX_PROCESSED_UIDS:
+ # Evict a random half to cap memory; mark_seen is the primary dedup
+ self._processed_uids = set(list(self._processed_uids)[len(self._processed_uids) // 2:])
+
+ if mark_seen:
+ client.store(imap_id, "+FLAGS", "\\Seen")
+ finally:
+ try:
+ client.logout()
+ except Exception:
+ pass
+
+ return messages
+
+ @classmethod
+ def _format_imap_date(cls, value: date) -> str:
+ """Format date for IMAP search (always English month abbreviations)."""
+ month = cls._IMAP_MONTHS[value.month - 1]
+ return f"{value.day:02d}-{month}-{value.year}"
+
+ @staticmethod
+ def _extract_message_bytes(fetched: list[Any]) -> bytes | None:
+ for item in fetched:
+ if isinstance(item, tuple) and len(item) >= 2 and isinstance(item[1], (bytes, bytearray)):
+ return bytes(item[1])
+ return None
+
+ @staticmethod
+ def _extract_uid(fetched: list[Any]) -> str:
+ for item in fetched:
+ if isinstance(item, tuple) and item and isinstance(item[0], (bytes, bytearray)):
+ head = bytes(item[0]).decode("utf-8", errors="ignore")
+ m = re.search(r"UID\s+(\d+)", head)
+ if m:
+ return m.group(1)
+ return ""
+
+ @staticmethod
+ def _decode_header_value(value: str) -> str:
+ if not value:
+ return ""
+ try:
+ return str(make_header(decode_header(value)))
+ except Exception:
+ return value
+
+ @classmethod
+ def _extract_text_body(cls, msg: Any) -> str:
+ """Best-effort extraction of readable body text."""
+ if msg.is_multipart():
+ plain_parts: list[str] = []
+ html_parts: list[str] = []
+ for part in msg.walk():
+ if part.get_content_disposition() == "attachment":
+ continue
+ content_type = part.get_content_type()
+ try:
+ payload = part.get_content()
+ except Exception:
+ payload_bytes = part.get_payload(decode=True) or b""
+ charset = part.get_content_charset() or "utf-8"
+ payload = payload_bytes.decode(charset, errors="replace")
+ if not isinstance(payload, str):
+ continue
+ if content_type == "text/plain":
+ plain_parts.append(payload)
+ elif content_type == "text/html":
+ html_parts.append(payload)
+ if plain_parts:
+ return "\n\n".join(plain_parts).strip()
+ if html_parts:
+ return cls._html_to_text("\n\n".join(html_parts)).strip()
+ return ""
+
+ try:
+ payload = msg.get_content()
+ except Exception:
+ payload_bytes = msg.get_payload(decode=True) or b""
+ charset = msg.get_content_charset() or "utf-8"
+ payload = payload_bytes.decode(charset, errors="replace")
+ if not isinstance(payload, str):
+ return ""
+ if msg.get_content_type() == "text/html":
+ return cls._html_to_text(payload).strip()
+ return payload.strip()
+
+ @staticmethod
+ def _html_to_text(raw_html: str) -> str:
+ text = re.sub(r"<\s*br\s*/?>", "\n", raw_html, flags=re.IGNORECASE)
+ text = re.sub(r"<\s*/\s*p\s*>", "\n", text, flags=re.IGNORECASE)
+ text = re.sub(r"<[^>]+>", "", text)
+ return html.unescape(text)
+
+ def _reply_subject(self, base_subject: str) -> str:
+ subject = (base_subject or "").strip() or "TutorBot reply"
+ prefix = self.config.subject_prefix or "Re: "
+ if subject.lower().startswith("re:"):
+ return subject
+ return f"{prefix}{subject}"
diff --git a/deeptutor/tutorbot/channels/feishu.py b/deeptutor/tutorbot/channels/feishu.py
new file mode 100644
index 000000000..b11d51102
--- /dev/null
+++ b/deeptutor/tutorbot/channels/feishu.py
@@ -0,0 +1,1025 @@
+"""Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection."""
+
+import asyncio
+import json
+import os
+import re
+import threading
+from collections import OrderedDict
+from pathlib import Path
+from typing import Any, Literal
+
+from loguru import logger
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.paths import get_media_dir
+from deeptutor.tutorbot.config.schema import Base
+from pydantic import Field
+
+import importlib.util
+
+FEISHU_AVAILABLE = importlib.util.find_spec("lark_oapi") is not None
+
+# Message type display mapping
+MSG_TYPE_MAP = {
+ "image": "[image]",
+ "audio": "[audio]",
+ "file": "[file]",
+ "sticker": "[sticker]",
+}
+
+
+def _extract_share_card_content(content_json: dict, msg_type: str) -> str:
+ """Extract text representation from share cards and interactive messages."""
+ parts = []
+
+ if msg_type == "share_chat":
+ parts.append(f"[shared chat: {content_json.get('chat_id', '')}]")
+ elif msg_type == "share_user":
+ parts.append(f"[shared user: {content_json.get('user_id', '')}]")
+ elif msg_type == "interactive":
+ parts.extend(_extract_interactive_content(content_json))
+ elif msg_type == "share_calendar_event":
+ parts.append(f"[shared calendar event: {content_json.get('event_key', '')}]")
+ elif msg_type == "system":
+ parts.append("[system message]")
+ elif msg_type == "merge_forward":
+ parts.append("[merged forward messages]")
+
+ return "\n".join(parts) if parts else f"[{msg_type}]"
+
+
+def _extract_interactive_content(content: dict) -> list[str]:
+ """Recursively extract text and links from interactive card content."""
+ parts = []
+
+ if isinstance(content, str):
+ try:
+ content = json.loads(content)
+ except (json.JSONDecodeError, TypeError):
+ return [content] if content.strip() else []
+
+ if not isinstance(content, dict):
+ return parts
+
+ if "title" in content:
+ title = content["title"]
+ if isinstance(title, dict):
+ title_content = title.get("content", "") or title.get("text", "")
+ if title_content:
+ parts.append(f"title: {title_content}")
+ elif isinstance(title, str):
+ parts.append(f"title: {title}")
+
+ for elements in content.get("elements", []) if isinstance(content.get("elements"), list) else []:
+ for element in elements:
+ parts.extend(_extract_element_content(element))
+
+ card = content.get("card", {})
+ if card:
+ parts.extend(_extract_interactive_content(card))
+
+ header = content.get("header", {})
+ if header:
+ header_title = header.get("title", {})
+ if isinstance(header_title, dict):
+ header_text = header_title.get("content", "") or header_title.get("text", "")
+ if header_text:
+ parts.append(f"title: {header_text}")
+
+ return parts
+
+
+def _extract_element_content(element: dict) -> list[str]:
+ """Extract content from a single card element."""
+ parts = []
+
+ if not isinstance(element, dict):
+ return parts
+
+ tag = element.get("tag", "")
+
+ if tag in ("markdown", "lark_md"):
+ content = element.get("content", "")
+ if content:
+ parts.append(content)
+
+ elif tag == "div":
+ text = element.get("text", {})
+ if isinstance(text, dict):
+ text_content = text.get("content", "") or text.get("text", "")
+ if text_content:
+ parts.append(text_content)
+ elif isinstance(text, str):
+ parts.append(text)
+ for field in element.get("fields", []):
+ if isinstance(field, dict):
+ field_text = field.get("text", {})
+ if isinstance(field_text, dict):
+ c = field_text.get("content", "")
+ if c:
+ parts.append(c)
+
+ elif tag == "a":
+ href = element.get("href", "")
+ text = element.get("text", "")
+ if href:
+ parts.append(f"link: {href}")
+ if text:
+ parts.append(text)
+
+ elif tag == "button":
+ text = element.get("text", {})
+ if isinstance(text, dict):
+ c = text.get("content", "")
+ if c:
+ parts.append(c)
+ url = element.get("url", "") or element.get("multi_url", {}).get("url", "")
+ if url:
+ parts.append(f"link: {url}")
+
+ elif tag == "img":
+ alt = element.get("alt", {})
+ parts.append(alt.get("content", "[image]") if isinstance(alt, dict) else "[image]")
+
+ elif tag == "note":
+ for ne in element.get("elements", []):
+ parts.extend(_extract_element_content(ne))
+
+ elif tag == "column_set":
+ for col in element.get("columns", []):
+ for ce in col.get("elements", []):
+ parts.extend(_extract_element_content(ce))
+
+ elif tag == "plain_text":
+ content = element.get("content", "")
+ if content:
+ parts.append(content)
+
+ else:
+ for ne in element.get("elements", []):
+ parts.extend(_extract_element_content(ne))
+
+ return parts
+
+
+def _extract_post_content(content_json: dict) -> tuple[str, list[str]]:
+ """Extract text and image keys from Feishu post (rich text) message.
+
+ Handles three payload shapes:
+ - Direct: {"title": "...", "content": [[...]]}
+ - Localized: {"zh_cn": {"title": "...", "content": [...]}}
+ - Wrapped: {"post": {"zh_cn": {"title": "...", "content": [...]}}}
+ """
+
+ def _parse_block(block: dict) -> tuple[str | None, list[str]]:
+ if not isinstance(block, dict) or not isinstance(block.get("content"), list):
+ return None, []
+ texts, images = [], []
+ if title := block.get("title"):
+ texts.append(title)
+ for row in block["content"]:
+ if not isinstance(row, list):
+ continue
+ for el in row:
+ if not isinstance(el, dict):
+ continue
+ tag = el.get("tag")
+ if tag in ("text", "a"):
+ texts.append(el.get("text", ""))
+ elif tag == "at":
+ texts.append(f"@{el.get('user_name', 'user')}")
+ elif tag == "img" and (key := el.get("image_key")):
+ images.append(key)
+ return (" ".join(texts).strip() or None), images
+
+ # Unwrap optional {"post": ...} envelope
+ root = content_json
+ if isinstance(root, dict) and isinstance(root.get("post"), dict):
+ root = root["post"]
+ if not isinstance(root, dict):
+ return "", []
+
+ # Direct format
+ if "content" in root:
+ text, imgs = _parse_block(root)
+ if text or imgs:
+ return text or "", imgs
+
+ # Localized: prefer known locales, then fall back to any dict child
+ for key in ("zh_cn", "en_us", "ja_jp"):
+ if key in root:
+ text, imgs = _parse_block(root[key])
+ if text or imgs:
+ return text or "", imgs
+ for val in root.values():
+ if isinstance(val, dict):
+ text, imgs = _parse_block(val)
+ if text or imgs:
+ return text or "", imgs
+
+ return "", []
+
+
+def _extract_post_text(content_json: dict) -> str:
+ """Extract plain text from Feishu post (rich text) message content.
+
+ Legacy wrapper for _extract_post_content, returns only text.
+ """
+ text, _ = _extract_post_content(content_json)
+ return text
+
+
+class FeishuConfig(Base):
+ """Feishu/Lark channel configuration using WebSocket long connection."""
+
+ enabled: bool = False
+ app_id: str = ""
+ app_secret: str = ""
+ encrypt_key: str = ""
+ verification_token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ react_emoji: str = "THUMBSUP"
+ group_policy: Literal["open", "mention"] = "mention"
+
+
+class FeishuChannel(BaseChannel):
+ """
+ Feishu/Lark channel using WebSocket long connection.
+
+ Uses WebSocket to receive events - no public IP or webhook required.
+
+ Requires:
+ - App ID and App Secret from Feishu Open Platform
+ - Bot capability enabled
+ - Event subscription enabled (im.message.receive_v1)
+ """
+
+ name = "feishu"
+ display_name = "Feishu"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return FeishuConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = FeishuConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: FeishuConfig = config
+ self._client: Any = None
+ self._ws_client: Any = None
+ self._ws_thread: threading.Thread | None = None
+ self._processed_message_ids: OrderedDict[str, None] = OrderedDict() # Ordered dedup cache
+ self._loop: asyncio.AbstractEventLoop | None = None
+
+ @staticmethod
+ def _register_optional_event(builder: Any, method_name: str, handler: Any) -> Any:
+ """Register an event handler only when the SDK supports it."""
+ method = getattr(builder, method_name, None)
+ return method(handler) if callable(method) else builder
+
+ async def start(self) -> None:
+ """Start the Feishu bot with WebSocket long connection."""
+ if not FEISHU_AVAILABLE:
+ logger.error("Feishu SDK not installed. Run: pip install lark-oapi")
+ return
+
+ if not self.config.app_id or not self.config.app_secret:
+ logger.error("Feishu app_id and app_secret not configured")
+ return
+
+ import lark_oapi as lark
+ self._running = True
+ self._loop = asyncio.get_running_loop()
+
+ # Create Lark client for sending messages
+ self._client = lark.Client.builder() \
+ .app_id(self.config.app_id) \
+ .app_secret(self.config.app_secret) \
+ .log_level(lark.LogLevel.INFO) \
+ .build()
+ builder = lark.EventDispatcherHandler.builder(
+ self.config.encrypt_key or "",
+ self.config.verification_token or "",
+ ).register_p2_im_message_receive_v1(
+ self._on_message_sync
+ )
+ builder = self._register_optional_event(
+ builder, "register_p2_im_message_reaction_created_v1", self._on_reaction_created
+ )
+ builder = self._register_optional_event(
+ builder, "register_p2_im_message_message_read_v1", self._on_message_read
+ )
+ builder = self._register_optional_event(
+ builder,
+ "register_p2_im_chat_access_event_bot_p2p_chat_entered_v1",
+ self._on_bot_p2p_chat_entered,
+ )
+ event_handler = builder.build()
+
+ # Create WebSocket client for long connection
+ self._ws_client = lark.ws.Client(
+ self.config.app_id,
+ self.config.app_secret,
+ event_handler=event_handler,
+ log_level=lark.LogLevel.INFO
+ )
+
+ # Start WebSocket client in a separate thread with reconnect loop.
+ # A dedicated event loop is created for this thread so that lark_oapi's
+ # module-level `loop = asyncio.get_event_loop()` picks up an idle loop
+ # instead of the already-running main asyncio loop, which would cause
+ # "This event loop is already running" errors.
+ def run_ws():
+ import time
+ import lark_oapi.ws.client as _lark_ws_client
+ ws_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(ws_loop)
+ # Patch the module-level loop used by lark's ws Client.start()
+ _lark_ws_client.loop = ws_loop
+ try:
+ while self._running:
+ try:
+ self._ws_client.start()
+ except Exception as e:
+ logger.warning("Feishu WebSocket error: {}", e)
+ if self._running:
+ time.sleep(5)
+ finally:
+ ws_loop.close()
+
+ self._ws_thread = threading.Thread(target=run_ws, daemon=True)
+ self._ws_thread.start()
+
+ logger.info("Feishu bot started with WebSocket long connection")
+ logger.info("No public IP required - using WebSocket to receive events")
+
+ # Keep running until stopped
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """
+ Stop the Feishu bot.
+
+ Notice: lark.ws.Client does not expose stop method, simply exiting the program will close the client.
+
+ Reference: https://github.com/larksuite/oapi-sdk-python/blob/v2_main/lark_oapi/ws/client.py#L86
+ """
+ self._running = False
+ logger.info("Feishu bot stopped")
+
+ def _is_bot_mentioned(self, message: Any) -> bool:
+ """Check if the bot is @mentioned in the message."""
+ raw_content = message.content or ""
+ if "@_all" in raw_content:
+ return True
+
+ for mention in getattr(message, "mentions", None) or []:
+ mid = getattr(mention, "id", None)
+ if not mid:
+ continue
+ # Bot mentions have no user_id (None or "") but a valid open_id
+ if not getattr(mid, "user_id", None) and (getattr(mid, "open_id", None) or "").startswith("ou_"):
+ return True
+ return False
+
+ def _is_group_message_for_bot(self, message: Any) -> bool:
+ """Allow group messages when policy is open or bot is @mentioned."""
+ if self.config.group_policy == "open":
+ return True
+ return self._is_bot_mentioned(message)
+
+ def _add_reaction_sync(self, message_id: str, emoji_type: str) -> None:
+ """Sync helper for adding reaction (runs in thread pool)."""
+ from lark_oapi.api.im.v1 import CreateMessageReactionRequest, CreateMessageReactionRequestBody, Emoji
+ try:
+ request = CreateMessageReactionRequest.builder() \
+ .message_id(message_id) \
+ .request_body(
+ CreateMessageReactionRequestBody.builder()
+ .reaction_type(Emoji.builder().emoji_type(emoji_type).build())
+ .build()
+ ).build()
+
+ response = self._client.im.v1.message_reaction.create(request)
+
+ if not response.success():
+ logger.warning("Failed to add reaction: code={}, msg={}", response.code, response.msg)
+ else:
+ logger.debug("Added {} reaction to message {}", emoji_type, message_id)
+ except Exception as e:
+ logger.warning("Error adding reaction: {}", e)
+
+ async def _add_reaction(self, message_id: str, emoji_type: str = "THUMBSUP") -> None:
+ """
+ Add a reaction emoji to a message (non-blocking).
+
+ Common emoji types: THUMBSUP, OK, EYES, DONE, OnIt, HEART
+ """
+ if not self._client:
+ return
+
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(None, self._add_reaction_sync, message_id, emoji_type)
+
+ # Regex to match markdown tables (header + separator + data rows)
+ _TABLE_RE = re.compile(
+ r"((?:^[ \t]*\|.+\|[ \t]*\n)(?:^[ \t]*\|[-:\s|]+\|[ \t]*\n)(?:^[ \t]*\|.+\|[ \t]*\n?)+)",
+ re.MULTILINE,
+ )
+
+ _HEADING_RE = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)
+
+ _CODE_BLOCK_RE = re.compile(r"(```[\s\S]*?```)", re.MULTILINE)
+
+ @staticmethod
+ def _parse_md_table(table_text: str) -> dict | None:
+ """Parse a markdown table into a Feishu table element."""
+ lines = [_line.strip() for _line in table_text.strip().split("\n") if _line.strip()]
+ if len(lines) < 3:
+ return None
+ def split(_line: str) -> list[str]:
+ return [c.strip() for c in _line.strip("|").split("|")]
+ headers = split(lines[0])
+ rows = [split(_line) for _line in lines[2:]]
+ columns = [{"tag": "column", "name": f"c{i}", "display_name": h, "width": "auto"}
+ for i, h in enumerate(headers)]
+ return {
+ "tag": "table",
+ "page_size": len(rows) + 1,
+ "columns": columns,
+ "rows": [{f"c{i}": r[i] if i < len(r) else "" for i in range(len(headers))} for r in rows],
+ }
+
+ def _build_card_elements(self, content: str) -> list[dict]:
+ """Split content into div/markdown + table elements for Feishu card."""
+ elements, last_end = [], 0
+ for m in self._TABLE_RE.finditer(content):
+ before = content[last_end:m.start()]
+ if before.strip():
+ elements.extend(self._split_headings(before))
+ elements.append(self._parse_md_table(m.group(1)) or {"tag": "markdown", "content": m.group(1)})
+ last_end = m.end()
+ remaining = content[last_end:]
+ if remaining.strip():
+ elements.extend(self._split_headings(remaining))
+ return elements or [{"tag": "markdown", "content": content}]
+
+ @staticmethod
+ def _split_elements_by_table_limit(elements: list[dict], max_tables: int = 1) -> list[list[dict]]:
+ """Split card elements into groups with at most *max_tables* table elements each.
+
+ Feishu cards have a hard limit of one table per card (API error 11310).
+ When the rendered content contains multiple markdown tables each table is
+ placed in a separate card message so every table reaches the user.
+ """
+ if not elements:
+ return [[]]
+ groups: list[list[dict]] = []
+ current: list[dict] = []
+ table_count = 0
+ for el in elements:
+ if el.get("tag") == "table":
+ if table_count >= max_tables:
+ if current:
+ groups.append(current)
+ current = []
+ table_count = 0
+ current.append(el)
+ table_count += 1
+ else:
+ current.append(el)
+ if current:
+ groups.append(current)
+ return groups or [[]]
+
+ def _split_headings(self, content: str) -> list[dict]:
+ """Split content by headings, converting headings to div elements."""
+ protected = content
+ code_blocks = []
+ for m in self._CODE_BLOCK_RE.finditer(content):
+ code_blocks.append(m.group(1))
+ protected = protected.replace(m.group(1), f"\x00CODE{len(code_blocks)-1}\x00", 1)
+
+ elements = []
+ last_end = 0
+ for m in self._HEADING_RE.finditer(protected):
+ before = protected[last_end:m.start()].strip()
+ if before:
+ elements.append({"tag": "markdown", "content": before})
+ text = m.group(2).strip()
+ elements.append({
+ "tag": "div",
+ "text": {
+ "tag": "lark_md",
+ "content": f"**{text}**",
+ },
+ })
+ last_end = m.end()
+ remaining = protected[last_end:].strip()
+ if remaining:
+ elements.append({"tag": "markdown", "content": remaining})
+
+ for i, cb in enumerate(code_blocks):
+ for el in elements:
+ if el.get("tag") == "markdown":
+ el["content"] = el["content"].replace(f"\x00CODE{i}\x00", cb)
+
+ return elements or [{"tag": "markdown", "content": content}]
+
+ # ── Smart format detection ──────────────────────────────────────────
+ # Patterns that indicate "complex" markdown needing card rendering
+ _COMPLEX_MD_RE = re.compile(
+ r"```" # fenced code block
+ r"|^\|.+\|.*\n\s*\|[-:\s|]+\|" # markdown table (header + separator)
+ r"|^#{1,6}\s+" # headings
+ , re.MULTILINE,
+ )
+
+ # Simple markdown patterns (bold, italic, strikethrough)
+ _SIMPLE_MD_RE = re.compile(
+ r"\*\*.+?\*\*" # **bold**
+ r"|__.+?__" # __bold__
+ r"|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)" # *italic* (single *)
+ r"|~~.+?~~" # ~~strikethrough~~
+ , re.DOTALL,
+ )
+
+ # Markdown link: [text](url)
+ _MD_LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\)]+)\)")
+
+ # Unordered list items
+ _LIST_RE = re.compile(r"^[\s]*[-*+]\s+", re.MULTILINE)
+
+ # Ordered list items
+ _OLIST_RE = re.compile(r"^[\s]*\d+\.\s+", re.MULTILINE)
+
+ # Max length for plain text format
+ _TEXT_MAX_LEN = 200
+
+ # Max length for post (rich text) format; beyond this, use card
+ _POST_MAX_LEN = 2000
+
+ @classmethod
+ def _detect_msg_format(cls, content: str) -> str:
+ """Determine the optimal Feishu message format for *content*.
+
+ Returns one of:
+ - ``"text"`` – plain text, short and no markdown
+ - ``"post"`` – rich text (links only, moderate length)
+ - ``"interactive"`` – card with full markdown rendering
+ """
+ stripped = content.strip()
+
+ # Complex markdown (code blocks, tables, headings) → always card
+ if cls._COMPLEX_MD_RE.search(stripped):
+ return "interactive"
+
+ # Long content → card (better readability with card layout)
+ if len(stripped) > cls._POST_MAX_LEN:
+ return "interactive"
+
+ # Has bold/italic/strikethrough → card (post format can't render these)
+ if cls._SIMPLE_MD_RE.search(stripped):
+ return "interactive"
+
+ # Has list items → card (post format can't render list bullets well)
+ if cls._LIST_RE.search(stripped) or cls._OLIST_RE.search(stripped):
+ return "interactive"
+
+ # Has links → post format (supports <a> tags)
+ if cls._MD_LINK_RE.search(stripped):
+ return "post"
+
+ # Short plain text → text format
+ if len(stripped) <= cls._TEXT_MAX_LEN:
+ return "text"
+
+ # Medium plain text without any formatting → post format
+ return "post"
+
+ @classmethod
+ def _markdown_to_post(cls, content: str) -> str:
+ """Convert markdown content to Feishu post message JSON.
+
+ Handles links ``[text](url)`` as ``a`` tags; everything else as ``text`` tags.
+ Each line becomes a paragraph (row) in the post body.
+ """
+ lines = content.strip().split("\n")
+ paragraphs: list[list[dict]] = []
+
+ for line in lines:
+ elements: list[dict] = []
+ last_end = 0
+
+ for m in cls._MD_LINK_RE.finditer(line):
+ # Text before this link
+ before = line[last_end:m.start()]
+ if before:
+ elements.append({"tag": "text", "text": before})
+ elements.append({
+ "tag": "a",
+ "text": m.group(1),
+ "href": m.group(2),
+ })
+ last_end = m.end()
+
+ # Remaining text after last link
+ remaining = line[last_end:]
+ if remaining:
+ elements.append({"tag": "text", "text": remaining})
+
+ # Empty line → empty paragraph for spacing
+ if not elements:
+ elements.append({"tag": "text", "text": ""})
+
+ paragraphs.append(elements)
+
+ post_body = {
+ "zh_cn": {
+ "content": paragraphs,
+ }
+ }
+ return json.dumps(post_body, ensure_ascii=False)
+
+ _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".ico", ".tiff", ".tif"}
+ _AUDIO_EXTS = {".opus"}
+ _VIDEO_EXTS = {".mp4", ".mov", ".avi"}
+ _FILE_TYPE_MAP = {
+ ".opus": "opus", ".mp4": "mp4", ".pdf": "pdf", ".doc": "doc", ".docx": "doc",
+ ".xls": "xls", ".xlsx": "xls", ".ppt": "ppt", ".pptx": "ppt",
+ }
+
+ def _upload_image_sync(self, file_path: str) -> str | None:
+ """Upload an image to Feishu and return the image_key."""
+ from lark_oapi.api.im.v1 import CreateImageRequest, CreateImageRequestBody
+ try:
+ with open(file_path, "rb") as f:
+ request = CreateImageRequest.builder() \
+ .request_body(
+ CreateImageRequestBody.builder()
+ .image_type("message")
+ .image(f)
+ .build()
+ ).build()
+ response = self._client.im.v1.image.create(request)
+ if response.success():
+ image_key = response.data.image_key
+ logger.debug("Uploaded image {}: {}", os.path.basename(file_path), image_key)
+ return image_key
+ else:
+ logger.error("Failed to upload image: code={}, msg={}", response.code, response.msg)
+ return None
+ except Exception as e:
+ logger.error("Error uploading image {}: {}", file_path, e)
+ return None
+
+ def _upload_file_sync(self, file_path: str) -> str | None:
+ """Upload a file to Feishu and return the file_key."""
+ from lark_oapi.api.im.v1 import CreateFileRequest, CreateFileRequestBody
+ ext = os.path.splitext(file_path)[1].lower()
+ file_type = self._FILE_TYPE_MAP.get(ext, "stream")
+ file_name = os.path.basename(file_path)
+ try:
+ with open(file_path, "rb") as f:
+ request = CreateFileRequest.builder() \
+ .request_body(
+ CreateFileRequestBody.builder()
+ .file_type(file_type)
+ .file_name(file_name)
+ .file(f)
+ .build()
+ ).build()
+ response = self._client.im.v1.file.create(request)
+ if response.success():
+ file_key = response.data.file_key
+ logger.debug("Uploaded file {}: {}", file_name, file_key)
+ return file_key
+ else:
+ logger.error("Failed to upload file: code={}, msg={}", response.code, response.msg)
+ return None
+ except Exception as e:
+ logger.error("Error uploading file {}: {}", file_path, e)
+ return None
+
+ def _download_image_sync(self, message_id: str, image_key: str) -> tuple[bytes | None, str | None]:
+ """Download an image from Feishu message by message_id and image_key."""
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+ try:
+ request = GetMessageResourceRequest.builder() \
+ .message_id(message_id) \
+ .file_key(image_key) \
+ .type("image") \
+ .build()
+ response = self._client.im.v1.message_resource.get(request)
+ if response.success():
+ file_data = response.file
+ # GetMessageResourceRequest returns BytesIO, need to read bytes
+ if hasattr(file_data, 'read'):
+ file_data = file_data.read()
+ return file_data, response.file_name
+ else:
+ logger.error("Failed to download image: code={}, msg={}", response.code, response.msg)
+ return None, None
+ except Exception as e:
+ logger.error("Error downloading image {}: {}", image_key, e)
+ return None, None
+
+ def _download_file_sync(
+ self, message_id: str, file_key: str, resource_type: str = "file"
+ ) -> tuple[bytes | None, str | None]:
+ """Download a file/audio/media from a Feishu message by message_id and file_key."""
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+
+ # Feishu API only accepts 'image' or 'file' as type parameter
+ # Convert 'audio' to 'file' for API compatibility
+ if resource_type == "audio":
+ resource_type = "file"
+
+ try:
+ request = (
+ GetMessageResourceRequest.builder()
+ .message_id(message_id)
+ .file_key(file_key)
+ .type(resource_type)
+ .build()
+ )
+ response = self._client.im.v1.message_resource.get(request)
+ if response.success():
+ file_data = response.file
+ if hasattr(file_data, "read"):
+ file_data = file_data.read()
+ return file_data, response.file_name
+ else:
+ logger.error("Failed to download {}: code={}, msg={}", resource_type, response.code, response.msg)
+ return None, None
+ except Exception:
+ logger.exception("Error downloading {} {}", resource_type, file_key)
+ return None, None
+
+ async def _download_and_save_media(
+ self,
+ msg_type: str,
+ content_json: dict,
+ message_id: str | None = None
+ ) -> tuple[str | None, str]:
+ """
+ Download media from Feishu and save to local disk.
+
+ Returns:
+ (file_path, content_text) - file_path is None if download failed
+ """
+ loop = asyncio.get_running_loop()
+ media_dir = get_media_dir("feishu")
+
+ data, filename = None, None
+
+ if msg_type == "image":
+ image_key = content_json.get("image_key")
+ if image_key and message_id:
+ data, filename = await loop.run_in_executor(
+ None, self._download_image_sync, message_id, image_key
+ )
+ if not filename:
+ filename = f"{image_key[:16]}.jpg"
+
+ elif msg_type in ("audio", "file", "media"):
+ file_key = content_json.get("file_key")
+ if file_key and message_id:
+ data, filename = await loop.run_in_executor(
+ None, self._download_file_sync, message_id, file_key, msg_type
+ )
+ if not filename:
+ filename = file_key[:16]
+ if msg_type == "audio" and not filename.endswith(".opus"):
+ filename = f"{filename}.opus"
+
+ if data and filename:
+ file_path = media_dir / filename
+ file_path.write_bytes(data)
+ logger.debug("Downloaded {} to {}", msg_type, file_path)
+ return str(file_path), f"[{msg_type}: {filename}]"
+
+ return None, f"[{msg_type}: download failed]"
+
+ def _send_message_sync(self, receive_id_type: str, receive_id: str, msg_type: str, content: str) -> bool:
+ """Send a single message (text/image/file/interactive) synchronously."""
+ from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody
+ try:
+ request = CreateMessageRequest.builder() \
+ .receive_id_type(receive_id_type) \
+ .request_body(
+ CreateMessageRequestBody.builder()
+ .receive_id(receive_id)
+ .msg_type(msg_type)
+ .content(content)
+ .build()
+ ).build()
+ response = self._client.im.v1.message.create(request)
+ if not response.success():
+ logger.error(
+ "Failed to send Feishu {} message: code={}, msg={}, log_id={}",
+ msg_type, response.code, response.msg, response.get_log_id()
+ )
+ return False
+ logger.debug("Feishu {} message sent to {}", msg_type, receive_id)
+ return True
+ except Exception as e:
+ logger.error("Error sending Feishu {} message: {}", msg_type, e)
+ return False
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Feishu, including media (images/files) if present."""
+ if not self._client:
+ logger.warning("Feishu client not initialized")
+ return
+
+ try:
+ receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
+ loop = asyncio.get_running_loop()
+
+ for file_path in msg.media:
+ if not os.path.isfile(file_path):
+ logger.warning("Media file not found: {}", file_path)
+ continue
+ ext = os.path.splitext(file_path)[1].lower()
+ if ext in self._IMAGE_EXTS:
+ key = await loop.run_in_executor(None, self._upload_image_sync, file_path)
+ if key:
+ await loop.run_in_executor(
+ None, self._send_message_sync,
+ receive_id_type, msg.chat_id, "image", json.dumps({"image_key": key}, ensure_ascii=False),
+ )
+ else:
+ key = await loop.run_in_executor(None, self._upload_file_sync, file_path)
+ if key:
+ # Use msg_type "media" for audio/video so users can play inline;
+ # "file" for everything else (documents, archives, etc.)
+ if ext in self._AUDIO_EXTS or ext in self._VIDEO_EXTS:
+ media_type = "media"
+ else:
+ media_type = "file"
+ await loop.run_in_executor(
+ None, self._send_message_sync,
+ receive_id_type, msg.chat_id, media_type, json.dumps({"file_key": key}, ensure_ascii=False),
+ )
+
+ if msg.content and msg.content.strip():
+ fmt = self._detect_msg_format(msg.content)
+
+ if fmt == "text":
+ # Short plain text – send as simple text message
+ text_body = json.dumps({"text": msg.content.strip()}, ensure_ascii=False)
+ await loop.run_in_executor(
+ None, self._send_message_sync,
+ receive_id_type, msg.chat_id, "text", text_body,
+ )
+
+ elif fmt == "post":
+ # Medium content with links – send as rich-text post
+ post_body = self._markdown_to_post(msg.content)
+ await loop.run_in_executor(
+ None, self._send_message_sync,
+ receive_id_type, msg.chat_id, "post", post_body,
+ )
+
+ else:
+ # Complex / long content – send as interactive card
+ elements = self._build_card_elements(msg.content)
+ for chunk in self._split_elements_by_table_limit(elements):
+ card = {"config": {"wide_screen_mode": True}, "elements": chunk}
+ await loop.run_in_executor(
+ None, self._send_message_sync,
+ receive_id_type, msg.chat_id, "interactive", json.dumps(card, ensure_ascii=False),
+ )
+
+ except Exception as e:
+ logger.error("Error sending Feishu message: {}", e)
+
+ def _on_message_sync(self, data: Any) -> None:
+ """
+ Sync handler for incoming messages (called from WebSocket thread).
+ Schedules async handling in the main event loop.
+ """
+ if self._loop and self._loop.is_running():
+ asyncio.run_coroutine_threadsafe(self._on_message(data), self._loop)
+
+ async def _on_message(self, data: Any) -> None:
+ """Handle incoming message from Feishu."""
+ try:
+ event = data.event
+ message = event.message
+ sender = event.sender
+
+ # Deduplication check
+ message_id = message.message_id
+ if message_id in self._processed_message_ids:
+ return
+ self._processed_message_ids[message_id] = None
+
+ # Trim cache
+ while len(self._processed_message_ids) > 1000:
+ self._processed_message_ids.popitem(last=False)
+
+ # Skip bot messages
+ if sender.sender_type == "bot":
+ return
+
+ sender_id = sender.sender_id.open_id if sender.sender_id else "unknown"
+ chat_id = message.chat_id
+ chat_type = message.chat_type
+ msg_type = message.message_type
+
+ if chat_type == "group" and not self._is_group_message_for_bot(message):
+ logger.debug("Feishu: skipping group message (not mentioned)")
+ return
+
+ # Add reaction
+ await self._add_reaction(message_id, self.config.react_emoji)
+
+ # Parse content
+ content_parts = []
+ media_paths = []
+
+ try:
+ content_json = json.loads(message.content) if message.content else {}
+ except json.JSONDecodeError:
+ content_json = {}
+
+ if msg_type == "text":
+ text = content_json.get("text", "")
+ if text:
+ content_parts.append(text)
+
+ elif msg_type == "post":
+ text, image_keys = _extract_post_content(content_json)
+ if text:
+ content_parts.append(text)
+ # Download images embedded in post
+ for img_key in image_keys:
+ file_path, content_text = await self._download_and_save_media(
+ "image", {"image_key": img_key}, message_id
+ )
+ if file_path:
+ media_paths.append(file_path)
+ content_parts.append(content_text)
+
+ elif msg_type in ("image", "audio", "file", "media"):
+ file_path, content_text = await self._download_and_save_media(msg_type, content_json, message_id)
+ if file_path:
+ media_paths.append(file_path)
+
+ if msg_type == "audio" and file_path:
+ transcription = await self.transcribe_audio(file_path)
+ if transcription:
+ content_text = f"[transcription: {transcription}]"
+
+ content_parts.append(content_text)
+
+ elif msg_type in ("share_chat", "share_user", "interactive", "share_calendar_event", "system", "merge_forward"):
+ # Handle share cards and interactive messages
+ text = _extract_share_card_content(content_json, msg_type)
+ if text:
+ content_parts.append(text)
+
+ else:
+ content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"))
+
+ content = "\n".join(content_parts) if content_parts else ""
+
+ if not content and not media_paths:
+ return
+
+ # Forward to message bus
+ reply_to = chat_id if chat_type == "group" else sender_id
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=reply_to,
+ content=content,
+ media=media_paths,
+ metadata={
+ "message_id": message_id,
+ "chat_type": chat_type,
+ "msg_type": msg_type,
+ }
+ )
+
+ except Exception as e:
+ logger.error("Error processing Feishu message: {}", e)
+
+ def _on_reaction_created(self, data: Any) -> None:
+ """Ignore reaction events so they do not generate SDK noise."""
+ pass
+
+ def _on_message_read(self, data: Any) -> None:
+ """Ignore read events so they do not generate SDK noise."""
+ pass
+
+ def _on_bot_p2p_chat_entered(self, data: Any) -> None:
+ """Ignore p2p-enter events when a user opens a bot chat."""
+ logger.debug("Bot entered p2p chat (user opened chat window)")
+ pass
diff --git a/deeptutor/tutorbot/channels/manager.py b/deeptutor/tutorbot/channels/manager.py
new file mode 100644
index 000000000..230b33f6f
--- /dev/null
+++ b/deeptutor/tutorbot/channels/manager.py
@@ -0,0 +1,153 @@
+"""Channel manager for coordinating chat channels."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from loguru import logger
+
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.schema import ChannelsConfig
+
+
+class ChannelManager:
+ """
+ Manages chat channels and coordinates message routing.
+
+ Responsibilities:
+ - Initialize enabled channels (Telegram, WhatsApp, etc.)
+ - Start/stop channels
+ - Route outbound messages
+ """
+
+ def __init__(
+ self,
+ channels_config: ChannelsConfig,
+ bus: MessageBus,
+ groq_api_key: str = "",
+ ):
+ self.channels_config = channels_config
+ self.bus = bus
+ self._groq_api_key = groq_api_key
+ self.channels: dict[str, BaseChannel] = {}
+ self._dispatch_task: asyncio.Task | None = None
+
+ self._init_channels()
+
+ def _init_channels(self) -> None:
+ """Initialize channels discovered via pkgutil scan + entry_points plugins."""
+ from deeptutor.tutorbot.channels.registry import discover_all
+
+ for name, cls in discover_all().items():
+ section = getattr(self.channels_config, name, None)
+ if section is None:
+ continue
+ enabled = (
+ section.get("enabled", False)
+ if isinstance(section, dict)
+ else getattr(section, "enabled", False)
+ )
+ if not enabled:
+ continue
+ try:
+ channel = cls(section, self.bus)
+ channel.transcription_api_key = self._groq_api_key
+ self.channels[name] = channel
+ logger.info("{} channel enabled", cls.display_name)
+ except Exception as e:
+ logger.warning("{} channel not available: {}", name, e)
+
+ self._validate_allow_from()
+
+ def _validate_allow_from(self) -> None:
+ for name, ch in self.channels.items():
+ if getattr(ch.config, "allow_from", None) == []:
+ raise SystemExit(
+ f'Error: "{name}" has empty allowFrom (denies all). '
+ f'Set ["*"] to allow everyone, or add specific user IDs.'
+ )
+
+ async def _start_channel(self, name: str, channel: BaseChannel) -> None:
+ try:
+ await channel.start()
+ except Exception as e:
+ logger.error("Failed to start channel {}: {}", name, e)
+
+ async def start_all(self) -> None:
+ """Start all channels and the outbound dispatcher."""
+ if not self.channels:
+ logger.warning("No channels enabled")
+ return
+
+ self._dispatch_task = asyncio.create_task(self._dispatch_outbound())
+
+ tasks = []
+ for name, channel in self.channels.items():
+ logger.info("Starting {} channel...", name)
+ tasks.append(asyncio.create_task(self._start_channel(name, channel)))
+
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+ async def stop_all(self) -> None:
+ """Stop all channels and the dispatcher."""
+ logger.info("Stopping all channels...")
+
+ if self._dispatch_task:
+ self._dispatch_task.cancel()
+ try:
+ await self._dispatch_task
+ except asyncio.CancelledError:
+ pass
+
+ for name, channel in self.channels.items():
+ try:
+ await channel.stop()
+ logger.info("Stopped {} channel", name)
+ except Exception as e:
+ logger.error("Error stopping {}: {}", name, e)
+
+ async def _dispatch_outbound(self) -> None:
+ """Dispatch outbound messages to the appropriate channel."""
+ logger.info("Outbound dispatcher started")
+
+ while True:
+ try:
+ msg = await asyncio.wait_for(
+ self.bus.consume_outbound(),
+ timeout=1.0
+ )
+
+ if msg.metadata.get("_progress"):
+ if msg.metadata.get("_tool_hint") and not self.channels_config.send_tool_hints:
+ continue
+ if not msg.metadata.get("_tool_hint") and not self.channels_config.send_progress:
+ continue
+
+ channel = self.channels.get(msg.channel)
+ if channel:
+ try:
+ await channel.send(msg)
+ except Exception as e:
+ logger.error("Error sending to {}: {}", msg.channel, e)
+ else:
+ logger.warning("Unknown channel: {}", msg.channel)
+
+ except asyncio.TimeoutError:
+ continue
+ except asyncio.CancelledError:
+ break
+
+ def get_channel(self, name: str) -> BaseChannel | None:
+ return self.channels.get(name)
+
+ def get_status(self) -> dict[str, Any]:
+ return {
+ name: {"enabled": True, "running": channel.is_running}
+ for name, channel in self.channels.items()
+ }
+
+ @property
+ def enabled_channels(self) -> list[str]:
+ return list(self.channels.keys())
diff --git a/deeptutor/tutorbot/channels/matrix.py b/deeptutor/tutorbot/channels/matrix.py
new file mode 100644
index 000000000..9ddc846e8
--- /dev/null
+++ b/deeptutor/tutorbot/channels/matrix.py
@@ -0,0 +1,739 @@
+"""Matrix (Element) channel — inbound sync + outbound message/media delivery."""
+
+import asyncio
+import logging
+import mimetypes
+from pathlib import Path
+from typing import Any, Literal, TypeAlias
+
+from loguru import logger
+from pydantic import Field
+
+try:
+ import nh3
+ from mistune import create_markdown
+ from nio import (
+ AsyncClient,
+ AsyncClientConfig,
+ ContentRepositoryConfigError,
+ DownloadError,
+ InviteEvent,
+ JoinError,
+ MatrixRoom,
+ MemoryDownloadResponse,
+ RoomEncryptedMedia,
+ RoomMessage,
+ RoomMessageMedia,
+ RoomMessageText,
+ RoomSendError,
+ RoomTypingError,
+ SyncError,
+ UploadError,
+ )
+ from nio.crypto.attachments import decrypt_attachment
+ from nio.exceptions import EncryptionError
+except ImportError as e:
+ raise ImportError(
+ "Matrix dependencies not installed. Run: pip install deeptutor[matrix]"
+ ) from e
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.paths import get_data_dir, get_media_dir
+from deeptutor.tutorbot.config.schema import Base
+from deeptutor.tutorbot.utils.helpers import safe_filename
+
+TYPING_NOTICE_TIMEOUT_MS = 30_000
+# Must stay below TYPING_NOTICE_TIMEOUT_MS so the indicator doesn't expire mid-processing.
+TYPING_KEEPALIVE_INTERVAL_MS = 20_000
+MATRIX_HTML_FORMAT = "org.matrix.custom.html"
+_ATTACH_MARKER = "[attachment: {}]"
+_ATTACH_TOO_LARGE = "[attachment: {} - too large]"
+_ATTACH_FAILED = "[attachment: {} - download failed]"
+_ATTACH_UPLOAD_FAILED = "[attachment: {} - upload failed]"
+_DEFAULT_ATTACH_NAME = "attachment"
+_MSGTYPE_MAP = {"m.image": "image", "m.audio": "audio", "m.video": "video", "m.file": "file"}
+
+MATRIX_MEDIA_EVENT_FILTER = (RoomMessageMedia, RoomEncryptedMedia)
+MatrixMediaEvent: TypeAlias = RoomMessageMedia | RoomEncryptedMedia
+
+MATRIX_MARKDOWN = create_markdown(
+ escape=True,
+ plugins=["table", "strikethrough", "url", "superscript", "subscript"],
+)
+
+MATRIX_ALLOWED_HTML_TAGS = {
+ "p", "a", "strong", "em", "del", "code", "pre", "blockquote",
+ "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6",
+ "hr", "br", "table", "thead", "tbody", "tr", "th", "td",
+ "caption", "sup", "sub", "img",
+}
+MATRIX_ALLOWED_HTML_ATTRIBUTES: dict[str, set[str]] = {
+ "a": {"href"}, "code": {"class"}, "ol": {"start"},
+ "img": {"src", "alt", "title", "width", "height"},
+}
+MATRIX_ALLOWED_URL_SCHEMES = {"https", "http", "matrix", "mailto", "mxc"}
+
+
+def _filter_matrix_html_attribute(tag: str, attr: str, value: str) -> str | None:
+ """Filter attribute values to a safe Matrix-compatible subset."""
+ if tag == "a" and attr == "href":
+ return value if value.lower().startswith(("https://", "http://", "matrix:", "mailto:")) else None
+ if tag == "img" and attr == "src":
+ return value if value.lower().startswith("mxc://") else None
+ if tag == "code" and attr == "class":
+ classes = [c for c in value.split() if c.startswith("language-") and not c.startswith("language-_")]
+ return " ".join(classes) if classes else None
+ return value
+
+
+MATRIX_HTML_CLEANER = nh3.Cleaner(
+ tags=MATRIX_ALLOWED_HTML_TAGS,
+ attributes=MATRIX_ALLOWED_HTML_ATTRIBUTES,
+ attribute_filter=_filter_matrix_html_attribute,
+ url_schemes=MATRIX_ALLOWED_URL_SCHEMES,
+ strip_comments=True,
+ link_rel="noopener noreferrer",
+)
+
+
+def _render_markdown_html(text: str) -> str | None:
+ """Render markdown to sanitized HTML; returns None for plain text."""
+ try:
+ formatted = MATRIX_HTML_CLEANER.clean(MATRIX_MARKDOWN(text)).strip()
+ except Exception:
+ return None
+ if not formatted:
+ return None
+ # Skip formatted_body for plain <p>text</p> to keep payload minimal.
+ if formatted.startswith("<p>") and formatted.endswith("</p>"):
+ inner = formatted[3:-4]
+ if "<" not in inner and ">" not in inner:
+ return None
+ return formatted
+
+
+def _build_matrix_text_content(text: str) -> dict[str, object]:
+ """Build Matrix m.text payload with optional HTML formatted_body."""
+ content: dict[str, object] = {"msgtype": "m.text", "body": text, "m.mentions": {}}
+ if html := _render_markdown_html(text):
+ content["format"] = MATRIX_HTML_FORMAT
+ content["formatted_body"] = html
+ return content
+
+
+class _NioLoguruHandler(logging.Handler):
+ """Route matrix-nio stdlib logs into Loguru."""
+
+ def emit(self, record: logging.LogRecord) -> None:
+ try:
+ level = logger.level(record.levelname).name
+ except ValueError:
+ level = record.levelno
+ frame, depth = logging.currentframe(), 2
+ while frame and frame.f_code.co_filename == logging.__file__:
+ frame, depth = frame.f_back, depth + 1
+ logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
+
+
+def _configure_nio_logging_bridge() -> None:
+ """Bridge matrix-nio logs to Loguru (idempotent)."""
+ nio_logger = logging.getLogger("nio")
+ if not any(isinstance(h, _NioLoguruHandler) for h in nio_logger.handlers):
+ nio_logger.handlers = [_NioLoguruHandler()]
+ nio_logger.propagate = False
+
+
+class MatrixConfig(Base):
+ """Matrix (Element) channel configuration."""
+
+ enabled: bool = False
+ homeserver: str = "https://matrix.org"
+ access_token: str = ""
+ user_id: str = ""
+ device_id: str = ""
+ e2ee_enabled: bool = True
+ sync_stop_grace_seconds: int = 2
+ max_media_bytes: int = 20 * 1024 * 1024
+ allow_from: list[str] = Field(default_factory=list)
+ group_policy: Literal["open", "mention", "allowlist"] = "open"
+ group_allow_from: list[str] = Field(default_factory=list)
+ allow_room_mentions: bool = False
+
+
+class MatrixChannel(BaseChannel):
+ """Matrix (Element) channel using long-polling sync."""
+
+ name = "matrix"
+ display_name = "Matrix"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return MatrixConfig().model_dump(by_alias=True)
+
+ def __init__(
+ self,
+ config: Any,
+ bus: MessageBus,
+ *,
+ restrict_to_workspace: bool = False,
+ workspace: str | Path | None = None,
+ ):
+ if isinstance(config, dict):
+ config = MatrixConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.client: AsyncClient | None = None
+ self._sync_task: asyncio.Task | None = None
+ self._typing_tasks: dict[str, asyncio.Task] = {}
+ self._restrict_to_workspace = bool(restrict_to_workspace)
+ self._workspace = (
+ Path(workspace).expanduser().resolve(strict=False) if workspace is not None else None
+ )
+ self._server_upload_limit_bytes: int | None = None
+ self._server_upload_limit_checked = False
+
+ async def start(self) -> None:
+ """Start Matrix client and begin sync loop."""
+ self._running = True
+ _configure_nio_logging_bridge()
+
+ store_path = get_data_dir() / "matrix-store"
+ store_path.mkdir(parents=True, exist_ok=True)
+
+ self.client = AsyncClient(
+ homeserver=self.config.homeserver, user=self.config.user_id,
+ store_path=store_path,
+ config=AsyncClientConfig(store_sync_tokens=True, encryption_enabled=self.config.e2ee_enabled),
+ )
+ self.client.user_id = self.config.user_id
+ self.client.access_token = self.config.access_token
+ self.client.device_id = self.config.device_id
+
+ self._register_event_callbacks()
+ self._register_response_callbacks()
+
+ if not self.config.e2ee_enabled:
+ logger.warning("Matrix E2EE disabled; encrypted rooms may be undecryptable.")
+
+ if self.config.device_id:
+ try:
+ self.client.load_store()
+ except Exception:
+ logger.exception("Matrix store load failed; restart may replay recent messages.")
+ else:
+ logger.warning("Matrix device_id empty; restart may replay recent messages.")
+
+ self._sync_task = asyncio.create_task(self._sync_loop())
+
+ async def stop(self) -> None:
+ """Stop the Matrix channel with graceful sync shutdown."""
+ self._running = False
+ for room_id in list(self._typing_tasks):
+ await self._stop_typing_keepalive(room_id, clear_typing=False)
+ if self.client:
+ self.client.stop_sync_forever()
+ if self._sync_task:
+ try:
+ await asyncio.wait_for(asyncio.shield(self._sync_task),
+ timeout=self.config.sync_stop_grace_seconds)
+ except (asyncio.TimeoutError, asyncio.CancelledError):
+ self._sync_task.cancel()
+ try:
+ await self._sync_task
+ except asyncio.CancelledError:
+ pass
+ if self.client:
+ await self.client.close()
+
+ def _is_workspace_path_allowed(self, path: Path) -> bool:
+ """Check path is inside workspace (when restriction enabled)."""
+ if not self._restrict_to_workspace or not self._workspace:
+ return True
+ try:
+ path.resolve(strict=False).relative_to(self._workspace)
+ return True
+ except ValueError:
+ return False
+
+ def _collect_outbound_media_candidates(self, media: list[str]) -> list[Path]:
+ """Deduplicate and resolve outbound attachment paths."""
+ seen: set[str] = set()
+ candidates: list[Path] = []
+ for raw in media:
+ if not isinstance(raw, str) or not raw.strip():
+ continue
+ path = Path(raw.strip()).expanduser()
+ try:
+ key = str(path.resolve(strict=False))
+ except OSError:
+ key = str(path)
+ if key not in seen:
+ seen.add(key)
+ candidates.append(path)
+ return candidates
+
+ @staticmethod
+ def _build_outbound_attachment_content(
+ *, filename: str, mime: str, size_bytes: int,
+ mxc_url: str, encryption_info: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Build Matrix content payload for an uploaded file/image/audio/video."""
+ prefix = mime.split("/")[0]
+ msgtype = {"image": "m.image", "audio": "m.audio", "video": "m.video"}.get(prefix, "m.file")
+ content: dict[str, Any] = {
+ "msgtype": msgtype, "body": filename, "filename": filename,
+ "info": {"mimetype": mime, "size": size_bytes}, "m.mentions": {},
+ }
+ if encryption_info:
+ content["file"] = {**encryption_info, "url": mxc_url}
+ else:
+ content["url"] = mxc_url
+ return content
+
+ def _is_encrypted_room(self, room_id: str) -> bool:
+ if not self.client:
+ return False
+ room = getattr(self.client, "rooms", {}).get(room_id)
+ return bool(getattr(room, "encrypted", False))
+
+ async def _send_room_content(self, room_id: str, content: dict[str, Any]) -> None:
+ """Send m.room.message with E2EE options."""
+ if not self.client:
+ return
+ kwargs: dict[str, Any] = {"room_id": room_id, "message_type": "m.room.message", "content": content}
+ if self.config.e2ee_enabled:
+ kwargs["ignore_unverified_devices"] = True
+ await self.client.room_send(**kwargs)
+
+ async def _resolve_server_upload_limit_bytes(self) -> int | None:
+ """Query homeserver upload limit once per channel lifecycle."""
+ if self._server_upload_limit_checked:
+ return self._server_upload_limit_bytes
+ self._server_upload_limit_checked = True
+ if not self.client:
+ return None
+ try:
+ response = await self.client.content_repository_config()
+ except Exception:
+ return None
+ upload_size = getattr(response, "upload_size", None)
+ if isinstance(upload_size, int) and upload_size > 0:
+ self._server_upload_limit_bytes = upload_size
+ return upload_size
+ return None
+
+ async def _effective_media_limit_bytes(self) -> int:
+ """min(local config, server advertised) — 0 blocks all uploads."""
+ local_limit = max(int(self.config.max_media_bytes), 0)
+ server_limit = await self._resolve_server_upload_limit_bytes()
+ if server_limit is None:
+ return local_limit
+ return min(local_limit, server_limit) if local_limit else 0
+
+ async def _upload_and_send_attachment(
+ self, room_id: str, path: Path, limit_bytes: int,
+ relates_to: dict[str, Any] | None = None,
+ ) -> str | None:
+ """Upload one local file to Matrix and send it as a media message. Returns failure marker or None."""
+ if not self.client:
+ return _ATTACH_UPLOAD_FAILED.format(path.name or _DEFAULT_ATTACH_NAME)
+
+ resolved = path.expanduser().resolve(strict=False)
+ filename = safe_filename(resolved.name) or _DEFAULT_ATTACH_NAME
+ fail = _ATTACH_UPLOAD_FAILED.format(filename)
+
+ if not resolved.is_file() or not self._is_workspace_path_allowed(resolved):
+ return fail
+ try:
+ size_bytes = resolved.stat().st_size
+ except OSError:
+ return fail
+ if limit_bytes <= 0 or size_bytes > limit_bytes:
+ return _ATTACH_TOO_LARGE.format(filename)
+
+ mime = mimetypes.guess_type(filename, strict=False)[0] or "application/octet-stream"
+ try:
+ with resolved.open("rb") as f:
+ upload_result = await self.client.upload(
+ f, content_type=mime, filename=filename,
+ encrypt=self.config.e2ee_enabled and self._is_encrypted_room(room_id),
+ filesize=size_bytes,
+ )
+ except Exception:
+ return fail
+
+ upload_response = upload_result[0] if isinstance(upload_result, tuple) else upload_result
+ encryption_info = upload_result[1] if isinstance(upload_result, tuple) and isinstance(upload_result[1], dict) else None
+ if isinstance(upload_response, UploadError):
+ return fail
+ mxc_url = getattr(upload_response, "content_uri", None)
+ if not isinstance(mxc_url, str) or not mxc_url.startswith("mxc://"):
+ return fail
+
+ content = self._build_outbound_attachment_content(
+ filename=filename, mime=mime, size_bytes=size_bytes,
+ mxc_url=mxc_url, encryption_info=encryption_info,
+ )
+ if relates_to:
+ content["m.relates_to"] = relates_to
+ try:
+ await self._send_room_content(room_id, content)
+ except Exception:
+ return fail
+ return None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send outbound content; clear typing for non-progress messages."""
+ if not self.client:
+ return
+ text = msg.content or ""
+ candidates = self._collect_outbound_media_candidates(msg.media)
+ relates_to = self._build_thread_relates_to(msg.metadata)
+ is_progress = bool((msg.metadata or {}).get("_progress"))
+ try:
+ failures: list[str] = []
+ if candidates:
+ limit_bytes = await self._effective_media_limit_bytes()
+ for path in candidates:
+ if fail := await self._upload_and_send_attachment(
+ room_id=msg.chat_id,
+ path=path,
+ limit_bytes=limit_bytes,
+ relates_to=relates_to,
+ ):
+ failures.append(fail)
+ if failures:
+ text = f"{text.rstrip()}\n{chr(10).join(failures)}" if text.strip() else "\n".join(failures)
+ if text or not candidates:
+ content = _build_matrix_text_content(text)
+ if relates_to:
+ content["m.relates_to"] = relates_to
+ await self._send_room_content(msg.chat_id, content)
+ finally:
+ if not is_progress:
+ await self._stop_typing_keepalive(msg.chat_id, clear_typing=True)
+
+ def _register_event_callbacks(self) -> None:
+ self.client.add_event_callback(self._on_message, RoomMessageText)
+ self.client.add_event_callback(self._on_media_message, MATRIX_MEDIA_EVENT_FILTER)
+ self.client.add_event_callback(self._on_room_invite, InviteEvent)
+
+ def _register_response_callbacks(self) -> None:
+ self.client.add_response_callback(self._on_sync_error, SyncError)
+ self.client.add_response_callback(self._on_join_error, JoinError)
+ self.client.add_response_callback(self._on_send_error, RoomSendError)
+
+ def _log_response_error(self, label: str, response: Any) -> None:
+ """Log Matrix response errors — auth errors at ERROR level, rest at WARNING."""
+ code = getattr(response, "status_code", None)
+ is_auth = code in {"M_UNKNOWN_TOKEN", "M_FORBIDDEN", "M_UNAUTHORIZED"}
+ is_fatal = is_auth or getattr(response, "soft_logout", False)
+ (logger.error if is_fatal else logger.warning)("Matrix {} failed: {}", label, response)
+
+ async def _on_sync_error(self, response: SyncError) -> None:
+ self._log_response_error("sync", response)
+
+ async def _on_join_error(self, response: JoinError) -> None:
+ self._log_response_error("join", response)
+
+ async def _on_send_error(self, response: RoomSendError) -> None:
+ self._log_response_error("send", response)
+
+ async def _set_typing(self, room_id: str, typing: bool) -> None:
+ """Best-effort typing indicator update."""
+ if not self.client:
+ return
+ try:
+ response = await self.client.room_typing(room_id=room_id, typing_state=typing,
+ timeout=TYPING_NOTICE_TIMEOUT_MS)
+ if isinstance(response, RoomTypingError):
+ logger.debug("Matrix typing failed for {}: {}", room_id, response)
+ except Exception:
+ pass
+
+ async def _start_typing_keepalive(self, room_id: str) -> None:
+ """Start periodic typing refresh (spec-recommended keepalive)."""
+ await self._stop_typing_keepalive(room_id, clear_typing=False)
+ await self._set_typing(room_id, True)
+ if not self._running:
+ return
+
+ async def loop() -> None:
+ try:
+ while self._running:
+ await asyncio.sleep(TYPING_KEEPALIVE_INTERVAL_MS / 1000)
+ await self._set_typing(room_id, True)
+ except asyncio.CancelledError:
+ pass
+
+ self._typing_tasks[room_id] = asyncio.create_task(loop())
+
+ async def _stop_typing_keepalive(self, room_id: str, *, clear_typing: bool) -> None:
+ if task := self._typing_tasks.pop(room_id, None):
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ if clear_typing:
+ await self._set_typing(room_id, False)
+
+ async def _sync_loop(self) -> None:
+ while self._running:
+ try:
+ await self.client.sync_forever(timeout=30000, full_state=True)
+ except asyncio.CancelledError:
+ break
+ except Exception:
+ await asyncio.sleep(2)
+
+ async def _on_room_invite(self, room: MatrixRoom, event: InviteEvent) -> None:
+ if self.is_allowed(event.sender):
+ await self.client.join(room.room_id)
+
+ def _is_direct_room(self, room: MatrixRoom) -> bool:
+ count = getattr(room, "member_count", None)
+ return isinstance(count, int) and count <= 2
+
+ def _is_bot_mentioned(self, event: RoomMessage) -> bool:
+ """Check m.mentions payload for bot mention."""
+ source = getattr(event, "source", None)
+ if not isinstance(source, dict):
+ return False
+ mentions = (source.get("content") or {}).get("m.mentions")
+ if not isinstance(mentions, dict):
+ return False
+ user_ids = mentions.get("user_ids")
+ if isinstance(user_ids, list) and self.config.user_id in user_ids:
+ return True
+ return bool(self.config.allow_room_mentions and mentions.get("room") is True)
+
+ def _should_process_message(self, room: MatrixRoom, event: RoomMessage) -> bool:
+ """Apply sender and room policy checks."""
+ if not self.is_allowed(event.sender):
+ return False
+ if self._is_direct_room(room):
+ return True
+ policy = self.config.group_policy
+ if policy == "open":
+ return True
+ if policy == "allowlist":
+ return room.room_id in (self.config.group_allow_from or [])
+ if policy == "mention":
+ return self._is_bot_mentioned(event)
+ return False
+
+ def _media_dir(self) -> Path:
+ return get_media_dir("matrix")
+
+ @staticmethod
+ def _event_source_content(event: RoomMessage) -> dict[str, Any]:
+ source = getattr(event, "source", None)
+ if not isinstance(source, dict):
+ return {}
+ content = source.get("content")
+ return content if isinstance(content, dict) else {}
+
+ def _event_thread_root_id(self, event: RoomMessage) -> str | None:
+ relates_to = self._event_source_content(event).get("m.relates_to")
+ if not isinstance(relates_to, dict) or relates_to.get("rel_type") != "m.thread":
+ return None
+ root_id = relates_to.get("event_id")
+ return root_id if isinstance(root_id, str) and root_id else None
+
+ def _thread_metadata(self, event: RoomMessage) -> dict[str, str] | None:
+ if not (root_id := self._event_thread_root_id(event)):
+ return None
+ meta: dict[str, str] = {"thread_root_event_id": root_id}
+ if isinstance(reply_to := getattr(event, "event_id", None), str) and reply_to:
+ meta["thread_reply_to_event_id"] = reply_to
+ return meta
+
+ @staticmethod
+ def _build_thread_relates_to(metadata: dict[str, Any] | None) -> dict[str, Any] | None:
+ if not metadata:
+ return None
+ root_id = metadata.get("thread_root_event_id")
+ if not isinstance(root_id, str) or not root_id:
+ return None
+ reply_to = metadata.get("thread_reply_to_event_id") or metadata.get("event_id")
+ if not isinstance(reply_to, str) or not reply_to:
+ return None
+ return {"rel_type": "m.thread", "event_id": root_id,
+ "m.in_reply_to": {"event_id": reply_to}, "is_falling_back": True}
+
+ def _event_attachment_type(self, event: MatrixMediaEvent) -> str:
+ msgtype = self._event_source_content(event).get("msgtype")
+ return _MSGTYPE_MAP.get(msgtype, "file")
+
+ @staticmethod
+ def _is_encrypted_media_event(event: MatrixMediaEvent) -> bool:
+ return (isinstance(getattr(event, "key", None), dict)
+ and isinstance(getattr(event, "hashes", None), dict)
+ and isinstance(getattr(event, "iv", None), str))
+
+ def _event_declared_size_bytes(self, event: MatrixMediaEvent) -> int | None:
+ info = self._event_source_content(event).get("info")
+ size = info.get("size") if isinstance(info, dict) else None
+ return size if isinstance(size, int) and size >= 0 else None
+
+ def _event_mime(self, event: MatrixMediaEvent) -> str | None:
+ info = self._event_source_content(event).get("info")
+ if isinstance(info, dict) and isinstance(m := info.get("mimetype"), str) and m:
+ return m
+ m = getattr(event, "mimetype", None)
+ return m if isinstance(m, str) and m else None
+
+ def _event_filename(self, event: MatrixMediaEvent, attachment_type: str) -> str:
+ body = getattr(event, "body", None)
+ if isinstance(body, str) and body.strip():
+ if candidate := safe_filename(Path(body).name):
+ return candidate
+ return _DEFAULT_ATTACH_NAME if attachment_type == "file" else attachment_type
+
+ def _build_attachment_path(self, event: MatrixMediaEvent, attachment_type: str,
+ filename: str, mime: str | None) -> Path:
+ safe_name = safe_filename(Path(filename).name) or _DEFAULT_ATTACH_NAME
+ suffix = Path(safe_name).suffix
+ if not suffix and mime:
+ if guessed := mimetypes.guess_extension(mime, strict=False):
+ safe_name, suffix = f"{safe_name}{guessed}", guessed
+ stem = (Path(safe_name).stem or attachment_type)[:72]
+ suffix = suffix[:16]
+ event_id = safe_filename(str(getattr(event, "event_id", "") or "evt").lstrip("$"))
+ event_prefix = (event_id[:24] or "evt").strip("_")
+ return self._media_dir() / f"{event_prefix}_{stem}{suffix}"
+
+ async def _download_media_bytes(self, mxc_url: str) -> bytes | None:
+ if not self.client:
+ return None
+ response = await self.client.download(mxc=mxc_url)
+ if isinstance(response, DownloadError):
+ logger.warning("Matrix download failed for {}: {}", mxc_url, response)
+ return None
+ body = getattr(response, "body", None)
+ if isinstance(body, (bytes, bytearray)):
+ return bytes(body)
+ if isinstance(response, MemoryDownloadResponse):
+ return bytes(response.body)
+ if isinstance(body, (str, Path)):
+ path = Path(body)
+ if path.is_file():
+ try:
+ return path.read_bytes()
+ except OSError:
+ return None
+ return None
+
+ def _decrypt_media_bytes(self, event: MatrixMediaEvent, ciphertext: bytes) -> bytes | None:
+ key_obj, hashes, iv = getattr(event, "key", None), getattr(event, "hashes", None), getattr(event, "iv", None)
+ key = key_obj.get("k") if isinstance(key_obj, dict) else None
+ sha256 = hashes.get("sha256") if isinstance(hashes, dict) else None
+ if not all(isinstance(v, str) for v in (key, sha256, iv)):
+ return None
+ try:
+ return decrypt_attachment(ciphertext, key, sha256, iv)
+ except (EncryptionError, ValueError, TypeError):
+ logger.warning("Matrix decrypt failed for event {}", getattr(event, "event_id", ""))
+ return None
+
+ async def _fetch_media_attachment(
+ self, room: MatrixRoom, event: MatrixMediaEvent,
+ ) -> tuple[dict[str, Any] | None, str]:
+ """Download, decrypt if needed, and persist a Matrix attachment."""
+ atype = self._event_attachment_type(event)
+ mime = self._event_mime(event)
+ filename = self._event_filename(event, atype)
+ mxc_url = getattr(event, "url", None)
+ fail = _ATTACH_FAILED.format(filename)
+
+ if not isinstance(mxc_url, str) or not mxc_url.startswith("mxc://"):
+ return None, fail
+
+ limit_bytes = await self._effective_media_limit_bytes()
+ declared = self._event_declared_size_bytes(event)
+ if declared is not None and declared > limit_bytes:
+ return None, _ATTACH_TOO_LARGE.format(filename)
+
+ downloaded = await self._download_media_bytes(mxc_url)
+ if downloaded is None:
+ return None, fail
+
+ encrypted = self._is_encrypted_media_event(event)
+ data = downloaded
+ if encrypted:
+ if (data := self._decrypt_media_bytes(event, downloaded)) is None:
+ return None, fail
+
+ if len(data) > limit_bytes:
+ return None, _ATTACH_TOO_LARGE.format(filename)
+
+ path = self._build_attachment_path(event, atype, filename, mime)
+ try:
+ path.write_bytes(data)
+ except OSError:
+ return None, fail
+
+ attachment = {
+ "type": atype, "mime": mime, "filename": filename,
+ "event_id": str(getattr(event, "event_id", "") or ""),
+ "encrypted": encrypted, "size_bytes": len(data),
+ "path": str(path), "mxc_url": mxc_url,
+ }
+ return attachment, _ATTACH_MARKER.format(path)
+
+ def _base_metadata(self, room: MatrixRoom, event: RoomMessage) -> dict[str, Any]:
+ """Build common metadata for text and media handlers."""
+ meta: dict[str, Any] = {"room": getattr(room, "display_name", room.room_id)}
+ if isinstance(eid := getattr(event, "event_id", None), str) and eid:
+ meta["event_id"] = eid
+ if thread := self._thread_metadata(event):
+ meta.update(thread)
+ return meta
+
+ async def _on_message(self, room: MatrixRoom, event: RoomMessageText) -> None:
+ if event.sender == self.config.user_id or not self._should_process_message(room, event):
+ return
+ await self._start_typing_keepalive(room.room_id)
+ try:
+ await self._handle_message(
+ sender_id=event.sender, chat_id=room.room_id,
+ content=event.body, metadata=self._base_metadata(room, event),
+ )
+ except Exception:
+ await self._stop_typing_keepalive(room.room_id, clear_typing=True)
+ raise
+
+ async def _on_media_message(self, room: MatrixRoom, event: MatrixMediaEvent) -> None:
+ if event.sender == self.config.user_id or not self._should_process_message(room, event):
+ return
+ attachment, marker = await self._fetch_media_attachment(room, event)
+ parts: list[str] = []
+ if isinstance(body := getattr(event, "body", None), str) and body.strip():
+ parts.append(body.strip())
+
+ if attachment and attachment.get("type") == "audio":
+ transcription = await self.transcribe_audio(attachment["path"])
+ if transcription:
+ parts.append(f"[transcription: {transcription}]")
+ else:
+ parts.append(marker)
+ elif marker:
+ parts.append(marker)
+
+ await self._start_typing_keepalive(room.room_id)
+ try:
+ meta = self._base_metadata(room, event)
+ meta["attachments"] = []
+ if attachment:
+ meta["attachments"] = [attachment]
+ await self._handle_message(
+ sender_id=event.sender, chat_id=room.room_id,
+ content="\n".join(parts),
+ media=[attachment["path"]] if attachment else [],
+ metadata=meta,
+ )
+ except Exception:
+ await self._stop_typing_keepalive(room.room_id, clear_typing=True)
+ raise
diff --git a/deeptutor/tutorbot/channels/mochat.py b/deeptutor/tutorbot/channels/mochat.py
new file mode 100644
index 000000000..efa4fc6bc
--- /dev/null
+++ b/deeptutor/tutorbot/channels/mochat.py
@@ -0,0 +1,946 @@
+"""Mochat channel implementation using Socket.IO with HTTP polling fallback."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from collections import deque
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+import httpx
+from loguru import logger
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.paths import get_runtime_subdir
+from deeptutor.tutorbot.config.schema import Base
+from pydantic import Field
+
+try:
+ import socketio
+ SOCKETIO_AVAILABLE = True
+except ImportError:
+ socketio = None
+ SOCKETIO_AVAILABLE = False
+
+try:
+ import msgpack # noqa: F401
+ MSGPACK_AVAILABLE = True
+except ImportError:
+ MSGPACK_AVAILABLE = False
+
+MAX_SEEN_MESSAGE_IDS = 2000
+CURSOR_SAVE_DEBOUNCE_S = 0.5
+
+
+# ---------------------------------------------------------------------------
+# Data classes
+# ---------------------------------------------------------------------------
+
+@dataclass
+class MochatBufferedEntry:
+ """Buffered inbound entry for delayed dispatch."""
+ raw_body: str
+ author: str
+ sender_name: str = ""
+ sender_username: str = ""
+ timestamp: int | None = None
+ message_id: str = ""
+ group_id: str = ""
+
+
+@dataclass
+class DelayState:
+ """Per-target delayed message state."""
+ entries: list[MochatBufferedEntry] = field(default_factory=list)
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ timer: asyncio.Task | None = None
+
+
+@dataclass
+class MochatTarget:
+ """Outbound target resolution result."""
+ id: str
+ is_panel: bool
+
+
+# ---------------------------------------------------------------------------
+# Pure helpers
+# ---------------------------------------------------------------------------
+
+def _safe_dict(value: Any) -> dict:
+ """Return *value* if it's a dict, else empty dict."""
+ return value if isinstance(value, dict) else {}
+
+
+def _str_field(src: dict, *keys: str) -> str:
+ """Return the first non-empty str value found for *keys*, stripped."""
+ for k in keys:
+ v = src.get(k)
+ if isinstance(v, str) and v.strip():
+ return v.strip()
+ return ""
+
+
+def _make_synthetic_event(
+ message_id: str, author: str, content: Any,
+ meta: Any, group_id: str, converse_id: str,
+ timestamp: Any = None, *, author_info: Any = None,
+) -> dict[str, Any]:
+ """Build a synthetic ``message.add`` event dict."""
+ payload: dict[str, Any] = {
+ "messageId": message_id, "author": author,
+ "content": content, "meta": _safe_dict(meta),
+ "groupId": group_id, "converseId": converse_id,
+ }
+ if author_info is not None:
+ payload["authorInfo"] = _safe_dict(author_info)
+ return {
+ "type": "message.add",
+ "timestamp": timestamp or datetime.utcnow().isoformat(),
+ "payload": payload,
+ }
+
+
+def normalize_mochat_content(content: Any) -> str:
+ """Normalize content payload to text."""
+ if isinstance(content, str):
+ return content.strip()
+ if content is None:
+ return ""
+ try:
+ return json.dumps(content, ensure_ascii=False)
+ except TypeError:
+ return str(content)
+
+
+def resolve_mochat_target(raw: str) -> MochatTarget:
+ """Resolve id and target kind from user-provided target string."""
+ trimmed = (raw or "").strip()
+ if not trimmed:
+ return MochatTarget(id="", is_panel=False)
+
+ lowered = trimmed.lower()
+ cleaned, forced_panel = trimmed, False
+ for prefix in ("mochat:", "group:", "channel:", "panel:"):
+ if lowered.startswith(prefix):
+ cleaned = trimmed[len(prefix):].strip()
+ forced_panel = prefix in {"group:", "channel:", "panel:"}
+ break
+
+ if not cleaned:
+ return MochatTarget(id="", is_panel=False)
+ return MochatTarget(id=cleaned, is_panel=forced_panel or not cleaned.startswith("session_"))
+
+
+def extract_mention_ids(value: Any) -> list[str]:
+ """Extract mention ids from heterogeneous mention payload."""
+ if not isinstance(value, list):
+ return []
+ ids: list[str] = []
+ for item in value:
+ if isinstance(item, str):
+ if item.strip():
+ ids.append(item.strip())
+ elif isinstance(item, dict):
+ for key in ("id", "userId", "_id"):
+ candidate = item.get(key)
+ if isinstance(candidate, str) and candidate.strip():
+ ids.append(candidate.strip())
+ break
+ return ids
+
+
+def resolve_was_mentioned(payload: dict[str, Any], agent_user_id: str) -> bool:
+ """Resolve mention state from payload metadata and text fallback."""
+ meta = payload.get("meta")
+ if isinstance(meta, dict):
+ if meta.get("mentioned") is True or meta.get("wasMentioned") is True:
+ return True
+ for f in ("mentions", "mentionIds", "mentionedUserIds", "mentionedUsers"):
+ if agent_user_id and agent_user_id in extract_mention_ids(meta.get(f)):
+ return True
+ if not agent_user_id:
+ return False
+ content = payload.get("content")
+ if not isinstance(content, str) or not content:
+ return False
+ return f"<@{agent_user_id}>" in content or f"@{agent_user_id}" in content
+
+
+def resolve_require_mention(config: MochatConfig, session_id: str, group_id: str) -> bool:
+ """Resolve mention requirement for group/panel conversations."""
+ groups = config.groups or {}
+ for key in (group_id, session_id, "*"):
+ if key and key in groups:
+ return bool(groups[key].require_mention)
+ return bool(config.mention.require_in_groups)
+
+
+def build_buffered_body(entries: list[MochatBufferedEntry], is_group: bool) -> str:
+ """Build text body from one or more buffered entries."""
+ if not entries:
+ return ""
+ if len(entries) == 1:
+ return entries[0].raw_body
+ lines: list[str] = []
+ for entry in entries:
+ if not entry.raw_body:
+ continue
+ if is_group:
+ label = entry.sender_name.strip() or entry.sender_username.strip() or entry.author
+ if label:
+ lines.append(f"{label}: {entry.raw_body}")
+ continue
+ lines.append(entry.raw_body)
+ return "\n".join(lines).strip()
+
+
+def parse_timestamp(value: Any) -> int | None:
+ """Parse event timestamp to epoch milliseconds."""
+ if not isinstance(value, str) or not value.strip():
+ return None
+ try:
+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() * 1000)
+ except ValueError:
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Config classes
+# ---------------------------------------------------------------------------
+
+class MochatMentionConfig(Base):
+ """Mochat mention behavior configuration."""
+
+ require_in_groups: bool = False
+
+
+class MochatGroupRule(Base):
+ """Mochat per-group mention requirement."""
+
+ require_mention: bool = False
+
+
+class MochatConfig(Base):
+ """Mochat channel configuration."""
+
+ enabled: bool = False
+ base_url: str = "https://mochat.io"
+ socket_url: str = ""
+ socket_path: str = "/socket.io"
+ socket_disable_msgpack: bool = False
+ socket_reconnect_delay_ms: int = 1000
+ socket_max_reconnect_delay_ms: int = 10000
+ socket_connect_timeout_ms: int = 10000
+ refresh_interval_ms: int = 30000
+ watch_timeout_ms: int = 25000
+ watch_limit: int = 100
+ retry_delay_ms: int = 500
+ max_retry_attempts: int = 0
+ claw_token: str = ""
+ agent_user_id: str = ""
+ sessions: list[str] = Field(default_factory=list)
+ panels: list[str] = Field(default_factory=list)
+ allow_from: list[str] = Field(default_factory=list)
+ mention: MochatMentionConfig = Field(default_factory=MochatMentionConfig)
+ groups: dict[str, MochatGroupRule] = Field(default_factory=dict)
+ reply_delay_mode: str = "non-mention"
+ reply_delay_ms: int = 120000
+
+
+# ---------------------------------------------------------------------------
+# Channel
+# ---------------------------------------------------------------------------
+
+class MochatChannel(BaseChannel):
+ """Mochat channel using socket.io with fallback polling workers."""
+
+ name = "mochat"
+ display_name = "Mochat"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return MochatConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = MochatConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: MochatConfig = config
+ self._http: httpx.AsyncClient | None = None
+ self._socket: Any = None
+ self._ws_connected = self._ws_ready = False
+
+ self._state_dir = get_runtime_subdir("mochat")
+ self._cursor_path = self._state_dir / "session_cursors.json"
+ self._session_cursor: dict[str, int] = {}
+ self._cursor_save_task: asyncio.Task | None = None
+
+ self._session_set: set[str] = set()
+ self._panel_set: set[str] = set()
+ self._auto_discover_sessions = self._auto_discover_panels = False
+
+ self._cold_sessions: set[str] = set()
+ self._session_by_converse: dict[str, str] = {}
+
+ self._seen_set: dict[str, set[str]] = {}
+ self._seen_queue: dict[str, deque[str]] = {}
+ self._delay_states: dict[str, DelayState] = {}
+
+ self._fallback_mode = False
+ self._session_fallback_tasks: dict[str, asyncio.Task] = {}
+ self._panel_fallback_tasks: dict[str, asyncio.Task] = {}
+ self._refresh_task: asyncio.Task | None = None
+ self._target_locks: dict[str, asyncio.Lock] = {}
+
+ # ---- lifecycle ---------------------------------------------------------
+
+ async def start(self) -> None:
+ """Start Mochat channel workers and websocket connection."""
+ if not self.config.claw_token:
+ logger.error("Mochat claw_token not configured")
+ return
+
+ self._running = True
+ self._http = httpx.AsyncClient(timeout=30.0)
+ self._state_dir.mkdir(parents=True, exist_ok=True)
+ await self._load_session_cursors()
+ self._seed_targets_from_config()
+ await self._refresh_targets(subscribe_new=False)
+
+ if not await self._start_socket_client():
+ await self._ensure_fallback_workers()
+
+ self._refresh_task = asyncio.create_task(self._refresh_loop())
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop all workers and clean up resources."""
+ self._running = False
+ if self._refresh_task:
+ self._refresh_task.cancel()
+ self._refresh_task = None
+
+ await self._stop_fallback_workers()
+ await self._cancel_delay_timers()
+
+ if self._socket:
+ try:
+ await self._socket.disconnect()
+ except Exception:
+ pass
+ self._socket = None
+
+ if self._cursor_save_task:
+ self._cursor_save_task.cancel()
+ self._cursor_save_task = None
+ await self._save_session_cursors()
+
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+ self._ws_connected = self._ws_ready = False
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send outbound message to session or panel."""
+ if not self.config.claw_token:
+ logger.warning("Mochat claw_token missing, skip send")
+ return
+
+ parts = ([msg.content.strip()] if msg.content and msg.content.strip() else [])
+ if msg.media:
+ parts.extend(m for m in msg.media if isinstance(m, str) and m.strip())
+ content = "\n".join(parts).strip()
+ if not content:
+ return
+
+ target = resolve_mochat_target(msg.chat_id)
+ if not target.id:
+ logger.warning("Mochat outbound target is empty")
+ return
+
+ is_panel = (target.is_panel or target.id in self._panel_set) and not target.id.startswith("session_")
+ try:
+ if is_panel:
+ await self._api_send("/api/claw/groups/panels/send", "panelId", target.id,
+ content, msg.reply_to, self._read_group_id(msg.metadata))
+ else:
+ await self._api_send("/api/claw/sessions/send", "sessionId", target.id,
+ content, msg.reply_to)
+ except Exception as e:
+ logger.error("Failed to send Mochat message: {}", e)
+
+ # ---- config / init helpers ---------------------------------------------
+
+ def _seed_targets_from_config(self) -> None:
+ sessions, self._auto_discover_sessions = self._normalize_id_list(self.config.sessions)
+ panels, self._auto_discover_panels = self._normalize_id_list(self.config.panels)
+ self._session_set.update(sessions)
+ self._panel_set.update(panels)
+ for sid in sessions:
+ if sid not in self._session_cursor:
+ self._cold_sessions.add(sid)
+
+ @staticmethod
+ def _normalize_id_list(values: list[str]) -> tuple[list[str], bool]:
+ cleaned = [str(v).strip() for v in values if str(v).strip()]
+ return sorted({v for v in cleaned if v != "*"}), "*" in cleaned
+
+ # ---- websocket ---------------------------------------------------------
+
+ async def _start_socket_client(self) -> bool:
+ if not SOCKETIO_AVAILABLE:
+ logger.warning("python-socketio not installed, Mochat using polling fallback")
+ return False
+
+ serializer = "default"
+ if not self.config.socket_disable_msgpack:
+ if MSGPACK_AVAILABLE:
+ serializer = "msgpack"
+ else:
+ logger.warning("msgpack not installed but socket_disable_msgpack=false; using JSON")
+
+ client = socketio.AsyncClient(
+ reconnection=True,
+ reconnection_attempts=self.config.max_retry_attempts or None,
+ reconnection_delay=max(0.1, self.config.socket_reconnect_delay_ms / 1000.0),
+ reconnection_delay_max=max(0.1, self.config.socket_max_reconnect_delay_ms / 1000.0),
+ logger=False, engineio_logger=False, serializer=serializer,
+ )
+
+ @client.event
+ async def connect() -> None:
+ self._ws_connected, self._ws_ready = True, False
+ logger.info("Mochat websocket connected")
+ subscribed = await self._subscribe_all()
+ self._ws_ready = subscribed
+ await (self._stop_fallback_workers() if subscribed else self._ensure_fallback_workers())
+
+ @client.event
+ async def disconnect() -> None:
+ if not self._running:
+ return
+ self._ws_connected = self._ws_ready = False
+ logger.warning("Mochat websocket disconnected")
+ await self._ensure_fallback_workers()
+
+ @client.event
+ async def connect_error(data: Any) -> None:
+ logger.error("Mochat websocket connect error: {}", data)
+
+ @client.on("claw.session.events")
+ async def on_session_events(payload: dict[str, Any]) -> None:
+ await self._handle_watch_payload(payload, "session")
+
+ @client.on("claw.panel.events")
+ async def on_panel_events(payload: dict[str, Any]) -> None:
+ await self._handle_watch_payload(payload, "panel")
+
+ for ev in ("notify:chat.inbox.append", "notify:chat.message.add",
+ "notify:chat.message.update", "notify:chat.message.recall",
+ "notify:chat.message.delete"):
+ client.on(ev, self._build_notify_handler(ev))
+
+ socket_url = (self.config.socket_url or self.config.base_url).strip().rstrip("/")
+ socket_path = (self.config.socket_path or "/socket.io").strip().lstrip("/")
+
+ try:
+ self._socket = client
+ await client.connect(
+ socket_url, transports=["websocket"], socketio_path=socket_path,
+ auth={"token": self.config.claw_token},
+ wait_timeout=max(1.0, self.config.socket_connect_timeout_ms / 1000.0),
+ )
+ return True
+ except Exception as e:
+ logger.error("Failed to connect Mochat websocket: {}", e)
+ try:
+ await client.disconnect()
+ except Exception:
+ pass
+ self._socket = None
+ return False
+
+ def _build_notify_handler(self, event_name: str):
+ async def handler(payload: Any) -> None:
+ if event_name == "notify:chat.inbox.append":
+ await self._handle_notify_inbox_append(payload)
+ elif event_name.startswith("notify:chat.message."):
+ await self._handle_notify_chat_message(payload)
+ return handler
+
+ # ---- subscribe ---------------------------------------------------------
+
+ async def _subscribe_all(self) -> bool:
+ ok = await self._subscribe_sessions(sorted(self._session_set))
+ ok = await self._subscribe_panels(sorted(self._panel_set)) and ok
+ if self._auto_discover_sessions or self._auto_discover_panels:
+ await self._refresh_targets(subscribe_new=True)
+ return ok
+
+ async def _subscribe_sessions(self, session_ids: list[str]) -> bool:
+ if not session_ids:
+ return True
+ for sid in session_ids:
+ if sid not in self._session_cursor:
+ self._cold_sessions.add(sid)
+
+ ack = await self._socket_call("com.claw.im.subscribeSessions", {
+ "sessionIds": session_ids, "cursors": self._session_cursor,
+ "limit": self.config.watch_limit,
+ })
+ if not ack.get("result"):
+ logger.error("Mochat subscribeSessions failed: {}", ack.get('message', 'unknown error'))
+ return False
+
+ data = ack.get("data")
+ items: list[dict[str, Any]] = []
+ if isinstance(data, list):
+ items = [i for i in data if isinstance(i, dict)]
+ elif isinstance(data, dict):
+ sessions = data.get("sessions")
+ if isinstance(sessions, list):
+ items = [i for i in sessions if isinstance(i, dict)]
+ elif "sessionId" in data:
+ items = [data]
+ for p in items:
+ await self._handle_watch_payload(p, "session")
+ return True
+
+ async def _subscribe_panels(self, panel_ids: list[str]) -> bool:
+ if not self._auto_discover_panels and not panel_ids:
+ return True
+ ack = await self._socket_call("com.claw.im.subscribePanels", {"panelIds": panel_ids})
+ if not ack.get("result"):
+ logger.error("Mochat subscribePanels failed: {}", ack.get('message', 'unknown error'))
+ return False
+ return True
+
+ async def _socket_call(self, event_name: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if not self._socket:
+ return {"result": False, "message": "socket not connected"}
+ try:
+ raw = await self._socket.call(event_name, payload, timeout=10)
+ except Exception as e:
+ return {"result": False, "message": str(e)}
+ return raw if isinstance(raw, dict) else {"result": True, "data": raw}
+
+ # ---- refresh / discovery -----------------------------------------------
+
+ async def _refresh_loop(self) -> None:
+ interval_s = max(1.0, self.config.refresh_interval_ms / 1000.0)
+ while self._running:
+ await asyncio.sleep(interval_s)
+ try:
+ await self._refresh_targets(subscribe_new=self._ws_ready)
+ except Exception as e:
+ logger.warning("Mochat refresh failed: {}", e)
+ if self._fallback_mode:
+ await self._ensure_fallback_workers()
+
+ async def _refresh_targets(self, subscribe_new: bool) -> None:
+ if self._auto_discover_sessions:
+ await self._refresh_sessions_directory(subscribe_new)
+ if self._auto_discover_panels:
+ await self._refresh_panels(subscribe_new)
+
+ async def _refresh_sessions_directory(self, subscribe_new: bool) -> None:
+ try:
+ response = await self._post_json("/api/claw/sessions/list", {})
+ except Exception as e:
+ logger.warning("Mochat listSessions failed: {}", e)
+ return
+
+ sessions = response.get("sessions")
+ if not isinstance(sessions, list):
+ return
+
+ new_ids: list[str] = []
+ for s in sessions:
+ if not isinstance(s, dict):
+ continue
+ sid = _str_field(s, "sessionId")
+ if not sid:
+ continue
+ if sid not in self._session_set:
+ self._session_set.add(sid)
+ new_ids.append(sid)
+ if sid not in self._session_cursor:
+ self._cold_sessions.add(sid)
+ cid = _str_field(s, "converseId")
+ if cid:
+ self._session_by_converse[cid] = sid
+
+ if not new_ids:
+ return
+ if self._ws_ready and subscribe_new:
+ await self._subscribe_sessions(new_ids)
+ if self._fallback_mode:
+ await self._ensure_fallback_workers()
+
+ async def _refresh_panels(self, subscribe_new: bool) -> None:
+ try:
+ response = await self._post_json("/api/claw/groups/get", {})
+ except Exception as e:
+ logger.warning("Mochat getWorkspaceGroup failed: {}", e)
+ return
+
+ raw_panels = response.get("panels")
+ if not isinstance(raw_panels, list):
+ return
+
+ new_ids: list[str] = []
+ for p in raw_panels:
+ if not isinstance(p, dict):
+ continue
+ pt = p.get("type")
+ if isinstance(pt, int) and pt != 0:
+ continue
+ pid = _str_field(p, "id", "_id")
+ if pid and pid not in self._panel_set:
+ self._panel_set.add(pid)
+ new_ids.append(pid)
+
+ if not new_ids:
+ return
+ if self._ws_ready and subscribe_new:
+ await self._subscribe_panels(new_ids)
+ if self._fallback_mode:
+ await self._ensure_fallback_workers()
+
+ # ---- fallback workers --------------------------------------------------
+
+ async def _ensure_fallback_workers(self) -> None:
+ if not self._running:
+ return
+ self._fallback_mode = True
+ for sid in sorted(self._session_set):
+ t = self._session_fallback_tasks.get(sid)
+ if not t or t.done():
+ self._session_fallback_tasks[sid] = asyncio.create_task(self._session_watch_worker(sid))
+ for pid in sorted(self._panel_set):
+ t = self._panel_fallback_tasks.get(pid)
+ if not t or t.done():
+ self._panel_fallback_tasks[pid] = asyncio.create_task(self._panel_poll_worker(pid))
+
+ async def _stop_fallback_workers(self) -> None:
+ self._fallback_mode = False
+ tasks = [*self._session_fallback_tasks.values(), *self._panel_fallback_tasks.values()]
+ for t in tasks:
+ t.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ self._session_fallback_tasks.clear()
+ self._panel_fallback_tasks.clear()
+
+ async def _session_watch_worker(self, session_id: str) -> None:
+ while self._running and self._fallback_mode:
+ try:
+ payload = await self._post_json("/api/claw/sessions/watch", {
+ "sessionId": session_id, "cursor": self._session_cursor.get(session_id, 0),
+ "timeoutMs": self.config.watch_timeout_ms, "limit": self.config.watch_limit,
+ })
+ await self._handle_watch_payload(payload, "session")
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.warning("Mochat watch fallback error ({}): {}", session_id, e)
+ await asyncio.sleep(max(0.1, self.config.retry_delay_ms / 1000.0))
+
+ async def _panel_poll_worker(self, panel_id: str) -> None:
+ sleep_s = max(1.0, self.config.refresh_interval_ms / 1000.0)
+ while self._running and self._fallback_mode:
+ try:
+ resp = await self._post_json("/api/claw/groups/panels/messages", {
+ "panelId": panel_id, "limit": min(100, max(1, self.config.watch_limit)),
+ })
+ msgs = resp.get("messages")
+ if isinstance(msgs, list):
+ for m in reversed(msgs):
+ if not isinstance(m, dict):
+ continue
+ evt = _make_synthetic_event(
+ message_id=str(m.get("messageId") or ""),
+ author=str(m.get("author") or ""),
+ content=m.get("content"),
+ meta=m.get("meta"), group_id=str(resp.get("groupId") or ""),
+ converse_id=panel_id, timestamp=m.get("createdAt"),
+ author_info=m.get("authorInfo"),
+ )
+ await self._process_inbound_event(panel_id, evt, "panel")
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.warning("Mochat panel polling error ({}): {}", panel_id, e)
+ await asyncio.sleep(sleep_s)
+
+ # ---- inbound event processing ------------------------------------------
+
+ async def _handle_watch_payload(self, payload: dict[str, Any], target_kind: str) -> None:
+ if not isinstance(payload, dict):
+ return
+ target_id = _str_field(payload, "sessionId")
+ if not target_id:
+ return
+
+ lock = self._target_locks.setdefault(f"{target_kind}:{target_id}", asyncio.Lock())
+ async with lock:
+ prev = self._session_cursor.get(target_id, 0) if target_kind == "session" else 0
+ pc = payload.get("cursor")
+ if target_kind == "session" and isinstance(pc, int) and pc >= 0:
+ self._mark_session_cursor(target_id, pc)
+
+ raw_events = payload.get("events")
+ if not isinstance(raw_events, list):
+ return
+ if target_kind == "session" and target_id in self._cold_sessions:
+ self._cold_sessions.discard(target_id)
+ return
+
+ for event in raw_events:
+ if not isinstance(event, dict):
+ continue
+ seq = event.get("seq")
+ if target_kind == "session" and isinstance(seq, int) and seq > self._session_cursor.get(target_id, prev):
+ self._mark_session_cursor(target_id, seq)
+ if event.get("type") == "message.add":
+ await self._process_inbound_event(target_id, event, target_kind)
+
+ async def _process_inbound_event(self, target_id: str, event: dict[str, Any], target_kind: str) -> None:
+ payload = event.get("payload")
+ if not isinstance(payload, dict):
+ return
+
+ author = _str_field(payload, "author")
+ if not author or (self.config.agent_user_id and author == self.config.agent_user_id):
+ return
+ if not self.is_allowed(author):
+ return
+
+ message_id = _str_field(payload, "messageId")
+ seen_key = f"{target_kind}:{target_id}"
+ if message_id and self._remember_message_id(seen_key, message_id):
+ return
+
+ raw_body = normalize_mochat_content(payload.get("content")) or "[empty message]"
+ ai = _safe_dict(payload.get("authorInfo"))
+ sender_name = _str_field(ai, "nickname", "email")
+ sender_username = _str_field(ai, "agentId")
+
+ group_id = _str_field(payload, "groupId")
+ is_group = bool(group_id)
+ was_mentioned = resolve_was_mentioned(payload, self.config.agent_user_id)
+ require_mention = target_kind == "panel" and is_group and resolve_require_mention(self.config, target_id, group_id)
+ use_delay = target_kind == "panel" and self.config.reply_delay_mode == "non-mention"
+
+ if require_mention and not was_mentioned and not use_delay:
+ return
+
+ entry = MochatBufferedEntry(
+ raw_body=raw_body, author=author, sender_name=sender_name,
+ sender_username=sender_username, timestamp=parse_timestamp(event.get("timestamp")),
+ message_id=message_id, group_id=group_id,
+ )
+
+ if use_delay:
+ delay_key = seen_key
+ if was_mentioned:
+ await self._flush_delayed_entries(delay_key, target_id, target_kind, "mention", entry)
+ else:
+ await self._enqueue_delayed_entry(delay_key, target_id, target_kind, entry)
+ return
+
+ await self._dispatch_entries(target_id, target_kind, [entry], was_mentioned)
+
+ # ---- dedup / buffering -------------------------------------------------
+
+ def _remember_message_id(self, key: str, message_id: str) -> bool:
+ seen_set = self._seen_set.setdefault(key, set())
+ seen_queue = self._seen_queue.setdefault(key, deque())
+ if message_id in seen_set:
+ return True
+ seen_set.add(message_id)
+ seen_queue.append(message_id)
+ while len(seen_queue) > MAX_SEEN_MESSAGE_IDS:
+ seen_set.discard(seen_queue.popleft())
+ return False
+
+ async def _enqueue_delayed_entry(self, key: str, target_id: str, target_kind: str, entry: MochatBufferedEntry) -> None:
+ state = self._delay_states.setdefault(key, DelayState())
+ async with state.lock:
+ state.entries.append(entry)
+ if state.timer:
+ state.timer.cancel()
+ state.timer = asyncio.create_task(self._delay_flush_after(key, target_id, target_kind))
+
+ async def _delay_flush_after(self, key: str, target_id: str, target_kind: str) -> None:
+ await asyncio.sleep(max(0, self.config.reply_delay_ms) / 1000.0)
+ await self._flush_delayed_entries(key, target_id, target_kind, "timer", None)
+
+ async def _flush_delayed_entries(self, key: str, target_id: str, target_kind: str, reason: str, entry: MochatBufferedEntry | None) -> None:
+ state = self._delay_states.setdefault(key, DelayState())
+ async with state.lock:
+ if entry:
+ state.entries.append(entry)
+ current = asyncio.current_task()
+ if state.timer and state.timer is not current:
+ state.timer.cancel()
+ state.timer = None
+ entries = state.entries[:]
+ state.entries.clear()
+ if entries:
+ await self._dispatch_entries(target_id, target_kind, entries, reason == "mention")
+
+ async def _dispatch_entries(self, target_id: str, target_kind: str, entries: list[MochatBufferedEntry], was_mentioned: bool) -> None:
+ if not entries:
+ return
+ last = entries[-1]
+ is_group = bool(last.group_id)
+ body = build_buffered_body(entries, is_group) or "[empty message]"
+ await self._handle_message(
+ sender_id=last.author, chat_id=target_id, content=body,
+ metadata={
+ "message_id": last.message_id, "timestamp": last.timestamp,
+ "is_group": is_group, "group_id": last.group_id,
+ "sender_name": last.sender_name, "sender_username": last.sender_username,
+ "target_kind": target_kind, "was_mentioned": was_mentioned,
+ "buffered_count": len(entries),
+ },
+ )
+
+ async def _cancel_delay_timers(self) -> None:
+ for state in self._delay_states.values():
+ if state.timer:
+ state.timer.cancel()
+ self._delay_states.clear()
+
+ # ---- notify handlers ---------------------------------------------------
+
+ async def _handle_notify_chat_message(self, payload: Any) -> None:
+ if not isinstance(payload, dict):
+ return
+ group_id = _str_field(payload, "groupId")
+ panel_id = _str_field(payload, "converseId", "panelId")
+ if not group_id or not panel_id:
+ return
+ if self._panel_set and panel_id not in self._panel_set:
+ return
+
+ evt = _make_synthetic_event(
+ message_id=str(payload.get("_id") or payload.get("messageId") or ""),
+ author=str(payload.get("author") or ""),
+ content=payload.get("content"), meta=payload.get("meta"),
+ group_id=group_id, converse_id=panel_id,
+ timestamp=payload.get("createdAt"), author_info=payload.get("authorInfo"),
+ )
+ await self._process_inbound_event(panel_id, evt, "panel")
+
+ async def _handle_notify_inbox_append(self, payload: Any) -> None:
+ if not isinstance(payload, dict) or payload.get("type") != "message":
+ return
+ detail = payload.get("payload")
+ if not isinstance(detail, dict):
+ return
+ if _str_field(detail, "groupId"):
+ return
+ converse_id = _str_field(detail, "converseId")
+ if not converse_id:
+ return
+
+ session_id = self._session_by_converse.get(converse_id)
+ if not session_id:
+ await self._refresh_sessions_directory(self._ws_ready)
+ session_id = self._session_by_converse.get(converse_id)
+ if not session_id:
+ return
+
+ evt = _make_synthetic_event(
+ message_id=str(detail.get("messageId") or payload.get("_id") or ""),
+ author=str(detail.get("messageAuthor") or ""),
+ content=str(detail.get("messagePlainContent") or detail.get("messageSnippet") or ""),
+ meta={"source": "notify:chat.inbox.append", "converseId": converse_id},
+ group_id="", converse_id=converse_id, timestamp=payload.get("createdAt"),
+ )
+ await self._process_inbound_event(session_id, evt, "session")
+
+ # ---- cursor persistence ------------------------------------------------
+
+ def _mark_session_cursor(self, session_id: str, cursor: int) -> None:
+ if cursor < 0 or cursor < self._session_cursor.get(session_id, 0):
+ return
+ self._session_cursor[session_id] = cursor
+ if not self._cursor_save_task or self._cursor_save_task.done():
+ self._cursor_save_task = asyncio.create_task(self._save_cursor_debounced())
+
+ async def _save_cursor_debounced(self) -> None:
+ await asyncio.sleep(CURSOR_SAVE_DEBOUNCE_S)
+ await self._save_session_cursors()
+
+ async def _load_session_cursors(self) -> None:
+ if not self._cursor_path.exists():
+ return
+ try:
+ data = json.loads(self._cursor_path.read_text("utf-8"))
+ except Exception as e:
+ logger.warning("Failed to read Mochat cursor file: {}", e)
+ return
+ cursors = data.get("cursors") if isinstance(data, dict) else None
+ if isinstance(cursors, dict):
+ for sid, cur in cursors.items():
+ if isinstance(sid, str) and isinstance(cur, int) and cur >= 0:
+ self._session_cursor[sid] = cur
+
+ async def _save_session_cursors(self) -> None:
+ try:
+ self._state_dir.mkdir(parents=True, exist_ok=True)
+ self._cursor_path.write_text(json.dumps({
+ "schemaVersion": 1, "updatedAt": datetime.utcnow().isoformat(),
+ "cursors": self._session_cursor,
+ }, ensure_ascii=False, indent=2) + "\n", "utf-8")
+ except Exception as e:
+ logger.warning("Failed to save Mochat cursor file: {}", e)
+
+ # ---- HTTP helpers ------------------------------------------------------
+
+ async def _post_json(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if not self._http:
+ raise RuntimeError("Mochat HTTP client not initialized")
+ url = f"{self.config.base_url.strip().rstrip('/')}{path}"
+ response = await self._http.post(url, headers={
+ "Content-Type": "application/json", "X-Claw-Token": self.config.claw_token,
+ }, json=payload)
+ if not response.is_success:
+ raise RuntimeError(f"Mochat HTTP {response.status_code}: {response.text[:200]}")
+ try:
+ parsed = response.json()
+ except Exception:
+ parsed = response.text
+ if isinstance(parsed, dict) and isinstance(parsed.get("code"), int):
+ if parsed["code"] != 200:
+ msg = str(parsed.get("message") or parsed.get("name") or "request failed")
+ raise RuntimeError(f"Mochat API error: {msg} (code={parsed['code']})")
+ data = parsed.get("data")
+ return data if isinstance(data, dict) else {}
+ return parsed if isinstance(parsed, dict) else {}
+
+ async def _api_send(self, path: str, id_key: str, id_val: str,
+ content: str, reply_to: str | None, group_id: str | None = None) -> dict[str, Any]:
+ """Unified send helper for session and panel messages."""
+ body: dict[str, Any] = {id_key: id_val, "content": content}
+ if reply_to:
+ body["replyTo"] = reply_to
+ if group_id:
+ body["groupId"] = group_id
+ return await self._post_json(path, body)
+
+ @staticmethod
+ def _read_group_id(metadata: dict[str, Any]) -> str | None:
+ if not isinstance(metadata, dict):
+ return None
+ value = metadata.get("group_id") or metadata.get("groupId")
+ return value.strip() if isinstance(value, str) and value.strip() else None
diff --git a/deeptutor/tutorbot/channels/qq.py b/deeptutor/tutorbot/channels/qq.py
new file mode 100644
index 000000000..1fc280939
--- /dev/null
+++ b/deeptutor/tutorbot/channels/qq.py
@@ -0,0 +1,183 @@
+"""QQ channel implementation using botpy SDK."""
+
+import asyncio
+from collections import deque
+from typing import TYPE_CHECKING, Any, Literal
+
+from loguru import logger
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.schema import Base
+from pydantic import Field
+
+try:
+ import botpy
+ from botpy.message import C2CMessage, GroupMessage
+
+ QQ_AVAILABLE = True
+except ImportError:
+ QQ_AVAILABLE = False
+ botpy = None
+ C2CMessage = None
+ GroupMessage = None
+
+if TYPE_CHECKING:
+ from botpy.message import C2CMessage, GroupMessage
+
+
+def _make_bot_class(channel: "QQChannel") -> "type[botpy.Client]":
+ """Create a botpy Client subclass bound to the given channel."""
+ intents = botpy.Intents(public_messages=True, direct_message=True)
+
+ class _Bot(botpy.Client):
+ def __init__(self):
+ # Disable botpy's file log — tutorbot uses loguru; default "botpy.log" fails on read-only fs
+ super().__init__(intents=intents, ext_handlers=False)
+
+ async def on_ready(self):
+ logger.info("QQ bot ready: {}", self.robot.name)
+
+ async def on_c2c_message_create(self, message: "C2CMessage"):
+ await channel._on_message(message, is_group=False)
+
+ async def on_group_at_message_create(self, message: "GroupMessage"):
+ await channel._on_message(message, is_group=True)
+
+ async def on_direct_message_create(self, message):
+ await channel._on_message(message, is_group=False)
+
+ return _Bot
+
+
+class QQConfig(Base):
+ """QQ channel configuration using botpy SDK."""
+
+ enabled: bool = False
+ app_id: str = ""
+ secret: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ msg_format: Literal["plain", "markdown"] = "plain"
+
+
+class QQChannel(BaseChannel):
+ """QQ channel using botpy SDK with WebSocket connection."""
+
+ name = "qq"
+ display_name = "QQ"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return QQConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = QQConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: QQConfig = config
+ self._client: "botpy.Client | None" = None
+ self._processed_ids: deque = deque(maxlen=1000)
+ self._msg_seq: int = 1 # 消息序列号,避免被 QQ API 去重
+ self._chat_type_cache: dict[str, str] = {}
+
+ async def start(self) -> None:
+ """Start the QQ bot."""
+ if not QQ_AVAILABLE:
+ logger.error("QQ SDK not installed. Run: pip install qq-botpy")
+ return
+
+ if not self.config.app_id or not self.config.secret:
+ logger.error("QQ app_id and secret not configured")
+ return
+
+ self._running = True
+ BotClass = _make_bot_class(self)
+ self._client = BotClass()
+ logger.info("QQ bot started (C2C & Group supported)")
+ await self._run_bot()
+
+ async def _run_bot(self) -> None:
+ """Run the bot connection with auto-reconnect."""
+ while self._running:
+ try:
+ await self._client.start(appid=self.config.app_id, secret=self.config.secret)
+ except Exception as e:
+ logger.warning("QQ bot error: {}", e)
+ if self._running:
+ logger.info("Reconnecting QQ bot in 5 seconds...")
+ await asyncio.sleep(5)
+
+ async def stop(self) -> None:
+ """Stop the QQ bot."""
+ self._running = False
+ if self._client:
+ try:
+ await self._client.close()
+ except Exception:
+ pass
+ logger.info("QQ bot stopped")
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through QQ."""
+ if not self._client:
+ logger.warning("QQ client not initialized")
+ return
+
+ try:
+ msg_id = msg.metadata.get("message_id")
+ self._msg_seq += 1
+ use_markdown = self.config.msg_format == "markdown"
+ payload: dict[str, Any] = {
+ "msg_type": 2 if use_markdown else 0,
+ "msg_id": msg_id,
+ "msg_seq": self._msg_seq,
+ }
+ if use_markdown:
+ payload["markdown"] = {"content": msg.content}
+ else:
+ payload["content"] = msg.content
+
+ chat_type = self._chat_type_cache.get(msg.chat_id, "c2c")
+ if chat_type == "group":
+ await self._client.api.post_group_message(
+ group_openid=msg.chat_id,
+ **payload,
+ )
+ else:
+ await self._client.api.post_c2c_message(
+ openid=msg.chat_id,
+ **payload,
+ )
+ except Exception as e:
+ logger.error("Error sending QQ message: {}", e)
+
+ async def _on_message(self, data: "C2CMessage | GroupMessage", is_group: bool = False) -> None:
+ """Handle incoming message from QQ."""
+ try:
+ # Dedup by message ID
+ if data.id in self._processed_ids:
+ return
+ self._processed_ids.append(data.id)
+
+ content = (data.content or "").strip()
+ if not content:
+ return
+
+ if is_group:
+ chat_id = data.group_openid
+ user_id = data.author.member_openid
+ self._chat_type_cache[chat_id] = "group"
+ else:
+ chat_id = str(getattr(data.author, 'id', None) or getattr(data.author, 'user_openid', 'unknown'))
+ user_id = chat_id
+ self._chat_type_cache[chat_id] = "c2c"
+
+ await self._handle_message(
+ sender_id=user_id,
+ chat_id=chat_id,
+ content=content,
+ metadata={"message_id": data.id},
+ )
+ except Exception:
+ logger.exception("Error handling QQ message")
diff --git a/deeptutor/tutorbot/channels/registry.py b/deeptutor/tutorbot/channels/registry.py
new file mode 100644
index 000000000..94b67ff49
--- /dev/null
+++ b/deeptutor/tutorbot/channels/registry.py
@@ -0,0 +1,71 @@
+"""Auto-discovery for built-in channel modules and external plugins."""
+
+from __future__ import annotations
+
+import importlib
+import pkgutil
+from typing import TYPE_CHECKING
+
+from loguru import logger
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.channels.base import BaseChannel
+
+_INTERNAL = frozenset({"base", "manager", "registry"})
+
+
+def discover_channel_names() -> list[str]:
+ """Return all built-in channel module names by scanning the package (zero imports)."""
+ import deeptutor.tutorbot.channels as pkg
+
+ return [
+ name
+ for _, name, ispkg in pkgutil.iter_modules(pkg.__path__)
+ if name not in _INTERNAL and not ispkg
+ ]
+
+
+def load_channel_class(module_name: str) -> type[BaseChannel]:
+ """Import *module_name* and return the first BaseChannel subclass found."""
+ from deeptutor.tutorbot.channels.base import BaseChannel as _Base
+
+ mod = importlib.import_module(f"deeptutor.tutorbot.channels.{module_name}")
+ for attr in dir(mod):
+ obj = getattr(mod, attr)
+ if isinstance(obj, type) and issubclass(obj, _Base) and obj is not _Base:
+ return obj
+ raise ImportError(f"No BaseChannel subclass in deeptutor.tutorbot.channels.{module_name}")
+
+
+def discover_plugins() -> dict[str, type[BaseChannel]]:
+ """Discover external channel plugins registered via entry_points."""
+ from importlib.metadata import entry_points
+
+ plugins: dict[str, type[BaseChannel]] = {}
+ for ep in entry_points(group="deeptutor.tutorbot.channels"):
+ try:
+ cls = ep.load()
+ plugins[ep.name] = cls
+ except Exception as e:
+ logger.warning("Failed to load channel plugin '{}': {}", ep.name, e)
+ return plugins
+
+
+def discover_all() -> dict[str, type[BaseChannel]]:
+ """Return all channels: built-in (pkgutil) merged with external (entry_points).
+
+ Built-in channels take priority — an external plugin cannot shadow a built-in name.
+ """
+ builtin: dict[str, type[BaseChannel]] = {}
+ for modname in discover_channel_names():
+ try:
+ builtin[modname] = load_channel_class(modname)
+ except ImportError as e:
+ logger.debug("Skipping built-in channel '{}': {}", modname, e)
+
+ external = discover_plugins()
+ shadowed = set(external) & set(builtin)
+ if shadowed:
+ logger.warning("Plugin(s) shadowed by built-in channels (ignored): {}", shadowed)
+
+ return {**external, **builtin}
diff --git a/deeptutor/tutorbot/channels/slack.py b/deeptutor/tutorbot/channels/slack.py
new file mode 100644
index 000000000..75cb978f6
--- /dev/null
+++ b/deeptutor/tutorbot/channels/slack.py
@@ -0,0 +1,314 @@
+"""Slack channel implementation using Socket Mode."""
+
+import asyncio
+import re
+from typing import Any
+
+from loguru import logger
+from slack_sdk.socket_mode.request import SocketModeRequest
+from slack_sdk.socket_mode.response import SocketModeResponse
+from slack_sdk.socket_mode.websockets import SocketModeClient
+from slack_sdk.web.async_client import AsyncWebClient
+from slackify_markdown import slackify_markdown
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from pydantic import Field
+
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.schema import Base
+
+
+class SlackDMConfig(Base):
+ """Slack DM policy configuration."""
+
+ enabled: bool = True
+ policy: str = "open"
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class SlackConfig(Base):
+ """Slack channel configuration."""
+
+ enabled: bool = False
+ mode: str = "socket"
+ webhook_path: str = "/slack/events"
+ bot_token: str = ""
+ app_token: str = ""
+ user_token_read_only: bool = True
+ reply_in_thread: bool = True
+ react_emoji: str = "eyes"
+ allow_from: list[str] = Field(default_factory=list)
+ group_policy: str = "mention"
+ group_allow_from: list[str] = Field(default_factory=list)
+ dm: SlackDMConfig = Field(default_factory=SlackDMConfig)
+
+
+class SlackChannel(BaseChannel):
+ """Slack channel using Socket Mode."""
+
+ name = "slack"
+ display_name = "Slack"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return SlackConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = SlackConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: SlackConfig = config
+ self._web_client: AsyncWebClient | None = None
+ self._socket_client: SocketModeClient | None = None
+ self._bot_user_id: str | None = None
+
+ async def start(self) -> None:
+ """Start the Slack Socket Mode client."""
+ if not self.config.bot_token or not self.config.app_token:
+ logger.error("Slack bot/app token not configured")
+ return
+ if self.config.mode != "socket":
+ logger.error("Unsupported Slack mode: {}", self.config.mode)
+ return
+
+ self._running = True
+
+ self._web_client = AsyncWebClient(token=self.config.bot_token)
+ self._socket_client = SocketModeClient(
+ app_token=self.config.app_token,
+ web_client=self._web_client,
+ )
+
+ self._socket_client.socket_mode_request_listeners.append(self._on_socket_request)
+
+ # Resolve bot user ID for mention handling
+ try:
+ auth = await self._web_client.auth_test()
+ self._bot_user_id = auth.get("user_id")
+ logger.info("Slack bot connected as {}", self._bot_user_id)
+ except Exception as e:
+ logger.warning("Slack auth_test failed: {}", e)
+
+ logger.info("Starting Slack Socket Mode client...")
+ await self._socket_client.connect()
+
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop the Slack client."""
+ self._running = False
+ if self._socket_client:
+ try:
+ await self._socket_client.close()
+ except Exception as e:
+ logger.warning("Slack socket close failed: {}", e)
+ self._socket_client = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Slack."""
+ if not self._web_client:
+ logger.warning("Slack client not running")
+ return
+ try:
+ slack_meta = msg.metadata.get("slack", {}) if msg.metadata else {}
+ thread_ts = slack_meta.get("thread_ts")
+ channel_type = slack_meta.get("channel_type")
+ # Slack DMs don't use threads; channel/group replies may keep thread_ts.
+ thread_ts_param = thread_ts if thread_ts and channel_type != "im" else None
+
+ # Slack rejects empty text payloads. Keep media-only messages media-only,
+ # but send a single blank message when the bot has no text or files to send.
+ if msg.content or not (msg.media or []):
+ await self._web_client.chat_postMessage(
+ channel=msg.chat_id,
+ text=self._to_mrkdwn(msg.content) if msg.content else " ",
+ thread_ts=thread_ts_param,
+ )
+
+ for media_path in msg.media or []:
+ try:
+ await self._web_client.files_upload_v2(
+ channel=msg.chat_id,
+ file=media_path,
+ thread_ts=thread_ts_param,
+ )
+ except Exception as e:
+ logger.error("Failed to upload file {}: {}", media_path, e)
+ except Exception as e:
+ logger.error("Error sending Slack message: {}", e)
+
+ async def _on_socket_request(
+ self,
+ client: SocketModeClient,
+ req: SocketModeRequest,
+ ) -> None:
+ """Handle incoming Socket Mode requests."""
+ if req.type != "events_api":
+ return
+
+ # Acknowledge right away
+ await client.send_socket_mode_response(
+ SocketModeResponse(envelope_id=req.envelope_id)
+ )
+
+ payload = req.payload or {}
+ event = payload.get("event") or {}
+ event_type = event.get("type")
+
+ # Handle app mentions or plain messages
+ if event_type not in ("message", "app_mention"):
+ return
+
+ sender_id = event.get("user")
+ chat_id = event.get("channel")
+
+ # Ignore bot/system messages (any subtype = not a normal user message)
+ if event.get("subtype"):
+ return
+ if self._bot_user_id and sender_id == self._bot_user_id:
+ return
+
+ # Avoid double-processing: Slack sends both `message` and `app_mention`
+ # for mentions in channels. Prefer `app_mention`.
+ text = event.get("text") or ""
+ if event_type == "message" and self._bot_user_id and f"<@{self._bot_user_id}>" in text:
+ return
+
+ # Debug: log basic event shape
+ logger.debug(
+ "Slack event: type={} subtype={} user={} channel={} channel_type={} text={}",
+ event_type,
+ event.get("subtype"),
+ sender_id,
+ chat_id,
+ event.get("channel_type"),
+ text[:80],
+ )
+ if not sender_id or not chat_id:
+ return
+
+ channel_type = event.get("channel_type") or ""
+
+ if not self._is_allowed(sender_id, chat_id, channel_type):
+ return
+
+ if channel_type != "im" and not self._should_respond_in_channel(event_type, text, chat_id):
+ return
+
+ text = self._strip_bot_mention(text)
+
+ thread_ts = event.get("thread_ts")
+ if self.config.reply_in_thread and not thread_ts:
+ thread_ts = event.get("ts")
+ # Add :eyes: reaction to the triggering message (best-effort)
+ try:
+ if self._web_client and event.get("ts"):
+ await self._web_client.reactions_add(
+ channel=chat_id,
+ name=self.config.react_emoji,
+ timestamp=event.get("ts"),
+ )
+ except Exception as e:
+ logger.debug("Slack reactions_add failed: {}", e)
+
+ # Thread-scoped session key for channel/group messages
+ session_key = f"slack:{chat_id}:{thread_ts}" if thread_ts and channel_type != "im" else None
+
+ try:
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=chat_id,
+ content=text,
+ metadata={
+ "slack": {
+ "event": event,
+ "thread_ts": thread_ts,
+ "channel_type": channel_type,
+ },
+ },
+ session_key=session_key,
+ )
+ except Exception:
+ logger.exception("Error handling Slack message from {}", sender_id)
+
+ def _is_allowed(self, sender_id: str, chat_id: str, channel_type: str) -> bool:
+ if channel_type == "im":
+ if not self.config.dm.enabled:
+ return False
+ if self.config.dm.policy == "allowlist":
+ return sender_id in self.config.dm.allow_from
+ return True
+
+ # Group / channel messages
+ if self.config.group_policy == "allowlist":
+ return chat_id in self.config.group_allow_from
+ return True
+
+ def _should_respond_in_channel(self, event_type: str, text: str, chat_id: str) -> bool:
+ if self.config.group_policy == "open":
+ return True
+ if self.config.group_policy == "mention":
+ if event_type == "app_mention":
+ return True
+ return self._bot_user_id is not None and f"<@{self._bot_user_id}>" in text
+ if self.config.group_policy == "allowlist":
+ return chat_id in self.config.group_allow_from
+ return False
+
+ def _strip_bot_mention(self, text: str) -> str:
+ if not text or not self._bot_user_id:
+ return text
+ return re.sub(rf"<@{re.escape(self._bot_user_id)}>\s*", "", text).strip()
+
+ _TABLE_RE = re.compile(r"(?m)^\|.*\|$(?:\n\|[\s:|-]*\|$)(?:\n\|.*\|$)*")
+ _CODE_FENCE_RE = re.compile(r"```[\s\S]*?```")
+ _INLINE_CODE_RE = re.compile(r"`[^`]+`")
+ _LEFTOVER_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
+ _LEFTOVER_HEADER_RE = re.compile(r"^#{1,6}\s+(.+)$", re.MULTILINE)
+ _BARE_URL_RE = re.compile(r"(?<![|<])(https?://\S+)")
+
+ @classmethod
+ def _to_mrkdwn(cls, text: str) -> str:
+ """Convert Markdown to Slack mrkdwn, including tables."""
+ if not text:
+ return ""
+ text = cls._TABLE_RE.sub(cls._convert_table, text)
+ return cls._fixup_mrkdwn(slackify_markdown(text))
+
+ @classmethod
+ def _fixup_mrkdwn(cls, text: str) -> str:
+ """Fix markdown artifacts that slackify_markdown misses."""
+ code_blocks: list[str] = []
+
+ def _save_code(m: re.Match) -> str:
+ code_blocks.append(m.group(0))
+ return f"\x00CB{len(code_blocks) - 1}\x00"
+
+ text = cls._CODE_FENCE_RE.sub(_save_code, text)
+ text = cls._INLINE_CODE_RE.sub(_save_code, text)
+ text = cls._LEFTOVER_BOLD_RE.sub(r"*\1*", text)
+ text = cls._LEFTOVER_HEADER_RE.sub(r"*\1*", text)
+ text = cls._BARE_URL_RE.sub(lambda m: m.group(0).replace("&amp;", "&"), text)
+
+ for i, block in enumerate(code_blocks):
+ text = text.replace(f"\x00CB{i}\x00", block)
+ return text
+
+ @staticmethod
+ def _convert_table(match: re.Match) -> str:
+ """Convert a Markdown table to a Slack-readable list."""
+ lines = [ln.strip() for ln in match.group(0).strip().splitlines() if ln.strip()]
+ if len(lines) < 2:
+ return match.group(0)
+ headers = [h.strip() for h in lines[0].strip("|").split("|")]
+ start = 2 if re.fullmatch(r"[|\s:\-]+", lines[1]) else 1
+ rows: list[str] = []
+ for line in lines[start:]:
+ cells = [c.strip() for c in line.strip("|").split("|")]
+ cells = (cells + [""] * len(headers))[: len(headers)]
+ parts = [f"**{headers[i]}**: {cells[i]}" for i in range(len(headers)) if cells[i]]
+ if parts:
+ rows.append(" · ".join(parts))
+ return "\n".join(rows)
diff --git a/deeptutor/tutorbot/channels/telegram.py b/deeptutor/tutorbot/channels/telegram.py
new file mode 100644
index 000000000..abc4a6de8
--- /dev/null
+++ b/deeptutor/tutorbot/channels/telegram.py
@@ -0,0 +1,801 @@
+"""Telegram channel implementation using python-telegram-bot."""
+
+from __future__ import annotations
+
+import asyncio
+import re
+import time
+import unicodedata
+from typing import Any, Literal
+
+from loguru import logger
+from pydantic import Field
+from telegram import BotCommand, ReplyParameters, Update
+from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
+from telegram.request import HTTPXRequest
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.paths import get_media_dir
+from deeptutor.tutorbot.config.schema import Base
+from deeptutor.tutorbot.utils.helpers import split_message
+
+TELEGRAM_MAX_MESSAGE_LEN = 4000 # Telegram message character limit
+TELEGRAM_REPLY_CONTEXT_MAX_LEN = TELEGRAM_MAX_MESSAGE_LEN # Max length for reply context in user message
+
+
+def _strip_md(s: str) -> str:
+ """Strip markdown inline formatting from text."""
+ s = re.sub(r'\*\*(.+?)\*\*', r'\1', s)
+ s = re.sub(r'__(.+?)__', r'\1', s)
+ s = re.sub(r'~~(.+?)~~', r'\1', s)
+ s = re.sub(r'`([^`]+)`', r'\1', s)
+ return s.strip()
+
+
+def _render_table_box(table_lines: list[str]) -> str:
+ """Convert markdown pipe-table to compact aligned text for <pre> display."""
+
+ def dw(s: str) -> int:
+ return sum(2 if unicodedata.east_asian_width(c) in ('W', 'F') else 1 for c in s)
+
+ rows: list[list[str]] = []
+ has_sep = False
+ for line in table_lines:
+ cells = [_strip_md(c) for c in line.strip().strip('|').split('|')]
+ if all(re.match(r'^:?-+:?$', c) for c in cells if c):
+ has_sep = True
+ continue
+ rows.append(cells)
+ if not rows or not has_sep:
+ return '\n'.join(table_lines)
+
+ ncols = max(len(r) for r in rows)
+ for r in rows:
+ r.extend([''] * (ncols - len(r)))
+ widths = [max(dw(r[c]) for r in rows) for c in range(ncols)]
+
+ def dr(cells: list[str]) -> str:
+ return ' '.join(f'{c}{" " * (w - dw(c))}' for c, w in zip(cells, widths))
+
+ out = [dr(rows[0])]
+ out.append(' '.join('─' * w for w in widths))
+ for row in rows[1:]:
+ out.append(dr(row))
+ return '\n'.join(out)
+
+
+def _markdown_to_telegram_html(text: str) -> str:
+ """
+ Convert markdown to Telegram-safe HTML.
+ """
+ if not text:
+ return ""
+
+ # 1. Extract and protect code blocks (preserve content from other processing)
+ code_blocks: list[str] = []
+ def save_code_block(m: re.Match) -> str:
+ code_blocks.append(m.group(1))
+ return f"\x00CB{len(code_blocks) - 1}\x00"
+
+ text = re.sub(r'```[\w]*\n?([\s\S]*?)```', save_code_block, text)
+
+ # 1.5. Convert markdown tables to box-drawing (reuse code_block placeholders)
+ lines = text.split('\n')
+ rebuilt: list[str] = []
+ li = 0
+ while li < len(lines):
+ if re.match(r'^\s*\|.+\|', lines[li]):
+ tbl: list[str] = []
+ while li < len(lines) and re.match(r'^\s*\|.+\|', lines[li]):
+ tbl.append(lines[li])
+ li += 1
+ box = _render_table_box(tbl)
+ if box != '\n'.join(tbl):
+ code_blocks.append(box)
+ rebuilt.append(f"\x00CB{len(code_blocks) - 1}\x00")
+ else:
+ rebuilt.extend(tbl)
+ else:
+ rebuilt.append(lines[li])
+ li += 1
+ text = '\n'.join(rebuilt)
+
+ # 2. Extract and protect inline code
+ inline_codes: list[str] = []
+ def save_inline_code(m: re.Match) -> str:
+ inline_codes.append(m.group(1))
+ return f"\x00IC{len(inline_codes) - 1}\x00"
+
+ text = re.sub(r'`([^`]+)`', save_inline_code, text)
+
+ # 3. Headers # Title -> just the title text
+ text = re.sub(r'^#{1,6}\s+(.+)$', r'\1', text, flags=re.MULTILINE)
+
+ # 4. Blockquotes > text -> just the text (before HTML escaping)
+ text = re.sub(r'^>\s*(.*)$', r'\1', text, flags=re.MULTILINE)
+
+ # 5. Escape HTML special characters
+ text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+ # 6. Links [text](url) - must be before bold/italic to handle nested cases
+ text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', text)
+
+ # 7. Bold **text** or __text__
+ text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text)
+ text = re.sub(r'__(.+?)__', r'<b>\1</b>', text)
+
+ # 8. Italic _text_ (avoid matching inside words like some_var_name)
+ text = re.sub(r'(?<![a-zA-Z0-9])_([^_]+)_(?![a-zA-Z0-9])', r'<i>\1</i>', text)
+
+ # 9. Strikethrough ~~text~~
+ text = re.sub(r'~~(.+?)~~', r'<s>\1</s>', text)
+
+ # 10. Bullet lists - item -> • item
+ text = re.sub(r'^[-*]\s+', '• ', text, flags=re.MULTILINE)
+
+ # 11. Restore inline code with HTML tags
+ for i, code in enumerate(inline_codes):
+ # Escape HTML in code content
+ escaped = code.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ text = text.replace(f"\x00IC{i}\x00", f"<code>{escaped}</code>")
+
+ # 12. Restore code blocks with HTML tags
+ for i, code in enumerate(code_blocks):
+ # Escape HTML in code content
+ escaped = code.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ text = text.replace(f"\x00CB{i}\x00", f"<pre><code>{escaped}</code></pre>")
+
+ return text
+
+
+class TelegramConfig(Base):
+ """Telegram channel configuration."""
+
+ enabled: bool = False
+ token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ proxy: str | None = None
+ reply_to_message: bool = False
+ group_policy: Literal["open", "mention"] = "mention"
+
+
+class TelegramChannel(BaseChannel):
+ """
+ Telegram channel using long polling.
+
+ Simple and reliable - no webhook/public IP needed.
+ """
+
+ name = "telegram"
+ display_name = "Telegram"
+
+ # Commands registered with Telegram's command menu
+ BOT_COMMANDS = [
+ BotCommand("start", "Start the bot"),
+ BotCommand("new", "Start a new conversation"),
+ BotCommand("stop", "Stop the current task"),
+ BotCommand("team", "Start or control nano team mode"),
+ BotCommand("btw", "Run an async side task"),
+ BotCommand("help", "Show available commands"),
+ BotCommand("restart", "Restart the bot"),
+ ]
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return TelegramConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = TelegramConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: TelegramConfig = config
+ self._app: Application | None = None
+ self._chat_ids: dict[str, int] = {} # Map sender_id to chat_id for replies
+ self._typing_tasks: dict[str, asyncio.Task] = {} # chat_id -> typing loop task
+ self._media_group_buffers: dict[str, dict] = {}
+ self._media_group_tasks: dict[str, asyncio.Task] = {}
+ self._message_threads: dict[tuple[str, int], int] = {}
+ self._bot_user_id: int | None = None
+ self._bot_username: str | None = None
+
+ def is_allowed(self, sender_id: str) -> bool:
+ """Preserve Telegram's legacy id|username allowlist matching."""
+ if super().is_allowed(sender_id):
+ return True
+
+ allow_list = getattr(self.config, "allow_from", [])
+ if not allow_list or "*" in allow_list:
+ return False
+
+ sender_str = str(sender_id)
+ if sender_str.count("|") != 1:
+ return False
+
+ sid, username = sender_str.split("|", 1)
+ if not sid.isdigit() or not username:
+ return False
+
+ return sid in allow_list or username in allow_list
+
+ async def start(self) -> None:
+ """Start the Telegram bot with long polling."""
+ if not self.config.token:
+ logger.error("Telegram bot token not configured")
+ return
+
+ self._running = True
+
+ # Build the application with larger connection pool to avoid pool-timeout on long runs
+ req = HTTPXRequest(
+ connection_pool_size=16,
+ pool_timeout=5.0,
+ connect_timeout=30.0,
+ read_timeout=30.0,
+ proxy=self.config.proxy if self.config.proxy else None,
+ )
+ builder = Application.builder().token(self.config.token).request(req).get_updates_request(req)
+ self._app = builder.build()
+ self._app.add_error_handler(self._on_error)
+
+ # Add command handlers
+ self._app.add_handler(CommandHandler("start", self._on_start))
+ self._app.add_handler(CommandHandler("new", self._forward_command))
+ self._app.add_handler(CommandHandler("stop", self._forward_command))
+ self._app.add_handler(CommandHandler("team", self._forward_command))
+ self._app.add_handler(CommandHandler("btw", self._forward_command))
+ self._app.add_handler(CommandHandler("restart", self._forward_command))
+ self._app.add_handler(CommandHandler("help", self._on_help))
+
+ # Add message handler for text, photos, voice, documents
+ self._app.add_handler(
+ MessageHandler(
+ (filters.TEXT | filters.PHOTO | filters.VOICE | filters.AUDIO | filters.Document.ALL)
+ & ~filters.COMMAND,
+ self._on_message
+ )
+ )
+
+ logger.info("Starting Telegram bot (polling mode)...")
+
+ # Initialize and start polling
+ await self._app.initialize()
+ await self._app.start()
+
+ # Get bot info and register command menu
+ bot_info = await self._app.bot.get_me()
+ self._bot_user_id = getattr(bot_info, "id", None)
+ self._bot_username = getattr(bot_info, "username", None)
+ logger.info("Telegram bot @{} connected", bot_info.username)
+
+ try:
+ await self._app.bot.set_my_commands(self.BOT_COMMANDS)
+ logger.debug("Telegram bot commands registered")
+ except Exception as e:
+ logger.warning("Failed to register bot commands: {}", e)
+
+ # Start polling (this runs until stopped)
+ await self._app.updater.start_polling(
+ allowed_updates=["message"],
+ drop_pending_updates=True # Ignore old messages on startup
+ )
+
+ # Keep running until stopped
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop the Telegram bot."""
+ self._running = False
+
+ # Cancel all typing indicators
+ for chat_id in list(self._typing_tasks):
+ self._stop_typing(chat_id)
+
+ for task in self._media_group_tasks.values():
+ task.cancel()
+ self._media_group_tasks.clear()
+ self._media_group_buffers.clear()
+
+ if self._app:
+ logger.info("Stopping Telegram bot...")
+ await self._app.updater.stop()
+ await self._app.stop()
+ await self._app.shutdown()
+ self._app = None
+
+ @staticmethod
+ def _get_media_type(path: str) -> str:
+ """Guess media type from file extension."""
+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""
+ if ext in ("jpg", "jpeg", "png", "gif", "webp"):
+ return "photo"
+ if ext == "ogg":
+ return "voice"
+ if ext in ("mp3", "m4a", "wav", "aac"):
+ return "audio"
+ return "document"
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Telegram."""
+ if not self._app:
+ logger.warning("Telegram bot not running")
+ return
+
+ # Only stop typing indicator for final responses
+ if not msg.metadata.get("_progress", False):
+ self._stop_typing(msg.chat_id)
+
+ try:
+ chat_id = int(msg.chat_id)
+ except ValueError:
+ logger.error("Invalid chat_id: {}", msg.chat_id)
+ return
+ reply_to_message_id = msg.metadata.get("message_id")
+ message_thread_id = msg.metadata.get("message_thread_id")
+ if message_thread_id is None and reply_to_message_id is not None:
+ message_thread_id = self._message_threads.get((msg.chat_id, reply_to_message_id))
+ thread_kwargs = {}
+ if message_thread_id is not None:
+ thread_kwargs["message_thread_id"] = message_thread_id
+
+ reply_params = None
+ if self.config.reply_to_message:
+ if reply_to_message_id:
+ reply_params = ReplyParameters(
+ message_id=reply_to_message_id,
+ allow_sending_without_reply=True
+ )
+
+ # Send media files
+ for media_path in (msg.media or []):
+ try:
+ media_type = self._get_media_type(media_path)
+ sender = {
+ "photo": self._app.bot.send_photo,
+ "voice": self._app.bot.send_voice,
+ "audio": self._app.bot.send_audio,
+ }.get(media_type, self._app.bot.send_document)
+ param = "photo" if media_type == "photo" else media_type if media_type in ("voice", "audio") else "document"
+ with open(media_path, 'rb') as f:
+ await sender(
+ chat_id=chat_id,
+ **{param: f},
+ reply_parameters=reply_params,
+ **thread_kwargs,
+ )
+ except Exception as e:
+ filename = media_path.rsplit("/", 1)[-1]
+ logger.error("Failed to send media {}: {}", media_path, e)
+ await self._app.bot.send_message(
+ chat_id=chat_id,
+ text=f"[Failed to send: {filename}]",
+ reply_parameters=reply_params,
+ **thread_kwargs,
+ )
+
+ # Send text content
+ if msg.content and msg.content != "[empty message]":
+ is_progress = msg.metadata.get("_progress", False)
+
+ for chunk in split_message(msg.content, TELEGRAM_MAX_MESSAGE_LEN):
+ # Final response: simulate streaming via draft, then persist
+ if not is_progress:
+ await self._send_with_streaming(chat_id, chunk, reply_params, thread_kwargs)
+ else:
+ await self._send_text(chat_id, chunk, reply_params, thread_kwargs)
+
+ async def _send_text(
+ self,
+ chat_id: int,
+ text: str,
+ reply_params=None,
+ thread_kwargs: dict | None = None,
+ ) -> None:
+ """Send a plain text message with HTML fallback."""
+ try:
+ html = _markdown_to_telegram_html(text)
+ await self._app.bot.send_message(
+ chat_id=chat_id, text=html, parse_mode="HTML",
+ reply_parameters=reply_params,
+ **(thread_kwargs or {}),
+ )
+ except Exception as e:
+ logger.warning("HTML parse failed, falling back to plain text: {}", e)
+ try:
+ await self._app.bot.send_message(
+ chat_id=chat_id,
+ text=text,
+ reply_parameters=reply_params,
+ **(thread_kwargs or {}),
+ )
+ except Exception as e2:
+ logger.error("Error sending Telegram message: {}", e2)
+
+ async def _send_with_streaming(
+ self,
+ chat_id: int,
+ text: str,
+ reply_params=None,
+ thread_kwargs: dict | None = None,
+ ) -> None:
+ """Simulate streaming via send_message_draft, then persist with send_message."""
+ draft_id = int(time.time() * 1000) % (2**31)
+ try:
+ step = max(len(text) // 8, 40)
+ for i in range(step, len(text), step):
+ await self._app.bot.send_message_draft(
+ chat_id=chat_id, draft_id=draft_id, text=text[:i],
+ )
+ await asyncio.sleep(0.04)
+ await self._app.bot.send_message_draft(
+ chat_id=chat_id, draft_id=draft_id, text=text,
+ )
+ await asyncio.sleep(0.15)
+ except Exception:
+ pass
+ await self._send_text(chat_id, text, reply_params, thread_kwargs)
+
+ async def _on_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Handle /start command."""
+ if not update.message or not update.effective_user:
+ return
+
+ user = update.effective_user
+ await update.message.reply_text(
+ f"👋 Hi {user.first_name}! I'm TutorBot.\n\n"
+ "Send me a message and I'll respond!\n"
+ "Type /help to see available commands."
+ )
+
+ async def _on_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Handle /help command, bypassing ACL so all users can access it."""
+ if not update.message:
+ return
+ await update.message.reply_text(
+ "🐈 TutorBot commands:\n"
+ "/new — Start a new conversation\n"
+ "/stop — Stop the current task\n"
+ "/restart — Restart the bot\n"
+ "/help — Show available commands"
+ )
+
+ @staticmethod
+ def _sender_id(user) -> str:
+ """Build sender_id with username for allowlist matching."""
+ sid = str(user.id)
+ return f"{sid}|{user.username}" if user.username else sid
+
+ @staticmethod
+ def _derive_topic_session_key(message) -> str | None:
+ """Derive topic-scoped session key for non-private Telegram chats."""
+ message_thread_id = getattr(message, "message_thread_id", None)
+ if message.chat.type == "private" or message_thread_id is None:
+ return None
+ return f"telegram:{message.chat_id}:topic:{message_thread_id}"
+
+ @staticmethod
+ def _build_message_metadata(message, user) -> dict:
+ """Build common Telegram inbound metadata payload."""
+ reply_to = getattr(message, "reply_to_message", None)
+ return {
+ "message_id": message.message_id,
+ "user_id": user.id,
+ "username": user.username,
+ "first_name": user.first_name,
+ "is_group": message.chat.type != "private",
+ "message_thread_id": getattr(message, "message_thread_id", None),
+ "is_forum": bool(getattr(message.chat, "is_forum", False)),
+ "reply_to_message_id": getattr(reply_to, "message_id", None) if reply_to else None,
+ }
+
+ @staticmethod
+ def _extract_reply_context(message) -> str | None:
+ """Extract text from the message being replied to, if any."""
+ reply = getattr(message, "reply_to_message", None)
+ if not reply:
+ return None
+ text = getattr(reply, "text", None) or getattr(reply, "caption", None) or ""
+ if len(text) > TELEGRAM_REPLY_CONTEXT_MAX_LEN:
+ text = text[:TELEGRAM_REPLY_CONTEXT_MAX_LEN] + "..."
+ return f"[Reply to: {text}]" if text else None
+
+ async def _download_message_media(
+ self, msg, *, add_failure_content: bool = False
+ ) -> tuple[list[str], list[str]]:
+ """Download media from a message (current or reply). Returns (media_paths, content_parts)."""
+ media_file = None
+ media_type = None
+ if getattr(msg, "photo", None):
+ media_file = msg.photo[-1]
+ media_type = "image"
+ elif getattr(msg, "voice", None):
+ media_file = msg.voice
+ media_type = "voice"
+ elif getattr(msg, "audio", None):
+ media_file = msg.audio
+ media_type = "audio"
+ elif getattr(msg, "document", None):
+ media_file = msg.document
+ media_type = "file"
+ elif getattr(msg, "video", None):
+ media_file = msg.video
+ media_type = "video"
+ elif getattr(msg, "video_note", None):
+ media_file = msg.video_note
+ media_type = "video"
+ elif getattr(msg, "animation", None):
+ media_file = msg.animation
+ media_type = "animation"
+ if not media_file or not self._app:
+ return [], []
+ try:
+ file = await self._app.bot.get_file(media_file.file_id)
+ ext = self._get_extension(
+ media_type,
+ getattr(media_file, "mime_type", None),
+ getattr(media_file, "file_name", None),
+ )
+ media_dir = get_media_dir("telegram")
+ unique_id = getattr(media_file, "file_unique_id", media_file.file_id)
+ file_path = media_dir / f"{unique_id}{ext}"
+ await file.download_to_drive(str(file_path))
+ path_str = str(file_path)
+ if media_type in ("voice", "audio"):
+ transcription = await self.transcribe_audio(file_path)
+ if transcription:
+ logger.info("Transcribed {}: {}...", media_type, transcription[:50])
+ return [path_str], [f"[transcription: {transcription}]"]
+ return [path_str], [f"[{media_type}: {path_str}]"]
+ return [path_str], [f"[{media_type}: {path_str}]"]
+ except Exception as e:
+ logger.warning("Failed to download message media: {}", e)
+ if add_failure_content:
+ return [], [f"[{media_type}: download failed]"]
+ return [], []
+
+ async def _ensure_bot_identity(self) -> tuple[int | None, str | None]:
+ """Load bot identity once and reuse it for mention/reply checks."""
+ if self._bot_user_id is not None or self._bot_username is not None:
+ return self._bot_user_id, self._bot_username
+ if not self._app:
+ return None, None
+ bot_info = await self._app.bot.get_me()
+ self._bot_user_id = getattr(bot_info, "id", None)
+ self._bot_username = getattr(bot_info, "username", None)
+ return self._bot_user_id, self._bot_username
+
+ @staticmethod
+ def _has_mention_entity(
+ text: str,
+ entities,
+ bot_username: str,
+ bot_id: int | None,
+ ) -> bool:
+ """Check Telegram mention entities against the bot username."""
+ handle = f"@{bot_username}".lower()
+ for entity in entities or []:
+ entity_type = getattr(entity, "type", None)
+ if entity_type == "text_mention":
+ user = getattr(entity, "user", None)
+ if user is not None and bot_id is not None and getattr(user, "id", None) == bot_id:
+ return True
+ continue
+ if entity_type != "mention":
+ continue
+ offset = getattr(entity, "offset", None)
+ length = getattr(entity, "length", None)
+ if offset is None or length is None:
+ continue
+ if text[offset : offset + length].lower() == handle:
+ return True
+ return handle in text.lower()
+
+ async def _is_group_message_for_bot(self, message) -> bool:
+ """Allow group messages when policy is open, @mentioned, or replying to the bot."""
+ if message.chat.type == "private" or self.config.group_policy == "open":
+ return True
+
+ bot_id, bot_username = await self._ensure_bot_identity()
+ if bot_username:
+ text = message.text or ""
+ caption = message.caption or ""
+ if self._has_mention_entity(
+ text,
+ getattr(message, "entities", None),
+ bot_username,
+ bot_id,
+ ):
+ return True
+ if self._has_mention_entity(
+ caption,
+ getattr(message, "caption_entities", None),
+ bot_username,
+ bot_id,
+ ):
+ return True
+
+ reply_user = getattr(getattr(message, "reply_to_message", None), "from_user", None)
+ return bool(bot_id and reply_user and reply_user.id == bot_id)
+
+ def _remember_thread_context(self, message) -> None:
+ """Cache topic thread id by chat/message id for follow-up replies."""
+ message_thread_id = getattr(message, "message_thread_id", None)
+ if message_thread_id is None:
+ return
+ key = (str(message.chat_id), message.message_id)
+ self._message_threads[key] = message_thread_id
+ if len(self._message_threads) > 1000:
+ self._message_threads.pop(next(iter(self._message_threads)))
+
+ async def _forward_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Forward slash commands to the bus for unified handling in AgentLoop."""
+ if not update.message or not update.effective_user:
+ return
+ message = update.message
+ user = update.effective_user
+ self._remember_thread_context(message)
+ await self._handle_message(
+ sender_id=self._sender_id(user),
+ chat_id=str(message.chat_id),
+ content=message.text or "",
+ metadata=self._build_message_metadata(message, user),
+ session_key=self._derive_topic_session_key(message),
+ )
+
+ async def _on_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Handle incoming messages (text, photos, voice, documents)."""
+ if not update.message or not update.effective_user:
+ return
+
+ message = update.message
+ user = update.effective_user
+ chat_id = message.chat_id
+ sender_id = self._sender_id(user)
+ self._remember_thread_context(message)
+
+ # Store chat_id for replies
+ self._chat_ids[sender_id] = chat_id
+
+ if not await self._is_group_message_for_bot(message):
+ return
+
+ # Build content from text and/or media
+ content_parts = []
+ media_paths = []
+
+ # Text content
+ if message.text:
+ content_parts.append(message.text)
+ if message.caption:
+ content_parts.append(message.caption)
+
+ # Download current message media
+ current_media_paths, current_media_parts = await self._download_message_media(
+ message, add_failure_content=True
+ )
+ media_paths.extend(current_media_paths)
+ content_parts.extend(current_media_parts)
+ if current_media_paths:
+ logger.debug("Downloaded message media to {}", current_media_paths[0])
+
+ # Reply context: text and/or media from the replied-to message
+ reply = getattr(message, "reply_to_message", None)
+ if reply is not None:
+ reply_ctx = self._extract_reply_context(message)
+ reply_media, reply_media_parts = await self._download_message_media(reply)
+ if reply_media:
+ media_paths = reply_media + media_paths
+ logger.debug("Attached replied-to media: {}", reply_media[0])
+ tag = reply_ctx or (f"[Reply to: {reply_media_parts[0]}]" if reply_media_parts else None)
+ if tag:
+ content_parts.insert(0, tag)
+ content = "\n".join(content_parts) if content_parts else "[empty message]"
+
+ logger.debug("Telegram message from {}: {}...", sender_id, content[:50])
+
+ str_chat_id = str(chat_id)
+ metadata = self._build_message_metadata(message, user)
+ session_key = self._derive_topic_session_key(message)
+
+ # Telegram media groups: buffer briefly, forward as one aggregated turn.
+ if media_group_id := getattr(message, "media_group_id", None):
+ key = f"{str_chat_id}:{media_group_id}"
+ if key not in self._media_group_buffers:
+ self._media_group_buffers[key] = {
+ "sender_id": sender_id, "chat_id": str_chat_id,
+ "contents": [], "media": [],
+ "metadata": metadata,
+ "session_key": session_key,
+ }
+ self._start_typing(str_chat_id)
+ buf = self._media_group_buffers[key]
+ if content and content != "[empty message]":
+ buf["contents"].append(content)
+ buf["media"].extend(media_paths)
+ if key not in self._media_group_tasks:
+ self._media_group_tasks[key] = asyncio.create_task(self._flush_media_group(key))
+ return
+
+ # Start typing indicator before processing
+ self._start_typing(str_chat_id)
+
+ # Forward to the message bus
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=str_chat_id,
+ content=content,
+ media=media_paths,
+ metadata=metadata,
+ session_key=session_key,
+ )
+
+ async def _flush_media_group(self, key: str) -> None:
+ """Wait briefly, then forward buffered media-group as one turn."""
+ try:
+ await asyncio.sleep(0.6)
+ if not (buf := self._media_group_buffers.pop(key, None)):
+ return
+ content = "\n".join(buf["contents"]) or "[empty message]"
+ await self._handle_message(
+ sender_id=buf["sender_id"], chat_id=buf["chat_id"],
+ content=content, media=list(dict.fromkeys(buf["media"])),
+ metadata=buf["metadata"],
+ session_key=buf.get("session_key"),
+ )
+ finally:
+ self._media_group_tasks.pop(key, None)
+
+ def _start_typing(self, chat_id: str) -> None:
+ """Start sending 'typing...' indicator for a chat."""
+ # Cancel any existing typing task for this chat
+ self._stop_typing(chat_id)
+ self._typing_tasks[chat_id] = asyncio.create_task(self._typing_loop(chat_id))
+
+ def _stop_typing(self, chat_id: str) -> None:
+ """Stop the typing indicator for a chat."""
+ task = self._typing_tasks.pop(chat_id, None)
+ if task and not task.done():
+ task.cancel()
+
+ async def _typing_loop(self, chat_id: str) -> None:
+ """Repeatedly send 'typing' action until cancelled."""
+ try:
+ while self._app:
+ await self._app.bot.send_chat_action(chat_id=int(chat_id), action="typing")
+ await asyncio.sleep(4)
+ except asyncio.CancelledError:
+ pass
+ except Exception as e:
+ logger.debug("Typing indicator stopped for {}: {}", chat_id, e)
+
+ async def _on_error(self, update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Log polling / handler errors instead of silently swallowing them."""
+ logger.error("Telegram error: {}", context.error)
+
+ def _get_extension(
+ self,
+ media_type: str,
+ mime_type: str | None,
+ filename: str | None = None,
+ ) -> str:
+ """Get file extension based on media type or original filename."""
+ if mime_type:
+ ext_map = {
+ "image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif",
+ "audio/ogg": ".ogg", "audio/mpeg": ".mp3", "audio/mp4": ".m4a",
+ }
+ if mime_type in ext_map:
+ return ext_map[mime_type]
+
+ type_map = {"image": ".jpg", "voice": ".ogg", "audio": ".mp3", "file": ""}
+ if ext := type_map.get(media_type, ""):
+ return ext
+
+ if filename:
+ from pathlib import Path
+
+ return "".join(Path(filename).suffixes)
+
+ return ""
diff --git a/deeptutor/tutorbot/channels/wecom.py b/deeptutor/tutorbot/channels/wecom.py
new file mode 100644
index 000000000..8cbbf06fe
--- /dev/null
+++ b/deeptutor/tutorbot/channels/wecom.py
@@ -0,0 +1,370 @@
+"""WeCom (Enterprise WeChat) channel implementation using wecom_aibot_sdk."""
+
+import asyncio
+import importlib.util
+import os
+from collections import OrderedDict
+from typing import Any
+
+from loguru import logger
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.paths import get_media_dir
+from deeptutor.tutorbot.config.schema import Base
+from pydantic import Field
+
+WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
+
+class WecomConfig(Base):
+ """WeCom (Enterprise WeChat) AI Bot channel configuration."""
+
+ enabled: bool = False
+ bot_id: str = ""
+ secret: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ welcome_message: str = ""
+
+
+# Message type display mapping
+MSG_TYPE_MAP = {
+ "image": "[image]",
+ "voice": "[voice]",
+ "file": "[file]",
+ "mixed": "[mixed content]",
+}
+
+
+class WecomChannel(BaseChannel):
+ """
+ WeCom (Enterprise WeChat) channel using WebSocket long connection.
+
+ Uses WebSocket to receive events - no public IP or webhook required.
+
+ Requires:
+ - Bot ID and Secret from WeCom AI Bot platform
+ """
+
+ name = "wecom"
+ display_name = "WeCom"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return WecomConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = WecomConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: WecomConfig = config
+ self._client: Any = None
+ self._processed_message_ids: OrderedDict[str, None] = OrderedDict()
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._generate_req_id = None
+ # Store frame headers for each chat to enable replies
+ self._chat_frames: dict[str, Any] = {}
+
+ async def start(self) -> None:
+ """Start the WeCom bot with WebSocket long connection."""
+ if not WECOM_AVAILABLE:
+ logger.error("WeCom SDK not installed. Run: pip install deeptutor[wecom]")
+ return
+
+ if not self.config.bot_id or not self.config.secret:
+ logger.error("WeCom bot_id and secret not configured")
+ return
+
+ from wecom_aibot_sdk import WSClient, generate_req_id
+
+ self._running = True
+ self._loop = asyncio.get_running_loop()
+ self._generate_req_id = generate_req_id
+
+ # Create WebSocket client
+ self._client = WSClient({
+ "bot_id": self.config.bot_id,
+ "secret": self.config.secret,
+ "reconnect_interval": 1000,
+ "max_reconnect_attempts": -1, # Infinite reconnect
+ "heartbeat_interval": 30000,
+ })
+
+ # Register event handlers
+ self._client.on("connected", self._on_connected)
+ self._client.on("authenticated", self._on_authenticated)
+ self._client.on("disconnected", self._on_disconnected)
+ self._client.on("error", self._on_error)
+ self._client.on("message.text", self._on_text_message)
+ self._client.on("message.image", self._on_image_message)
+ self._client.on("message.voice", self._on_voice_message)
+ self._client.on("message.file", self._on_file_message)
+ self._client.on("message.mixed", self._on_mixed_message)
+ self._client.on("event.enter_chat", self._on_enter_chat)
+
+ logger.info("WeCom bot starting with WebSocket long connection")
+ logger.info("No public IP required - using WebSocket to receive events")
+
+ # Connect
+ await self._client.connect_async()
+
+ # Keep running until stopped
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop the WeCom bot."""
+ self._running = False
+ if self._client:
+ await self._client.disconnect()
+ logger.info("WeCom bot stopped")
+
+ async def _on_connected(self, frame: Any) -> None:
+ """Handle WebSocket connected event."""
+ logger.info("WeCom WebSocket connected")
+
+ async def _on_authenticated(self, frame: Any) -> None:
+ """Handle authentication success event."""
+ logger.info("WeCom authenticated successfully")
+
+ async def _on_disconnected(self, frame: Any) -> None:
+ """Handle WebSocket disconnected event."""
+ reason = frame.body if hasattr(frame, 'body') else str(frame)
+ logger.warning("WeCom WebSocket disconnected: {}", reason)
+
+ async def _on_error(self, frame: Any) -> None:
+ """Handle error event."""
+ logger.error("WeCom error: {}", frame)
+
+ async def _on_text_message(self, frame: Any) -> None:
+ """Handle text message."""
+ await self._process_message(frame, "text")
+
+ async def _on_image_message(self, frame: Any) -> None:
+ """Handle image message."""
+ await self._process_message(frame, "image")
+
+ async def _on_voice_message(self, frame: Any) -> None:
+ """Handle voice message."""
+ await self._process_message(frame, "voice")
+
+ async def _on_file_message(self, frame: Any) -> None:
+ """Handle file message."""
+ await self._process_message(frame, "file")
+
+ async def _on_mixed_message(self, frame: Any) -> None:
+ """Handle mixed content message."""
+ await self._process_message(frame, "mixed")
+
+ async def _on_enter_chat(self, frame: Any) -> None:
+ """Handle enter_chat event (user opens chat with bot)."""
+ try:
+ # Extract body from WsFrame dataclass or dict
+ if hasattr(frame, 'body'):
+ body = frame.body or {}
+ elif isinstance(frame, dict):
+ body = frame.get("body", frame)
+ else:
+ body = {}
+
+ chat_id = body.get("chatid", "") if isinstance(body, dict) else ""
+
+ if chat_id and self.config.welcome_message:
+ await self._client.reply_welcome(frame, {
+ "msgtype": "text",
+ "text": {"content": self.config.welcome_message},
+ })
+ except Exception as e:
+ logger.error("Error handling enter_chat: {}", e)
+
+ async def _process_message(self, frame: Any, msg_type: str) -> None:
+ """Process incoming message and forward to bus."""
+ try:
+ # Extract body from WsFrame dataclass or dict
+ if hasattr(frame, 'body'):
+ body = frame.body or {}
+ elif isinstance(frame, dict):
+ body = frame.get("body", frame)
+ else:
+ body = {}
+
+ # Ensure body is a dict
+ if not isinstance(body, dict):
+ logger.warning("Invalid body type: {}", type(body))
+ return
+
+ # Extract message info
+ msg_id = body.get("msgid", "")
+ if not msg_id:
+ msg_id = f"{body.get('chatid', '')}_{body.get('sendertime', '')}"
+
+ # Deduplication check
+ if msg_id in self._processed_message_ids:
+ return
+ self._processed_message_ids[msg_id] = None
+
+ # Trim cache
+ while len(self._processed_message_ids) > 1000:
+ self._processed_message_ids.popitem(last=False)
+
+ # Extract sender info from "from" field (SDK format)
+ from_info = body.get("from", {})
+ sender_id = from_info.get("userid", "unknown") if isinstance(from_info, dict) else "unknown"
+
+ # For single chat, chatid is the sender's userid
+ # For group chat, chatid is provided in body
+ chat_type = body.get("chattype", "single")
+ chat_id = body.get("chatid", sender_id)
+
+ content_parts = []
+
+ if msg_type == "text":
+ text = body.get("text", {}).get("content", "")
+ if text:
+ content_parts.append(text)
+
+ elif msg_type == "image":
+ image_info = body.get("image", {})
+ file_url = image_info.get("url", "")
+ aes_key = image_info.get("aeskey", "")
+
+ if file_url and aes_key:
+ file_path = await self._download_and_save_media(file_url, aes_key, "image")
+ if file_path:
+ filename = os.path.basename(file_path)
+ content_parts.append(f"[image: {filename}]\n[Image: source: {file_path}]")
+ else:
+ content_parts.append("[image: download failed]")
+ else:
+ content_parts.append("[image: download failed]")
+
+ elif msg_type == "voice":
+ voice_info = body.get("voice", {})
+ # Voice message already contains transcribed content from WeCom
+ voice_content = voice_info.get("content", "")
+ if voice_content:
+ content_parts.append(f"[voice] {voice_content}")
+ else:
+ content_parts.append("[voice]")
+
+ elif msg_type == "file":
+ file_info = body.get("file", {})
+ file_url = file_info.get("url", "")
+ aes_key = file_info.get("aeskey", "")
+ file_name = file_info.get("name", "unknown")
+
+ if file_url and aes_key:
+ file_path = await self._download_and_save_media(file_url, aes_key, "file", file_name)
+ if file_path:
+ content_parts.append(f"[file: {file_name}]\n[File: source: {file_path}]")
+ else:
+ content_parts.append(f"[file: {file_name}: download failed]")
+ else:
+ content_parts.append(f"[file: {file_name}: download failed]")
+
+ elif msg_type == "mixed":
+ # Mixed content contains multiple message items
+ msg_items = body.get("mixed", {}).get("item", [])
+ for item in msg_items:
+ item_type = item.get("type", "")
+ if item_type == "text":
+ text = item.get("text", {}).get("content", "")
+ if text:
+ content_parts.append(text)
+ else:
+ content_parts.append(MSG_TYPE_MAP.get(item_type, f"[{item_type}]"))
+
+ else:
+ content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"))
+
+ content = "\n".join(content_parts) if content_parts else ""
+
+ if not content:
+ return
+
+ # Store frame for this chat to enable replies
+ self._chat_frames[chat_id] = frame
+
+ # Forward to message bus
+ # Note: media paths are included in content for broader model compatibility
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=chat_id,
+ content=content,
+ media=None,
+ metadata={
+ "message_id": msg_id,
+ "msg_type": msg_type,
+ "chat_type": chat_type,
+ }
+ )
+
+ except Exception as e:
+ logger.error("Error processing WeCom message: {}", e)
+
+ async def _download_and_save_media(
+ self,
+ file_url: str,
+ aes_key: str,
+ media_type: str,
+ filename: str | None = None,
+ ) -> str | None:
+ """
+ Download and decrypt media from WeCom.
+
+ Returns:
+ file_path or None if download failed
+ """
+ try:
+ data, fname = await self._client.download_file(file_url, aes_key)
+
+ if not data:
+ logger.warning("Failed to download media from WeCom")
+ return None
+
+ media_dir = get_media_dir("wecom")
+ if not filename:
+ filename = fname or f"{media_type}_{hash(file_url) % 100000}"
+ filename = os.path.basename(filename)
+
+ file_path = media_dir / filename
+ file_path.write_bytes(data)
+ logger.debug("Downloaded {} to {}", media_type, file_path)
+ return str(file_path)
+
+ except Exception as e:
+ logger.error("Error downloading media: {}", e)
+ return None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through WeCom."""
+ if not self._client:
+ logger.warning("WeCom client not initialized")
+ return
+
+ try:
+ content = msg.content.strip()
+ if not content:
+ return
+
+ # Get the stored frame for this chat
+ frame = self._chat_frames.get(msg.chat_id)
+ if not frame:
+ logger.warning("No frame found for chat {}, cannot reply", msg.chat_id)
+ return
+
+ # Use streaming reply for better UX
+ stream_id = self._generate_req_id("stream")
+
+ # Send as streaming message with finish=True
+ await self._client.reply_stream(
+ frame,
+ stream_id,
+ content,
+ finish=True,
+ )
+
+ logger.debug("WeCom message sent to {}", msg.chat_id)
+
+ except Exception as e:
+ logger.error("Error sending WeCom message: {}", e)
diff --git a/deeptutor/tutorbot/channels/whatsapp.py b/deeptutor/tutorbot/channels/whatsapp.py
new file mode 100644
index 000000000..2f1876684
--- /dev/null
+++ b/deeptutor/tutorbot/channels/whatsapp.py
@@ -0,0 +1,188 @@
+"""WhatsApp channel implementation using Node.js bridge."""
+
+import asyncio
+import json
+import mimetypes
+from collections import OrderedDict
+from typing import Any
+
+from loguru import logger
+
+from pydantic import Field
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.schema import Base
+
+
+class WhatsAppConfig(Base):
+ """WhatsApp channel configuration."""
+
+ enabled: bool = False
+ bridge_url: str = "ws://localhost:3001"
+ bridge_token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class WhatsAppChannel(BaseChannel):
+ """
+ WhatsApp channel that connects to a Node.js bridge.
+
+ The bridge uses @whiskeysockets/baileys to handle the WhatsApp Web protocol.
+ Communication between Python and Node.js is via WebSocket.
+ """
+
+ name = "whatsapp"
+ display_name = "WhatsApp"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return WhatsAppConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = WhatsAppConfig.model_validate(config)
+ super().__init__(config, bus)
+ self._ws = None
+ self._connected = False
+ self._processed_message_ids: OrderedDict[str, None] = OrderedDict()
+
+ async def start(self) -> None:
+ """Start the WhatsApp channel by connecting to the bridge."""
+ import websockets
+
+ bridge_url = self.config.bridge_url
+
+ logger.info("Connecting to WhatsApp bridge at {}...", bridge_url)
+
+ self._running = True
+
+ while self._running:
+ try:
+ async with websockets.connect(bridge_url) as ws:
+ self._ws = ws
+ # Send auth token if configured
+ if self.config.bridge_token:
+ await ws.send(json.dumps({"type": "auth", "token": self.config.bridge_token}))
+ self._connected = True
+ logger.info("Connected to WhatsApp bridge")
+
+ # Listen for messages
+ async for message in ws:
+ try:
+ await self._handle_bridge_message(message)
+ except Exception as e:
+ logger.error("Error handling bridge message: {}", e)
+
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ self._connected = False
+ self._ws = None
+ logger.warning("WhatsApp bridge connection error: {}", e)
+
+ if self._running:
+ logger.info("Reconnecting in 5 seconds...")
+ await asyncio.sleep(5)
+
+ async def stop(self) -> None:
+ """Stop the WhatsApp channel."""
+ self._running = False
+ self._connected = False
+
+ if self._ws:
+ await self._ws.close()
+ self._ws = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through WhatsApp."""
+ if not self._ws or not self._connected:
+ logger.warning("WhatsApp bridge not connected")
+ return
+
+ try:
+ payload = {
+ "type": "send",
+ "to": msg.chat_id,
+ "text": msg.content
+ }
+ await self._ws.send(json.dumps(payload, ensure_ascii=False))
+ except Exception as e:
+ logger.error("Error sending WhatsApp message: {}", e)
+
+ async def _handle_bridge_message(self, raw: str) -> None:
+ """Handle a message from the bridge."""
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ logger.warning("Invalid JSON from bridge: {}", raw[:100])
+ return
+
+ msg_type = data.get("type")
+
+ if msg_type == "message":
+ # Incoming message from WhatsApp
+ # Deprecated by whatsapp: old phone number style typically: <phone>@s.whatspp.net
+ pn = data.get("pn", "")
+ # New LID sytle typically:
+ sender = data.get("sender", "")
+ content = data.get("content", "")
+ message_id = data.get("id", "")
+
+ if message_id:
+ if message_id in self._processed_message_ids:
+ return
+ self._processed_message_ids[message_id] = None
+ while len(self._processed_message_ids) > 1000:
+ self._processed_message_ids.popitem(last=False)
+
+ # Extract just the phone number or lid as chat_id
+ user_id = pn if pn else sender
+ sender_id = user_id.split("@")[0] if "@" in user_id else user_id
+ logger.info("Sender {}", sender)
+
+ # Handle voice transcription if it's a voice message
+ if content == "[Voice Message]":
+ logger.info("Voice message received from {}, but direct download from bridge is not yet supported.", sender_id)
+ content = "[Voice Message: Transcription not available for WhatsApp yet]"
+
+ # Extract media paths (images/documents/videos downloaded by the bridge)
+ media_paths = data.get("media") or []
+
+ # Build content tags matching Telegram's pattern: [image: /path] or [file: /path]
+ if media_paths:
+ for p in media_paths:
+ mime, _ = mimetypes.guess_type(p)
+ media_type = "image" if mime and mime.startswith("image/") else "file"
+ media_tag = f"[{media_type}: {p}]"
+ content = f"{content}\n{media_tag}" if content else media_tag
+
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=sender, # Use full LID for replies
+ content=content,
+ media=media_paths,
+ metadata={
+ "message_id": message_id,
+ "timestamp": data.get("timestamp"),
+ "is_group": data.get("isGroup", False)
+ }
+ )
+
+ elif msg_type == "status":
+ # Connection status update
+ status = data.get("status")
+ logger.info("WhatsApp status: {}", status)
+
+ if status == "connected":
+ self._connected = True
+ elif status == "disconnected":
+ self._connected = False
+
+ elif msg_type == "qr":
+ # QR code for authentication
+ logger.info("Scan QR code in the bridge terminal to connect WhatsApp")
+
+ elif msg_type == "error":
+ logger.error("WhatsApp bridge error: {}", data.get('error'))
diff --git a/deeptutor/tutorbot/config/__init__.py b/deeptutor/tutorbot/config/__init__.py
new file mode 100644
index 000000000..78ffc48cb
--- /dev/null
+++ b/deeptutor/tutorbot/config/__init__.py
@@ -0,0 +1,31 @@
+"""Configuration module for TutorBot."""
+
+from deeptutor.tutorbot.config.paths import (
+ get_cron_dir,
+ get_data_dir,
+ get_legacy_sessions_dir,
+ get_logs_dir,
+ get_media_dir,
+ get_runtime_subdir,
+ get_workspace_path,
+)
+from deeptutor.tutorbot.config.schema import (
+ ChannelsConfig,
+ ExecToolConfig,
+ ToolsConfig,
+ WebSearchConfig,
+)
+
+__all__ = [
+ "ChannelsConfig",
+ "ExecToolConfig",
+ "ToolsConfig",
+ "WebSearchConfig",
+ "get_cron_dir",
+ "get_data_dir",
+ "get_legacy_sessions_dir",
+ "get_logs_dir",
+ "get_media_dir",
+ "get_runtime_subdir",
+ "get_workspace_path",
+]
diff --git a/deeptutor/tutorbot/config/paths.py b/deeptutor/tutorbot/config/paths.py
new file mode 100644
index 000000000..750c46ce0
--- /dev/null
+++ b/deeptutor/tutorbot/config/paths.py
@@ -0,0 +1,74 @@
+"""Path helpers for TutorBot — delegates to DeepTutor's PathService."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.tutorbot.utils.helpers import ensure_dir
+
+
+def _base_dir() -> Path:
+ from deeptutor.services.path_service import get_path_service
+ return ensure_dir(get_path_service().project_root / "data" / "tutorbot")
+
+
+def get_data_dir() -> Path:
+ return _base_dir()
+
+
+def get_runtime_subdir(name: str) -> Path:
+ return ensure_dir(_base_dir() / name)
+
+
+def get_media_dir(channel: str | None = None) -> Path:
+ base = get_runtime_subdir("media")
+ return ensure_dir(base / channel) if channel else base
+
+
+def get_cron_dir() -> Path:
+ return get_runtime_subdir("cron")
+
+
+def get_logs_dir() -> Path:
+ return get_runtime_subdir("logs")
+
+
+def get_workspace_path(workspace: str | None = None) -> Path:
+ if workspace:
+ return ensure_dir(Path(workspace).expanduser())
+ return ensure_dir(_base_dir() / "workspace")
+
+
+def get_legacy_sessions_dir() -> Path:
+ return _base_dir() / "sessions"
+
+
+def get_shared_memory_dir() -> Path:
+ """Public memory shared by DeepTutor and all bots: data/memory/."""
+ from deeptutor.services.path_service import get_path_service
+ return ensure_dir(get_path_service().project_root / "data" / "memory")
+
+
+# ── Per-bot path helpers ──────────────────────────────────────────
+
+
+def get_bot_dir(bot_id: str) -> Path:
+ """data/tutorbot/{bot_id}/ — flat layout, no bots/ sub-directory."""
+ return ensure_dir(_base_dir() / bot_id)
+
+
+def get_bot_workspace(bot_id: str) -> Path:
+ return ensure_dir(get_bot_dir(bot_id) / "workspace")
+
+
+def get_bot_cron_dir(bot_id: str) -> Path:
+ return ensure_dir(get_bot_dir(bot_id) / "cron")
+
+
+def get_bot_logs_dir(bot_id: str) -> Path:
+ return ensure_dir(get_bot_dir(bot_id) / "logs")
+
+
+def get_bot_media_dir(bot_id: str, channel: str | None = None) -> Path:
+ base = ensure_dir(get_bot_dir(bot_id) / "media")
+ return ensure_dir(base / channel) if channel else base
diff --git a/deeptutor/tutorbot/config/schema.py b/deeptutor/tutorbot/config/schema.py
new file mode 100644
index 000000000..e2ff2f091
--- /dev/null
+++ b/deeptutor/tutorbot/config/schema.py
@@ -0,0 +1,155 @@
+"""Configuration schema — Pydantic models for TutorBot channels, tools, and agent settings."""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+from pydantic.alias_generators import to_camel
+
+
+class Base(BaseModel):
+ """Base model that accepts both camelCase and snake_case keys."""
+
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
+
+
+class ChannelsConfig(Base):
+ """Configuration for chat channels.
+
+ Built-in and plugin channel configs are stored as extra fields (dicts).
+ Each channel parses its own config in __init__.
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ send_progress: bool = True # stream agent's text progress to the channel
+ send_tool_hints: bool = False # stream tool-call hints (e.g. read_file("…"))
+
+
+class AgentDefaults(Base):
+ """Default agent configuration."""
+
+ workspace: str = "~/.deeptutor/tutorbot/workspace"
+ model: str = "anthropic/claude-opus-4-5"
+ provider: str = (
+ "auto" # Provider name (e.g. "anthropic", "openrouter") or "auto" for auto-detection
+ )
+ max_tokens: int = 8192
+ context_window_tokens: int = 65_536
+ temperature: float = 0.1
+ max_tool_iterations: int = 40
+ # Deprecated compatibility field: accepted from old configs but ignored at runtime.
+ memory_window: int | None = Field(default=None, exclude=True)
+ reasoning_effort: str | None = None # low / medium / high — enables LLM thinking mode
+ team_max_workers: int = 5
+ team_worker_max_iterations: int = 25
+
+ @property
+ def should_warn_deprecated_memory_window(self) -> bool:
+ """Return True when old memoryWindow is present without contextWindowTokens."""
+ return self.memory_window is not None and "context_window_tokens" not in self.model_fields_set
+
+
+class AgentsConfig(Base):
+ """Agent configuration."""
+
+ defaults: AgentDefaults = Field(default_factory=AgentDefaults)
+
+
+class ProviderConfig(Base):
+ """LLM provider configuration."""
+
+ api_key: str = ""
+ api_base: str | None = None
+ extra_headers: dict[str, str] | None = None # Custom headers (e.g. APP-Code for AiHubMix)
+
+
+class ProvidersConfig(Base):
+ """Configuration for LLM providers."""
+
+ custom: ProviderConfig = Field(default_factory=ProviderConfig) # Any OpenAI-compatible endpoint
+ azure_openai: ProviderConfig = Field(default_factory=ProviderConfig) # Azure OpenAI (model = deployment name)
+ anthropic: ProviderConfig = Field(default_factory=ProviderConfig)
+ openai: ProviderConfig = Field(default_factory=ProviderConfig)
+ openrouter: ProviderConfig = Field(default_factory=ProviderConfig)
+ deepseek: ProviderConfig = Field(default_factory=ProviderConfig)
+ groq: ProviderConfig = Field(default_factory=ProviderConfig)
+ zhipu: ProviderConfig = Field(default_factory=ProviderConfig)
+ dashscope: ProviderConfig = Field(default_factory=ProviderConfig)
+ vllm: ProviderConfig = Field(default_factory=ProviderConfig)
+ ollama: ProviderConfig = Field(default_factory=ProviderConfig) # Ollama local models
+ gemini: ProviderConfig = Field(default_factory=ProviderConfig)
+ moonshot: ProviderConfig = Field(default_factory=ProviderConfig)
+ minimax: ProviderConfig = Field(default_factory=ProviderConfig)
+ aihubmix: ProviderConfig = Field(default_factory=ProviderConfig) # AiHubMix API gateway
+ siliconflow: ProviderConfig = Field(default_factory=ProviderConfig) # SiliconFlow (硅基流动)
+ volcengine: ProviderConfig = Field(default_factory=ProviderConfig) # VolcEngine (火山引擎)
+ volcengine_coding_plan: ProviderConfig = Field(default_factory=ProviderConfig) # VolcEngine Coding Plan
+ byteplus: ProviderConfig = Field(default_factory=ProviderConfig) # BytePlus (VolcEngine international)
+ byteplus_coding_plan: ProviderConfig = Field(default_factory=ProviderConfig) # BytePlus Coding Plan
+ openai_codex: ProviderConfig = Field(default_factory=ProviderConfig) # OpenAI Codex (OAuth)
+ github_copilot: ProviderConfig = Field(default_factory=ProviderConfig) # Github Copilot (OAuth)
+
+
+class HeartbeatConfig(Base):
+ """Heartbeat service configuration."""
+
+ enabled: bool = True
+ interval_s: int = 30 * 60 # 30 minutes
+
+
+class GatewayConfig(Base):
+ """Gateway/server configuration."""
+
+ host: str = "0.0.0.0"
+ port: int = 18790
+ heartbeat: HeartbeatConfig = Field(default_factory=HeartbeatConfig)
+
+
+class WebSearchConfig(Base):
+ """Web search tool configuration."""
+
+ provider: str = "brave" # brave, tavily, duckduckgo, searxng, jina
+ api_key: str = ""
+ base_url: str = "" # SearXNG base URL
+ max_results: int = 5
+
+
+class WebToolsConfig(Base):
+ """Web tools configuration."""
+
+ proxy: str | None = (
+ None # HTTP/SOCKS5 proxy URL, e.g. "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080"
+ )
+ search: WebSearchConfig = Field(default_factory=WebSearchConfig)
+
+
+class ExecToolConfig(Base):
+ """Shell exec tool configuration."""
+
+ timeout: int = 60
+ path_append: str = ""
+
+
+class MCPServerConfig(Base):
+ """MCP server connection configuration (stdio or HTTP)."""
+
+ type: Literal["stdio", "sse", "streamableHttp"] | None = None # auto-detected if omitted
+ command: str = "" # Stdio: command to run (e.g. "npx")
+ args: list[str] = Field(default_factory=list) # Stdio: command arguments
+ env: dict[str, str] = Field(default_factory=dict) # Stdio: extra env vars
+ url: str = "" # HTTP/SSE: endpoint URL
+ headers: dict[str, str] = Field(default_factory=dict) # HTTP/SSE: custom headers
+ tool_timeout: int = 30 # seconds before a tool call is cancelled
+ enabled_tools: list[str] = Field(default_factory=lambda: ["*"]) # Only register these tools; accepts raw MCP names or wrapped mcp_<server>_<tool> names; ["*"] = all tools; [] = no tools
+
+class ToolsConfig(Base):
+ """Tools configuration."""
+
+ web: WebToolsConfig = Field(default_factory=WebToolsConfig)
+ exec: ExecToolConfig = Field(default_factory=ExecToolConfig)
+ restrict_to_workspace: bool = False # If true, restrict all tool access to workspace directory
+ mcp_servers: dict[str, MCPServerConfig] = Field(default_factory=dict)
+
+
diff --git a/deeptutor/tutorbot/cron/__init__.py b/deeptutor/tutorbot/cron/__init__.py
new file mode 100644
index 000000000..37b3250f9
--- /dev/null
+++ b/deeptutor/tutorbot/cron/__init__.py
@@ -0,0 +1,6 @@
+"""Cron service for scheduled agent tasks."""
+
+from deeptutor.tutorbot.cron.service import CronService
+from deeptutor.tutorbot.cron.types import CronJob, CronSchedule
+
+__all__ = ["CronService", "CronJob", "CronSchedule"]
diff --git a/deeptutor/tutorbot/cron/service.py b/deeptutor/tutorbot/cron/service.py
new file mode 100644
index 000000000..1ba5b3ef7
--- /dev/null
+++ b/deeptutor/tutorbot/cron/service.py
@@ -0,0 +1,376 @@
+"""Cron service for scheduling agent tasks."""
+
+import asyncio
+import json
+import time
+import uuid
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Callable, Coroutine
+
+from loguru import logger
+
+from deeptutor.tutorbot.cron.types import CronJob, CronJobState, CronPayload, CronSchedule, CronStore
+
+
+def _now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:
+ """Compute next run time in ms."""
+ if schedule.kind == "at":
+ return schedule.at_ms if schedule.at_ms and schedule.at_ms > now_ms else None
+
+ if schedule.kind == "every":
+ if not schedule.every_ms or schedule.every_ms <= 0:
+ return None
+ # Next interval from now
+ return now_ms + schedule.every_ms
+
+ if schedule.kind == "cron" and schedule.expr:
+ try:
+ from zoneinfo import ZoneInfo
+
+ from croniter import croniter
+ # Use caller-provided reference time for deterministic scheduling
+ base_time = now_ms / 1000
+ tz = ZoneInfo(schedule.tz) if schedule.tz else datetime.now().astimezone().tzinfo
+ base_dt = datetime.fromtimestamp(base_time, tz=tz)
+ cron = croniter(schedule.expr, base_dt)
+ next_dt = cron.get_next(datetime)
+ return int(next_dt.timestamp() * 1000)
+ except Exception:
+ return None
+
+ return None
+
+
+def _validate_schedule_for_add(schedule: CronSchedule) -> None:
+ """Validate schedule fields that would otherwise create non-runnable jobs."""
+ if schedule.tz and schedule.kind != "cron":
+ raise ValueError("tz can only be used with cron schedules")
+
+ if schedule.kind == "cron" and schedule.tz:
+ try:
+ from zoneinfo import ZoneInfo
+
+ ZoneInfo(schedule.tz)
+ except Exception:
+ raise ValueError(f"unknown timezone '{schedule.tz}'") from None
+
+
+class CronService:
+ """Service for managing and executing scheduled jobs."""
+
+ def __init__(
+ self,
+ store_path: Path,
+ on_job: Callable[[CronJob], Coroutine[Any, Any, str | None]] | None = None
+ ):
+ self.store_path = store_path
+ self.on_job = on_job
+ self._store: CronStore | None = None
+ self._last_mtime: float = 0.0
+ self._timer_task: asyncio.Task | None = None
+ self._running = False
+
+ def _load_store(self) -> CronStore:
+ """Load jobs from disk. Reloads automatically if file was modified externally."""
+ if self._store and self.store_path.exists():
+ mtime = self.store_path.stat().st_mtime
+ if mtime != self._last_mtime:
+ logger.info("Cron: jobs.json modified externally, reloading")
+ self._store = None
+ if self._store:
+ return self._store
+
+ if self.store_path.exists():
+ try:
+ data = json.loads(self.store_path.read_text(encoding="utf-8"))
+ jobs = []
+ for j in data.get("jobs", []):
+ jobs.append(CronJob(
+ id=j["id"],
+ name=j["name"],
+ enabled=j.get("enabled", True),
+ schedule=CronSchedule(
+ kind=j["schedule"]["kind"],
+ at_ms=j["schedule"].get("atMs"),
+ every_ms=j["schedule"].get("everyMs"),
+ expr=j["schedule"].get("expr"),
+ tz=j["schedule"].get("tz"),
+ ),
+ payload=CronPayload(
+ kind=j["payload"].get("kind", "agent_turn"),
+ message=j["payload"].get("message", ""),
+ deliver=j["payload"].get("deliver", False),
+ channel=j["payload"].get("channel"),
+ to=j["payload"].get("to"),
+ ),
+ state=CronJobState(
+ next_run_at_ms=j.get("state", {}).get("nextRunAtMs"),
+ last_run_at_ms=j.get("state", {}).get("lastRunAtMs"),
+ last_status=j.get("state", {}).get("lastStatus"),
+ last_error=j.get("state", {}).get("lastError"),
+ ),
+ created_at_ms=j.get("createdAtMs", 0),
+ updated_at_ms=j.get("updatedAtMs", 0),
+ delete_after_run=j.get("deleteAfterRun", False),
+ ))
+ self._store = CronStore(jobs=jobs)
+ except Exception as e:
+ logger.warning("Failed to load cron store: {}", e)
+ self._store = CronStore()
+ else:
+ self._store = CronStore()
+
+ return self._store
+
+ def _save_store(self) -> None:
+ """Save jobs to disk."""
+ if not self._store:
+ return
+
+ self.store_path.parent.mkdir(parents=True, exist_ok=True)
+
+ data = {
+ "version": self._store.version,
+ "jobs": [
+ {
+ "id": j.id,
+ "name": j.name,
+ "enabled": j.enabled,
+ "schedule": {
+ "kind": j.schedule.kind,
+ "atMs": j.schedule.at_ms,
+ "everyMs": j.schedule.every_ms,
+ "expr": j.schedule.expr,
+ "tz": j.schedule.tz,
+ },
+ "payload": {
+ "kind": j.payload.kind,
+ "message": j.payload.message,
+ "deliver": j.payload.deliver,
+ "channel": j.payload.channel,
+ "to": j.payload.to,
+ },
+ "state": {
+ "nextRunAtMs": j.state.next_run_at_ms,
+ "lastRunAtMs": j.state.last_run_at_ms,
+ "lastStatus": j.state.last_status,
+ "lastError": j.state.last_error,
+ },
+ "createdAtMs": j.created_at_ms,
+ "updatedAtMs": j.updated_at_ms,
+ "deleteAfterRun": j.delete_after_run,
+ }
+ for j in self._store.jobs
+ ]
+ }
+
+ self.store_path.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
+ self._last_mtime = self.store_path.stat().st_mtime
+
+ async def start(self) -> None:
+ """Start the cron service."""
+ self._running = True
+ self._load_store()
+ self._recompute_next_runs()
+ self._save_store()
+ self._arm_timer()
+ logger.info("Cron service started with {} jobs", len(self._store.jobs if self._store else []))
+
+ def stop(self) -> None:
+ """Stop the cron service."""
+ self._running = False
+ if self._timer_task:
+ self._timer_task.cancel()
+ self._timer_task = None
+
+ def _recompute_next_runs(self) -> None:
+ """Recompute next run times for all enabled jobs."""
+ if not self._store:
+ return
+ now = _now_ms()
+ for job in self._store.jobs:
+ if job.enabled:
+ job.state.next_run_at_ms = _compute_next_run(job.schedule, now)
+
+ def _get_next_wake_ms(self) -> int | None:
+ """Get the earliest next run time across all jobs."""
+ if not self._store:
+ return None
+ times = [j.state.next_run_at_ms for j in self._store.jobs
+ if j.enabled and j.state.next_run_at_ms]
+ return min(times) if times else None
+
+ def _arm_timer(self) -> None:
+ """Schedule the next timer tick."""
+ if self._timer_task:
+ self._timer_task.cancel()
+
+ next_wake = self._get_next_wake_ms()
+ if not next_wake or not self._running:
+ return
+
+ delay_ms = max(0, next_wake - _now_ms())
+ delay_s = delay_ms / 1000
+
+ async def tick():
+ await asyncio.sleep(delay_s)
+ if self._running:
+ await self._on_timer()
+
+ self._timer_task = asyncio.create_task(tick())
+
+ async def _on_timer(self) -> None:
+ """Handle timer tick - run due jobs."""
+ self._load_store()
+ if not self._store:
+ return
+
+ now = _now_ms()
+ due_jobs = [
+ j for j in self._store.jobs
+ if j.enabled and j.state.next_run_at_ms and now >= j.state.next_run_at_ms
+ ]
+
+ for job in due_jobs:
+ await self._execute_job(job)
+
+ self._save_store()
+ self._arm_timer()
+
+ async def _execute_job(self, job: CronJob) -> None:
+ """Execute a single job."""
+ start_ms = _now_ms()
+ logger.info("Cron: executing job '{}' ({})", job.name, job.id)
+
+ try:
+ response = None
+ if self.on_job:
+ response = await self.on_job(job)
+
+ job.state.last_status = "ok"
+ job.state.last_error = None
+ logger.info("Cron: job '{}' completed", job.name)
+
+ except Exception as e:
+ job.state.last_status = "error"
+ job.state.last_error = str(e)
+ logger.error("Cron: job '{}' failed: {}", job.name, e)
+
+ job.state.last_run_at_ms = start_ms
+ job.updated_at_ms = _now_ms()
+
+ # Handle one-shot jobs
+ if job.schedule.kind == "at":
+ if job.delete_after_run:
+ self._store.jobs = [j for j in self._store.jobs if j.id != job.id]
+ else:
+ job.enabled = False
+ job.state.next_run_at_ms = None
+ else:
+ # Compute next run
+ job.state.next_run_at_ms = _compute_next_run(job.schedule, _now_ms())
+
+ # ========== Public API ==========
+
+ def list_jobs(self, include_disabled: bool = False) -> list[CronJob]:
+ """List all jobs."""
+ store = self._load_store()
+ jobs = store.jobs if include_disabled else [j for j in store.jobs if j.enabled]
+ return sorted(jobs, key=lambda j: j.state.next_run_at_ms or float('inf'))
+
+ def add_job(
+ self,
+ name: str,
+ schedule: CronSchedule,
+ message: str,
+ deliver: bool = False,
+ channel: str | None = None,
+ to: str | None = None,
+ delete_after_run: bool = False,
+ ) -> CronJob:
+ """Add a new job."""
+ store = self._load_store()
+ _validate_schedule_for_add(schedule)
+ now = _now_ms()
+
+ job = CronJob(
+ id=str(uuid.uuid4())[:8],
+ name=name,
+ enabled=True,
+ schedule=schedule,
+ payload=CronPayload(
+ kind="agent_turn",
+ message=message,
+ deliver=deliver,
+ channel=channel,
+ to=to,
+ ),
+ state=CronJobState(next_run_at_ms=_compute_next_run(schedule, now)),
+ created_at_ms=now,
+ updated_at_ms=now,
+ delete_after_run=delete_after_run,
+ )
+
+ store.jobs.append(job)
+ self._save_store()
+ self._arm_timer()
+
+ logger.info("Cron: added job '{}' ({})", name, job.id)
+ return job
+
+ def remove_job(self, job_id: str) -> bool:
+ """Remove a job by ID."""
+ store = self._load_store()
+ before = len(store.jobs)
+ store.jobs = [j for j in store.jobs if j.id != job_id]
+ removed = len(store.jobs) < before
+
+ if removed:
+ self._save_store()
+ self._arm_timer()
+ logger.info("Cron: removed job {}", job_id)
+
+ return removed
+
+ def enable_job(self, job_id: str, enabled: bool = True) -> CronJob | None:
+ """Enable or disable a job."""
+ store = self._load_store()
+ for job in store.jobs:
+ if job.id == job_id:
+ job.enabled = enabled
+ job.updated_at_ms = _now_ms()
+ if enabled:
+ job.state.next_run_at_ms = _compute_next_run(job.schedule, _now_ms())
+ else:
+ job.state.next_run_at_ms = None
+ self._save_store()
+ self._arm_timer()
+ return job
+ return None
+
+ async def run_job(self, job_id: str, force: bool = False) -> bool:
+ """Manually run a job."""
+ store = self._load_store()
+ for job in store.jobs:
+ if job.id == job_id:
+ if not force and not job.enabled:
+ return False
+ await self._execute_job(job)
+ self._save_store()
+ self._arm_timer()
+ return True
+ return False
+
+ def status(self) -> dict:
+ """Get service status."""
+ store = self._load_store()
+ return {
+ "enabled": self._running,
+ "jobs": len(store.jobs),
+ "next_wake_at_ms": self._get_next_wake_ms(),
+ }
diff --git a/deeptutor/tutorbot/cron/types.py b/deeptutor/tutorbot/cron/types.py
new file mode 100644
index 000000000..2b4206057
--- /dev/null
+++ b/deeptutor/tutorbot/cron/types.py
@@ -0,0 +1,59 @@
+"""Cron types."""
+
+from dataclasses import dataclass, field
+from typing import Literal
+
+
+@dataclass
+class CronSchedule:
+ """Schedule definition for a cron job."""
+ kind: Literal["at", "every", "cron"]
+ # For "at": timestamp in ms
+ at_ms: int | None = None
+ # For "every": interval in ms
+ every_ms: int | None = None
+ # For "cron": cron expression (e.g. "0 9 * * *")
+ expr: str | None = None
+ # Timezone for cron expressions
+ tz: str | None = None
+
+
+@dataclass
+class CronPayload:
+ """What to do when the job runs."""
+ kind: Literal["system_event", "agent_turn"] = "agent_turn"
+ message: str = ""
+ # Deliver response to channel
+ deliver: bool = False
+ channel: str | None = None # e.g. "whatsapp"
+ to: str | None = None # e.g. phone number
+
+
+@dataclass
+class CronJobState:
+ """Runtime state of a job."""
+ next_run_at_ms: int | None = None
+ last_run_at_ms: int | None = None
+ last_status: Literal["ok", "error", "skipped"] | None = None
+ last_error: str | None = None
+
+
+@dataclass
+class CronJob:
+ """A scheduled job."""
+ id: str
+ name: str
+ enabled: bool = True
+ schedule: CronSchedule = field(default_factory=lambda: CronSchedule(kind="every"))
+ payload: CronPayload = field(default_factory=CronPayload)
+ state: CronJobState = field(default_factory=CronJobState)
+ created_at_ms: int = 0
+ updated_at_ms: int = 0
+ delete_after_run: bool = False
+
+
+@dataclass
+class CronStore:
+ """Persistent store for cron jobs."""
+ version: int = 1
+ jobs: list[CronJob] = field(default_factory=list)
diff --git a/deeptutor/tutorbot/heartbeat/__init__.py b/deeptutor/tutorbot/heartbeat/__init__.py
new file mode 100644
index 000000000..646c330fc
--- /dev/null
+++ b/deeptutor/tutorbot/heartbeat/__init__.py
@@ -0,0 +1,5 @@
+"""Heartbeat service for periodic agent wake-ups."""
+
+from deeptutor.tutorbot.heartbeat.service import HeartbeatService
+
+__all__ = ["HeartbeatService"]
diff --git a/deeptutor/tutorbot/heartbeat/service.py b/deeptutor/tutorbot/heartbeat/service.py
new file mode 100644
index 000000000..d7d9c3448
--- /dev/null
+++ b/deeptutor/tutorbot/heartbeat/service.py
@@ -0,0 +1,182 @@
+"""Heartbeat service - periodic agent wake-up to check for tasks."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Callable, Coroutine
+
+from loguru import logger
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.providers.base import LLMProvider
+
+_HEARTBEAT_TOOL = [
+ {
+ "type": "function",
+ "function": {
+ "name": "heartbeat",
+ "description": "Report heartbeat decision after reviewing tasks.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["skip", "run"],
+ "description": "skip = nothing to do, run = has active tasks",
+ },
+ "tasks": {
+ "type": "string",
+ "description": "Natural-language summary of active tasks (required for run)",
+ },
+ },
+ "required": ["action"],
+ },
+ },
+ }
+]
+
+
+class HeartbeatService:
+ """
+ Periodic heartbeat service that wakes the agent to check for tasks.
+
+ Phase 1 (decision): reads HEARTBEAT.md and asks the LLM — via a virtual
+ tool call — whether there are active tasks. This avoids free-text parsing
+ and the unreliable HEARTBEAT_OK token.
+
+ Phase 2 (execution): only triggered when Phase 1 returns ``run``. The
+ ``on_execute`` callback runs the task through the full agent loop and
+ returns the result to deliver.
+ """
+
+ def __init__(
+ self,
+ workspace: Path,
+ provider: LLMProvider,
+ model: str,
+ on_execute: Callable[[str], Coroutine[Any, Any, str]] | None = None,
+ on_notify: Callable[[str], Coroutine[Any, Any, None]] | None = None,
+ interval_s: int = 30 * 60,
+ enabled: bool = True,
+ ):
+ self.workspace = workspace
+ self.provider = provider
+ self.model = model
+ self.on_execute = on_execute
+ self.on_notify = on_notify
+ self.interval_s = interval_s
+ self.enabled = enabled
+ self._running = False
+ self._task: asyncio.Task | None = None
+
+ @property
+ def heartbeat_file(self) -> Path:
+ return self.workspace / "HEARTBEAT.md"
+
+ def _read_heartbeat_file(self) -> str | None:
+ if self.heartbeat_file.exists():
+ try:
+ return self.heartbeat_file.read_text(encoding="utf-8")
+ except Exception:
+ return None
+ return None
+
+ async def _decide(self, content: str) -> tuple[str, str]:
+ """Phase 1: ask LLM to decide skip/run via virtual tool call.
+
+ Returns (action, tasks) where action is 'skip' or 'run'.
+ """
+ response = await self.provider.chat_with_retry(
+ messages=[
+ {"role": "system", "content": "You are a heartbeat agent. Call the heartbeat tool to report your decision."},
+ {"role": "user", "content": (
+ "Review the following HEARTBEAT.md and decide whether there are active tasks.\n\n"
+ f"{content}"
+ )},
+ ],
+ tools=_HEARTBEAT_TOOL,
+ model=self.model,
+ )
+
+ if not response.has_tool_calls:
+ return "skip", ""
+
+ args = response.tool_calls[0].arguments
+ return args.get("action", "skip"), args.get("tasks", "")
+
+ async def start(self) -> None:
+ """Start the heartbeat service."""
+ if not self.enabled:
+ logger.info("Heartbeat disabled")
+ return
+ if self._running:
+ logger.warning("Heartbeat already running")
+ return
+
+ self._running = True
+ self._task = asyncio.create_task(self._run_loop())
+ logger.info("Heartbeat started (every {}s)", self.interval_s)
+
+ def stop(self) -> None:
+ """Stop the heartbeat service."""
+ self._running = False
+ if self._task:
+ self._task.cancel()
+ self._task = None
+
+ async def _run_loop(self) -> None:
+ """Main heartbeat loop."""
+ while self._running:
+ try:
+ await asyncio.sleep(self.interval_s)
+ if self._running:
+ await self._tick()
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.error("Heartbeat error: {}", e)
+
+ async def _tick(self) -> None:
+ """Execute a single heartbeat tick."""
+ from deeptutor.tutorbot.utils.evaluator import evaluate_response
+
+ content = self._read_heartbeat_file()
+ if not content:
+ logger.debug("Heartbeat: HEARTBEAT.md missing or empty")
+ return
+
+ logger.info("Heartbeat: checking for tasks...")
+
+ try:
+ action, tasks = await self._decide(content)
+
+ if action != "run":
+ logger.info("Heartbeat: OK (nothing to report)")
+ return
+
+ logger.info("Heartbeat: tasks found, executing...")
+ if self.on_execute:
+ response = await self.on_execute(tasks)
+
+ if response:
+ should_notify = await evaluate_response(
+ response, tasks, self.provider, self.model,
+ )
+ if should_notify and self.on_notify:
+ logger.info("Heartbeat: completed, delivering response")
+ await self.on_notify(response)
+ else:
+ logger.info("Heartbeat: silenced by post-run evaluation")
+ except Exception:
+ logger.exception("Heartbeat execution failed")
+
+ async def trigger_now(self) -> str | None:
+ """Manually trigger a heartbeat."""
+ content = self._read_heartbeat_file()
+ if not content:
+ return None
+ action, tasks = await self._decide(content)
+ if action != "run" or not self.on_execute:
+ return None
+ return await self.on_execute(tasks)
diff --git a/deeptutor/tutorbot/providers/__init__.py b/deeptutor/tutorbot/providers/__init__.py
new file mode 100644
index 000000000..07a9ead7e
--- /dev/null
+++ b/deeptutor/tutorbot/providers/__init__.py
@@ -0,0 +1,12 @@
+"""LLM provider abstraction module."""
+
+from deeptutor.tutorbot.providers.base import LLMProvider, LLMResponse
+
+__all__ = ["LLMProvider", "LLMResponse", "LiteLLMProvider"]
+
+
+def __getattr__(name: str):
+ if name == "LiteLLMProvider":
+ from deeptutor.tutorbot.providers.litellm_provider import LiteLLMProvider
+ return LiteLLMProvider
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/deeptutor/tutorbot/providers/base.py b/deeptutor/tutorbot/providers/base.py
new file mode 100644
index 000000000..114a94861
--- /dev/null
+++ b/deeptutor/tutorbot/providers/base.py
@@ -0,0 +1,270 @@
+"""Base LLM provider interface."""
+
+import asyncio
+import json
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from typing import Any
+
+from loguru import logger
+
+
+@dataclass
+class ToolCallRequest:
+ """A tool call request from the LLM."""
+ id: str
+ name: str
+ arguments: dict[str, Any]
+ provider_specific_fields: dict[str, Any] | None = None
+ function_provider_specific_fields: dict[str, Any] | None = None
+
+ def to_openai_tool_call(self) -> dict[str, Any]:
+ """Serialize to an OpenAI-style tool_call payload."""
+ tool_call = {
+ "id": self.id,
+ "type": "function",
+ "function": {
+ "name": self.name,
+ "arguments": json.dumps(self.arguments, ensure_ascii=False),
+ },
+ }
+ if self.provider_specific_fields:
+ tool_call["provider_specific_fields"] = self.provider_specific_fields
+ if self.function_provider_specific_fields:
+ tool_call["function"]["provider_specific_fields"] = self.function_provider_specific_fields
+ return tool_call
+
+
+@dataclass
+class LLMResponse:
+ """Response from an LLM provider."""
+ content: str | None
+ tool_calls: list[ToolCallRequest] = field(default_factory=list)
+ finish_reason: str = "stop"
+ usage: dict[str, int] = field(default_factory=dict)
+ reasoning_content: str | None = None # Kimi, DeepSeek-R1 etc.
+ thinking_blocks: list[dict] | None = None # Anthropic extended thinking
+
+ @property
+ def has_tool_calls(self) -> bool:
+ """Check if response contains tool calls."""
+ return len(self.tool_calls) > 0
+
+
+@dataclass(frozen=True)
+class GenerationSettings:
+ """Default generation parameters for LLM calls.
+
+ Stored on the provider so every call site inherits the same defaults
+ without having to pass temperature / max_tokens / reasoning_effort
+ through every layer. Individual call sites can still override by
+ passing explicit keyword arguments to chat() / chat_with_retry().
+ """
+
+ temperature: float = 0.7
+ max_tokens: int = 4096
+ reasoning_effort: str | None = None
+
+
+class LLMProvider(ABC):
+ """
+ Abstract base class for LLM providers.
+
+ Implementations should handle the specifics of each provider's API
+ while maintaining a consistent interface.
+ """
+
+ _CHAT_RETRY_DELAYS = (1, 2, 4)
+ _TRANSIENT_ERROR_MARKERS = (
+ "429",
+ "rate limit",
+ "500",
+ "502",
+ "503",
+ "504",
+ "overloaded",
+ "timeout",
+ "timed out",
+ "connection",
+ "server error",
+ "temporarily unavailable",
+ )
+
+ _SENTINEL = object()
+
+ def __init__(self, api_key: str | None = None, api_base: str | None = None):
+ self.api_key = api_key
+ self.api_base = api_base
+ self.generation: GenerationSettings = GenerationSettings()
+
+ @staticmethod
+ def _sanitize_empty_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Replace empty text content that causes provider 400 errors.
+
+ Empty content can appear when MCP tools return nothing. Most providers
+ reject empty-string content or empty text blocks in list content.
+ """
+ result: list[dict[str, Any]] = []
+ for msg in messages:
+ content = msg.get("content")
+
+ if isinstance(content, str) and not content:
+ clean = dict(msg)
+ clean["content"] = None if (msg.get("role") == "assistant" and msg.get("tool_calls")) else "(empty)"
+ result.append(clean)
+ continue
+
+ if isinstance(content, list):
+ filtered = [
+ item for item in content
+ if not (
+ isinstance(item, dict)
+ and item.get("type") in ("text", "input_text", "output_text")
+ and not item.get("text")
+ )
+ ]
+ if len(filtered) != len(content):
+ clean = dict(msg)
+ if filtered:
+ clean["content"] = filtered
+ elif msg.get("role") == "assistant" and msg.get("tool_calls"):
+ clean["content"] = None
+ else:
+ clean["content"] = "(empty)"
+ result.append(clean)
+ continue
+
+ if isinstance(content, dict):
+ clean = dict(msg)
+ clean["content"] = [content]
+ result.append(clean)
+ continue
+
+ result.append(msg)
+ return result
+
+ @staticmethod
+ def _sanitize_request_messages(
+ messages: list[dict[str, Any]],
+ allowed_keys: frozenset[str],
+ ) -> list[dict[str, Any]]:
+ """Keep only provider-safe message keys and normalize assistant content."""
+ sanitized = []
+ for msg in messages:
+ clean = {k: v for k, v in msg.items() if k in allowed_keys}
+ if clean.get("role") == "assistant" and "content" not in clean:
+ clean["content"] = None
+ sanitized.append(clean)
+ return sanitized
+
+ @abstractmethod
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ ) -> LLMResponse:
+ """
+ Send a chat completion request.
+
+ Args:
+ messages: List of message dicts with 'role' and 'content'.
+ tools: Optional list of tool definitions.
+ model: Model identifier (provider-specific).
+ max_tokens: Maximum tokens in response.
+ temperature: Sampling temperature.
+ tool_choice: Tool selection strategy ("auto", "required", or specific tool dict).
+
+ Returns:
+ LLMResponse with content and/or tool calls.
+ """
+ pass
+
+ @classmethod
+ def _is_transient_error(cls, content: str | None) -> bool:
+ err = (content or "").lower()
+ return any(marker in err for marker in cls._TRANSIENT_ERROR_MARKERS)
+
+ async def chat_with_retry(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: object = _SENTINEL,
+ temperature: object = _SENTINEL,
+ reasoning_effort: object = _SENTINEL,
+ tool_choice: str | dict[str, Any] | None = None,
+ ) -> LLMResponse:
+ """Call chat() with retry on transient provider failures.
+
+ Parameters default to ``self.generation`` when not explicitly passed,
+ so callers no longer need to thread temperature / max_tokens /
+ reasoning_effort through every layer.
+ """
+ if max_tokens is self._SENTINEL:
+ max_tokens = self.generation.max_tokens
+ if temperature is self._SENTINEL:
+ temperature = self.generation.temperature
+ if reasoning_effort is self._SENTINEL:
+ reasoning_effort = self.generation.reasoning_effort
+
+ for attempt, delay in enumerate(self._CHAT_RETRY_DELAYS, start=1):
+ try:
+ response = await self.chat(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ response = LLMResponse(
+ content=f"Error calling LLM: {exc}",
+ finish_reason="error",
+ )
+
+ if response.finish_reason != "error":
+ return response
+ if not self._is_transient_error(response.content):
+ return response
+
+ err = (response.content or "").lower()
+ logger.warning(
+ "LLM transient error (attempt {}/{}), retrying in {}s: {}",
+ attempt,
+ len(self._CHAT_RETRY_DELAYS),
+ delay,
+ err[:120],
+ )
+ await asyncio.sleep(delay)
+
+ try:
+ return await self.chat(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ return LLMResponse(
+ content=f"Error calling LLM: {exc}",
+ finish_reason="error",
+ )
+
+ @abstractmethod
+ def get_default_model(self) -> str:
+ """Get the default model for this provider."""
+ pass
diff --git a/deeptutor/tutorbot/providers/deeptutor_adapter.py b/deeptutor/tutorbot/providers/deeptutor_adapter.py
new file mode 100644
index 000000000..bbebf2d75
--- /dev/null
+++ b/deeptutor/tutorbot/providers/deeptutor_adapter.py
@@ -0,0 +1,24 @@
+"""LLM provider adapter that reuses DeepTutor's LLM configuration.
+
+When TutorBot runs in-process inside the DeepTutor server, this provider
+reads api_key / model / base_url from DeepTutor's unified config and
+delegates to the standard LiteLLMProvider, avoiding duplicate configuration.
+"""
+
+from __future__ import annotations
+
+from deeptutor.tutorbot.providers.litellm_provider import LiteLLMProvider
+
+
+def create_deeptutor_provider() -> LiteLLMProvider:
+ """Build a LiteLLMProvider pre-configured from DeepTutor's LLMConfig."""
+ from deeptutor.services.llm.config import get_llm_config
+
+ cfg = get_llm_config()
+ return LiteLLMProvider(
+ api_key=cfg.api_key or None,
+ api_base=cfg.effective_url or cfg.base_url or None,
+ default_model=cfg.model,
+ extra_headers=cfg.extra_headers or {},
+ provider_name=cfg.provider_name or None,
+ )
diff --git a/deeptutor/tutorbot/providers/litellm_provider.py b/deeptutor/tutorbot/providers/litellm_provider.py
new file mode 100644
index 000000000..64ee6e9b1
--- /dev/null
+++ b/deeptutor/tutorbot/providers/litellm_provider.py
@@ -0,0 +1,353 @@
+"""LiteLLM provider implementation for multi-provider support."""
+
+import hashlib
+import os
+import secrets
+import string
+from typing import Any
+
+import json_repair
+import litellm
+from litellm import acompletion
+from loguru import logger
+
+from deeptutor.tutorbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
+from deeptutor.tutorbot.providers.registry import find_by_model, find_gateway
+
+# Standard chat-completion message keys.
+_ALLOWED_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name", "reasoning_content"})
+_ANTHROPIC_EXTRA_KEYS = frozenset({"thinking_blocks"})
+_ALNUM = string.ascii_letters + string.digits
+
+def _short_tool_id() -> str:
+ """Generate a 9-char alphanumeric ID compatible with all providers (incl. Mistral)."""
+ return "".join(secrets.choice(_ALNUM) for _ in range(9))
+
+
+class LiteLLMProvider(LLMProvider):
+ """
+ LLM provider using LiteLLM for multi-provider support.
+
+ Supports OpenRouter, Anthropic, OpenAI, Gemini, MiniMax, and many other providers through
+ a unified interface. Provider-specific logic is driven by the registry
+ (see providers/registry.py) — no if-elif chains needed here.
+ """
+
+ def __init__(
+ self,
+ api_key: str | None = None,
+ api_base: str | None = None,
+ default_model: str = "anthropic/claude-opus-4-5",
+ extra_headers: dict[str, str] | None = None,
+ provider_name: str | None = None,
+ ):
+ super().__init__(api_key, api_base)
+ self.default_model = default_model
+ self.extra_headers = extra_headers or {}
+
+ # Detect gateway / local deployment.
+ # provider_name (from config key) is the primary signal;
+ # api_key / api_base are fallback for auto-detection.
+ self._gateway = find_gateway(provider_name, api_key, api_base)
+
+ # Configure environment variables
+ if api_key:
+ self._setup_env(api_key, api_base, default_model)
+
+ if api_base:
+ litellm.api_base = api_base
+
+ # Disable LiteLLM logging noise
+ litellm.suppress_debug_info = True
+ # Drop unsupported parameters for providers (e.g., gpt-5 rejects some params)
+ litellm.drop_params = True
+
+ self._langsmith_enabled = bool(os.getenv("LANGSMITH_API_KEY"))
+
+ def _setup_env(self, api_key: str, api_base: str | None, model: str) -> None:
+ """Set environment variables based on detected provider."""
+ spec = self._gateway or find_by_model(model)
+ if not spec:
+ return
+ if not spec.env_key:
+ # OAuth/provider-only specs (for example: openai_codex)
+ return
+
+ # Gateway/local overrides existing env; standard provider doesn't
+ if self._gateway:
+ os.environ[spec.env_key] = api_key
+ else:
+ os.environ.setdefault(spec.env_key, api_key)
+
+ # Resolve env_extras placeholders:
+ # {api_key} → user's API key
+ # {api_base} → user's api_base, falling back to spec.default_api_base
+ effective_base = api_base or spec.default_api_base
+ for env_name, env_val in spec.env_extras:
+ resolved = env_val.replace("{api_key}", api_key)
+ resolved = resolved.replace("{api_base}", effective_base)
+ os.environ.setdefault(env_name, resolved)
+
+ def _resolve_model(self, model: str) -> str:
+ """Resolve model name by applying provider/gateway prefixes."""
+ if self._gateway:
+ # Gateway mode: apply gateway prefix, skip provider-specific prefixes
+ prefix = self._gateway.litellm_prefix
+ if self._gateway.strip_model_prefix:
+ model = model.split("/")[-1]
+ if prefix and not model.startswith(f"{prefix}/"):
+ model = f"{prefix}/{model}"
+ return model
+
+ # Standard mode: auto-prefix for known providers
+ spec = find_by_model(model)
+ if spec and spec.litellm_prefix:
+ model = self._canonicalize_explicit_prefix(model, spec.name, spec.litellm_prefix)
+ if not any(model.startswith(s) for s in spec.skip_prefixes):
+ model = f"{spec.litellm_prefix}/{model}"
+
+ return model
+
+ @staticmethod
+ def _canonicalize_explicit_prefix(model: str, spec_name: str, canonical_prefix: str) -> str:
+ """Normalize explicit provider prefixes like `github-copilot/...`."""
+ if "/" not in model:
+ return model
+ prefix, remainder = model.split("/", 1)
+ if prefix.lower().replace("-", "_") != spec_name:
+ return model
+ return f"{canonical_prefix}/{remainder}"
+
+ def _supports_cache_control(self, model: str) -> bool:
+ """Return True when the provider supports cache_control on content blocks."""
+ if self._gateway is not None:
+ return self._gateway.supports_prompt_caching
+ spec = find_by_model(model)
+ return spec is not None and spec.supports_prompt_caching
+
+ def _apply_cache_control(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]:
+ """Return copies of messages and tools with cache_control injected."""
+ new_messages = []
+ for msg in messages:
+ if msg.get("role") == "system":
+ content = msg["content"]
+ if isinstance(content, str):
+ new_content = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}]
+ else:
+ new_content = list(content)
+ new_content[-1] = {**new_content[-1], "cache_control": {"type": "ephemeral"}}
+ new_messages.append({**msg, "content": new_content})
+ else:
+ new_messages.append(msg)
+
+ new_tools = tools
+ if tools:
+ new_tools = list(tools)
+ new_tools[-1] = {**new_tools[-1], "cache_control": {"type": "ephemeral"}}
+
+ return new_messages, new_tools
+
+ def _apply_model_overrides(self, model: str, kwargs: dict[str, Any]) -> None:
+ """Apply model-specific parameter overrides from the registry."""
+ model_lower = model.lower()
+ spec = find_by_model(model)
+ if spec:
+ for pattern, overrides in spec.model_overrides:
+ if pattern in model_lower:
+ kwargs.update(overrides)
+ return
+
+ @staticmethod
+ def _extra_msg_keys(original_model: str, resolved_model: str) -> frozenset[str]:
+ """Return provider-specific extra keys to preserve in request messages."""
+ spec = find_by_model(original_model) or find_by_model(resolved_model)
+ if (spec and spec.name == "anthropic") or "claude" in original_model.lower() or resolved_model.startswith("anthropic/"):
+ return _ANTHROPIC_EXTRA_KEYS
+ return frozenset()
+
+ @staticmethod
+ def _normalize_tool_call_id(tool_call_id: Any) -> Any:
+ """Normalize tool_call_id to a provider-safe 9-char alphanumeric form."""
+ if not isinstance(tool_call_id, str):
+ return tool_call_id
+ if len(tool_call_id) == 9 and tool_call_id.isalnum():
+ return tool_call_id
+ return hashlib.sha1(tool_call_id.encode()).hexdigest()[:9]
+
+ @staticmethod
+ def _sanitize_messages(messages: list[dict[str, Any]], extra_keys: frozenset[str] = frozenset()) -> list[dict[str, Any]]:
+ """Strip non-standard keys and ensure assistant messages have a content key."""
+ allowed = _ALLOWED_MSG_KEYS | extra_keys
+ sanitized = LLMProvider._sanitize_request_messages(messages, allowed)
+ id_map: dict[str, str] = {}
+
+ def map_id(value: Any) -> Any:
+ if not isinstance(value, str):
+ return value
+ return id_map.setdefault(value, LiteLLMProvider._normalize_tool_call_id(value))
+
+ for clean in sanitized:
+ # Keep assistant tool_calls[].id and tool tool_call_id in sync after
+ # shortening, otherwise strict providers reject the broken linkage.
+ if isinstance(clean.get("tool_calls"), list):
+ normalized_tool_calls = []
+ for tc in clean["tool_calls"]:
+ if not isinstance(tc, dict):
+ normalized_tool_calls.append(tc)
+ continue
+ tc_clean = dict(tc)
+ tc_clean["id"] = map_id(tc_clean.get("id"))
+ normalized_tool_calls.append(tc_clean)
+ clean["tool_calls"] = normalized_tool_calls
+
+ if "tool_call_id" in clean and clean["tool_call_id"]:
+ clean["tool_call_id"] = map_id(clean["tool_call_id"])
+ return sanitized
+
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ ) -> LLMResponse:
+ """
+ Send a chat completion request via LiteLLM.
+
+ Args:
+ messages: List of message dicts with 'role' and 'content'.
+ tools: Optional list of tool definitions in OpenAI format.
+ model: Model identifier (e.g., 'anthropic/claude-sonnet-4-5').
+ max_tokens: Maximum tokens in response.
+ temperature: Sampling temperature.
+
+ Returns:
+ LLMResponse with content and/or tool calls.
+ """
+ original_model = model or self.default_model
+ model = self._resolve_model(original_model)
+ extra_msg_keys = self._extra_msg_keys(original_model, model)
+
+ if self._supports_cache_control(original_model):
+ messages, tools = self._apply_cache_control(messages, tools)
+
+ # Clamp max_tokens to at least 1 — negative or zero values cause
+ # LiteLLM to reject the request with "max_tokens must be at least 1".
+ max_tokens = max(1, max_tokens)
+
+ kwargs: dict[str, Any] = {
+ "model": model,
+ "messages": self._sanitize_messages(self._sanitize_empty_content(messages), extra_keys=extra_msg_keys),
+ "max_tokens": max_tokens,
+ "temperature": temperature,
+ }
+
+ # Apply model-specific overrides (e.g. kimi-k2.5 temperature)
+ self._apply_model_overrides(model, kwargs)
+
+ if self._langsmith_enabled:
+ kwargs.setdefault("callbacks", []).append("langsmith")
+
+ # Pass api_key directly — more reliable than env vars alone
+ if self.api_key:
+ kwargs["api_key"] = self.api_key
+
+ # Pass api_base for custom endpoints
+ if self.api_base:
+ kwargs["api_base"] = self.api_base
+
+ # Pass extra headers (e.g. APP-Code for AiHubMix)
+ if self.extra_headers:
+ kwargs["extra_headers"] = self.extra_headers
+
+ if reasoning_effort:
+ kwargs["reasoning_effort"] = reasoning_effort
+ kwargs["drop_params"] = True
+
+ if tools:
+ kwargs["tools"] = tools
+ kwargs["tool_choice"] = tool_choice or "auto"
+
+ try:
+ response = await acompletion(**kwargs)
+ return self._parse_response(response)
+ except Exception as e:
+ # Return error as content for graceful handling
+ return LLMResponse(
+ content=f"Error calling LLM: {str(e)}",
+ finish_reason="error",
+ )
+
+ def _parse_response(self, response: Any) -> LLMResponse:
+ """Parse LiteLLM response into our standard format."""
+ choice = response.choices[0]
+ message = choice.message
+ content = message.content
+ finish_reason = choice.finish_reason
+
+ # Some providers (e.g. GitHub Copilot) split content and tool_calls
+ # across multiple choices. Merge them so tool_calls are not lost.
+ raw_tool_calls = []
+ for ch in response.choices:
+ msg = ch.message
+ if hasattr(msg, "tool_calls") and msg.tool_calls:
+ raw_tool_calls.extend(msg.tool_calls)
+ if ch.finish_reason in ("tool_calls", "stop"):
+ finish_reason = ch.finish_reason
+ if not content and msg.content:
+ content = msg.content
+
+ if len(response.choices) > 1:
+ logger.debug("LiteLLM response has {} choices, merged {} tool_calls",
+ len(response.choices), len(raw_tool_calls))
+
+ tool_calls = []
+ for tc in raw_tool_calls:
+ # Parse arguments from JSON string if needed
+ args = tc.function.arguments
+ if isinstance(args, str):
+ args = json_repair.loads(args)
+
+ provider_specific_fields = getattr(tc, "provider_specific_fields", None) or None
+ function_provider_specific_fields = (
+ getattr(tc.function, "provider_specific_fields", None) or None
+ )
+
+ tool_calls.append(ToolCallRequest(
+ id=_short_tool_id(),
+ name=tc.function.name,
+ arguments=args,
+ provider_specific_fields=provider_specific_fields,
+ function_provider_specific_fields=function_provider_specific_fields,
+ ))
+
+ usage = {}
+ if hasattr(response, "usage") and response.usage:
+ usage = {
+ "prompt_tokens": response.usage.prompt_tokens,
+ "completion_tokens": response.usage.completion_tokens,
+ "total_tokens": response.usage.total_tokens,
+ }
+
+ reasoning_content = getattr(message, "reasoning_content", None) or None
+ thinking_blocks = getattr(message, "thinking_blocks", None) or None
+
+ return LLMResponse(
+ content=content,
+ tool_calls=tool_calls,
+ finish_reason=finish_reason or "stop",
+ usage=usage,
+ reasoning_content=reasoning_content,
+ thinking_blocks=thinking_blocks,
+ )
+
+ def get_default_model(self) -> str:
+ """Get the default model."""
+ return self.default_model
diff --git a/deeptutor/tutorbot/providers/registry.py b/deeptutor/tutorbot/providers/registry.py
new file mode 100644
index 000000000..bee6c5eb1
--- /dev/null
+++ b/deeptutor/tutorbot/providers/registry.py
@@ -0,0 +1,522 @@
+"""
+Provider Registry — single source of truth for LLM provider metadata.
+
+Adding a new provider:
+ 1. Add a ProviderSpec to PROVIDERS below.
+ 2. Add a field to ProvidersConfig in config/schema.py.
+ Done. Env vars, prefixing, config matching, status display all derive from here.
+
+Order matters — it controls match priority and fallback. Gateways first.
+Every entry writes out all fields so you can copy-paste as a template.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+
+@dataclass(frozen=True)
+class ProviderSpec:
+ """One LLM provider's metadata. See PROVIDERS below for real examples.
+
+ Placeholders in env_extras values:
+ {api_key} — the user's API key
+ {api_base} — api_base from config, or this spec's default_api_base
+ """
+
+ # identity
+ name: str # config field name, e.g. "dashscope"
+ keywords: tuple[str, ...] # model-name keywords for matching (lowercase)
+ env_key: str # LiteLLM env var, e.g. "DASHSCOPE_API_KEY"
+ display_name: str = "" # shown in status output
+
+ # model prefixing
+ litellm_prefix: str = "" # "dashscope" → model becomes "dashscope/{model}"
+ skip_prefixes: tuple[str, ...] = () # don't prefix if model already starts with these
+
+ # extra env vars, e.g. (("ZHIPUAI_API_KEY", "{api_key}"),)
+ env_extras: tuple[tuple[str, str], ...] = ()
+
+ # gateway / local detection
+ is_gateway: bool = False # routes any model (OpenRouter, AiHubMix)
+ is_local: bool = False # local deployment (vLLM, Ollama)
+ detect_by_key_prefix: str = "" # match api_key prefix, e.g. "sk-or-"
+ detect_by_base_keyword: str = "" # match substring in api_base URL
+ default_api_base: str = "" # fallback base URL
+
+ # gateway behavior
+ strip_model_prefix: bool = False # strip "provider/" before re-prefixing
+
+ # per-model param overrides, e.g. (("kimi-k2.5", {"temperature": 1.0}),)
+ model_overrides: tuple[tuple[str, dict[str, Any]], ...] = ()
+
+ # OAuth-based providers (e.g., OpenAI Codex) don't use API keys
+ is_oauth: bool = False # if True, uses OAuth flow instead of API key
+
+ # Direct providers bypass LiteLLM entirely (e.g., CustomProvider)
+ is_direct: bool = False
+
+ # Provider supports cache_control on content blocks (e.g. Anthropic prompt caching)
+ supports_prompt_caching: bool = False
+
+ @property
+ def label(self) -> str:
+ return self.display_name or self.name.title()
+
+
+# ---------------------------------------------------------------------------
+# PROVIDERS — the registry. Order = priority. Copy any entry as template.
+# ---------------------------------------------------------------------------
+
+PROVIDERS: tuple[ProviderSpec, ...] = (
+ # === Custom (direct OpenAI-compatible endpoint, bypasses LiteLLM) ======
+ ProviderSpec(
+ name="custom",
+ keywords=(),
+ env_key="",
+ display_name="Custom",
+ litellm_prefix="",
+ is_direct=True,
+ ),
+
+ # === Azure OpenAI (direct API calls with API version 2024-10-21) =====
+ ProviderSpec(
+ name="azure_openai",
+ keywords=("azure", "azure-openai"),
+ env_key="",
+ display_name="Azure OpenAI",
+ litellm_prefix="",
+ is_direct=True,
+ ),
+ # === Gateways (detected by api_key / api_base, not model name) =========
+ # Gateways can route any model, so they win in fallback.
+ # OpenRouter: global gateway, keys start with "sk-or-"
+ ProviderSpec(
+ name="openrouter",
+ keywords=("openrouter",),
+ env_key="OPENROUTER_API_KEY",
+ display_name="OpenRouter",
+ litellm_prefix="openrouter", # claude-3 → openrouter/claude-3
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=True,
+ is_local=False,
+ detect_by_key_prefix="sk-or-",
+ detect_by_base_keyword="openrouter",
+ default_api_base="https://openrouter.ai/api/v1",
+ strip_model_prefix=False,
+ model_overrides=(),
+ supports_prompt_caching=True,
+ ),
+ # AiHubMix: global gateway, OpenAI-compatible interface.
+ # strip_model_prefix=True: it doesn't understand "anthropic/claude-3",
+ # so we strip to bare "claude-3" then re-prefix as "openai/claude-3".
+ ProviderSpec(
+ name="aihubmix",
+ keywords=("aihubmix",),
+ env_key="OPENAI_API_KEY", # OpenAI-compatible
+ display_name="AiHubMix",
+ litellm_prefix="openai", # → openai/{model}
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=True,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="aihubmix",
+ default_api_base="https://aihubmix.com/v1",
+ strip_model_prefix=True, # anthropic/claude-3 → claude-3 → openai/claude-3
+ model_overrides=(),
+ ),
+ # SiliconFlow (硅基流动): OpenAI-compatible gateway, model names keep org prefix
+ ProviderSpec(
+ name="siliconflow",
+ keywords=("siliconflow",),
+ env_key="OPENAI_API_KEY",
+ display_name="SiliconFlow",
+ litellm_prefix="openai",
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=True,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="siliconflow",
+ default_api_base="https://api.siliconflow.cn/v1",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+
+ # VolcEngine (火山引擎): OpenAI-compatible gateway, pay-per-use models
+ ProviderSpec(
+ name="volcengine",
+ keywords=("volcengine", "volces", "ark"),
+ env_key="OPENAI_API_KEY",
+ display_name="VolcEngine",
+ litellm_prefix="volcengine",
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=True,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="volces",
+ default_api_base="https://ark.cn-beijing.volces.com/api/v3",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+
+ # VolcEngine Coding Plan (火山引擎 Coding Plan): same key as volcengine
+ ProviderSpec(
+ name="volcengine_coding_plan",
+ keywords=("volcengine-plan",),
+ env_key="OPENAI_API_KEY",
+ display_name="VolcEngine Coding Plan",
+ litellm_prefix="volcengine",
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=True,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="https://ark.cn-beijing.volces.com/api/coding/v3",
+ strip_model_prefix=True,
+ model_overrides=(),
+ ),
+
+ # BytePlus: VolcEngine international, pay-per-use models
+ ProviderSpec(
+ name="byteplus",
+ keywords=("byteplus",),
+ env_key="OPENAI_API_KEY",
+ display_name="BytePlus",
+ litellm_prefix="volcengine",
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=True,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="bytepluses",
+ default_api_base="https://ark.ap-southeast.bytepluses.com/api/v3",
+ strip_model_prefix=True,
+ model_overrides=(),
+ ),
+
+ # BytePlus Coding Plan: same key as byteplus
+ ProviderSpec(
+ name="byteplus_coding_plan",
+ keywords=("byteplus-plan",),
+ env_key="OPENAI_API_KEY",
+ display_name="BytePlus Coding Plan",
+ litellm_prefix="volcengine",
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=True,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="https://ark.ap-southeast.bytepluses.com/api/coding/v3",
+ strip_model_prefix=True,
+ model_overrides=(),
+ ),
+
+
+ # === Standard providers (matched by model-name keywords) ===============
+ # Anthropic: LiteLLM recognizes "claude-*" natively, no prefix needed.
+ ProviderSpec(
+ name="anthropic",
+ keywords=("anthropic", "claude"),
+ env_key="ANTHROPIC_API_KEY",
+ display_name="Anthropic",
+ litellm_prefix="",
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ supports_prompt_caching=True,
+ ),
+ # OpenAI: LiteLLM recognizes "gpt-*" natively, no prefix needed.
+ ProviderSpec(
+ name="openai",
+ keywords=("openai", "gpt"),
+ env_key="OPENAI_API_KEY",
+ display_name="OpenAI",
+ litellm_prefix="",
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # OpenAI Codex: uses OAuth, not API key.
+ ProviderSpec(
+ name="openai_codex",
+ keywords=("openai-codex",),
+ env_key="", # OAuth-based, no API key
+ display_name="OpenAI Codex",
+ litellm_prefix="", # Not routed through LiteLLM
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="codex",
+ default_api_base="https://chatgpt.com/backend-api",
+ strip_model_prefix=False,
+ model_overrides=(),
+ is_oauth=True, # OAuth-based authentication
+ ),
+ # Github Copilot: uses OAuth, not API key.
+ ProviderSpec(
+ name="github_copilot",
+ keywords=("github_copilot", "copilot"),
+ env_key="", # OAuth-based, no API key
+ display_name="Github Copilot",
+ litellm_prefix="github_copilot", # github_copilot/model → github_copilot/model
+ skip_prefixes=("github_copilot/",),
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ is_oauth=True, # OAuth-based authentication
+ ),
+ # DeepSeek: needs "deepseek/" prefix for LiteLLM routing.
+ ProviderSpec(
+ name="deepseek",
+ keywords=("deepseek",),
+ env_key="DEEPSEEK_API_KEY",
+ display_name="DeepSeek",
+ litellm_prefix="deepseek", # deepseek-chat → deepseek/deepseek-chat
+ skip_prefixes=("deepseek/",), # avoid double-prefix
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # Gemini: needs "gemini/" prefix for LiteLLM.
+ ProviderSpec(
+ name="gemini",
+ keywords=("gemini",),
+ env_key="GEMINI_API_KEY",
+ display_name="Gemini",
+ litellm_prefix="gemini", # gemini-pro → gemini/gemini-pro
+ skip_prefixes=("gemini/",), # avoid double-prefix
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # Zhipu: LiteLLM uses "zai/" prefix.
+ # Also mirrors key to ZHIPUAI_API_KEY (some LiteLLM paths check that).
+ # skip_prefixes: don't add "zai/" when already routed via gateway.
+ ProviderSpec(
+ name="zhipu",
+ keywords=("zhipu", "glm", "zai"),
+ env_key="ZAI_API_KEY",
+ display_name="Zhipu AI",
+ litellm_prefix="zai", # glm-4 → zai/glm-4
+ skip_prefixes=("zhipu/", "zai/", "openrouter/", "hosted_vllm/"),
+ env_extras=(("ZHIPUAI_API_KEY", "{api_key}"),),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # DashScope: Qwen models, needs "dashscope/" prefix.
+ ProviderSpec(
+ name="dashscope",
+ keywords=("qwen", "dashscope"),
+ env_key="DASHSCOPE_API_KEY",
+ display_name="DashScope",
+ litellm_prefix="dashscope", # qwen-max → dashscope/qwen-max
+ skip_prefixes=("dashscope/", "openrouter/"),
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # Moonshot: Kimi models, needs "moonshot/" prefix.
+ # LiteLLM requires MOONSHOT_API_BASE env var to find the endpoint.
+ # Kimi K2.5 API enforces temperature >= 1.0.
+ ProviderSpec(
+ name="moonshot",
+ keywords=("moonshot", "kimi"),
+ env_key="MOONSHOT_API_KEY",
+ display_name="Moonshot",
+ litellm_prefix="moonshot", # kimi-k2.5 → moonshot/kimi-k2.5
+ skip_prefixes=("moonshot/", "openrouter/"),
+ env_extras=(("MOONSHOT_API_BASE", "{api_base}"),),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="https://api.moonshot.ai/v1", # intl; use api.moonshot.cn for China
+ strip_model_prefix=False,
+ model_overrides=(("kimi-k2.5", {"temperature": 1.0}),),
+ ),
+ # MiniMax: needs "minimax/" prefix for LiteLLM routing.
+ # Uses OpenAI-compatible API at api.minimax.io/v1.
+ ProviderSpec(
+ name="minimax",
+ keywords=("minimax",),
+ env_key="MINIMAX_API_KEY",
+ display_name="MiniMax",
+ litellm_prefix="minimax", # MiniMax-M2.1 → minimax/MiniMax-M2.1
+ skip_prefixes=("minimax/", "openrouter/"),
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="https://api.minimax.io/v1",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # === Local deployment (matched by config key, NOT by api_base) =========
+ # vLLM / any OpenAI-compatible local server.
+ # Detected when config key is "vllm" (provider_name="vllm").
+ ProviderSpec(
+ name="vllm",
+ keywords=("vllm",),
+ env_key="HOSTED_VLLM_API_KEY",
+ display_name="vLLM/Local",
+ litellm_prefix="hosted_vllm", # Llama-3-8B → hosted_vllm/Llama-3-8B
+ skip_prefixes=(),
+ env_extras=(),
+ is_gateway=False,
+ is_local=True,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="", # user must provide in config
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # === Ollama (local, OpenAI-compatible) ===================================
+ ProviderSpec(
+ name="ollama",
+ keywords=("ollama", "nemotron"),
+ env_key="OLLAMA_API_KEY",
+ display_name="Ollama",
+ litellm_prefix="ollama_chat", # model → ollama_chat/model
+ skip_prefixes=("ollama/", "ollama_chat/"),
+ env_extras=(),
+ is_gateway=False,
+ is_local=True,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="11434",
+ default_api_base="http://localhost:11434",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+ # === Auxiliary (not a primary LLM provider) ============================
+ # Groq: mainly used for Whisper voice transcription, also usable for LLM.
+ # Needs "groq/" prefix for LiteLLM routing. Placed last — it rarely wins fallback.
+ ProviderSpec(
+ name="groq",
+ keywords=("groq",),
+ env_key="GROQ_API_KEY",
+ display_name="Groq",
+ litellm_prefix="groq", # llama3-8b-8192 → groq/llama3-8b-8192
+ skip_prefixes=("groq/",), # avoid double-prefix
+ env_extras=(),
+ is_gateway=False,
+ is_local=False,
+ detect_by_key_prefix="",
+ detect_by_base_keyword="",
+ default_api_base="",
+ strip_model_prefix=False,
+ model_overrides=(),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Lookup helpers
+# ---------------------------------------------------------------------------
+
+
+def find_by_model(model: str) -> ProviderSpec | None:
+ """Match a standard provider by model-name keyword (case-insensitive).
+ Skips gateways/local — those are matched by api_key/api_base instead."""
+ model_lower = model.lower()
+ model_normalized = model_lower.replace("-", "_")
+ model_prefix = model_lower.split("/", 1)[0] if "/" in model_lower else ""
+ normalized_prefix = model_prefix.replace("-", "_")
+ std_specs = [s for s in PROVIDERS if not s.is_gateway and not s.is_local]
+
+ # Prefer explicit provider prefix — prevents `github-copilot/...codex` matching openai_codex.
+ for spec in std_specs:
+ if model_prefix and normalized_prefix == spec.name:
+ return spec
+
+ for spec in std_specs:
+ if any(
+ kw in model_lower or kw.replace("-", "_") in model_normalized for kw in spec.keywords
+ ):
+ return spec
+ return None
+
+
+def find_gateway(
+ provider_name: str | None = None,
+ api_key: str | None = None,
+ api_base: str | None = None,
+) -> ProviderSpec | None:
+ """Detect gateway/local provider.
+
+ Priority:
+ 1. provider_name — if it maps to a gateway/local spec, use it directly.
+ 2. api_key prefix — e.g. "sk-or-" → OpenRouter.
+ 3. api_base keyword — e.g. "aihubmix" in URL → AiHubMix.
+
+ A standard provider with a custom api_base (e.g. DeepSeek behind a proxy)
+ will NOT be mistaken for vLLM — the old fallback is gone.
+ """
+ # 1. Direct match by config key
+ if provider_name:
+ spec = find_by_name(provider_name)
+ if spec and (spec.is_gateway or spec.is_local):
+ return spec
+
+ # 2. Auto-detect by api_key prefix / api_base keyword
+ for spec in PROVIDERS:
+ if spec.detect_by_key_prefix and api_key and api_key.startswith(spec.detect_by_key_prefix):
+ return spec
+ if spec.detect_by_base_keyword and api_base and spec.detect_by_base_keyword in api_base:
+ return spec
+
+ return None
+
+
+def find_by_name(name: str) -> ProviderSpec | None:
+ """Find a provider spec by config field name, e.g. "dashscope"."""
+ for spec in PROVIDERS:
+ if spec.name == name:
+ return spec
+ return None
diff --git a/deeptutor/tutorbot/providers/transcription.py b/deeptutor/tutorbot/providers/transcription.py
new file mode 100644
index 000000000..1c8cb6a3f
--- /dev/null
+++ b/deeptutor/tutorbot/providers/transcription.py
@@ -0,0 +1,64 @@
+"""Voice transcription provider using Groq."""
+
+import os
+from pathlib import Path
+
+import httpx
+from loguru import logger
+
+
+class GroqTranscriptionProvider:
+ """
+ Voice transcription provider using Groq's Whisper API.
+
+ Groq offers extremely fast transcription with a generous free tier.
+ """
+
+ def __init__(self, api_key: str | None = None):
+ self.api_key = api_key or os.environ.get("GROQ_API_KEY")
+ self.api_url = "https://api.groq.com/openai/v1/audio/transcriptions"
+
+ async def transcribe(self, file_path: str | Path) -> str:
+ """
+ Transcribe an audio file using Groq.
+
+ Args:
+ file_path: Path to the audio file.
+
+ Returns:
+ Transcribed text.
+ """
+ if not self.api_key:
+ logger.warning("Groq API key not configured for transcription")
+ return ""
+
+ path = Path(file_path)
+ if not path.exists():
+ logger.error("Audio file not found: {}", file_path)
+ return ""
+
+ try:
+ async with httpx.AsyncClient() as client:
+ with open(path, "rb") as f:
+ files = {
+ "file": (path.name, f),
+ "model": (None, "whisper-large-v3"),
+ }
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ }
+
+ response = await client.post(
+ self.api_url,
+ headers=headers,
+ files=files,
+ timeout=60.0
+ )
+
+ response.raise_for_status()
+ data = response.json()
+ return data.get("text", "")
+
+ except Exception as e:
+ logger.error("Groq transcription error: {}", e)
+ return ""
diff --git a/deeptutor/tutorbot/session/__init__.py b/deeptutor/tutorbot/session/__init__.py
new file mode 100644
index 000000000..dcb957962
--- /dev/null
+++ b/deeptutor/tutorbot/session/__init__.py
@@ -0,0 +1,5 @@
+"""Session management module."""
+
+from deeptutor.tutorbot.session.manager import Session, SessionManager
+
+__all__ = ["SessionManager", "Session"]
diff --git a/deeptutor/tutorbot/session/manager.py b/deeptutor/tutorbot/session/manager.py
new file mode 100644
index 000000000..aac8964e7
--- /dev/null
+++ b/deeptutor/tutorbot/session/manager.py
@@ -0,0 +1,213 @@
+"""Session management for conversation history."""
+
+import json
+import shutil
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from deeptutor.tutorbot.config.paths import get_legacy_sessions_dir
+from deeptutor.tutorbot.utils.helpers import ensure_dir, safe_filename
+
+
+@dataclass
+class Session:
+ """
+ A conversation session.
+
+ Stores messages in JSONL format for easy reading and persistence.
+
+ Important: Messages are append-only for LLM cache efficiency.
+ The consolidation process writes summaries to MEMORY.md/HISTORY.md
+ but does NOT modify the messages list or get_history() output.
+ """
+
+ key: str # channel:chat_id
+ messages: list[dict[str, Any]] = field(default_factory=list)
+ created_at: datetime = field(default_factory=datetime.now)
+ updated_at: datetime = field(default_factory=datetime.now)
+ metadata: dict[str, Any] = field(default_factory=dict)
+ last_consolidated: int = 0 # Number of messages already consolidated to files
+
+ def add_message(self, role: str, content: str, **kwargs: Any) -> None:
+ """Add a message to the session."""
+ msg = {
+ "role": role,
+ "content": content,
+ "timestamp": datetime.now().isoformat(),
+ **kwargs
+ }
+ self.messages.append(msg)
+ self.updated_at = datetime.now()
+
+ def get_history(self, max_messages: int = 500) -> list[dict[str, Any]]:
+ """Return unconsolidated messages for LLM input, aligned to a user turn."""
+ unconsolidated = self.messages[self.last_consolidated:]
+ sliced = unconsolidated[-max_messages:]
+
+ # Drop leading non-user messages to avoid orphaned tool_result blocks
+ for i, m in enumerate(sliced):
+ if m.get("role") == "user":
+ sliced = sliced[i:]
+ break
+
+ out: list[dict[str, Any]] = []
+ for m in sliced:
+ entry: dict[str, Any] = {"role": m["role"], "content": m.get("content", "")}
+ for k in ("tool_calls", "tool_call_id", "name"):
+ if k in m:
+ entry[k] = m[k]
+ out.append(entry)
+ return out
+
+ def clear(self) -> None:
+ """Clear all messages and reset session to initial state."""
+ self.messages = []
+ self.last_consolidated = 0
+ self.updated_at = datetime.now()
+
+
+class SessionManager:
+ """
+ Manages conversation sessions.
+
+ Sessions are stored as JSONL files in the sessions directory.
+ """
+
+ def __init__(self, workspace: Path):
+ self.workspace = workspace
+ self.sessions_dir = ensure_dir(self.workspace / "sessions")
+ self.legacy_sessions_dir = get_legacy_sessions_dir()
+ self._cache: dict[str, Session] = {}
+
+ def _get_session_path(self, key: str) -> Path:
+ """Get the file path for a session."""
+ safe_key = safe_filename(key.replace(":", "_"))
+ return self.sessions_dir / f"{safe_key}.jsonl"
+
+ def _get_legacy_session_path(self, key: str) -> Path:
+ """Legacy global session path (~/.tutorbot/sessions/)."""
+ safe_key = safe_filename(key.replace(":", "_"))
+ return self.legacy_sessions_dir / f"{safe_key}.jsonl"
+
+ def get_or_create(self, key: str) -> Session:
+ """
+ Get an existing session or create a new one.
+
+ Args:
+ key: Session key (usually channel:chat_id).
+
+ Returns:
+ The session.
+ """
+ if key in self._cache:
+ return self._cache[key]
+
+ session = self._load(key)
+ if session is None:
+ session = Session(key=key)
+
+ self._cache[key] = session
+ return session
+
+ def _load(self, key: str) -> Session | None:
+ """Load a session from disk."""
+ path = self._get_session_path(key)
+ if not path.exists():
+ legacy_path = self._get_legacy_session_path(key)
+ if legacy_path.exists():
+ try:
+ shutil.move(str(legacy_path), str(path))
+ logger.info("Migrated session {} from legacy path", key)
+ except Exception:
+ logger.exception("Failed to migrate session {}", key)
+
+ if not path.exists():
+ return None
+
+ try:
+ messages = []
+ metadata = {}
+ created_at = None
+ last_consolidated = 0
+
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+
+ data = json.loads(line)
+
+ if data.get("_type") == "metadata":
+ metadata = data.get("metadata", {})
+ created_at = datetime.fromisoformat(data["created_at"]) if data.get("created_at") else None
+ last_consolidated = data.get("last_consolidated", 0)
+ else:
+ messages.append(data)
+
+ return Session(
+ key=key,
+ messages=messages,
+ created_at=created_at or datetime.now(),
+ metadata=metadata,
+ last_consolidated=last_consolidated
+ )
+ except Exception as e:
+ logger.warning("Failed to load session {}: {}", key, e)
+ return None
+
+ def save(self, session: Session) -> None:
+ """Save a session to disk."""
+ path = self._get_session_path(session.key)
+
+ with open(path, "w", encoding="utf-8") as f:
+ metadata_line = {
+ "_type": "metadata",
+ "key": session.key,
+ "created_at": session.created_at.isoformat(),
+ "updated_at": session.updated_at.isoformat(),
+ "metadata": session.metadata,
+ "last_consolidated": session.last_consolidated
+ }
+ f.write(json.dumps(metadata_line, ensure_ascii=False) + "\n")
+ for msg in session.messages:
+ f.write(json.dumps(msg, ensure_ascii=False) + "\n")
+
+ self._cache[session.key] = session
+
+ def invalidate(self, key: str) -> None:
+ """Remove a session from the in-memory cache."""
+ self._cache.pop(key, None)
+
+ def list_sessions(self) -> list[dict[str, Any]]:
+ """
+ List all sessions.
+
+ Returns:
+ List of session info dicts.
+ """
+ sessions = []
+
+ for path in self.sessions_dir.glob("*.jsonl"):
+ try:
+ # Read just the metadata line
+ with open(path, encoding="utf-8") as f:
+ first_line = f.readline().strip()
+ if first_line:
+ data = json.loads(first_line)
+ if data.get("_type") == "metadata":
+ key = data.get("key") or path.stem.replace("_", ":", 1)
+ sessions.append({
+ "key": key,
+ "created_at": data.get("created_at"),
+ "updated_at": data.get("updated_at"),
+ "path": str(path)
+ })
+ except Exception:
+ continue
+
+ return sorted(sessions, key=lambda x: x.get("updated_at", ""), reverse=True)
diff --git a/deeptutor/tutorbot/session/sqlite_adapter.py b/deeptutor/tutorbot/session/sqlite_adapter.py
new file mode 100644
index 000000000..3745b9839
--- /dev/null
+++ b/deeptutor/tutorbot/session/sqlite_adapter.py
@@ -0,0 +1,144 @@
+"""SessionManager adapter backed by DeepTutor's SQLite store.
+
+Implements the SessionManager interface (get_or_create, save, list_sessions) but
+reads/writes through DeepTutor's SQLiteSessionStore, unifying conversation history
+for TutorBot and DeepTutor in a single database.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from deeptutor.tutorbot.session.manager import Session
+
+
+class SQLiteSessionAdapter:
+ """Drop-in replacement for SessionManager, backed by DeepTutor SQLite."""
+
+ def __init__(self, store: Any) -> None:
+ """
+ Args:
+ store: A DeepTutor SQLiteSessionStore instance.
+ """
+ self.store = store
+ self._cache: dict[str, Session] = {}
+
+ @property
+ def sessions_dir(self) -> Path:
+ """Compatibility stub — not used when persisting to SQLite."""
+ return Path("/dev/null")
+
+ @property
+ def workspace(self) -> Path:
+ return Path("/dev/null")
+
+ def _session_id(self, key: str) -> str:
+ """Derive a stable DeepTutor session_id from a TutorBot key (channel:chat_id)."""
+ return f"tutorbot:{key}"
+
+ def get_or_create(self, key: str) -> Session:
+ """Get or create a session synchronously (loads from SQLite via event loop)."""
+ if key in self._cache:
+ return self._cache[key]
+
+ session = self._load_sync(key)
+ if session is None:
+ session = Session(key=key)
+ self._ensure_sqlite_session_sync(key)
+ self._cache[key] = session
+ return session
+
+ def save(self, session: Session) -> None:
+ """Persist session messages to SQLite synchronously."""
+ try:
+ loop = asyncio.get_running_loop()
+ loop.create_task(self._save_async(session))
+ except RuntimeError:
+ asyncio.run(self._save_async(session))
+
+ def invalidate(self, key: str) -> None:
+ self._cache.pop(key, None)
+
+ def list_sessions(self) -> list[dict[str, Any]]:
+ try:
+ loop = asyncio.get_running_loop()
+ future = asyncio.ensure_future(self.store.list_sessions(limit=50))
+ if loop.is_running():
+ return []
+ return loop.run_until_complete(future)
+ except RuntimeError:
+ return asyncio.run(self.store.list_sessions(limit=50))
+
+ def _load_sync(self, key: str) -> Session | None:
+ """Load a session from SQLite by running the coroutine."""
+ session_id = self._session_id(key)
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = None
+
+ if loop and loop.is_running():
+ return None
+
+ try:
+ coro = self.store.get_messages_for_context(session_id)
+ messages_raw = asyncio.run(coro) if not loop else loop.run_until_complete(coro)
+ except Exception:
+ return None
+
+ if not messages_raw:
+ return None
+
+ messages = [
+ {"role": m["role"], "content": m.get("content", ""), "timestamp": ""}
+ for m in messages_raw
+ ]
+ return Session(key=key, messages=messages)
+
+ def _ensure_sqlite_session_sync(self, key: str) -> None:
+ """Ensure a corresponding DeepTutor session row exists."""
+ session_id = self._session_id(key)
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = None
+
+ coro = self.store.create_session(title=f"TutorBot: {key}", session_id=session_id)
+ try:
+ if loop and loop.is_running():
+ loop.create_task(coro)
+ elif loop:
+ loop.run_until_complete(coro)
+ else:
+ asyncio.run(coro)
+ except Exception:
+ logger.debug("Session {} may already exist", session_id)
+
+ async def _save_async(self, session: Session) -> None:
+ """Write new messages to SQLite."""
+ session_id = self._session_id(session.key)
+
+ existing = await self.store.get_session(session_id)
+ if existing is None:
+ await self.store.create_session(
+ title=f"TutorBot: {session.key}", session_id=session_id,
+ )
+
+ existing_msgs = await self.store.get_messages(session_id)
+ existing_count = len(existing_msgs)
+
+ for msg in session.messages[existing_count:]:
+ role = msg.get("role", "user")
+ content = msg.get("content", "")
+ if role in ("user", "assistant") and content:
+ await self.store.add_message(
+ session_id=session_id,
+ role=role,
+ content=content,
+ capability="tutorbot",
+ )
diff --git a/deeptutor/tutorbot/skills/README.md b/deeptutor/tutorbot/skills/README.md
new file mode 100644
index 000000000..519279694
--- /dev/null
+++ b/deeptutor/tutorbot/skills/README.md
@@ -0,0 +1,25 @@
+# nanobot Skills
+
+This directory contains built-in skills that extend nanobot's capabilities.
+
+## Skill Format
+
+Each skill is a directory containing a `SKILL.md` file with:
+- YAML frontmatter (name, description, metadata)
+- Markdown instructions for the agent
+
+## Attribution
+
+These skills are adapted from [OpenClaw](https://github.com/openclaw/openclaw)'s skill system.
+The skill format and metadata structure follow OpenClaw's conventions to maintain compatibility.
+
+## Available Skills
+
+| Skill | Description |
+|-------|-------------|
+| `github` | Interact with GitHub using the `gh` CLI |
+| `weather` | Get weather info using wttr.in and Open-Meteo |
+| `summarize` | Summarize URLs, files, and YouTube videos |
+| `tmux` | Remote-control tmux sessions |
+| `clawhub` | Search and install skills from ClawHub registry |
+| `skill-creator` | Create new skills |
\ No newline at end of file
diff --git a/deeptutor/tutorbot/skills/clawhub/SKILL.md b/deeptutor/tutorbot/skills/clawhub/SKILL.md
new file mode 100644
index 000000000..7409bf470
--- /dev/null
+++ b/deeptutor/tutorbot/skills/clawhub/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: clawhub
+description: Search and install agent skills from ClawHub, the public skill registry.
+homepage: https://clawhub.ai
+metadata: {"nanobot":{"emoji":"🦞"}}
+---
+
+# ClawHub
+
+Public skill registry for AI agents. Search by natural language (vector search).
+
+## When to use
+
+Use this skill when the user asks any of:
+- "find a skill for …"
+- "search for skills"
+- "install a skill"
+- "what skills are available?"
+- "update my skills"
+
+## Search
+
+```bash
+npx --yes clawhub@latest search "web scraping" --limit 5
+```
+
+## Install
+
+```bash
+npx --yes clawhub@latest install <slug> --workdir ~/.nanobot/workspace
+```
+
+Replace `<slug>` with the skill name from search results. This places the skill into `~/.nanobot/workspace/skills/`, where nanobot loads workspace skills from. Always include `--workdir`.
+
+## Update
+
+```bash
+npx --yes clawhub@latest update --all --workdir ~/.nanobot/workspace
+```
+
+## List installed
+
+```bash
+npx --yes clawhub@latest list --workdir ~/.nanobot/workspace
+```
+
+## Notes
+
+- Requires Node.js (`npx` comes with it).
+- No API key needed for search and install.
+- Login (`npx --yes clawhub@latest login`) is only required for publishing.
+- `--workdir ~/.nanobot/workspace` is critical — without it, skills install to the current directory instead of the nanobot workspace.
+- After install, remind the user to start a new session to load the skill.
diff --git a/deeptutor/tutorbot/skills/cron/SKILL.md b/deeptutor/tutorbot/skills/cron/SKILL.md
new file mode 100644
index 000000000..cc3516e03
--- /dev/null
+++ b/deeptutor/tutorbot/skills/cron/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: cron
+description: Schedule reminders and recurring tasks.
+---
+
+# Cron
+
+Use the `cron` tool to schedule reminders or recurring tasks.
+
+## Three Modes
+
+1. **Reminder** - message is sent directly to user
+2. **Task** - message is a task description, agent executes and sends result
+3. **One-time** - runs once at a specific time, then auto-deletes
+
+## Examples
+
+Fixed reminder:
+```
+cron(action="add", message="Time to take a break!", every_seconds=1200)
+```
+
+Dynamic task (agent executes each time):
+```
+cron(action="add", message="Check HKUDS/nanobot GitHub stars and report", every_seconds=600)
+```
+
+One-time scheduled task (compute ISO datetime from current time):
+```
+cron(action="add", message="Remind me about the meeting", at="<ISO datetime>")
+```
+
+Timezone-aware cron:
+```
+cron(action="add", message="Morning standup", cron_expr="0 9 * * 1-5", tz="America/Vancouver")
+```
+
+List/remove:
+```
+cron(action="list")
+cron(action="remove", job_id="abc123")
+```
+
+## Time Expressions
+
+| User says | Parameters |
+|-----------|------------|
+| every 20 minutes | every_seconds: 1200 |
+| every hour | every_seconds: 3600 |
+| every day at 8am | cron_expr: "0 8 * * *" |
+| weekdays at 5pm | cron_expr: "0 17 * * 1-5" |
+| 9am Vancouver time daily | cron_expr: "0 9 * * *", tz: "America/Vancouver" |
+| at a specific time | at: ISO datetime string (compute from current time) |
+
+## Timezone
+
+Use `tz` with `cron_expr` to schedule in a specific IANA timezone. Without `tz`, the server's local timezone is used.
diff --git a/deeptutor/tutorbot/skills/deep-question/SKILL.md b/deeptutor/tutorbot/skills/deep-question/SKILL.md
new file mode 100644
index 000000000..387955679
--- /dev/null
+++ b/deeptutor/tutorbot/skills/deep-question/SKILL.md
@@ -0,0 +1,56 @@
+---
+name: deep-question
+description: "Generate quiz questions with answers on any topic."
+metadata: {"nanobot":{"emoji":"❓","requires":{"bins":["deeptutor"]}}}
+always: false
+---
+
+# Deep Question (Quiz Generation)
+
+Use the `exec` tool to invoke DeepTutor's quiz generation pipeline (ideation → evaluation → generation → validation).
+
+## When to Use
+
+- User wants **practice questions** or **quizzes** on a topic
+- User is preparing for an exam or self-testing
+- User asks to "generate questions", "quiz me", "create practice problems"
+
+## Command
+
+```bash
+deeptutor run deep_question "<topic>" --format json -l <lang> [options]
+```
+
+### Options
+
+| Flag | Description |
+|------|-------------|
+| `-l <lang>` | Response language: `en` or `zh` |
+| `--config num_questions=N` | Number of questions (default: 1, max: 50) |
+| `--config difficulty=<level>` | `easy`, `medium`, `hard` |
+| `--config question_type=<type>` | `multiple_choice`, `open_ended`, `true_false`, etc. |
+| `--config mode=<mode>` | `custom` (default) or `mimic` |
+| `-t rag` | Ground questions in a knowledge base |
+| `--kb <name>` | Knowledge base to use |
+
+## Examples
+
+Basic quiz:
+```bash
+deeptutor run deep_question "Calculus integration techniques" --format json -l en --config num_questions=5 --config difficulty=medium
+```
+
+Multiple-choice from a textbook:
+```bash
+deeptutor run deep_question "Chapter 3: Linear Algebra" --format json -l zh -t rag --kb math-textbook --config question_type=multiple_choice --config num_questions=10
+```
+
+Hard open-ended questions:
+```bash
+deeptutor run deep_question "Quantum mechanics fundamentals" --format json -l en --config difficulty=hard --config question_type=open_ended
+```
+
+## Important
+
+- This capability can take **over a minute** for multiple questions — use `timeout=300` with the `exec` tool.
+- Parse NDJSON events with `"type": "content"` for the generated questions and answers.
diff --git a/deeptutor/tutorbot/skills/deep-research/SKILL.md b/deeptutor/tutorbot/skills/deep-research/SKILL.md
new file mode 100644
index 000000000..d0375933e
--- /dev/null
+++ b/deeptutor/tutorbot/skills/deep-research/SKILL.md
@@ -0,0 +1,60 @@
+---
+name: deep-research
+description: "Multi-agent research reports on any topic."
+metadata: {"nanobot":{"emoji":"🔬","requires":{"bins":["deeptutor"]}}}
+always: false
+---
+
+# Deep Research
+
+Use the `exec` tool to invoke DeepTutor's multi-agent research pipeline for comprehensive topic analysis.
+
+## When to Use
+
+- User needs a **research report** or **literature review**
+- User wants a **comparison** of approaches, frameworks, or technologies
+- User asks for a **learning path** or **structured overview** of a field
+- The topic requires aggregating information from multiple sources
+
+## Command
+
+```bash
+deeptutor run deep_research "<topic>" --format json -l <lang> --config-json '<json>'
+```
+
+### Config JSON Fields
+
+| Field | Values | Description |
+|-------|--------|-------------|
+| `mode` | `notes`, `report`, `comparison`, `learning_path` | Output format |
+| `depth` | `quick`, `standard`, `deep` | Research thoroughness |
+| `sources` | `["kb", "web", "papers"]` | Information sources to use |
+
+## Examples
+
+Standard report from web + papers:
+```bash
+deeptutor run deep_research "Recent advances in attention mechanisms" --format json -l en --config-json '{"mode":"report","depth":"deep","sources":["papers","web"]}'
+```
+
+Quick comparison:
+```bash
+deeptutor run deep_research "Rust vs Go for backend services" --format json -l en --config-json '{"mode":"comparison","depth":"quick","sources":["web"]}'
+```
+
+Learning path from knowledge base:
+```bash
+deeptutor run deep_research "Machine learning fundamentals" --format json -l zh --config-json '{"mode":"learning_path","depth":"standard","sources":["kb"]}' --kb ml-textbook
+```
+
+KB + web hybrid:
+```bash
+deeptutor run deep_research "Agentic RAG vs traditional RAG" --format json -l zh --config-json '{"mode":"comparison","depth":"deep","sources":["kb","web"]}' --kb my-papers
+```
+
+## Important
+
+- **All three config fields (`mode`, `depth`, `sources`) are required.** Always use `--config-json` to pass them together.
+- `depth=deep` can take **several minutes** — use `timeout=300` or higher with the `exec` tool.
+- Always pass `--format json` to get parseable NDJSON output.
+- Parse lines with `"type": "content"` and concatenate for the full report.
diff --git a/deeptutor/tutorbot/skills/deep-solve/SKILL.md b/deeptutor/tutorbot/skills/deep-solve/SKILL.md
new file mode 100644
index 000000000..a94218405
--- /dev/null
+++ b/deeptutor/tutorbot/skills/deep-solve/SKILL.md
@@ -0,0 +1,56 @@
+---
+name: deep-solve
+description: "Multi-stage problem solving via DeepTutor (plan → reason → write)."
+metadata: {"nanobot":{"emoji":"🧠","requires":{"bins":["deeptutor"]}}}
+always: false
+---
+
+# Deep Solve
+
+Use the `exec` tool to invoke DeepTutor's multi-stage solver for complex math, science, or engineering problems.
+
+## When to Use
+
+- User asks to **prove** something, **derive** a formula, or **solve** a hard problem
+- The problem requires structured multi-step reasoning
+- A direct answer would be insufficient or unreliable
+
+## Command
+
+```bash
+deeptutor run deep_solve "<problem description>" --format json -l <lang>
+```
+
+### Options
+
+| Flag | Description |
+|------|-------------|
+| `-l <lang>` | Response language: `en` or `zh` |
+| `-t rag` | Enable RAG to ground in knowledge base |
+| `-t web_search` | Enable web search |
+| `-t code_execution` | Enable code verification |
+| `-t reason` | Enable dedicated reasoning |
+| `--kb <name>` | Knowledge base to use with RAG |
+| `--config detailed_answer=false` | Return a concise answer |
+
+## Examples
+
+Prove a theorem:
+```bash
+deeptutor run deep_solve "Prove that for any positive integer n, n³ - n is divisible by 6" --format json -l en
+```
+
+Solve with knowledge base:
+```bash
+deeptutor run deep_solve "Derive the Euler-Lagrange equation" --format json -l en -t rag --kb physics-textbook
+```
+
+Solve with code verification:
+```bash
+deeptutor run deep_solve "Find all roots of x⁴ - 5x² + 4 = 0" --format json -l en -t code_execution
+```
+
+## Important
+
+- Deep solve can take **over a minute** — use `timeout=300` with the `exec` tool.
+- The `--format json` flag outputs NDJSON stream events. Parse the `content` field from lines with `"type": "content"` to get the final answer. Concatenate all content events for the full response.
diff --git a/deeptutor/tutorbot/skills/github/SKILL.md b/deeptutor/tutorbot/skills/github/SKILL.md
new file mode 100644
index 000000000..57d81278d
--- /dev/null
+++ b/deeptutor/tutorbot/skills/github/SKILL.md
@@ -0,0 +1,48 @@
+---
+name: github
+description: "Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries."
+metadata: {"nanobot":{"emoji":"🐙","requires":{"bins":["gh"]},"install":[{"id":"brew","kind":"brew","formula":"gh","bins":["gh"],"label":"Install GitHub CLI (brew)"},{"id":"apt","kind":"apt","package":"gh","bins":["gh"],"label":"Install GitHub CLI (apt)"}]}}
+---
+
+# GitHub Skill
+
+Use the `gh` CLI to interact with GitHub. Always specify `--repo owner/repo` when not in a git directory, or use URLs directly.
+
+## Pull Requests
+
+Check CI status on a PR:
+```bash
+gh pr checks 55 --repo owner/repo
+```
+
+List recent workflow runs:
+```bash
+gh run list --repo owner/repo --limit 10
+```
+
+View a run and see which steps failed:
+```bash
+gh run view <run-id> --repo owner/repo
+```
+
+View logs for failed steps only:
+```bash
+gh run view <run-id> --repo owner/repo --log-failed
+```
+
+## API for Advanced Queries
+
+The `gh api` command is useful for accessing data not available through other subcommands.
+
+Get PR with specific fields:
+```bash
+gh api repos/owner/repo/pulls/55 --jq '.title, .state, .user.login'
+```
+
+## JSON Output
+
+Most commands support `--json` for structured output. You can use `--jq` to filter:
+
+```bash
+gh issue list --repo owner/repo --json number,title --jq '.[] | "\(.number): \(.title)"'
+```
diff --git a/deeptutor/tutorbot/skills/knowledge-base/SKILL.md b/deeptutor/tutorbot/skills/knowledge-base/SKILL.md
new file mode 100644
index 000000000..ae7e1a527
--- /dev/null
+++ b/deeptutor/tutorbot/skills/knowledge-base/SKILL.md
@@ -0,0 +1,70 @@
+---
+name: knowledge-base
+description: "Manage DeepTutor knowledge bases — list, create, search, add documents, delete."
+metadata: {"nanobot":{"emoji":"📚","requires":{"bins":["deeptutor"]}}}
+always: false
+---
+
+# Knowledge Base Management
+
+Use the `exec` tool to manage DeepTutor knowledge bases via CLI.
+
+## When to Use
+
+- User asks about their **knowledge bases** or **study materials**
+- User wants to **create**, **search**, or **manage** a knowledge base
+- User needs to **add documents** to an existing KB
+
+## Commands
+
+### List all knowledge bases
+
+```bash
+deeptutor kb list --format json
+```
+
+> `--format json` outputs machine-readable JSON instead of a Rich table.
+
+### Get info about a knowledge base
+
+```bash
+deeptutor kb info <kb_name>
+```
+
+### Create a knowledge base
+
+```bash
+deeptutor kb create <kb_name> --doc /path/to/file.pdf
+deeptutor kb create <kb_name> --docs-dir /path/to/directory/
+```
+
+### Add documents to existing KB
+
+```bash
+deeptutor kb add <kb_name> --doc /path/to/new_file.pdf
+```
+
+### Search a knowledge base
+
+```bash
+deeptutor kb search <kb_name> "<query>" --format json
+```
+
+### Set a default knowledge base
+
+```bash
+deeptutor kb set-default <kb_name>
+```
+
+### Delete a knowledge base
+
+```bash
+deeptutor kb delete <kb_name> --force
+```
+
+## Tips
+
+- Use `kb list` first to see what's available before searching.
+- The `rag` tool can also search KBs directly within the conversation — use it for quick lookups.
+- KB creation from large PDFs can take a few minutes.
+- Always confirm with the user before deleting a knowledge base.
diff --git a/deeptutor/tutorbot/skills/memory/SKILL.md b/deeptutor/tutorbot/skills/memory/SKILL.md
new file mode 100644
index 000000000..fd188f518
--- /dev/null
+++ b/deeptutor/tutorbot/skills/memory/SKILL.md
@@ -0,0 +1,44 @@
+---
+name: memory
+description: Three-file shared memory system (SUMMARY, PROFILE, SOUL).
+always: true
+---
+
+# Memory
+
+TutorBot shares a three-file memory system with DeepTutor. These files persist across sessions and are automatically loaded into your context.
+
+## Structure
+
+| File | Purpose | Loaded |
+|------|---------|--------|
+| `SUMMARY.md` | Chronological log of all interactions (both DeepTutor and TutorBot) | Yes |
+| `PROFILE.md` | User identity, preferences, and recurring patterns extracted from conversations | Yes |
+| `SOUL.md` | TutorBot's persona and personality configuration | Yes |
+
+## When to Update
+
+### PROFILE.md
+Write important user facts immediately using `edit_file`:
+- User preferences ("prefers Chinese responses")
+- Background info ("PhD student in computer science")
+- Learning context ("studying for linear algebra exam")
+
+### SUMMARY.md
+Append notable events or session summaries. Entries should start with `[YYYY-MM-DD HH:MM]`.
+
+### SOUL.md
+Only modify if the user explicitly asks to change TutorBot's personality or behavior.
+
+## Searching Memory
+
+For quick lookups in SUMMARY.md:
+```bash
+grep -i "keyword" memory/SUMMARY.md
+```
+
+Or use `read_file` for small files.
+
+## Auto-consolidation
+
+Old conversations are automatically summarized and appended to SUMMARY.md when the session grows large. Long-term user facts are extracted to PROFILE.md. You don't need to manage this manually.
diff --git a/deeptutor/tutorbot/skills/notebook/SKILL.md b/deeptutor/tutorbot/skills/notebook/SKILL.md
new file mode 100644
index 000000000..e5d3c20fa
--- /dev/null
+++ b/deeptutor/tutorbot/skills/notebook/SKILL.md
@@ -0,0 +1,60 @@
+---
+name: notebook
+description: "Manage DeepTutor notebooks — list, create, view, import and remove records."
+metadata: {"nanobot":{"emoji":"📓","requires":{"bins":["deeptutor"]}}}
+always: false
+---
+
+# Notebook Management
+
+Use the `exec` tool to manage DeepTutor notebooks via CLI.
+
+## When to Use
+
+- User asks about their **notebooks** or **notes**
+- User wants to **create**, **view**, or **organize** notebook records
+- User needs to **import Markdown** into a notebook
+
+## Commands
+
+### List all notebooks
+
+```bash
+deeptutor notebook list
+```
+
+### Create a notebook
+
+```bash
+deeptutor notebook create <name> --description "Description text"
+```
+
+### Show a notebook and its records
+
+```bash
+deeptutor notebook show <notebook_id>
+```
+
+### Import a Markdown file as a record
+
+```bash
+deeptutor notebook add-md <notebook_id> /path/to/file.md
+```
+
+### Replace an existing record
+
+```bash
+deeptutor notebook replace-md <notebook_id> <record_id> /path/to/file.md
+```
+
+### Remove a record
+
+```bash
+deeptutor notebook remove-record <notebook_id> <record_id>
+```
+
+## Tips
+
+- Use `notebook list` first to see available notebooks and their IDs.
+- Use `notebook show <id>` to see individual records within a notebook.
+- Notebooks are distinct from knowledge bases: notebooks store structured notes, KBs store indexed documents for RAG retrieval.
diff --git a/deeptutor/tutorbot/skills/skill-creator/SKILL.md b/deeptutor/tutorbot/skills/skill-creator/SKILL.md
new file mode 100644
index 000000000..ea53abeab
--- /dev/null
+++ b/deeptutor/tutorbot/skills/skill-creator/SKILL.md
@@ -0,0 +1,374 @@
+---
+name: skill-creator
+description: Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
+---
+
+# Skill Creator
+
+This skill provides guidance for creating effective skills.
+
+## About Skills
+
+Skills are modular, self-contained packages that extend the agent's capabilities by providing
+specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
+domains or tasks—they transform the agent from a general-purpose agent into a specialized agent
+equipped with procedural knowledge that no model can fully possess.
+
+### What Skills Provide
+
+1. Specialized workflows - Multi-step procedures for specific domains
+2. Tool integrations - Instructions for working with specific file formats or APIs
+3. Domain expertise - Company-specific knowledge, schemas, business logic
+4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
+
+## Core Principles
+
+### Concise is Key
+
+The context window is a public good. Skills share the context window with everything else the agent needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
+
+**Default assumption: the agent is already very smart.** Only add context the agent doesn't already have. Challenge each piece of information: "Does the agent really need this explanation?" and "Does this paragraph justify its token cost?"
+
+Prefer concise examples over verbose explanations.
+
+### Set Appropriate Degrees of Freedom
+
+Match the level of specificity to the task's fragility and variability:
+
+**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
+
+**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
+
+**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
+
+Think of the agent as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
+
+### Anatomy of a Skill
+
+Every skill consists of a required SKILL.md file and optional bundled resources:
+
+```
+skill-name/
+├── SKILL.md (required)
+│ ├── YAML frontmatter metadata (required)
+│ │ ├── name: (required)
+│ │ └── description: (required)
+│ └── Markdown instructions (required)
+└── Bundled Resources (optional)
+ ├── scripts/ - Executable code (Python/Bash/etc.)
+ ├── references/ - Documentation intended to be loaded into context as needed
+ └── assets/ - Files used in output (templates, icons, fonts, etc.)
+```
+
+#### SKILL.md (required)
+
+Every SKILL.md consists of:
+
+- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that the agent reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
+- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
+
+#### Bundled Resources (optional)
+
+##### Scripts (`scripts/`)
+
+Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
+
+- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
+- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
+- **Benefits**: Token efficient, deterministic, may be executed without loading into context
+- **Note**: Scripts may still need to be read by the agent for patching or environment-specific adjustments
+
+##### References (`references/`)
+
+Documentation and reference material intended to be loaded as needed into context to inform the agent's process and thinking.
+
+- **When to include**: For documentation that the agent should reference while working
+- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
+- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
+- **Benefits**: Keeps SKILL.md lean, loaded only when the agent determines it's needed
+- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
+- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
+
+##### Assets (`assets/`)
+
+Files not intended to be loaded into context, but rather used within the output the agent produces.
+
+- **When to include**: When the skill needs files that will be used in the final output
+- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
+- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
+- **Benefits**: Separates output resources from documentation, enables the agent to use files without loading them into context
+
+#### What to Not Include in a Skill
+
+A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
+
+- README.md
+- INSTALLATION_GUIDE.md
+- QUICK_REFERENCE.md
+- CHANGELOG.md
+- etc.
+
+The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxiliary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
+
+### Progressive Disclosure Design Principle
+
+Skills use a three-level loading system to manage context efficiently:
+
+1. **Metadata (name + description)** - Always in context (~100 words)
+2. **SKILL.md body** - When skill triggers (<5k words)
+3. **Bundled resources** - As needed by the agent (Unlimited because scripts can be executed without reading into context window)
+
+#### Progressive Disclosure Patterns
+
+Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
+
+**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
+
+**Pattern 1: High-level guide with references**
+
+```markdown
+# PDF Processing
+
+## Quick start
+
+Extract text with pdfplumber:
+[code example]
+
+## Advanced features
+
+- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
+- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
+- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
+```
+
+the agent loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
+
+**Pattern 2: Domain-specific organization**
+
+For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
+
+```
+bigquery-skill/
+├── SKILL.md (overview and navigation)
+└── reference/
+ ├── finance.md (revenue, billing metrics)
+ ├── sales.md (opportunities, pipeline)
+ ├── product.md (API usage, features)
+ └── marketing.md (campaigns, attribution)
+```
+
+When a user asks about sales metrics, the agent only reads sales.md.
+
+Similarly, for skills supporting multiple frameworks or variants, organize by variant:
+
+```
+cloud-deploy/
+├── SKILL.md (workflow + provider selection)
+└── references/
+ ├── aws.md (AWS deployment patterns)
+ ├── gcp.md (GCP deployment patterns)
+ └── azure.md (Azure deployment patterns)
+```
+
+When the user chooses AWS, the agent only reads aws.md.
+
+**Pattern 3: Conditional details**
+
+Show basic content, link to advanced content:
+
+```markdown
+# DOCX Processing
+
+## Creating documents
+
+Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
+
+## Editing documents
+
+For simple edits, modify the XML directly.
+
+**For tracked changes**: See [REDLINING.md](REDLINING.md)
+**For OOXML details**: See [OOXML.md](OOXML.md)
+```
+
+the agent reads REDLINING.md or OOXML.md only when the user needs those features.
+
+**Important guidelines:**
+
+- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
+- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so the agent can see the full scope when previewing.
+
+## Skill Creation Process
+
+Skill creation involves these steps:
+
+1. Understand the skill with concrete examples
+2. Plan reusable skill contents (scripts, references, assets)
+3. Initialize the skill (run init_skill.py)
+4. Edit the skill (implement resources and write SKILL.md)
+5. Package the skill (run package_skill.py)
+6. Iterate based on real usage
+
+Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
+
+### Skill Naming
+
+- Use lowercase letters, digits, and hyphens only; normalize user-provided titles to hyphen-case (e.g., "Plan Mode" -> `plan-mode`).
+- When generating names, generate a name under 64 characters (letters, digits, hyphens).
+- Prefer short, verb-led phrases that describe the action.
+- Namespace by tool when it improves clarity or triggering (e.g., `gh-address-comments`, `linear-address-issue`).
+- Name the skill folder exactly after the skill name.
+
+### Step 1: Understanding the Skill with Concrete Examples
+
+Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
+
+To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
+
+For example, when building an image-editor skill, relevant questions include:
+
+- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
+- "Can you give some examples of how this skill would be used?"
+- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
+- "What would a user say that should trigger this skill?"
+
+To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
+
+Conclude this step when there is a clear sense of the functionality the skill should support.
+
+### Step 2: Planning the Reusable Skill Contents
+
+To turn concrete examples into an effective skill, analyze each example by:
+
+1. Considering how to execute on the example from scratch
+2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
+
+Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
+
+1. Rotating a PDF requires re-writing the same code each time
+2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
+
+Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
+
+1. Writing a frontend webapp requires the same boilerplate HTML/React each time
+2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
+
+Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
+
+1. Querying BigQuery requires re-discovering the table schemas and relationships each time
+2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
+
+To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
+
+### Step 3: Initializing the Skill
+
+At this point, it is time to actually create the skill.
+
+Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
+
+When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
+
+For `nanobot`, custom skills should live under the active workspace `skills/` directory so they can be discovered automatically at runtime (for example, `<workspace>/skills/my-skill/SKILL.md`).
+
+Usage:
+
+```bash
+scripts/init_skill.py <skill-name> --path <output-directory> [--resources scripts,references,assets] [--examples]
+```
+
+Examples:
+
+```bash
+scripts/init_skill.py my-skill --path ./workspace/skills
+scripts/init_skill.py my-skill --path ./workspace/skills --resources scripts,references
+scripts/init_skill.py my-skill --path ./workspace/skills --resources scripts --examples
+```
+
+The script:
+
+- Creates the skill directory at the specified path
+- Generates a SKILL.md template with proper frontmatter and TODO placeholders
+- Optionally creates resource directories based on `--resources`
+- Optionally adds example files when `--examples` is set
+
+After initialization, customize the SKILL.md and add resources as needed. If you used `--examples`, replace or delete placeholder files.
+
+### Step 4: Edit the Skill
+
+When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of the agent to use. Include information that would be beneficial and non-obvious to the agent. Consider what procedural knowledge, domain-specific details, or reusable assets would help another the agent instance execute these tasks more effectively.
+
+#### Learn Proven Design Patterns
+
+Consult these helpful guides based on your skill's needs:
+
+- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
+- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
+
+These files contain established best practices for effective skill design.
+
+#### Start with Reusable Skill Contents
+
+To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
+
+Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
+
+If you used `--examples`, delete any placeholder files that are not needed for the skill. Only create resource directories that are actually required.
+
+#### Update SKILL.md
+
+**Writing Guidelines:** Always use imperative/infinitive form.
+
+##### Frontmatter
+
+Write the YAML frontmatter with `name` and `description`:
+
+- `name`: The skill name
+- `description`: This is the primary triggering mechanism for your skill, and helps the agent understand when to use the skill.
+ - Include both what the Skill does and specific triggers/contexts for when to use it.
+ - Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to the agent.
+ - Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when the agent needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
+
+Keep frontmatter minimal. In `nanobot`, `metadata` and `always` are also supported when needed, but avoid adding extra fields unless they are actually required.
+
+##### Body
+
+Write instructions for using the skill and its bundled resources.
+
+### Step 5: Packaging a Skill
+
+Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
+
+```bash
+scripts/package_skill.py <path/to/skill-folder>
+```
+
+Optional output directory specification:
+
+```bash
+scripts/package_skill.py <path/to/skill-folder> ./dist
+```
+
+The packaging script will:
+
+1. **Validate** the skill automatically, checking:
+ - YAML frontmatter format and required fields
+ - Skill naming conventions and directory structure
+ - Description completeness and quality
+ - File organization and resource references
+
+2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
+
+ Security restriction: symlinks are rejected and packaging fails when any symlink is present.
+
+If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
+
+### Step 6: Iterate
+
+After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
+
+**Iteration workflow:**
+
+1. Use the skill on real tasks
+2. Notice struggles or inefficiencies
+3. Identify how SKILL.md or bundled resources should be updated
+4. Implement changes and test again
diff --git a/deeptutor/tutorbot/skills/skill-creator/scripts/init_skill.py b/deeptutor/tutorbot/skills/skill-creator/scripts/init_skill.py
new file mode 100644
index 000000000..8633fe9e3
--- /dev/null
+++ b/deeptutor/tutorbot/skills/skill-creator/scripts/init_skill.py
@@ -0,0 +1,378 @@
+#!/usr/bin/env python3
+"""
+Skill Initializer - Creates a new skill from template
+
+Usage:
+ init_skill.py <skill-name> --path <path> [--resources scripts,references,assets] [--examples]
+
+Examples:
+ init_skill.py my-new-skill --path skills/public
+ init_skill.py my-new-skill --path skills/public --resources scripts,references
+ init_skill.py my-api-helper --path skills/private --resources scripts --examples
+ init_skill.py custom-skill --path /custom/location
+"""
+
+import argparse
+import re
+import sys
+from pathlib import Path
+
+MAX_SKILL_NAME_LENGTH = 64
+ALLOWED_RESOURCES = {"scripts", "references", "assets"}
+
+SKILL_TEMPLATE = """---
+name: {skill_name}
+description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
+---
+
+# {skill_title}
+
+## Overview
+
+[TODO: 1-2 sentences explaining what this skill enables]
+
+## Structuring This Skill
+
+[TODO: Choose the structure that best fits this skill's purpose. Common patterns:
+
+**1. Workflow-Based** (best for sequential processes)
+- Works well when there are clear step-by-step procedures
+- Example: DOCX skill with "Workflow Decision Tree" -> "Reading" -> "Creating" -> "Editing"
+- Structure: ## Overview -> ## Workflow Decision Tree -> ## Step 1 -> ## Step 2...
+
+**2. Task-Based** (best for tool collections)
+- Works well when the skill offers different operations/capabilities
+- Example: PDF skill with "Quick Start" -> "Merge PDFs" -> "Split PDFs" -> "Extract Text"
+- Structure: ## Overview -> ## Quick Start -> ## Task Category 1 -> ## Task Category 2...
+
+**3. Reference/Guidelines** (best for standards or specifications)
+- Works well for brand guidelines, coding standards, or requirements
+- Example: Brand styling with "Brand Guidelines" -> "Colors" -> "Typography" -> "Features"
+- Structure: ## Overview -> ## Guidelines -> ## Specifications -> ## Usage...
+
+**4. Capabilities-Based** (best for integrated systems)
+- Works well when the skill provides multiple interrelated features
+- Example: Product Management with "Core Capabilities" -> numbered capability list
+- Structure: ## Overview -> ## Core Capabilities -> ### 1. Feature -> ### 2. Feature...
+
+Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
+
+Delete this entire "Structuring This Skill" section when done - it's just guidance.]
+
+## [TODO: Replace with the first main section based on chosen structure]
+
+[TODO: Add content here. See examples in existing skills:
+- Code samples for technical skills
+- Decision trees for complex workflows
+- Concrete examples with realistic user requests
+- References to scripts/templates/references as needed]
+
+## Resources (optional)
+
+Create only the resource directories this skill actually needs. Delete this section if no resources are required.
+
+### scripts/
+Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
+
+**Examples from other skills:**
+- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
+- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
+
+**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
+
+**Note:** Scripts may be executed without loading into context, but can still be read by Codex for patching or environment adjustments.
+
+### references/
+Documentation and reference material intended to be loaded into context to inform Codex's process and thinking.
+
+**Examples from other skills:**
+- Product management: `communication.md`, `context_building.md` - detailed workflow guides
+- BigQuery: API reference documentation and query examples
+- Finance: Schema documentation, company policies
+
+**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Codex should reference while working.
+
+### assets/
+Files not intended to be loaded into context, but rather used within the output Codex produces.
+
+**Examples from other skills:**
+- Brand styling: PowerPoint template files (.pptx), logo files
+- Frontend builder: HTML/React boilerplate project directories
+- Typography: Font files (.ttf, .woff2)
+
+**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
+
+---
+
+**Not every skill requires all three types of resources.**
+"""
+
+EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
+"""
+Example helper script for {skill_name}
+
+This is a placeholder script that can be executed directly.
+Replace with actual implementation or delete if not needed.
+
+Example real scripts from other skills:
+- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
+- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
+"""
+
+def main():
+ print("This is an example script for {skill_name}")
+ # TODO: Add actual script logic here
+ # This could be data processing, file conversion, API calls, etc.
+
+if __name__ == "__main__":
+ main()
+'''
+
+EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
+
+This is a placeholder for detailed reference documentation.
+Replace with actual reference content or delete if not needed.
+
+Example real reference docs from other skills:
+- product-management/references/communication.md - Comprehensive guide for status updates
+- product-management/references/context_building.md - Deep-dive on gathering context
+- bigquery/references/ - API references and query examples
+
+## When Reference Docs Are Useful
+
+Reference docs are ideal for:
+- Comprehensive API documentation
+- Detailed workflow guides
+- Complex multi-step processes
+- Information too lengthy for main SKILL.md
+- Content that's only needed for specific use cases
+
+## Structure Suggestions
+
+### API Reference Example
+- Overview
+- Authentication
+- Endpoints with examples
+- Error codes
+- Rate limits
+
+### Workflow Guide Example
+- Prerequisites
+- Step-by-step instructions
+- Common patterns
+- Troubleshooting
+- Best practices
+"""
+
+EXAMPLE_ASSET = """# Example Asset File
+
+This placeholder represents where asset files would be stored.
+Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
+
+Asset files are NOT intended to be loaded into context, but rather used within
+the output Codex produces.
+
+Example asset files from other skills:
+- Brand guidelines: logo.png, slides_template.pptx
+- Frontend builder: hello-world/ directory with HTML/React boilerplate
+- Typography: custom-font.ttf, font-family.woff2
+- Data: sample_data.csv, test_dataset.json
+
+## Common Asset Types
+
+- Templates: .pptx, .docx, boilerplate directories
+- Images: .png, .jpg, .svg, .gif
+- Fonts: .ttf, .otf, .woff, .woff2
+- Boilerplate code: Project directories, starter files
+- Icons: .ico, .svg
+- Data files: .csv, .json, .xml, .yaml
+
+Note: This is a text placeholder. Actual assets can be any file type.
+"""
+
+
+def normalize_skill_name(skill_name):
+ """Normalize a skill name to lowercase hyphen-case."""
+ normalized = skill_name.strip().lower()
+ normalized = re.sub(r"[^a-z0-9]+", "-", normalized)
+ normalized = normalized.strip("-")
+ normalized = re.sub(r"-{2,}", "-", normalized)
+ return normalized
+
+
+def title_case_skill_name(skill_name):
+ """Convert hyphenated skill name to Title Case for display."""
+ return " ".join(word.capitalize() for word in skill_name.split("-"))
+
+
+def parse_resources(raw_resources):
+ if not raw_resources:
+ return []
+ resources = [item.strip() for item in raw_resources.split(",") if item.strip()]
+ invalid = sorted({item for item in resources if item not in ALLOWED_RESOURCES})
+ if invalid:
+ allowed = ", ".join(sorted(ALLOWED_RESOURCES))
+ print(f"[ERROR] Unknown resource type(s): {', '.join(invalid)}")
+ print(f" Allowed: {allowed}")
+ sys.exit(1)
+ deduped = []
+ seen = set()
+ for resource in resources:
+ if resource not in seen:
+ deduped.append(resource)
+ seen.add(resource)
+ return deduped
+
+
+def create_resource_dirs(skill_dir, skill_name, skill_title, resources, include_examples):
+ for resource in resources:
+ resource_dir = skill_dir / resource
+ resource_dir.mkdir(exist_ok=True)
+ if resource == "scripts":
+ if include_examples:
+ example_script = resource_dir / "example.py"
+ example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
+ example_script.chmod(0o755)
+ print("[OK] Created scripts/example.py")
+ else:
+ print("[OK] Created scripts/")
+ elif resource == "references":
+ if include_examples:
+ example_reference = resource_dir / "api_reference.md"
+ example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
+ print("[OK] Created references/api_reference.md")
+ else:
+ print("[OK] Created references/")
+ elif resource == "assets":
+ if include_examples:
+ example_asset = resource_dir / "example_asset.txt"
+ example_asset.write_text(EXAMPLE_ASSET)
+ print("[OK] Created assets/example_asset.txt")
+ else:
+ print("[OK] Created assets/")
+
+
+def init_skill(skill_name, path, resources, include_examples):
+ """
+ Initialize a new skill directory with template SKILL.md.
+
+ Args:
+ skill_name: Name of the skill
+ path: Path where the skill directory should be created
+ resources: Resource directories to create
+ include_examples: Whether to create example files in resource directories
+
+ Returns:
+ Path to created skill directory, or None if error
+ """
+ # Determine skill directory path
+ skill_dir = Path(path).resolve() / skill_name
+
+ # Check if directory already exists
+ if skill_dir.exists():
+ print(f"[ERROR] Skill directory already exists: {skill_dir}")
+ return None
+
+ # Create skill directory
+ try:
+ skill_dir.mkdir(parents=True, exist_ok=False)
+ print(f"[OK] Created skill directory: {skill_dir}")
+ except Exception as e:
+ print(f"[ERROR] Error creating directory: {e}")
+ return None
+
+ # Create SKILL.md from template
+ skill_title = title_case_skill_name(skill_name)
+ skill_content = SKILL_TEMPLATE.format(skill_name=skill_name, skill_title=skill_title)
+
+ skill_md_path = skill_dir / "SKILL.md"
+ try:
+ skill_md_path.write_text(skill_content)
+ print("[OK] Created SKILL.md")
+ except Exception as e:
+ print(f"[ERROR] Error creating SKILL.md: {e}")
+ return None
+
+ # Create resource directories if requested
+ if resources:
+ try:
+ create_resource_dirs(skill_dir, skill_name, skill_title, resources, include_examples)
+ except Exception as e:
+ print(f"[ERROR] Error creating resource directories: {e}")
+ return None
+
+ # Print next steps
+ print(f"\n[OK] Skill '{skill_name}' initialized successfully at {skill_dir}")
+ print("\nNext steps:")
+ print("1. Edit SKILL.md to complete the TODO items and update the description")
+ if resources:
+ if include_examples:
+ print("2. Customize or delete the example files in scripts/, references/, and assets/")
+ else:
+ print("2. Add resources to scripts/, references/, and assets/ as needed")
+ else:
+ print("2. Create resource directories only if needed (scripts/, references/, assets/)")
+ print("3. Run the validator when ready to check the skill structure")
+
+ return skill_dir
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Create a new skill directory with a SKILL.md template.",
+ )
+ parser.add_argument("skill_name", help="Skill name (normalized to hyphen-case)")
+ parser.add_argument("--path", required=True, help="Output directory for the skill")
+ parser.add_argument(
+ "--resources",
+ default="",
+ help="Comma-separated list: scripts,references,assets",
+ )
+ parser.add_argument(
+ "--examples",
+ action="store_true",
+ help="Create example files inside the selected resource directories",
+ )
+ args = parser.parse_args()
+
+ raw_skill_name = args.skill_name
+ skill_name = normalize_skill_name(raw_skill_name)
+ if not skill_name:
+ print("[ERROR] Skill name must include at least one letter or digit.")
+ sys.exit(1)
+ if len(skill_name) > MAX_SKILL_NAME_LENGTH:
+ print(
+ f"[ERROR] Skill name '{skill_name}' is too long ({len(skill_name)} characters). "
+ f"Maximum is {MAX_SKILL_NAME_LENGTH} characters."
+ )
+ sys.exit(1)
+ if skill_name != raw_skill_name:
+ print(f"Note: Normalized skill name from '{raw_skill_name}' to '{skill_name}'.")
+
+ resources = parse_resources(args.resources)
+ if args.examples and not resources:
+ print("[ERROR] --examples requires --resources to be set.")
+ sys.exit(1)
+
+ path = args.path
+
+ print(f"Initializing skill: {skill_name}")
+ print(f" Location: {path}")
+ if resources:
+ print(f" Resources: {', '.join(resources)}")
+ if args.examples:
+ print(" Examples: enabled")
+ else:
+ print(" Resources: none (create as needed)")
+ print()
+
+ result = init_skill(skill_name, path, resources, args.examples)
+
+ if result:
+ sys.exit(0)
+ else:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/deeptutor/tutorbot/skills/skill-creator/scripts/package_skill.py b/deeptutor/tutorbot/skills/skill-creator/scripts/package_skill.py
new file mode 100644
index 000000000..48fcbbe5e
--- /dev/null
+++ b/deeptutor/tutorbot/skills/skill-creator/scripts/package_skill.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""
+Skill Packager - Creates a distributable .skill file of a skill folder
+
+Usage:
+ python package_skill.py <path/to/skill-folder> [output-directory]
+
+Example:
+ python package_skill.py skills/public/my-skill
+ python package_skill.py skills/public/my-skill ./dist
+"""
+
+import sys
+import zipfile
+from pathlib import Path
+
+from quick_validate import validate_skill
+
+
+def _is_within(path: Path, root: Path) -> bool:
+ try:
+ path.relative_to(root)
+ return True
+ except ValueError:
+ return False
+
+
+def _cleanup_partial_archive(skill_filename: Path) -> None:
+ try:
+ if skill_filename.exists():
+ skill_filename.unlink()
+ except OSError:
+ pass
+
+
+def package_skill(skill_path, output_dir=None):
+ """
+ Package a skill folder into a .skill file.
+
+ Args:
+ skill_path: Path to the skill folder
+ output_dir: Optional output directory for the .skill file (defaults to current directory)
+
+ Returns:
+ Path to the created .skill file, or None if error
+ """
+ skill_path = Path(skill_path).resolve()
+
+ # Validate skill folder exists
+ if not skill_path.exists():
+ print(f"[ERROR] Skill folder not found: {skill_path}")
+ return None
+
+ if not skill_path.is_dir():
+ print(f"[ERROR] Path is not a directory: {skill_path}")
+ return None
+
+ # Validate SKILL.md exists
+ skill_md = skill_path / "SKILL.md"
+ if not skill_md.exists():
+ print(f"[ERROR] SKILL.md not found in {skill_path}")
+ return None
+
+ # Run validation before packaging
+ print("Validating skill...")
+ valid, message = validate_skill(skill_path)
+ if not valid:
+ print(f"[ERROR] Validation failed: {message}")
+ print(" Please fix the validation errors before packaging.")
+ return None
+ print(f"[OK] {message}\n")
+
+ # Determine output location
+ skill_name = skill_path.name
+ if output_dir:
+ output_path = Path(output_dir).resolve()
+ output_path.mkdir(parents=True, exist_ok=True)
+ else:
+ output_path = Path.cwd()
+
+ skill_filename = output_path / f"{skill_name}.skill"
+
+ EXCLUDED_DIRS = {".git", ".svn", ".hg", "__pycache__", "node_modules"}
+
+ files_to_package = []
+ resolved_archive = skill_filename.resolve()
+
+ for file_path in skill_path.rglob("*"):
+ # Fail closed on symlinks so the packaged contents are explicit and predictable.
+ if file_path.is_symlink():
+ print(f"[ERROR] Symlink not allowed in packaged skill: {file_path}")
+ _cleanup_partial_archive(skill_filename)
+ return None
+
+ rel_parts = file_path.relative_to(skill_path).parts
+ if any(part in EXCLUDED_DIRS for part in rel_parts):
+ continue
+
+ if file_path.is_file():
+ resolved_file = file_path.resolve()
+ if not _is_within(resolved_file, skill_path):
+ print(f"[ERROR] File escapes skill root: {file_path}")
+ _cleanup_partial_archive(skill_filename)
+ return None
+ # If output lives under skill_path, avoid writing archive into itself.
+ if resolved_file == resolved_archive:
+ print(f"[WARN] Skipping output archive: {file_path}")
+ continue
+ files_to_package.append(file_path)
+
+ # Create the .skill file (zip format)
+ try:
+ with zipfile.ZipFile(skill_filename, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for file_path in files_to_package:
+ # Calculate the relative path within the zip.
+ arcname = Path(skill_name) / file_path.relative_to(skill_path)
+ zipf.write(file_path, arcname)
+ print(f" Added: {arcname}")
+
+ print(f"\n[OK] Successfully packaged skill to: {skill_filename}")
+ return skill_filename
+
+ except Exception as e:
+ _cleanup_partial_archive(skill_filename)
+ print(f"[ERROR] Error creating .skill file: {e}")
+ return None
+
+
+def main():
+ if len(sys.argv) < 2:
+ print("Usage: python package_skill.py <path/to/skill-folder> [output-directory]")
+ print("\nExample:")
+ print(" python package_skill.py skills/public/my-skill")
+ print(" python package_skill.py skills/public/my-skill ./dist")
+ sys.exit(1)
+
+ skill_path = sys.argv[1]
+ output_dir = sys.argv[2] if len(sys.argv) > 2 else None
+
+ print(f"Packaging skill: {skill_path}")
+ if output_dir:
+ print(f" Output directory: {output_dir}")
+ print()
+
+ result = package_skill(skill_path, output_dir)
+
+ if result:
+ sys.exit(0)
+ else:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/deeptutor/tutorbot/skills/skill-creator/scripts/quick_validate.py b/deeptutor/tutorbot/skills/skill-creator/scripts/quick_validate.py
new file mode 100644
index 000000000..03d246d6e
--- /dev/null
+++ b/deeptutor/tutorbot/skills/skill-creator/scripts/quick_validate.py
@@ -0,0 +1,213 @@
+#!/usr/bin/env python3
+"""
+Minimal validator for nanobot skill folders.
+"""
+
+import re
+import sys
+from pathlib import Path
+from typing import Optional
+
+try:
+ import yaml
+except ModuleNotFoundError:
+ yaml = None
+
+MAX_SKILL_NAME_LENGTH = 64
+ALLOWED_FRONTMATTER_KEYS = {
+ "name",
+ "description",
+ "metadata",
+ "always",
+ "license",
+ "allowed-tools",
+}
+ALLOWED_RESOURCE_DIRS = {"scripts", "references", "assets"}
+PLACEHOLDER_MARKERS = ("[todo", "todo:")
+
+
+def _extract_frontmatter(content: str) -> Optional[str]:
+ lines = content.splitlines()
+ if not lines or lines[0].strip() != "---":
+ return None
+ for i in range(1, len(lines)):
+ if lines[i].strip() == "---":
+ return "\n".join(lines[1:i])
+ return None
+
+
+def _parse_simple_frontmatter(frontmatter_text: str) -> Optional[dict[str, str]]:
+ """Fallback parser for simple frontmatter when PyYAML is unavailable."""
+ parsed: dict[str, str] = {}
+ current_key: Optional[str] = None
+ multiline_key: Optional[str] = None
+
+ for raw_line in frontmatter_text.splitlines():
+ stripped = raw_line.strip()
+ if not stripped or stripped.startswith("#"):
+ continue
+
+ is_indented = raw_line[:1].isspace()
+ if is_indented:
+ if current_key is None:
+ return None
+ current_value = parsed[current_key]
+ parsed[current_key] = f"{current_value}\n{stripped}" if current_value else stripped
+ continue
+
+ if ":" not in stripped:
+ return None
+
+ key, value = stripped.split(":", 1)
+ key = key.strip()
+ value = value.strip()
+ if not key:
+ return None
+
+ if value in {"|", ">"}:
+ parsed[key] = ""
+ current_key = key
+ multiline_key = key
+ continue
+
+ if (value.startswith('"') and value.endswith('"')) or (
+ value.startswith("'") and value.endswith("'")
+ ):
+ value = value[1:-1]
+ parsed[key] = value
+ current_key = key
+ multiline_key = None
+
+ if multiline_key is not None and multiline_key not in parsed:
+ return None
+ return parsed
+
+
+def _load_frontmatter(frontmatter_text: str) -> tuple[Optional[dict], Optional[str]]:
+ if yaml is not None:
+ try:
+ frontmatter = yaml.safe_load(frontmatter_text)
+ except yaml.YAMLError as exc:
+ return None, f"Invalid YAML in frontmatter: {exc}"
+ if not isinstance(frontmatter, dict):
+ return None, "Frontmatter must be a YAML dictionary"
+ return frontmatter, None
+
+ frontmatter = _parse_simple_frontmatter(frontmatter_text)
+ if frontmatter is None:
+ return None, "Invalid YAML in frontmatter: unsupported syntax without PyYAML installed"
+ return frontmatter, None
+
+
+def _validate_skill_name(name: str, folder_name: str) -> Optional[str]:
+ if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name):
+ return (
+ f"Name '{name}' should be hyphen-case "
+ "(lowercase letters, digits, and single hyphens only)"
+ )
+ if len(name) > MAX_SKILL_NAME_LENGTH:
+ return (
+ f"Name is too long ({len(name)} characters). "
+ f"Maximum is {MAX_SKILL_NAME_LENGTH} characters."
+ )
+ if name != folder_name:
+ return f"Skill name '{name}' must match directory name '{folder_name}'"
+ return None
+
+
+def _validate_description(description: str) -> Optional[str]:
+ trimmed = description.strip()
+ if not trimmed:
+ return "Description cannot be empty"
+ lowered = trimmed.lower()
+ if any(marker in lowered for marker in PLACEHOLDER_MARKERS):
+ return "Description still contains TODO placeholder text"
+ if "<" in trimmed or ">" in trimmed:
+ return "Description cannot contain angle brackets (< or >)"
+ if len(trimmed) > 1024:
+ return f"Description is too long ({len(trimmed)} characters). Maximum is 1024 characters."
+ return None
+
+
+def validate_skill(skill_path):
+ """Validate a skill folder structure and required frontmatter."""
+ skill_path = Path(skill_path).resolve()
+
+ if not skill_path.exists():
+ return False, f"Skill folder not found: {skill_path}"
+ if not skill_path.is_dir():
+ return False, f"Path is not a directory: {skill_path}"
+
+ skill_md = skill_path / "SKILL.md"
+ if not skill_md.exists():
+ return False, "SKILL.md not found"
+
+ try:
+ content = skill_md.read_text(encoding="utf-8")
+ except OSError as exc:
+ return False, f"Could not read SKILL.md: {exc}"
+
+ frontmatter_text = _extract_frontmatter(content)
+ if frontmatter_text is None:
+ return False, "Invalid frontmatter format"
+
+ frontmatter, error = _load_frontmatter(frontmatter_text)
+ if error:
+ return False, error
+
+ unexpected_keys = sorted(set(frontmatter.keys()) - ALLOWED_FRONTMATTER_KEYS)
+ if unexpected_keys:
+ allowed = ", ".join(sorted(ALLOWED_FRONTMATTER_KEYS))
+ unexpected = ", ".join(unexpected_keys)
+ return (
+ False,
+ f"Unexpected key(s) in SKILL.md frontmatter: {unexpected}. Allowed properties are: {allowed}",
+ )
+
+ if "name" not in frontmatter:
+ return False, "Missing 'name' in frontmatter"
+ if "description" not in frontmatter:
+ return False, "Missing 'description' in frontmatter"
+
+ name = frontmatter["name"]
+ if not isinstance(name, str):
+ return False, f"Name must be a string, got {type(name).__name__}"
+ name_error = _validate_skill_name(name.strip(), skill_path.name)
+ if name_error:
+ return False, name_error
+
+ description = frontmatter["description"]
+ if not isinstance(description, str):
+ return False, f"Description must be a string, got {type(description).__name__}"
+ description_error = _validate_description(description)
+ if description_error:
+ return False, description_error
+
+ always = frontmatter.get("always")
+ if always is not None and not isinstance(always, bool):
+ return False, f"'always' must be a boolean, got {type(always).__name__}"
+
+ for child in skill_path.iterdir():
+ if child.name == "SKILL.md":
+ continue
+ if child.is_dir() and child.name in ALLOWED_RESOURCE_DIRS:
+ continue
+ if child.is_symlink():
+ continue
+ return (
+ False,
+ f"Unexpected file or directory in skill root: {child.name}. "
+ "Only SKILL.md, scripts/, references/, and assets/ are allowed.",
+ )
+
+ return True, "Skill is valid!"
+
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ print("Usage: python quick_validate.py <skill_directory>")
+ sys.exit(1)
+
+ valid, message = validate_skill(sys.argv[1])
+ print(message)
+ sys.exit(0 if valid else 1)
diff --git a/deeptutor/tutorbot/skills/summarize/SKILL.md b/deeptutor/tutorbot/skills/summarize/SKILL.md
new file mode 100644
index 000000000..766ab5d0b
--- /dev/null
+++ b/deeptutor/tutorbot/skills/summarize/SKILL.md
@@ -0,0 +1,67 @@
+---
+name: summarize
+description: Summarize or extract text/transcripts from URLs, podcasts, and local files (great fallback for “transcribe this YouTube/video”).
+homepage: https://summarize.sh
+metadata: {"nanobot":{"emoji":"🧾","requires":{"bins":["summarize"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/summarize","bins":["summarize"],"label":"Install summarize (brew)"}]}}
+---
+
+# Summarize
+
+Fast CLI to summarize URLs, local files, and YouTube links.
+
+## When to use (trigger phrases)
+
+Use this skill immediately when the user asks any of:
+- “use summarize.sh”
+- “what’s this link/video about?”
+- “summarize this URL/article”
+- “transcribe this YouTube/video” (best-effort transcript extraction; no `yt-dlp` needed)
+
+## Quick start
+
+```bash
+summarize "https://example.com" --model google/gemini-3-flash-preview
+summarize "/path/to/file.pdf" --model google/gemini-3-flash-preview
+summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto
+```
+
+## YouTube: summary vs transcript
+
+Best-effort transcript (URLs only):
+
+```bash
+summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto --extract-only
+```
+
+If the user asked for a transcript but it’s huge, return a tight summary first, then ask which section/time range to expand.
+
+## Model + keys
+
+Set the API key for your chosen provider:
+- OpenAI: `OPENAI_API_KEY`
+- Anthropic: `ANTHROPIC_API_KEY`
+- xAI: `XAI_API_KEY`
+- Google: `GEMINI_API_KEY` (aliases: `GOOGLE_GENERATIVE_AI_API_KEY`, `GOOGLE_API_KEY`)
+
+Default model is `google/gemini-3-flash-preview` if none is set.
+
+## Useful flags
+
+- `--length short|medium|long|xl|xxl|<chars>`
+- `--max-output-tokens <count>`
+- `--extract-only` (URLs only)
+- `--json` (machine readable)
+- `--firecrawl auto|off|always` (fallback extraction)
+- `--youtube auto` (Apify fallback if `APIFY_API_TOKEN` set)
+
+## Config
+
+Optional config file: `~/.summarize/config.json`
+
+```json
+{ "model": "openai/gpt-5.2" }
+```
+
+Optional services:
+- `FIRECRAWL_API_KEY` for blocked sites
+- `APIFY_API_TOKEN` for YouTube fallback
diff --git a/deeptutor/tutorbot/skills/tmux/SKILL.md b/deeptutor/tutorbot/skills/tmux/SKILL.md
new file mode 100644
index 000000000..f2a3144d8
--- /dev/null
+++ b/deeptutor/tutorbot/skills/tmux/SKILL.md
@@ -0,0 +1,121 @@
+---
+name: tmux
+description: Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output.
+metadata: {"nanobot":{"emoji":"🧵","os":["darwin","linux"],"requires":{"bins":["tmux"]}}}
+---
+
+# tmux Skill
+
+Use tmux only when you need an interactive TTY. Prefer exec background mode for long-running, non-interactive tasks.
+
+## Quickstart (isolated socket, exec tool)
+
+```bash
+SOCKET_DIR="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"
+mkdir -p "$SOCKET_DIR"
+SOCKET="$SOCKET_DIR/nanobot.sock"
+SESSION=nanobot-python
+
+tmux -S "$SOCKET" new -d -s "$SESSION" -n shell
+tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- 'PYTHON_BASIC_REPL=1 python3 -q' Enter
+tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
+```
+
+After starting a session, always print monitor commands:
+
+```
+To monitor:
+ tmux -S "$SOCKET" attach -t "$SESSION"
+ tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
+```
+
+## Socket convention
+
+- Use `NANOBOT_TMUX_SOCKET_DIR` environment variable.
+- Default socket path: `"$NANOBOT_TMUX_SOCKET_DIR/nanobot.sock"`.
+
+## Targeting panes and naming
+
+- Target format: `session:window.pane` (defaults to `:0.0`).
+- Keep names short; avoid spaces.
+- Inspect: `tmux -S "$SOCKET" list-sessions`, `tmux -S "$SOCKET" list-panes -a`.
+
+## Finding sessions
+
+- List sessions on your socket: `{baseDir}/scripts/find-sessions.sh -S "$SOCKET"`.
+- Scan all sockets: `{baseDir}/scripts/find-sessions.sh --all` (uses `NANOBOT_TMUX_SOCKET_DIR`).
+
+## Sending input safely
+
+- Prefer literal sends: `tmux -S "$SOCKET" send-keys -t target -l -- "$cmd"`.
+- Control keys: `tmux -S "$SOCKET" send-keys -t target C-c`.
+
+## Watching output
+
+- Capture recent history: `tmux -S "$SOCKET" capture-pane -p -J -t target -S -200`.
+- Wait for prompts: `{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern'`.
+- Attaching is OK; detach with `Ctrl+b d`.
+
+## Spawning processes
+
+- For python REPLs, set `PYTHON_BASIC_REPL=1` (non-basic REPL breaks send-keys flows).
+
+## Windows / WSL
+
+- tmux is supported on macOS/Linux. On Windows, use WSL and install tmux inside WSL.
+- This skill is gated to `darwin`/`linux` and requires `tmux` on PATH.
+
+## Orchestrating Coding Agents (Codex, Claude Code)
+
+tmux excels at running multiple coding agents in parallel:
+
+```bash
+SOCKET="${TMPDIR:-/tmp}/codex-army.sock"
+
+# Create multiple sessions
+for i in 1 2 3 4 5; do
+ tmux -S "$SOCKET" new-session -d -s "agent-$i"
+done
+
+# Launch agents in different workdirs
+tmux -S "$SOCKET" send-keys -t agent-1 "cd /tmp/project1 && codex --yolo 'Fix bug X'" Enter
+tmux -S "$SOCKET" send-keys -t agent-2 "cd /tmp/project2 && codex --yolo 'Fix bug Y'" Enter
+
+# Poll for completion (check if prompt returned)
+for sess in agent-1 agent-2; do
+ if tmux -S "$SOCKET" capture-pane -p -t "$sess" -S -3 | grep -q "❯"; then
+ echo "$sess: DONE"
+ else
+ echo "$sess: Running..."
+ fi
+done
+
+# Get full output from completed session
+tmux -S "$SOCKET" capture-pane -p -t agent-1 -S -500
+```
+
+**Tips:**
+- Use separate git worktrees for parallel fixes (no branch conflicts)
+- `pnpm install` first before running codex in fresh clones
+- Check for shell prompt (`❯` or `$`) to detect completion
+- Codex needs `--yolo` or `--full-auto` for non-interactive fixes
+
+## Cleanup
+
+- Kill a session: `tmux -S "$SOCKET" kill-session -t "$SESSION"`.
+- Kill all sessions on a socket: `tmux -S "$SOCKET" list-sessions -F '#{session_name}' | xargs -r -n1 tmux -S "$SOCKET" kill-session -t`.
+- Remove everything on the private socket: `tmux -S "$SOCKET" kill-server`.
+
+## Helper: wait-for-text.sh
+
+`{baseDir}/scripts/wait-for-text.sh` polls a pane for a regex (or fixed string) with a timeout.
+
+```bash
+{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern' [-F] [-T 20] [-i 0.5] [-l 2000]
+```
+
+- `-t`/`--target` pane target (required)
+- `-p`/`--pattern` regex to match (required); add `-F` for fixed string
+- `-T` timeout seconds (integer, default 15)
+- `-i` poll interval seconds (default 0.5)
+- `-l` history lines to search (integer, default 1000)
diff --git a/deeptutor/tutorbot/skills/tmux/scripts/find-sessions.sh b/deeptutor/tutorbot/skills/tmux/scripts/find-sessions.sh
new file mode 100755
index 000000000..00552c684
--- /dev/null
+++ b/deeptutor/tutorbot/skills/tmux/scripts/find-sessions.sh
@@ -0,0 +1,112 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+usage() {
+ cat <<'USAGE'
+Usage: find-sessions.sh [-L socket-name|-S socket-path|-A] [-q pattern]
+
+List tmux sessions on a socket (default tmux socket if none provided).
+
+Options:
+ -L, --socket tmux socket name (passed to tmux -L)
+ -S, --socket-path tmux socket path (passed to tmux -S)
+ -A, --all scan all sockets under NANOBOT_TMUX_SOCKET_DIR
+ -q, --query case-insensitive substring to filter session names
+ -h, --help show this help
+USAGE
+}
+
+socket_name=""
+socket_path=""
+query=""
+scan_all=false
+socket_dir="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ -L|--socket) socket_name="${2-}"; shift 2 ;;
+ -S|--socket-path) socket_path="${2-}"; shift 2 ;;
+ -A|--all) scan_all=true; shift ;;
+ -q|--query) query="${2-}"; shift 2 ;;
+ -h|--help) usage; exit 0 ;;
+ *) echo "Unknown option: $1" >&2; usage; exit 1 ;;
+ esac
+done
+
+if [[ "$scan_all" == true && ( -n "$socket_name" || -n "$socket_path" ) ]]; then
+ echo "Cannot combine --all with -L or -S" >&2
+ exit 1
+fi
+
+if [[ -n "$socket_name" && -n "$socket_path" ]]; then
+ echo "Use either -L or -S, not both" >&2
+ exit 1
+fi
+
+if ! command -v tmux >/dev/null 2>&1; then
+ echo "tmux not found in PATH" >&2
+ exit 1
+fi
+
+list_sessions() {
+ local label="$1"; shift
+ local tmux_cmd=(tmux "$@")
+
+ if ! sessions="$("${tmux_cmd[@]}" list-sessions -F '#{session_name}\t#{session_attached}\t#{session_created_string}' 2>/dev/null)"; then
+ echo "No tmux server found on $label" >&2
+ return 1
+ fi
+
+ if [[ -n "$query" ]]; then
+ sessions="$(printf '%s\n' "$sessions" | grep -i -- "$query" || true)"
+ fi
+
+ if [[ -z "$sessions" ]]; then
+ echo "No sessions found on $label"
+ return 0
+ fi
+
+ echo "Sessions on $label:"
+ printf '%s\n' "$sessions" | while IFS=$'\t' read -r name attached created; do
+ attached_label=$([[ "$attached" == "1" ]] && echo "attached" || echo "detached")
+ printf ' - %s (%s, started %s)\n' "$name" "$attached_label" "$created"
+ done
+}
+
+if [[ "$scan_all" == true ]]; then
+ if [[ ! -d "$socket_dir" ]]; then
+ echo "Socket directory not found: $socket_dir" >&2
+ exit 1
+ fi
+
+ shopt -s nullglob
+ sockets=("$socket_dir"/*)
+ shopt -u nullglob
+
+ if [[ "${#sockets[@]}" -eq 0 ]]; then
+ echo "No sockets found under $socket_dir" >&2
+ exit 1
+ fi
+
+ exit_code=0
+ for sock in "${sockets[@]}"; do
+ if [[ ! -S "$sock" ]]; then
+ continue
+ fi
+ list_sessions "socket path '$sock'" -S "$sock" || exit_code=$?
+ done
+ exit "$exit_code"
+fi
+
+tmux_cmd=(tmux)
+socket_label="default socket"
+
+if [[ -n "$socket_name" ]]; then
+ tmux_cmd+=(-L "$socket_name")
+ socket_label="socket name '$socket_name'"
+elif [[ -n "$socket_path" ]]; then
+ tmux_cmd+=(-S "$socket_path")
+ socket_label="socket path '$socket_path'"
+fi
+
+list_sessions "$socket_label" "${tmux_cmd[@]:1}"
diff --git a/deeptutor/tutorbot/skills/tmux/scripts/wait-for-text.sh b/deeptutor/tutorbot/skills/tmux/scripts/wait-for-text.sh
new file mode 100755
index 000000000..56354be83
--- /dev/null
+++ b/deeptutor/tutorbot/skills/tmux/scripts/wait-for-text.sh
@@ -0,0 +1,83 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+usage() {
+ cat <<'USAGE'
+Usage: wait-for-text.sh -t target -p pattern [options]
+
+Poll a tmux pane for text and exit when found.
+
+Options:
+ -t, --target tmux target (session:window.pane), required
+ -p, --pattern regex pattern to look for, required
+ -F, --fixed treat pattern as a fixed string (grep -F)
+ -T, --timeout seconds to wait (integer, default: 15)
+ -i, --interval poll interval in seconds (default: 0.5)
+ -l, --lines number of history lines to inspect (integer, default: 1000)
+ -h, --help show this help
+USAGE
+}
+
+target=""
+pattern=""
+grep_flag="-E"
+timeout=15
+interval=0.5
+lines=1000
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ -t|--target) target="${2-}"; shift 2 ;;
+ -p|--pattern) pattern="${2-}"; shift 2 ;;
+ -F|--fixed) grep_flag="-F"; shift ;;
+ -T|--timeout) timeout="${2-}"; shift 2 ;;
+ -i|--interval) interval="${2-}"; shift 2 ;;
+ -l|--lines) lines="${2-}"; shift 2 ;;
+ -h|--help) usage; exit 0 ;;
+ *) echo "Unknown option: $1" >&2; usage; exit 1 ;;
+ esac
+done
+
+if [[ -z "$target" || -z "$pattern" ]]; then
+ echo "target and pattern are required" >&2
+ usage
+ exit 1
+fi
+
+if ! [[ "$timeout" =~ ^[0-9]+$ ]]; then
+ echo "timeout must be an integer number of seconds" >&2
+ exit 1
+fi
+
+if ! [[ "$lines" =~ ^[0-9]+$ ]]; then
+ echo "lines must be an integer" >&2
+ exit 1
+fi
+
+if ! command -v tmux >/dev/null 2>&1; then
+ echo "tmux not found in PATH" >&2
+ exit 1
+fi
+
+# End time in epoch seconds (integer, good enough for polling)
+start_epoch=$(date +%s)
+deadline=$((start_epoch + timeout))
+
+while true; do
+ # -J joins wrapped lines, -S uses negative index to read last N lines
+ pane_text="$(tmux capture-pane -p -J -t "$target" -S "-${lines}" 2>/dev/null || true)"
+
+ if printf '%s\n' "$pane_text" | grep $grep_flag -- "$pattern" >/dev/null 2>&1; then
+ exit 0
+ fi
+
+ now=$(date +%s)
+ if (( now >= deadline )); then
+ echo "Timed out after ${timeout}s waiting for pattern: $pattern" >&2
+ echo "Last ${lines} lines from $target:" >&2
+ printf '%s\n' "$pane_text" >&2
+ exit 1
+ fi
+
+ sleep "$interval"
+done
diff --git a/deeptutor/tutorbot/skills/weather/SKILL.md b/deeptutor/tutorbot/skills/weather/SKILL.md
new file mode 100644
index 000000000..8073de192
--- /dev/null
+++ b/deeptutor/tutorbot/skills/weather/SKILL.md
@@ -0,0 +1,49 @@
+---
+name: weather
+description: Get current weather and forecasts (no API key required).
+homepage: https://wttr.in/:help
+metadata: {"nanobot":{"emoji":"🌤️","requires":{"bins":["curl"]}}}
+---
+
+# Weather
+
+Two free services, no API keys needed.
+
+## wttr.in (primary)
+
+Quick one-liner:
+```bash
+curl -s "wttr.in/London?format=3"
+# Output: London: ⛅️ +8°C
+```
+
+Compact format:
+```bash
+curl -s "wttr.in/London?format=%l:+%c+%t+%h+%w"
+# Output: London: ⛅️ +8°C 71% ↙5km/h
+```
+
+Full forecast:
+```bash
+curl -s "wttr.in/London?T"
+```
+
+Format codes: `%c` condition · `%t` temp · `%h` humidity · `%w` wind · `%l` location · `%m` moon
+
+Tips:
+- URL-encode spaces: `wttr.in/New+York`
+- Airport codes: `wttr.in/JFK`
+- Units: `?m` (metric) `?u` (USCS)
+- Today only: `?1` · Current only: `?0`
+- PNG: `curl -s "wttr.in/Berlin.png" -o /tmp/weather.png`
+
+## Open-Meteo (fallback, JSON)
+
+Free, no key, good for programmatic use:
+```bash
+curl -s "https://api.open-meteo.com/v1/forecast?latitude=51.5&longitude=-0.12&current_weather=true"
+```
+
+Find coordinates for a city, then query. Returns JSON with temp, windspeed, weathercode.
+
+Docs: https://open-meteo.com/en/docs
diff --git a/deeptutor/tutorbot/templates/AGENTS.md b/deeptutor/tutorbot/templates/AGENTS.md
new file mode 100644
index 000000000..1a5a1a440
--- /dev/null
+++ b/deeptutor/tutorbot/templates/AGENTS.md
@@ -0,0 +1,21 @@
+# Agent Instructions
+
+You are a helpful AI assistant. Be concise, accurate, and friendly.
+
+## Scheduled Reminders
+
+Before scheduling reminders, check available skills and follow skill guidance first.
+Use the built-in `cron` tool to create/list/remove jobs (do not call CLI commands via `exec` for cron).
+Get USER_ID and CHANNEL from the current session (e.g., `8281248569` and `telegram` from `telegram:8281248569`).
+
+**Do NOT just write reminders to MEMORY.md** — that won't trigger actual notifications.
+
+## Heartbeat Tasks
+
+`HEARTBEAT.md` is checked on the configured heartbeat interval. Use file tools to manage periodic tasks:
+
+- **Add**: `edit_file` to append new tasks
+- **Remove**: `edit_file` to delete completed tasks
+- **Rewrite**: `write_file` to replace all tasks
+
+When the user asks for a recurring/periodic task, update `HEARTBEAT.md` instead of creating a one-time cron reminder.
diff --git a/deeptutor/tutorbot/templates/HEARTBEAT.md b/deeptutor/tutorbot/templates/HEARTBEAT.md
new file mode 100644
index 000000000..5613ed34e
--- /dev/null
+++ b/deeptutor/tutorbot/templates/HEARTBEAT.md
@@ -0,0 +1,16 @@
+# Heartbeat Tasks
+
+This file is checked every 30 minutes by TutorBot.
+Add tasks below that you want the agent to work on periodically.
+
+If this file has no tasks (only headers and comments), the agent will skip the heartbeat.
+
+## Active Tasks
+
+<!-- Add your periodic tasks below this line -->
+
+
+## Completed
+
+<!-- Move completed tasks here or delete them -->
+
diff --git a/deeptutor/tutorbot/templates/SOUL.md b/deeptutor/tutorbot/templates/SOUL.md
new file mode 100644
index 000000000..2d4f19645
--- /dev/null
+++ b/deeptutor/tutorbot/templates/SOUL.md
@@ -0,0 +1,21 @@
+# Soul
+
+I am TutorBot, a personal AI assistant.
+
+## Personality
+
+- Helpful and friendly
+- Concise and to the point
+- Curious and eager to learn
+
+## Values
+
+- Accuracy over speed
+- User privacy and safety
+- Transparency in actions
+
+## Communication Style
+
+- Be clear and direct
+- Explain reasoning when helpful
+- Ask clarifying questions when needed
diff --git a/deeptutor/tutorbot/templates/TOOLS.md b/deeptutor/tutorbot/templates/TOOLS.md
new file mode 100644
index 000000000..51c3a2d0d
--- /dev/null
+++ b/deeptutor/tutorbot/templates/TOOLS.md
@@ -0,0 +1,15 @@
+# Tool Usage Notes
+
+Tool signatures are provided automatically via function calling.
+This file documents non-obvious constraints and usage patterns.
+
+## exec — Safety Limits
+
+- Commands have a configurable timeout (default 60s)
+- Dangerous commands are blocked (rm -rf, format, dd, shutdown, etc.)
+- Output is truncated at 10,000 characters
+- `restrictToWorkspace` config can limit file access to the workspace
+
+## cron — Scheduled Reminders
+
+- Please refer to cron skill for usage.
diff --git a/deeptutor/tutorbot/templates/USER.md b/deeptutor/tutorbot/templates/USER.md
new file mode 100644
index 000000000..671ec49a1
--- /dev/null
+++ b/deeptutor/tutorbot/templates/USER.md
@@ -0,0 +1,49 @@
+# User Profile
+
+Information about the user to help personalize interactions.
+
+## Basic Information
+
+- **Name**: (your name)
+- **Timezone**: (your timezone, e.g., UTC+8)
+- **Language**: (preferred language)
+
+## Preferences
+
+### Communication Style
+
+- [ ] Casual
+- [ ] Professional
+- [ ] Technical
+
+### Response Length
+
+- [ ] Brief and concise
+- [ ] Detailed explanations
+- [ ] Adaptive based on question
+
+### Technical Level
+
+- [ ] Beginner
+- [ ] Intermediate
+- [ ] Expert
+
+## Work Context
+
+- **Primary Role**: (your role, e.g., developer, researcher)
+- **Main Projects**: (what you're working on)
+- **Tools You Use**: (IDEs, languages, frameworks)
+
+## Topics of Interest
+
+-
+-
+-
+
+## Special Instructions
+
+(Any specific instructions for how the assistant should behave)
+
+---
+
+*Edit this file to customize nanobot's behavior for your needs.*
diff --git a/deeptutor/tutorbot/templates/__init__.py b/deeptutor/tutorbot/templates/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/deeptutor/tutorbot/utils/__init__.py b/deeptutor/tutorbot/utils/__init__.py
new file mode 100644
index 000000000..cc2d1ea33
--- /dev/null
+++ b/deeptutor/tutorbot/utils/__init__.py
@@ -0,0 +1,5 @@
+"""Utility functions for TutorBot."""
+
+from deeptutor.tutorbot.utils.helpers import ensure_dir
+
+__all__ = ["ensure_dir"]
diff --git a/deeptutor/tutorbot/utils/evaluator.py b/deeptutor/tutorbot/utils/evaluator.py
new file mode 100644
index 000000000..017e1a211
--- /dev/null
+++ b/deeptutor/tutorbot/utils/evaluator.py
@@ -0,0 +1,91 @@
+"""Post-run evaluation for background tasks (heartbeat & cron).
+
+After the agent executes a background task, this module makes a lightweight
+LLM call to decide whether the result warrants notifying the user.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from loguru import logger
+
+if TYPE_CHECKING:
+ from deeptutor.tutorbot.providers.base import LLMProvider
+
+_EVALUATE_TOOL = [
+ {
+ "type": "function",
+ "function": {
+ "name": "evaluate_notification",
+ "description": "Decide whether the user should be notified about this background task result.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "should_notify": {
+ "type": "boolean",
+ "description": "true = result contains actionable/important info the user should see; false = routine or empty, safe to suppress",
+ },
+ "reason": {
+ "type": "string",
+ "description": "One-sentence reason for the decision",
+ },
+ },
+ "required": ["should_notify"],
+ },
+ },
+ }
+]
+
+_SYSTEM_PROMPT = (
+ "You are a notification gate for a background agent. "
+ "You will be given the original task and the agent's response. "
+ "Call the evaluate_notification tool to decide whether the user "
+ "should be notified.\n\n"
+ "Notify when the response contains actionable information, errors, "
+ "completed deliverables, or anything the user explicitly asked to "
+ "be reminded about.\n\n"
+ "Suppress when the response is a routine status check with nothing "
+ "new, a confirmation that everything is normal, or essentially empty."
+)
+
+
+async def evaluate_response(
+ response: str,
+ task_context: str,
+ provider: LLMProvider,
+ model: str,
+) -> bool:
+ """Decide whether a background-task result should be delivered to the user.
+
+ Falls back to True (notify) on any failure so that important messages
+ are never silently dropped.
+ """
+ try:
+ llm_response = await provider.chat_with_retry(
+ messages=[
+ {"role": "system", "content": _SYSTEM_PROMPT},
+ {"role": "user", "content": (
+ f"## Original task\n{task_context}\n\n"
+ f"## Agent response\n{response}"
+ )},
+ ],
+ tools=_EVALUATE_TOOL,
+ model=model,
+ max_tokens=256,
+ temperature=0.0,
+ )
+
+ if not llm_response.has_tool_calls:
+ logger.warning("evaluate_response: no tool call returned, defaulting to notify")
+ return True
+
+ args = llm_response.tool_calls[0].arguments
+ should_notify = args.get("should_notify", True)
+ reason = args.get("reason", "")
+ logger.info("evaluate_response: should_notify={}, reason={}", should_notify, reason)
+ return bool(should_notify)
+
+ except Exception:
+ logger.exception("evaluate_response failed, defaulting to notify")
+ return True
diff --git a/deeptutor/tutorbot/utils/helpers.py b/deeptutor/tutorbot/utils/helpers.py
new file mode 100644
index 000000000..49e30e7fd
--- /dev/null
+++ b/deeptutor/tutorbot/utils/helpers.py
@@ -0,0 +1,227 @@
+"""Utility functions for TutorBot."""
+
+import json
+import re
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import tiktoken
+
+
+def detect_image_mime(data: bytes) -> str | None:
+ """Detect image MIME type from magic bytes, ignoring file extension."""
+ if data[:8] == b"\x89PNG\r\n\x1a\n":
+ return "image/png"
+ if data[:3] == b"\xff\xd8\xff":
+ return "image/jpeg"
+ if data[:6] in (b"GIF87a", b"GIF89a"):
+ return "image/gif"
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "image/webp"
+ return None
+
+
+def ensure_dir(path: Path) -> Path:
+ """Ensure directory exists, return it."""
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def timestamp() -> str:
+ """Current ISO timestamp."""
+ return datetime.now().isoformat()
+
+
+_UNSAFE_CHARS = re.compile(r'[<>:"/\\|?*]')
+
+def safe_filename(name: str) -> str:
+ """Replace unsafe path characters with underscores."""
+ return _UNSAFE_CHARS.sub("_", name).strip()
+
+
+def split_message(content: str, max_len: int = 2000) -> list[str]:
+ """
+ Split content into chunks within max_len, preferring line breaks.
+
+ Args:
+ content: The text content to split.
+ max_len: Maximum length per chunk (default 2000 for Discord compatibility).
+
+ Returns:
+ List of message chunks, each within max_len.
+ """
+ if not content:
+ return []
+ if len(content) <= max_len:
+ return [content]
+ chunks: list[str] = []
+ while content:
+ if len(content) <= max_len:
+ chunks.append(content)
+ break
+ cut = content[:max_len]
+ # Try to break at newline first, then space, then hard break
+ pos = cut.rfind('\n')
+ if pos <= 0:
+ pos = cut.rfind(' ')
+ if pos <= 0:
+ pos = max_len
+ chunks.append(content[:pos])
+ content = content[pos:].lstrip()
+ return chunks
+
+
+def build_assistant_message(
+ content: str | None,
+ tool_calls: list[dict[str, Any]] | None = None,
+ reasoning_content: str | None = None,
+ thinking_blocks: list[dict] | None = None,
+) -> dict[str, Any]:
+ """Build a provider-safe assistant message with optional reasoning fields."""
+ msg: dict[str, Any] = {"role": "assistant", "content": content}
+ if tool_calls:
+ msg["tool_calls"] = tool_calls
+ if reasoning_content is not None:
+ msg["reasoning_content"] = reasoning_content
+ if thinking_blocks:
+ msg["thinking_blocks"] = thinking_blocks
+ return msg
+
+
+def estimate_prompt_tokens(
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+) -> int:
+ """Estimate prompt tokens with tiktoken."""
+ try:
+ enc = tiktoken.get_encoding("cl100k_base")
+ parts: list[str] = []
+ for msg in messages:
+ content = msg.get("content")
+ if isinstance(content, str):
+ parts.append(content)
+ elif isinstance(content, list):
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "text":
+ txt = part.get("text", "")
+ if txt:
+ parts.append(txt)
+ if tools:
+ parts.append(json.dumps(tools, ensure_ascii=False))
+ return len(enc.encode("\n".join(parts)))
+ except Exception:
+ return 0
+
+
+def estimate_message_tokens(message: dict[str, Any]) -> int:
+ """Estimate prompt tokens contributed by one persisted message."""
+ content = message.get("content")
+ parts: list[str] = []
+ if isinstance(content, str):
+ parts.append(content)
+ elif isinstance(content, list):
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "text":
+ text = part.get("text", "")
+ if text:
+ parts.append(text)
+ else:
+ parts.append(json.dumps(part, ensure_ascii=False))
+ elif content is not None:
+ parts.append(json.dumps(content, ensure_ascii=False))
+
+ for key in ("name", "tool_call_id"):
+ value = message.get(key)
+ if isinstance(value, str) and value:
+ parts.append(value)
+ if message.get("tool_calls"):
+ parts.append(json.dumps(message["tool_calls"], ensure_ascii=False))
+
+ payload = "\n".join(parts)
+ if not payload:
+ return 1
+ try:
+ enc = tiktoken.get_encoding("cl100k_base")
+ return max(1, len(enc.encode(payload)))
+ except Exception:
+ return max(1, len(payload) // 4)
+
+
+def estimate_prompt_tokens_chain(
+ provider: Any,
+ model: str | None,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+) -> tuple[int, str]:
+ """Estimate prompt tokens via provider counter first, then tiktoken fallback."""
+ provider_counter = getattr(provider, "estimate_prompt_tokens", None)
+ if callable(provider_counter):
+ try:
+ tokens, source = provider_counter(messages, tools, model)
+ if isinstance(tokens, (int, float)) and tokens > 0:
+ return int(tokens), str(source or "provider_counter")
+ except Exception:
+ pass
+
+ estimated = estimate_prompt_tokens(messages, tools)
+ if estimated > 0:
+ return int(estimated), "tiktoken"
+ return 0, "none"
+
+
+def sync_workspace_templates(workspace: Path, silent: bool = False) -> list[str]:
+ """Sync bundled templates to workspace. Only creates missing files."""
+ from importlib.resources import files as pkg_files
+ try:
+ tpl = pkg_files("deeptutor.tutorbot") / "templates"
+ except Exception:
+ return []
+ if not tpl.is_dir():
+ return []
+
+ added: list[str] = []
+
+ def _write(src, dest: Path):
+ if dest.exists():
+ return
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(src.read_text(encoding="utf-8") if src else "", encoding="utf-8")
+ added.append(str(dest.relative_to(workspace)))
+
+ for item in tpl.iterdir():
+ if item.name.endswith(".md") and not item.name.startswith("."):
+ _write(item, workspace / item.name)
+ _write(tpl / "memory" / "MEMORY.md", workspace / "memory" / "MEMORY.md")
+ _write(None, workspace / "memory" / "HISTORY.md")
+ (workspace / "skills").mkdir(exist_ok=True)
+
+ if added and not silent:
+ from rich.console import Console
+ for name in added:
+ Console().print(f" [dim]Created {name}[/dim]")
+ return added
+
+
+def parse_json_from_llm(text: str) -> dict[str, Any] | None:
+ """Extract a JSON object from LLM output, tolerating markdown fences."""
+ if not text:
+ return None
+ s = text.strip()
+ if s.startswith("```"):
+ s = re.sub(r"^```(?:json)?\s*", "", s)
+ s = re.sub(r"\s*```$", "", s)
+ try:
+ obj = json.loads(s)
+ return obj if isinstance(obj, dict) else None
+ except Exception:
+ pass
+ start = s.find("{")
+ end = s.rfind("}")
+ if start < 0 or end <= start:
+ return None
+ try:
+ obj = json.loads(s[start : end + 1])
+ return obj if isinstance(obj, dict) else None
+ except Exception:
+ return None
diff --git a/deeptutor_cli/README.md b/deeptutor_cli/README.md
new file mode 100644
index 000000000..5ed850409
--- /dev/null
+++ b/deeptutor_cli/README.md
@@ -0,0 +1,212 @@
+# DeepTutor CLI
+
+Agent-first 的命令行界面。两条核心路径:
+
+- **`run`** — 单次执行任意 capability(为 agent 调用设计)
+- **`chat`** — 交互式 REPL(为人类设计)
+
+## 安装
+
+```bash
+# 仅 CLI
+pip install -r requirements/cli.txt && pip install -e .
+
+# CLI + Web/API 服务
+pip install -r requirements/server.txt && pip install -e .
+
+# 数学动画(可选)
+pip install -r requirements/math-animator.txt
+```
+
+---
+
+## `run` — 执行 Capability
+
+统一入口,单次执行任意 capability。Agent 只需掌握这一个命令。
+
+```bash
+deeptutor run <capability> <message> [options]
+```
+
+### 内置 Capability
+
+| Capability | 说明 |
+|------------|------|
+| `chat` | 对话(默认,可挂载工具) |
+| `deep_solve` | 多阶段深度解题 |
+| `deep_question` | 智能出题 |
+| `deep_research` | 多 agent 深度研究 |
+| `math_animator` | 数学动画生成 |
+
+### 选项
+
+| 选项 | 缩写 | 说明 |
+|------|------|------|
+| `--tool` | `-t` | 启用工具(可多次指定):`rag`, `web_search`, `code_execution`, `reason`, `brainstorm`, `paper_search` |
+| `--kb` | | 挂载知识库 |
+| `--language` | `-l` | 回复语言(默认 `en`) |
+| `--session` | | 继续已有会话 |
+| `--config` | | capability 配置 `key=value`(可多次指定) |
+| `--config-json` | | capability 配置(JSON 字符串) |
+| `--notebook-ref` | | 笔记本引用 |
+| `--history-ref` | | 引用历史会话 |
+| `--format` | `-f` | 输出格式:`rich`(默认)\| `json` |
+
+### 示例
+
+```bash
+# 对话
+deeptutor run chat "什么是傅里叶变换?" -l zh
+
+# 深度解题
+deeptutor run deep_solve "证明 n^3-n 能被 6 整除" -t rag --kb math-textbook
+
+# 简要回答
+deeptutor run deep_solve "求 sin(x) 的导数" --config detailed_answer=false
+
+# 智能出题
+deeptutor run deep_question "线性代数" --config num_questions=5 --config difficulty=hard
+
+# 仿真出题
+deeptutor run deep_question "模拟考试" --config mode=mimic --config paper_path=exam.json
+
+# 深度研究
+deeptutor run deep_research "Transformer 最新进展" \
+ --config-json '{"mode":"report","depth":"deep","sources":["web","papers"]}'
+
+# 数学动画
+deeptutor run math_animator "展示正弦函数变换" --config quality=high
+
+# JSON 输出(适合 agent 解析)
+deeptutor run deep_solve "求解 x^2=4" -f json
+```
+
+---
+
+## `chat` — 交互式 REPL
+
+进入多轮对话界面,在 REPL 内通过 `/` 命令切换 capability、工具、知识库等。
+
+```bash
+deeptutor chat [options]
+```
+
+| 选项 | 说明 |
+|------|------|
+| `--session` | 恢复已有会话 |
+| `--tool`, `-t` | 预启用工具 |
+| `--capability`, `-c` | 初始 capability(默认 `chat`) |
+| `--kb` | 预挂载知识库 |
+| `--language`, `-l` | 回复语言 |
+
+### REPL 内置命令
+
+| 命令 | 说明 |
+|------|------|
+| `/quit` | 退出 |
+| `/session` | 显示当前 session ID |
+| `/new` | 新建会话 |
+| `/tool on\|off <name>` | 启用/关闭工具 |
+| `/cap <name>` | 切换 capability |
+| `/kb <name>\|none` | 切换知识库 |
+| `/history add <id>\|clear` | 管理历史引用 |
+| `/notebook add <ref>\|clear` | 管理笔记本引用 |
+| `/refs` | 查看当前设置 |
+| `/config show\|set\|clear` | 管理 capability 配置 |
+
+---
+
+## `serve` — 启动 API 服务
+
+```bash
+deeptutor serve [--host 0.0.0.0] [--port 8001] [--reload]
+```
+
+---
+
+## 资源管理命令
+
+### `kb` — 知识库
+
+```bash
+deeptutor kb list # 列出所有知识库
+deeptutor kb info <name> # 查看详情
+deeptutor kb create <name> --doc file.pdf # 创建并导入文档
+deeptutor kb create <name> --docs-dir ./docs/ # 从目录批量导入
+deeptutor kb add <name> --doc extra.pdf # 追加文档
+deeptutor kb set-default <name> # 设为默认
+deeptutor kb search <name> "查询内容" # 搜索
+deeptutor kb delete <name> --force # 删除
+```
+
+### `session` — 会话
+
+```bash
+deeptutor session list [--limit 20]
+deeptutor session show <id>
+deeptutor session open <id> # 进入 REPL 继续对话
+deeptutor session rename <id> --title "新标题"
+deeptutor session delete <id>
+```
+
+### `notebook` — 笔记本
+
+```bash
+deeptutor notebook list
+deeptutor notebook create "笔记" --description "描述"
+deeptutor notebook show <id>
+deeptutor notebook add-md <id> ./notes.md
+deeptutor notebook replace-md <id> <record_id> ./updated.md
+deeptutor notebook remove-record <id> <record_id>
+```
+
+### `memory` — 长期记忆
+
+```bash
+deeptutor memory show
+deeptutor memory export ./backup/
+deeptutor memory clear --force
+```
+
+### `plugin` — 插件信息
+
+```bash
+deeptutor plugin list # 查看所有工具和 capability
+deeptutor plugin info <name> # 查看详情
+```
+
+### `config` — 配置
+
+```bash
+deeptutor config show
+```
+
+### `provider` — OAuth 登录
+
+```bash
+deeptutor provider login openai-codex
+deeptutor provider login github-copilot
+```
+
+---
+
+## 典型工作流
+
+```bash
+# 1. 创建知识库
+deeptutor kb create calculus --doc 微积分教材.pdf
+
+# 2. 用知识库解题
+deeptutor run deep_solve "求 ∫sin(x)cos(x)dx" -t rag --kb calculus -l zh
+
+# 3. 基于知识库出题
+deeptutor run deep_question "微积分" --kb calculus \
+ --config num_questions=5 --config difficulty=medium -l zh
+
+# 4. 深度研究某课题
+deeptutor run deep_research "注意力机制演进" \
+ --config-json '{"mode":"report","depth":"deep","sources":["papers","web"]}' -l zh
+
+# 5. 查看会话记录
+deeptutor session list
+```
diff --git a/deeptutor_cli/bot.py b/deeptutor_cli/bot.py
new file mode 100644
index 000000000..787e83490
--- /dev/null
+++ b/deeptutor_cli/bot.py
@@ -0,0 +1,99 @@
+"""
+CLI commands for managing TutorBot instances.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import typer
+from rich.console import Console
+from rich.table import Table
+
+console = Console()
+
+
+def register(app: typer.Typer) -> None:
+
+ @app.command("list")
+ def bot_list() -> None:
+ """List all TutorBot instances."""
+ from deeptutor.services.tutorbot import get_tutorbot_manager
+
+ bots = get_tutorbot_manager().list_bots()
+ if not bots:
+ console.print("[dim]No TutorBots configured.[/]")
+ return
+
+ table = Table(title="TutorBots")
+ table.add_column("ID", style="cyan")
+ table.add_column("Name")
+ table.add_column("Status")
+ table.add_column("Model", style="dim")
+ table.add_column("Channels", style="dim")
+
+ for b in bots:
+ status = "[green]running[/]" if b.get("running") else "[dim]stopped[/]"
+ table.add_row(
+ b["bot_id"],
+ b.get("name", ""),
+ status,
+ b.get("model") or "(default)",
+ ", ".join(b.get("channels", [])) or "-",
+ )
+ console.print(table)
+
+ @app.command("start")
+ def bot_start(
+ name: str = typer.Argument(..., help="Bot ID to start."),
+ ) -> None:
+ """Start a TutorBot instance."""
+ from deeptutor.services.tutorbot import get_tutorbot_manager
+
+ mgr = get_tutorbot_manager()
+ try:
+ instance = asyncio.get_event_loop().run_until_complete(mgr.start_bot(name))
+ console.print(f"[green]Started TutorBot '{instance.config.name}' ({name})[/]")
+ except RuntimeError as e:
+ console.print(f"[red]Failed to start: {e}[/]")
+ raise typer.Exit(1)
+
+ @app.command("stop")
+ def bot_stop(
+ name: str = typer.Argument(..., help="Bot ID to stop."),
+ ) -> None:
+ """Stop a running TutorBot instance."""
+ from deeptutor.services.tutorbot import get_tutorbot_manager
+
+ mgr = get_tutorbot_manager()
+ stopped = asyncio.get_event_loop().run_until_complete(mgr.stop_bot(name))
+ if stopped:
+ console.print(f"[green]Stopped TutorBot '{name}'[/]")
+ else:
+ console.print(f"[yellow]Bot '{name}' not found or not running.[/]")
+
+ @app.command("create")
+ def bot_create(
+ name: str = typer.Argument(..., help="Bot ID."),
+ display_name: str = typer.Option("", "--name", "-n", help="Display name."),
+ persona: str = typer.Option("", "--persona", "-p", help="Persona description."),
+ model: str = typer.Option("", "--model", "-m", help="Model override."),
+ ) -> None:
+ """Create a new TutorBot configuration and start it."""
+ from deeptutor.services.tutorbot import get_tutorbot_manager
+ from deeptutor.services.tutorbot.manager import BotConfig
+
+ config = BotConfig(
+ name=display_name or name,
+ persona=persona,
+ model=model or None,
+ )
+ mgr = get_tutorbot_manager()
+ try:
+ instance = asyncio.get_event_loop().run_until_complete(
+ mgr.start_bot(name, config)
+ )
+ console.print(f"[green]Created and started TutorBot '{instance.config.name}' ({name})[/]")
+ except RuntimeError as e:
+ console.print(f"[red]Failed: {e}[/]")
+ raise typer.Exit(1)
diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.py
index 935043c0d..5a6e33208 100644
--- a/deeptutor_cli/chat.py
+++ b/deeptutor_cli/chat.py
@@ -1,4 +1,4 @@
-"""Chat and capability execution commands."""
+"""Interactive chat REPL."""
from __future__ import annotations
@@ -11,7 +11,7 @@ from rich.panel import Panel
from deeptutor.app import DeepTutorApp, TurnRequest
-from .common import build_turn_request, console, maybe_run, run_turn_and_render
+from .common import console, maybe_run, run_turn_and_render
@dataclass
@@ -30,46 +30,18 @@ def register(app: typer.Typer) -> None:
@app.callback(invoke_without_command=True)
def chat(
ctx: typer.Context,
- message: str | None = typer.Argument(None, help="Message to send."),
- tool: list[str] = typer.Option([], "--tool", "-t", help="Enable tool(s)."),
- capability: str = typer.Option("chat", "--capability", "-c", help="Capability name or alias."),
- kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),
- session: str | None = typer.Option(None, "--session", help="Existing session id."),
- notebook_ref: list[str] = typer.Option(
- [],
- "--notebook-ref",
- help="Notebook reference in NOTEBOOK_ID[:record_id,record_id] format.",
- ),
+ session: str | None = typer.Option(None, "--session", help="Resume an existing session."),
+ tool: list[str] = typer.Option([], "--tool", "-t", help="Pre-enable tool(s)."),
+ capability: str = typer.Option("chat", "--capability", "-c", help="Initial capability."),
+ kb: list[str] = typer.Option([], "--kb", help="Pre-attach knowledge base(s)."),
+ notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),
history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),
language: str = typer.Option("en", "--language", "-l", help="Response language."),
- config: list[str] = typer.Option([], "--config", help="Capability config key=value."),
- config_json: str | None = typer.Option(None, "--config-json", help="Capability config as JSON."),
- once: bool = typer.Option(False, "--once", help="Single-shot mode."),
- fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),
) -> None:
- """Chat with DeepTutor through the unified turn runtime."""
+ """Enter interactive chat REPL. Use `deeptutor run` for single-turn execution."""
if ctx.invoked_subcommand is not None:
return
- if message or once:
- if not message:
- console.print("[red]Provide a message for single-shot mode.[/]")
- raise typer.Exit(code=1)
- request = build_turn_request(
- content=message,
- capability=capability,
- session_id=session,
- tools=tool,
- knowledge_bases=kb,
- language=language,
- config_items=config,
- config_json=config_json,
- notebook_refs=notebook_ref,
- history_refs=history_ref,
- )
- maybe_run(_run_single_turn(request=request, fmt=fmt))
- return
-
state = ChatState(
session_id=session,
capability=capability,
@@ -78,16 +50,10 @@ def register(app: typer.Typer) -> None:
language=language,
notebook_references=_parse_notebook_refs(notebook_ref),
history_references=[item.strip() for item in history_ref if item.strip()],
- config=_merge_config(config, config_json),
)
maybe_run(_chat_repl(state))
-async def _run_single_turn(*, request: TurnRequest, fmt: str) -> tuple[dict[str, Any], dict[str, Any]]:
- client = DeepTutorApp()
- return await run_turn_and_render(app=client, request=request, fmt=fmt)
-
-
async def _chat_repl(state: ChatState) -> None:
client = DeepTutorApp()
if state.session_id:
@@ -110,18 +76,14 @@ async def _chat_repl(state: ChatState) -> None:
console.print(
Panel(
"[bold]DeepTutor CLI[/]\n"
- "直接输入消息即可继续对话。\n"
- "Commands:\n"
- " /quit\n"
- " /session\n"
- " /new\n"
- " /tool on <name> | /tool off <name>\n"
+ "Type a message to chat. Commands:\n"
+ " /quit /session /new\n"
+ " /tool on|off <name>\n"
" /cap <name>\n"
" /kb <name>|none\n"
- " /history add <session_id> | /history clear\n"
- " /notebook add <id[:record1,record2]> | /notebook clear\n"
- " /refs\n"
- " /config show | /config set key=value | /config clear",
+ " /history add <id> | /history clear\n"
+ " /notebook add <ref> | /notebook clear\n"
+ " /refs /config show|set|clear",
title="deeptutor chat",
)
)
@@ -234,21 +196,6 @@ def _print_state(state: ChatState) -> None:
)
-def _merge_config(config_items: list[str], config_json: str | None) -> dict[str, Any]:
- base = {}
- if config_json:
- parsed = json.loads(config_json)
- if not isinstance(parsed, dict):
- raise typer.BadParameter("--config-json must be a JSON object.")
- base.update(parsed)
- for item in config_items:
- key, sep, raw_value = item.partition("=")
- if not sep:
- raise typer.BadParameter(f"Invalid --config item `{item}`.")
- base[key.strip()] = _parse_config_value(raw_value.strip())
- return base
-
-
def _parse_notebook_refs(values: list[str]) -> list[dict[str, Any]]:
refs = []
for value in values:
diff --git a/deeptutor_cli/kb.py b/deeptutor_cli/kb.py
index 75debe690..39b73746d 100644
--- a/deeptutor_cli/kb.py
+++ b/deeptutor_cli/kb.py
@@ -17,12 +17,19 @@ from rich.console import Console
from rich.table import Table
from deeptutor.knowledge.manager import KnowledgeBaseManager
+from deeptutor.services.path_service import get_path_service
from deeptutor.services.rag.components.routing import FileTypeRouter
from deeptutor.services.rag.factory import DEFAULT_PROVIDER
console = Console()
+def _get_kb_manager() -> KnowledgeBaseManager:
+ """Return a KnowledgeBaseManager rooted at the canonical project-level KB directory."""
+ base_dir = get_path_service().project_root / "data" / "knowledge_bases"
+ return KnowledgeBaseManager(base_dir=str(base_dir))
+
+
def _collect_documents(docs: list[str], docs_dir: Optional[str]) -> list[str]:
"""Collect and de-duplicate document files from explicit paths and a directory."""
candidates: list[Path] = []
@@ -53,12 +60,33 @@ def _collect_documents(docs: list[str], docs_dir: Optional[str]) -> list[str]:
def register(app: typer.Typer) -> None:
@app.command("list")
- def kb_list() -> None:
+ def kb_list(
+ fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),
+ ) -> None:
"""List all knowledge bases."""
- mgr = KnowledgeBaseManager()
+ mgr = _get_kb_manager()
kb_names = mgr.list_knowledge_bases()
if not kb_names:
- console.print("[dim]No knowledge bases found.[/]")
+ if fmt == "json":
+ console.print_json("[]")
+ else:
+ console.print("[dim]No knowledge bases found.[/]")
+ return
+
+ if fmt == "json":
+ items = []
+ for name in kb_names:
+ info = mgr.get_info(name)
+ stats = info.get("statistics", {})
+ metadata = info.get("metadata", {})
+ items.append({
+ "name": name,
+ "status": info.get("status", "unknown"),
+ "documents": stats.get("raw_documents", 0),
+ "rag_provider": metadata.get("rag_provider", stats.get("rag_provider", DEFAULT_PROVIDER)),
+ "is_default": bool(info.get("is_default")),
+ })
+ console.print_json(json.dumps(items, ensure_ascii=False, default=str))
return
table = Table(title="Knowledge Bases")
@@ -85,7 +113,7 @@ def register(app: typer.Typer) -> None:
@app.command("info")
def kb_info(name: str = typer.Argument(..., help="Knowledge base name.")) -> None:
"""Show details of a knowledge base."""
- mgr = KnowledgeBaseManager()
+ mgr = _get_kb_manager()
try:
info = mgr.get_info(name)
except Exception as exc:
@@ -96,7 +124,7 @@ def register(app: typer.Typer) -> None:
@app.command("set-default")
def kb_set_default(name: str = typer.Argument(..., help="Knowledge base name.")) -> None:
"""Set the default knowledge base."""
- mgr = KnowledgeBaseManager()
+ mgr = _get_kb_manager()
try:
mgr.set_default(name)
except Exception as exc:
@@ -111,7 +139,7 @@ def register(app: typer.Typer) -> None:
docs_dir: Optional[str] = typer.Option(None, "--docs-dir", help="Directory of documents."),
) -> None:
"""Initialize a new knowledge base from documents."""
- mgr = KnowledgeBaseManager()
+ mgr = _get_kb_manager()
if name in mgr.list_knowledge_bases():
console.print(f"[red]Knowledge base '{name}' already exists.[/]")
raise typer.Exit(code=1)
@@ -152,7 +180,7 @@ def register(app: typer.Typer) -> None:
docs_dir: Optional[str] = typer.Option(None, "--docs-dir", help="Directory of documents."),
) -> None:
"""Add documents to an existing knowledge base."""
- mgr = KnowledgeBaseManager()
+ mgr = _get_kb_manager()
if name not in mgr.list_knowledge_bases():
console.print(f"[red]Knowledge base '{name}' not found.[/]")
raise typer.Exit(code=1)
@@ -199,7 +227,7 @@ def register(app: typer.Typer) -> None:
if not confirm:
raise typer.Abort()
- mgr = KnowledgeBaseManager()
+ mgr = _get_kb_manager()
try:
deleted = mgr.delete_knowledge_base(name, confirm=True)
except Exception as exc:
@@ -221,7 +249,7 @@ def register(app: typer.Typer) -> None:
"""Search a knowledge base."""
from deeptutor.tools.rag_tool import rag_search
- mgr = KnowledgeBaseManager()
+ mgr = _get_kb_manager()
if name not in mgr.list_knowledge_bases():
console.print(f"[red]Knowledge base '{name}' not found.[/]")
raise typer.Exit(code=1)
diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.py
index 1086f6b4b..15427d40b 100644
--- a/deeptutor_cli/main.py
+++ b/deeptutor_cli/main.py
@@ -1,14 +1,12 @@
"""CLI entry point for the standalone ``deeptutor-cli`` package."""
from __future__ import annotations
-
-import json
-
import typer
from deeptutor.runtime.mode import RunMode, set_mode
from deeptutor.services.setup import get_backend_port
+from .bot import register as register_bot
from .chat import register as register_chat
from .common import build_turn_request, console, maybe_run
from .config_cmd import register as register_config
@@ -23,12 +21,13 @@ set_mode(RunMode.CLI)
app = typer.Typer(
name="deeptutor",
- help="DeepTutor CLI – fully usable without starting the web server.",
+ help="DeepTutor CLI – agent-first interface for capabilities, tools, and knowledge.",
no_args_is_help=True,
add_completion=False,
)
-chat_app = typer.Typer(help="Interactive chat and one-shot turns.")
+bot_app = typer.Typer(help="Manage TutorBot instances.")
+chat_app = typer.Typer(help="Interactive chat REPL.")
kb_app = typer.Typer(help="Manage knowledge bases.")
memory_app = typer.Typer(help="View and manage lightweight memory.")
plugin_app = typer.Typer(help="List plugins.")
@@ -37,6 +36,7 @@ session_app = typer.Typer(help="Manage shared sessions.")
notebook_app = typer.Typer(help="Manage notebooks and imported markdown records.")
provider_app = typer.Typer(help="Manage provider OAuth login.")
+app.add_typer(bot_app, name="bot")
app.add_typer(chat_app, name="chat")
app.add_typer(kb_app, name="kb")
app.add_typer(memory_app, name="memory")
@@ -46,6 +46,7 @@ app.add_typer(session_app, name="session")
app.add_typer(notebook_app, name="notebook")
app.add_typer(provider_app, name="provider")
+register_bot(bot_app)
register_chat(chat_app)
register_kb(kb_app)
register_memory(memory_app)
@@ -58,7 +59,7 @@ register_provider(provider_app)
@app.command("run")
def run_capability(
- capability: str = typer.Argument(..., help="Capability name or CLI alias."),
+ capability: str = typer.Argument(..., help="Capability name (e.g. chat, deep_solve, deep_question, deep_research, math_animator)."),
message: str = typer.Argument(..., help="Message to send."),
session: str | None = typer.Option(None, "--session", help="Existing session id."),
tool: list[str] = typer.Option([], "--tool", "-t", help="Enabled tool(s)."),
@@ -70,7 +71,7 @@ def run_capability(
config_json: str | None = typer.Option(None, "--config-json", help="Capability config as JSON."),
fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),
) -> None:
- """Run any capability through the unified turn runtime."""
+ """Run any capability in a single turn (agent-first entry point)."""
from deeptutor.app import DeepTutorApp
from .common import run_turn_and_render
@@ -89,148 +90,6 @@ def run_capability(
maybe_run(run_turn_and_render(app=DeepTutorApp(), request=request, fmt=fmt))
-def solve(
- message: str = typer.Argument(..., help="Problem to solve."),
- session: str | None = typer.Option(None, "--session", help="Existing session id."),
- tool: list[str] = typer.Option([], "--tool", "-t", help="Enabled tool(s)."),
- kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),
- notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),
- history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),
- language: str = typer.Option("en", "--language", "-l", help="Response language."),
- detailed_answer: bool = typer.Option(True, "--detailed-answer/--brief-answer", help="Control deep solve detail."),
- fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),
-) -> None:
- """Alias for ``run deep_solve``."""
- _run_alias(
- capability="deep_solve",
- message=message,
- session=session,
- tool=tool,
- kb=kb,
- notebook_ref=notebook_ref,
- history_ref=history_ref,
- language=language,
- fmt=fmt,
- config_items=[f"detailed_answer={str(detailed_answer).lower()}"],
- config_json=None,
- )
-
-
-def quiz(
- message: str = typer.Argument(..., help="Topic or instruction for quiz generation."),
- session: str | None = typer.Option(None, "--session", help="Existing session id."),
- tool: list[str] = typer.Option([], "--tool", "-t", help="Enabled tool(s)."),
- kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),
- notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),
- history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),
- language: str = typer.Option("en", "--language", "-l", help="Response language."),
- mode: str = typer.Option("custom", "--mode", help="Quiz mode: custom | mimic."),
- num_questions: int = typer.Option(1, "--num-questions", help="Number of questions."),
- difficulty: str = typer.Option("", "--difficulty", help="Difficulty hint."),
- question_type: str = typer.Option("", "--question-type", help="Question type hint."),
- preference: str = typer.Option("", "--preference", help="Preference hint."),
- paper_path: str = typer.Option("", "--paper-path", help="Parsed exam paper path."),
- max_questions: int = typer.Option(10, "--max-questions", help="Question limit for mimic mode."),
- fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),
-) -> None:
- """Alias for ``run deep_question``."""
- _run_alias(
- capability="deep_question",
- message=message,
- session=session,
- tool=tool,
- kb=kb,
- notebook_ref=notebook_ref,
- history_ref=history_ref,
- language=language,
- fmt=fmt,
- config_items=[
- f"mode={mode}",
- f"num_questions={num_questions}",
- f"difficulty={difficulty}",
- f"question_type={question_type}",
- f"preference={preference}",
- f"paper_path={paper_path}",
- f"max_questions={max_questions}",
- ],
- config_json=None,
- )
-
-
[email protected]("research")
-def research(
- message: str = typer.Argument(..., help="Research prompt."),
- session: str | None = typer.Option(None, "--session", help="Existing session id."),
- tool: list[str] = typer.Option([], "--tool", "-t", help="Additional tools."),
- kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),
- notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),
- history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),
- language: str = typer.Option("en", "--language", "-l", help="Response language."),
- mode: str = typer.Option(..., "--mode", help="Research mode: notes | report | comparison | learning_path."),
- depth: str = typer.Option(..., "--depth", help="Research depth: quick | standard | deep."),
- source: list[str] = typer.Option(..., "--source", help="Research source(s): kb | web | papers."),
- fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),
-) -> None:
- """Alias for ``run deep_research``."""
- config_json = {
- "mode": mode,
- "depth": depth,
- "sources": source,
- }
- _run_alias(
- capability="deep_research",
- message=message,
- session=session,
- tool=tool,
- kb=kb,
- notebook_ref=notebook_ref,
- history_ref=history_ref,
- language=language,
- fmt=fmt,
- config_items=[],
- config_json=json.dumps(config_json, ensure_ascii=False),
- )
-
-
-def animate(
- message: str = typer.Argument(..., help="Animation prompt."),
- session: str | None = typer.Option(None, "--session", help="Existing session id."),
- language: str = typer.Option("en", "--language", "-l", help="Response language."),
- output_mode: str = typer.Option(
- "video",
- "--output-mode",
- help="video | image (legacy aliases: frames | storyboard)",
- ),
- quality: str = typer.Option("medium", "--quality", help="low | medium | high"),
- style_hint: str = typer.Option("", "--style-hint", help="Visual style hint."),
- fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),
-) -> None:
- """Alias for ``run math_animator``."""
- normalized_output_mode = output_mode
- if output_mode in {"frames", "storyboard"}:
- normalized_output_mode = "image"
- _run_alias(
- capability="math_animator",
- message=message,
- session=session,
- tool=[],
- kb=[],
- notebook_ref=[],
- history_ref=[],
- language=language,
- fmt=fmt,
- config_items=[
- f"output_mode={normalized_output_mode}",
- f"quality={quality}",
- f"style_hint={style_hint}",
- ],
- config_json=None,
- )
-
-
@app.command()
def serve(
host: str = typer.Option("0.0.0.0", help="Bind address."),
@@ -244,7 +103,7 @@ def serve(
except ImportError:
console.print(
"[bold red]Error:[/] API server dependencies not installed.\n"
- "Run: pip install 'deeptutor[server]' or pip install -r requirements/server.txt"
+ "Run: pip install -r requirements/server.txt"
)
raise typer.Exit(code=1)
@@ -257,38 +116,6 @@ def serve(
)
-def _run_alias(
- *,
- capability: str,
- message: str,
- session: str | None,
- tool: list[str],
- kb: list[str],
- notebook_ref: list[str],
- history_ref: list[str],
- language: str,
- fmt: str,
- config_items: list[str],
- config_json: str | None,
-) -> None:
- from deeptutor.app import DeepTutorApp
- from .common import run_turn_and_render
-
- request = build_turn_request(
- content=message,
- capability=capability,
- session_id=session,
- tools=tool,
- knowledge_bases=kb,
- language=language,
- config_items=config_items,
- config_json=config_json,
- notebook_refs=notebook_ref,
- history_refs=history_ref,
- )
- maybe_run(run_turn_and_render(app=DeepTutorApp(), request=request, fmt=fmt))
-
-
def main() -> None:
app()
diff --git a/deeptutor_cli/memory.py b/deeptutor_cli/memory.py
index e0456b508..3eff771cb 100644
--- a/deeptutor_cli/memory.py
+++ b/deeptutor_cli/memory.py
@@ -1,11 +1,9 @@
"""
-CLI memory command.
+CLI memory commands for the two-file public memory system (SUMMARY/PROFILE).
"""
from __future__ import annotations
-from pathlib import Path
-
import typer
from rich.console import Console
from rich.markdown import Markdown
@@ -16,47 +14,55 @@ from deeptutor.services.memory import get_memory_service
console = Console()
-def _get_memory_path() -> Path:
- return get_memory_service().memory_path
-
-
def register(app: typer.Typer) -> None:
@app.command("show")
- def memory_show() -> None:
- """Display the current long-term memory."""
- snapshot = get_memory_service().read_snapshot()
- if snapshot.content:
- console.print(Panel(Markdown(snapshot.content), title="[bold]memory.md[/]"))
+ def memory_show(
+ file: str = typer.Argument(
+ "all", help="File to show: summary, profile, or all.",
+ ),
+ ) -> None:
+ """Display memory file content."""
+ svc = get_memory_service()
+ if file == "all":
+ snap = svc.read_snapshot()
+ for label, content in [
+ ("SUMMARY", snap.summary),
+ ("PROFILE", snap.profile),
+ ]:
+ if content:
+ console.print(Panel(Markdown(content), title=f"[bold]{label}.md[/]"))
+ else:
+ console.print(f"[dim]{label}.md: (empty)[/]")
+ elif file in ("summary", "profile"):
+ content = svc.read_file(file)
+ if content:
+ console.print(Panel(Markdown(content), title=f"[bold]{file.upper()}.md[/]"))
+ else:
+ console.print(f"[dim]{file.upper()}.md: (empty)[/]")
else:
- console.print("[dim]memory.md: (empty)[/]")
+ console.print(f"[red]Unknown file: {file}. Use summary, profile, or all.[/]")
@app.command("clear")
def memory_clear(
+ file: str = typer.Argument(
+ "all", help="File to clear: summary, profile, or all.",
+ ),
force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation."),
) -> None:
- """Clear the long-term memory file."""
+ """Clear memory file(s)."""
+ svc = get_memory_service()
+ if file not in ("summary", "profile", "all"):
+ console.print(f"[red]Unknown file: {file}[/]")
+ raise typer.Exit(1)
+
if not force:
- confirm = typer.confirm("Clear memory.md?")
- if not confirm:
+ target = "all memory files" if file == "all" else f"{file.upper()}.md"
+ if not typer.confirm(f"Clear {target}?"):
raise typer.Abort()
- path = _get_memory_path()
- get_memory_service().clear_memory()
- console.print(f"[green]Cleared {path.name}.[/]")
-
- @app.command("export")
- def memory_export(
- dest: str = typer.Argument(..., help="Destination directory."),
- ) -> None:
- """Export memory.md to a directory."""
- import shutil
-
- source = _get_memory_path()
- if not source.exists():
- console.print("[yellow]memory.md is empty.[/]")
- return
-
- dest_path = Path(dest)
- dest_path.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source, dest_path / source.name)
- console.print(f"[green]Exported {source.name} to {dest_path}[/]")
+ if file == "all":
+ svc.clear_memory()
+ console.print("[green]Cleared all memory files.[/]")
+ else:
+ svc.clear_file(file)
+ console.print(f"[green]Cleared {file.upper()}.md.[/]")
diff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.py
index 7ef3d40cd..ab8a9218f 100644
--- a/deeptutor_cli/provider_cmd.py
+++ b/deeptutor_cli/provider_cmd.py
@@ -33,8 +33,8 @@ def _login_openai_codex() -> None:
from oauth_cli_kit import get_token, login_oauth_interactive
except ImportError:
typer.echo(
- "oauth_cli_kit is not installed. Install optional deps: "
- "pip install -r requirements/providers.txt"
+ "oauth_cli_kit is not installed. Install CLI deps: "
+ "pip install -r requirements/cli.txt"
)
raise typer.Exit(code=1)
@@ -58,7 +58,7 @@ async def _login_github_copilot() -> None:
try:
from litellm import acompletion
except ImportError:
- typer.echo("litellm is not installed. Install core deps: pip install -r requirements/core.txt")
+ typer.echo("litellm is not installed. Install CLI deps: pip install -r requirements/cli.txt")
raise typer.Exit(code=1)
try:
await acompletion(
diff --git a/nanobot b/nanobot
deleted file mode 160000
index 65cbd7eb7..000000000
--- a/nanobot
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 65cbd7eb78672e226a8108c81da3ed8ce50ab192
diff --git a/paper/2510.12323v1.pdf b/paper/2510.12323v1.pdf
deleted file mode 100644
index fd9bfdbf9..000000000
Binary files a/paper/2510.12323v1.pdf and /dev/null differ
diff --git a/paper/COMMENTS.md b/paper/COMMENTS.md
deleted file mode 100644
index 8b7b5a64e..000000000
--- a/paper/COMMENTS.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# Evaluation Summary - Overall
-
-- Generated at: 2026-03-14T16:09:36.638022
-- Output root: `/data2/zjh/DeepTutor/benchmark/data/bench_pipeline`
-- Eval files: 15
-- Backends: 5
-
-## Metrics Table
-
-
-| Backend | Profiles | Faith | Personal. | Applic. | Vivid. | Logic | Faith Fail | Teach Fail | PQ Fail | PQ Fitness | PQ Ground | PQ Diversity | PQ AnsQual | PQ Cross |
-| ------------------------ | -------- | ------ | --------- | ------- | ------ | ------ | ---------- | ---------- | ------- | ---------- | --------- | ------------ | ---------- | -------- |
-| deep_tutor | 3 | 3.6465 | 4.5737 | 4.7111 | 4.7995 | 4.6269 | 0.00% | 0.00% | 0.00% | 4.1111 | 2.8222 | 3.1556 | 4.5556 | 3.5334 |
-| deep_tutor_no_memory | 3 | 3.2921 | 4.1556 | 4.6878 | 4.7778 | 4.6222 | 0.00% | 0.00% | 0.00% | 3.6500 | 2.7555 | 3.0778 | 4.2389 | 3.3278 |
-| deep_tutor_no_rag | 3 | 3.3750 | 4.0677 | 4.6635 | 4.7984 | 4.5570 | 0.00% | 0.00% | 0.00% | 3.7333 | 2.6667 | 3.0889 | 4.2667 | 3.4667 |
-| deep_tutor_no_rag_memory | 3 | 3.2738 | 4.0667 | 4.7094 | 4.7026 | 4.6616 | 0.00% | 0.00% | 0.00% | 3.9556 | 2.7111 | 2.8444 | 4.3111 | 3.2222 |
-| mock | 3 | 3.2998 | 3.8615 | 4.5272 | 3.9509 | 4.0719 | 0.00% | 0.00% | 0.00% | 4.0222 | 2.8000 | 2.7111 | 4.2445 | 3.2667 |
-
-
diff --git a/paper/REVIEW.md b/paper/REVIEW.md
deleted file mode 100644
index 6f6bcb3b3..000000000
--- a/paper/REVIEW.md
+++ /dev/null
@@ -1,105 +0,0 @@
-Review Form
-Paper Summary
-Describe what this paper is about. This should help action editors and area chairs to understand the topic of the work and highlight any possible misunderstandings.
-
-Summary of Strengths
-What are the major reasons to publish this paper at a selective *ACL venue? These could include novel and useful methodology, insightful empirical results or theoretical analysis, clear organization of related literature, or any other reason why interested readers of *ACL papers may find the paper useful.
-
-Summary of Weaknesses
-What are the concerns that you have about the paper that would cause you to favor prioritizing other high-quality papers that are also under consideration for publication? These could include concerns about correctness of the results or argumentation, limited perceived impact of the methods or findings (note that impact can be significant both in broad or in narrow sub-fields), lack of clarity in exposition, or any other reason why interested readers of *ACL papers may gain less from this paper than they would from other papers under consideration. Where possible, please number your concerns so authors may respond to them individually.
-
-Comments/Suggestions/Typos
-If you have any comments to the authors about how they may improve their paper, other than addressing the concerns above, please list them here.
-
-Reviewer Confidence
-5 = Positive that my evaluation is correct. I read the paper very carefully and am familiar with related work.
-4 = Quite sure. I tried to check the important points carefully. It’s unlikely, though conceivable, that I missed something that should affect my ratings.
-3 = Pretty sure, but there’s a chance I missed something. Although I have a good feel for this area in general, I did not carefully check the paper’s details, e.g., the math or experimental design.
-2 = Willing to defend my evaluation, but it is fairly likely that I missed some details, didn’t understand some central points, or can’t be sure about the novelty of the work.
-1 = Not my area, or paper is very hard to understand. My evaluation is just an educated guess.
-Soundness
-Given that this is a short/long paper, is it sufficiently sound and thorough? Does it clearly state scientific claims and provide adequate support for them? For experimental papers: consider the depth and/or breadth of the research questions investigated, technical soundness of experiments, methodological validity of evaluation. For position papers, surveys: consider whether the current state of the field is adequately represented and main counter-arguments acknowledged. For resource papers: consider the data collection methodology, resulting data & the difference from existing resources are described in sufficient detail.
-
-5 = Excellent: This study is one of the most thorough I have seen, given its type.
-4.5
-4 = Strong: This study provides sufficient support for all of its claims. Some extra experiments could be nice, but not essential.
-3.5
-3 = Acceptable: This study provides sufficient support for its main claims. Some minor points may need extra support or details.
-2.5
-2 = Poor: Some of the main claims are not sufficiently supported. There are major technical/methodological problems.
-1.5
-1 = Major Issues: This study is not yet sufficiently thorough to warrant publication or is not relevant to ACL.
-Excitement
-How exciting is this paper for you? Excitement is subjective, and does not necessarily follow what is popular in the field. We may perceive papers as transformational/innovative/surprising, e.g. because they present conceptual breakthroughs or evidence challenging common assumptions/methods/datasets/metrics. We may be excited about the possible impact of the paper on some community (not necessarily large or our own), e.g. lowering barriers, reducing costs, enabling new applications. We may be excited for papers that are relevant, inspiring, or useful for our own research. These factors may combine in different ways for different reviewers.
-
-5 = Highly Exciting: I would recommend this paper to others and/or attend its presentation in a conference.
-4.5
-4 = Exciting: I would mention this paper to others and/or make an effort to attend its presentation in a conference.
-3.5
-3 = Interesting: I might mention some points of this paper to others and/or attend its presentation in a conference if there’s time.
-2.5
-2 = Potentially Interesting: this paper does not resonate with me, but it might with others in the *ACL community.
-1.5
-1 = Not Exciting: this paper does not resonate with me, and I don’t think it would with others in the *ACL community (e.g. it is in no way related to computational processing of language).
-Overall Assessment
-If this paper was committed to an *ACL conference, do you believe it should be accepted? If you recommend conference, Findings and or even award consideration, you can still suggest minor revisions (e.g. typos, non-core missing refs, etc.).
-
-Outstanding papers should be either fascinating, controversial, surprising, impressive, or potentially field-changing. Awards will be decided based on the camera-ready version of the paper. ACL award policy: https://www.aclweb.org/adminwiki/index.php/ACL_Conference_Awards_Policy
-
-Main vs Findings papers: the main criteria for Findings are soundness and reproducibility. Conference recommendations may also consider novelty, impact and other factors.
-
-5 = Consider for Award: I think this paper could be considered for an outstanding paper award at an *ACL conference (up to top 2.5% papers).
-4.5 = Borderline Award
-4 = Conference: I think this paper could be accepted to an *ACL conference.
-3.5 = Borderline Conference
-3 = Findings: I think this paper could be accepted to the Findings of the ACL.
-2.5 = Borderline Findings
-2 = Resubmit next cycle: I think this paper needs substantial revisions that can be completed by the next ARR cycle.
-1.5 = Resubmit after next cycle: I think this paper needs substantial revisions that cannot be completed by the next ARR cycle.
-1 = Do not resubmit: This paper has to be fully redone, or it is not relevant to the *ACL community (e.g. it is in no way related to computational processing of language).
-Best paper justification
-If your overall assessment for this paper is either ‘Consider for award’ or ‘Borderline award’, please briefly describe why.
-
-Further Questions
-Limitations and Societal Impact
-Have the authors adequately discussed the limitations and potential positive and negative societal impacts of their work? If not, please include constructive suggestions for improvement. Authors should be rewarded rather than punished for being up front about the limitations of their work and any potential negative societal impact. You are encouraged to think through whether any critical points are missing and provide these as feedback for the authors. Consider, for example, cases of exclusion of user groups, overgeneralization of findings, unfair impacts on traditionally marginalized populations, bias confirmation, under- and overexposure of languages or approaches, and dual use (see Hovy and Spruit, 2016, for examples of those). Consider who benefits from the technology if it is functioning as intended, as well as who might be harmed, and how. Consider the failure modes, and in case of failure, who might be harmed and how.
-
-Ethical Concerns
-Please review the ACL code of ethics (https://www.aclweb.org/portal/content/acl-code-ethics) and the ARR checklist submitted by the authors in the submission form. If there are ethical issues with this paper, please describe them and the extent to which they have been acknowledged or addressed by the authors.
-
-Needs Ethics Review
-Should this paper be sent for an in-depth ethics review? We have a small ethics committee that can specially review very challenging papers when it comes to ethical issues. If this seems to be such a paper, then please explain why here, and we will try to ensure that it receives a separate review.
-
-Reproducibility
-Is there enough information in this paper for a reader to reproduce the main results, use results presented in this paper in future work (e.g., as a baseline), or build upon this work?
-
-5 = They could easily reproduce the results.
-4 = They could mostly reproduce the results, but there may be some variation because of sample variance or minor variations in their interpretation of the protocol or method.
-3 = They could reproduce the results with some difficulty. The settings of parameters are underspecified or subjectively determined, and/or the training/evaluation data are not widely available.
-2 = They would be hard pressed to reproduce the results: The contribution depends on data that are simply not available outside the author’s institution or consortium and/or not enough details are provided.
-1 = They would not be able to reproduce the results here no matter how hard they tried.
-Datasets
-If the authors state (in anonymous fashion) that datasets will be released, how valuable will they be to others?
-
-5 = Enabling: The newly released datasets should affect other people’s choice of research or development projects to undertake.
-4 = Useful: I would recommend the new datasets to other researchers or developers for their ongoing work.
-3 = Potentially useful: Someone might find the new datasets useful for their work.
-2 = Documentary: The new datasets will be useful to study or replicate the reported research, although for other purposes they may have limited interest or limited usability. (Still a positive rating)
-1 = No usable datasets submitted.
-Software
-If the authors state (in anonymous fashion) that their software will be available, how valuable will it be to others?
-
-5 = Enabling: The newly released software should affect other people’s choice of research or development projects to undertake.
-4 = Useful: I would recommend the new software to other researchers or developers for their ongoing work.
-3 = Potentially useful: Someone might find the new software useful for their work.
-2 = Documentary: The new software will be useful to study or replicate the reported research, although for other purposes it may have limited interest or limited usability. (Still a positive rating)
-1 = No usable software released.
-Knowledge of/educated guess at author identity
-5 = From a violation of double-blind-submission rules, I know/can guess at least one author’s name. (Note that non-anonymous preprints are permitted at any time, so this is not a violation.)
-4 = From a preprint or allowed workshop paper, I know/can guess at least one author’s name.
-3 = From the contents of the submission itself, I know/can guess at least one author’s name.
-2 = From social media/a talk/other informal communication, I know/can guess at least one author’s name.
-1 = I do not have even an educated guess about author identity.
-(Optional) Conjecture as to author identity. Authors will not see your response.
-
-
\ No newline at end of file
diff --git a/paper/custom.bib b/paper/custom.bib
deleted file mode 100644
index a16395636..000000000
--- a/paper/custom.bib
+++ /dev/null
@@ -1,269 +0,0 @@
-@misc{yao2023reactsynergizingreasoningacting,
- title = {ReAct: Synergizing Reasoning and Acting in Language Models},
- author = {Shunyu Yao and Jeffrey Zhao and Dian Yu and Nan Du and Izhak Shafran and Karthik Narasimhan and Yuan Cao},
- year = {2023},
- eprint = {2210.03629},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL},
- url = {https://arxiv.org/abs/2210.03629},
- doi = {10.48550/arXiv.2210.03629}
-}
-
-@misc{zhao2025llmbasedagenticreasoningframeworks,
- title = {LLM-based Agentic Reasoning Frameworks: A Survey from Methods to Scenarios},
- author = {Bingxi Zhao and Lin Geng Foo and Ping Hu and Christian Theobalt and Hossein Rahmani and Jun Liu},
- year = {2025},
- eprint = {2508.17692},
- archivePrefix = {arXiv},
- primaryClass = {cs.AI},
- url = {https://arxiv.org/abs/2508.17692},
- doi = {10.48550/arXiv.2508.17692}
-}
-
-@inproceedings{wu-etal-2025-agentic,
- title = {Agentic Reasoning: A Streamlined Framework for Enhancing {LLM} Reasoning with Agentic Tools},
- author = {Wu, Junde and Zhu, Jiayuan and Liu, Yuyuan and Xu, Min and Jin, Yueming},
- booktitle = {Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
- month = jul,
- year = {2025},
- address = {Vienna, Austria},
- publisher = {Association for Computational Linguistics},
- url = {https://aclanthology.org/2025.acl-long.1383/},
- doi = {10.18653/v1/2025.acl-long.1383},
- pages = {28489--28503}
-}
-
-@misc{li2025intheflowagenticoptimizationeffective,
- title = {In-the-Flow Agentic System Optimization for Effective Planning and Tool Use},
- author = {Zhuofeng Li and Haoxiang Zhang and Seungju Han and Sheng Liu and Jianwen Xie and Yu Zhang and Yejin Choi and James Zou and Pan Lu},
- year = {2025},
- eprint = {2510.05592},
- archivePrefix = {arXiv},
- primaryClass = {cs.AI},
- url = {https://arxiv.org/abs/2510.05592},
- doi = {10.48550/arXiv.2510.05592}
-}
-
-@inproceedings{tan-etal-2025-prospect,
- title = {In Prospect and Retrospect: Reflective Memory Management for Long-term Personalized Dialogue Agents},
- author = {Tan, Zhen and Yan, Jun and Hsu, I-Hung and Han, Rujun and Wang, Zifeng and Le, Long and Song, Yiwen and Chen, Yanfei and Palangi, Hamid and Lee, George and Iyer, Anand Rajan and Chen, Tianlong and Liu, Huan and Lee, Chen-Yu and Pfister, Tomas},
- booktitle = {Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
- month = jul,
- year = {2025},
- address = {Vienna, Austria},
- publisher = {Association for Computational Linguistics},
- url = {https://aclanthology.org/2025.acl-long.413/},
- doi = {10.18653/v1/2025.acl-long.413},
- pages = {8416--8439}
-}
-
-@inproceedings{cho-etal-2022-personalized,
- title = {A Personalized Dialogue Generator with Implicit User Persona Detection},
- author = {Cho, Itsugun and Wang, Dongyang and Takahashi, Ryota and Saito, Hiroaki},
- booktitle = {Proceedings of the 29th International Conference on Computational Linguistics},
- month = oct,
- year = {2022},
- address = {Gyeongju, Republic of Korea},
- publisher = {International Committee on Computational Linguistics},
- url = {https://aclanthology.org/2022.coling-1.29/},
- pages = {367--377},
- doi = {10.48550/arXiv.2204.07372}
-}
-
-@inproceedings{li-etal-2025-hello,
- title = {Hello Again! {LLM}-powered Personalized Agent for Long-term Dialogue},
- author = {Li, Hao and Yang, Chenghao and Zhang, An and Deng, Yang and Wang, Xiang and Chua, Tat-Seng},
- booktitle = {Proceedings of the 2025 Conference of the Nations of the Americas Chapter of the Association for Computational Linguistics: Human Language Technologies (Volume 1: Long Papers)},
- month = apr,
- year = {2025},
- address = {Albuquerque, New Mexico},
- publisher = {Association for Computational Linguistics},
- url = {https://aclanthology.org/2025.naacl-long.272/},
- doi = {10.18653/v1/2025.naacl-long.272},
- pages = {5259--5276}
-}
-
-@misc{wang2024agentworkflowmemory,
- title = {Agent Workflow Memory},
- author = {Zora Zhiruo Wang and Jiayuan Mao and Daniel Fried and Graham Neubig},
- year = {2024},
- eprint = {2409.07429},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL},
- url = {https://arxiv.org/abs/2409.07429},
- doi = {10.48550/arXiv.2409.07429}
-}
-
-@misc{li2025surveypersonalizationragagent,
- title = {A Survey of Personalization: From RAG to Agent},
- author = {Xiaopeng Li and Pengyue Jia and Derong Xu and Yi Wen and Yingyi Zhang and Wenlin Zhang and Wanyu Wang and Yichao Wang and Zhaocheng Du and Xiangyang Li and Yong Liu and Huifeng Guo and Ruiming Tang and Xiangyu Zhao},
- year = {2025},
- eprint = {2504.10147},
- archivePrefix = {arXiv},
- primaryClass = {cs.IR},
- url = {https://arxiv.org/abs/2504.10147},
- doi = {10.48550/arXiv.2504.10147}
-}
-
-@misc{guo2025raganythingallinoneragframework,
- title = {RAG-Anything: All-in-One RAG Framework},
- author = {Zirui Guo and Xubin Ren and Lingrui Xu and Jiahao Zhang and Chao Huang},
- year = {2025},
- eprint = {2510.12323},
- archivePrefix = {arXiv},
- primaryClass = {cs.AI},
- url = {https://arxiv.org/abs/2510.12323},
- doi = {10.48550/arXiv.2510.12323}
-}
-
-@article{letourneau2025systematicreviewaidriven,
- title = {A systematic review of AI-driven intelligent tutoring systems (ITS) in K-12 education},
- author = {L{\'e}tourneau, Ang{\'e}lique and Deslandes Martineau, Marion and Charland, Patrick and Karran, John Alexander and Boasen, Jared and L{\'e}ger, Pierre Majorique},
- journal = {npj Science of Learning},
- volume = {10},
- number = {1},
- year = {2025},
- month = may,
- publisher = {Springer Science and Business Media LLC},
- doi = {10.1038/s41539-025-00320-7},
- url = {https://doi.org/10.1038/s41539-025-00320-7}
-}
-
-@inproceedings{park2024empoweringpersonalizedlearning,
- title = {Empowering Personalized Learning through a Conversation-based Tutoring System with Student Modeling},
- author = {Park, Minju and Kim, Sojung and Lee, Seunghyun and Kwon, Soonwoo and Kim, Kyuseok},
- booktitle = {Extended Abstracts of the CHI Conference on Human Factors in Computing Systems},
- series = {CHI '24},
- pages = {1--10},
- year = {2024},
- month = may,
- publisher = {ACM},
- doi = {10.1145/3613905.3651122},
- url = {https://doi.org/10.1145/3613905.3651122}
-}
-
-@misc{wang2025llmpoweredmultiagentframeworkgoaloriented,
- title = {LLM-powered Multi-agent Framework for Goal-oriented Learning in Intelligent Tutoring System},
- author = {Tianfu Wang and Yi Zhan and Jianxun Lian and Zhengyu Hu and Nicholas Jing Yuan and Qi Zhang and Xing Xie and Hui Xiong},
- year = {2025},
- eprint = {2501.15749},
- archivePrefix = {arXiv},
- primaryClass = {cs.AI},
- url = {https://arxiv.org/abs/2501.15749},
- doi = {10.48550/arXiv.2501.15749}
-}
-
-@inproceedings{frankford2024aitutoringsoftwareengineering,
- title = {AI-Tutoring in Software Engineering Education},
- author = {Frankford, Eduard and Sauerwein, Clemens and Bassner, Patrick and Krusche, Stephan and Breu, Ruth},
- booktitle = {Proceedings of the 46th International Conference on Software Engineering: Software Engineering Education and Training},
- series = {ICSE-SEET '24},
- pages = {309--319},
- year = {2024},
- month = apr,
- publisher = {ACM},
- doi = {10.1145/3639474.3640061},
- url = {https://doi.org/10.1145/3639474.3640061}
-}
-
-% ===========================================================================
-% Benchmark References
-% ===========================================================================
-
-@misc{phan2025hle,
- title = {Humanity's Last Exam},
- author = {Long Phan and Alice Gatti and Ziwen Han and Nathaniel Li and Josephina Hu and Hugh Zhang and Sean Shi and Michael Byun and Len Sohl-Dickstein and Leonard Tang and others},
- year = {2025},
- eprint = {2501.14249},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL},
- url = {https://arxiv.org/abs/2501.14249}
-}
-
-@misc{rein2023gpqa,
- title = {{GPQA}: A Graduate-Level Google-Proof Q\&A Benchmark},
- author = {David Rein and Betty Li Hou and Asa Cooper Stickland and Jackson Petty and Richard Yuanzhe Pang and Julien Dirani and Julian Michael and Samuel R. Bowman},
- year = {2023},
- eprint = {2311.12022},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL},
- url = {https://arxiv.org/abs/2311.12022}
-}
-
-@misc{mialon2023gaia,
- title = {{GAIA}: A Benchmark for General {AI} Assistants},
- author = {Gr{\'e}goire Mialon and Cl{\'e}mentine Fourrier and Craig Swift and Thomas Wolf and Yann LeCun and Thomas Scialom},
- year = {2023},
- eprint = {2311.12983},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL},
- url = {https://arxiv.org/abs/2311.12983}
-}
-
-@misc{white2024livebench,
- title = {{LiveBench}: A Challenging, Contamination-Free {LLM} Benchmark},
- author = {Colin White and Samuel Dooley and Manley Roberts and Arka Pal and Ben Feuer and Siddhartha Jain and Ravid Shwartz-Ziv and Neel Jain and Khalid Saifullah and Siddartha Naidu and others},
- year = {2024},
- eprint = {2406.19314},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL},
- url = {https://arxiv.org/abs/2406.19314}
-}
-
-@misc{aalcr2024,
- title = {{AA-LCR}: Artificial Analysis Long Context Reasoning Benchmark},
- author = {{Artificial Analysis}},
- year = {2024},
- howpublished = {\url{https://huggingface.co/datasets/ArtificialAnalysis/AA-LCR}},
- note = {100 human-crafted questions requiring multi-step reasoning across long documents}
-}
-
-@misc{openai2023gpt4,
- title = {{GPT-4} Technical Report},
- author = {{OpenAI}},
- year = {2023},
- eprint = {2303.08774},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL},
- url = {https://arxiv.org/abs/2303.08774}
-}
-
-@article{kurdi2020systematic,
- title = {A Systematic Review of Automatic Question Generation for Educational Purposes},
- author = {Kurdi, Ghader and Leo, Jared and Parsia, Bijan and Sattler, Uli and Al-Emari, Salam},
- journal = {International Journal of Artificial Intelligence in Education},
- volume = {30},
- pages = {121--204},
- year = {2020},
- publisher = {Springer},
- doi = {10.1007/s40593-019-00186-y}
-}
-
-@misc{lewkowycz2022solving,
- title = {Solving Quantitative Reasoning Problems with Language Models},
- author = {Aitor Lewkowycz and Anders Andreassen and David Dohan and Ethan Dyer and Henryk Michalewski and Vinay Ramasesh and Ambrose Slone and Cem Anil and Imanol Schlag and Theo Gutman-Solo and others},
- year = {2022},
- eprint = {2206.14858},
- archivePrefix = {arXiv},
- primaryClass = {cs.CL}
-}
-
-@article{trinh2024solving,
- title = {Solving Olympiad Geometry without Human Demonstrations},
- author = {Trinh, Trieu H. and Wu, Yuhuai and Le, Quoc V. and He, He and Luong, Thang},
- journal = {Nature},
- volume = {625},
- pages = {476--482},
- year = {2024},
- publisher = {Springer Nature}
-}
-
-@article{abdi2020complementary,
- title = {Complementing Education via Virtual Learning Environments: Existing Findings and Future Directions},
- author = {Abdi, Saba and Khosravi, Hassan and Sadiq, Shazia and Gasevic, Dragan},
- journal = {Journal of Learning Analytics},
- volume = {7},
- number = {1},
- year = {2020},
- doi = {10.18608/jla.2020.71.6}
-}
diff --git "a/paper/experiments/\344\270\200\344\272\233\347\211\271\344\276\213.md" "b/paper/experiments/\344\270\200\344\272\233\347\211\271\344\276\213.md"
deleted file mode 100644
index bf3dfb1cf..000000000
--- "a/paper/experiments/\344\270\200\344\272\233\347\211\271\344\276\213.md"
+++ /dev/null
@@ -1,2 +0,0 @@
-1 个 CORRECT → INCORRECT:aalcr_0024(GT 是 $204 million)这个我们系统给的是205million,可以作为一个特例,就说我们的评估非常严格,对数值类的评估,没有任何容许误差。
-有的时候json的解析会出现问题,我们的方法是设计了fallback逻辑,或者建议通过模型微调来增加鲁棒性。
\ No newline at end of file
diff --git a/paper/figures/compare-ver1.png b/paper/figures/compare-ver1.png
deleted file mode 100644
index d41d42d1d..000000000
Binary files a/paper/figures/compare-ver1.png and /dev/null differ
diff --git a/paper/figures/data-gen-ver2.png b/paper/figures/data-gen-ver2.png
deleted file mode 100644
index 285c210ab..000000000
Binary files a/paper/figures/data-gen-ver2.png and /dev/null differ
diff --git a/paper/figures/evaluation-ver1.png b/paper/figures/evaluation-ver1.png
deleted file mode 100644
index 6edad4f2b..000000000
Binary files a/paper/figures/evaluation-ver1.png and /dev/null differ
diff --git a/paper/figures/full-pipe-ver7.png b/paper/figures/full-pipe-ver7.png
deleted file mode 100644
index 64269f27e..000000000
Binary files a/paper/figures/full-pipe-ver7.png and /dev/null differ
diff --git a/paper/main.tex b/paper/main.tex
deleted file mode 100644
index 0d287619f..000000000
--- a/paper/main.tex
+++ /dev/null
@@ -1,92 +0,0 @@
-\documentclass[11pt]{article}
-
-% Change "review" to "final" to generate the final (sometimes called camera-ready) version.
-% Change to "preprint" to generate a non-anonymous version with page numbers.
-\usepackage[preprint]{acl}
-
-% Standard package includes
-\usepackage{times}
-\usepackage{latexsym}
-
-% For proper rendering and hyphenation of words containing Latin characters (including in bib files)
-\usepackage[T1]{fontenc}
-
-% This assumes your files are encoded as UTF8
-\usepackage[utf8]{inputenc}
-
-% This is not strictly necessary, and may be commented out,
-% but it will improve the layout of the manuscript,
-% and will typically save some space.
-\usepackage{microtype}
-
-% This is also not strictly necessary, and may be commented out.
-% However, it will improve the aesthetics of text in
-% the typewriter font.
-\usepackage{inconsolata}
-
-% Additional packages
-\usepackage{graphicx}
-\usepackage{amsmath}
-\usepackage{amssymb}
-\usepackage{booktabs}
-\usepackage{enumitem}
-\usepackage{xcolor}
-\usepackage{algorithm}
-\usepackage{algpseudocode}
-\usepackage{pifont}
-\usepackage{multirow}
-\usepackage{stfloats}
-
-% If the title and author information does not fit in the area allocated, uncomment the following
-%\setlength\titlebox{<dim>}
-
-\author{
- \textbf{Bingxi Zhao\textsuperscript{1,2}$^*$},
- \textbf{Jiahao Zhang\textsuperscript{1}$^*$},
- \textbf{Xubin Ren\textsuperscript{1}},
- \textbf{Zirui Guo\textsuperscript{1}},
- \textbf{Chao Huang\textsuperscript{1}$^\dagger$}
-\\
- \textsuperscript{1}University of Hong Kong,
- \textsuperscript{2}Beijing Jiaotong University,
-\\
- \small{
- \textbf{Correspondence: \{bingxizhao39, chaohuang75\}@gmail.com}
- }
-}
-
-\begin{document}
-\title{DeepTutor: Tool-Augmented Personalized Tutoring System}
-\maketitle
-
-\begin{abstract}
-\renewcommand{\thefootnote}{}%
-\footnotetext{\hspace{-1.8em}$^*$Equal contribution.\newline $^\dagger$Corresponding author.}%
-\renewcommand{\thefootnote}{\arabic{footnote}}%
-\setcounter{footnote}{0}%
-Education is one of the most promising real-world applications for Large Language Models (LLMs). However, current LLMs rely heavily on static knowledge from pre-training, and existing Retrieval-Augmented Generation (RAG) systems often prioritize retrieval precision over the adaptive, guided explanations essential for effective tutoring.
-In this paper, we present \textsc{DeepTutor}, a fully open-source agentic framework that unifies citation-grounded problem-solving with difficulty-calibrated question generation.
-These capabilities are integrated through a hybrid personalization engine that couples static knowledge grounding with a trace forest, which continuously refines evolving learner profiles to customize every interaction.
-To evaluate personalized tutoring, we construct TutorBench, featuring 100 KB-grounded customized learner profiles.
-We further conduct interactive assessments via a profile-driven student simulator, complemented by general problem-solving evaluations on authoritative benchmarks.
-Our results demonstrate that \textsc{DeepTutor} excels in personalized scenarios while maintaining robust generalized agentic abilities.
-The \textsc{DeepTutor} system and its evaluation suites are open-sourced at \url{https://github.com/HKUDS/DeepTutor}.
-\end{abstract}
-
-% ===== Sections =====
-\input{sections/intro}
-\input{sections/related-work}
-\input{sections/method}
-\input{sections/experiments}
-\input{sections/conclusion}
-\input{sections/limitation}
-
-\section*{Acknowledgments}
-
-% Bibliography
-\bibliography{custom}
-
-\appendix
-\input{sections/appendix}
-
-\end{document}
diff --git a/paper/related_work/paper.md b/paper/related_work/paper.md
deleted file mode 100644
index a0d5b9f65..000000000
--- a/paper/related_work/paper.md
+++ /dev/null
@@ -1,26 +0,0 @@
-Related Work
-- Agentic Tool Use
-ReAct范式奠定了agent进行多轮交互的基础。
-很多工作尝试为agentic系统配备了数学工具、代码工具、网络工具、rag工具,从而实现了多样性的tool-based agentic workflow。
-不过大多workflow是无状态的,无法覆盖多轮对话的场景。
-
-LLM-based Agentic Reasoning Frameworks: A Survey from Methods to Scenarios
-React: Synergizing reasoning and acting in language models
-Agentic reasoning: A streamlined framework for enhancing llm reasoning with agentic tools
-In-the-flow agentic system optimization for effective planning and tool use
-
-- Personalization
-有很多个性化的工作。包括多样的dialogue-based memory机制,以及RAG-based 个性化QA。然而,RAG的知识是静态的,而部分memory的工作往往停留在general的视角。not applicable。
-In prospect and retrospect: Reflective memory management for long-term personalized dialogue agents
-A personalized dialogue generator with implicit user persona detection
-Hello again! llm-powered personalized agent for long-term dialogue
-Agent workflow memory
-A survey of personalization: From rag to agent
-Rag-anything: All-in-one rag framework
-
-- AI for Education
-Agentic Tutroing System的研究较少。【具体例子】。有一些往往从HCI视角开展。现有的for edu的工作往往忽略了学生资料的私有性,个性化做的不好。
-A systematic review of AI-driven intelligent tutoring systems (ITS) in K-12 education
-Empowering personalized learning through a conversation-based tutoring system with student modeling
-Llm-powered multi-agent framework for goal-oriented learning in intelligent tutoring system
-Ai-tutoring in software engineering education
\ No newline at end of file
diff --git a/paper/sections/appendix.tex b/paper/sections/appendix.tex
deleted file mode 100644
index f5e0ea514..000000000
--- a/paper/sections/appendix.tex
+++ /dev/null
@@ -1,4 +0,0 @@
-\section{Example Appendix}
-\label{sec:appendix}
-
-This is an appendix.
diff --git a/paper/sections/conclusion.tex b/paper/sections/conclusion.tex
deleted file mode 100644
index 9045caebe..000000000
--- a/paper/sections/conclusion.tex
+++ /dev/null
@@ -1,6 +0,0 @@
-\section{Conclusion}
-
-We presented \textsc{DeepTutor}, a tool-augmented agentic tutoring system that unifies citation-grounded problem solving, difficulty-calibrated question generation, and structured long-term memory into a closed interactive loop.
-A hybrid personalization engine couples cross-modal knowledge grounding with \textit{Trace Forest}, a hierarchical memory whose specialized agents continuously distill interaction histories into an evolving learner profile, enabling bidirectional coupling where diagnosed weaknesses shape practice and learner performance refines future explanations.
-We also introduced \textsc{TutorBench}, a benchmark with KB-grounded learner profiles and a first-person student simulator for interactive evaluation.
-Experiments show that \textsc{DeepTutor} lifts backbone accuracy by approximately 25\% on average across five standard benchmarks while delivering substantially improved personalized tutoring.
diff --git a/paper/sections/experiments.tex b/paper/sections/experiments.tex
deleted file mode 100644
index ed558583c..000000000
--- a/paper/sections/experiments.tex
+++ /dev/null
@@ -1,227 +0,0 @@
- % ===========================================================================
- % Section 4: Experiments
- % ===========================================================================
-
- \begin{figure*}[htbp!]
- \centering
- \includegraphics[width=\textwidth]{figures/data-gen-ver2.png}
- \caption{Construction pipeline of \textbf{TutorBench}. Four stages---KB Initialization, Profile Definition, Personal Profile Construction (with grounded knowledge gaps and rejection sampling), and final assembly---produce entries each containing a learner profile, knowledge gaps, an interactive task, and source references.}
- \label{fig:datagen}
- \end{figure*}
-
-
- \section{Experiments}
- \label{sec:experiments}
-
-Conventional QA-style benchmarks mostly measure final correctness, but personalized tutoring requires process-level evaluation: whether the system diagnoses learner-specific gaps, corrects them through interaction, and then generates targeted follow-up practice.
-Accordingly, we evaluate \textsc{DeepTutor} along three axes:
-\textbf{TutorBench} construction quality (\S\ref{sec:tutorbench}),
-\textbf{first-person interactive tutoring quality} (\S\ref{sec:interactive_eval}),
-and \textbf{general problem-solving transfer} (\S\ref{sec:generalization}).
-
-
- % ===========================================================================
- \subsection{TutorBench: A Personalized Tutoring Benchmark}
- \label{sec:tutorbench}
- % ===========================================================================
-
-Existing educational benchmarks rarely model who the student is and what they specifically misunderstand.
-We construct \textbf{TutorBench}, where each entry explicitly couples a learner persona, grounded knowledge gaps, and an interactive tutoring task.
-The construction pipeline is shown in Figure~\ref{fig:datagen}.
-
- \paragraph{KB Initialization.}
- University-level textbooks and research papers are indexed into the dual-representation knowledge base described in \S\ref{sec:rag}.
- A \textit{domain hierarchy} is simultaneously derived from the document structure, providing topical scaffolding for subsequent profile generation.
-
-\paragraph{Profile Definition.}
-Each KB instantiates three learner profiles---\textit{beginner}, \textit{intermediate}, and \textit{advanced}---with distinct educational background, learning purpose, and per-topic mastery states (\textit{known well}/\textit{partially known}/\textit{unknown}).
-This mirrors the benchmark generator configuration used in the codebase.
-
-\paragraph{Personal Profile Construction.}
-For each profile, we sample source pages from the KB and generate three types of \emph{grounded knowledge gaps}:
- \textbf{misconceptions} (incorrect beliefs),
- \textbf{incomplete understanding} (partial grasp with missed edge cases), and
- \textbf{missing knowledge} (never-encountered concepts).
- Each gap is anchored to specific source pages and includes both a \textit{manifestation} (how the student would exhibit the gap) and the \textit{correct understanding} for evaluation reference.
-
-Gaps are assembled into \textbf{interactive tasks} via rejection sampling that verifies task--gap consistency, source grounding, and conversational naturalness.
-
-\paragraph{Statistics.}
-TutorBench is generated with a fixed, configuration-driven recipe.
-For each KB, we instantiate three learner profiles (\textit{beginner},
-\textit{intermediate}, \textit{advanced}), yielding $3 \times N_{\text{KB}}$
-profiles in total. We sample source pages to generate at least 3 knowledge gaps for each interactive task and construct 3
-interactive tasks per profile via rejection sampling. In our current release, this produces 90 KB-grounded learner
-profiles overall, which is 270 interactive tasks.
-
-
- % ===========================================================================
- \subsection{First-Person Interactive Evaluation}
- \label{sec:interactive_eval}
- % ===========================================================================
-
-Static evaluation cannot capture whether a tutor adaptively resolves misconceptions over turns.
-We therefore use a \textbf{first-person interactive protocol}: an LLM student simulator (initialized from TutorBench entries) interacts with each evaluated system, and we score both dialogue behavior and generated practice questions (Figure~\ref{fig:evaluation}).
-
- \begin{figure}[t]
- \centering
- \includegraphics[width=\columnwidth]{figures/evaluation-ver1.png}
- \caption{First-person interactive evaluation protocol. A \textbf{Student Simulator} initialized from TutorBench (persona + first-person gap beliefs + dynamic gap pacing) interacts with the tutor. After session completion, the tutor generates five practice questions. Evaluation is split into \textbf{turn-level tutoring metrics} and \textbf{practice-question metrics}, then aggregated in a fixed-judge Step-3 pipeline.}
- \label{fig:evaluation}
- \end{figure}
-
-\paragraph{Student Simulator.}
-Each gap is transformed into a first-person belief so the simulator \emph{acts as the student} rather than describing errors from an outside view.
-Combined with dynamic gap pacing, this yields realistic resistance patterns: the student may defend misconceptions, partially accept corrections, and only mark completion after sufficient explanation.
-
-\paragraph{Evaluation Rubrics.}
-Following the latest evaluation pipeline, metrics are explicitly split into
-\textbf{turn-level tutoring metrics} and \textbf{practice-question metrics}.
-Importantly, the final practice-question turn is \emph{excluded} from turn-level scoring and evaluated independently.
-
- \begin{itemize}[nosep,leftmargin=*]
-\item \textbf{Iter}: raw turn count from interactive sessions (lower is better). This is the only non-1--5 metric.
-
-\item \textbf{Solve-side Quality}: per-turn 1--5 scores for \textit{personalization}, \textit{applicability}, \textit{source faithfulness}, \textit{vividness} (modality diversity of expression, e.g., structured tables when useful), and \textit{logical depth}.
-
-\item \textbf{Practice Metrics}: after dialogue ends, five generated \textbf{MCQ} questions are evaluated separately:
-\textit{fitness}, \textit{groundedness}, \textit{diversity}, \textit{answer quality}, and \textit{cross concept} (all per-question, all 1--5).
- \end{itemize}
-
- \paragraph{Protocol.}
-We run a three-stage pipeline:
-\textbf{Step 1} generates benchmark entries,
-\textbf{Step 2} runs interactive simulation and logs transcripts,
-\textbf{Step 3} scores transcripts with LLM-as-judge prompts.
-To ensure comparability in model studies, we support multi-model Step-2 generation while fixing a single judge model in Step-3.
-We compare \textbf{\textsc{DeepTutor}} against one baseline:
-\textbf{Naive Tutor} (the project mock tutor: base LLM + simple RAG, without structured planning/memory loop).
-
- \paragraph{Results.}
-Table~\ref{tab:interactive_results_main} reports the main interactive metrics used in the paper body.
-Table~\ref{tab:interactive_results_full} provides the extended metric breakdown (turn-level teaching quality and additional practice-quality dimensions).
-Across our internal runs, \textsc{DeepTutor} consistently improves both tutoring and practice metrics over \textit{Naive Tutor}. For all 1--5 metrics, we report averages with four decimal places.
-
- \begin{table}[t]
- \centering
- \small
- \begin{tabular}{lcccc}
- \toprule
- \textbf{System} & \textbf{SQ}$\uparrow$ & \textbf{PQ}$\uparrow$ & \textbf{OQ}$\uparrow$ & \textbf{Iter}$\downarrow$ \\
- \midrule
- Naive Tutor & -- & -- & -- & -- \\
- \textsc{DeepTutor} & -- & -- & -- & -- \\
- \bottomrule
- \end{tabular}
-\caption{Main first-person interactive results. SQ: solve-quality composite over \{SF, personalization, applicability, vividness, logical depth\}. PQ: practice-quality composite over \{fitness, groundedness, diversity, answer quality, cross concept\}. OQ: average of SQ and PQ. Iter: raw turn count (lower is better).
- }
- \label{tab:interactive_results_main}
- \end{table}
-
-\begin{table*}[t]
-\centering
-\small
-\setlength{\tabcolsep}{4.5pt}
-\begin{tabular}{lcccccccccc}
-\toprule
-\textbf{System} &
-\textbf{SF}$\uparrow$ &
-\textbf{PER}$\uparrow$ &
-\textbf{APP}$\uparrow$ &
-\textbf{VID}$\uparrow$ &
-\textbf{LD}$\uparrow$ &
-\textbf{FIT}$\uparrow$ &
-\textbf{GND}$\uparrow$ &
-\textbf{DIV}$\uparrow$ &
-\textbf{ANS}$\uparrow$ &
-\textbf{CC}$\uparrow$ \\
-\midrule
-Naive Tutor & -- & -- & -- & -- & -- & -- & -- & -- & -- & -- \\
-\textsc{DeepTutor}& -- & -- & -- & -- & -- & -- & -- & -- & -- & -- \\
-\bottomrule
-\end{tabular}
-\caption{Extended first-person interactive results (all metrics are 1--5 with four-decimal averages). PER/APP/VID/LD denote personalization, applicability, vividness, and logical depth for solve turns. FIT/GND/DIV/ANS/CC denote fitness, groundedness, diversity, answer quality, and cross concept for practice questions. Baseline is Naive Tutor (mock tutor: base LLM + simple RAG).}
-\label{tab:interactive_results_full}
-\end{table*}
-
-
-% ===========================================================================
-\subsection{Ablation Study}
-\label{sec:ablation_rag_memory}
-% ===========================================================================
-
-To quantify the contribution of retrieval grounding and long-horizon personalization, we run ablations on both the \textit{solve} and \textit{question-generation} pipelines.
-Starting from full \textsc{DeepTutor}, we evaluate three variants:
-\textbf{without RAG} (disable retrieval in planner/solver and question generation),
-\textbf{without Memory} (disable personalization memory context in both pipelines),
-and \textbf{without RAG+Memory} (disable both).
-All settings use the same TutorBench entries, simulation protocol, and fixed judge model. Results are reported in table 4.
-
-\begin{table}[t]
-\centering
-\small
-\begin{tabular}{lcccc}
-\toprule
-\textbf{Variant} & \textbf{SQ}$\uparrow$ & \textbf{PQ}$\uparrow$ & \textbf{OQ}$\uparrow$ & \textbf{Iter}$\downarrow$ \\
-\midrule
-\textsc{DeepTutor} (full) & -- & -- & -- & -- \\
-w/o RAG & -- & -- & -- & -- \\
-w/o Memory & -- & -- & -- & -- \\
-w/o RAG + Memory & -- & -- & -- & -- \\
-\bottomrule
-\end{tabular}
-\caption{Ablation on retrieval grounding and personalization memory. SQ/PQ/OQ follow the definitions in Table~\ref{tab:interactive_results_main}. For 1--5 metrics, we report four-decimal averages; Iter is raw turn count.}
-\label{tab:ablation_rag_memory}
-\end{table}
-
-
-\begin{table*}[!t]
-\centering
-\caption{General Problem-solving \textbf{pass@1 scores} across five benchmarks.
-\textit{Avg~$\Delta$} means relative improvement across benchmarks.
-$^*$use the first 500 quesitons within HLE.
-$^{**}$represents GPQA-diamond.
-$^{***}$use live reasoning subset.
-$^\dagger$GAIA scores are reported \textit{per difficulty level (L1--L3)}.}
-\label{tab:generalization}
-\small
-\setlength{\tabcolsep}{5pt}
-\begin{tabular}{l ccc cccc c c}
-\toprule
-& \multicolumn{3}{c}{\textbf{STEM Reasoning}} & \multicolumn{4}{c}{\textbf{General Agent (GAIA)}} & \textbf{Long Ctx} & \textbf{Enhance.} \\
-\cmidrule(lr){2-4} \cmidrule(lr){5-8} \cmidrule(lr){9-9}
-\textbf{Pass@1} & HLE$^*$ & GPQA-D$^{**}$ & LiveBench$^{***}$ & L1 & L2 & L3 & Overall$^\dagger$ & AA-LCR & \textit{Avg~$\Delta$} \\
-\midrule
-Gemini-3-Flash & 19.40 & 81.31 & 70.00 & 43.40 & 40.70 & 15.38 & 37.58 & 63.00 & \multirow{2}{*}{+29.12\%} \\
-\quad+\textsc{DeepTutor} & \textbf{30.80} & \textbf{84.85} & \textbf{96.00} & \textbf{56.60} & \textbf{50.00} & \textbf{23.08} & \textbf{47.88} & \textbf{74.67} & \\
-\midrule
-Sonnet-4.5 & 8.40 & 72.22 & 64.33 & 37.74 & 30.23 & 7.69 & 29.09 & 53.33 & \multirow{2}{*}{+32.03\%} \\
-\quad+\textsc{DeepTutor} & \textbf{14.60} & \textbf{73.23} & \textbf{82.00} & \textbf{50.94} & \textbf{48.84} & \textbf{23.08} & \textbf{45.45} & \textbf{54.00} & \\
-\midrule
-Qwen-3.5-plus & 16.80 & 88.38 & 69.00 & 44.23 & 35.71 & 13.64 & 33.94 & 66.00 & \multirow{2}{*}{+23.00\%} \\
-\quad+\textsc{DeepTutor} & \textbf{24.20} & \textcolor{red!70!black}{87.88} & \textbf{93.00} & \textbf{50.94} & \textbf{53.49} & \textbf{32.00} & \textbf{49.09} & \textbf{69.67} & \\
-\midrule
-GPT-5-mini & 16.46 & 80.81 & 71.00 & 32.08 & 30.23 & 7.69 & 27.27 & 68.67 & \multirow{2}{*}{+27.11\%} \\
-\quad+\textsc{DeepTutor} & \textbf{21.20} & \textcolor{red!70!black}{80.30} & \textbf{93.00} & \textbf{54.72} & \textbf{52.33} & \textbf{26.92} & \textbf{49.09} & \textbf{71.00} & \\
-\midrule
-Minimax-m2.5 & 14.00 & 82.83 & 59.30 & 35.29 & 22.78 & 12.00 & 23.64 & 66.00 & \multirow{2}{*}{+31.50\%} \\
-\quad+\textsc{DeepTutor} & \textbf{19.40} & \textbf{83.33} & \textbf{73.00} & \textbf{52.94} & \textbf{44.30} & \textbf{32.00} & \textbf{42.42} & \textbf{76.40} & \\
-\bottomrule
-\end{tabular}
-\end{table*}
-
-% ===========================================================================
-\subsection{General Problem-Solving}
-\label{sec:generalization}
-% ===========================================================================
-
-Beyond personalized tutoring, a practical tutor should retain strong general reasoning ability.
-We therefore evaluate \textsc{DeepTutor} on five public benchmarks over five backbone families (\textit{Claude, GPT, Gemini, Qwen, MiniMax}), covering three capability groups:
-\textbf{STEM reasoning} (HLE~\citep{phan2025hle}, GPQA-Diamond~\citep{rein2024gpqa}, LiveBench~\citep{white2025livebench}),
-\textbf{general agentic problem-solving} (GAIA~\citep{mialon2024gaia}),
-and \textbf{long-context reasoning} (AA-LCR~\citep{artificialanalysis2025lcr}).
-Correctness is judged by LLM evaluators following benchmark-specific rubrics.
-
-As shown in Table~\ref{tab:generalization}, \textsc{DeepTutor} consistently improves backbone pass@1 performance by \textit{+23\% to +32\%} on average across model families.
-These gains suggest that our tutoring-oriented decomposition (plan, tool-grounded solving, and critic-guided generation) improves general reasoning robustness rather than overfitting to TutorBench-specific prompts.
-
\ No newline at end of file
diff --git a/paper/sections/intro.tex b/paper/sections/intro.tex
deleted file mode 100644
index dfd5da903..000000000
--- a/paper/sections/intro.tex
+++ /dev/null
@@ -1,33 +0,0 @@
-\section{Introduction}
-
-\begin{figure}[t]
- \centering
- \includegraphics[width=\columnwidth]{figures/compare-ver1.png}
- \caption{Comparison of \textit{prior LLM products} and \textsc{DeepTutor}. Existing products provide generic answers regardless of the learner's background; \textsc{DeepTutor} adapts both problem-solving explanations and generated practice to match the student's syllabus, knowledge level, and specific weaknesses exposed during conversation.}
- \label{fig:compare}
-\end{figure}
-
-Education is among the most promising real-world applications of large language models (LLMs).
-An effective human tutor does far more than supply correct answers--they diagnose misconceptions, scaffold explanations to the learner's level, and continuously pose targeted practice that turns weaknesses into strengths \citep{letourneau2025systematicreviewaidriven}.
-While LLMs exhibit impressive fluency in educational dialogues, replicating this tightly integrated set of pedagogical skills within a unified, adaptive system remains an open challenge \citep{chu-etal-2025-llm}.
-
-Existing approaches tackle fragments of this challenge in isolation. As illustrated in Figure~\ref{fig:compare}, the question generation of existing LLM systems rarely calibrates difficulty to the individual learner. Though SOTA LLMs demonstrate strong STEM reasoning abilities, they often tend to solve the question in a general way as they were trained.
-Question generation, on the other hand, often fails to fit the student's syllabus.
-Personalized educational platforms track coarse skill inventories rather than the fine-grained reasoning traces that reveal \textit{how} a student errs.
-Meanwhile, retrieval-augmented generation (RAG) often lacks consideration for the adaptive, guided explanations that effective tutoring demands.
-
-We argue that the missing ingredient is a \textit{closed interactive loop}: weaknesses exposed during problem solving should directly shape which questions are generated next, while the learner's performance on those questions should, in turn, refine the model that informs future explanations.
-This requires operationalizing personalization into measurable mechanisms, such as calibrating question difficulty based on diagnosed weaknesses and adapting explanation depth to the learner's proficiency.
-Realizing such a loop requires (i)~a structured memory that captures fine-grained interaction histories rather than scalar skill scores, and (ii)~a unified tutoring system whose modules share and continuously update that memory.
-
-To address these problems, we propose \textsc{DeepTutor} that unifies both problem solving and question generation within a hybrid personalization framework.
-For problem solving, we utilize an \textit{investigation--solving--writing} pipeline that decomposes complex queries, executes multi-step tool-augmented reasoning, and synthesizes citation-grounded explanations.
-For question generation, a \textit{critic-guided generate--validate loop} iteratively proposes and verifies difficulty-calibrated practice items.
-Moreover, both pipelines are unified through a hybrid personalization engine that couples static knowledge grounding with \textit{trace forest}, a dynamic structured memory that records multi-resolution interaction traces and employs specialized memory agents to continuously refine an evolving learner profile---creating the closed tutoring cycle where every interaction personalizes the next.
-
-Our main contributions are as follows:
-\begin{itemize}[nosep,leftmargin=*]
- \item We propose \textsc{DeepTutor}, an agentic tutoring framework that, to the best of our knowledge, is among the first to unify tool-augmented problem solving, critic-guided question generation, and long-term structured memory into a closed interactive loop.
- \item We introduce \textit{trace forest}, a hierarchical memory architecture in which specialized agents collaboratively maintain a fine-grained, evolving learner model from multi-resolution interaction traces.
- \item We construct \textsc{TutorBench}, a benchmark of 100 knowledge-base-grounded learner profiles paired with a student simulator for first-person interactive evaluation. Experiments on TutorBench and five standard reasoning benchmarks show that \textsc{DeepTutor} substantially outperforms various baselines, providing insights for the future shape of personalized tutoring systems.
-\end{itemize}
diff --git a/paper/sections/limitation.tex b/paper/sections/limitation.tex
deleted file mode 100644
index 7f4a81394..000000000
--- a/paper/sections/limitation.tex
+++ /dev/null
@@ -1,6 +0,0 @@
-\section*{Limitations}
-
-Our interactive evaluation relies on LLM-powered student simulators and rubric assessors, which may not fully capture real learner behaviors such as affective states or idiosyncratic reasoning; validation with human learners in authentic classrooms remains important future work.
-The multi-stage pipeline issues multiple LLM calls per interaction, incurring latency and cost that may challenge real-time deployment in resource-constrained settings.
-Additionally, the trace forest grows monotonically and may require periodic pruning for very long-term engagements, and the system's performance ceiling is ultimately bounded by the backbone model's capabilities.
-Finally, our automated evaluation applies exact-match criteria for numerical answers without tolerance for rounding differences, which may understate effective accuracy in certain cases.
diff --git a/paper/sections/method.tex b/paper/sections/method.tex
deleted file mode 100644
index a2bb35414..000000000
--- a/paper/sections/method.tex
+++ /dev/null
@@ -1,185 +0,0 @@
-\section{Method}
-\label{sec:method}
-
-\begin{figure*}[t]
- \centering
- \includegraphics[width=\textwidth]{figures/full-pipe-ver7.png}
- \caption{Overview of \textsc{DeepTutor}. The system unifies two task pipelines through a Hybrid Personalization layer. \textbf{Static Knowledge Grounding} (center) constructs multi-modal knowledge graphs and vector databases from course materials, enabling mixed graph--embedding retrieval. \textbf{Dynamic Personal Memory} (bottom) maintains a trace forest accessible via a programmatic \emph{TraceToolkit}, and distills interaction histories into three evolving profile dimensions. \textbf{Personalized Problem Solving} (left) proceeds through Investigation~(\ding{172}), Step-by-step Solving~(\ding{173}), and Iterative Writing~(\ding{174}). \textbf{Personalized Question Generation} (right) proceeds via Idea Generation~(\ding{175}) and a Critic-Guided Q-A Pair Generation loop~(\ding{176}). Both pipelines record interaction traces that continuously refine the learner profile, forming a closed tutoring cycle.}
- \label{fig:overview}
-\end{figure*}
-
-DeepTutor is built around two sub-pipes with a common personalization engine, as shown in figure~\ref{fig:overview}.
-The \textit{Hybrid Personalization Engine} (\S\ref{sec:personalization}) couples a static knowledge grounding with a dynamic memory that maintains an evolving learner profile.
-Building upon this substrate, the \textit{problem-solving pipeline} (\S\ref{sec:solve}) produces citation-grounded explanations through three stages, while the \textit{question-generation pipeline} (\S\ref{sec:generate}) produces difficulty-calibrated practice items.
-Each completed interaction feeds back into the learner profile, creating a closed tutoring cycle (\S\ref{sec:system}).
-
-% ===========================================================================
-\subsection{Preliminaries}
-\label{sec:prelim}
-% ===========================================================================
-
-\paragraph{Task Formulation.}
-DeepTutor addresses two complementary tutoring tasks:
-(i)~\emph{problem solving}, producing a citation-grounded explanation $a$ for a learner question $q$, calibrated to the student's proficiency; and
-(ii)~\emph{question generation}, producing customized practice items for a topic $\tau$ that target the learner's specific gaps.
-Both tasks share the personalization substrate described below.
-
-\paragraph{Notation.}
-Course materials are indexed into a knowledge base $\mathcal{K}$ with dual representations for structured and semantic retrieval (\S\ref{sec:rag}).
-The system maintains a learner profile $\mathcal{D} = (\mathcal{D}_s, \mathcal{D}_w, \mathcal{D}_r)$ capturing interaction summaries, diagnosed weaknesses, and tutor self-reflections, continuously updated by specialized memory agents (\S\ref{sec:memory}).
-Before every agent step, a personalization context $\mathcal{C}_{\text{mem}}$ is assembled from $\mathcal{D}$ and the trace forest (the latter queried via a dedicated \emph{TraceToolkit}), yielding a compact, role-specific excerpt that steers the agent's behavior (\S\ref{sec:injection}).
-
-Algorithm~\ref{alg:loop} gives a unified view of the full tutoring cycle.
-Each session begins with profile injection and mixed retrieval, then branches into either problem solving (\ding{172}--\ding{174}) or question generation (\ding{175}--\ding{176}).
-The resulting interaction trace is appended to the trace forest and used to update the learner profile.
-
-\begin{algorithm}[t]
-\caption{Closed-Loop Personalized Tutoring}\label{alg:loop}
-\small
-\begin{algorithmic}[1]
-\Require learner profile $\mathcal{D}^{(0)}$;\; trace forest $\mathcal{F}^{(0)} = \emptyset$
-\For{session $j = 1, 2, \ldots$}
- \State $\mathcal{C}_{\text{mem}} \gets \Call{ProfileInject}{\mathcal{D}^{(j{-}1)}, \mathcal{F}^{(j{-}1)}, \text{task}_j}$
- \State $\mathcal{C}_{\text{rag}} \gets \textsc{RagTool}(\text{task}_j)$
- \If{$\text{task}_j = (\textsc{Solve},\, q)$}
- \State $\mathcal{P}{=}\langle s_1,\dots,s_K\rangle \gets \Call{Plan}{q,\;\mathcal{C}_{\text{rag}},\;\mathcal{C}_{\text{mem}}}$ \Comment{\ding{172}}
- \For{$k = 1$ \textbf{to} $K$} \Comment{\ding{173}}
- \While{$s_k$ not resolved}
- \State $(\alpha_t,\, \mathbf{s}_t) \gets \Call{ToolAgent}{q, \mathcal{P}, \mathcal{S}, \mathcal{C}_{\text{mem}}}$
- \State $\mathcal{S} \gets \mathcal{S} \cup \{\mathbf{s}_t\}$
- \If{$\alpha_t = \textsc{Replan}$}
- \State $\mathcal{P} \gets \Call{Revise}{\mathcal{P}, \mathcal{S}}$
- \EndIf
- \EndWhile
- \State $\mathcal{S} \gets \Call{Compress}{\mathcal{S}, k}$
- \EndFor
- \State $a \gets \Call{IterativeWrite}{\mathcal{S},\;\mathcal{C}_{\text{mem}}}$ \Comment{\ding{174}}
- \State $T_j \gets \Call{BuildTrace}{q, a}$
- \Else \Comment{$\text{task}_j = (\textsc{Generate},\, \tau)$}
- \State $\mathcal{I} \gets \Call{IdeaAgent}{\tau,\;\mathcal{C}_{\text{rag}},\;\mathcal{C}_{\text{mem}}}$ \Comment{\ding{175}}
- \State $\mathcal{T}_{1..N} \gets \Call{TopKSelect}{\mathcal{I}}$
- \For{$i = 1$ \textbf{to} $N$} \Comment{\ding{176}}
- \Repeat
- \State $(q_i, a_i) \gets \Call{Generator}{\mathcal{T}_i,\;\mathcal{C}_{\text{rag}},\;\mathcal{C}_{\text{mem}}}$
- \State $(\textit{pass}, f_i) \gets \Call{Validator}{q_i, a_i, \mathcal{T}_i}$
- \If{$\lnot\,\textit{pass}$} $\mathcal{T}_i \gets \Call{Revise}{\mathcal{T}_i, f_i}$
- \EndIf
- \Until{\textit{pass}}
- \EndFor
- \State $T_j \gets \Call{BuildTrace}{\tau, \{(q_i, a_i)\}}$
- \EndIf
- \State $\mathcal{F}^{(j)} \gets \mathcal{F}^{(j{-}1)} \cup \{T_j\}$
- \State $\mathcal{D}^{(j)} \gets \Call{MemoryUpdate}{\mathcal{D}^{(j{-}1)}, T_j}$
-\EndFor
-\end{algorithmic}
-\end{algorithm}
-
-% ===========================================================================
-\subsection{Hybrid Personalization Engine}
-\label{sec:personalization}
-% ===========================================================================
-
-Both the solver and the generator require two types of knowledge: \emph{domain expertise} and \emph{learner awareness}. DeepTutor provides the former through Static Knowledge Grounding and the latter through Dynamic Memory, unified by a Profile Injection mechanism that delivers tailored context to each specific stage.
-
-\subsubsection{Static Knowledge Grounding}
-\label{sec:rag}
-
-Real-world course materials are inherently multimodal: textbooks interleave prose with figures, equations, and data tables, each encoding domain knowledge that is difficult to faithfully flatten into plain text.
-To preserve this richness, we perform multimodal knowledge unification, decomposing source documents into atomic content units $\{c_j=(t_j, x_j)\}$, where $t_j\!\in\!\{\text{text}, \text{image}, \text{table}, \text{equation}\}$ denotes the modality and $x_j$ the raw payload~\cite{wang2024mineruopensourcesolutionprecise}.
-Dedicated extractors handle each modality so as to retain its internal structure: figures keep their captions, equations stay anchored to surrounding definitions, and tables preserve header--cell relationships.
-
-The resulting units are indexed through a dual-graph construction: a cross-modal KG grounds non-textual units within their contextual neighborhood via entity and relation extraction, while a text-based KG captures fine-grained semantic relationships from prose~\cite{guo2025raganythingallinoneragframework}.
-The two graphs are merged through entity alignment into a unified knowledge graph $\mathcal{G}=(\mathcal{V},\mathcal{E})$ that encodes both cross-modal associations and textual semantics.
-In parallel, dense encoders map all content units into modality-specific vector stores (a text VDB and a multi-modal VDB), unified into a combined embedding index $\mathcal{B}$.
-Together, $\mathcal{G}$ and $\mathcal{B}$ form the complete retrieval index over the knowledge base $\mathcal{K}$.
-
-At query time, we introduce cross-modal hybrid retrieval that operates over both indices in parallel: graph-based retrieval traverses $\mathcal{G}$ to capture explicit relationships and multi-hop reasoning paths, while embedding-based retrieval searches $\mathcal{B}$ to surface semantically relevant content beyond the graph's structural coverage.
-The resulting candidate sets are merged via reciprocal rank fusion, scoring each passage $d$ as $\textstyle\sum_{r}{1}/({k+\mathrm{rank}_r(d)})$, where $k$ is a smoothing constant~\citep{cormack2009reciprocal}.
-Retrieved passages are deduplicated and truncated to a context budget before injection as domain grounding $\mathcal{C}_{\text{rag}}$.
-
-\subsubsection{Dynamic Personal Memory}
-\label{sec:memory}
-
-While the knowledge base captures \emph{what the course materials contain}, the dynamic personal memory captures \emph{how the individual learner has engaged with them}.
-We further propose \textit{Trace Forest}, a structured memory $\mathcal{F} = \{T_1, T_2, \ldots\}$ in which each tree $T_j = (V_j, E_j)$ records one complete tutoring interaction as a multi-resolution, semantically searchable artifact.
-Every node $v \in V_j$ is a triple $(\texttt{type}, \texttt{content}, \mathbf{e}_v)$ where \texttt{type} identifies the granularity level, \texttt{content} stores the payload, and $\mathbf{e}_v$ is a dense embedding, forming a three-level hierarchy. \textit{Level~1} captures the session-level input and a global summary; \textit{Level~2} records intermediate planning units produced by task decomposition; and \textit{Level~3} stores fine-grained execution records including tool invocations, evidence, and validation outcomes.
-The concrete node types at each level are task-specific and detailed alongside the respective pipelines (\S\ref{sec:solve}, \S\ref{sec:generate}).
-
-Rather than treating the forest as a passive data store, we expose it to all pipeline agents through a programmatic \emph{TraceToolkit} with three operations: \textsc{SearchTrace} embeds a query and retrieves the most relevant nodes across $\mathcal{F}$ via cosine similarity-based ANN search using a shared encoder; \textsc{ListTraces} enumerates traces filtered by time range, task type, or topic; and \textsc{ReadNodes} fetches the full content of specific nodes along with their ancestry path.
-This interface lets each agent actively explore the learner's history with their specific demands, from coarse session summaries at Level~1 to fine-grained reasoning steps at Level~3.
-
-\paragraph{Profile Construction.}
-\label{sec:injection}
-Raw traces must be interpreted into actionable tutoring signals.
-We introduce three specialized memory agents to process each new trace tree $T_j$ in parallel, incrementally updating a dedicated dimension of the learner profile $\mathcal{D}$:
-\begin{itemize}[nosep,leftmargin=*]
-\item Session History $ \mathcal{D}_s$: distills topics covered and performance trends. This will record what has happened, providing general session memories.
-\item User Weakness $\mathcal{D}_w$: compares learner responses against reference solutions, labeling each weakness as active or resolved to maintain a prioritized gap inventory, emphasizing where to focus.
-\item Self-Reflection $\mathcal{D}_r$: critiques the system's own prior outputs for pedagogical alignment, producing actionable improvement notes, indicating how to improve.
-\end{itemize}
-Each agent receives the new trace along with its current profile dimension and produces an updated version through incremental revision. To prevent error accumulation, this process employs a \textit{confidence-gated update} mechanism, where state transitions (e.g., marking a weakness as resolved) require explicit evidence grounding, preserving long-term trends while incorporating recent signals.
-
-Before each agent step, the system assembles a personalization context $\mathcal{C}_{\text{mem}}$ through two channels:
-(i)~\emph{active trace retrieval} via the TraceToolkit, retrieving the top-$k$ most relevant nodes with $k$ allocated proportionally across levels to balance broad session context with fine-grained precedents;
-(ii)~\emph{profile excerpting}, where role-specific slices of $\mathcal{D}$ are drawn based on the requesting agent's function to decouple their attention (e.g., the planner receives $\mathcal{D}_s$ and $\mathcal{D}_w$; the writer receives $\mathcal{D}_r$; generation agents receive $\mathcal{D}_w$ alongside historical question patterns). The total token budget is dynamically partitioned between $\mathcal{C}_{\text{rag}}$ and $\mathcal{C}_{\text{mem}}$ (see Appendix for a worked example).
-
-% ===========================================================================
-\subsection{Personalized Problem-Solving}
-\label{sec:solve}
-% ===========================================================================
-
-Prior tool-augmented agents~\citep{yao2023reactsynergizingreasoningacting, chen2026iterresearch} pack planning, retrieval, and exposition into a full reasoning loop.
-This suffices for short factoid queries but becomes a bottleneck in tutoring, where thorough investigation and personalized presentation compete for the same context budget.
-DeepTutor disentangles them into three incremental stages (\ding{172}--\ding{174} in Algorithm~\ref{alg:loop}), guided by \textit{scaffolding theory} to provide step-by-step cognitive support.
-
-\paragraph{Stage \ding{172}: Personalized Investigation.}
-The planner decomposes $q$ into several meta-questions and launches a multi-source investigation: it retrieves relevant passages from $\mathcal{K}$ via the RAG tool, consults the trace forest via the trace toolkit for precedents from similar past interactions, and invokes auxiliary toolkits as needed.
-Jointly conditioning on the assembled domain context $\mathcal{C}_{\text{rag}}$ and the learner context $\mathcal{C}_{\text{mem}}$, the planner produces a solving plan $\mathcal{P} = \langle s_1, \ldots, s_K \rangle$ of concrete sub-goals, each annotated with its step-level goal and a brief description.
-A shared scratchpad $\mathcal{S}$ accumulates all subsequent reasoning artifacts.
-Investigating before planning prevents sub-goals that are too vague or redundant with what the learner already understands (e.g., generating ``review chain rule in trigonometry'' rather than a vague ``review calculus'').
-
-\paragraph{Stage \ding{173}: Step-by-step Problem Solving.}
-Each sub-goal $s_k$ is executed through a ReAct-style loop, ~\citep{yao2023reactsynergizingreasoningacting}, conditioned on both the domain grounding $\mathcal{C}_{\text{rag}}$ and the learner context $\mathcal{C}_{\text{mem}}$.
-At every iteration the tool agent produces a reasoning trace $r_t$, selects an action $\alpha_t$ from a shared tool suite $\mathcal{A}$ (encompassing knowledge-base retrieval, trace-forest lookup, sandboxed code execution, web search, and deep reasoning), observes the output $o_t$, and records a \emph{self-note} $n_t$.
-Unlike the reasoning trace, which captures the full deliberation process, the self-note distills the step's outcome into a concise takeaway (e.g., ``retrieved formula confirmed'') that subsequent steps can reference without re-reading verbose intermediates.
-When the current plan proves inadequate, the agent triggers \emph{adaptive replanning}, revising remaining sub-goals while preserving completed work.
-
-Hierarchical compression (line 14 in Algorithm~\ref{alg:loop}) prevents the scratchpad from exceeding the model's context window.
-Once sub-goal $s_k$ is resolved, an LLM-based summarizer distills its full trace into a compact digest that retains key conclusions and evidence pointers while discarding verbose intermediate steps.
-As the plan advances, earlier sub-goals are represented by increasingly concise digests, freeing context capacity for deeper reasoning on later sub-goals.
-
-\paragraph{Stage \ding{174}: Evidence-based Iterative Writing.}
-Rather than concatenating raw tool outputs, the writing stage extracts structured evidence bundles from the scratchpad and constructs the answer through successive draft-refine iterations, reconciling potentially conflicting findings.
-The learner context $\mathcal{C}_{\text{mem}}$
-% ---including diagnosed weaknesses from $\mathcal{D}_w$ and the system's pedagogical self-reflections from $\mathcal{D}_r$---
-steers both the depth and the tone of the explanation within the learner's \textit{Zone of Proximal Development}: \textit{beginners} receive step-by-step derivations with scaffolding, while \textit{proficient learners} receive focused summaries that foreground key insights.
-Every claim is grounded with traceable citations back to $\mathcal{K}$.
-
-% ===========================================================================
-\subsection{Personalized Question Generation}
-\label{sec:generate}
-% ===========================================================================
-
-A tutor must also pose the right questions: ones that are meaningful, factually grounded, and calibrated to the individual learner.
-We propose a two-stage architecture (\ding{175}--\ding{176} in Algorithm~\ref{alg:loop}) that separates \emph{what to ask} from \emph{how to ask and verify}.
-
-\paragraph{Stage \ding{175}: Personalized Idea Generation.}
-Rather than generating questions directly from a bare topic, DeepTutor first maps the conceptual landscape around $\tau$ through the lens of the individual learner.
-The idea agent jointly conditions on domain knowledge $\mathcal{C}_{\text{rag}}$ and learner context $\mathcal{C}_{\text{mem}}$---including past mistakes, difficulty trends, and related problems surfaced via the TraceToolkit---to synthesize a diverse pool of candidate ideas, each characterized by a target concept, a question format (MCQ, written-response, or coding), and a personalized rationale grounded in the learner's diagnosed gaps.
-A two-stage selection then filters ill-formed or redundant candidates and ranks survivors along quality dimensions such as clarity, relevance, and diversity, yielding structured question templates $\{\mathcal{T}_i\}$ that serve as blueprints for the subsequent generation stage.
-
-\paragraph{Stage \ding{176}: Critic-Guided Q-A Pair Generation.}
-For each template $\mathcal{T}_i$, a \textbf{generator} produces a complete question--answer--explanation triple $(q_i, a_i, e_i)$, drawing on $\mathcal{C}_{\text{rag}}$ for factual grounding and $\mathcal{C}_{\text{mem}}$ to calibrate difficulty and phrasing to the learner's level.
-A structurally separated \textbf{validator} then challenges the output through two-level quality assurance: an LLM-based reasoning check evaluates template alignment, factual correctness, and pedagogical soundness, while computational questions undergo additional verification via sandboxed code execution.
-This dual-agent separation is critical: because the validator shares no reasoning chain with the generator, it must independently verify correctness, catching errors that self-evaluation would miss.
-Failed pairs receive structured diagnostic feedback $f_i$; the template is revised and the pair regenerated until both pedagogical and factual constraints are satisfied.
-
-% ===========================================================================
-\subsection{Closed-Loop Tutoring Cycle}
-\label{sec:system}
-% ===========================================================================
-
-As shown in Algorithm~\ref{alg:loop}, the components above form a self-reinforcing cycle.
-After each task, whether a problem-solving session or a question-generation episode, the pipeline records a new trace tree $T_j$ into the trace forest $\mathcal{F}$, and the three memory agents update the learner profile in parallel, producing $\mathcal{D}^{(j)}$ that immediately informs subsequent interactions.
-The key property is \textbf{bidirectional task coupling}, which operationalizes \textit{formative assessment}: weaknesses diagnosed during problem solving propagate to $\mathcal{D}_w$ and directly shape which questions are generated next; conversely, the learner's performance on generated questions refines $\mathcal{D}_s$ and $\mathcal{D}_r$, improving future explanations.
-Because every agent can actively query the trace forest through the TraceToolkit, this feedback is not limited to profile-level summaries: agents can retrieve fine-grained precedents from any prior interaction, enabling increasingly nuanced personalization as the interaction history grows.
diff --git a/paper/sections/related-work.tex b/paper/sections/related-work.tex
deleted file mode 100644
index 8b606cae4..000000000
--- a/paper/sections/related-work.tex
+++ /dev/null
@@ -1,11 +0,0 @@
-\section{Related Work}
-\label{sec:related}
-
-\paragraph{Agentic Tool Use.}
-ReAct \citep{yao2023reactsynergizingreasoningacting} introduced interleaved reasoning and action for tool-augmented LLMs, inspiring planning-and-tool workflows \citep{zhao2025llmbasedagenticreasoningframeworks,wu-etal-2025-agentic,li2025intheflowagenticoptimizationeffective}. These frameworks target short-horizon tasks without persistent learner state. DeepTutor extends tool-based agentic reasoning to stateful tutoring by coupling solving, generation, and memory.
-
-\paragraph{Personalization and Memory.}
-LLM personalization spans dialogue memory \citep{tan-etal-2025-prospect,li-etal-2025-hello,cho-etal-2022-personalized}, RAG-style adaptation \citep{li2025surveypersonalizationragagent,guo2025raganythingallinoneragframework}, and reusable workflow induction \citep{wang2024agentworkflowmemory}. Unlike traditional knowledge tracing (e.g., BKT, DKT) that maintains scalar skill scores, DeepTutor introduces Trace Forest, an event-driven structured memory that provides interpretable, multi-resolution records of learner-specific weaknesses and historical traces.
-
-\paragraph{AI for Education.}
-While classic intelligent tutoring systems (ITS) like Cognitive Tutor rely on hard-coded rules, recent LLM-based works improve personalization through conversational tutoring \citep{park2024empoweringpersonalizedlearning} and multi-agent paths \citep{wang2025llmpoweredmultiagentframeworkgoaloriented}. However, they typically rely on prompt-level adaptation without unifying solve/generate/memory loops. DeepTutor integrates tool-based reasoning, structured long-term memory, and bidirectional task coupling within a single architecture.
diff --git a/pyproject.toml b/pyproject.toml
index cb25ea441..51ee5c14b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,6 +26,7 @@ dependencies = [
"nest_asyncio>=1.5.8",
"tenacity>=8.0.0",
"pydantic>=2.0.0",
+ "pydantic-settings>=2.0.0",
"aiosqlite>=0.19.0",
"typer[all]>=0.9.0",
"rich>=13.0.0",
diff --git a/requirements.txt b/requirements.txt
index 7eb34cdb1..9fdaa96ec 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,17 +3,12 @@
# ============================================
# Python >= 3.10 required
#
-# For lighter installs, use the layered requirements:
-# pip install -r requirements/core.txt # CLI only (~80MB)
-# pip install -r requirements/server.txt # + API server
-# pip install -r requirements/rag-lite.txt # + LlamaIndex RAG
-# pip install -r requirements/rag-full.txt # compatibility alias of rag-lite
-# pip install -r requirements/providers.txt # + native LLM SDKs
-# pip install -r requirements/dev.txt # + dev/test tools
+# For targeted installs:
+# pip install -r requirements/cli.txt # CLI (full, with RAG + tools)
+# pip install -r requirements/server.txt # CLI + API server
+# pip install -r requirements/math-animator.txt # + Manim animation engine
+# pip install -r requirements/dev.txt # + dev/test tools
#
-# This file intentionally installs runtime-only dependencies.
-# Development tooling (pytest, pre-commit, security linters) lives in dev.txt.
+# This file installs the server runtime (CLI + API).
-r requirements/server.txt
--r requirements/rag-lite.txt
--r requirements/providers.txt
diff --git a/requirements/cli.txt b/requirements/cli.txt
index 249f19f1b..3123bd8ec 100644
--- a/requirements/cli.txt
+++ b/requirements/cli.txt
@@ -1,10 +1,49 @@
# ============================================
-# DeepTutor CLI Dependencies
+# DeepTutor CLI — Full Dependencies
# ============================================
-# Install: pip install -r requirements/cli.txt
+# Install: pip install -r requirements/cli.txt && pip install -e .
+# Everything needed to run the CLI with all tools (RAG, code execution, etc.)
--r core.txt
+# --- Config & templating ---
+python-dotenv>=1.0.0
+PyYAML>=6.0
+jinja2>=3.1.0
+# --- LLM ---
+openai>=1.30.0
+litellm>=1.79.0
+tiktoken>=0.5.0
+
+# --- LLM provider SDKs ---
+anthropic>=0.30.0
+dashscope>=1.14.0
+perplexityai>=0.1.0
+oauth-cli-kit>=0.1.1
+
+# --- HTTP clients ---
+aiohttp>=3.9.4
+httpx>=0.27.0
+requests>=2.32.2
+
+# --- Async helpers ---
+nest_asyncio>=1.5.8
+tenacity>=8.0.0
+
+# --- Data models & storage ---
+pydantic>=2.0.0
+pydantic-settings>=2.0.0
+aiosqlite>=0.19.0
+
+# --- RAG (LlamaIndex) ---
+llama-index>=0.14.12
+PyMuPDF>=1.26.0
+numpy>=1.24.0,<2.0.0
+arxiv>=2.0.0
+
+# --- Web search ---
+ddgs>=9.9.1
+
+# --- CLI framework ---
typer[all]>=0.9.0
rich>=13.0.0
prompt_toolkit>=3.0.36
diff --git a/requirements/core.txt b/requirements/core.txt
deleted file mode 100644
index 69f54c102..000000000
--- a/requirements/core.txt
+++ /dev/null
@@ -1,34 +0,0 @@
-# ============================================
-# DeepTutor Core Dependencies (CLI minimum)
-# ============================================
-# Install: pip install -r requirements/core.txt
-# This is the minimal set for CLI-only usage (~80MB)
-
-# --- Config & templating ---
-python-dotenv>=1.0.0
-PyYAML>=6.0
-jinja2>=3.1.0
-
-# --- LLM ---
-openai>=1.30.0
-litellm>=1.79.0
-tiktoken>=0.5.0
-ddgs>=9.9.1
-
-# --- HTTP clients ---
-aiohttp>=3.9.4
-httpx>=0.27.0
-requests>=2.32.2
-
-# --- Async helpers ---
-nest_asyncio>=1.5.8
-tenacity>=8.0.0
-
-# --- Data models ---
-pydantic>=2.0.0
-aiosqlite>=0.19.0
-
-# --- CLI framework ---
-typer[all]>=0.9.0
-rich>=13.0.0
-prompt_toolkit>=3.0.36
diff --git a/requirements/dev.txt b/requirements/dev.txt
index cf46625c0..2d2d8cda0 100644
--- a/requirements/dev.txt
+++ b/requirements/dev.txt
@@ -2,11 +2,9 @@
# DeepTutor Development Dependencies
# ============================================
# Install: pip install -r requirements/dev.txt
-# Includes runtime bundle layers + development tooling.
+# Includes full runtime + development tooling.
-r server.txt
--r rag-lite.txt
--r providers.txt
pytest>=7.0.0
pre-commit>=3.0.0
diff --git a/requirements/math-animator.txt b/requirements/math-animator.txt
index 9e902dfc7..6c08a9f14 100644
--- a/requirements/math-animator.txt
+++ b/requirements/math-animator.txt
@@ -1,8 +1,7 @@
# ============================================
-# DeepTutor Math Animator Dependencies
+# DeepTutor Math Animator — Addon
# ============================================
# Install: pip install -r requirements/math-animator.txt
-
--r cli.txt
+# Addon for `deeptutor animate`. Install alongside cli.txt or server.txt.
manim>=0.19.0
diff --git a/requirements/providers.txt b/requirements/providers.txt
deleted file mode 100644
index d7f38a594..000000000
--- a/requirements/providers.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-# ============================================
-# DeepTutor Optional LLM Provider SDKs
-# ============================================
-# Install: pip install -r requirements/providers.txt
-# Optional add-on layer for native provider SDKs.
-# Skip this if you only use OpenAI-compatible endpoints.
-
-anthropic>=0.30.0
-dashscope>=1.14.0
-perplexityai>=0.1.0
-oauth-cli-kit>=0.2.0
diff --git a/requirements/rag-full.txt b/requirements/rag-full.txt
deleted file mode 100644
index 96ac3e19d..000000000
--- a/requirements/rag-full.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-# ============================================
-# DeepTutor Full RAG Dependencies
-# ============================================
-# Install: pip install -r requirements/rag-full.txt
-# Compatibility alias for rag-lite (llamaindex-only add-on layer).
-
--r rag-lite.txt
diff --git a/requirements/rag-lite.txt b/requirements/rag-lite.txt
deleted file mode 100644
index 73a8bfa4b..000000000
--- a/requirements/rag-lite.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-# ============================================
-# DeepTutor Lightweight RAG Dependencies
-# ============================================
-# Install: pip install -r requirements/rag-lite.txt
-# Add-on layer for LlamaIndex-only RAG + PDF parsing.
-# Use with core/server (e.g., `core + rag-lite` or `server + rag-lite`).
-
-llama-index>=0.14.12
-PyMuPDF>=1.26.0
-numpy>=1.24.0,<2.0.0
-arxiv>=2.0.0
diff --git a/requirements/server.txt b/requirements/server.txt
index f3bb68d9b..6c7350fb1 100644
--- a/requirements/server.txt
+++ b/requirements/server.txt
@@ -1,11 +1,12 @@
# ============================================
-# DeepTutor API Server Dependencies
+# DeepTutor Server — Full Dependencies (CLI + Web)
# ============================================
-# Install: pip install -r requirements/server.txt
-# Adds FastAPI/uvicorn on top of core
+# Install: pip install -r requirements/server.txt && pip install -e .
+# Everything needed to run the API server and web frontend.
--r core.txt
+-r cli.txt
+# --- API server ---
fastapi>=0.100.0
uvicorn[standard]>=0.24.0
websockets>=12.0
diff --git a/requirements/tutorbot.txt b/requirements/tutorbot.txt
new file mode 100644
index 000000000..ab17800df
--- /dev/null
+++ b/requirements/tutorbot.txt
@@ -0,0 +1,32 @@
+# ============================================
+# DeepTutor TutorBot — Agent Engine Dependencies
+# ============================================
+# Install: pip install -r requirements/tutorbot.txt
+# These are the extra dependencies needed for TutorBot channels and agent features.
+# DeepTutor's core dependencies (litellm, pydantic, httpx, etc.) are NOT repeated here.
+
+-r server.txt
+
+# --- Agent core ---
+loguru>=0.7.3,<1.0.0
+croniter>=6.0.0,<7.0.0
+json-repair>=0.57.0,<1.0.0
+tiktoken>=0.12.0,<1.0.0
+chardet>=3.0.2,<6.0.0
+mcp>=1.26.0,<2.0.0
+
+# --- Web tools ---
+readability-lxml>=0.8.4,<1.0.0
+
+# --- Channel SDKs ---
+python-telegram-bot[socks]>=22.6,<23.0
+lark-oapi>=1.5.0,<2.0.0
+dingtalk-stream>=0.24.0,<1.0.0
+slack-sdk>=3.39.0,<4.0.0
+slackify-markdown>=0.2.0,<1.0.0
+qq-botpy>=1.2.0,<2.0.0
+python-socketio>=5.16.0,<6.0.0
+msgpack>=1.1.0,<2.0.0
+python-socks[asyncio]>=2.8.0,<3.0.0
+socksio>=1.0.0,<2.0.0
+websocket-client>=1.9.0,<2.0.0
diff --git a/scripts/start_tour.py b/scripts/start_tour.py
index 0aafe12d7..d5af721cb 100644
--- a/scripts/start_tour.py
+++ b/scripts/start_tour.py
@@ -84,10 +84,10 @@ def _load_runtime_deps():
# ---------------------------------------------------------------------------
PROFILE_COMMANDS: dict[str, list[str]] = {
- "cli-core": ["requirements/core.txt"],
- "cli-rag": ["requirements/core.txt", "requirements/rag-lite.txt"],
+ "cli-core": ["requirements/cli.txt"],
+ "cli-rag": ["requirements/cli.txt"],
"web-basic": ["requirements/server.txt"],
- "web-rag": ["requirements/server.txt", "requirements/rag-lite.txt"],
+ "web-rag": ["requirements/server.txt"],
}
# Legacy aliases kept for backward compatibility (hidden from UI).
@@ -164,7 +164,7 @@ def _node_install_cmd() -> list[str] | None:
# ---------------------------------------------------------------------------
-# Provider detection (for requirements/providers.txt)
+# Provider detection (providers are now bundled in cli.txt)
# ---------------------------------------------------------------------------
_NATIVE_BINDINGS = frozenset(
@@ -199,8 +199,7 @@ def _install_commands(profile: str, catalog: dict[str, Any]) -> list[tuple[list[
cmds.append(([sys.executable, "-m", "pip", "install", "-e", ".", "--no-deps"], PROJECT_ROOT))
if profile.startswith("web"):
cmds.append((["npm", "install"], PROJECT_ROOT / "web"))
- if _needs_providers(catalog):
- cmds.append(([sys.executable, "-m", "pip", "install", "-r", "requirements/providers.txt"], PROJECT_ROOT))
+ # Provider SDKs are now bundled in cli.txt, no separate install needed.
return cmds
diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py
index e5fedd2c0..425d624ec 100644
--- a/tests/cli/test_chat_cli.py
+++ b/tests/cli/test_chat_cli.py
@@ -31,36 +31,24 @@ def _install_fake_runtime(monkeypatch, captured_requests: list[TurnRequest]) ->
monkeypatch.setattr("deeptutor.app.facade.DeepTutorApp.stream_turn", _stream_turn)
-def test_chat_cli_json_mode_supports_runtime_payloads(monkeypatch) -> None:
+def test_run_command_json_mode(monkeypatch) -> None:
captured_requests: list[TurnRequest] = []
_install_fake_runtime(monkeypatch, captured_requests)
- capability_args = [
- [],
- ["--capability", "chat"],
- ["--capability", "deep_solve"],
- ["--capability", "deep_question"],
- ["--capability", "deep_research"],
- ]
+ capabilities = ["chat", "deep_solve", "deep_question", "deep_research"]
- for extra_args in capability_args:
+ for cap in capabilities:
result = runner.invoke(
app,
[
- "chat",
- "--once",
- "--format",
- "json",
- "--tool",
- "rag",
- "--kb",
- "demo-kb",
- "--history-ref",
- "session-old",
- "--notebook-ref",
- "nb1:rec1,rec2",
- *extra_args,
+ "run",
+ cap,
"hello world",
+ "--format", "json",
+ "--tool", "rag",
+ "--kb", "demo-kb",
+ "--history-ref", "session-old",
+ "--notebook-ref", "nb1:rec1,rec2",
],
)
@@ -68,7 +56,8 @@ def test_chat_cli_json_mode_supports_runtime_payloads(monkeypatch) -> None:
lines = [json.loads(line) for line in result.output.splitlines() if line.strip()]
assert any(line["type"] == "result" for line in lines)
- assert len(captured_requests) == 5
+ assert len(captured_requests) == 4
+ assert captured_requests[0].capability == "chat"
assert captured_requests[0].tools == ["rag"]
assert captured_requests[0].knowledge_bases == ["demo-kb"]
assert captured_requests[0].history_references == ["session-old"]
@@ -76,34 +65,29 @@ def test_chat_cli_json_mode_supports_runtime_payloads(monkeypatch) -> None:
assert captured_requests[-1].capability == "deep_research"
-def test_chat_cli_rich_single_shot_mode_uses_turn_runtime(monkeypatch) -> None:
+def test_run_command_rich_mode(monkeypatch) -> None:
captured_requests: list[TurnRequest] = []
_install_fake_runtime(monkeypatch, captured_requests)
- result = runner.invoke(app, ["chat", "--once", "hello rich"])
+ result = runner.invoke(app, ["run", "chat", "hello rich"])
assert result.exit_code == 0, result.output
assert "response body" in result.output
assert captured_requests[0].capability == "chat"
-def test_research_alias_maps_flags_to_typed_config(monkeypatch) -> None:
+def test_run_command_with_config(monkeypatch) -> None:
captured_requests: list[TurnRequest] = []
_install_fake_runtime(monkeypatch, captured_requests)
result = runner.invoke(
app,
[
- "research",
- "--mode",
- "report",
- "--depth",
- "deep",
- "--source",
- "web",
- "--source",
- "papers",
+ "run",
+ "deep_research",
"compare retrieval stacks",
+ "--config-json",
+ '{"mode":"report","depth":"deep","sources":["web","papers"]}',
],
)
diff --git a/tests/knowledge/test_kb_directory_layout.py b/tests/knowledge/test_kb_directory_layout.py
new file mode 100644
index 000000000..eb35133fc
--- /dev/null
+++ b/tests/knowledge/test_kb_directory_layout.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.knowledge.add_documents import DocumentAdder
+from deeptutor.knowledge.initializer import KnowledgeBaseInitializer
+
+
+def test_initializer_creates_llamaindex_only_layout(tmp_path: Path) -> None:
+ initializer = KnowledgeBaseInitializer(kb_name="demo", base_dir=str(tmp_path))
+ initializer.create_directory_structure()
+
+ kb_dir = tmp_path / "demo"
+ assert (kb_dir / "raw").exists()
+ assert (kb_dir / "llamaindex_storage").exists()
+ assert not (kb_dir / "images").exists()
+ assert not (kb_dir / "content_list").exists()
+ assert not (kb_dir / "rag_storage").exists()
+
+
+def test_document_adder_does_not_create_compatibility_dirs(tmp_path: Path) -> None:
+ kb_dir = tmp_path / "demo"
+ (kb_dir / "raw").mkdir(parents=True, exist_ok=True)
+ (kb_dir / "llamaindex_storage").mkdir(parents=True, exist_ok=True)
+
+ DocumentAdder(kb_name="demo", base_dir=str(tmp_path))
+
+ assert (kb_dir / "raw").exists()
+ assert (kb_dir / "llamaindex_storage").exists()
+ assert not (kb_dir / "images").exists()
+ assert not (kb_dir / "content_list").exists()
diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.py
index 24b81fdb9..c754335e1 100644
--- a/tests/services/config/test_provider_runtime.py
+++ b/tests/services/config/test_provider_runtime.py
@@ -1,4 +1,4 @@
-"""Tests for nanobot-style runtime config adapter."""
+"""Tests for TutorBot-style runtime config adapter."""
from __future__ import annotations
diff --git a/tests/services/search/test_web_search_runtime.py b/tests/services/search/test_web_search_runtime.py
index e052995fd..6551ffe50 100644
--- a/tests/services/search/test_web_search_runtime.py
+++ b/tests/services/search/test_web_search_runtime.py
@@ -1,4 +1,4 @@
-"""Tests for nanobot-style web_search runtime behavior."""
+"""Tests for TutorBot-style web_search runtime behavior."""
from __future__ import annotations
diff --git a/web/app/(utility)/memory/page.tsx b/web/app/(utility)/memory/page.tsx
index 81b680bef..f68a16955 100644
--- a/web/app/(utility)/memory/page.tsx
+++ b/web/app/(utility)/memory/page.tsx
@@ -2,7 +2,7 @@
import dynamic from "next/dynamic";
import { useCallback, useEffect, useRef, useState } from "react";
-import { Brain, Eraser, Loader2, RefreshCw, Save } from "lucide-react";
+import { Brain, Eraser, Loader2, RefreshCw, Save, BookOpen, User } from "lucide-react";
import { useAppShell } from "@/context/AppShellContext";
import { apiUrl } from "@/lib/api";
@@ -10,12 +10,39 @@ const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRende
ssr: false,
});
-interface MemoryPayload {
- content: string;
- exists: boolean;
- updated_at: string | null;
+type MemoryFile = "summary" | "profile";
+
+interface MemoryData {
+ summary: string;
+ profile: string;
+ summary_updated_at: string | null;
+ profile_updated_at: string | null;
}
+const TABS: { key: MemoryFile; label: string; icon: typeof Brain; hint: string; placeholder: string }[] = [
+ {
+ key: "summary",
+ label: "Summary",
+ icon: BookOpen,
+ hint: "Running summary of the learning journey. Auto-updated after conversations.",
+ placeholder: "## Current Focus\n- ...\n\n## Accomplishments\n- ...\n\n## Open Questions\n- ...",
+ },
+ {
+ key: "profile",
+ label: "Profile",
+ icon: User,
+ hint: "User identity, preferences, and knowledge levels. Auto-updated after conversations.",
+ placeholder: "## Identity\n- ...\n\n## Learning Style\n- ...\n\n## Knowledge Level\n- ...\n\n## Preferences\n- ...",
+ },
+];
+
+const EMPTY: MemoryData = {
+ summary: "",
+ profile: "",
+ summary_updated_at: null,
+ profile_updated_at: null,
+};
+
function formatUpdatedAt(value: string | null): string {
if (!value) return "Not updated yet";
const date = new Date(value);
@@ -25,21 +52,21 @@ function formatUpdatedAt(value: string | null): string {
export default function MemoryPage() {
const { activeSessionId, language } = useAppShell();
- const [memory, setMemory] = useState<MemoryPayload>({
- content: "",
- exists: false,
- updated_at: null,
- });
+ const [data, setData] = useState<MemoryData>(EMPTY);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [clearing, setClearing] = useState(false);
const [saving, setSaving] = useState(false);
- const [editorValue, setEditorValue] = useState("");
+ const [activeTab, setActiveTab] = useState<MemoryFile>("summary");
const [activeView, setActiveView] = useState<"edit" | "preview">("edit");
+ const [editors, setEditors] = useState<Record<MemoryFile, string>>({ summary: "", profile: "" });
const [toast, setToast] = useState("");
const textareaRef = useRef<HTMLTextAreaElement>(null);
- const hasChanges = editorValue !== memory.content;
+ const tab = TABS.find((t) => t.key === activeTab)!;
+ const editorValue = editors[activeTab];
+ const hasChanges = editorValue !== data[activeTab];
+ const updatedAt = data[`${activeTab}_updated_at` as keyof MemoryData] as string | null;
useEffect(() => {
if (!toast) return;
@@ -51,21 +78,32 @@ export default function MemoryPage() {
setLoading(true);
try {
const res = await fetch(apiUrl("/api/v1/memory"));
- const data = await res.json();
- setMemory({
- content: data.content || "",
- exists: Boolean(data.exists),
- updated_at: data.updated_at || null,
- });
- setEditorValue(data.content || "");
+ const d: MemoryData = await res.json();
+ setData(d);
+ setEditors({ summary: d.summary || "", profile: d.profile || "" });
} finally {
setLoading(false);
}
}, []);
- useEffect(() => {
- void loadMemory();
- }, [loadMemory]);
+ useEffect(() => { void loadMemory(); }, [loadMemory]);
+
+ const saveMemory = useCallback(async () => {
+ setSaving(true);
+ try {
+ const res = await fetch(apiUrl("/api/v1/memory"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ file: activeTab, content: editorValue }),
+ });
+ const d: MemoryData = await res.json();
+ setData(d);
+ setEditors((prev) => ({ ...prev, [activeTab]: d[activeTab] || "" }));
+ setToast(`${tab.label} saved`);
+ } finally {
+ setSaving(false);
+ }
+ }, [activeTab, editorValue, tab.label]);
const refreshMemory = useCallback(async () => {
setRefreshing(true);
@@ -73,62 +111,34 @@ export default function MemoryPage() {
const res = await fetch(apiUrl("/api/v1/memory/refresh"), {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- session_id: activeSessionId || undefined,
- language,
- }),
- });
- const data = await res.json();
- setMemory({
- content: data.content || "",
- exists: Boolean(data.exists),
- updated_at: data.updated_at || null,
+ body: JSON.stringify({ session_id: activeSessionId || undefined, language }),
});
- setEditorValue(data.content || "");
- setToast("Memory refreshed");
+ const d: MemoryData = await res.json();
+ setData(d);
+ setEditors({ summary: d.summary || "", profile: d.profile || "" });
+ setToast("Memory refreshed from session");
} finally {
setRefreshing(false);
}
}, [activeSessionId, language]);
const clearMemory = useCallback(async () => {
- if (!window.confirm("Clear memory.md?")) return;
+ if (!window.confirm(`Clear ${tab.label}?`)) return;
setClearing(true);
try {
- const res = await fetch(apiUrl("/api/v1/memory/clear"), { method: "POST" });
- const data = await res.json();
- setMemory({
- content: data.content || "",
- exists: Boolean(data.exists),
- updated_at: data.updated_at || null,
- });
- setEditorValue(data.content || "");
- setToast("Memory cleared");
- } finally {
- setClearing(false);
- }
- }, []);
-
- const saveMemory = useCallback(async () => {
- setSaving(true);
- try {
- const res = await fetch(apiUrl("/api/v1/memory"), {
- method: "PUT",
+ const res = await fetch(apiUrl("/api/v1/memory/clear"), {
+ method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: editorValue }),
- });
- const data = await res.json();
- setMemory({
- content: data.content || "",
- exists: Boolean(data.exists),
- updated_at: data.updated_at || null,
+ body: JSON.stringify({ file: activeTab }),
});
- setEditorValue(data.content || "");
- setToast("Memory saved");
+ const d: MemoryData = await res.json();
+ setData(d);
+ setEditors((prev) => ({ ...prev, [activeTab]: d[activeTab] || "" }));
+ setToast(`${tab.label} cleared`);
} finally {
- setSaving(false);
+ setClearing(false);
}
- }, [editorValue]);
+ }, [activeTab, tab.label]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -144,16 +154,14 @@ export default function MemoryPage() {
<div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
<div className="mx-auto max-w-[960px] px-6 py-8">
- {/* ── Header ── */}
+ {/* Header */}
<div className="mb-6 flex items-start justify-between">
<div>
<h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">
Memory
</h1>
{toast ? (
- <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">
- {toast}
- </p>
+ <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">{toast}</p>
) : (
<p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
{hasChanges ? "Unsaved changes" : "All changes saved"}
@@ -188,35 +196,54 @@ export default function MemoryPage() {
</div>
</div>
- {/* ── Meta & View toggle ── */}
- <div className="mb-8 flex items-center justify-between border-b border-[var(--border)]/50 pb-6">
- <div className="flex items-center gap-1">
- {(["edit", "preview"] as const).map((v) => (
+ {/* Tab selector */}
+ <div className="mb-4 flex items-center gap-1 border-b border-[var(--border)]/50 pb-3">
+ {TABS.map((t) => {
+ const Icon = t.icon;
+ const active = activeTab === t.key;
+ return (
<button
- key={v}
- onClick={() => setActiveView(v)}
+ key={t.key}
+ onClick={() => setActiveTab(t.key)}
className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- activeView === v
+ active
? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
}`}
>
- {v === "edit" ? "Edit" : "Preview"}
+ <Icon className="h-3.5 w-3.5" />
+ {t.label}
</button>
- ))}
- </div>
- <div className="flex items-center gap-4 text-[12px] text-[var(--muted-foreground)]">
- <span>
- Updated: {formatUpdatedAt(memory.updated_at)}
- </span>
- <span className="text-[var(--border)]">·</span>
- <span>
- Source: {activeSessionId ? "current session" : "latest session"}
+ );
+ })}
+ </div>
+
+ {/* Meta & View toggle */}
+ <div className="mb-6 flex items-center justify-between">
+ <p className="max-w-lg text-[12px] text-[var(--muted-foreground)]">{tab.hint}</p>
+ <div className="flex items-center gap-3">
+ <div className="flex items-center gap-1">
+ {(["edit", "preview"] as const).map((v) => (
+ <button
+ key={v}
+ onClick={() => setActiveView(v)}
+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
+ activeView === v
+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {v === "edit" ? "Edit" : "Preview"}
+ </button>
+ ))}
+ </div>
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ Updated: {formatUpdatedAt(updatedAt)}
</span>
</div>
</div>
- {/* ── Content ── */}
+ {/* Content */}
{loading ? (
<div className="flex min-h-[420px] items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
@@ -226,11 +253,11 @@ export default function MemoryPage() {
<textarea
ref={textareaRef}
value={editorValue}
- onChange={(e) => setEditorValue(e.target.value)}
+ onChange={(e) => setEditors((prev) => ({ ...prev, [activeTab]: e.target.value }))}
onKeyDown={handleKeyDown}
spellCheck={false}
className="min-h-[480px] w-full resize-none rounded-xl border border-[var(--border)] bg-transparent px-5 py-4 font-mono text-[13px] leading-7 text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- placeholder={"## Preferences\n- ...\n\n## Context\n- ..."}
+ placeholder={tab.placeholder}
/>
<p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">
Cmd+S to save · Markdown supported
@@ -238,18 +265,14 @@ export default function MemoryPage() {
</div>
) : editorValue.trim() ? (
<div className="rounded-xl border border-[var(--border)] px-6 py-5">
- <MarkdownRenderer
- content={editorValue}
- variant="prose"
- className="text-[14px] leading-relaxed"
- />
+ <MarkdownRenderer content={editorValue} variant="prose" className="text-[14px] leading-relaxed" />
</div>
) : (
<div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
<div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
<Brain size={18} />
</div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">No memory yet</p>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">No {tab.label.toLowerCase()} yet</p>
<p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
Refresh from a session or write directly in the editor.
</p>
diff --git a/web/app/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsx
new file mode 100644
index 000000000..d1618d2d3
--- /dev/null
+++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx
@@ -0,0 +1,229 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useParams, useRouter } from "next/navigation";
+import { ArrowLeft, Bot, Loader2, Send } from "lucide-react";
+import { apiUrl, wsUrl } from "@/lib/api";
+import AssistantResponse from "@/components/common/AssistantResponse";
+
+interface BotInfo {
+ bot_id: string;
+ name: string;
+ running: boolean;
+}
+
+interface ChatMsg {
+ role: "user" | "assistant";
+ content: string;
+ thinking?: string[];
+}
+
+export default function BotChatPage() {
+ const { botId } = useParams<{ botId: string }>();
+ const router = useRouter();
+
+ const [bot, setBot] = useState<BotInfo | null>(null);
+ const [messages, setMessages] = useState<ChatMsg[]>([]);
+ const [input, setInput] = useState("");
+ const [streaming, setStreaming] = useState(false);
+ const [thinking, setThinking] = useState<string[]>([]);
+ const thinkingRef = useRef<string[]>([]);
+
+ const wsRef = useRef<WebSocket | null>(null);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+
+ const scrollToBottom = useCallback(() => {
+ requestAnimationFrame(() => {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
+ });
+ }, []);
+
+ useEffect(() => {
+ fetch(apiUrl(`/api/v1/tutorbot/${botId}`))
+ .then((r) => (r.ok ? r.json() : null))
+ .then(setBot)
+ .catch(() => setBot(null));
+
+ fetch(apiUrl(`/api/v1/tutorbot/${botId}/history`))
+ .then((r) => (r.ok ? r.json() : []))
+ .then((history: { role: string; content: string }[]) => {
+ const restored: ChatMsg[] = history
+ .filter((m) => m.role === "user" || m.role === "assistant")
+ .map((m) => ({ role: m.role as "user" | "assistant", content: m.content }));
+ if (restored.length) setMessages(restored);
+ })
+ .catch(() => {});
+ }, [botId]);
+
+ useEffect(() => {
+ const ws = new WebSocket(wsUrl(`/api/v1/tutorbot/${botId}/ws`));
+ wsRef.current = ws;
+
+ ws.onmessage = (e) => {
+ const data = JSON.parse(e.data);
+ if (data.type === "thinking") {
+ thinkingRef.current = [...thinkingRef.current, data.content];
+ setThinking(thinkingRef.current);
+ scrollToBottom();
+ } else if (data.type === "content") {
+ const snap = thinkingRef.current;
+ setMessages((msgs) => [
+ ...msgs,
+ { role: "assistant", content: data.content, thinking: snap.length ? [...snap] : undefined },
+ ]);
+ thinkingRef.current = [];
+ setThinking([]);
+ scrollToBottom();
+ } else if (data.type === "done") {
+ setStreaming(false);
+ setTimeout(() => inputRef.current?.focus(), 50);
+ } else if (data.type === "proactive") {
+ setMessages((msgs) => [...msgs, { role: "assistant", content: data.content }]);
+ scrollToBottom();
+ } else if (data.type === "error") {
+ setMessages((msgs) => [...msgs, { role: "assistant", content: `Error: ${data.content}` }]);
+ thinkingRef.current = [];
+ setThinking([]);
+ setStreaming(false);
+ }
+ };
+
+ ws.onclose = () => {
+ setStreaming(false);
+ };
+
+ return () => {
+ ws.close();
+ wsRef.current = null;
+ };
+ }, [botId, scrollToBottom]);
+
+ const send = useCallback(() => {
+ const text = input.trim();
+ if (!text || streaming || !wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
+
+ setMessages((msgs) => [...msgs, { role: "user", content: text }]);
+ setInput("");
+ setStreaming(true);
+ setThinking([]);
+ wsRef.current.send(JSON.stringify({ content: text }));
+ scrollToBottom();
+ }, [input, streaming, scrollToBottom]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ send();
+ }
+ },
+ [send],
+ );
+
+ return (
+ <div className="flex h-full flex-col">
+ {/* Header */}
+ <div className="flex items-center gap-3 border-b border-[var(--border)] px-5 py-3">
+ <button
+ onClick={() => router.push("/agents")}
+ className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ </button>
+ <Bot className="h-4 w-4 text-[var(--muted-foreground)]" />
+ <span className="text-[14px] font-medium text-[var(--foreground)]">
+ {bot?.name ?? botId}
+ </span>
+ {bot?.running && (
+ <span className="h-2 w-2 rounded-full bg-emerald-500" />
+ )}
+ </div>
+
+ {/* Messages */}
+ <div ref={scrollRef} className="flex-1 overflow-y-auto px-5 py-6 [scrollbar-gutter:stable]">
+ <div className="mx-auto max-w-[720px] space-y-5">
+ {messages.length === 0 && !streaming && (
+ <div className="flex flex-col items-center justify-center pt-24 text-center">
+ <div className="mb-3 rounded-xl bg-[var(--muted)] p-3 text-[var(--muted-foreground)]">
+ <Bot size={22} />
+ </div>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">
+ Chat with {bot?.name ?? botId}
+ </p>
+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
+ Send a message to start the conversation.
+ </p>
+ </div>
+ )}
+
+ {messages.map((msg, i) => (
+ <div key={i} className={msg.role === "user" ? "flex justify-end" : ""}>
+ {msg.role === "user" ? (
+ <div className="max-w-[80%] rounded-2xl rounded-br-md bg-[var(--primary)] px-4 py-2.5 text-[14px] text-[var(--primary-foreground)]">
+ {msg.content}
+ </div>
+ ) : (
+ <div className="max-w-full">
+ {msg.thinking && msg.thinking.length > 0 && (
+ <details className="mb-2">
+ <summary className="cursor-pointer text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
+ Thinking ({msg.thinking.length} steps)
+ </summary>
+ <div className="mt-1 space-y-1 border-l-2 border-[var(--border)] pl-3">
+ {msg.thinking.map((t, j) => (
+ <p key={j} className="text-[12px] text-[var(--muted-foreground)]">{t}</p>
+ ))}
+ </div>
+ </details>
+ )}
+ <AssistantResponse content={msg.content} />
+ </div>
+ )}
+ </div>
+ ))}
+
+ {/* Streaming indicator */}
+ {streaming && (
+ <div className="space-y-2">
+ {thinking.length > 0 && (
+ <div className="space-y-1 border-l-2 border-[var(--border)] pl-3">
+ {thinking.map((t, i) => (
+ <p key={i} className="text-[12px] text-[var(--muted-foreground)]">{t}</p>
+ ))}
+ </div>
+ )}
+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ <span>{thinking.length > 0 ? "Working..." : "Thinking..."}</span>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Input */}
+ <div className="border-t border-[var(--border)] px-5 py-3">
+ <div className="mx-auto flex max-w-[720px] items-end gap-2">
+ <textarea
+ ref={inputRef}
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder="Type a message..."
+ rows={1}
+ disabled={streaming}
+ className="flex-1 resize-none rounded-xl border border-[var(--border)] bg-transparent px-4 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] disabled:opacity-50 placeholder:text-[var(--muted-foreground)]/40"
+ />
+ <button
+ onClick={send}
+ disabled={streaming || !input.trim()}
+ className="flex h-[42px] w-[42px] items-center justify-center rounded-xl bg-[var(--primary)] text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-30"
+ >
+ <Send className="h-4 w-4" />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
new file mode 100644
index 000000000..8efabd70b
--- /dev/null
+++ b/web/app/(workspace)/agents/page.tsx
@@ -0,0 +1,887 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ Bot,
+ FileText,
+ Heart,
+ Loader2,
+ MessageCircle,
+ Pencil,
+ Play,
+ Plus,
+ Save,
+ Square,
+ Trash2,
+ X,
+} from "lucide-react";
+import { useRouter } from "next/navigation";
+import dynamic from "next/dynamic";
+import { apiUrl } from "@/lib/api";
+
+const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {
+ ssr: false,
+});
+
+/* ── Types ──────────────────────────────────────────────── */
+
+interface BotInfo {
+ bot_id: string;
+ name: string;
+ description: string;
+ persona: string;
+ channels: string[];
+ model: string | null;
+ running: boolean;
+ started_at: string | null;
+}
+
+interface SoulTemplate {
+ id: string;
+ name: string;
+ content: string;
+}
+
+type Tab = "bots" | "profiles" | "souls";
+
+const BOT_FILES = ["SOUL.md", "USER.md", "TOOLS.md", "AGENTS.md", "HEARTBEAT.md"] as const;
+type BotFile = (typeof BOT_FILES)[number];
+
+/* ── Main Page ──────────────────────────────────────────── */
+
+export default function AgentsPage() {
+ const router = useRouter();
+ const [bots, setBots] = useState<BotInfo[]>([]);
+ const [souls, setSouls] = useState<SoulTemplate[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [activeTab, setActiveTab] = useState<Tab>("bots");
+ const [toast, setToast] = useState("");
+
+ useEffect(() => {
+ if (!toast) return;
+ const t = setTimeout(() => setToast(""), 3500);
+ return () => clearTimeout(t);
+ }, [toast]);
+
+ const loadBots = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await fetch(apiUrl("/api/v1/tutorbot"));
+ setBots(await res.json());
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ const loadSouls = useCallback(async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/tutorbot/souls"));
+ if (res.ok) setSouls(await res.json());
+ } catch { /* ignore */ }
+ }, []);
+
+ useEffect(() => { void loadBots(); void loadSouls(); }, [loadBots, loadSouls]);
+
+ return (
+ <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
+ <div className="mx-auto max-w-[960px] px-6 py-8">
+ {/* Header */}
+ <div className="mb-6">
+ <h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">
+ TutorBot Agents
+ </h1>
+ {toast ? (
+ <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">{toast}</p>
+ ) : (
+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
+ Manage your in-process TutorBot instances
+ </p>
+ )}
+ </div>
+
+ {/* Tabs */}
+ <div className="mb-6 flex items-center gap-1 border-b border-[var(--border)]/50 pb-3">
+ {([
+ { key: "bots" as Tab, label: "Bots", icon: Bot },
+ { key: "profiles" as Tab, label: "Profiles", icon: FileText },
+ { key: "souls" as Tab, label: "Souls", icon: Heart },
+ ]).map((t) => {
+ const Icon = t.icon;
+ const active = activeTab === t.key;
+ return (
+ <button
+ key={t.key}
+ onClick={() => setActiveTab(t.key)}
+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
+ active
+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Icon className="h-3.5 w-3.5" />
+ {t.label}
+ </button>
+ );
+ })}
+ </div>
+
+ {activeTab === "bots" ? (
+ <BotsTab
+ bots={bots}
+ souls={souls}
+ loading={loading}
+ onReload={loadBots}
+ onToast={setToast}
+ router={router}
+ />
+ ) : activeTab === "profiles" ? (
+ <ProfilesTab bots={bots} loading={loading} onToast={setToast} />
+ ) : (
+ <SoulsTab souls={souls} onReload={loadSouls} onToast={setToast} />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/* ── Bots Tab ───────────────────────────────────────────── */
+
+function BotsTab({
+ bots,
+ souls,
+ loading,
+ onReload,
+ onToast,
+ router,
+}: {
+ bots: BotInfo[];
+ souls: SoulTemplate[];
+ loading: boolean;
+ onReload: () => Promise<void>;
+ onToast: (msg: string) => void;
+ router: ReturnType<typeof useRouter>;
+}) {
+ const [showCreate, setShowCreate] = useState(false);
+ const [creating, setCreating] = useState(false);
+
+ const [formName, setFormName] = useState("");
+ const [formDesc, setFormDesc] = useState("");
+ const [formSoulId, setFormSoulId] = useState("_custom");
+ const [formSoul, setFormSoul] = useState("");
+ const [formModel, setFormModel] = useState("");
+
+ const resetForm = () => {
+ setFormName(""); setFormDesc(""); setFormSoulId("_custom");
+ setFormSoul(""); setFormModel("");
+ };
+
+ const botId = useMemo(() => {
+ const slug = formName.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
+ return slug || "";
+ }, [formName]);
+
+ const selectSoul = (id: string) => {
+ setFormSoulId(id);
+ if (id !== "_custom") {
+ const soul = souls.find((s) => s.id === id);
+ if (soul) setFormSoul(soul.content);
+ }
+ };
+
+ const createBot = useCallback(async () => {
+ if (!botId) return;
+ setCreating(true);
+ try {
+ const res = await fetch(apiUrl("/api/v1/tutorbot"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ bot_id: botId,
+ name: formName.trim(),
+ description: formDesc.trim(),
+ persona: formSoul.trim(),
+ model: formModel.trim() || undefined,
+ }),
+ });
+ if (res.ok) {
+ onToast(`${formName.trim()} created`);
+ setShowCreate(false);
+ resetForm();
+ await onReload();
+ }
+ } finally {
+ setCreating(false);
+ }
+ }, [botId, formName, formDesc, formSoul, formModel, onReload, onToast]);
+
+ const startBot = useCallback(async (bid: string) => {
+ const res = await fetch(apiUrl("/api/v1/tutorbot"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ bot_id: bid }),
+ });
+ if (res.ok) { onToast(`${bid} started`); await onReload(); }
+ }, [onReload, onToast]);
+
+ const stopBot = useCallback(async (bid: string) => {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`), { method: "DELETE" });
+ if (res.ok) { onToast(`${bid} stopped`); await onReload(); }
+ }, [onReload, onToast]);
+
+ const destroyBot = useCallback(async (bid: string, name: string) => {
+ if (!window.confirm(`Permanently delete "${name}" (${bid})? This cannot be undone.`)) return;
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/destroy`), { method: "DELETE" });
+ if (res.ok) { onToast(`${name} deleted`); await onReload(); }
+ }, [onReload, onToast]);
+
+ return (
+ <>
+ {/* New Bot button */}
+ <div className="mb-4 flex justify-end">
+ <button
+ onClick={() => setShowCreate(true)}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Plus className="h-3 w-3" />
+ New Bot
+ </button>
+ </div>
+
+ {/* Create form */}
+ {showCreate && (
+ <div className="mb-6 rounded-xl border border-[var(--border)] p-5">
+ <div className="mb-4 flex items-center justify-between">
+ <h2 className="text-[15px] font-medium text-[var(--foreground)]">Create TutorBot</h2>
+ <button onClick={() => { setShowCreate(false); resetForm(); }} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+ <div className="grid gap-3">
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Name</label>
+ <input
+ value={formName}
+ onChange={(e) => setFormName(e.target.value)}
+ placeholder="e.g. Math Tutor"
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
+ />
+ {botId && (
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">ID: {botId}</p>
+ )}
+ </div>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Description <span className="font-normal opacity-60">(optional)</span></label>
+ <input
+ value={formDesc}
+ onChange={(e) => setFormDesc(e.target.value)}
+ placeholder="A brief description of what this bot does"
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
+ />
+ </div>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Soul</label>
+ <div className="flex flex-wrap gap-1.5 mb-2">
+ <button
+ onClick={() => selectSoul("_custom")}
+ className={`rounded-md px-2.5 py-1 text-[12px] transition-colors ${
+ formSoulId === "_custom"
+ ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ Custom
+ </button>
+ {souls.map((s) => (
+ <button
+ key={s.id}
+ onClick={() => selectSoul(s.id)}
+ className={`rounded-md px-2.5 py-1 text-[12px] transition-colors ${
+ formSoulId === s.id
+ ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {s.name}
+ </button>
+ ))}
+ </div>
+ <textarea
+ value={formSoul}
+ onChange={(e) => { setFormSoul(e.target.value); setFormSoulId("_custom"); }}
+ placeholder="Define the bot's personality, values, and communication style in markdown..."
+ rows={8}
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
+ />
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
+ Pick a soul from the library above, or write your own. Manage the library in the Souls tab.
+ </p>
+ </div>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Model <span className="font-normal opacity-60">(optional)</span></label>
+ <input
+ value={formModel}
+ onChange={(e) => setFormModel(e.target.value)}
+ placeholder="Uses default model if empty"
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
+ />
+ </div>
+ <div className="flex justify-end">
+ <button
+ onClick={createBot}
+ disabled={creating || !botId}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
+ >
+ {creating ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}
+ Create & Start
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Bot list */}
+ {loading ? (
+ <div className="flex min-h-[320px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : bots.length === 0 ? (
+ <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
+ <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
+ <Bot size={18} />
+ </div>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">No TutorBots yet</p>
+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
+ Create your first TutorBot to get started.
+ </p>
+ </div>
+ ) : (
+ <div className="grid gap-3">
+ {bots.map((bot) => (
+ <div
+ key={bot.bot_id}
+ className="flex items-center justify-between rounded-xl border border-[var(--border)] px-5 py-4 transition-colors hover:border-[var(--border)]"
+ >
+ <div className="flex items-center gap-4 min-w-0">
+ <div className={`h-2 w-2 shrink-0 rounded-full ${bot.running ? "bg-emerald-500" : "bg-[var(--muted-foreground)]/30"}`} />
+ <div className="min-w-0">
+ <p className="text-[14px] font-medium text-[var(--foreground)] truncate">{bot.name}</p>
+ <div className="mt-0.5 flex items-center gap-3 text-[12px] text-[var(--muted-foreground)]">
+ {bot.description ? (
+ <span className="truncate max-w-[300px]">{bot.description}</span>
+ ) : (
+ <span>{bot.bot_id}</span>
+ )}
+ {bot.model && <span>· {bot.model}</span>}
+ {bot.started_at && (
+ <span>· started {new Date(bot.started_at).toLocaleString()}</span>
+ )}
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-2 shrink-0">
+ {bot.running ? (
+ <>
+ <button
+ onClick={() => router.push(`/agents/${bot.bot_id}/chat`)}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--primary)] transition-colors hover:border-[var(--primary)]/50"
+ >
+ <MessageCircle className="h-3 w-3" />
+ Chat
+ </button>
+ <button
+ onClick={() => stopBot(bot.bot_id)}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-red-400 transition-colors hover:border-red-400/50"
+ >
+ <Square className="h-3 w-3" />
+ Stop
+ </button>
+ </>
+ ) : (
+ <button
+ onClick={() => startBot(bot.bot_id)}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Play className="h-3 w-3" />
+ Start
+ </button>
+ )}
+ <button
+ onClick={() => destroyBot(bot.bot_id, bot.name)}
+ className="inline-flex items-center justify-center rounded-lg border border-[var(--border)]/50 p-1.5 text-[var(--muted-foreground)]/50 transition-colors hover:border-red-400/50 hover:text-red-400"
+ >
+ <Trash2 className="h-3 w-3" />
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </>
+ );
+}
+
+/* ── Profiles Tab ───────────────────────────────────────── */
+
+function ProfilesTab({
+ bots,
+ loading,
+ onToast,
+}: {
+ bots: BotInfo[];
+ loading: boolean;
+ onToast: (msg: string) => void;
+}) {
+ const [selectedBot, setSelectedBot] = useState<string>("");
+ const [activeFile, setActiveFile] = useState<BotFile>("SOUL.md");
+ const [files, setFiles] = useState<Record<string, string>>({});
+ const [editor, setEditor] = useState("");
+ const [loadingFiles, setLoadingFiles] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [activeView, setActiveView] = useState<"edit" | "preview">("edit");
+
+ const hasChanges = editor !== (files[activeFile] ?? "");
+
+ useEffect(() => {
+ if (bots.length > 0 && !selectedBot) {
+ setSelectedBot(bots[0].bot_id);
+ }
+ }, [bots, selectedBot]);
+
+ const loadFiles = useCallback(async (bid: string) => {
+ if (!bid) return;
+ setLoadingFiles(true);
+ try {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}/files`));
+ const data: Record<string, string> = await res.json();
+ setFiles(data);
+ setEditor(data[activeFile] ?? "");
+ } finally {
+ setLoadingFiles(false);
+ }
+ }, [activeFile]);
+
+ useEffect(() => {
+ if (selectedBot) void loadFiles(selectedBot);
+ }, [selectedBot, loadFiles]);
+
+ useEffect(() => {
+ setEditor(files[activeFile] ?? "");
+ setActiveView("edit");
+ }, [activeFile, files]);
+
+ const saveFile = useCallback(async () => {
+ if (!selectedBot) return;
+ setSaving(true);
+ try {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${selectedBot}/files/${activeFile}`), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ content: editor }),
+ });
+ if (res.ok) {
+ setFiles((prev) => ({ ...prev, [activeFile]: editor }));
+ onToast(`${activeFile} saved`);
+ }
+ } finally {
+ setSaving(false);
+ }
+ }, [selectedBot, activeFile, editor, onToast]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === "s") {
+ e.preventDefault();
+ void saveFile();
+ }
+ },
+ [saveFile],
+ );
+
+ if (loading) {
+ return (
+ <div className="flex min-h-[320px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ );
+ }
+
+ if (bots.length === 0) {
+ return (
+ <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
+ <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
+ <FileText size={18} />
+ </div>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">No bots to configure</p>
+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
+ Create a bot first in the Bots tab.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ {/* Bot selector */}
+ <div className="flex items-center gap-3">
+ <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">Bot</label>
+ <select
+ value={selectedBot}
+ onChange={(e) => setSelectedBot(e.target.value)}
+ className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ >
+ {bots.map((b) => (
+ <option key={b.bot_id} value={b.bot_id}>
+ {b.name} ({b.bot_id})
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* File tabs */}
+ <div className="flex items-center gap-1 border-b border-[var(--border)]/50 pb-2">
+ {BOT_FILES.map((fn) => (
+ <button
+ key={fn}
+ onClick={() => setActiveFile(fn)}
+ className={`rounded-lg px-2.5 py-1 text-[12px] transition-colors ${
+ activeFile === fn
+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {fn.replace(".md", "")}
+ </button>
+ ))}
+ </div>
+
+ {/* Toolbar */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1">
+ {(["edit", "preview"] as const).map((v) => (
+ <button
+ key={v}
+ onClick={() => setActiveView(v)}
+ className={`rounded-lg px-3 py-1.5 text-[12px] transition-colors ${
+ activeView === v
+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {v === "edit" ? "Edit" : "Preview"}
+ </button>
+ ))}
+ </div>
+ <button
+ onClick={saveFile}
+ disabled={saving || !hasChanges}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
+ >
+ {saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}
+ Save
+ </button>
+ </div>
+
+ {/* Editor / Preview */}
+ {loadingFiles ? (
+ <div className="flex min-h-[400px] items-center justify-center">
+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
+ </div>
+ ) : activeView === "edit" ? (
+ <div>
+ <textarea
+ value={editor}
+ onChange={(e) => setEditor(e.target.value)}
+ onKeyDown={handleKeyDown}
+ spellCheck={false}
+ className="min-h-[420px] w-full resize-none rounded-xl border border-[var(--border)] bg-transparent px-5 py-4 font-mono text-[13px] leading-7 text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
+ placeholder={`Edit ${activeFile}...`}
+ />
+ <p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">
+ Cmd+S to save · Markdown supported
+ {hasChanges && " · Unsaved changes"}
+ </p>
+ </div>
+ ) : editor.trim() ? (
+ <div className="rounded-xl border border-[var(--border)] px-6 py-5">
+ <MarkdownRenderer content={editor} variant="prose" className="text-[14px] leading-relaxed" />
+ </div>
+ ) : (
+ <div className="flex min-h-[300px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
+ <p className="text-[14px] font-medium text-[var(--foreground)]">{activeFile} is empty</p>
+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
+ Switch to Edit to add content.
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ── Souls Tab ──────────────────────────────────────────── */
+
+function SoulsTab({
+ souls,
+ onReload,
+ onToast,
+}: {
+ souls: SoulTemplate[];
+ onReload: () => Promise<void>;
+ onToast: (msg: string) => void;
+}) {
+ const [editing, setEditing] = useState<string | null>(null);
+ const [creating, setCreating] = useState(false);
+ const [saving, setSaving] = useState(false);
+
+ const [editName, setEditName] = useState("");
+ const [editContent, setEditContent] = useState("");
+ const [newName, setNewName] = useState("");
+ const [newContent, setNewContent] = useState("");
+
+ const startEdit = (soul: SoulTemplate) => {
+ setEditing(soul.id);
+ setEditName(soul.name);
+ setEditContent(soul.content);
+ setCreating(false);
+ };
+
+ const cancelEdit = () => {
+ setEditing(null);
+ setEditName("");
+ setEditContent("");
+ };
+
+ const startCreate = () => {
+ setCreating(true);
+ setEditing(null);
+ setNewName("");
+ setNewContent("");
+ };
+
+ const saveSoul = useCallback(async () => {
+ if (!editing) return;
+ setSaving(true);
+ try {
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/souls/${editing}`), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: editName.trim(), content: editContent }),
+ });
+ if (res.ok) {
+ onToast(`"${editName.trim()}" updated`);
+ cancelEdit();
+ await onReload();
+ }
+ } finally {
+ setSaving(false);
+ }
+ }, [editing, editName, editContent, onReload, onToast]);
+
+ const createSoul = useCallback(async () => {
+ const name = newName.trim();
+ if (!name) return;
+ const id = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
+ if (!id) return;
+ setSaving(true);
+ try {
+ const res = await fetch(apiUrl("/api/v1/tutorbot/souls"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ id, name, content: newContent }),
+ });
+ if (res.ok) {
+ onToast(`"${name}" created`);
+ setCreating(false);
+ setNewName("");
+ setNewContent("");
+ await onReload();
+ } else if (res.status === 409) {
+ onToast(`Soul ID "${id}" already exists`);
+ }
+ } finally {
+ setSaving(false);
+ }
+ }, [newName, newContent, onReload, onToast]);
+
+ const deleteSoul = useCallback(async (soul: SoulTemplate) => {
+ if (!window.confirm(`Delete soul "${soul.name}"?`)) return;
+ const res = await fetch(apiUrl(`/api/v1/tutorbot/souls/${soul.id}`), { method: "DELETE" });
+ if (res.ok) {
+ if (editing === soul.id) cancelEdit();
+ onToast(`"${soul.name}" deleted`);
+ await onReload();
+ }
+ }, [editing, onReload, onToast]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLTextAreaElement>, save: () => void) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === "s") {
+ e.preventDefault();
+ save();
+ }
+ },
+ [],
+ );
+
+ return (
+ <div className="space-y-4">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <p className="text-[13px] text-[var(--muted-foreground)]">
+ Reusable soul templates for creating TutorBots.
+ </p>
+ <button
+ onClick={startCreate}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Plus className="h-3 w-3" />
+ New Soul
+ </button>
+ </div>
+
+ {/* Create form */}
+ {creating && (
+ <div className="rounded-xl border border-[var(--border)] p-5">
+ <div className="mb-4 flex items-center justify-between">
+ <h2 className="text-[15px] font-medium text-[var(--foreground)]">New Soul</h2>
+ <button onClick={() => setCreating(false)} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+ <div className="grid gap-3">
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Name</label>
+ <input
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ placeholder="e.g. Creative Writer"
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
+ />
+ {newName.trim() && (
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ ID: {newName.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}
+ </p>
+ )}
+ </div>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Content</label>
+ <textarea
+ value={newContent}
+ onChange={(e) => setNewContent(e.target.value)}
+ onKeyDown={(e) => handleKeyDown(e, createSoul)}
+ placeholder="Define the soul in markdown..."
+ rows={10}
+ spellCheck={false}
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <button
+ onClick={() => setCreating(false)}
+ className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={createSoul}
+ disabled={saving || !newName.trim()}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
+ >
+ {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus className="h-3.5 w-3.5" />}
+ Create
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Soul list */}
+ {souls.length === 0 && !creating ? (
+ <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
+ <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
+ <Heart size={18} />
+ </div>
+ <p className="text-[14px] font-medium text-[var(--foreground)]">No souls yet</p>
+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
+ Create your first soul template. Default presets will be seeded automatically on next server restart.
+ </p>
+ </div>
+ ) : (
+ <div className="grid gap-3">
+ {souls.map((soul) =>
+ editing === soul.id ? (
+ <div key={soul.id} className="rounded-xl border border-[var(--ring)] p-5">
+ <div className="grid gap-3">
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Name</label>
+ <input
+ value={editName}
+ onChange={(e) => setEditName(e.target.value)}
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ />
+ </div>
+ <div>
+ <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">Content</label>
+ <textarea
+ value={editContent}
+ onChange={(e) => setEditContent(e.target.value)}
+ onKeyDown={(e) => handleKeyDown(e, saveSoul)}
+ rows={12}
+ spellCheck={false}
+ className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <button
+ onClick={cancelEdit}
+ className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={saveSoul}
+ disabled={saving || !editName.trim()}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
+ >
+ {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
+ Save
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div
+ key={soul.id}
+ className="group flex items-start justify-between rounded-xl border border-[var(--border)] px-5 py-4 transition-colors hover:border-[var(--border)]"
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <Heart className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />
+ <p className="text-[14px] font-medium text-[var(--foreground)]">{soul.name}</p>
+ <span className="text-[11px] text-[var(--muted-foreground)]/60">{soul.id}</span>
+ </div>
+ <p className="mt-1.5 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)] pl-5.5">
+ {soul.content.replace(/^#.*\n+/g, "").slice(0, 200)}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-1 ml-4 opacity-0 group-hover:opacity-100 transition-opacity">
+ <button
+ onClick={() => startEdit(soul)}
+ className="inline-flex items-center justify-center rounded-lg border border-[var(--border)]/50 p-1.5 text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Pencil className="h-3 w-3" />
+ </button>
+ <button
+ onClick={() => deleteSoul(soul)}
+ className="inline-flex items-center justify-center rounded-lg border border-[var(--border)]/50 p-1.5 text-[var(--muted-foreground)] transition-colors hover:border-red-400/50 hover:text-red-400"
+ >
+ <Trash2 className="h-3 w-3" />
+ </button>
+ </div>
+ </div>
+ ),
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/app/(workspace)/page.tsx b/web/app/(workspace)/page.tsx
index 70f3854ca..2f1e2aa8b 100644
--- a/web/app/(workspace)/page.tsx
+++ b/web/app/(workspace)/page.tsx
@@ -2,7 +2,7 @@
import dynamic from "next/dynamic";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import Image from "next/image";
+
import {
BrainCircuit,
Clapperboard,
@@ -48,6 +48,7 @@ import {
createEmptyResearchConfig,
validateResearchConfig,
type DeepResearchFormConfig,
+ type OutlineItem,
type ResearchSource,
} from "@/lib/research-types";
import { listKnowledgeBases } from "@/lib/knowledge-api";
@@ -662,20 +663,39 @@ export default function HomePage() {
setShowAtPopup(false);
};
+ const handleConfirmOutline = useCallback(
+ (outline: OutlineItem[], _topic: string, originalConfig?: Record<string, unknown> | null) => {
+ const config: Record<string, unknown> = {
+ ...(originalConfig ?? {
+ mode: researchConfig.mode,
+ depth: researchConfig.depth,
+ sources: [...researchConfig.sources],
+ }),
+ confirmed_outline: outline,
+ };
+ sendMessage(_topic, [], config, undefined, undefined, {
+ displayUserMessage: false,
+ persistUserMessage: false,
+ });
+ shouldAutoScrollRef.current = true;
+ },
+ [researchConfig, sendMessage],
+ );
+
return (
- <div className="flex h-full flex-col bg-[var(--background)]">
- <div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col px-6">
+ <div className="flex h-full flex-col overflow-hidden bg-[var(--background)]">
+ <div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">
{/* ===== Welcome / Messages ===== */}
{!hasMessages ? (
<div className="flex flex-1 min-h-0 flex-col items-center justify-center animate-fade-in">
- <div className="mb-8 text-center">
- <div className="mb-5 inline-flex">
- <Image src="/logo-ver2.png" alt={t("DeepTutor")} width={56} height={56} priority />
- </div>
- <h1 className="text-[32px] font-semibold tracking-tight text-[var(--foreground)]">
+ <div className="text-center">
+ <h1 className="font-serif text-[36px] font-medium tracking-[-0.01em] text-[var(--foreground)]">
{t("What would you like to learn?")}
</h1>
+ <p className="mt-4 text-[15px] text-[var(--muted-foreground)]">
+ {t("Ask anything — I'm here to help you understand.")}
+ </p>
</div>
</div>
) : (
@@ -683,7 +703,7 @@ export default function HomePage() {
ref={messagesContainerRef}
data-chat-scroll-root="true"
onScroll={handleMessagesScroll}
- className={`mx-auto w-full flex-1 min-h-0 space-y-6 overflow-y-auto scroll-smooth pt-6 pr-4 [scrollbar-gutter:stable] ${
+ className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pt-6 pr-4 [scrollbar-gutter:stable] ${
hasMessages ? "" : "pb-6"
}`}
style={hasMessages ? { paddingBottom: `${Math.max(composerHeight + 24, 120)}px` } : undefined}
@@ -719,6 +739,7 @@ export default function HomePage() {
onAnswerNow={handleAnswerNow}
onCopyAssistantMessage={copyAssistantMessage}
onRetryMessage={(snapshot) => replaySnapshot(snapshot)}
+ onConfirmOutline={handleConfirmOutline}
/>
<div ref={messagesEndRef} className="h-px w-full shrink-0" />
</div>
diff --git a/web/app/globals.css b/web/app/globals.css
index 233538318..1c2772899 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -4,51 +4,59 @@
@layer base {
:root {
- --background: #f9fafb;
- --foreground: #111827;
- --card: #ffffff;
- --card-foreground: #111827;
- --popover: #ffffff;
- --popover-foreground: #111827;
- --primary: #6366f1;
- --primary-foreground: #ffffff;
- --secondary: #f1f5f9;
- --secondary-foreground: #111827;
- --muted: #f1f5f9;
- --muted-foreground: #64748b;
- --accent: #f1f5f9;
- --accent-foreground: #111827;
- --destructive: #ef4444;
- --destructive-foreground: #ffffff;
- --border: #e5e7eb;
- --input: #e5e7eb;
- --ring: #6366f1;
+ --background: #FAF9F6;
+ --foreground: #2D2B28;
+ --card: #FFFFFF;
+ --card-foreground: #2D2B28;
+ --popover: #FFFFFF;
+ --popover-foreground: #2D2B28;
+ --primary: #C35A2C;
+ --primary-foreground: #FFFFFF;
+ --secondary: #F0EDE7;
+ --secondary-foreground: #2D2B28;
+ --muted: #F0EDE7;
+ --muted-foreground: #8B8580;
+ --accent: #F0EDE7;
+ --accent-foreground: #2D2B28;
+ --destructive: #D44A3C;
+ --destructive-foreground: #FFFFFF;
+ --border: #E8E4DE;
+ --input: #E8E4DE;
+ --ring: #C35A2C;
}
.dark {
- --background: #10121a;
- --foreground: #e8ecf4;
- --card: #1a1e2a;
- --card-foreground: #e8ecf4;
- --popover: #1a1e2a;
- --popover-foreground: #e8ecf4;
- --primary: #818cf8;
- --primary-foreground: #10121a;
- --secondary: #1f2435;
- --secondary-foreground: #e8ecf4;
- --muted: #1f2435;
- --muted-foreground: #8b95a9;
- --accent: #252a3c;
- --accent-foreground: #e8ecf4;
- --destructive: #ef4444;
- --destructive-foreground: #ffffff;
- --border: #2a3044;
- --input: #2a3044;
- --ring: #818cf8;
+ --background: #1A1918;
+ --foreground: #E8E4DE;
+ --card: #242220;
+ --card-foreground: #E8E4DE;
+ --popover: #242220;
+ --popover-foreground: #E8E4DE;
+ --primary: #D4734B;
+ --primary-foreground: #1A1918;
+ --secondary: #2A2725;
+ --secondary-foreground: #E8E4DE;
+ --muted: #2A2725;
+ --muted-foreground: #9B9590;
+ --accent: #302D2A;
+ --accent-foreground: #E8E4DE;
+ --destructive: #D44A3C;
+ --destructive-foreground: #FFFFFF;
+ --border: #3A3634;
+ --input: #3A3634;
+ --ring: #D4734B;
}
* {
@apply border-[color:var(--border)];
+ scrollbar-width: thin;
+ scrollbar-color: var(--border) transparent;
+ }
+
+ html,
+ body {
+ height: 100%;
+ overflow: hidden;
}
html {
@@ -95,11 +103,34 @@
}
}
+/* ─── Scrollbar ─── */
+::-webkit-scrollbar {
+ width: 6px;
+ height: 6px;
+}
+
+::-webkit-scrollbar-track {
+ background: transparent;
+}
+
+::-webkit-scrollbar-thumb {
+ background: var(--border);
+ border-radius: 3px;
+}
+
+::-webkit-scrollbar-thumb:hover {
+ background: var(--muted-foreground);
+}
+
/* ─── Prose: base ─── */
+.prose {
+ @apply font-serif text-[15px];
+}
+
.prose pre {
@apply rounded-lg p-4 overflow-x-auto my-4;
- background: #1e293b;
- color: #cbd5e1;
+ background: #292524;
+ color: #D6D3D1;
}
.prose code:not(.md-code-block__code):not(.md-inline-code) {
@@ -151,29 +182,47 @@
/* ─── Headings ─── */
.prose h1,
.prose h2,
+.prose h3,
+.prose h4,
+.prose h5,
+.prose h6 {
+ @apply font-sans;
+}
+
+.prose h1 {
+ @apply text-2xl font-bold tracking-tight mt-8 mb-4;
+ color: var(--foreground);
+}
+
+.prose h2 {
+ @apply text-xl font-semibold tracking-tight mt-7 mb-3;
+ color: var(--foreground);
+}
+
.prose h3 {
- @apply font-semibold tracking-tight mt-6 mb-3;
+ @apply text-lg font-semibold tracking-tight mt-6 mb-2.5;
color: var(--foreground);
}
.prose h4 {
- @apply font-semibold tracking-tight mt-5 mb-2 text-base;
+ @apply text-base font-semibold tracking-tight mt-5 mb-2;
color: var(--foreground);
}
.prose h5 {
- @apply font-semibold tracking-tight mt-4 mb-2 text-sm;
+ @apply text-sm font-semibold tracking-tight mt-4 mb-2;
color: var(--foreground);
}
.prose h6 {
- @apply font-semibold tracking-tight mt-4 mb-2 text-sm;
+ @apply text-sm font-semibold tracking-tight mt-4 mb-2;
color: var(--muted-foreground);
}
/* ─── Body text ─── */
.prose p {
- @apply leading-7 mb-4;
+ @apply mb-4;
+ line-height: 1.75;
color: var(--foreground);
}
@@ -274,7 +323,7 @@
/* ─── Blockquote ─── */
.prose blockquote {
@apply border-l-[3px] pl-4 italic my-4;
- border-color: var(--primary);
+ border-color: var(--muted-foreground);
color: var(--muted-foreground);
}
@@ -329,6 +378,17 @@
border-color: var(--border);
}
+.prose details:empty,
+.prose details:not(:has(> :not(summary))),
+.md-renderer details:empty,
+.md-renderer details:not(:has(> :not(summary))) {
+ display: none;
+}
+
+.prose > :empty:not(hr):not(br):not(img) {
+ display: none;
+}
+
.prose summary {
@apply cursor-pointer font-medium select-none;
color: var(--foreground);
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
index fb0615a57..6b5614cc1 100644
--- a/web/app/layout.tsx
+++ b/web/app/layout.tsx
@@ -1,14 +1,20 @@
import type { Metadata } from "next";
-import { Inter } from "next/font/google";
+import { Plus_Jakarta_Sans, Lora } from "next/font/google";
import "./globals.css";
import ThemeScript from "@/components/ThemeScript";
import { AppShellProvider } from "@/context/AppShellContext";
import { I18nClientBridge } from "@/i18n/I18nClientBridge";
-const font = Inter({
+const fontSans = Plus_Jakarta_Sans({
subsets: ["latin"],
display: "swap",
- fallback: ["system-ui", "sans-serif"],
+ variable: "--font-sans",
+});
+
+const fontSerif = Lora({
+ subsets: ["latin"],
+ display: "swap",
+ variable: "--font-serif",
});
export const metadata: Metadata = {
@@ -22,11 +28,11 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
- <html lang="en" suppressHydrationWarning>
+ <html lang="en" suppressHydrationWarning className={`${fontSans.variable} ${fontSerif.variable}`}>
<head>
<ThemeScript />
</head>
- <body className={`${font.className} bg-[var(--background)] text-[var(--foreground)]`}>
+ <body className="font-sans bg-[var(--background)] text-[var(--foreground)]">
<AppShellProvider>
<I18nClientBridge>
{children}
diff --git a/web/components/Mermaid.tsx b/web/components/Mermaid.tsx
index e79491ccf..b3466d645 100644
--- a/web/components/Mermaid.tsx
+++ b/web/components/Mermaid.tsx
@@ -40,34 +40,56 @@ async function loadMermaid() {
return mermaidLoader;
}
+function cleanupMermaidOrphans(id: string) {
+ try {
+ document.getElementById(id)?.remove();
+ document.getElementById(`d${id}`)?.remove();
+ } catch {
+ /* ignore */
+ }
+}
+
let mermaidIdCounter = 0;
+const DEBOUNCE_MS = 600;
+
export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
const [svg, setSvg] = useState<string>("");
const [error, setError] = useState<string | null>(null);
+ const [stable, setStable] = useState(false);
const [id] = useState(() => `mermaid-${++mermaidIdCounter}`);
+ const lastChartRef = useRef(chart);
useEffect(() => {
- let cancelled = false;
+ lastChartRef.current = chart;
+ setStable(false);
+
+ const timer = window.setTimeout(() => {
+ if (lastChartRef.current === chart) setStable(true);
+ }, DEBOUNCE_MS);
+
+ return () => window.clearTimeout(timer);
+ }, [chart]);
+
+ useEffect(() => {
+ if (!stable) return;
+ let cancelled = false;
const renderChart = async () => {
- if (!chart || !containerRef.current) return;
+ if (!chart.trim() || !containerRef.current) return;
try {
const mermaid = await loadMermaid();
- // Clean up the chart code
- const cleanedChart = chart.trim();
-
- // Validate and render
- const { svg: renderedSvg } = await mermaid.render(id, cleanedChart);
+ cleanupMermaidOrphans(id);
+ const { svg: renderedSvg } = await mermaid.render(id, chart.trim());
if (!cancelled) {
setSvg(renderedSvg);
setError(null);
}
} catch (err) {
- console.error("Mermaid rendering error:", err);
+ cleanupMermaidOrphans(id);
if (!cancelled) {
setError(err instanceof Error ? err.message : "Failed to render diagram");
}
@@ -75,11 +97,10 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
};
void renderChart();
-
return () => {
cancelled = true;
};
- }, [chart, id]);
+ }, [stable, chart, id]);
if (error) {
return (
@@ -102,6 +123,14 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
);
}
+ if (!stable && !svg) {
+ return (
+ <div className={`my-4 rounded-xl border border-[var(--border)] bg-[var(--muted)]/50 px-4 py-3 text-sm text-[var(--muted-foreground)] ${className}`}>
+ Rendering diagram...
+ </div>
+ );
+ }
+
return (
<div
ref={containerRef}
diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsx
index 746bb6382..6090f529a 100644
--- a/web/components/SessionList.tsx
+++ b/web/components/SessionList.tsx
@@ -16,11 +16,29 @@ interface SessionListProps {
sessions: SessionSummary[];
activeSessionId: string | null;
loading?: boolean;
+ compact?: boolean;
onSelect: (sessionId: string) => void | Promise<void>;
onRename: (sessionId: string, title: string) => void | Promise<void>;
onDelete: (sessionId: string) => void | Promise<void>;
}
+function statusColor(status?: SessionRuntimeStatus): string {
+ switch (status) {
+ case "running":
+ return "bg-blue-500";
+ case "completed":
+ return "bg-emerald-400";
+ case "failed":
+ return "bg-rose-500";
+ case "rejected":
+ return "bg-fuchsia-500";
+ case "cancelled":
+ return "bg-amber-500";
+ default:
+ return "bg-[var(--muted-foreground)]/25";
+ }
+}
+
function StatusIndicator({ status }: { status?: SessionRuntimeStatus }) {
if (!status || status === "idle") return null;
@@ -86,6 +104,7 @@ export default function SessionList({
sessions,
activeSessionId,
loading = false,
+ compact = false,
onSelect,
onRename,
onDelete,
@@ -123,6 +142,15 @@ export default function SessionList({
};
if (loading) {
+ if (compact) {
+ return (
+ <div className="ml-5 space-y-1.5 border-l border-[var(--border)]/30 py-1 pl-3">
+ {[1, 2, 3].map((i) => (
+ <div key={i} className="h-4 w-3/4 animate-pulse rounded bg-[var(--muted)]/40" />
+ ))}
+ </div>
+ );
+ }
return (
<div className="space-y-2 px-1.5 py-2">
{[1, 2, 3].map((i) => (
@@ -133,6 +161,7 @@ export default function SessionList({
}
if (sessions.length === 0) {
+ if (compact) return null;
return (
<div className="px-3 py-4 text-center text-[11px] text-[var(--muted-foreground)]/70">
No conversations yet
@@ -140,11 +169,104 @@ export default function SessionList({
);
}
+ /* ---- Compact tree-line style (under Chat nav item) ---- */
+ if (compact) {
+ return (
+ <div className="ml-5 border-l border-[var(--border)]/30 py-1">
+ {grouped.map(([label, items], groupIdx) => (
+ <div key={label}>
+ {groupIdx > 0 && (
+ <div className="my-1 ml-3 mr-2 border-t border-[var(--border)]/20" />
+ )}
+ <div className="px-3 py-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]/40">
+ {label}
+ </div>
+ {items.map((session) => {
+ const active = activeSessionId === session.session_id;
+ const isEditing = editingId === session.session_id;
+ return (
+ <div
+ key={session.session_id}
+ onClick={() => void onSelect(session.session_id)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ void onSelect(session.session_id);
+ }
+ }}
+ role="button"
+ tabIndex={0}
+ className={`group flex items-center gap-2 rounded-r-lg py-1 pl-3 pr-2 transition-colors ${
+ active
+ ? "bg-[var(--background)]/50 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <span className={`block h-1.5 w-1.5 shrink-0 rounded-full ${
+ active ? "bg-[var(--foreground)]/60" : statusColor(session.status)
+ }`} />
+ {isEditing ? (
+ <input
+ value={draftTitle}
+ autoFocus
+ onChange={(event) => setDraftTitle(event.target.value)}
+ onBlur={() => void commitEdit()}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") void commitEdit();
+ if (event.key === "Escape") {
+ setEditingId(null);
+ setDraftTitle("");
+ }
+ }}
+ onClick={(event) => event.stopPropagation()}
+ className="min-w-0 flex-1 rounded border border-[var(--border)] bg-[var(--background)] px-1.5 py-px text-[12px] text-[var(--foreground)] outline-none focus:ring-1 focus:ring-[var(--primary)]/40"
+ />
+ ) : (
+ <span className={`min-w-0 flex-1 truncate text-[13px] ${active ? "font-medium" : ""}`}>
+ {session.title || "Untitled chat"}
+ </span>
+ )}
+ <div className="flex shrink-0 items-center gap-px opacity-0 transition-opacity group-hover:opacity-100">
+ {isEditing ? (
+ <button
+ onClick={(event) => { event.stopPropagation(); void commitEdit(); }}
+ className="rounded p-0.5 text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ aria-label="Save title"
+ >
+ <Check size={10} />
+ </button>
+ ) : (
+ <button
+ onClick={(event) => { event.stopPropagation(); startEdit(session); }}
+ className="rounded p-0.5 text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ aria-label="Rename chat"
+ >
+ <Pencil size={10} />
+ </button>
+ )}
+ <button
+ onClick={(event) => { event.stopPropagation(); void onDelete(session.session_id); }}
+ className="rounded p-0.5 text-[var(--muted-foreground)] hover:text-[var(--destructive)]"
+ aria-label="Delete chat"
+ >
+ <Trash2 size={10} />
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ /* ---- Classic style ---- */
return (
<div className="space-y-3">
{grouped.map(([label, items]) => (
<div key={label}>
- <div className="mb-1 px-2 text-[10px] font-medium uppercase tracking-widest text-[var(--muted-foreground)]/50">
+ <div className="mb-1 px-2 text-[11px] font-semibold uppercase tracking-widest text-[var(--muted-foreground)]">
{label}
</div>
<div className="space-y-px">
@@ -163,10 +285,10 @@ export default function SessionList({
}}
role="button"
tabIndex={0}
- className={`group relative w-full rounded-lg px-2.5 py-[7px] text-left transition-all duration-150 ${
+ className={`group relative w-full rounded-lg px-2.5 py-2 text-left transition-all duration-150 ${
active
- ? "bg-[var(--muted)] text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50 hover:text-[var(--foreground)]"
+ ? "bg-[var(--background)]/70 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
}`}
>
{active && (
@@ -188,13 +310,13 @@ export default function SessionList({
}
}}
onClick={(event) => event.stopPropagation()}
- className="w-full rounded border border-[var(--border)] bg-[var(--background)] px-2 py-0.5 text-[11.5px] text-[var(--foreground)] outline-none focus:ring-1 focus:ring-[var(--primary)]/40"
+ className="w-full rounded border border-[var(--border)] bg-[var(--background)] px-2 py-0.5 text-[12px] text-[var(--foreground)] outline-none focus:ring-1 focus:ring-[var(--primary)]/40"
/>
) : (
<div className="flex items-center">
<span
- className={`line-clamp-1 min-w-0 flex-1 text-[11.5px] leading-snug ${
- active ? "font-semibold" : "font-normal"
+ className={`line-clamp-1 min-w-0 flex-1 text-[12px] leading-snug ${
+ active ? "font-medium" : "font-normal"
}`}
>
{session.title || "Untitled chat"}
@@ -203,7 +325,7 @@ export default function SessionList({
</div>
)}
{!isEditing && (
- <div className="mt-0.5 line-clamp-1 text-[10px] leading-tight text-[var(--muted-foreground)]/60">
+ <div className="mt-0.5 line-clamp-1 text-[11px] leading-tight text-[var(--muted-foreground)]">
{session.last_message || relativeTime(session.updated_at)}
</div>
)}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index 789901538..4e0163a2c 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -254,7 +254,7 @@ export default function ChatComposer({
/>
<div
- className={`relative rounded-2xl border bg-[var(--card)] shadow-[0_2px_12px_rgba(0,0,0,0.04)] transition-colors ${
+ className={`relative rounded-2xl border bg-[var(--card)] shadow-[0_1px_8px_rgba(0,0,0,0.03)] transition-colors ${
dragging
? "border-[var(--primary)] bg-[var(--primary)]/[0.03]"
: "border-[var(--border)]"
@@ -332,15 +332,15 @@ export default function ChatComposer({
</div>
)}
- <div className="border-t border-[var(--border)]/45 px-3 py-2">
+ <div className="border-t border-[var(--border)]/35 px-3 py-2">
<div className="flex items-center gap-2">
- <button
+ <button
ref={capBtnRef}
onClick={() => onSetCapMenuOpen((v) => !v)}
className={`inline-flex shrink-0 items-center gap-1.5 py-1.5 px-1 text-[12px] transition-colors ${
capMenuOpen
? "text-[var(--foreground)]"
- : "text-[var(--muted-foreground)]/78 hover:text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
}`}
>
<CapIcon size={14} strokeWidth={1.6} />
@@ -348,7 +348,7 @@ export default function ChatComposer({
<ChevronDown size={11} className={`transition-transform ${capMenuOpen ? "rotate-180" : ""}`} />
</button>
- <div className="h-3.5 w-px bg-[var(--border)]/40" />
+ <div className="h-3.5 w-px bg-[var(--border)]/30" />
<div className="flex min-w-0 flex-1 items-center gap-1">
{isResearchMode ? (
@@ -359,13 +359,13 @@ export default function ChatComposer({
<button
key={source.name}
onClick={() => onToggleResearchSource(source.name)}
- className={`inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium transition-colors ${
+ className={`inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-[3px] text-[10px] font-medium transition-all ${
active
- ? "text-[var(--primary)]"
- : "text-[var(--muted-foreground)]/60 hover:text-[var(--foreground)]"
+ ? "border-[var(--primary)]/25 bg-[var(--primary)]/8 text-[var(--primary)]"
+ : "border-[var(--border)]/30 text-[var(--muted-foreground)]/60 hover:border-[var(--border)]/50 hover:text-[var(--foreground)]"
}`}
>
- <Icon size={12} strokeWidth={1.7} />
+ <Icon size={11} strokeWidth={1.7} />
{source.label}
</button>
);
@@ -375,16 +375,21 @@ export default function ChatComposer({
<button
ref={toolBtnRef}
onClick={() => onSetToolMenuOpen((v) => !v)}
- className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)]/70 transition-colors hover:text-[var(--foreground)]"
+ className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
>
<Sparkles size={12} strokeWidth={1.7} />
- {t("Tools")}
+ {t("Tools")}
<ChevronDown size={10} className={`transition-transform ${toolMenuOpen ? "rotate-180" : ""}`} />
</button>
{selectedTools.size > 0 && (
- <span className="text-[10px] text-[var(--muted-foreground)]/55">
- {visibleTools.filter((t) => selectedTools.has(t.name)).map((t) => t.label).join(", ")}
- </span>
+ <div className="flex items-center gap-[3px] overflow-hidden">
+ {visibleTools.filter((vt) => selectedTools.has(vt.name)).map((vt, i) => (
+ <span key={vt.name} className="shrink-0 text-[10px] text-[var(--muted-foreground)]/35">
+ {i > 0 && <span className="text-[12px] leading-none">·</span>}
+ {vt.label}
+ </span>
+ ))}
+ </div>
)}
{toolMenuOpen && (
<div
@@ -422,11 +427,12 @@ export default function ChatComposer({
onChange={(e) => onSetKB(e.target.value)}
disabled={!ragActive}
title={ragActive ? "Select knowledge base" : "Enable Knowledge Base source first"}
- className={`h-[30px] rounded-lg border border-transparent bg-transparent py-0.5 pl-2 pr-6 text-[11px] outline-none transition-colors ${
+ className={`h-[28px] appearance-none rounded-full border bg-transparent py-0 pl-2.5 pr-5 text-[11px] outline-none transition-colors ${
ragActive
- ? "cursor-pointer text-[var(--muted-foreground)]/70 hover:text-[var(--foreground)]"
- : "cursor-not-allowed text-[var(--border)]"
+ ? "cursor-pointer border-[var(--border)]/40 text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ : "cursor-not-allowed border-transparent text-[var(--border)]"
}`}
+ style={{ backgroundImage: ragActive ? "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E\")" : "none", backgroundRepeat: "no-repeat", backgroundPosition: "right 6px center" }}
>
<option value="">{ragActive ? "No KB" : "—"}</option>
{knowledgeBases.map((kb) => (
@@ -444,7 +450,7 @@ export default function ChatComposer({
isStreaming ||
(isResearchMode && Object.keys(researchValidationErrors).length > 0)
}
- className="rounded-full bg-[var(--primary)] p-[7px] text-white shadow-[0_6px_16px_rgba(139,92,246,0.15)] transition-[transform,opacity,box-shadow] hover:shadow-[0_8px_20px_rgba(139,92,246,0.2)] disabled:opacity-25 disabled:shadow-none"
+ className="rounded-full bg-[var(--primary)] p-[7px] text-white shadow-[0_4px_12px_rgba(195,90,44,0.15)] transition-[transform,opacity,box-shadow] hover:shadow-[0_6px_16px_rgba(195,90,44,0.22)] disabled:opacity-25 disabled:shadow-none"
aria-label={t("Send")}
>
{isStreaming ? (
@@ -458,7 +464,7 @@ export default function ChatComposer({
</div>
{(isQuizMode || isMathAnimatorMode || isResearchMode) && (
- <div className="border-t border-[var(--border)]/30">
+ <div className="border-t border-[var(--border)]/15">
{isQuizMode ? (
<QuizConfigPanel
value={quizConfig}
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 6698e1b6b..8cbb3b302 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -5,6 +5,7 @@ import { memo, useMemo } from "react";
import Image from "next/image";
import {
BookOpen,
+ Coins,
Copy,
MessageSquare,
RotateCcw,
@@ -21,13 +22,17 @@ import { extractMathAnimatorResult } from "@/lib/math-animator-types";
import { extractQuizQuestions } from "@/lib/quiz-types";
import type { StreamEvent } from "@/lib/unified-ws";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
-import { CallTracePanel, ResearchStagePanel } from "./TracePanels";
+import { CallTracePanel } from "./TracePanels";
const MathAnimatorViewer = dynamic(
() => import("@/components/math-animator/MathAnimatorViewer"),
{ ssr: false },
);
const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), { ssr: false });
+const ResearchOutlineEditor = dynamic(
+ () => import("@/components/research/ResearchOutlineEditor"),
+ { ssr: false },
+);
interface ChatMessageItem {
role: "user" | "assistant" | "system";
@@ -60,41 +65,64 @@ function getModeBadgeLabel(capability?: string | null) {
const AssistantMessage = memo(function AssistantMessage({
msg,
isStreaming,
+ outlineStatus,
sessionId,
language,
+ onConfirmOutline,
}: {
msg: { content: string; capability?: string; events?: StreamEvent[] };
isStreaming?: boolean;
+ outlineStatus?: "editing" | "researching" | "done";
sessionId?: string | null;
language?: string;
+ onConfirmOutline?: (outline: Array<{ title: string; overview: string }>, topic: string, researchConfig?: Record<string, unknown> | null) => void;
}) {
const events = useMemo(() => msg.events ?? [], [msg.events]);
const hasCallTrace = useMemo(
() => events.some((event) => Boolean(event.metadata?.call_id)),
[events],
);
- const hasResearchTrace = msg.capability === "deep_research" && events.length > 0;
+ const resultEvent = useMemo(
+ () => msg.events?.find((event) => event.type === "result") ?? null,
+ [msg.events],
+ );
+
+ const outlinePreview = useMemo(() => {
+ if (msg.capability !== "deep_research" || !resultEvent) return null;
+ const meta = resultEvent.metadata as Record<string, unknown> | undefined;
+ if (!meta?.outline_preview) return null;
+ return {
+ sub_topics: (meta.sub_topics ?? []) as Array<{ title: string; overview: string }>,
+ topic: String(meta.topic ?? ""),
+ research_config: (meta.research_config ?? null) as Record<string, unknown> | null,
+ };
+ }, [msg.capability, resultEvent]);
const quizQuestions = useMemo(() => {
- const resultEv = msg.events?.find((e) => e.type === "result");
- if (!resultEv) return null;
- return extractQuizQuestions(resultEv.metadata);
- }, [msg.events]);
+ if (msg.capability !== "deep_question" || !resultEvent) return null;
+ return extractQuizQuestions(resultEvent.metadata);
+ }, [msg.capability, resultEvent]);
+
const mathAnimatorResult = useMemo(() => {
- const resultEv = msg.events?.find((e) => e.type === "result");
- if (!resultEv) return null;
- return extractMathAnimatorResult(resultEv.metadata);
- }, [msg.events]);
+ if (msg.capability !== "math_animator" || !resultEvent) return null;
+ return extractMathAnimatorResult(resultEvent.metadata);
+ }, [msg.capability, resultEvent]);
return (
<>
- {hasResearchTrace ? (
- <ResearchStagePanel events={events} isStreaming={isStreaming} />
- ) : hasCallTrace ? (
+ {hasCallTrace ? (
<CallTracePanel events={events} isStreaming={isStreaming} />
) : null}
- {mathAnimatorResult ? <MathAnimatorViewer result={mathAnimatorResult} /> : null}
- {quizQuestions && quizQuestions.length > 0 ? (
+ {outlinePreview && outlinePreview.sub_topics.length > 0 ? (
+ <ResearchOutlineEditor
+ outline={outlinePreview.sub_topics}
+ topic={outlinePreview.topic}
+ onConfirm={(items) => onConfirmOutline?.(items, outlinePreview.topic, outlinePreview.research_config)}
+ status={outlineStatus}
+ />
+ ) : mathAnimatorResult ? (
+ <MathAnimatorViewer result={mathAnimatorResult} />
+ ) : quizQuestions && quizQuestions.length > 0 ? (
<QuizViewer questions={quizQuestions} sessionId={sessionId} language={language} />
) : (
<AssistantResponse content={msg.content} />
@@ -105,6 +133,27 @@ const AssistantMessage = memo(function AssistantMessage({
AssistantMessage.displayName = "AssistantMessage";
+function CostFooter({ cost, tokens, calls }: { cost: number; tokens: number; calls: number }) {
+ const formatCost = (usd: number) => {
+ if (usd < 0.01) return `$${usd.toFixed(4)}`;
+ return `$${usd.toFixed(2)}`;
+ };
+ const formatTokens = (n: number) => {
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
+ return String(n);
+ };
+ return (
+ <div className="flex items-center gap-2 text-[10px] text-[var(--muted-foreground)]/40">
+ <Coins size={10} strokeWidth={1.5} className="shrink-0" />
+ <span>{formatCost(cost)}</span>
+ <span className="opacity-40">·</span>
+ <span>{formatTokens(tokens)} tokens</span>
+ <span className="opacity-40">·</span>
+ <span>{calls} calls</span>
+ </div>
+ );
+}
+
function RoughActionButton({
icon: Icon,
label,
@@ -121,7 +170,7 @@ function RoughActionButton({
type="button"
onClick={onClick}
disabled={disabled}
- className="inline-flex items-center gap-1 px-0.5 py-0.5 text-[11px] text-[var(--muted-foreground)]/45 transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-35"
+ className="inline-flex items-center gap-1 px-0.5 py-0.5 text-[11px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-35"
>
<Icon size={11} strokeWidth={1.5} />
<span>{label}</span>
@@ -194,6 +243,7 @@ export function ChatMessageList({
onAnswerNow,
onCopyAssistantMessage,
onRetryMessage,
+ onConfirmOutline,
}: {
messages: ChatMessageItem[];
isStreaming: boolean;
@@ -208,8 +258,35 @@ export function ChatMessageList({
) => void;
onCopyAssistantMessage: (content: string) => void | Promise<void>;
onRetryMessage: (snapshot?: MessageRequestSnapshot) => void;
+ onConfirmOutline?: (outline: Array<{ title: string; overview: string }>, topic: string, researchConfig?: Record<string, unknown> | null) => void;
}) {
const { t } = useTranslation();
+ const outlineStatusByIndex = useMemo(() => {
+ const map = new Map<number, "editing" | "researching" | "done">();
+ for (let i = 0; i < messages.length; i++) {
+ const msg = messages[i];
+ if (msg.role !== "assistant" || msg.capability !== "deep_research") continue;
+ const resultEv = msg.events?.find((e) => e.type === "result");
+ const meta = resultEv?.metadata as Record<string, unknown> | undefined;
+ if (!meta?.outline_preview) continue;
+ const hasFollowup = messages.slice(i + 1).some(
+ (m) => m.role === "assistant" && m.capability === "deep_research",
+ );
+ if (hasFollowup) {
+ const followup = messages.slice(i + 1).find(
+ (m) => m.role === "assistant" && m.capability === "deep_research",
+ );
+ const followupResult = followup?.events?.find((e) => e.type === "result");
+ map.set(i, followupResult ? "done" : "researching");
+ } else if (isStreaming) {
+ map.set(i, "researching");
+ } else {
+ map.set(i, "editing");
+ }
+ }
+ return map;
+ }, [messages, isStreaming]);
+
const messageRows = useMemo(() => {
return messages.map((msg, index) => {
if (msg.role === "user") {
@@ -234,7 +311,7 @@ export function ChatMessageList({
<div key={`${msg.role}-${i}`} className="flex justify-end">
<div className="max-w-[75%] space-y-1.5">
<div className="flex justify-end pr-1">
- <span className="text-[10px] tracking-wide text-[var(--muted-foreground)]/40">
+ <span className="text-[10px] tracking-wide text-[var(--muted-foreground)]">
{getModeBadgeLabel(msg.capability)}
</span>
</div>
@@ -256,7 +333,7 @@ export function ChatMessageList({
))}
</div>
)}
- <div className="rounded-2xl rounded-br-lg bg-[var(--primary)] px-4 py-2.5 text-[14px] leading-relaxed text-white shadow-sm">
+ <div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
{(() => {
const snap = msg.requestSnapshot;
const hasNotebook = Boolean(snap?.notebookReferences?.length);
@@ -267,7 +344,7 @@ export function ChatMessageList({
{snap?.notebookReferences?.map((ref) => (
<span
key={ref.notebook_id}
- className="inline-flex items-center gap-1.5 rounded-md border border-white/18 bg-white/12 px-2 py-1 text-[11px] font-medium text-white"
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
>
<BookOpen size={11} strokeWidth={1.8} />
{t("Notebook")} · {ref.record_ids.length} {t("records")}
@@ -276,7 +353,7 @@ export function ChatMessageList({
{snap?.historyReferences?.map((sid) => (
<span
key={sid}
- className="inline-flex items-center gap-1.5 rounded-md border border-white/18 bg-white/12 px-2 py-1 text-[11px] font-medium text-white"
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"
>
<MessageSquare size={11} strokeWidth={1.8} />
{t("Chat History")}
@@ -316,33 +393,59 @@ export function ChatMessageList({
);
}
- const showAssistantActions =
- !isStreaming &&
+ const msgDone = !isStreaming || i !== messages.length - 1;
+ const showActions =
+ msgDone && hasVisibleMarkdownContent(msg.content);
+ const showRetry =
+ showActions &&
(!pairedUserMessage?.capability || pairedUserMessage?.capability === "chat") &&
- Boolean(pairedUserMessage?.requestSnapshot) &&
- hasVisibleMarkdownContent(msg.content);
+ Boolean(pairedUserMessage?.requestSnapshot);
+
+ const costSummary = (() => {
+ if (!msgDone) return null;
+ const resultEv = msg.events?.find((e) => e.type === "result");
+ if (!resultEv) return null;
+ const meta = resultEv.metadata?.metadata as Record<string, unknown> | undefined;
+ const cs = meta?.cost_summary as { total_cost_usd?: number; total_tokens?: number; total_calls?: number } | undefined;
+ if (!cs || !cs.total_calls) return null;
+ return cs;
+ })();
+
return (
<div key={`${msg.role}-${i}`} className="w-full">
<AssistantMessage
msg={msg}
isStreaming={isStreaming && i === messages.length - 1}
+ outlineStatus={outlineStatusByIndex.get(i)}
sessionId={sessionId}
language={language}
+ onConfirmOutline={onConfirmOutline}
/>
- {showAssistantActions ? (
- <div className="mt-3 flex gap-2">
- <RoughActionButton
- icon={Copy}
- label="Copy"
- onClick={() => void onCopyAssistantMessage(msg.content)}
- />
- <RoughActionButton
- icon={RotateCcw}
- label="Retry"
- onClick={() => onRetryMessage(pairedUserMessage?.requestSnapshot)}
- />
+ {(showActions || costSummary) && (
+ <div className="mt-2 flex items-center">
+ {showActions && (
+ <div className="flex gap-2">
+ <RoughActionButton
+ icon={Copy}
+ label="Copy"
+ onClick={() => void onCopyAssistantMessage(msg.content)}
+ />
+ {showRetry && (
+ <RoughActionButton
+ icon={RotateCcw}
+ label="Retry"
+ onClick={() => onRetryMessage(pairedUserMessage?.requestSnapshot)}
+ />
+ )}
+ </div>
+ )}
+ {costSummary && (
+ <div className="ml-auto">
+ <CostFooter cost={costSummary.total_cost_usd ?? 0} tokens={costSummary.total_tokens ?? 0} calls={costSummary.total_calls ?? 0} />
+ </div>
+ )}
</div>
- ) : null}
+ )}
</div>
);
})}
diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsx
index e7284be4f..f96d8dc11 100644
--- a/web/components/chat/home/TracePanels.tsx
+++ b/web/components/chat/home/TracePanels.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
BrainCircuit,
ChevronDown,
@@ -49,6 +49,15 @@ const RESEARCH_STAGE_SPECS: Array<Pick<ResearchStageCard, "id" | "title" | "hint
{ id: "result", title: "形成结果", hint: "把证据整理成最终输出。" },
];
+type TraceItem = { callId: string; events: StreamEvent[] };
+type DisplayItem =
+ | { kind: "trace"; trace: TraceItem }
+ | { kind: "step"; stepId: string; traces: TraceItem[] };
+
+/* ------------------------------------------------------------------ */
+/* Helpers */
+/* ------------------------------------------------------------------ */
+
function titleCase(value: string) {
return value.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
@@ -132,7 +141,7 @@ function isTracePending(events: StreamEvent[]) {
return hasRunning && !hasTerminal;
}
-function getTraceHeader(events: StreamEvent[], nowSeconds?: number) {
+function getTraceHeader(events: StreamEvent[], nowSeconds?: number, nested?: boolean) {
const label = getTraceLabel(events);
const role = getTraceRole(events);
const group = getTraceGroup(events);
@@ -160,9 +169,13 @@ function getTraceHeader(events: StreamEvent[], nowSeconds?: number) {
} else if (kind === "tool_planning") {
title = "Tool call";
} else if (group === "react_round") {
- const step = meta.step_id ? `Step ${meta.step_id}` : "";
- const round = meta.round ? `Round ${meta.round}` : label;
- title = [step, round].filter(Boolean).join(" · ");
+ if (nested) {
+ title = meta.round ? `Round ${meta.round}` : label;
+ } else {
+ const step = meta.step_id ? `Step ${meta.step_id}` : "";
+ const round = meta.round ? `Round ${meta.round}` : label;
+ title = [step, round].filter(Boolean).join(" · ");
+ }
} else if (role === "plan" && kind === "llm_planning") {
title = "Plan";
} else if (role === "observe" || kind === "llm_observation") {
@@ -202,8 +215,106 @@ function formatTraceArgs(args: unknown) {
}
}
-function ScrollableTraceBody({ children }: { children: React.ReactNode }) {
- return <div className="ml-5 mr-3 mt-1 px-3 py-1.5">{children}</div>;
+/* ------------------------------------------------------------------ */
+/* Display-item grouping (step-level) */
+/* ------------------------------------------------------------------ */
+
+function buildDisplayItems(traceGroups: TraceItem[]): DisplayItem[] {
+ const items: DisplayItem[] = [];
+ let stepId_: string | null = null;
+ let stepTraces: TraceItem[] = [];
+
+ function flushStep() {
+ if (stepId_ !== null && stepTraces.length > 0) {
+ items.push({ kind: "step", stepId: stepId_, traces: stepTraces });
+ }
+ stepId_ = null;
+ stepTraces = [];
+ }
+
+ for (const group of traceGroups) {
+ const meta = getTraceMeta(group.events[0]);
+ const groupType = getTraceGroup(group.events);
+ const stepId = meta.step_id ? String(meta.step_id) : "";
+ const kind = getTraceCallKind(group.events);
+
+ if (kind === "llm_final_response") continue;
+
+ if (groupType === "react_round" && stepId) {
+ if (stepId_ === stepId) {
+ stepTraces.push(group);
+ } else {
+ flushStep();
+ stepId_ = stepId;
+ stepTraces = [group];
+ }
+ } else if (stepId_ !== null && kind !== "llm_generation") {
+ stepTraces.push(group);
+ } else {
+ flushStep();
+ items.push({ kind: "trace", trace: group });
+ }
+ }
+ flushStep();
+ return items;
+}
+
+function getStepGroupDuration(traces: TraceItem[]): string {
+ let start: number | null = null;
+ let end: number | null = null;
+ for (const trace of traces) {
+ for (const event of trace.events) {
+ const state = String(getTraceMeta(event).call_state || "");
+ if (state === "running" && (start === null || event.timestamp < start))
+ start = event.timestamp;
+ if (
+ (state === "complete" || state === "error") &&
+ (end === null || event.timestamp > end)
+ )
+ end = event.timestamp;
+ }
+ }
+ if (start === null || end === null) return "";
+ return `${Math.max(1, Math.round(end - start))}s`;
+}
+
+/* ------------------------------------------------------------------ */
+/* Primitive UI pieces */
+/* ------------------------------------------------------------------ */
+
+function ScrollableTraceBody({
+ children,
+ autoScroll,
+ className = "ml-5 mr-3 mt-0.5 max-h-[180px] overflow-y-auto px-3 py-1",
+}: {
+ children: React.ReactNode;
+ autoScroll?: boolean;
+ className?: string;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const stickRef = useRef(true);
+
+ useEffect(() => {
+ if (!autoScroll || !stickRef.current) return;
+ const el = ref.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ });
+
+ useEffect(() => {
+ if (autoScroll) stickRef.current = true;
+ }, [autoScroll]);
+
+ const handleScroll = useCallback(() => {
+ const el = ref.current;
+ if (!el) return;
+ stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 30;
+ }, []);
+
+ return (
+ <div ref={ref} onScroll={handleScroll} className={className}>
+ {children}
+ </div>
+ );
}
function TraceIcon({ kind, phase }: { kind: string; phase: string }) {
@@ -235,8 +346,8 @@ function TraceSection({
}) {
if (!children) return null;
return (
- <div className="space-y-1.5">
- <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/55">
+ <div className="space-y-0.5">
+ <div className="not-italic text-[10px] font-semibold tracking-[0.04em] text-[var(--muted-foreground)]/70">
{title}
</div>
{children}
@@ -244,6 +355,235 @@ function TraceSection({
);
}
+/* ------------------------------------------------------------------ */
+/* Per-trace rendering */
+/* ------------------------------------------------------------------ */
+
+function TraceRowBody({
+ callId,
+ callEvents,
+ group,
+ role,
+ kind,
+ t,
+}: {
+ callId: string;
+ callEvents: StreamEvent[];
+ group: string;
+ role: string;
+ kind: string;
+ t: (key: string) => string;
+}) {
+ const progressEvents = callEvents.filter((event) => {
+ if (event.type !== "progress") return false;
+ const traceKind = String(getTraceMeta(event).trace_kind || "");
+ if (traceKind === "call_status") return false;
+ return event.content.trim().length > 0;
+ });
+ const toolEvents = callEvents.filter(
+ (event) => event.type === "tool_call" || event.type === "tool_result",
+ );
+ const summaryProgressEvents = progressEvents.filter(
+ (event) => String(getTraceMeta(event).trace_layer || "summary") !== "raw",
+ );
+ const rawProgressEvents = progressEvents.filter(
+ (event) => String(getTraceMeta(event).trace_layer || "") === "raw",
+ );
+ const errorEvents = callEvents.filter(
+ (event) => event.type === "error" && event.content.trim().length > 0,
+ );
+ const thoughtText = getTraceText(callEvents, ["thinking"]);
+ const observationText = getTraceText(callEvents, ["observation"]);
+ const contentText = getTraceText(callEvents, ["content"]);
+ const genericBodyText =
+ role === "observe"
+ ? observationText
+ : role === "retrieve"
+ ? ""
+ : thoughtText || contentText;
+ const inlineSources = callEvents.flatMap((event) => getTraceMeta(event).sources ?? []);
+
+ return (
+ <div className="text-[11px] italic leading-[1.6] text-[var(--muted-foreground)]">
+ {group === "react_round" ? (
+ <div className="space-y-2">
+ <TraceSection title={t("Thought")}>
+ {thoughtText ? <MarkdownRenderer content={thoughtText} variant="trace" /> : null}
+ </TraceSection>
+ <TraceSection title={t("Tool")}>
+ {toolEvents.length > 0 ? (
+ <div className="space-y-0.5">
+ {toolEvents.map((event, idx) => {
+ if (event.type === "tool_call") {
+ const formattedArgs = formatTraceArgs(event.metadata?.args);
+ return (
+ <div key={`${callId}-tool-call-${idx}`}>
+ <span className="opacity-50">→ </span>
+ <span>{event.content}</span>
+ {formattedArgs && (
+ <pre className="ml-3 mt-0.5 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)] px-2 py-1 font-mono text-[10px] not-italic leading-[1.5] text-[var(--muted-foreground)]">
+ {formattedArgs}
+ </pre>
+ )}
+ </div>
+ );
+ }
+ return (
+ <div key={`${callId}-tool-result-${idx}`}>
+ <span className="opacity-50">✓ </span>
+ <span>{String(event.metadata?.tool ?? "result")}</span>
+ {event.content && (
+ <div className="ml-3 mt-0.5">
+ <MarkdownRenderer content={event.content} variant="trace" />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ ) : null}
+ </TraceSection>
+ <TraceSection title={t("Observe")}>
+ {observationText ? <MarkdownRenderer content={observationText} variant="trace" /> : null}
+ </TraceSection>
+ </div>
+ ) : (
+ <div className="space-y-1">
+ {summaryProgressEvents.length > 0 && (
+ <div className="space-y-0.5">
+ {summaryProgressEvents.map((event, idx) => (
+ <div key={`${callId}-progress-${idx}`} className="opacity-70">
+ {event.content}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {(role === "retrieve" || kind === "math_render_output") && rawProgressEvents.length > 0 && (
+ <div className="space-y-0.5">
+ <div className="not-italic text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]">
+ {t("Raw logs")}
+ </div>
+ <div className="max-h-[200px] overflow-y-auto rounded-md border border-[var(--border)] bg-[#292524] px-3 py-2 font-mono text-[10px] leading-[1.55] text-[#D6D3D1] shadow-inner">
+ {rawProgressEvents.map((event, idx) => (
+ <div key={`${callId}-raw-${idx}`} className="whitespace-pre-wrap break-words">
+ {event.content}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {toolEvents.length > 0 && (
+ <div className="space-y-0.5">
+ {toolEvents.map((event, idx) => {
+ if (event.type === "tool_call") {
+ const formattedArgs = formatTraceArgs(event.metadata?.args);
+ return (
+ <div key={`${callId}-tool-call-${idx}`}>
+ <span className="opacity-50">→ </span>
+ <span>{event.content}</span>
+ {formattedArgs && (
+ <pre className="ml-3 mt-0.5 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)] px-2 py-1 font-mono text-[10px] not-italic leading-[1.5] text-[var(--muted-foreground)]">
+ {formattedArgs}
+ </pre>
+ )}
+ </div>
+ );
+ }
+ return (
+ <div key={`${callId}-tool-result-${idx}`}>
+ <span className="opacity-50">✓ </span>
+ <span>{String(event.metadata?.tool ?? "result")}</span>
+ {event.content && (
+ <div className="ml-3 mt-0.5">
+ <MarkdownRenderer content={event.content} variant="trace" />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {genericBodyText && (
+ <div className="mt-1">
+ <MarkdownRenderer content={genericBodyText} variant="trace" />
+ </div>
+ )}
+ </div>
+ )}
+
+ {inlineSources.length > 0 && (
+ <div className="mt-1 opacity-50">
+ {t("Sources")}:{" "}
+ {inlineSources.map((source, idx) => (
+ <span key={`${callId}-source-${idx}`}>
+ {idx > 0 && " · "}
+ {String(source.title || source.query || source.type || "source")}
+ </span>
+ ))}
+ </div>
+ )}
+
+ {errorEvents.length > 0 && (
+ <div className="mt-1 space-y-0.5">
+ {errorEvents.map((event, idx) => (
+ <div key={`${callId}-error-${idx}`} className="text-red-400/80">
+ ✗ {event.content}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function hasExpandableContent(callEvents: StreamEvent[], group: string, role: string) {
+ const progressEvents = callEvents.filter((event) => {
+ if (event.type !== "progress") return false;
+ const traceKind = String(getTraceMeta(event).trace_kind || "");
+ if (traceKind === "call_status") return false;
+ return event.content.trim().length > 0;
+ });
+ const toolEvents = callEvents.filter(
+ (event) => event.type === "tool_call" || event.type === "tool_result",
+ );
+ const summaryProgressEvents = progressEvents.filter(
+ (event) => String(getTraceMeta(event).trace_layer || "summary") !== "raw",
+ );
+ const rawProgressEvents = progressEvents.filter(
+ (event) => String(getTraceMeta(event).trace_layer || "") === "raw",
+ );
+ const errorEvents = callEvents.filter(
+ (event) => event.type === "error" && event.content.trim().length > 0,
+ );
+ const thoughtText = getTraceText(callEvents, ["thinking"]);
+ const observationText = getTraceText(callEvents, ["observation"]);
+ const contentText = getTraceText(callEvents, ["content"]);
+ const genericBodyText =
+ role === "observe"
+ ? observationText
+ : role === "retrieve"
+ ? ""
+ : thoughtText || contentText;
+ const inlineSources = callEvents.flatMap((event) => getTraceMeta(event).sources ?? []);
+
+ return (
+ toolEvents.length > 0 ||
+ summaryProgressEvents.length > 0 ||
+ rawProgressEvents.length > 0 ||
+ errorEvents.length > 0 ||
+ Boolean(genericBodyText) ||
+ inlineSources.length > 0 ||
+ (group === "react_round" && (Boolean(thoughtText) || Boolean(observationText)))
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* CallTracePanel */
+/* ------------------------------------------------------------------ */
+
export function CallTracePanel({
events,
isStreaming,
@@ -261,7 +601,7 @@ export function CallTracePanel({
}, [isStreaming]);
const traceGroups = useMemo(() => {
- const groups: Array<{ callId: string; events: StreamEvent[] }> = [];
+ const groups: TraceItem[] = [];
const indexById = new Map<string, number>();
for (const event of events) {
@@ -279,238 +619,265 @@ export function CallTracePanel({
return groups;
}, [events]);
+ const displayItems = useMemo(() => buildDisplayItems(traceGroups), [traceGroups]);
+
if (!traceGroups.length) return null;
- return (
- <div className="mb-3 space-y-2">
- {traceGroups.map(({ callId, events: callEvents }, index) => {
- const first = callEvents[0];
- const meta = getTraceMeta(first);
- const phase = String(meta.phase || first.stage || "");
- const role = getTraceRole(callEvents);
- const group = getTraceGroup(callEvents);
- const kind = getTraceCallKind(callEvents);
- const header = getTraceHeader(callEvents, nowSeconds);
- const active = Boolean(isStreaming) && index === traceGroups.length - 1 && isTracePending(callEvents);
- const isFinalResponse = kind === "llm_final_response";
- const progressEvents = callEvents.filter((event) => {
- if (event.type !== "progress") return false;
- const traceKind = String(getTraceMeta(event).trace_kind || "");
- if (traceKind === "call_status") return false;
- return event.content.trim().length > 0;
- });
- const toolEvents = callEvents.filter(
- (event) => event.type === "tool_call" || event.type === "tool_result",
- );
- const summaryProgressEvents = progressEvents.filter(
- (event) => String(getTraceMeta(event).trace_layer || "summary") !== "raw",
- );
- const rawProgressEvents = progressEvents.filter(
- (event) => String(getTraceMeta(event).trace_layer || "") === "raw",
- );
- const errorEvents = callEvents.filter(
- (event) => event.type === "error" && event.content.trim().length > 0,
- );
- const thoughtText = getTraceText(callEvents, ["thinking"]);
- const observationText = getTraceText(callEvents, ["observation"]);
- const contentText = getTraceText(callEvents, ["content"]);
- const genericBodyText =
- role === "observe"
- ? observationText
- : role === "retrieve"
- ? ""
- : thoughtText || contentText;
- const inlineSources = callEvents.flatMap((event) => getTraceMeta(event).sources ?? []);
- const hasExpandableBody =
- !isFinalResponse && (
- toolEvents.length > 0 ||
- summaryProgressEvents.length > 0 ||
- rawProgressEvents.length > 0 ||
- errorEvents.length > 0 ||
- Boolean(genericBodyText) ||
- inlineSources.length > 0 ||
- (group === "react_round" && (Boolean(thoughtText) || Boolean(observationText)))
- );
+ function renderTraceRow(
+ { callId, events: callEvents }: TraceItem,
+ isGloballyLast: boolean,
+ nested: boolean,
+ ) {
+ const first = callEvents[0];
+ const meta = getTraceMeta(first);
+ const phase = String(meta.phase || first.stage || "");
+ const role = getTraceRole(callEvents);
+ const group = getTraceGroup(callEvents);
+ const kind = getTraceCallKind(callEvents);
+ const header = getTraceHeader(callEvents, nowSeconds, nested);
+ const active = Boolean(isStreaming) && isGloballyLast && isTracePending(callEvents);
+ const isFinalResponse = kind === "llm_final_response";
+
+ if (isFinalResponse) return null;
+
+ const expandable = hasExpandableContent(callEvents, group, role);
+ if (!expandable && !active) return null;
+
+ const summaryRow = (
+ <div className="flex list-none items-center gap-2 py-0.5 not-italic text-[12px] font-medium text-[var(--muted-foreground)]">
+ {expandable ? (
+ <ChevronDown
+ size={12}
+ className="shrink-0 transition-transform group-open:rotate-180"
+ />
+ ) : (
+ <span className="w-3 shrink-0" />
+ )}
+ <TraceIcon kind={kind} phase={phase} />
+ <span>{header}</span>
+ {active && <Loader2 size={11} className="animate-spin" />}
+ </div>
+ );
- const hasVisibleBody = hasExpandableBody || isFinalResponse;
-
- if (!hasVisibleBody && !active) return null;
-
- const summaryRow = (
- <div className="flex list-none items-center gap-2 py-1 text-[12px] text-[var(--muted-foreground)]/78">
- {hasExpandableBody ? (
- <ChevronDown
- size={12}
- className="shrink-0 transition-transform group-open:rotate-180"
- />
- ) : (
- <span className="w-3 shrink-0" />
- )}
- <TraceIcon kind={kind} phase={phase} />
- <span>{header}</span>
- {active && <Loader2 size={11} className="animate-spin" />}
- </div>
- );
+ if (!expandable) {
+ return <div key={callId}>{summaryRow}</div>;
+ }
- if (!hasExpandableBody) {
- return <div key={callId}>{summaryRow}</div>;
- }
+ return (
+ <details key={callId} open={active} className="group">
+ <summary className="list-none cursor-pointer hover:text-[var(--foreground)] [&::-webkit-details-marker]:hidden">
+ {summaryRow}
+ </summary>
+ {nested ? (
+ <div className="ml-5 mr-3 mt-0.5 px-3 py-1">
+ <TraceRowBody callId={callId} callEvents={callEvents} group={group} role={role} kind={kind} t={t} />
+ </div>
+ ) : (
+ <ScrollableTraceBody autoScroll={active}>
+ <TraceRowBody callId={callId} callEvents={callEvents} group={group} role={role} kind={kind} t={t} />
+ </ScrollableTraceBody>
+ )}
+ </details>
+ );
+ }
- return (
- <details
- key={callId}
- open={active}
- className="group"
- >
- <summary className="list-none cursor-pointer hover:text-[var(--foreground)] [&::-webkit-details-marker]:hidden">
- {summaryRow}
- </summary>
- <ScrollableTraceBody>
- <div className="text-[12px] leading-[1.7] text-[var(--muted-foreground)]/82">
- {group === "react_round" ? (
- <div className="space-y-3">
- <TraceSection title={t("Thought")}>
- {thoughtText ? <MarkdownRenderer content={thoughtText} variant="trace" /> : null}
- </TraceSection>
- <TraceSection title={t("Tool")}>
- {toolEvents.length > 0 ? (
- <div className="space-y-1.5">
- {toolEvents.map((event, idx) => {
- if (event.type === "tool_call") {
- const formattedArgs = formatTraceArgs(event.metadata?.args);
- return (
- <div key={`${callId}-tool-call-${idx}`}>
- <span className="opacity-50">→ </span>
- <span>{event.content}</span>
- {formattedArgs && (
- <pre className="ml-3 mt-0.5 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)]/45 px-2 py-1 font-mono text-[11px] leading-[1.55] text-[var(--muted-foreground)]/78">
- {formattedArgs}
- </pre>
- )}
+ return (
+ <div className="mb-3 space-y-0.5">
+ {displayItems.map((item, displayIdx) => {
+ const isLastDisplayItem = displayIdx === displayItems.length - 1;
+
+ if (item.kind === "step") {
+ const roundCount = item.traces.filter((tr) => getTraceGroup(tr.events) === "react_round").length;
+ const lastTrace = item.traces[item.traces.length - 1];
+ const isActiveStep =
+ Boolean(isStreaming) && isLastDisplayItem && isTracePending(lastTrace.events);
+ const stepDuration = isActiveStep ? "" : getStepGroupDuration(item.traces);
+
+ return (
+ <details key={item.stepId} open={isActiveStep || undefined} className="group/step">
+ <summary className="list-none cursor-pointer hover:text-[var(--foreground)] [&::-webkit-details-marker]:hidden">
+ <div className="flex items-center gap-2 py-0.5 not-italic text-[12px] font-medium text-[var(--muted-foreground)]">
+ <ChevronDown
+ size={12}
+ className="shrink-0 transition-transform group-open/step:rotate-180"
+ />
+ <Sparkles size={12} strokeWidth={1.6} className="shrink-0" />
+ <span>Step {item.stepId}</span>
+ <span className="text-[11px] opacity-60">
+ {roundCount} {roundCount === 1 ? "round" : "rounds"}
+ {stepDuration ? ` · ${stepDuration}` : ""}
+ </span>
+ {isActiveStep && <Loader2 size={11} className="animate-spin" />}
+ </div>
+ </summary>
+ <ScrollableTraceBody
+ autoScroll={isActiveStep}
+ className="ml-5 mr-3 mt-0.5 max-h-[280px] overflow-y-auto px-3 py-1"
+ >
+ <div className="text-[11px] italic leading-[1.6] text-[var(--muted-foreground)]">
+ {item.traces.map((trace, idx) => {
+ const trGroup = getTraceGroup(trace.events);
+ const trKind = getTraceCallKind(trace.events);
+ const trRole = getTraceRole(trace.events);
+ const trMeta = getTraceMeta(trace.events[0]);
+
+ if (trKind === "llm_final_response") return null;
+
+ if (trGroup === "react_round") {
+ const roundNum = trMeta.round;
+ const duration = getTraceDurationLabel(trace.events);
+ const thoughtText = getTraceText(trace.events, ["thinking"]);
+ const observationText = getTraceText(trace.events, ["observation"]);
+ const traceToolEvents = trace.events.filter(
+ (e) => e.type === "tool_call" || e.type === "tool_result",
+ );
+ const isLastInStep = idx === item.traces.length - 1;
+ const roundActive =
+ Boolean(isStreaming) && isLastDisplayItem && isLastInStep && isTracePending(trace.events);
+
+ return (
+ <div key={trace.callId}>
+ {idx > 0 && <div className="my-1.5 h-px bg-[var(--border)]/30" />}
+ <div className="mb-1 flex items-center gap-1.5 not-italic text-[11px]">
+ <span className="font-bold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">
+ Round {roundNum}
+ </span>
+ {duration && (
+ <span className="font-normal text-[var(--muted-foreground)]/40">{duration}</span>
+ )}
+ {roundActive && <Loader2 size={10} className="animate-spin" />}
+ </div>
+ <div className="space-y-1.5 pl-0.5">
+ <TraceSection title={t("Thought")}>
+ {thoughtText ? (
+ <MarkdownRenderer content={thoughtText} variant="trace" />
+ ) : null}
+ </TraceSection>
+ <TraceSection title={t("Tool")}>
+ {traceToolEvents.length > 0 ? (
+ <div className="space-y-0.5">
+ {traceToolEvents.map((ev, ei) => {
+ if (ev.type === "tool_call") {
+ const fa = formatTraceArgs(ev.metadata?.args);
+ return (
+ <div key={`${trace.callId}-tc-${ei}`}>
+ <span className="opacity-50">→ </span>
+ <span>{ev.content}</span>
+ {fa && (
+ <pre className="ml-3 mt-0.5 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)] px-2 py-1 font-mono text-[10px] not-italic leading-[1.5] text-[var(--muted-foreground)]">
+ {fa}
+ </pre>
+ )}
+ </div>
+ );
+ }
+ return (
+ <div key={`${trace.callId}-tr-${ei}`}>
+ <span className="opacity-50">✓ </span>
+ <span>{String(ev.metadata?.tool ?? "result")}</span>
+ {ev.content && (
+ <div className="ml-3 mt-0.5">
+ <MarkdownRenderer content={ev.content} variant="trace" />
+ </div>
+ )}
+ </div>
+ );
+ })}
</div>
- );
- }
-
- return (
- <div key={`${callId}-tool-result-${idx}`}>
- <span className="opacity-50">✓ </span>
- <span>{String(event.metadata?.tool ?? "result")}</span>
- {event.content && (
- <div className="ml-3 mt-0.5">
- <MarkdownRenderer content={event.content} variant="trace" />
- </div>
- )}
- </div>
- );
- })}
- </div>
- ) : null}
- </TraceSection>
- <TraceSection title={t("Observe")}>
- {observationText ? <MarkdownRenderer content={observationText} variant="trace" /> : null}
- </TraceSection>
- </div>
- ) : (
- <div className="space-y-2">
- {summaryProgressEvents.length > 0 && (
- <div className="space-y-1.5">
- {summaryProgressEvents.map((event, idx) => (
- <div key={`${callId}-progress-${idx}`} className="opacity-65">
- {event.content}
+ ) : null}
+ </TraceSection>
+ <TraceSection title={t("Observe")}>
+ {observationText ? (
+ <MarkdownRenderer content={observationText} variant="trace" />
+ ) : null}
+ </TraceSection>
</div>
- ))}
- </div>
- )}
-
- {(role === "retrieve" || kind === "math_render_output") && rawProgressEvents.length > 0 && (
- <div className="space-y-1.5">
- <div className="text-[11px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/55">
- {t("Raw logs")}
</div>
- <div className="max-h-[200px] overflow-y-auto rounded-md border border-white/6 bg-[#0b0d10] px-3 py-2 font-mono text-[10px] leading-[1.55] text-[#d7dce2] shadow-inner">
- {rawProgressEvents.map((event, idx) => (
- <div key={`${callId}-raw-${idx}`} className="whitespace-pre-wrap break-words">
- {event.content}
+ );
+ }
+
+ /* Non-round trace (retrieve, tool, etc.) — inline within the step */
+ const inlineHeader = getTraceHeader(trace.events, nowSeconds, true);
+ const progressEvts = trace.events.filter(
+ (e) =>
+ e.type === "progress" &&
+ String(getTraceMeta(e).trace_kind || "") !== "call_status" &&
+ e.content.trim().length > 0,
+ );
+ const rawEvts = progressEvts.filter(
+ (e) => String(getTraceMeta(e).trace_layer || "") === "raw",
+ );
+ const summaryEvts = progressEvts.filter(
+ (e) => String(getTraceMeta(e).trace_layer || "summary") !== "raw",
+ );
+ const inlineToolEvts = trace.events.filter(
+ (e) => e.type === "tool_call" || e.type === "tool_result",
+ );
+ const genericText =
+ trRole === "observe"
+ ? getTraceText(trace.events, ["observation"])
+ : trRole === "retrieve"
+ ? ""
+ : getTraceText(trace.events, ["thinking"]) || getTraceText(trace.events, ["content"]);
+
+ const hasContent =
+ summaryEvts.length > 0 ||
+ rawEvts.length > 0 ||
+ inlineToolEvts.length > 0 ||
+ Boolean(genericText);
+ if (!hasContent) return null;
+
+ return (
+ <div key={trace.callId} className="mt-1.5 pl-0.5">
+ <div className="not-italic text-[11px] font-bold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">
+ {inlineHeader}
+ </div>
+ <div className="mt-0.5 space-y-0.5">
+ {summaryEvts.map((ev, ei) => (
+ <div key={`${trace.callId}-sp-${ei}`} className="opacity-70">
+ {ev.content}
</div>
))}
- </div>
- </div>
- )}
-
- {toolEvents.length > 0 && (
- <div className="space-y-1.5">
- {toolEvents.map((event, idx) => {
- if (event.type === "tool_call") {
- const formattedArgs = formatTraceArgs(event.metadata?.args);
- return (
- <div key={`${callId}-tool-call-${idx}`}>
- <span className="opacity-50">→ </span>
- <span>{event.content}</span>
- {formattedArgs && (
- <pre className="ml-3 mt-0.5 whitespace-pre-wrap break-words rounded-md bg-[var(--muted)]/45 px-2 py-1 font-mono text-[11px] leading-[1.55] text-[var(--muted-foreground)]/78">
- {formattedArgs}
- </pre>
- )}
- </div>
- );
- }
-
- return (
- <div key={`${callId}-tool-result-${idx}`}>
- <span className="opacity-50">✓ </span>
- <span>{String(event.metadata?.tool ?? "result")}</span>
- {event.content && (
- <div className="ml-3 mt-0.5">
- <MarkdownRenderer content={event.content} variant="trace" />
+ {(trRole === "retrieve" || trKind === "math_render_output") && rawEvts.length > 0 && (
+ <div className="max-h-[160px] overflow-y-auto rounded-md border border-[var(--border)] bg-[#292524] px-3 py-2 font-mono text-[10px] not-italic leading-[1.55] text-[#D6D3D1] shadow-inner">
+ {rawEvts.map((ev, ei) => (
+ <div key={`${trace.callId}-rw-${ei}`} className="whitespace-pre-wrap break-words">
+ {ev.content}
</div>
- )}
+ ))}
</div>
- );
- })}
- </div>
- )}
-
- {!isFinalResponse && genericBodyText && (
- <div className="mt-2">
- <MarkdownRenderer
- content={genericBodyText}
- variant="trace"
- />
+ )}
+ {inlineToolEvts.map((ev, ei) => (
+ <div key={`${trace.callId}-it-${ei}`}>
+ <span className="opacity-50">{ev.type === "tool_call" ? "→ " : "✓ "}</span>
+ <span>{ev.type === "tool_call" ? ev.content : String(ev.metadata?.tool ?? "result")}</span>
+ </div>
+ ))}
+ {genericText && (
+ <div className="mt-0.5">
+ <MarkdownRenderer content={genericText} variant="trace" />
+ </div>
+ )}
+ </div>
</div>
- )}
- </div>
- )}
-
- {inlineSources.length > 0 && (
- <div className="mt-2 opacity-50">
- {t("Sources")}:{" "}
- {inlineSources.map((source, idx) => (
- <span key={`${callId}-source-${idx}`}>
- {idx > 0 && " · "}
- {String(source.title || source.query || source.type || "source")}
- </span>
- ))}
- </div>
- )}
+ );
+ })}
+ </div>
+ </ScrollableTraceBody>
+ </details>
+ );
+ }
- {errorEvents.length > 0 && (
- <div className="mt-2 space-y-1">
- {errorEvents.map((event, idx) => (
- <div key={`${callId}-error-${idx}`} className="text-red-400/80">
- ✗ {event.content}
- </div>
- ))}
- </div>
- )}
- </div>
- </ScrollableTraceBody>
- </details>
- );
+ return renderTraceRow(item.trace, isLastDisplayItem, false);
})}
</div>
);
}
+/* ------------------------------------------------------------------ */
+/* ResearchStagePanel */
+/* ------------------------------------------------------------------ */
+
function getResearchStageId(event: StreamEvent): ResearchStageCard["id"] {
const meta = getTraceMeta(event);
const explicitStage = String((event.metadata as Record<string, unknown> | undefined)?.research_stage_card || "");
@@ -571,7 +938,7 @@ export function ResearchStagePanel({
if (!cards.length) return null;
return (
- <div className="mb-3 space-y-1">
+ <div className="mb-3 space-y-0.5">
{cards.map((card, index) => {
const hasTrace = card.events.some((event) => Boolean(getTraceMeta(event).call_id));
const active =
@@ -582,8 +949,8 @@ export function ResearchStagePanel({
return (
<div key={card.id}>
- <div className="flex items-center gap-2 py-1.5 text-[12px] text-[var(--muted-foreground)]/70">
- <span className="font-medium">{card.title}</span>
+ <div className="flex items-center gap-2 py-1 text-[12px] text-[var(--muted-foreground)]">
+ <span className="font-semibold">{card.title}</span>
<span className="text-[11px] opacity-60">{summary}</span>
{active && <Loader2 size={11} className="animate-spin text-[var(--primary)]" />}
</div>
diff --git a/web/components/chat/home/composer-field.tsx b/web/components/chat/home/composer-field.tsx
new file mode 100644
index 000000000..59521ba38
--- /dev/null
+++ b/web/components/chat/home/composer-field.tsx
@@ -0,0 +1,23 @@
+import type { ReactNode } from "react";
+
+export const INPUT_CLS =
+ "h-[30px] rounded-lg border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px] text-[var(--foreground)] outline-none transition-colors hover:border-[var(--border)]/50 focus:border-[var(--primary)]/35 placeholder:text-[var(--muted-foreground)]/40";
+
+export function Field({
+ label,
+ width,
+ children,
+}: {
+ label: string;
+ width?: string;
+ children: ReactNode;
+}) {
+ return (
+ <label className={`flex min-w-0 flex-col ${width || ""}`}>
+ <span className="mb-0.5 text-[10px] font-medium text-[var(--muted-foreground)]/60">
+ {label}
+ </span>
+ {children}
+ </label>
+ );
+}
diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsx
index 3c443a939..ca77d274f 100644
--- a/web/components/common/MarkdownRenderer.tsx
+++ b/web/components/common/MarkdownRenderer.tsx
@@ -18,7 +18,12 @@ export interface MarkdownRendererProps {
}
function detectMathContent(content: string): boolean {
- return /(^|[^\\])\$\$[\s\S]+?\$\$|\\\(|\\\[/.test(content);
+ if (/(^|[^\\])\$\$[\s\S]+?\$\$/.test(content)) return true;
+ if (/\\\(|\\\[/.test(content)) return true;
+ // Single-dollar inline math containing LaTeX commands (\cmd) or math operators ({}_^)
+ if (/(?:^|[^$\\])\$(?!\$|\s)(?:[^$\n]*(?:\\[a-zA-Z]+|[{}_^]))[^$\n]*\$(?!\$)/m.test(content))
+ return true;
+ return false;
}
function detectCodeContent(content: string): boolean {
diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsx
index 6672c7acc..53a9b54c7 100644
--- a/web/components/common/RichMarkdownRenderer.tsx
+++ b/web/components/common/RichMarkdownRenderer.tsx
@@ -57,6 +57,30 @@ function hasRenderableChildren(children: React.ReactNode): boolean {
return extractText(children).replace(/[\s\u200B-\u200D\uFEFF]/g, "").length > 0;
}
+function hasRenderableDetailsBody(children: React.ReactNode): boolean {
+ return React.Children.toArray(children).some((child) => {
+ if (typeof child === "string" || typeof child === "number") {
+ return String(child).replace(/[\s\u200B-\u200D\uFEFF]/g, "").length > 0;
+ }
+
+ if (!React.isValidElement(child)) return false;
+ if (typeof child.type === "string" && child.type.toLowerCase() === "summary") {
+ return false;
+ }
+
+ return true;
+ });
+}
+
+function stripLeadingHashes(children: React.ReactNode): React.ReactNode {
+ const arr = React.Children.toArray(children);
+ if (arr.length > 0 && typeof arr[0] === "string") {
+ const cleaned = arr[0].replace(/^#{1,6}\s+/, "");
+ if (cleaned !== arr[0]) return [cleaned, ...arr.slice(1)];
+ }
+ return children;
+}
+
export default function RichMarkdownRenderer({
content,
className = "",
@@ -66,7 +90,7 @@ export default function RichMarkdownRenderer({
enableMermaid = false,
allowHtml = false,
}: MarkdownRendererProps) {
- const normalizedContent = normalizeMarkdownForDisplay(content);
+ const normalizedContent = useMemo(() => normalizeMarkdownForDisplay(content), [content]);
const [plugins, setPlugins] = useState<PluginBundle>({});
const isTrace = variant === "trace";
const gap = isTrace ? "my-1" : variant === "compact" ? "my-2" : "my-4";
@@ -120,7 +144,7 @@ export default function RichMarkdownRenderer({
h5: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,
h6: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,
strong: ({ node, children }: any) => (
- <strong className="font-semibold text-[var(--foreground)]/92">{children}</strong>
+ <strong className="font-semibold text-[var(--foreground)]">{children}</strong>
),
em: ({ node, children }: any) => <em className="italic">{children}</em>,
a: ({ node, children }: any) => (
@@ -143,7 +167,9 @@ export default function RichMarkdownRenderer({
table: ({ node, children, ...props }: any) =>
hasRenderableChildren(children) ? (
<div className="my-1 overflow-x-auto rounded border border-[var(--border)]/50">
- <table className="min-w-full text-[inherit]" {...props} />
+ <table className="min-w-full text-[inherit]" {...props}>
+ {children}
+ </table>
</div>
) : null,
thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]/50" {...props} />,
@@ -162,79 +188,103 @@ export default function RichMarkdownRenderer({
type === "checkbox" ? (
<input type="checkbox" readOnly className="mr-1 align-middle" {...props} />
) : null,
+ progress: () => null,
+ meter: () => null,
+ button: () => null,
+ select: () => null,
+ option: () => null,
+ textarea: () => null,
details: ({ node, children }: any) =>
- hasRenderableChildren(children) ? <div>{children}</div> : null,
+ hasRenderableDetailsBody(children) ? <div>{children}</div> : null,
summary: ({ node, children }: any) =>
hasRenderableChildren(children) ? <span>{children}</span> : null,
};
const headingComponents = {
- h1: ({ node, children, className: headingClassName, ...props }: any) => (
- <h1
- id={headingId(children)}
- className={`scroll-mt-20 text-3xl font-bold tracking-tight ${textColor} ${headingSpacing} ${
- headingClassName || ""
- }`}
- {...props}
- >
- {children}
- </h1>
- ),
- h2: ({ node, children, className: headingClassName, ...props }: any) => (
- <h2
- id={headingId(children)}
- className={`scroll-mt-20 text-2xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${
- headingClassName || ""
- }`}
- {...props}
- >
- {children}
- </h2>
- ),
- h3: ({ node, children, className: headingClassName, ...props }: any) => (
- <h3
- id={headingId(children)}
- className={`scroll-mt-20 text-xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${
- headingClassName || ""
- }`}
- {...props}
- >
- {children}
- </h3>
- ),
- h4: ({ node, children, className: headingClassName, ...props }: any) => (
- <h4
- id={headingId(children)}
- className={`scroll-mt-20 text-lg font-semibold ${textColor} ${
- variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"
- } ${headingClassName || ""}`}
- {...props}
- >
- {children}
- </h4>
- ),
- h5: ({ node, children, className: headingClassName, ...props }: any) => (
- <h5
- id={headingId(children)}
- className={`scroll-mt-20 text-base font-semibold ${textColor} ${
- variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
- } ${headingClassName || ""}`}
- {...props}
- >
- {children}
- </h5>
- ),
- h6: ({ node, children, className: headingClassName, ...props }: any) => (
- <h6
- id={headingId(children)}
- className={`scroll-mt-20 text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${
- variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
- } ${headingClassName || ""}`}
- {...props}
- >
- {children}
- </h6>
- ),
+ h1: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h1
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-2xl font-bold tracking-tight ${textColor} ${
+ variant === "compact" ? "mt-5 mb-2" : "mt-8 mb-4"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h1>
+ );
+ },
+ h2: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h2
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-xl font-semibold tracking-tight ${textColor} ${
+ variant === "compact" ? "mt-4 mb-2" : "mt-7 mb-3"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h2>
+ );
+ },
+ h3: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h3
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-lg font-semibold tracking-tight ${textColor} ${
+ variant === "compact" ? "mt-4 mb-1.5" : "mt-6 mb-2.5"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h3>
+ );
+ },
+ h4: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h4
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-base font-semibold ${textColor} ${
+ variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h4>
+ );
+ },
+ h5: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h5
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-sm font-semibold ${textColor} ${
+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h5>
+ );
+ },
+ h6: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h6
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${
+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h6>
+ );
+ },
};
const normalComponents: Record<string, React.ComponentType<any>> = {
@@ -242,13 +292,15 @@ export default function RichMarkdownRenderer({
table: ({ node, children, ...props }: any) =>
hasRenderableChildren(children) ? (
<div className={`overflow-x-auto rounded-lg border border-[var(--border)] shadow-sm ${gap}`}>
- <table className="min-w-full divide-y divide-[var(--border)] text-sm" {...props} />
+ <table className="min-w-full divide-y divide-[var(--border)] text-sm" {...props}>
+ {children}
+ </table>
</div>
) : null,
thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]" {...props} />,
th: ({ node, ...props }: any) => (
<th
- className={`whitespace-nowrap border-b border-[var(--border)] text-left font-semibold text-[var(--foreground)] ${cellPad}`}
+ className={`border-b border-[var(--border)] text-left font-semibold text-[var(--foreground)] ${cellPad}`}
{...props}
/>
),
@@ -281,9 +333,9 @@ export default function RichMarkdownRenderer({
if (raw.includes("\n")) {
return (
<div
- className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}
+ className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#292524]`}
>
- <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#d1d5db]">
+ <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#D6D3D1]">
<code {...props}>{raw}</code>
</pre>
</div>
@@ -299,9 +351,44 @@ export default function RichMarkdownRenderer({
</code>
);
},
- a: ({ node, href, children, ...props }: any) => {
+ a: ({ node, href, children, title, ...props }: any) => {
+ const isCitation = title === "citation";
const isHashLink = href?.startsWith("#");
const external = href?.startsWith("http://") || href?.startsWith("https://");
+
+ if (isCitation) {
+ const label = extractText(children);
+ const ids = label.split(/\s*,\s*/);
+ const scrollToRef = (event: React.MouseEvent) => {
+ event.preventDefault();
+ const target = document.getElementById("references");
+ target?.scrollIntoView({ block: "start", behavior: "smooth" });
+ };
+ return (
+ <span className="citation-group mx-0.5 text-[0.78em] leading-snug text-[var(--muted-foreground)]" {...props}>
+ [
+ {ids.map((id, idx) => {
+ const prefixMatch = id.match(/^(web|rag|code|src)-/);
+ const prefix = prefixMatch?.[1] ?? "";
+ const num = prefix ? id.slice(prefixMatch[0].length) : id;
+ return (
+ <React.Fragment key={id}>
+ {idx > 0 && ", "}
+ <a
+ href={href}
+ onClick={scrollToRef}
+ className="cursor-pointer text-[var(--primary)] no-underline transition-colors hover:text-[var(--primary)]/70 hover:underline"
+ >
+ {prefix ? <><span className="text-[0.85em] font-semibold uppercase tracking-wide">{prefix}</span>{num}</> : num}
+ </a>
+ </React.Fragment>
+ );
+ })}
+ ]
+ </span>
+ );
+ }
+
return (
<a
href={href}
@@ -332,7 +419,7 @@ export default function RichMarkdownRenderer({
),
blockquote: ({ node, ...props }: any) => (
<blockquote
- className={`${gap} border-l-[3px] border-[var(--primary)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}
+ className={`${gap} border-l-[3px] border-[var(--muted-foreground)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}
{...props}
/>
),
@@ -343,14 +430,20 @@ export default function RichMarkdownRenderer({
type === "checkbox" ? (
<input
type="checkbox"
- checked={checked}
+ checked={checked ?? false}
readOnly
className="mr-2 h-4 w-4 rounded border-[var(--border)] align-middle accent-[var(--primary)]"
{...props}
/>
) : null,
+ progress: () => null,
+ meter: () => null,
+ button: () => null,
+ select: () => null,
+ option: () => null,
+ textarea: () => null,
details: ({ node, children, ...props }: any) =>
- hasRenderableChildren(children) ? (
+ hasRenderableDetailsBody(children) ? (
<details
className={`${gap} rounded-lg border border-[var(--border)] bg-[var(--card)] px-4 py-2`}
{...props}
@@ -369,25 +462,30 @@ export default function RichMarkdownRenderer({
) : null,
};
- const components = isTrace ? traceComponents : normalComponents;
+ const components = useMemo(
+ () => (isTrace ? traceComponents : normalComponents),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- components only change with variant/feature flags
+ [isTrace, variant, enableMermaid, enableCode],
+ );
+
const rootClasses = isTrace
- ? "md-renderer max-w-none text-[12px] leading-[1.7] text-[var(--muted-foreground)]/82"
+ ? "md-renderer max-w-none font-sans text-[11px] leading-[1.55] text-[var(--muted-foreground)]"
: variant === "prose"
- ? "md-renderer prose max-w-none"
- : "md-renderer prose prose-sm max-w-none";
+ ? "md-renderer prose max-w-none font-serif"
+ : "md-renderer prose prose-sm max-w-none font-serif";
- const remarkPlugins: Array<any> = [remarkGfm];
- if (plugins.remarkMath) {
- remarkPlugins.push(plugins.remarkMath as never);
- }
+ const remarkPlugins = useMemo(() => {
+ const p: Array<any> = [remarkGfm];
+ if (plugins.remarkMath) p.push(plugins.remarkMath as never);
+ return p;
+ }, [plugins.remarkMath]);
- const rehypePlugins: Array<any> = [];
- if (allowHtml && plugins.rehypeRaw) {
- rehypePlugins.push(plugins.rehypeRaw as never);
- }
- if (enableMath && plugins.rehypeKatex) {
- rehypePlugins.push(plugins.rehypeKatex as never);
- }
+ const rehypePlugins = useMemo(() => {
+ const p: Array<any> = [];
+ if (allowHtml && plugins.rehypeRaw) p.push(plugins.rehypeRaw as never);
+ if (enableMath && plugins.rehypeKatex) p.push(plugins.rehypeKatex as never);
+ return p;
+ }, [allowHtml, enableMath, plugins.rehypeRaw, plugins.rehypeKatex]);
return (
<div className={`${rootClasses} ${className}`}>
diff --git a/web/components/common/SimpleMarkdownRenderer.tsx b/web/components/common/SimpleMarkdownRenderer.tsx
index 29ad7b8ab..f2bfb5545 100644
--- a/web/components/common/SimpleMarkdownRenderer.tsx
+++ b/web/components/common/SimpleMarkdownRenderer.tsx
@@ -1,6 +1,6 @@
"use client";
-import React from "react";
+import React, { useMemo } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
@@ -34,12 +34,36 @@ function hasRenderableChildren(children: React.ReactNode): boolean {
return extractText(children).replace(/[\s\u200B-\u200D\uFEFF]/g, "").length > 0;
}
+function hasRenderableDetailsBody(children: React.ReactNode): boolean {
+ return React.Children.toArray(children).some((child) => {
+ if (typeof child === "string" || typeof child === "number") {
+ return String(child).replace(/[\s\u200B-\u200D\uFEFF]/g, "").length > 0;
+ }
+
+ if (!React.isValidElement(child)) return false;
+ if (typeof child.type === "string" && child.type.toLowerCase() === "summary") {
+ return false;
+ }
+
+ return true;
+ });
+}
+
+function stripLeadingHashes(children: React.ReactNode): React.ReactNode {
+ const arr = React.Children.toArray(children);
+ if (arr.length > 0 && typeof arr[0] === "string") {
+ const cleaned = arr[0].replace(/^#{1,6}\s+/, "");
+ if (cleaned !== arr[0]) return [cleaned, ...arr.slice(1)];
+ }
+ return children;
+}
+
export default function SimpleMarkdownRenderer({
content,
className = "",
variant = "default",
}: MarkdownRendererProps) {
- const normalizedContent = normalizeMarkdownForDisplay(content);
+ const normalizedContent = useMemo(() => normalizeMarkdownForDisplay(content), [content]);
const isTrace = variant === "trace";
const gap = isTrace ? "my-1" : variant === "compact" ? "my-2" : "my-4";
const cellPad =
@@ -56,7 +80,7 @@ export default function SimpleMarkdownRenderer({
h5: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,
h6: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,
strong: ({ node, children }: any) => (
- <strong className="font-semibold text-[var(--foreground)]/92">{children}</strong>
+ <strong className="font-semibold text-[var(--foreground)]">{children}</strong>
),
em: ({ node, children }: any) => <em className="italic">{children}</em>,
a: ({ node, children }: any) => (
@@ -67,7 +91,7 @@ export default function SimpleMarkdownRenderer({
),
pre: ({ children }: any) => <>{children}</>,
code: ({ node, children }: any) => (
- <code className="rounded bg-[var(--muted)] px-1 py-0.5 font-mono text-[0.95em] text-[var(--foreground)]/90">
+ <code className="rounded bg-[var(--muted)] px-1 py-0.5 font-mono text-[0.95em] text-[var(--foreground)]">
{String(children).replace(/\n$/, "")}
</code>
),
@@ -79,7 +103,9 @@ export default function SimpleMarkdownRenderer({
table: ({ node, children, ...props }: any) =>
hasRenderableChildren(children) ? (
<div className="my-1 overflow-x-auto rounded border border-[var(--border)]/50">
- <table className="min-w-full text-[inherit]" {...props} />
+ <table className="min-w-full text-[inherit]" {...props}>
+ {children}
+ </table>
</div>
) : null,
thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]/50" {...props} />,
@@ -98,79 +124,103 @@ export default function SimpleMarkdownRenderer({
type === "checkbox" ? (
<input type="checkbox" readOnly className="mr-1 align-middle" {...props} />
) : null,
+ progress: () => null,
+ meter: () => null,
+ button: () => null,
+ select: () => null,
+ option: () => null,
+ textarea: () => null,
details: ({ node, children }: any) =>
- hasRenderableChildren(children) ? <div>{children}</div> : null,
+ hasRenderableDetailsBody(children) ? <div>{children}</div> : null,
summary: ({ node, children }: any) =>
hasRenderableChildren(children) ? <span>{children}</span> : null,
};
const headingComponents = {
- h1: ({ node, children, className: headingClassName, ...props }: any) => (
- <h1
- id={headingId(children)}
- className={`scroll-mt-20 text-3xl font-bold tracking-tight ${textColor} ${headingSpacing} ${
- headingClassName || ""
- }`}
- {...props}
- >
- {children}
- </h1>
- ),
- h2: ({ node, children, className: headingClassName, ...props }: any) => (
- <h2
- id={headingId(children)}
- className={`scroll-mt-20 text-2xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${
- headingClassName || ""
- }`}
- {...props}
- >
- {children}
- </h2>
- ),
- h3: ({ node, children, className: headingClassName, ...props }: any) => (
- <h3
- id={headingId(children)}
- className={`scroll-mt-20 text-xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${
- headingClassName || ""
- }`}
- {...props}
- >
- {children}
- </h3>
- ),
- h4: ({ node, children, className: headingClassName, ...props }: any) => (
- <h4
- id={headingId(children)}
- className={`scroll-mt-20 text-lg font-semibold ${textColor} ${
- variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"
- } ${headingClassName || ""}`}
- {...props}
- >
- {children}
- </h4>
- ),
- h5: ({ node, children, className: headingClassName, ...props }: any) => (
- <h5
- id={headingId(children)}
- className={`scroll-mt-20 text-base font-semibold ${textColor} ${
- variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
- } ${headingClassName || ""}`}
- {...props}
- >
- {children}
- </h5>
- ),
- h6: ({ node, children, className: headingClassName, ...props }: any) => (
- <h6
- id={headingId(children)}
- className={`scroll-mt-20 text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${
- variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
- } ${headingClassName || ""}`}
- {...props}
- >
- {children}
- </h6>
- ),
+ h1: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h1
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-2xl font-bold tracking-tight ${textColor} ${
+ variant === "compact" ? "mt-5 mb-2" : "mt-8 mb-4"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h1>
+ );
+ },
+ h2: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h2
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-xl font-semibold tracking-tight ${textColor} ${
+ variant === "compact" ? "mt-4 mb-2" : "mt-7 mb-3"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h2>
+ );
+ },
+ h3: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h3
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-lg font-semibold tracking-tight ${textColor} ${
+ variant === "compact" ? "mt-4 mb-1.5" : "mt-6 mb-2.5"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h3>
+ );
+ },
+ h4: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h4
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-base font-semibold ${textColor} ${
+ variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h4>
+ );
+ },
+ h5: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h5
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-sm font-semibold ${textColor} ${
+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h5>
+ );
+ },
+ h6: ({ node, children, className: headingClassName, ...props }: any) => {
+ const clean = stripLeadingHashes(children);
+ return (
+ <h6
+ id={headingId(clean)}
+ className={`scroll-mt-20 font-sans text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${
+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"
+ } ${headingClassName || ""}`}
+ {...props}
+ >
+ {clean}
+ </h6>
+ );
+ },
};
const normalComponents: Record<string, React.ComponentType<any>> = {
@@ -178,13 +228,15 @@ export default function SimpleMarkdownRenderer({
table: ({ node, children, ...props }: any) =>
hasRenderableChildren(children) ? (
<div className={`overflow-x-auto rounded-lg border border-[var(--border)] shadow-sm ${gap}`}>
- <table className="min-w-full divide-y divide-[var(--border)] text-sm" {...props} />
+ <table className="min-w-full divide-y divide-[var(--border)] text-sm" {...props}>
+ {children}
+ </table>
</div>
) : null,
thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]" {...props} />,
th: ({ node, ...props }: any) => (
<th
- className={`whitespace-nowrap border-b border-[var(--border)] text-left font-semibold text-[var(--foreground)] ${cellPad}`}
+ className={`border-b border-[var(--border)] text-left font-semibold text-[var(--foreground)] ${cellPad}`}
{...props}
/>
),
@@ -202,9 +254,9 @@ export default function SimpleMarkdownRenderer({
),
pre: ({ children }: any) => (
<div
- className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}
+ className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#292524]`}
>
- <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#d1d5db]">
+ <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#D6D3D1]">
{children}
</pre>
</div>
@@ -217,9 +269,44 @@ export default function SimpleMarkdownRenderer({
{children}
</code>
),
- a: ({ node, href, children, ...props }: any) => {
+ a: ({ node, href, children, title, ...props }: any) => {
+ const isCitation = title === "citation";
const isHashLink = href?.startsWith("#");
const external = href?.startsWith("http://") || href?.startsWith("https://");
+
+ if (isCitation) {
+ const label = extractText(children);
+ const ids = label.split(/\s*,\s*/);
+ const scrollToRef = (event: React.MouseEvent) => {
+ event.preventDefault();
+ const target = document.getElementById("references");
+ target?.scrollIntoView({ block: "start", behavior: "smooth" });
+ };
+ return (
+ <span className="citation-group mx-0.5 text-[0.78em] leading-snug text-[var(--muted-foreground)]" {...props}>
+ [
+ {ids.map((id, idx) => {
+ const prefixMatch = id.match(/^(web|rag|code|src)-/);
+ const prefix = prefixMatch?.[1] ?? "";
+ const num = prefix ? id.slice(prefixMatch[0].length) : id;
+ return (
+ <React.Fragment key={id}>
+ {idx > 0 && ", "}
+ <a
+ href={href}
+ onClick={scrollToRef}
+ className="cursor-pointer text-[var(--primary)] no-underline transition-colors hover:text-[var(--primary)]/70 hover:underline"
+ >
+ {prefix ? <><span className="text-[0.85em] font-semibold uppercase tracking-wide">{prefix}</span>{num}</> : num}
+ </a>
+ </React.Fragment>
+ );
+ })}
+ ]
+ </span>
+ );
+ }
+
return (
<a
href={href}
@@ -250,7 +337,7 @@ export default function SimpleMarkdownRenderer({
),
blockquote: ({ node, ...props }: any) => (
<blockquote
- className={`${gap} border-l-[3px] border-[var(--primary)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}
+ className={`${gap} border-l-[3px] border-[var(--muted-foreground)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}
{...props}
/>
),
@@ -267,8 +354,14 @@ export default function SimpleMarkdownRenderer({
{...props}
/>
) : null,
+ progress: () => null,
+ meter: () => null,
+ button: () => null,
+ select: () => null,
+ option: () => null,
+ textarea: () => null,
details: ({ node, children, ...props }: any) =>
- hasRenderableChildren(children) ? (
+ hasRenderableDetailsBody(children) ? (
<details
className={`${gap} rounded-lg border border-[var(--border)] bg-[var(--card)] px-4 py-2`}
{...props}
@@ -287,16 +380,23 @@ export default function SimpleMarkdownRenderer({
) : null,
};
- const components = isTrace ? traceComponents : normalComponents;
+ const components = useMemo(
+ () => (isTrace ? traceComponents : normalComponents),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- components only change with variant
+ [isTrace, variant],
+ );
+
+ const remarkPlugins = useMemo(() => [remarkGfm], []);
+
const rootClasses = isTrace
- ? "md-renderer max-w-none text-[12px] leading-[1.7] text-[var(--muted-foreground)]/82"
+ ? "md-renderer max-w-none font-sans text-[11px] leading-[1.55] text-[var(--muted-foreground)]"
: variant === "prose"
- ? "md-renderer prose max-w-none"
- : "md-renderer prose prose-sm max-w-none";
+ ? "md-renderer prose max-w-none font-serif"
+ : "md-renderer prose prose-sm max-w-none font-serif";
return (
<div className={`${rootClasses} ${className}`}>
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ <ReactMarkdown remarkPlugins={remarkPlugins} components={components}>
{normalizedContent}
</ReactMarkdown>
</div>
diff --git a/web/components/math-animator/MathAnimatorConfigPanel.tsx b/web/components/math-animator/MathAnimatorConfigPanel.tsx
index cfd070775..5191c38ca 100644
--- a/web/components/math-animator/MathAnimatorConfigPanel.tsx
+++ b/web/components/math-animator/MathAnimatorConfigPanel.tsx
@@ -1,15 +1,13 @@
"use client";
import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";
+import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";
interface MathAnimatorConfigPanelProps {
value: MathAnimatorFormConfig;
onChange: (next: MathAnimatorFormConfig) => void;
}
-const INPUT_CLS =
- "h-[32px] rounded-md border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px] text-[var(--foreground)] outline-none transition-colors hover:border-[var(--border)]/50 focus:border-[var(--primary)]/35 placeholder:text-[var(--muted-foreground)]/40";
-
export default function MathAnimatorConfigPanel({
value,
onChange,
@@ -57,21 +55,3 @@ export default function MathAnimatorConfigPanel({
);
}
-function Field({
- label,
- width,
- children,
-}: {
- label: string;
- width?: string;
- children: React.ReactNode;
-}) {
- return (
- <label className={`flex min-w-0 flex-col ${width || ""}`}>
- <span className="mb-1 text-[9px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/40">
- {label}
- </span>
- {children}
- </label>
- );
-}
diff --git a/web/components/quiz/QuizConfigPanel.tsx b/web/components/quiz/QuizConfigPanel.tsx
index 99b95b257..ec0ee322b 100644
--- a/web/components/quiz/QuizConfigPanel.tsx
+++ b/web/components/quiz/QuizConfigPanel.tsx
@@ -3,6 +3,7 @@
import { useRef, useState } from "react";
import { FileText, Upload, X } from "lucide-react";
import type { DeepQuestionFormConfig, DeepQuestionMode } from "@/lib/quiz-types";
+import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";
interface QuizConfigPanelProps {
value: DeepQuestionFormConfig;
@@ -11,9 +12,6 @@ interface QuizConfigPanelProps {
onUploadPdf: (file: File | null) => void;
}
-const INPUT_CLS =
- "h-[32px] rounded-md border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px] text-[var(--foreground)] outline-none transition-colors hover:border-[var(--border)]/50 focus:border-[var(--primary)]/35 placeholder:text-[var(--muted-foreground)]/40";
-
export default function QuizConfigPanel({
value,
onChange,
@@ -32,17 +30,16 @@ export default function QuizConfigPanel({
return (
<div className="px-3.5 py-2.5 space-y-2.5">
- {/* Mode tabs — baseline-aligned */}
- <div className="flex items-baseline gap-4">
+ <div className="inline-flex rounded-lg border border-[var(--border)]/25 p-0.5">
{(["custom", "mimic"] as const).map((m) => (
<button
key={m}
type="button"
onClick={() => setMode(m)}
- className={`pb-0.5 text-[11px] font-medium transition-colors border-b ${
+ className={`rounded-md px-3 py-1 text-[11px] font-medium transition-all ${
value.mode === m
- ? "border-[var(--foreground)]/30 text-[var(--foreground)]"
- : "border-transparent text-[var(--muted-foreground)]/45 hover:text-[var(--muted-foreground)]"
+ ? "bg-[var(--muted)] text-[var(--foreground)] shadow-sm"
+ : "text-[var(--muted-foreground)]/50 hover:text-[var(--muted-foreground)]"
}`}
>
{m === "custom" ? "Custom" : "Mimic Paper"}
@@ -105,7 +102,7 @@ export default function QuizConfigPanel({
<div className="flex flex-wrap items-end gap-x-3 gap-y-2">
<Field label="Paper" width="min-w-[180px] flex-[1.3]">
{uploadedPdf ? (
- <div className="flex h-[32px] items-center gap-2 rounded-md border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px]">
+ <div className="flex h-[30px] items-center gap-2 rounded-lg border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px]">
<FileText size={12} className="shrink-0 text-[var(--primary)]/60" />
<span className="min-w-0 truncate text-[var(--foreground)]">{uploadedPdf.name}</span>
<button
@@ -119,7 +116,7 @@ export default function QuizConfigPanel({
</div>
) : (
<label
- className={`flex h-[32px] cursor-pointer items-center justify-center gap-1.5 rounded-md border border-dashed px-2.5 text-[12px] transition-colors ${
+ className={`flex h-[30px] cursor-pointer items-center justify-center gap-1.5 rounded-lg border border-dashed px-2.5 text-[12px] transition-colors ${
dragOver
? "border-[var(--primary)]/35 text-[var(--primary)]"
: "border-[var(--border)]/35 text-[var(--muted-foreground)]/50 hover:border-[var(--border)]/55 hover:text-[var(--foreground)]"
@@ -190,21 +187,3 @@ export default function QuizConfigPanel({
);
}
-function Field({
- label,
- width,
- children,
-}: {
- label: string;
- width?: string;
- children: React.ReactNode;
-}) {
- return (
- <div className={width}>
- <div className="mb-1 text-[9px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/40">
- {label}
- </div>
- {children}
- </div>
- );
-}
diff --git a/web/components/research/ResearchConfigPanel.tsx b/web/components/research/ResearchConfigPanel.tsx
index e945cc0e3..004a202a1 100644
--- a/web/components/research/ResearchConfigPanel.tsx
+++ b/web/components/research/ResearchConfigPanel.tsx
@@ -1,6 +1,5 @@
"use client";
-import type { ReactNode } from "react";
import { ChevronDown } from "lucide-react";
import type {
DeepResearchFormConfig,
@@ -8,6 +7,7 @@ import type {
ResearchMode,
} from "@/lib/research-types";
import { summarizeResearchConfig } from "@/lib/research-types";
+import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";
interface ResearchConfigPanelProps {
value: DeepResearchFormConfig;
@@ -17,9 +17,6 @@ interface ResearchConfigPanelProps {
onToggleCollapsed: () => void;
}
-const INPUT_CLS =
- "h-[32px] rounded-md border border-[var(--border)]/30 bg-[var(--background)]/50 px-2.5 text-[12px] text-[var(--foreground)] outline-none transition-colors hover:border-[var(--border)]/50 focus:border-[var(--primary)]/35";
-
const MODE_OPTIONS: Array<{ value: Exclude<ResearchMode, "">; label: string }> = [
{ value: "notes", label: "Study Notes" },
{ value: "report", label: "Report" },
@@ -31,8 +28,41 @@ const DEPTH_OPTIONS: Array<{ value: Exclude<ResearchDepth, "">; label: string }>
{ value: "quick", label: "Quick" },
{ value: "standard", label: "Standard" },
{ value: "deep", label: "Deep" },
+ { value: "manual", label: "Manual" },
];
+function NumberSlider({
+ label,
+ value,
+ min,
+ max,
+ onChange,
+}: {
+ label: string;
+ value: number;
+ min: number;
+ max: number;
+ onChange: (n: number) => void;
+}) {
+ return (
+ <div className="flex items-center gap-2">
+ <span className="shrink-0 text-[10px] text-[var(--muted-foreground)]/60">{label}</span>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={1}
+ value={value}
+ onChange={(e) => onChange(Number(e.target.value))}
+ className="h-1 flex-1 cursor-pointer appearance-none rounded-full bg-[var(--muted-foreground)]/15 accent-[var(--primary)] [&::-webkit-slider-thumb]:h-3.5 [&::-webkit-slider-thumb]:w-3.5 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-[var(--primary)]"
+ />
+ <span className="w-5 text-center text-[11px] font-semibold tabular-nums text-[var(--foreground)]">
+ {value}
+ </span>
+ </div>
+ );
+}
+
export default function ResearchConfigPanel({
value,
errors: _errors,
@@ -52,69 +82,70 @@ export default function ResearchConfigPanel({
<button
type="button"
onClick={onToggleCollapsed}
- className="flex w-full items-center gap-2 px-3.5 py-2 text-left transition-colors hover:opacity-80"
+ className="flex w-full items-center gap-1.5 px-3.5 py-1.5 text-left transition-colors hover:opacity-80"
>
- <span className="text-[11px] font-medium text-[var(--muted-foreground)]/55">Settings</span>
- {collapsed && summary !== "Incomplete settings" && (
- <span className="min-w-0 truncate text-[10px] text-[var(--muted-foreground)]/35">{summary}</span>
- )}
<ChevronDown
- size={11}
- className={`ml-auto shrink-0 text-[var(--muted-foreground)]/40 transition-transform ${collapsed ? "" : "rotate-180"}`}
+ size={10}
+ className={`shrink-0 text-[var(--muted-foreground)]/40 transition-transform ${collapsed ? "-rotate-90" : ""}`}
/>
+ <span className="text-[10px] font-medium text-[var(--muted-foreground)]/55">Settings</span>
+ {collapsed && summary !== "Incomplete settings" && (
+ <span className="min-w-0 truncate text-[10px] text-[var(--muted-foreground)]/30">— {summary}</span>
+ )}
</button>
{!collapsed && (
- <div className="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5">
- <Field label="Mode" width="min-w-[130px] flex-1">
- <select
- value={value.mode}
- onChange={(e) => update("mode", e.target.value as ResearchMode)}
- className={`${INPUT_CLS} w-full`}
- >
- <option value="">Select...</option>
- {MODE_OPTIONS.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- </Field>
- <Field label="Depth" width="min-w-[130px] flex-1">
- <select
- value={value.depth}
- onChange={(e) => update("depth", e.target.value as ResearchDepth)}
- className={`${INPUT_CLS} w-full`}
- >
- <option value="">Select...</option>
- {DEPTH_OPTIONS.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- </Field>
+ <div className="space-y-2 px-3.5 pb-2.5">
+ <div className="flex flex-wrap items-end gap-x-3 gap-y-2">
+ <Field label="Mode" width="min-w-[130px] flex-1">
+ <select
+ value={value.mode}
+ onChange={(e) => update("mode", e.target.value as ResearchMode)}
+ className={`${INPUT_CLS} w-full`}
+ >
+ <option value="">Select...</option>
+ {MODE_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ </Field>
+ <Field label="Depth" width="min-w-[130px] flex-1">
+ <select
+ value={value.depth}
+ onChange={(e) => update("depth", e.target.value as ResearchDepth)}
+ className={`${INPUT_CLS} w-full`}
+ >
+ <option value="">Select...</option>
+ {DEPTH_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ </Field>
+ </div>
+ {value.depth === "manual" && (
+ <div className="space-y-1.5 rounded-md bg-[var(--muted-foreground)]/5 px-3 py-2">
+ <NumberSlider
+ label="Sub-topics"
+ value={value.manual_subtopics ?? 3}
+ min={1}
+ max={10}
+ onChange={(n) => update("manual_subtopics", n)}
+ />
+ <NumberSlider
+ label="Iterations"
+ value={value.manual_max_iterations ?? 3}
+ min={1}
+ max={8}
+ onChange={(n) => update("manual_max_iterations", n)}
+ />
+ </div>
+ )}
</div>
)}
</div>
);
}
-
-function Field({
- label,
- width,
- children,
-}: {
- label: string;
- width?: string;
- children: ReactNode;
-}) {
- return (
- <div className={width}>
- <div className="mb-1 text-[9px] font-medium uppercase tracking-[0.08em] text-[var(--muted-foreground)]/40">
- {label}
- </div>
- {children}
- </div>
- );
-}
diff --git a/web/components/research/ResearchOutlineEditor.tsx b/web/components/research/ResearchOutlineEditor.tsx
new file mode 100644
index 000000000..d1e24cbee
--- /dev/null
+++ b/web/components/research/ResearchOutlineEditor.tsx
@@ -0,0 +1,157 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { Plus, Play, Trash2, Loader2, CheckCircle2 } from "lucide-react";
+import type { OutlineItem } from "@/lib/research-types";
+
+type OutlineStatus = "editing" | "researching" | "done";
+
+interface ResearchOutlineEditorProps {
+ outline: OutlineItem[];
+ topic: string;
+ onConfirm: (outline: OutlineItem[]) => void;
+ status?: OutlineStatus;
+}
+
+export default function ResearchOutlineEditor({
+ outline: initialOutline,
+ topic,
+ onConfirm,
+ status: externalStatus,
+}: ResearchOutlineEditorProps) {
+ const [items, setItems] = useState<OutlineItem[]>(initialOutline);
+ const [localConfirmed, setLocalConfirmed] = useState(false);
+
+ const locked = externalStatus === "researching" || externalStatus === "done" || localConfirmed;
+
+ const updateItem = useCallback((index: number, field: keyof OutlineItem, value: string) => {
+ setItems((prev) => prev.map((item, i) => (i === index ? { ...item, [field]: value } : item)));
+ }, []);
+
+ const removeItem = useCallback((index: number) => {
+ setItems((prev) => prev.filter((_, i) => i !== index));
+ }, []);
+
+ const addItem = useCallback(() => {
+ setItems((prev) => [...prev, { title: "", overview: "" }]);
+ }, []);
+
+ const handleConfirm = useCallback(() => {
+ const valid = items.filter((item) => item.title.trim());
+ if (valid.length === 0) return;
+ setLocalConfirmed(true);
+ onConfirm(valid);
+ }, [items, onConfirm]);
+
+ const validItems = locked ? initialOutline.filter((i) => i.title.trim()) : items;
+
+ const statusLabel = (() => {
+ if (externalStatus === "done") return "Research Complete";
+ if (externalStatus === "researching" || localConfirmed) return "Researching…";
+ return null;
+ })();
+
+ const StatusIcon = externalStatus === "done" ? CheckCircle2 : Loader2;
+
+ return (
+ <div className="my-2 rounded-lg border border-[var(--border)]/30 bg-[var(--background)] shadow-sm">
+ <div className="border-b border-[var(--border)]/20 px-4 py-2.5">
+ <div className="flex items-center justify-between">
+ <h3 className="text-[13px] font-semibold text-[var(--foreground)]">
+ Research Outline
+ </h3>
+ {statusLabel && (
+ <span className="flex items-center gap-1.5 text-[11px] text-[var(--muted-foreground)]/60">
+ <StatusIcon
+ size={12}
+ className={externalStatus === "done" ? "" : "animate-spin"}
+ />
+ {statusLabel}
+ </span>
+ )}
+ </div>
+ {!locked && (
+ <p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]/60">
+ Review and edit the sub-topics below, then start the research. You can also type in the
+ chat to regenerate the outline.
+ </p>
+ )}
+ </div>
+
+ <div className="space-y-0 divide-y divide-[var(--border)]/15">
+ {validItems.map((item, index) => (
+ <div
+ key={index}
+ className="group flex items-start gap-2 px-3 py-2.5 transition-colors hover:bg-[var(--muted-foreground)]/[0.02]"
+ >
+ <span className="mt-1.5 w-4 shrink-0 text-center text-[11px] font-medium tabular-nums text-[var(--muted-foreground)]/30">
+ {index + 1}
+ </span>
+ <div className="min-w-0 flex-1 space-y-1">
+ {locked ? (
+ <>
+ <div className="text-[12px] font-medium text-[var(--foreground)]">
+ {item.title}
+ </div>
+ {item.overview && (
+ <div className="text-[11px] leading-relaxed text-[var(--muted-foreground)]/70">
+ {item.overview}
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ <input
+ type="text"
+ value={item.title ?? ""}
+ onChange={(e) => updateItem(index, "title", e.target.value)}
+ placeholder="Sub-topic title..."
+ className="w-full bg-transparent text-[12px] font-medium text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/30"
+ />
+ <textarea
+ value={item.overview ?? ""}
+ onChange={(e) => updateItem(index, "overview", e.target.value)}
+ placeholder="Research direction and focus..."
+ rows={2}
+ className="w-full resize-none bg-transparent text-[11px] leading-relaxed text-[var(--muted-foreground)]/70 outline-none placeholder:text-[var(--muted-foreground)]/25"
+ />
+ </>
+ )}
+ </div>
+ {!locked && items.length > 1 && (
+ <button
+ type="button"
+ onClick={() => removeItem(index)}
+ className="mt-1 shrink-0 rounded p-0.5 text-[var(--muted-foreground)]/20 opacity-0 transition-all hover:bg-red-500/10 hover:text-red-500/60 group-hover:opacity-100"
+ >
+ <Trash2 size={12} />
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+
+ {!locked && (
+ <div className="flex items-center justify-between border-t border-[var(--border)]/20 px-4 py-2">
+ <button
+ type="button"
+ onClick={addItem}
+ className="flex items-center gap-1 rounded-md px-2 py-1 text-[11px] text-[var(--muted-foreground)]/50 transition-colors hover:bg-[var(--muted-foreground)]/5 hover:text-[var(--muted-foreground)]/70"
+ >
+ <Plus size={12} />
+ Add sub-topic
+ </button>
+ <button
+ type="button"
+ onClick={handleConfirm}
+ disabled={items.every((i) => !i.title.trim())}
+ className="flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[11px] font-medium text-[var(--primary-foreground)] transition-all hover:opacity-90 disabled:opacity-40"
+ >
+ <Play size={11} />
+ Start Research
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index cc0febed1..7d0fd5cf3 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -5,8 +5,8 @@ import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState, type ReactNode } from "react";
import {
- Blocks,
BookOpen,
+ Bot,
Brain,
GraduationCap,
MessageSquare,
@@ -18,6 +18,7 @@ import {
type LucideIcon,
} from "lucide-react";
import SessionList from "@/components/SessionList";
+import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";
import type { SessionSummary } from "@/lib/session-api";
interface NavEntry {
@@ -28,15 +29,15 @@ interface NavEntry {
const PRIMARY_NAV: NavEntry[] = [
{ href: "/", label: "Chat", icon: MessageSquare },
+ { href: "/agents", label: "TutorBot", icon: Bot },
{ href: "/co-writer", label: "Co-Writer", icon: PenLine },
{ href: "/guide", label: "Guided Learning", icon: GraduationCap },
{ href: "/knowledge", label: "Knowledge", icon: BookOpen },
{ href: "/memory", label: "Memory", icon: Brain },
- { href: "/playground", label: "Playground", icon: Blocks },
];
const SECONDARY_NAV: NavEntry[] = [{ href: "/settings", label: "Settings", icon: Settings }];
-const DEFAULT_SESSION_VIEWPORT_CLASS_NAME = "max-h-[220px]";
+const DEFAULT_SESSION_VIEWPORT_CLASS_NAME = "max-h-[112px]";
interface SidebarShellProps {
sessions?: SessionSummary[];
@@ -75,119 +76,164 @@ export function SidebarShell({
router.push("/");
};
- return (
- <aside
- className={`${
- collapsed ? "w-[56px]" : "w-[216px]"
- } flex h-screen shrink-0 flex-col bg-[var(--accent)] transition-all duration-200 dark:bg-[var(--card)]`}
- >
- <div
- className={`flex h-14 items-center ${
- collapsed ? "justify-center px-2" : "justify-between px-4"
- }`}
- >
- {collapsed ? (
- <Link href="/">
- <Image src="/logo-ver2.png" alt="DeepTutor" width={22} height={22} />
- </Link>
- ) : (
- <>
- <Link href="/" className="flex items-center gap-2">
- <Image src="/logo-ver2.png" alt="DeepTutor" width={22} height={22} />
- <span className="text-[13px] font-semibold text-[var(--foreground)]">
- DeepTutor
- </span>
- </Link>
- <button
- onClick={() => setCollapsed(true)}
- className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
- aria-label="Collapse sidebar"
- >
- <PanelLeftClose size={15} />
- </button>
- </>
- )}
- </div>
+ /* ---- Collapsed state ---- */
+ if (collapsed) {
+ return (
+ <aside className="flex w-[56px] h-screen shrink-0 flex-col items-center bg-[var(--secondary)] py-3 transition-all duration-200">
+ <button
+ onClick={() => setCollapsed(false)}
+ className="mb-4 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ aria-label="Expand sidebar"
+ >
+ <PanelLeftOpen size={15} />
+ </button>
- <div className={`${collapsed ? "px-1.5" : "px-2"} pb-1`}>
<button
onClick={handleNewChat}
- className={`flex w-full items-center gap-2 rounded-lg px-3 py-[7px] text-[13px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] ${
- collapsed ? "justify-center px-0" : ""
- }`}
+ className="mb-3 rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"
+ aria-label="New chat"
>
- <Plus size={15} strokeWidth={2} />
- {!collapsed && <span>New chat</span>}
+ <Plus size={16} strokeWidth={2} />
</button>
- </div>
-
- {!collapsed && showSessions && onSelectSession && onRenameSession && onDeleteSession ? (
- <div className="px-2 pb-2">
- <div className={`${sessionViewportClassName} overflow-y-auto`}>
- <SessionList
- sessions={sessions}
- activeSessionId={activeSessionId}
- loading={loadingSessions}
- onSelect={onSelectSession}
- onRename={onRenameSession}
- onDelete={onDeleteSession}
- />
- </div>
- </div>
- ) : null}
- <nav className={`flex-1 ${collapsed ? "px-1.5" : "px-2"} pt-2`}>
- <div className="space-y-px">
+ <nav className="flex flex-col items-center gap-px pt-1">
{PRIMARY_NAV.map((item) => {
const active = item.href === "/" ? pathname === "/" : pathname.startsWith(item.href);
+ return (
+ <div key={item.href} className="flex flex-col items-center">
+ <Link
+ href={item.href}
+ className={`rounded-lg p-2 transition-colors ${
+ active
+ ? "bg-[var(--background)]/70 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
+ </Link>
+ {item.href === "/agents" && <TutorBotRecent collapsed />}
+ </div>
+ );
+ })}
+ </nav>
+
+ <div className="flex-1" />
+
+ <div className="flex flex-col items-center gap-px pb-1">
+ {SECONDARY_NAV.map((item) => {
+ const active = pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
- className={`flex items-center gap-2.5 rounded-lg px-3 py-[7px] text-[13px] transition-colors ${
+ className={`rounded-lg p-2 transition-colors ${
active
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
- } ${collapsed ? "justify-center px-0" : ""}`}
+ ? "bg-[var(--background)]/70 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ }`}
>
<item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
- {!collapsed && <span>{item.label}</span>}
</Link>
);
})}
+ {footerSlot}
+ </div>
+ </aside>
+ );
+ }
+
+ /* ---- Expanded state ---- */
+ return (
+ <aside className="flex w-[220px] h-screen shrink-0 flex-col bg-[var(--secondary)] transition-all duration-200">
+ {/* Header: logo + collapse toggle */}
+ <div className="flex h-12 items-center justify-between px-4">
+ <Link href="/" className="flex items-center gap-2">
+ <Image src="/logo-ver2.png" alt="DeepTutor" width={20} height={20} />
+ <span className="text-[15px] font-semibold tracking-tight text-[var(--foreground)]">
+ DeepTutor
+ </span>
+ </Link>
+ <button
+ onClick={() => setCollapsed(true)}
+ className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ aria-label="Collapse sidebar"
+ >
+ <PanelLeftClose size={15} />
+ </button>
+ </div>
+
+ {/* Primary nav */}
+ <nav className="px-2 pt-1">
+ <div className="space-y-px">
+ {/* New chat */}
+ <button
+ onClick={handleNewChat}
+ className="flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/60 hover:text-[var(--foreground)]"
+ >
+ <Plus size={16} strokeWidth={2} />
+ <span>New chat</span>
+ </button>
+
+ {PRIMARY_NAV.map((item) => {
+ const active = item.href === "/" ? pathname === "/" : pathname.startsWith(item.href);
+ const hasSessionsBelow = item.href === "/" && showSessions && onSelectSession && onRenameSession && onDeleteSession;
+ const hasBots = item.href === "/agents";
+ return (
+ <div key={item.href}>
+ <Link
+ href={item.href}
+ className={`flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] transition-colors ${
+ active
+ ? "bg-[var(--background)]/70 font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ }`}
+ >
+ <item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
+ <span>{item.label}</span>
+ </Link>
+ {hasSessionsBelow && (
+ <div className={`${sessionViewportClassName} overflow-y-auto`}>
+ <SessionList
+ sessions={sessions}
+ activeSessionId={activeSessionId}
+ loading={loadingSessions}
+ onSelect={onSelectSession}
+ onRename={onRenameSession}
+ onDelete={onDeleteSession}
+ compact
+ />
+ </div>
+ )}
+ {hasBots && <TutorBotRecent />}
+ </div>
+ );
+ })}
</div>
</nav>
- <div className={`${collapsed ? "px-1.5" : "px-2"} pb-3`}>
+ {/* Spacer */}
+ <div className="flex-1" />
+
+ {/* Secondary nav + footer */}
+ <div className="border-t border-[var(--border)]/40 px-2 py-2">
{SECONDARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
- className={`flex items-center gap-2.5 rounded-lg px-3 py-[7px] text-[13px] transition-colors ${
+ className={`flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] transition-colors ${
active
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
- } ${collapsed ? "justify-center px-0" : ""}`}
+ ? "bg-[var(--background)]/70 font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ }`}
>
<item.icon size={16} strokeWidth={active ? 1.9 : 1.5} />
- {!collapsed && <span>{item.label}</span>}
+ <span>{item.label}</span>
</Link>
);
})}
-
{footerSlot}
-
- {collapsed ? (
- <button
- onClick={() => setCollapsed(false)}
- className="mt-1 flex w-full items-center justify-center rounded-lg py-[7px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
- aria-label="Expand sidebar"
- >
- <PanelLeftOpen size={15} />
- </button>
- ) : null}
</div>
</aside>
);
diff --git a/web/components/sidebar/TutorBotRecent.tsx b/web/components/sidebar/TutorBotRecent.tsx
new file mode 100644
index 000000000..5db00c20c
--- /dev/null
+++ b/web/components/sidebar/TutorBotRecent.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { Bot } from "lucide-react";
+import { apiUrl } from "@/lib/api";
+
+interface RecentBot {
+ bot_id: string;
+ name: string;
+ running: boolean;
+ last_message: string;
+ updated_at: string;
+}
+
+function relativeTime(iso: string): string {
+ const diff = Date.now() - new Date(iso).getTime();
+ const mins = Math.floor(diff / 60000);
+ if (mins < 1) return "just now";
+ if (mins < 60) return `${mins}m`;
+ const hrs = Math.floor(mins / 60);
+ if (hrs < 24) return `${hrs}h`;
+ const days = Math.floor(hrs / 24);
+ return `${days}d`;
+}
+
+export function TutorBotRecent({ collapsed = false }: { collapsed?: boolean }) {
+ const [bots, setBots] = useState<RecentBot[]>([]);
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/tutorbot/recent?limit=3"));
+ if (!res.ok) return;
+ const data = await res.json();
+ if (!cancelled) setBots(data);
+ } catch {
+ /* ignore */
+ }
+ })();
+ return () => { cancelled = true; };
+ }, []);
+
+ if (bots.length === 0) return null;
+
+ if (collapsed) {
+ return (
+ <div className="flex flex-col items-center gap-0.5 pb-0.5 pt-px">
+ {bots.map((bot) => (
+ <Link
+ key={bot.bot_id}
+ href={`/agents/${bot.bot_id}/chat`}
+ title={bot.name}
+ className="relative rounded-md p-1.5 text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"
+ >
+ <Bot size={12} strokeWidth={1.5} />
+ {bot.running && (
+ <span className="absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full bg-emerald-400 ring-1 ring-[var(--secondary)]" />
+ )}
+ </Link>
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <div className="ml-5 border-l border-[var(--border)]/30 py-1">
+ {bots.map((bot) => (
+ <Link
+ key={bot.bot_id}
+ href={`/agents/${bot.bot_id}/chat`}
+ className="group flex items-center gap-2 rounded-r-lg py-1 pl-3 pr-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
+ >
+ <div className="relative shrink-0">
+ {bot.running ? (
+ <span className="block h-1.5 w-1.5 rounded-full bg-emerald-400" />
+ ) : (
+ <span className="block h-1.5 w-1.5 rounded-full bg-[var(--muted-foreground)]/25" />
+ )}
+ </div>
+ <span className="min-w-0 flex-1 truncate text-[13px]">
+ {bot.name}
+ </span>
+ <span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
+ {relativeTime(bot.updated_at)}
+ </span>
+ </Link>
+ ))}
+ </div>
+ );
+}
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 4cd9b1ba9..06d1ef3db 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -239,7 +239,12 @@ function reducer(state: ProviderState, action: Action): ProviderState {
status: "running",
messages: [
...(state.sessions[action.key]?.messages ?? []),
- { role: "assistant", content: "", events: [] },
+ {
+ role: "assistant",
+ content: "",
+ events: [],
+ capability: (state.sessions[action.key] ?? createSessionEntry(action.key)).activeCapability || "",
+ },
],
updatedAt: Date.now(),
},
@@ -250,13 +255,14 @@ function reducer(state: ProviderState, action: Action): ProviderState {
const msgs = [...session.messages];
let last = msgs[msgs.length - 1];
if (last?.role !== "assistant") {
- msgs.push({ role: "assistant", content: "", events: [] });
+ msgs.push({ role: "assistant", content: "", events: [], capability: session.activeCapability || "" });
last = msgs[msgs.length - 1];
}
const events = [...(last?.events || []), action.event];
let content = last?.content || "";
if (shouldAppendEventContent(action.event)) content += action.event.content;
- msgs[msgs.length - 1] = { ...(last || { role: "assistant", content: "" }), content, events };
+ const capability = last?.capability || session.activeCapability || "";
+ msgs[msgs.length - 1] = { ...(last || { role: "assistant", content: "" }), content, events, capability };
return {
...state,
sessions: {
diff --git a/web/hooks/useChatAutoScroll.ts b/web/hooks/useChatAutoScroll.ts
index a75b5ca24..8d70c1221 100644
--- a/web/hooks/useChatAutoScroll.ts
+++ b/web/hooks/useChatAutoScroll.ts
@@ -11,6 +11,8 @@ interface AutoScrollOptions {
lastEventCount?: number;
}
+const THROTTLE_MS = 80;
+
export function useChatAutoScroll({
hasMessages,
isStreaming,
@@ -22,15 +24,12 @@ export function useChatAutoScroll({
const containerRef = useRef<HTMLDivElement>(null);
const endRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
+ const lastScrollTimeRef = useRef(0);
+ const pendingRafRef = useRef(0);
const scrollToBottom = useCallback((behavior: ScrollBehavior) => {
const container = containerRef.current;
- const anchor = endRef.current;
if (!container) return;
- if (anchor) {
- anchor.scrollIntoView({ block: "end", behavior });
- return;
- }
container.scrollTo({
top: container.scrollHeight,
behavior,
@@ -39,26 +38,40 @@ export function useChatAutoScroll({
useEffect(() => {
if (!shouldAutoScrollRef.current) return;
- let raf1 = 0;
- let raf2 = 0;
- raf1 = window.requestAnimationFrame(() => {
- scrollToBottom(isStreaming ? "auto" : "smooth");
- if (isStreaming) {
- raf2 = window.requestAnimationFrame(() => {
- scrollToBottom("auto");
- });
- }
+
+ const now = performance.now();
+ const elapsed = now - lastScrollTimeRef.current;
+
+ if (isStreaming && elapsed < THROTTLE_MS) {
+ if (pendingRafRef.current) return;
+ pendingRafRef.current = window.setTimeout(() => {
+ pendingRafRef.current = 0;
+ if (shouldAutoScrollRef.current) {
+ scrollToBottom("instant");
+ lastScrollTimeRef.current = performance.now();
+ }
+ }, THROTTLE_MS - elapsed);
+ return;
+ }
+
+ const raf = window.requestAnimationFrame(() => {
+ scrollToBottom(isStreaming ? "instant" : "smooth");
+ lastScrollTimeRef.current = performance.now();
});
+
return () => {
- window.cancelAnimationFrame(raf1);
- window.cancelAnimationFrame(raf2);
+ window.cancelAnimationFrame(raf);
+ if (pendingRafRef.current) {
+ clearTimeout(pendingRafRef.current);
+ pendingRafRef.current = 0;
+ }
};
}, [isStreaming, lastEventCount, lastMessageContent, messageCount, scrollToBottom]);
useEffect(() => {
if (!hasMessages || !shouldAutoScrollRef.current) return;
const raf = window.requestAnimationFrame(() => {
- scrollToBottom("auto");
+ scrollToBottom("instant");
});
return () => window.cancelAnimationFrame(raf);
}, [composerHeight, hasMessages, scrollToBottom]);
diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.ts
index 31edb7108..57f517551 100644
--- a/web/lib/markdown-display.ts
+++ b/web/lib/markdown-display.ts
@@ -5,6 +5,11 @@ const EMPTY_DETAILS_REGEX =
/<details(?:\s[^>]*)?>\s*(<summary(?:\s[^>]*)?>\s*(?:&nbsp;|\s|<br\s*\/?>)*\s*<\/summary>\s*)?<\/details>/gi;
const EMPTY_SUMMARY_REGEX =
/<summary(?:\s[^>]*)?>\s*(?:&nbsp;|\s|<br\s*\/?>)*\s*<\/summary>/gi;
+const EMPTY_PROGRESS_REGEX =
+ /<progress(?:\s[^>]*)?>\s*(?:&nbsp;|\s|<br\s*\/?>)*\s*<\/progress>/gi;
+const RAW_INPUT_REGEX = /<input(?:\s[^>]*)?>/gi;
+const EMPTY_FORM_CONTROL_REGEX =
+ /<(textarea|select|button|meter)(?:\s[^>]*)?>\s*(?:&nbsp;|\s|<br\s*\/?>)*\s*<\/\1>/gi;
const EMPTY_FENCED_CODE_BLOCK_REGEX = /```[^\n`]*\n?\s*```/g;
const EMPTY_HTML_BLOCK_REGEX =
/<(p|div|section|article|aside|blockquote)(?:\s[^>]*)?>\s*(?:&nbsp;|\s|<br\s*\/?>)*\s*<\/\1>/gi;
@@ -93,6 +98,64 @@ function removeEmptyHtmlTables(content: string): string {
return content.replace(HTML_TABLE_REGEX, (block) => (stripDisplaySyntax(block) ? block : ""));
}
+const PREFIXED_CIT = String.raw`(?:web|rag|code|src)-\d+`;
+const NUMERIC_CIT = String.raw`\d+`;
+const SINGLE_CIT = `(?:${PREFIXED_CIT}|${NUMERIC_CIT})`;
+const MULTI_CIT = `${SINGLE_CIT}(?:\\s*,\\s*${SINGLE_CIT})*`;
+
+const INLINE_CITATION_REGEX = new RegExp(
+ String.raw`(?<!\*\*|\[)\[(${MULTI_CIT})\](?!\(|:)`,
+ "g",
+);
+
+const ESCAPED_CITATION_LINK_REGEX = new RegExp(
+ String.raw`\\?\[(${SINGLE_CIT})\\?\]\s*\(#references\s+["` + "\u201c" + String.raw`]citation["` + "\u201d" + String.raw`]\)`,
+ "g",
+);
+
+function unwrapBacktickedCitations(content: string): string {
+ return content.replace(
+ new RegExp(
+ "`(\\[" + MULTI_CIT + "\\](?:\\s*\\(#references\\s+[\"\\u201c]citation[\"\\u201d]\\))?)`",
+ "g",
+ ),
+ "$1",
+ );
+}
+
+function linkifyCitations(content: string): string {
+ const refSectionIdx = content.search(/^##\s+(References|参考文献)/m);
+ const body = refSectionIdx >= 0 ? content.slice(0, refSectionIdx) : content;
+ const tail = refSectionIdx >= 0 ? content.slice(refSectionIdx) : "";
+
+ // Normalize existing citation links that may have escaped brackets or smart quotes
+ let linked = body.replace(
+ ESCAPED_CITATION_LINK_REGEX,
+ (_match, id: string) => `[${id.trim()}](#references "citation")`,
+ );
+
+ // Convert bare [web-1] / [rag-1] / [1] / [1, 3] references to a single citation link
+ linked = linked.replace(INLINE_CITATION_REGEX, (_match, refs: string) => {
+ return `[${refs.trim()}](#references "citation")`;
+ });
+
+ // Handle escaped bare citations like \[web-1\] or \[1\] that linkifyCitations missed
+ linked = linked.replace(
+ new RegExp(String.raw`\\\[(${MULTI_CIT})\\\](?!\s*\()`, "g"),
+ (_match, refs: string) => {
+ return `[${refs.trim()}](#references "citation")`;
+ },
+ );
+
+ // Remove stray space before trailing punctuation after citations
+ linked = linked.replace(
+ /(\(#references\s+"citation"\))\s+([.。,,;:!?])/g,
+ "$1$2",
+ );
+
+ return linked + tail;
+}
+
export function normalizeMarkdownForDisplay(content: string): string {
if (!content) return "";
@@ -100,11 +163,15 @@ export function normalizeMarkdownForDisplay(content: string): string {
.replace(/\r\n/g, "\n")
.replace(EMPTY_DETAILS_REGEX, "")
.replace(EMPTY_SUMMARY_REGEX, "")
+ .replace(EMPTY_PROGRESS_REGEX, "")
+ .replace(RAW_INPUT_REGEX, "")
+ .replace(EMPTY_FORM_CONTROL_REGEX, "")
.replace(EMPTY_HTML_BLOCK_REGEX, "")
.replace(/\n{3,}/g, "\n\n")
.replace(/^\n+|\n+$/g, "");
- return removeEmptyMarkdownTables(removeEmptyHtmlTables(normalized)).replace(/\n{3,}/g, "\n\n");
+ const cleaned = removeEmptyMarkdownTables(removeEmptyHtmlTables(normalized)).replace(/\n{3,}/g, "\n\n");
+ return linkifyCitations(unwrapBacktickedCitations(cleaned));
}
export function hasVisibleMarkdownContent(content: string): boolean {
diff --git a/web/lib/math-animator-types.ts b/web/lib/math-animator-types.ts
index 9f8d54bc2..509718830 100644
--- a/web/lib/math-animator-types.ts
+++ b/web/lib/math-animator-types.ts
@@ -80,10 +80,28 @@ export function extractMathAnimatorResult(
resultMetadata.code && typeof resultMetadata.code === "object"
? (resultMetadata.code as Record<string, unknown>)
: {};
- const outputMode =
- resultMetadata.output_mode === "image" ? "image" : "video";
+ const hasOutputMode =
+ resultMetadata.output_mode === "image" || resultMetadata.output_mode === "video";
+ const timings =
+ resultMetadata.timings && typeof resultMetadata.timings === "object"
+ ? (resultMetadata.timings as Record<string, number>)
+ : {};
+ const render =
+ resultMetadata.render && typeof resultMetadata.render === "object"
+ ? (resultMetadata.render as MathAnimatorResult["render"])
+ : {};
+ const outputMode = resultMetadata.output_mode === "image" ? "image" : "video";
- if (!artifacts.length && !codeRaw.content && !resultMetadata.response) {
+ // A plain `response` field is common across capabilities. Only treat the
+ // payload as a math-animator result when it carries math-animator-specific
+ // artifacts or render metadata.
+ if (
+ !artifacts.length &&
+ !codeRaw.content &&
+ !hasOutputMode &&
+ Object.keys(timings).length === 0 &&
+ Object.keys(render).length === 0
+ ) {
return null;
}
@@ -95,14 +113,8 @@ export function extractMathAnimatorResult(
content: String(codeRaw.content ?? ""),
},
artifacts,
- timings:
- resultMetadata.timings && typeof resultMetadata.timings === "object"
- ? (resultMetadata.timings as Record<string, number>)
- : {},
- render:
- resultMetadata.render && typeof resultMetadata.render === "object"
- ? (resultMetadata.render as MathAnimatorResult["render"])
- : {},
+ timings,
+ render,
summary:
resultMetadata.summary && typeof resultMetadata.summary === "object"
? (resultMetadata.summary as MathAnimatorResult["summary"])
diff --git a/web/lib/research-types.ts b/web/lib/research-types.ts
index 308e2cdf3..9d55f9714 100644
--- a/web/lib/research-types.ts
+++ b/web/lib/research-types.ts
@@ -1,11 +1,19 @@
export type ResearchMode = "" | "notes" | "report" | "comparison" | "learning_path";
-export type ResearchDepth = "" | "quick" | "standard" | "deep";
+export type ResearchDepth = "" | "quick" | "standard" | "deep" | "manual";
export type ResearchSource = "kb" | "web" | "papers";
+export interface OutlineItem {
+ title: string;
+ overview: string;
+}
+
export interface DeepResearchFormConfig {
mode: ResearchMode;
depth: ResearchDepth;
sources: ResearchSource[];
+ manual_subtopics?: number;
+ manual_max_iterations?: number;
+ confirmed_outline?: OutlineItem[];
}
export interface ResearchConfigValidationResult {
@@ -34,7 +42,7 @@ export function normalizeResearchConfig(
? raw.mode
: empty.mode,
depth:
- raw?.depth === "quick" || raw?.depth === "standard" || raw?.depth === "deep"
+ raw?.depth === "quick" || raw?.depth === "standard" || raw?.depth === "deep" || raw?.depth === "manual"
? raw.depth
: empty.depth,
sources: Array.isArray(raw?.sources)
@@ -63,17 +71,30 @@ export function validateResearchConfig(
export function buildResearchWSConfig(
cfg: DeepResearchFormConfig,
+ confirmedOutline?: OutlineItem[],
): Record<string, unknown> {
const validation = validateResearchConfig(cfg);
if (!validation.valid) {
throw new Error("Deep research settings are incomplete.");
}
- return {
+ const result: Record<string, unknown> = {
mode: cfg.mode,
depth: cfg.depth,
sources: [...cfg.sources],
};
+
+ if (cfg.depth === "manual") {
+ if (cfg.manual_subtopics != null) result.manual_subtopics = cfg.manual_subtopics;
+ if (cfg.manual_max_iterations != null) result.manual_max_iterations = cfg.manual_max_iterations;
+ }
+
+ const outline = confirmedOutline ?? cfg.confirmed_outline;
+ if (outline && outline.length > 0) {
+ result.confirmed_outline = outline;
+ }
+
+ return result;
}
export function summarizeResearchConfig(cfg: DeepResearchFormConfig): string {
diff --git a/web/tailwind.config.js b/web/tailwind.config.js
index eafc65fdc..550a6afcd 100644
--- a/web/tailwind.config.js
+++ b/web/tailwind.config.js
@@ -8,6 +8,10 @@ module.exports = {
],
theme: {
extend: {
+ fontFamily: {
+ sans: ["var(--font-sans)", "system-ui", "sans-serif"],
+ serif: ["var(--font-serif)", "Georgia", "serif"],
+ },
colors: {
border: "var(--border)",
input: "var(--input)",
diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.ts
index b894234c8..edb95bdce 100644
--- a/web/tests/markdown-display.test.ts
+++ b/web/tests/markdown-display.test.ts
@@ -10,6 +10,11 @@ test("normalizeMarkdownForDisplay removes empty details blocks", () => {
assert.equal(normalizeMarkdownForDisplay(input), "Before\n\nAfter");
});
+test("normalizeMarkdownForDisplay removes raw html control placeholders", () => {
+ const input = "Before\n\n<progress></progress>\n<input type=\"text\" />\n<textarea> </textarea>\n\nAfter";
+ assert.equal(normalizeMarkdownForDisplay(input), "Before\n\nAfter");
+});
+
test("normalizeMarkdownForDisplay removes empty markdown tables", () => {
const input = "Before\n\n| |\n|---|\n\nAfter";
assert.equal(normalizeMarkdownForDisplay(input), "Before\n\nAfter");
@@ -32,6 +37,13 @@ test("hasVisibleMarkdownContent rejects empty raw-html placeholders", () => {
);
});
+test("hasVisibleMarkdownContent rejects raw html control placeholders", () => {
+ assert.equal(
+ hasVisibleMarkdownContent("<progress></progress>\n<input type=\"text\" />"),
+ false,
+ );
+});
+
test("hasVisibleMarkdownContent rejects empty markdown tables", () => {
assert.equal(hasVisibleMarkdownContent("| |\n|---|"), false);
});
diff --git a/web/tests/math-animator-types.test.ts b/web/tests/math-animator-types.test.ts
new file mode 100644
index 000000000..9903b6f3c
--- /dev/null
+++ b/web/tests/math-animator-types.test.ts
@@ -0,0 +1,37 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { extractMathAnimatorResult } from "../lib/math-animator-types";
+
+test("extractMathAnimatorResult ignores generic response-only payloads", () => {
+ assert.equal(
+ extractMathAnimatorResult({
+ response: "Hello! I'm DeepTutor.",
+ metadata: {
+ cost_summary: {
+ total_cost_usd: 0,
+ total_tokens: 1043,
+ total_calls: 3,
+ },
+ },
+ }),
+ null,
+ );
+});
+
+test("extractMathAnimatorResult keeps actual math animator payloads", () => {
+ const result = extractMathAnimatorResult({
+ response: "Storyboard generated.",
+ output_mode: "image",
+ artifacts: [
+ {
+ type: "image",
+ url: "/api/v1/files/frame-1.png",
+ filename: "frame-1.png",
+ },
+ ],
+ });
+
+ assert.ok(result);
+ assert.equal(result.output_mode, "image");
+ assert.equal(result.artifacts.length, 1);
+});