DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
prepare 1.4.7
Bingxi Zhao (Frank)1bf11d13e777
diff --git a/.github/ISSUE_TEMPLATE/eduhub.yml b/.github/ISSUE_TEMPLATE/eduhub.ymlnew file mode 100644index 000000000..661254982--- /dev/null+++ b/.github/ISSUE_TEMPLATE/eduhub.yml@@ -0,0 +1,78 @@+name: EduHub / Skill Registry+description: Report an issue with EduHub — the DeepTutor skill registry (site, API, CLI, or a published skill)+title: "[EduHub]:"+labels: ["eduhub", "triage"]++body:+ - type: markdown+ attributes:+ value: |+ EduHub is DeepTutor's skill registry at https://eduhub.deeptutor.info.+ Use this template for the EduHub web site, the ClawHub-compatible API, the `eduhub` CLI,+ or a specific published skill. For bugs in the DeepTutor app itself, use the Bug Report template.+ - type: checkboxes+ id: existingcheck+ attributes:+ label: Do you need to file an issue?+ description: Please help us manage our time by avoiding duplicates with the steps below.+ options:+ - label: I have searched the existing issues and this is not already filed.+ - label: I have read the usage guide at https://eduhub.deeptutor.info/how-to-use+ - type: dropdown+ id: area+ attributes:+ label: Area+ description: Which part of EduHub is this about?+ options:+ - Web site (eduhub.deeptutor.info)+ - HTTP API (/api/v1)+ - CLI (eduhub command)+ - A published skill (install / content / metadata)+ - Report a skill for removal (policy / copyright / security)+ - Publishing a skill+ - Other+ validations:+ required: true+ - type: input+ id: skill_slug+ attributes:+ label: Skill slug+ description: If this is about a specific skill, its slug (e.g. socratic-tutor). Leave blank otherwise.+ placeholder: socratic-tutor+ - type: textarea+ id: description+ attributes:+ label: Describe the issue+ description: A clear and concise description of the problem.+ placeholder: What happened? What did you expect to happen?+ validations:+ required: true+ - type: textarea+ id: reproduce+ attributes:+ label: Steps to reproduce+ description: Steps to reproduce the behavior (if applicable).+ placeholder: |+ 1. Run `eduhub install <slug>`+ 2. ...+ 3. See error+ - type: textarea+ id: logs+ attributes:+ label: Logs and screenshots+ description: Paste the full command output or browser console errors.+ render: shell+ - type: textarea+ id: environment+ attributes:+ label: Environment+ description: |+ - eduhub CLI Version: run `eduhub --version` (CLI issues only)+ - Operating System: e.g., macOS 14.0, Windows 11, Ubuntu 22.04+ - Node.js Version: e.g., 20.x+ - Registry: e.g., https://eduhub.deeptutor.info+ value: |+ - eduhub CLI Version:+ - Operating System:+ - Node.js Version:+ - Registry:diff --git a/.github/pull.yml b/.github/pull.ymlnew file mode 100644index 000000000..f8d140e51--- /dev/null+++ b/.github/pull.yml@@ -0,0 +1,12 @@+version: "1"+rules:+ - base: main+ upstream: HKUDS:main+ mergeMethod: hardreset+ mergeUnstable: true+ - base: dev+ upstream: HKUDS:dev+ mergeMethod: hardreset+ mergeUnstable: true+label: ":arrow_heading_down: pull"+conflictLabel: "merge-conflict"diff --git a/README.md b/README.mdindex da14ae9a2..01ce8301c 100644--- a/README.md+++ b/README.md@@ -42,11 +42,15 @@> 🤝 **We welcome any kinds of contributing!** Vote on roadmap items or propose new ones at [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498), and see our [Contributing Guide](CONTRIBUTING.md) for branching strategy, coding standards, and how to get started.+> 📖 **Docs note:** The documentation at [deeptutor.info](https://deeptutor.info) currently reflects **v1.4.5** and will be updated to the latest release shortly.+### 📦 Releases-> **[2026.6.17]** [v1.4.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.6) — Consolidation across four surfaces: Space becomes a learning dashboard with importable **My Agents** and a top-level Memory, the **Knowledge Center** adds GraphRAG / PageIndex / LightRAG engines plus linked-KB and Obsidian mounts, Settings opens up document parsing / voice / image+video, and LLM capabilities are gated per assigned model.+> **[2026.6.18]** [v1.4.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.7) — Connect your local **Claude Code / Codex** and consult it live mid-turn, **My Agents** graduates to a top-level `/agents`, and Partner conversations gain branch / resume / delete with a replayable trace.++> **[2026.6.17]** [v1.4.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.6) — Four-surface consolidation: a **Knowledge Center** with GraphRAG / PageIndex / LightRAG engines and linked-KB / Obsidian mounts, a Space learning dashboard with **My Agents** and top-level Memory, plus document parsing / voice / media settings.-> **[2026.6.14]** [v1.4.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.5) — Guided Learning rebuilt on the chat agent loop with a hard per-type mastery gate and a `/learning` dashboard, a new extensible loop-plugin framework, plus Markdown export / save-to-notebook for Partner conversations.+> **[2026.6.14]** [v1.4.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.5) — Guided Learning rebuilt on the chat agent loop with a hard per-type mastery gate and a `/learning` dashboard, a new loop-plugin framework, plus Markdown export for Partner conversations.> **[2026.6.13]** [v1.4.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.4) — Install community skills from [ClawHub](https://clawhub.ai/) with `deeptutor skill install` behind a security gate, plus real in-browser DOCX/XLSX previews for knowledge-base files.diff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.04.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.04.png"new file mode 100644index 000000000..87518c0bfBinary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.04.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.15.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.15.png"new file mode 100644index 000000000..d6b9277ccBinary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.15.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.27.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.27.png"new file mode 100644index 000000000..f459742a3Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.27.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.35.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.35.png"new file mode 100644index 000000000..98c3cc2d7Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.35.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.42.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.42.png"new file mode 100644index 000000000..f1aa1e3e4Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.43.42.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.19.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.19.png"new file mode 100644index 000000000..41fcbf035Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.19.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.25.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.25.png"new file mode 100644index 000000000..a74873691Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.25.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.31.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.31.png"new file mode 100644index 000000000..f99906e13Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.31.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.46.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.46.png"new file mode 100644index 000000000..72a2b36a1Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 20.44.46.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.16.32.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.16.32.png"new file mode 100644index 000000000..976bce3d1Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.16.32.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.24.00.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.24.00.png"new file mode 100644index 000000000..1bcb37406Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.24.00.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.26.03.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.26.03.png"new file mode 100644index 000000000..12c4a34e1Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.26.03.png" differdiff --git "a/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.26.24.png" "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.26.24.png"new file mode 100644index 000000000..80710fed1Binary files /dev/null and "b/assets/figs/web-1.4.6+/home/\346\210\252\345\261\2172026-06-17 22.26.24.png" differdiff --git "a/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.27.png" "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.27.png"new file mode 100644index 000000000..979b24182Binary files /dev/null and "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.27.png" differdiff --git "a/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.37.png" "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.37.png"new file mode 100644index 000000000..adfde5842Binary files /dev/null and "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.37.png" differdiff --git "a/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.44.png" "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.44.png"new file mode 100644index 000000000..9c9371e91Binary files /dev/null and "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.44.png" differdiff --git "a/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.51.png" "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.51.png"new file mode 100644index 000000000..e609abe6eBinary files /dev/null and "b/assets/figs/web-1.4.6+/knowledge/\346\210\252\345\261\2172026-06-17 22.25.51.png" differdiff --git "a/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.22.26.png" "b/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.22.26.png"new file mode 100644index 000000000..21785a99dBinary files /dev/null and "b/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.22.26.png" differdiff --git "a/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.22.38.png" "b/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.22.38.png"new file mode 100644index 000000000..63a5f3830Binary files /dev/null and "b/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.22.38.png" differdiff --git "a/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.26.14.png" "b/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.26.14.png"new file mode 100644index 000000000..7a3a83e9eBinary files /dev/null and "b/assets/figs/web-1.4.6+/memory/\346\210\252\345\261\2172026-06-17 22.26.14.png" differdiff --git "a/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.19.26.png" "b/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.19.26.png"new file mode 100644index 000000000..1de483cecBinary files /dev/null and "b/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.19.26.png" differdiff --git "a/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.20.14.png" "b/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.20.14.png"new file mode 100644index 000000000..08601a45fBinary files /dev/null and "b/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.20.14.png" differdiff --git "a/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.21.02.png" "b/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.21.02.png"new file mode 100644index 000000000..3fbb79b9dBinary files /dev/null and "b/assets/figs/web-1.4.6+/partners/\346\210\252\345\261\2172026-06-17 22.21.02.png" differdiff --git "a/assets/figs/web-1.4.6+/settings/\346\210\252\345\261\2172026-06-17 22.26.00.png" "b/assets/figs/web-1.4.6+/settings/\346\210\252\345\261\2172026-06-17 22.26.00.png"new file mode 100644index 000000000..52dedbdb1Binary files /dev/null and "b/assets/figs/web-1.4.6+/settings/\346\210\252\345\261\2172026-06-17 22.26.00.png" differdiff --git "a/assets/figs/web-1.4.6+/settings/\346\210\252\345\261\2172026-06-17 22.26.30.png" "b/assets/figs/web-1.4.6+/settings/\346\210\252\345\261\2172026-06-17 22.26.30.png"new file mode 100644index 000000000..49f13316aBinary files /dev/null and "b/assets/figs/web-1.4.6+/settings/\346\210\252\345\261\2172026-06-17 22.26.30.png" differdiff --git a/assets/releases/ver1-4-7.md b/assets/releases/ver1-4-7.mdnew file mode 100644index 000000000..5c9e5c51c--- /dev/null+++ b/assets/releases/ver1-4-7.md@@ -0,0 +1,71 @@+# DeepTutor v1.4.7 Release Notes++**Release Date:** 2026.06.18++A focused release on top of [v1.4.6](ver1-4-6.md): your local coding agents+become something DeepTutor can talk to. Connect **Claude Code** or **Codex**+running on your machine as a knowledge source, and chat consults it live+mid-turn. **My Agents** graduates to a top-level destination, Partner+conversations gain branch / resume / delete with a replayable trace, and the+EduHub skill browser and voice providers are sturdier. Drop-in — no migrations.++> **Everything new is opt-in.** Connecting a local agent needs the Claude Code+> or Codex CLI already installed on the machine running DeepTutor — nothing is+> detected or launched until you connect one. **My Agents** moved from+> `/space/agents` to a top-level `/agents` (same content, new home). Existing+> data loads as-is; nothing to migrate.++## What's New++### Connected Agents — Consult Your Local Claude Code / Codex++You can now point a knowledge base at a **live agent CLI on your own machine**+and consult it from chat:++- DeepTutor detects an installed **Claude Code** or **Codex** and connects it as+ a new `subagent` knowledge source — a pointer to the CLI plus an optional+ working directory, with nothing indexed or copied.+- Select that agent in the composer and the turn runs on a single+ `consult_subagent` tool: the model asks your local agent, watches its run+ stream in, and goes back and forth up to a per-turn budget before answering+ you in its own voice.+- Configure each backend at `/settings/agents`.++### My Agents, Now Top-Level++The **My Agents** hub moves out of the Learning Space to its own destination at+`/agents`, with two halves: the live agents you've **connected** (above), and+the Claude Code / Codex chat histories you've **imported** as resumable agents.++### Partners: Branch, Resume, and a Replayable Trace++Partner conversations got sturdier on both IM and the web:++- New slash commands — `/branch`, `/stop`, `/sessions`, `/resume`, `/delete` —+ join `/help`, `/new`, `/status`, `/history`, and `/tool`.+- The web Partner chat now persists each turn's thinking/tool trace and+ **rehydrates** it into the collapsible activity panel when you reopen a+ conversation, switch sessions, or branch — matching product chat.+- Conversations carry **real auto-derived titles**, and you can branch, resume,+ or delete them from either surface.+- Built-in tools are now configurable per Partner alongside the toggleable+ system tools.++### Sturdier EduHub & Voice++The **EduHub** skill browser is a full in-app catalog now — search and preview+registry skills before importing — and a new `[EduHub]` issue template routes+registry bug reports to the main repo. On the **voice** side, providers surface+HTTP errors with status and body instead of a generic failure, and STT accepts+raw PCM streams (converted to WAV server-side).++## Upgrade Notes++- Drop-in from v1.4.6: `pip install -U deeptutor`; Docker users pull+ `ghcr.io/hkuds/deeptutor:latest`. No migrations.+- Connected Agents require the Claude Code and/or Codex CLI installed on the+ host running DeepTutor — they are detected, never installed for you.+- The docs at [deeptutor.info](https://deeptutor.info/) are still catching up to+ the recent releases and will be refreshed shortly.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.4.6...v1.4.7diff --git a/deeptutor/__version__.py b/deeptutor/__version__.pyindex 841ab1ab7..df94bee9c 100644--- a/deeptutor/__version__.py+++ b/deeptutor/__version__.py@@ -6,6 +6,6 @@ before publishing to PyPI; the web sidebar badge and CLI banner read from thisfile directly."""-__version__ = "1.4.6"+__version__ = "1.4.7"__all__ = ("__version__",)diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.pyindex 884b1a834..03992d056 100644--- a/deeptutor/agents/_shared/tool_composition.py+++ b/deeptutor/agents/_shared/tool_composition.py@@ -24,30 +24,19 @@ from collections.abc import Iterablefrom dataclasses import dataclassfrom typing import Any-from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES, USER_TOGGLEABLE_TOOL_NAMES+from deeptutor.tools.builtin import (+ BUILTIN_TOOL_NAMES,+ CONFIGURABLE_BUILTIN_TOOL_NAMES,+ USER_TOGGLEABLE_TOOL_NAMES,+)# Tools whose mounting is owned by the pipeline (auto-on under specific-# context conditions), not by the user's composer toggles. Adding a tool-# here hides it from ``{tool_list}`` until its corresponding condition-# fires in :func:`compose_enabled_tools`.-AUTO_MOUNTED_TOOLS: frozenset[str] = frozenset(- {- "rag",- "read_source",- "read_memory",- "write_memory",- "read_skill",- "load_tools",- "exec",- "code_execution",- "list_notebook",- "write_note",- "ask_user",- "web_fetch",- "github",- "cron",- }-)+# context conditions), not by the user's composer toggles. Membership here+# hides the tool from ``{tool_list}`` until its corresponding condition fires+# in :func:`compose_enabled_tools`. Derived from+# ``CONFIGURABLE_BUILTIN_TOOL_NAMES`` so the partner config surface and the+# auto-mount set can never drift apart.+AUTO_MOUNTED_TOOLS: frozenset[str] = frozenset(CONFIGURABLE_BUILTIN_TOOL_NAMES)# Conditional auto-mounts: tool name -> the ``ToolMountFlags`` attribute that# gates it. Single source of truth shared by the default composition (mount@@ -111,6 +100,7 @@ def compose_enabled_tools(mount_flags: ToolMountFlags,capability_owned: Iterable[str] = (),exclusive: bool = False,+ builtin_whitelist: set[str] | None = None,) -> list[str]:"""Compose the per-turn enabled-tool list.@@ -136,6 +126,15 @@ def compose_enabled_tools(runs only on ``capability_owned`` plus the ``ask_user`` floor — no built-ins,no composer toggles, no conditional mounts. The capability owns the surface.+ ``builtin_whitelist`` gates the *built-in* auto-mounts (steps 2 and 4 —+ the :data:`AUTO_MOUNTED_TOOLS` members). ``None`` (the product-chat default)+ means "no gating": every built-in mounts under its usual context condition,+ exactly as before. A set restricts which built-ins may mount — partners use+ this so an owner can deny e.g. ``read_memory`` to an IM-facing companion.+ It never *adds* tools (a built-in still needs its context gate); it only+ subtracts. User-toggled tools (step 1) and capability-owned tools (step 3)+ are unaffected — they have their own gates.+The result is ordered and deduplicated. ``optional_whitelist`` is stillexpected to exclude ``AUTO_MOUNTED_TOOLS`` via :func:`default_optional_tools`."""@@ -143,20 +142,21 @@ def compose_enabled_tools(owned = [str(name) for name in capability_owned if str(name).strip()]return _ordered_unique([*owned, "ask_user"])+ def _builtin_allowed(name: str) -> bool:+ return builtin_whitelist is None or name in builtin_whitelist+composed: list[str] = [tool.namefor tool in registry.get_enabled(requested_tools or [])if tool.name in optional_whitelist]for tool_name, flag in _CONDITIONAL_MOUNT_FLAGS.items():- if getattr(mount_flags, flag):+ if getattr(mount_flags, flag) and _builtin_allowed(tool_name):composed.append(tool_name)composed.extend(str(name) for name in capability_owned if str(name).strip())- composed.append("write_memory")- composed.append("web_fetch")- composed.append("github")- composed.append("ask_user")- composed.append("cron")+ for always_on in ("write_memory", "web_fetch", "github", "ask_user", "cron"):+ if _builtin_allowed(always_on):+ composed.append(always_on)return _ordered_unique(composed)diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.pyindex 1b1f19250..d1c6a5047 100644--- a/deeptutor/agents/chat/agent_loop.py+++ b/deeptutor/agents/chat/agent_loop.py@@ -232,7 +232,7 @@ class AgentLoop:"""explore_label = self.pipeline._t("labels.exploring", default="Exploring")nudged_empty_finish = False- for _round in range(max(1, self.pipeline.max_rounds)):+ for _round in range(max(1, self.pipeline.effective_max_rounds(self.context))):try:result = await self._call_llm(messages=messages,diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex 2038957e5..52c0536e8 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -260,6 +260,21 @@ class AgenticChatPipeline:def max_rounds(self) -> int:return max(1, self._max_rounds)+ def effective_max_rounds(self, context: UnifiedContext) -> int:+ """Round budget for this turn, lifted to satisfy any capability minimum.++ A capability that needs guaranteed loop headroom — the subagent+ capability, which must allow its full consult budget plus a finishing+ round — sets ``context.metadata["_min_loop_rounds"]``; the loop honours+ the larger of that and the configured budget. A generic seam (like+ solve's ``solve_max_replans``) so the loop stays capability-agnostic.+ """+ try:+ floor = int(context.metadata.get("_min_loop_rounds") or 0)+ except (TypeError, ValueError):+ floor = 0+ return max(self.max_rounds, floor)+@propertydef exploring_max_tokens(self) -> int:return max(128, self._exploring_max_tokens)@@ -281,7 +296,7 @@ class AgenticChatPipeline:async def run(self, context: UnifiedContext, stream: StreamBus) -> None:await self._prepare_deferred_tools(context)- self._exec_enabled = await self._exec_allowed()+ self._exec_enabled = await self._exec_allowed(context)enabled_tools = self._compose_enabled_tools(context)use_native_tools = bool(enabled_tools) and self._can_use_native_tool_calling()tool_schemas = (@@ -450,10 +465,16 @@ class AgenticChatPipeline:language=self.language,)- async def _exec_allowed(self) -> bool:+ async def _exec_allowed(self, context: UnifiedContext) -> bool:try:from deeptutor.services.sandbox import IsolationLevel, get_sandbox_service+ # A partner turn runs as a synthetic non-admin user but IS the admin+ # owner's extension (partners are anchored to the admin workspace), so+ # exec follows the owner's authority — not the partner's "user" role.+ # The owner still gates exec per-partner via the builtin-tool whitelist.+ is_partner = str((context.metadata or {}).get("source")) == "partner"+level = await get_sandbox_service().isolation_level()if level is IsolationLevel.SYSTEM:# Admin can switch exec off per user (grant v2). ``None``@@ -462,6 +483,8 @@ class AgenticChatPipeline:return exec_override() is not Falseif level is IsolationLevel.APPLICATION:+ if is_partner:+ return Truetry:from deeptutor.multi_user.context import get_current_user@@ -495,6 +518,11 @@ class AgenticChatPipeline:),capability_owned=self._capability_owned_tools(context),exclusive=self._exclusive_capability_active(context),+ builtin_whitelist=(+ set(context.allowed_builtin_tools)+ if context.allowed_builtin_tools is not None+ else None+ ),)return _drop_unconfigured_generation_tools(composed)@@ -927,6 +955,17 @@ class AgenticChatPipeline:call_kind="media_generation",query=str(tool_args.get("prompt", "") or ""),)+ # consult_subagent drives a live local agent that runs for as long as it+ # needs: wiring retrieve_meta gives it an event_sink so every native+ # output/log streams to the sidebar in real time (and keeps the+ # idle-timeout watchdog fed during a long agent run).+ if tool_name == "consult_subagent":+ return derive_trace_metadata(+ tool_meta,+ label=self._t("labels.consult_subagent", default="Consult agent"),+ call_kind="subagent_consult",+ query=str(tool_args.get("question", "") or ""),+ )return None# ---- KB seed ---------------------------------------------------------diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yamlindex 30d769f35..447c1f45b 100644--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml@@ -4,6 +4,7 @@ labels:exploring: "Exploring"tool_call: "Tool call"retrieve: "Retrieve"+ consult_subagent: "Consult agent"final_response: "Final response"general: |-diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yamlindex df18e45c7..b8e1f23a2 100644--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml@@ -4,6 +4,7 @@ labels:exploring: "探索"tool_call: "调用工具"retrieve: "检索"+ consult_subagent: "咨询智能体"final_response: "生成回答"general: |-diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 80000b352..2249b9add 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -308,6 +308,7 @@ from deeptutor.api.routers import (sessions,settings,skills,+ subagents,system,unified_ws,voice,@@ -387,6 +388,9 @@ app.include_router(dependencies=_auth,)app.include_router(skills.router, prefix="/api/v1/skills", tags=["skills"], dependencies=_auth)+app.include_router(+ subagents.router, prefix="/api/v1/subagents", tags=["subagents"], dependencies=_auth+)app.include_router(personas.router, prefix="/api/v1/personas", tags=["personas"], dependencies=_auth)diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.pyindex 154b1ac8a..fda24bbe4 100644--- a/deeptutor/api/routers/partners.py+++ b/deeptutor/api/routers/partners.py@@ -123,6 +123,7 @@ class CreatePartnerRequest(BaseModel):color: str | None = Noneavatar: str | None = Noneenabled_tools: list[str] | None = None+ builtin_tools: list[str] | None = Nonemcp_tools: list[str] | None = Noneassets: AssetSpec | None = Nonestart: bool = True@@ -139,6 +140,7 @@ class UpdatePartnerRequest(BaseModel):color: str | None = Noneavatar: str | None = Noneenabled_tools: list[str] | None = None+ builtin_tools: list[str] | None = Nonemcp_tools: list[str] | None = None@@ -163,11 +165,21 @@ class ChatMessageRequest(BaseModel):content: str = ""session_id: str | None = None+ session_key: str | None = Nonechat_id: str | None = Noneattachments: list[ChatAttachmentRequest] = Field(default_factory=list)llm_selection: dict[str, str] | None = Field(default=None, alias="llmSelection")+class SessionKeyBody(BaseModel):+ session_key: str = Field(..., min_length=1)+++class SessionBranchBody(BaseModel):+ source_key: str = Field(..., min_length=1)+ new_key: str = Field(..., min_length=1)++class SoulCreateRequest(BaseModel):id: strname: str@@ -407,8 +419,10 @@ async def tool_options():"""The configurable tool surface for a partner.``tools`` mirrors the user-toggleable system tools (the same pool the- chat composer / settings expose); ``mcp_tools`` lists every configured- MCP tool the partner could be allowed to load.+ chat composer / settings expose); ``builtin_tools`` lists the auto-mounted+ built-in tools (rag / read_memory / web_fetch / …) the owner can allow or+ deny; ``mcp_tools`` lists every configured MCP tool the partner could be+ allowed to load."""from deeptutor.api.utils.tool_options import build_tool_options@@ -446,6 +460,7 @@ async def create_partner(payload: CreatePartnerRequest):avatar=_validate_avatar_payload(payload.avatar),soul_origin=soul_origin,enabled_tools=payload.enabled_tools,+ builtin_tools=payload.builtin_tools,mcp_tools=payload.mcp_tools,)mgr.save_config(partner_id, config, auto_start=bool(payload.start))@@ -499,6 +514,7 @@ def _stopped_partner_dict("avatar": cfg.avatar,"soul_origin": cfg.soul_origin,"enabled_tools": cfg.enabled_tools,+ "builtin_tools": cfg.builtin_tools,"mcp_tools": cfg.mcp_tools,"running": False,"started_at": None,@@ -552,6 +568,8 @@ def _apply_update(cfg: PartnerConfig, payload: UpdatePartnerRequest) -> None:cfg.backup_llm_selection = _validate_llm_selection_payload(payload.backup_llm_selection)if "enabled_tools" in payload.model_fields_set:cfg.enabled_tools = payload.enabled_tools+ if "builtin_tools" in payload.model_fields_set:+ cfg.builtin_tools = payload.builtin_toolsif "mcp_tools" in payload.model_fields_set:cfg.mcp_tools = payload.mcp_tools@@ -593,6 +611,10 @@ async def update_partner(partner_id: str, payload: UpdatePartnerRequest):@router.post("/{partner_id}/start")async def start_partner(partner_id: str):instance = await _ensure_running_partner(partner_id, allow_stopped=True)+ # An explicit start is a persisted "run on boot" intent — so the partner+ # comes back in this state after a DeepTutor restart (a manual /stop clears+ # it; a lazy chat-driven start does NOT reach here, so it can't flip it).+ get_partner_manager().save_config(partner_id, instance.config, auto_start=True)return instance.to_dict(mask_secrets=True)@@ -694,9 +716,16 @@ async def delete_partner_asset(partner_id: str, asset_type: str, name: str):async def get_partner_history(partner_id: str,session_key: str | None = None,+ session_id: str | None = None,limit: int = 100,):- return get_partner_manager().get_history(partner_id, session_key=session_key, limit=limit)+ """Conversation history. Pass ``session_key`` for an exact key, or+ ``session_id`` for a web session (mapped through ``web_session_key``);+ with neither, all non-archived sessions are merged."""+ mgr = get_partner_manager()+ if session_id and not session_key:+ session_key = mgr.web_session_key(partner_id, session_id=session_id)+ return mgr.get_history(partner_id, session_key=session_key, limit=limit)@router.get("/{partner_id}/sessions")@@ -707,6 +736,51 @@ async def get_partner_sessions(partner_id: str):return mgr.session_store(partner_id).list_sessions()[email protected]("/{partner_id}/sessions/archive")+async def archive_partner_session(partner_id: str, payload: SessionKeyBody):+ """Soft-archive a session (web /new) — it stays resumable, file untouched."""+ mgr = get_partner_manager()+ if not mgr.partner_exists(partner_id):+ raise HTTPException(status_code=404, detail=t("api.partner_not_found"))+ mgr.archive_session(partner_id, payload.session_key)+ return {"partner_id": partner_id, "archived": True, "session_key": payload.session_key}++[email protected]("/{partner_id}/sessions/resume")+async def resume_partner_session(partner_id: str, payload: SessionKeyBody):+ """Clear a session's archived flag so the web app can continue it."""+ mgr = get_partner_manager()+ if not mgr.partner_exists(partner_id):+ raise HTTPException(status_code=404, detail=t("api.partner_not_found"))+ summary = mgr.resume_session(partner_id, payload.session_key)+ if summary is None:+ raise HTTPException(status_code=404, detail="Session not found")+ return {"partner_id": partner_id, "resumed": True, "session": summary}++[email protected]("/{partner_id}/sessions/delete")+async def delete_partner_session(partner_id: str, payload: SessionKeyBody):+ mgr = get_partner_manager()+ if not mgr.partner_exists(partner_id):+ raise HTTPException(status_code=404, detail=t("api.partner_not_found"))+ removed = mgr.delete_session(partner_id, payload.session_key)+ if not removed:+ raise HTTPException(status_code=404, detail="Session not found")+ return {"partner_id": partner_id, "deleted": True, "session_key": payload.session_key}++[email protected]("/{partner_id}/sessions/branch")+async def branch_partner_session(partner_id: str, payload: SessionBranchBody):+ """Copy a session's full history into a new key and archive the source."""+ mgr = get_partner_manager()+ if not mgr.partner_exists(partner_id):+ raise HTTPException(status_code=404, detail=t("api.partner_not_found"))+ summary = mgr.branch_session(partner_id, payload.source_key, payload.new_key)+ if summary is None:+ raise HTTPException(status_code=400, detail="Nothing to branch (source is empty)")+ return {"partner_id": partner_id, "branched": True, "session": summary}++@router.get("/commands/palette")async def partner_command_palette():from deeptutor.services.partners.commands import partner_command_palette@@ -808,6 +882,7 @@ async def partner_chat_http(partner_id: str, payload: ChatMessageRequest) -> dicchat_id=chat_id,session_id=session_id,media=media_paths,+ session_key=payload.session_key,)except RuntimeError as exc:raise HTTPException(status_code=400, detail=str(exc)) from None@@ -850,6 +925,7 @@ async def _partner_chat_stream(session_id=session_id,media=media_paths,on_event=on_event,+ session_key=payload.session_key,)except Exception as exc: # noqa: BLE001holder["error"] = str(exc)@@ -935,6 +1011,36 @@ async def partner_chat_ws(ws: WebSocket, partner_id: str):logger.info("WebSocket connected for partner '%s'", partner_id)+ # Web turns run on the partner instance (see LiveTurn), NOT tied to this+ # socket — so a refresh reattaches and replays instead of killing the turn.+ # The socket just drains a subscriber queue; the receive loop stays free to+ # process stop / attach frames concurrently.+ drain: dict[str, asyncio.Task | None] = {"task": None}++ async def _drain(queue: asyncio.Queue) -> None:+ while True:+ frame = await queue.get()+ if not await _safe_send(frame):+ return+ if frame.get("type") in {"done", "stopped"}:+ return++ def _start_drain(queue: asyncio.Queue) -> None:+ prev = drain["task"]+ if prev is not None and not prev.done():+ prev.cancel()+ drain["task"] = asyncio.create_task(_drain(queue))++ def _resolve_key(data: dict[str, Any]) -> str:+ return str(+ data.get("session_key")+ or mgr.web_session_key(+ partner_id,+ chat_id=data.get("chat_id", "web"),+ session_id=data.get("session_id"),+ )+ )+async def _handle_user_messages():while not disconnected.is_set():try:@@ -949,6 +1055,21 @@ async def partner_chat_ws(ws: WebSocket, partner_id: str):breakcontinue+ action = data.get("action")+ if action == "stop":+ mgr.stop_web_turn(partner_id, _resolve_key(data))+ continue+ if action == "attach":+ # Reconnect (a page refresh) — replay an in-flight turn so the+ # streaming answer the user was watching survives the reload.+ turn = mgr.subscribe_web_turn(partner_id, _resolve_key(data))+ if turn is not None:+ await _safe_send({"type": "resuming"})+ if turn.user_content:+ await _safe_send({"type": "user_echo", "content": turn.user_content})+ _start_drain(turn.subscribe())+ continue+content = data.get("content", "").strip()try:attachments = [@@ -972,38 +1093,13 @@ async def partner_chat_ws(ws: WebSocket, partner_id: str):if not content and media_paths:content = _default_attachment_prompt(attachments)- async def on_event(event: Any) -> None:- # Best-effort: never raise into the runner. A vanished- # client just stops receiving frames; the turn finishes- # server-side and lands in the session store.- try:- await _safe_send({"type": "stream_event", "event": event.to_dict()})- except Exception:- pass-try:- response = await mgr.send_message(- partner_id,- content,- chat_id=data.get("chat_id", "web"),- session_id=data.get("session_id"),- media=media_paths,- on_event=on_event,- )- if not await _safe_send({"type": "content", "content": response}):- break- if not await _safe_send({"type": "done"}):- break+ turn = mgr.start_web_turn(partner_id, _resolve_key(data), content, media_paths)except RuntimeError as exc:if not await _safe_send({"type": "error", "content": str(exc)}):break- except WebSocketDisconnect:- disconnected.set()- break- except Exception:- logger.exception("Error processing message for partner '%s'", partner_id)- if not await _safe_send({"type": "error", "content": "Internal error"}):- break+ continue+ _start_drain(turn.subscribe())async def _handle_notifications():while not disconnected.is_set():@@ -1043,6 +1139,11 @@ async def partner_chat_ws(ws: WebSocket, partner_id: str):user_task.cancel()notify_task.cancel()finally:+ # Detach from the stream only — the turn keeps running on the instance+ # so a reconnecting client can reattach and replay it.+ d = drain["task"]+ if d is not None and not d.done():+ d.cancel()if user_token is not None:try:reset_current_user(user_token)diff --git a/deeptutor/api/routers/skills.py b/deeptutor/api/routers/skills.pyindex 8259270ba..3e71d18ad 100644--- a/deeptutor/api/routers/skills.py+++ b/deeptutor/api/routers/skills.py@@ -137,6 +137,56 @@ async def list_skills() -> dict[str, list[dict[str, object]]]:return {"skills": merged}+# ── hub browse (in-app EduHub skill browser; declared before `/{name}`) ──++[email protected]("/hub/catalog")+async def hub_catalog(hub: str = "eduhub", q: str = "", limit: int = 50) -> dict[str, object]:+ """Proxy a skill hub's public catalog for the in-app browser.++ The web "Import from EduHub" panel renders these rows in DeepTutor's own+ UI — no embedded iframe, no login — so users can browse, search, and+ one-click download skills. Returns ``web_url`` (the hub's site origin) so+ the panel can offer a "view on EduHub" link out.+ """+ import asyncio++ from deeptutor.services.skill.hub import ClawHubProvider, HubError, get_hub_provider++ try:+ provider = get_hub_provider(hub)+ except HubError as exc:+ raise HTTPException(status_code=400, detail=str(exc))+ if not isinstance(provider, ClawHubProvider):+ raise HTTPException(status_code=400, detail=f"Hub `{hub}` does not support browsing.")+ try:+ skills = await asyncio.to_thread(provider.catalog, query=q, limit=limit)+ except HubError as exc:+ raise HTTPException(status_code=502, detail=str(exc))+ return {"hub": provider.name, "web_url": provider.web_origin, "skills": skills}++[email protected]("/hub/detail")+async def hub_detail(slug: str, hub: str = "eduhub") -> dict[str, object]:+ """Full metadata + SKILL.md body for one hub skill (browser detail view)."""+ import asyncio++ from deeptutor.services.skill.hub import ClawHubProvider, HubError, get_hub_provider++ try:+ provider = get_hub_provider(hub)+ except HubError as exc:+ raise HTTPException(status_code=400, detail=str(exc))+ if not isinstance(provider, ClawHubProvider):+ raise HTTPException(status_code=400, detail=f"Hub `{hub}` does not support browsing.")+ try:+ detail = await asyncio.to_thread(provider.detail, slug)+ except HubError as exc:+ raise HTTPException(status_code=502, detail=str(exc))+ detail["web_url"] = f"{provider.web_origin}/skills/{slug}"+ return detail++@router.get("/{name}")async def get_skill(name: str) -> dict[str, object]:service = get_skill_service()diff --git a/deeptutor/api/routers/subagents.py b/deeptutor/api/routers/subagents.pynew file mode 100644index 000000000..4fd6ab8a3--- /dev/null+++ b/deeptutor/api/routers/subagents.py@@ -0,0 +1,276 @@+"""Subagent connections API.++Backs the "My Agents → connected agents" feature: detect which local agent CLIs+(Claude Code / Codex) are installed on this machine, connect one as a pointer KB+the chat composer can select, and configure the consult budget. Connections are+stored as ``type: subagent`` knowledge bases (per-user, via the KB manager), so+they ride the same selection/persistence path as the other connected KB types —+the subagent capability drives them live, nothing is indexed.++The CLIs run on the host with the host user's own credentials, so detection is+machine-global; whether a connection is usable is simply "is the CLI installed+here". If it isn't, the UI just doesn't offer it.+"""++from __future__ import annotations++import asyncio+import json+import logging++from fastapi import APIRouter, Depends, HTTPException+from fastapi.responses import StreamingResponse+from pydantic import BaseModel, Field++from deeptutor.api.routers.auth import require_admin+from deeptutor.knowledge.kb_types import SUBAGENT_KB_TYPE+from deeptutor.multi_user.knowledge_access import current_kb_manager+from deeptutor.services.rag.linked_kb import assert_path_allowed+from deeptutor.services.subagent import (+ detect_all,+ list_backend_kinds,+ load_subagent_settings,+ save_subagent_settings,+ settings_from_dict,+)++logger = logging.getLogger(__name__)+router = APIRouter()+++class ConnectSubagentRequest(BaseModel):+ name: str+ agent_kind: str+ cwd: str = ""+++class SubagentSettingsPayload(BaseModel):+ consult_budget: int | None = None+ backends: dict[str, dict] | None = Field(default=None)+++class SubagentMessageRequest(BaseModel):+ chat_session_id: str = ""+ message: str++[email protected]("/detect")+async def detect_subagents():+ """Report which agent CLIs are installed and usable on this machine."""+ detections = await detect_all()+ return {"backends": [d.to_dict() for d in detections]}++[email protected]("/backends/options")+async def backend_options():+ """Synced model + reasoning-effort options per backend (settings page sync)."""+ from deeptutor.services.subagent.models import list_backend_options++ options = await list_backend_options()+ return {"backends": [o.to_dict() for o in options]}++[email protected]("/backends/{kind}/sync")+async def sync_backend(kind: str):+ """Re-pull one backend's model catalog (the settings "sync" button).++ For Claude Code this scrapes its ``/model`` TUI live and caches the result;+ for Codex it re-reads the CLI-maintained cache.+ """+ from deeptutor.services.subagent import list_backend_kinds+ from deeptutor.services.subagent.models import sync_backend_options++ if kind not in list_backend_kinds():+ raise HTTPException(status_code=400, detail=f"Unknown agent kind: {kind!r}")+ options = await sync_backend_options(kind)+ return options.to_dict()++[email protected]("/connections")+async def list_connections():+ """List the current user's connected subagents."""+ manager = current_kb_manager()+ connections = []+ for name in manager.list_knowledge_bases():+ meta = manager.get_metadata(name)+ if not isinstance(meta, dict) or meta.get("type") != SUBAGENT_KB_TYPE:+ continue+ connections.append(+ {+ "name": name,+ "agent_kind": meta.get("agent_kind", ""),+ "cwd": meta.get("cwd", ""),+ "description": meta.get("description", ""),+ "created_at": meta.get("created_at"),+ "updated_at": meta.get("updated_at"),+ }+ )+ return {"connections": connections}++[email protected]("/connections")+async def create_connection(payload: ConnectSubagentRequest):+ """Connect a local agent CLI as a selectable subagent KB."""+ name = (payload.name or "").strip()+ agent_kind = (payload.agent_kind or "").strip()+ if not name or not agent_kind:+ raise HTTPException(status_code=400, detail="Both name and agent_kind are required.")+ if agent_kind not in list_backend_kinds():+ raise HTTPException(status_code=400, detail=f"Unknown agent kind: {agent_kind!r}")++ resolved_cwd = ""+ raw_cwd = (payload.cwd or "").strip()+ if raw_cwd:+ try:+ resolved_cwd = str(assert_path_allowed(raw_cwd))+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ try:+ manager = current_kb_manager()+ entry = manager.register_subagent_connection(name, agent_kind, cwd=resolved_cwd)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except Exception as exc: # pragma: no cover - defensive+ logger.error("Error connecting subagent: %s", exc)+ raise HTTPException(status_code=500, detail=str(exc)) from exc++ return {+ "status": "connected",+ "name": name,+ "agent_kind": entry["agent_kind"],+ "cwd": entry["cwd"],+ }++[email protected]("/connections/{name}")+async def delete_connection(name: str):+ """Disconnect a subagent (removes the pointer KB; touches no files)."""+ manager = current_kb_manager()+ meta = manager.get_metadata(name)+ if not isinstance(meta, dict) or meta.get("type") != SUBAGENT_KB_TYPE:+ raise HTTPException(status_code=404, detail=f"No connected subagent named {name!r}.")+ try:+ manager.delete_knowledge_base(name, confirm=True)+ except Exception as exc: # pragma: no cover - defensive+ logger.error("Error disconnecting subagent: %s", exc)+ raise HTTPException(status_code=500, detail=str(exc)) from exc+ # Drop any remembered live-session ids for this connection.+ from deeptutor.services.subagent.sessions import forget_connection++ forget_connection(name)+ return {"status": "disconnected", "name": name}+++def _ndjson(obj: dict) -> str:+ return json.dumps(obj, ensure_ascii=False) + "\n"++[email protected]("/connections/{name}/message")+async def message_connection(name: str, payload: SubagentMessageRequest):+ """Send a message straight to a connected subagent and stream its run.++ This is the sidebar's "talk to the agent directly" path: it resumes the same+ live session DeepTutor consults (shared via the cross-turn registry, keyed by+ chat session + connection), so the agent keeps full context. Streams the+ native run as newline-delimited JSON, in the same channel shape the chat WS+ uses, so the sidebar transcript renders it identically.+ """+ message = (payload.message or "").strip()+ if not message:+ raise HTTPException(status_code=400, detail="A non-empty 'message' is required.")++ manager = current_kb_manager()+ meta = manager.get_metadata(name)+ if not isinstance(meta, dict) or meta.get("type") != SUBAGENT_KB_TYPE:+ raise HTTPException(status_code=404, detail=f"No connected subagent named {name!r}.")++ from deeptutor.services.subagent import get_backend+ from deeptutor.services.subagent.sessions import get_session, remember_session, session_key++ kind = str(meta.get("agent_kind") or "")+ cwd = str(meta.get("cwd") or "")+ backend = get_backend(kind)+ if backend is None:+ raise HTTPException(status_code=400, detail=f"Unknown agent kind: {kind!r}")++ config = load_subagent_settings().backend(kind)+ skey = session_key(payload.chat_session_id, name) if payload.chat_session_id else ""+ resume_id = get_session(skey) if skey else None++ async def event_stream():+ queue: asyncio.Queue = asyncio.Queue()++ async def on_event(event) -> None:+ await queue.put(("event", event))++ async def run() -> None:+ try:+ res = await backend.consult(+ message,+ on_event=on_event,+ cwd=cwd or None,+ session_id=resume_id,+ config=config,+ )+ await queue.put(("done", res))+ except Exception as exc: # pragma: no cover - defensive+ logger.warning("subagent message failed: %s", exc, exc_info=True)+ await queue.put(("fail", str(exc)))++ task = asyncio.create_task(run())+ # The user's own message heads the exchange.+ yield _ndjson({"channel": "user_question", "text": message})+ try:+ while True:+ kind_, item = await queue.get()+ if kind_ == "event":+ line = {"channel": item.kind, "text": item.text}+ merge_id = (item.meta or {}).get("merge_id")+ if merge_id:+ # Namespace away from the chat turn's consult merge ids.+ line["merge_id"] = f"side:{merge_id}"+ yield _ndjson(line)+ elif kind_ == "done":+ if skey and item.session_id:+ remember_session(skey, item.session_id, kind=kind, cwd=cwd)+ yield _ndjson(+ {"done": True, "success": item.success, "session_id": item.session_id or ""}+ )+ break+ else: # fail+ yield _ndjson({"channel": "error", "text": item})+ yield _ndjson({"done": True, "success": False})+ break+ finally:+ if not task.done():+ await task++ return StreamingResponse(event_stream(), media_type="application/x-ndjson")++[email protected]("/settings")+async def get_settings():+ """Read the consult budget and per-backend run config."""+ return load_subagent_settings().to_dict()++[email protected]("/settings", dependencies=[Depends(require_admin)])+async def update_settings(payload: SubagentSettingsPayload):+ """Update the subagent settings (admin-gated; deployment-wide)."""+ merged = load_subagent_settings().to_dict()+ if payload.consult_budget is not None:+ merged["consult_budget"] = payload.consult_budget+ if payload.backends is not None:+ # Merge per backend (and per field) so saving one backend's settings+ # never clobbers the other's or any unsent field.+ backends = dict(merged.get("backends") or {})+ for kind, cfg in payload.backends.items():+ backends[str(kind)] = {**(backends.get(str(kind)) or {}), **(cfg or {})}+ merged["backends"] = backends+ settings = settings_from_dict(merged)+ save_subagent_settings(settings)+ return settings.to_dict()+++__all__ = ["router"]diff --git a/deeptutor/api/routers/voice.py b/deeptutor/api/routers/voice.pyindex e67820007..5a8d49acf 100644--- a/deeptutor/api/routers/voice.py+++ b/deeptutor/api/routers/voice.py@@ -8,7 +8,9 @@ may call it; it is not gated by per-user LLM grants.from __future__ import annotations+import ioimport logging+import wavefrom fastapi import APIRouter, File, Form, HTTPException, Response, UploadFile, statusfrom pydantic import BaseModel, Field@@ -25,6 +27,9 @@ router = APIRouter()# Guard against pathological uploads (the providers cap well below this anyway)._MAX_AUDIO_BYTES = 25 * 1024 * 1024 # 25 MB, matching OpenAI's limit.+_DEFAULT_PCM_SAMPLE_RATE = 24_000+_DEFAULT_PCM_CHANNELS = 1+_PCM16_SAMPLE_WIDTH = 2class TTSRequest(BaseModel):@@ -35,6 +40,41 @@ class TTSRequest(BaseModel):format: str | None = None+def _parse_pcm_content_type(content_type: str) -> tuple[int, int] | None:+ """Return ``(sample_rate, channels)`` when a provider sent raw PCM audio."""+ media_type, *params = (content_type or "").split(";")+ if media_type.strip().lower() not in {"audio/pcm", "audio/x-pcm", "audio/l16"}:+ return None+ sample_rate = _DEFAULT_PCM_SAMPLE_RATE+ channels = _DEFAULT_PCM_CHANNELS+ for item in params:+ key, sep, value = item.strip().partition("=")+ if not sep:+ continue+ key = key.strip().lower()+ value = value.strip().strip('"')+ try:+ parsed = int(value)+ except ValueError:+ continue+ if key in {"rate", "sample-rate", "samplerate"} and parsed > 0:+ sample_rate = parsed+ elif key in {"channels", "channel"} and parsed > 0:+ channels = parsed+ return sample_rate, channels+++def _pcm16_to_wav(audio: bytes, *, sample_rate: int, channels: int) -> bytes:+ """Wrap provider PCM16 bytes in a WAV container browsers can play."""+ buffer = io.BytesIO()+ with wave.open(buffer, "wb") as wav:+ wav.setnchannels(channels)+ wav.setsampwidth(_PCM16_SAMPLE_WIDTH)+ wav.setframerate(sample_rate)+ wav.writeframes(audio)+ return buffer.getvalue()++@router.post("/tts")async def text_to_speech(payload: TTSRequest) -> Response:"""Synthesize ``text`` to audio using the active TTS provider."""@@ -49,6 +89,11 @@ async def text_to_speech(payload: TTSRequest) -> Response:except VoiceProviderError as exc:logger.warning("TTS provider error: %s", exc)raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc+ pcm_info = _parse_pcm_content_type(content_type)+ if pcm_info:+ sample_rate, channels = pcm_info+ audio = _pcm16_to_wav(audio, sample_rate=sample_rate, channels=channels)+ content_type = "audio/wav"return Response(content=audio,media_type=content_type,diff --git a/deeptutor/api/utils/tool_options.py b/deeptutor/api/utils/tool_options.pyindex ff68301b8..7b32eeddc 100644--- a/deeptutor/api/utils/tool_options.py+++ b/deeptutor/api/utils/tool_options.py@@ -1,8 +1,10 @@"""Configurable-tool surface shared by the partners and multi-user admin APIs.``tools`` mirrors the user-toggleable system tools (the same pool the chat-composer / settings expose); ``mcp_tools`` lists every configured MCP tool-that a whitelist (partner config or user grant) could allow.+composer / settings expose); ``builtin_tools`` lists the auto-mounted built-in+tools (rag / read_memory / web_fetch / …) a partner owner can selectively+allow or deny; ``mcp_tools`` lists every configured MCP tool that a whitelist+(partner config or user grant) could allow."""from __future__ import annotations@@ -19,6 +21,7 @@ logger = logging.getLogger(__name__)async def build_tool_options() -> dict[str, list[dict[str, Any]]]:from deeptutor.agents._shared.tool_composition import default_optional_toolsfrom deeptutor.runtime.registry.tool_registry import get_tool_registry+ from deeptutor.tools.builtin import CONFIGURABLE_BUILTIN_TOOL_NAMESregistry = get_tool_registry()language = current_language()@@ -29,8 +32,7 @@ async def build_tool_options() -> dict[str, list[dict[str, Any]]]:except Exception:logger.debug("MCP manager unavailable for tool options", exc_info=True)- tools: list[dict[str, Any]] = []- for name in default_optional_tools():+ def _describe(name: str) -> dict[str, Any]:tool = registry.get(name)description = ""if tool is not None:@@ -39,13 +41,16 @@ async def build_tool_options() -> dict[str, list[dict[str, Any]]]:except Exception:description = ""descriptions = tool_description_i18n(name, description)- tools.append(- {- "name": name,- "description": localized_description(descriptions, language),- "description_i18n": descriptions,- }- )+ return {+ "name": name,+ "description": localized_description(descriptions, language),+ "description_i18n": descriptions,+ }++ tools: list[dict[str, Any]] = [_describe(name) for name in default_optional_tools()]+ builtin_tools: list[dict[str, Any]] = [+ _describe(name) for name in CONFIGURABLE_BUILTIN_TOOL_NAMES+ ]mcp_tools: list[dict[str, Any]] = []for tool in registry.deferred_tools():@@ -65,7 +70,7 @@ async def build_tool_options() -> dict[str, list[dict[str, Any]]]:})- return {"tools": tools, "mcp_tools": mcp_tools}+ return {"tools": tools, "builtin_tools": builtin_tools, "mcp_tools": mcp_tools}__all__ = ["build_tool_options"]diff --git a/deeptutor/capabilities/registry.py b/deeptutor/capabilities/registry.pyindex 0f47457d0..bec40a4e1 100644--- a/deeptutor/capabilities/registry.py+++ b/deeptutor/capabilities/registry.py@@ -7,12 +7,14 @@ from deeptutor.capabilities.mastery import MasteryLoopCapabilityfrom deeptutor.capabilities.obsidian import ObsidianCapabilityfrom deeptutor.capabilities.protocol import LoopCapabilityfrom deeptutor.capabilities.solve import SolveLoopCapability+from deeptutor.capabilities.subagent import SubagentCapabilityfrom deeptutor.core.context import UnifiedContextLOOP_CAPABILITIES: tuple[LoopCapability, ...] = (MasteryLoopCapability(),SolveLoopCapability(),ObsidianCapability(),+ SubagentCapability(),ExploreContextCapability(),)diff --git a/deeptutor/capabilities/subagent/__init__.py b/deeptutor/capabilities/subagent/__init__.pynew file mode 100644index 000000000..c7d3dfac7--- /dev/null+++ b/deeptutor/capabilities/subagent/__init__.py@@ -0,0 +1,26 @@+"""Subagent capability — consult a user's live local agent (Claude Code / Codex).++Selected like any connected KB: when the user picks a ``type: subagent`` KB, the+chat turn runs exclusively on the ``consult_subagent`` tool, driving the live CLI+through :mod:`deeptutor.services.subagent` and streaming its native run to the+sidebar. The chat model gathers what it needs across a bounded number of+consults, then answers the user itself.+"""++from __future__ import annotations++from deeptutor.capabilities.subagent.binding import connection_for_turn+from deeptutor.capabilities.subagent.capability import SubagentCapability+from deeptutor.capabilities.subagent.tools import (+ SUBAGENT_TOOL_NAMES,+ SUBAGENT_TOOL_TYPES,+ ConsultSubagentTool,+)++__all__ = [+ "SubagentCapability",+ "ConsultSubagentTool",+ "SUBAGENT_TOOL_NAMES",+ "SUBAGENT_TOOL_TYPES",+ "connection_for_turn",+]diff --git a/deeptutor/capabilities/subagent/binding.py b/deeptutor/capabilities/subagent/binding.pynew file mode 100644index 000000000..0f3c16de0--- /dev/null+++ b/deeptutor/capabilities/subagent/binding.py@@ -0,0 +1,53 @@+"""Resolve which connected subagent (if any) the current turn targets.++Mirrors :mod:`deeptutor.capabilities.obsidian.binding`: the binding is derived+once per turn from the user's selected knowledge bases — the first selection+whose KB metadata is ``type == subagent`` wins, and its ``agent_kind`` / ``cwd``+become the live connection the consult tool drives. Cached on+``context.metadata`` so ``is_active`` / ``augment_kwargs`` / ``system_block``+share one lookup. Pure read; access errors resolve to "no connection".+"""++from __future__ import annotations++from deeptutor.core.context import UnifiedContext+from deeptutor.knowledge.kb_types import SUBAGENT_KB_TYPE++# Cached on context.metadata: a {"name", "kind", "cwd"} dict, or "" once we've+# looked and found none. Absence of the key means "not resolved yet".+_CACHE_KEY = "_subagent_connection"+_UNSET = object()+++def connection_for_turn(context: UnifiedContext) -> dict[str, str] | None:+ """Return ``{"name", "kind", "cwd"}`` of the selected subagent, or ``None``."""+ cached = context.metadata.get(_CACHE_KEY, _UNSET)+ if cached is not _UNSET:+ return cached or None+ resolved = _resolve(context)+ context.metadata[_CACHE_KEY] = resolved or ""+ return resolved+++def _resolve(context: UnifiedContext) -> dict[str, str] | None:+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata++ for ref in context.knowledge_bases or []:+ ref = str(ref).strip()+ if not ref:+ continue+ meta = resolve_kb_metadata(ref)+ if not meta or meta.get("type") != SUBAGENT_KB_TYPE:+ continue+ kind = str(meta.get("agent_kind") or "").strip()+ if not kind:+ continue+ return {+ "name": str(meta.get("name") or ref),+ "kind": kind,+ "cwd": str(meta.get("cwd") or "").strip(),+ }+ return None+++__all__ = ["connection_for_turn"]diff --git a/deeptutor/capabilities/subagent/capability.py b/deeptutor/capabilities/subagent/capability.pynew file mode 100644index 000000000..8b441f4eb--- /dev/null+++ b/deeptutor/capabilities/subagent/capability.py@@ -0,0 +1,182 @@+"""Subagent loop capability — consult the user's live local agent as a delegate.++Active whenever the user's selected knowledge base is a connected subagent+(resolved by :mod:`deeptutor.capabilities.subagent.binding`). As a+:class:`KnowledgeCapability` it owns the turn: the chat loop runs exclusively on+the single ``consult_subagent`` tool (plus the ``ask_user`` floor). The chat+model decides what to ask, asks the local Claude Code / Codex up to the consult+budget, watches its streamed run, and then answers the user in its own voice.++The connection (which backend, working dir), the per-backend config and the+turn-scoped budget/session state are injected into each tool call server-side;+the model never supplies them.+"""++from __future__ import annotations++from typing import Any++from deeptutor.capabilities.protocol import KnowledgeCapability, PromptBlock+from deeptutor.capabilities.subagent.binding import connection_for_turn+from deeptutor.capabilities.subagent.tools import SUBAGENT_TOOL_NAMES+from deeptutor.core.context import UnifiedContext++# Headroom over the consult budget so the loop always has rounds left to write+# the final answer after the last consult. Read by the pipeline via+# ``context.metadata["_min_loop_rounds"]`` (a generic seam, like solve's+# ``solve_max_replans``) so a high budget is never clipped by the default round+# budget.+_FINISH_HEADROOM = 2+++class SubagentCapability(KnowledgeCapability):+ """Turn-scoped integration for a connected local subagent."""++ name = "subagent"+ owned_tools = SUBAGENT_TOOL_NAMES++ def is_active(self, context: UnifiedContext) -> bool:+ return connection_for_turn(context) is not None++ def system_block(+ self,+ context: UnifiedContext,+ *,+ language: str,+ prompts: dict[str, Any],+ ) -> PromptBlock | None:+ conn = connection_for_turn(context)+ if conn is None:+ return None+ budget = _resolve_budget(context)+ # Ensure the loop has room for ``budget`` consults plus the answer. This+ # runs once during prompt assembly, before the loop reads its round+ # budget — see ``_FINISH_HEADROOM``.+ context.metadata["_min_loop_rounds"] = budget + _FINISH_HEADROOM+ return PromptBlock("subagent", _system_text(language, conn["name"], budget))++ def augment_kwargs(+ self,+ tool_name: str,+ kwargs: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ if tool_name not in SUBAGENT_TOOL_NAMES:+ return kwargs+ conn = connection_for_turn(context)+ if conn is None:+ return kwargs+ from deeptutor.services.subagent import load_subagent_settings+ from deeptutor.services.subagent.sessions import get_session, session_key++ settings = load_subagent_settings()+ # Turn-scoped, mutable: persists across the loop's rounds via the shared+ # context object — the consult counter and the backend session id that+ # threads context across the model's successive questions.+ state = context.metadata.setdefault(+ "_subagent_state",+ {"count": 0, "session_id": None, "name": conn["name"]},+ )+ # Persistent continuity: on the first consult of a turn, seed the session+ # id from the cross-turn registry so we resume the SAME local agent+ # session the user/DeepTutor built up earlier (and the sidebar shares).+ chat_sid = str(getattr(context, "session_id", "") or "")+ skey = session_key(chat_sid, conn["name"]) if chat_sid else ""+ if skey and not state.get("_seeded"):+ state["_seeded"] = True+ if not state.get("session_id"):+ state["session_id"] = get_session(skey)+ config = _effective_config(settings.backend(conn["kind"]))+ # Multimodal: forward the turn's image attachments only when the user+ # opted this backend in (/settings → forward_images). The tool+ # materializes them to files the CLI can ingest.+ images = (+ [a for a in (context.attachments or []) if getattr(a, "type", "") == "image"]+ if getattr(config, "forward_images", False)+ else []+ )+ updated = dict(kwargs)+ updated["_subagent"] = {+ "kind": conn["kind"],+ "cwd": conn.get("cwd") or "",+ "name": conn["name"],+ "budget": _resolve_budget(context),+ "config": config,+ "state": state,+ "images": images,+ "session_key": skey,+ }+ return updated++ def pre_loop_seed(self, context: UnifiedContext) -> str:+ _ = context+ return ""+++# Default instruction injected (CC --append-system-prompt) so a consulted agent+# behaves like a delegate, not an interactive session, when the user hasn't set+# their own in /settings.+_DEFAULT_CONSULT_INSTRUCTION = (+ "You are being consulted programmatically by DeepTutor on the user's behalf, "+ "not in an interactive terminal. Answer the question directly, concisely, and "+ "self-contained. Do not ask the user follow-up questions or wait for input; "+ "if something is ambiguous, state your assumption and proceed."+)+++def _effective_config(config):+ """Fill product defaults the user hasn't overridden in /settings.++ Today: a default ``system_prompt`` so the consulted agent knows it's a+ delegate (applied by backends that support it, e.g. Claude Code).+ """+ if config.system_prompt.strip():+ return config+ from dataclasses import replace++ return replace(config, system_prompt=_DEFAULT_CONSULT_INSTRUCTION)+++def _resolve_budget(context: UnifiedContext) -> int:+ """Consult budget for this turn: a per-turn override from the chat composer+ (``config.subagent_consult_budget``) if present, else the configured default.+ """+ from deeptutor.services.subagent import load_subagent_settings+ from deeptutor.services.subagent.config import CONSULT_BUDGET_MAX, CONSULT_BUDGET_MIN++ overrides = context.config_overrides if isinstance(context.config_overrides, dict) else {}+ raw = overrides.get("subagent_consult_budget")+ if raw is not None:+ try:+ return max(CONSULT_BUDGET_MIN, min(CONSULT_BUDGET_MAX, int(raw)))+ except (TypeError, ValueError):+ pass+ return load_subagent_settings().consult_budget+++def _system_text(language: str, name: str, budget: int) -> str:+ if str(language or "en").lower().startswith("zh"):+ return (+ f"本轮你已连接到用户本机的外部智能体「{name}」。你可以通过 `consult_subagent` "+ f"工具向它提问,把它当作一个能在用户机器上读写文件、运行命令的得力助手来委派任务"+ f"(例如排查代码库、复现问题、运行脚本)。它的完整运行过程会实时展示给用户。\n\n"+ f"- 本轮最多可向它提问 {budget} 次;每次结果会告诉你还剩几次。它会在本轮内记住你"+ f"之前的提问,所以可以层层追问。\n"+ f"- 当你掌握了足够信息后,停止调用该工具,用你自己的口吻直接回答用户——"+ f"不要假借该智能体的身份或第一人称转述它的话。"+ )+ return (+ f"You are connected this turn to the user's local external agent “{name}”. "+ f"Consult it with the `consult_subagent` tool, delegating work it is better "+ f"placed to do on the user's machine — inspecting a codebase, reproducing a "+ f"bug, running commands. Its full run is shown to the user live.\n\n"+ f"- You may consult it at most {budget} time(s) this turn; each result tells "+ f"you how many remain. It remembers your earlier questions this turn, so you "+ f"can drill down.\n"+ f"- Once you have enough, stop calling the tool and answer the user directly "+ f"in your own voice — never impersonate the agent or relay its words in the "+ f"first person."+ )+++__all__ = ["SubagentCapability"]diff --git a/deeptutor/capabilities/subagent/tools.py b/deeptutor/capabilities/subagent/tools.pynew file mode 100644index 000000000..e9d25c307--- /dev/null+++ b/deeptutor/capabilities/subagent/tools.py@@ -0,0 +1,224 @@+"""The ``consult_subagent`` tool — the seam between the chat loop and a live agent.++One tool, auto-mounted only when a connected subagent is the selected KB (via+:class:`~deeptutor.capabilities.subagent.capability.SubagentCapability`, which+runs the turn exclusively on it). Each call puts one question to the local CLI,+streams every native event through the dispatcher's ``event_sink`` so the+sidebar shows the agent's real intermediate steps, and returns the agent's final+answer to the chat model.++Two server-owned pieces are injected by the capability's ``augment_kwargs`` and+never supplied by the model: ``_subagent`` (which backend, working dir, the+resolved per-backend config, and the turn-scoped budget/session state). The+model only ever supplies ``question``.++Budget: the turn-scoped state caps how many times the chat model may consult the+agent (the user's "max rounds"). Beyond it the tool refuses and tells the model+to answer — authoritative here, independent of how the loop batches rounds. The+same state carries the backend session id so successive consults resume the same+agent session and it keeps context across the model's questions.+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING, Any++from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult++if TYPE_CHECKING: # avoid importing the services package at module-load time (cycle)+ from deeptutor.services.subagent import SubagentEvent++logger = logging.getLogger(__name__)++SUBAGENT_TOOL_NAMES: tuple[str, ...] = ("consult_subagent",)++# Single trace_kind for every streamed subagent event; the fine-grained channel+# (text / tool / tool_result / reasoning / log / result) rides in metadata so the+# sidebar can render a CLI-faithful transcript while filtering on one key.+_TRACE_KIND = "subagent_event"+++class ConsultSubagentTool(BaseTool):+ """Put one question to the connected subagent and stream its native run."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="consult_subagent",+ description=(+ "Ask the connected external agent (the user's local Claude Code / "+ "Codex) a focused question and get its answer. The agent runs on the "+ "user's machine with access to their files and tools; its full "+ "step-by-step run is shown to the user live. Use it to delegate work "+ "the local agent is better placed to do — inspecting a codebase, "+ "running commands, reproducing a bug. You may consult it more than "+ "once to drill down, but you have a limited number of consults this "+ "turn (the result tells you how many remain). When you have enough, "+ "stop calling this tool and answer the user yourself in your own "+ "voice — never impersonate the agent."+ ),+ parameters=[+ ToolParameter(+ name="question",+ type="string",+ description=(+ "The question or task to put to the agent. Be specific and "+ "self-contained; the agent keeps context across your consults "+ "this turn, so each one can build on the last."+ ),+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ spec = kwargs.get("_subagent")+ if not isinstance(spec, dict):+ return ToolResult(+ content="No subagent is connected on this turn; consult_subagent is unavailable.",+ success=False,+ )+ question = str(kwargs.get("question") or "").strip()+ if not question:+ return ToolResult(content="consult_subagent needs a non-empty 'question'.", success=False)++ state = spec["state"]+ budget = int(spec["budget"])+ name = str(spec.get("name") or "the agent")+ if int(state.get("count", 0)) >= budget:+ return ToolResult(+ content=(+ f"[Consult budget reached: you have already asked {name} {budget} "+ "time(s) this turn — the maximum. Do not call consult_subagent "+ "again. Answer the user now with what you have gathered.]"+ ),+ success=False,+ )++ from deeptutor.services.subagent import get_backend++ backend = get_backend(str(spec.get("kind") or ""))+ if backend is None:+ return ToolResult(content=f"Unknown subagent backend: {spec.get('kind')!r}", success=False)++ state["count"] = int(state.get("count", 0)) + 1+ consult_index = state["count"]+ event_sink = kwargs.get("event_sink")++ async def _stream(+ channel: str, text: str, extra: dict[str, object] | None = None+ ) -> None:+ if event_sink is None or not text:+ return+ metadata: dict[str, object] = {+ "subagent_kind": backend.kind,+ "subagent_name": name,+ "subagent_channel": channel,+ "consult_index": consult_index,+ }+ # ``merge_id`` correlates a backend's start/finish (a web search) or+ # streaming deltas (the answer typing out) into one evolving row.+ # Namespace it by consult round so ids stay unique across the turn's+ # several consults (which share one transcript).+ merge_id = (extra or {}).get("merge_id")+ if merge_id:+ metadata["subagent_merge_id"] = f"{consult_index}:{merge_id}"+ await event_sink(_TRACE_KIND, text, metadata)++ async def on_event(event: SubagentEvent) -> None:+ await _stream(event.kind, event.text, event.meta)++ # Materialize any forwarded images (gated by the per-backend+ # ``forward_images`` setting) to a temp dir the CLI can ingest; cleaned up+ # in ``finally`` once the run ends.+ image_dir, image_paths = _stage_images(spec.get("images") or [])++ # Head this round with the question DeepTutor is putting to the agent, so+ # the transcript reads as a dialogue (esp. across several consults).+ await _stream("question", question)++ try:+ result = await backend.consult(+ question,+ on_event=on_event,+ cwd=spec.get("cwd") or None,+ session_id=state.get("session_id"),+ config=spec.get("config"),+ images=image_paths or None,+ )+ except Exception as exc: # pragma: no cover - defensive: surface, don't crash the turn+ logger.warning("consult_subagent failed: %s", exc, exc_info=True)+ return ToolResult(content=f"The subagent run failed: {exc}", success=False)+ finally:+ if image_dir is not None:+ import shutil++ shutil.rmtree(image_dir, ignore_errors=True)++ if result.session_id:+ state["session_id"] = result.session_id+ # Remember it across turns so the next turn (and the sidebar) resume+ # this same live agent session.+ session_key_value = spec.get("session_key")+ if session_key_value:+ from deeptutor.services.subagent.sessions import remember_session++ remember_session(+ str(session_key_value),+ result.session_id,+ kind=backend.kind,+ cwd=str(spec.get("cwd") or ""),+ )++ remaining = max(0, budget - consult_index)+ metadata = {+ "subagent_kind": backend.kind,+ "consult_index": consult_index,+ "consult_remaining": remaining,+ "event_count": result.event_count,+ }+ if not result.final_text:+ detail = result.error or "the agent produced no final answer text"+ return ToolResult(+ content=f"[The agent returned no answer: {detail}]",+ success=False,+ metadata=metadata,+ )++ budget_note = (+ f"\n\n[{remaining} consult(s) left with {name} this turn.]"+ if remaining > 0+ else f"\n\n[No consults left with {name} — answer the user now.]"+ )+ return ToolResult(+ content=result.final_text + budget_note,+ success=result.success,+ metadata=metadata,+ )+++def _stage_images(images: list[Any]) -> tuple[str | None, list[str]]:+ """Write forwarded image attachments to a temp dir for the CLI to ingest.++ Returns ``(dir, paths)`` — the caller removes ``dir`` once the run ends.+ ``(None, [])`` when there's nothing to forward.+ """+ if not images:+ return None, []+ from pathlib import Path+ import tempfile++ from deeptutor.services.subagent.images import materialize_images++ staging = tempfile.mkdtemp(prefix="dt-subagent-img-")+ paths = materialize_images(images, Path(staging))+ if not paths:+ import shutil++ shutil.rmtree(staging, ignore_errors=True)+ return None, []+ return staging, paths+++SUBAGENT_TOOL_TYPES: tuple[type[BaseTool], ...] = (ConsultSubagentTool,)++__all__ = ["SUBAGENT_TOOL_NAMES", "SUBAGENT_TOOL_TYPES", "ConsultSubagentTool"]diff --git a/deeptutor/core/context.py b/deeptutor/core/context.pyindex a3a7df32d..5c2f9a350 100644--- a/deeptutor/core/context.py+++ b/deeptutor/core/context.py@@ -42,6 +42,11 @@ class UnifiedContext:enabled_tools: Tool names the user has toggled on (Level 1).``None`` means "not specified", while ``[]`` means"explicitly disable all optional tools".+ allowed_builtin_tools: Whitelist gating the built-in auto-mounted tools+ (rag / read_memory / web_fetch / …). ``None`` (the product-chat+ default) means "no gating" — every built-in mounts under its usual+ context condition. A list restricts which built-ins may mount;+ partners set this so an owner can deny built-ins per companion.active_capability: Capability name selected by the user, or None for plain chat.knowledge_bases: KB names to use for RAG.attachments: Images / files sent with the message.@@ -66,6 +71,7 @@ class UnifiedContext:user_message: str = ""conversation_history: list[dict[str, Any]] = field(default_factory=list)enabled_tools: list[str] | None = None+ allowed_builtin_tools: list[str] | None = Noneactive_capability: str | None = Noneknowledge_bases: list[str] = field(default_factory=list)attachments: list[Attachment] = field(default_factory=list)diff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.pyindex ddf01881b..ccf456b5a 100644--- a/deeptutor/knowledge/kb_types.py+++ b/deeptutor/knowledge/kb_types.py@@ -13,12 +13,19 @@ flavours exist today:engine index the user built elsewhere (LlamaIndex / GraphRAG / LightRAG).Retrieval reads that index in place — the indexing step is skipped, and theKB is queried by its bound ``rag_provider`` exactly like an ordinary KB.+* ``subagent`` — a pointer to one of the user's *local* agent CLIs (Claude+ Code / Codex). It has no path on disk: ``agent_kind`` names the backend and+ an optional ``cwd`` is the working directory. There is nothing to index or+ retrieve — the subagent capability drives the live CLI through the+ ``consult_subagent`` tool. See ``capabilities/subagent``.-Both flavours share the same lifecycle quirks: no on-disk folder under+All connected flavours share the same lifecycle quirks: no on-disk folder under``base_dir``, no embedding reconcile, and deletion must never touch theexternal files. The :func:`is_connected_kb` / :func:`external_root_of` helperslet the manager treat them uniformly without sprinkling ``type`` literals-across the codebase.+across the codebase. ``subagent`` is connected but points at no folder, so+:func:`external_root_of` returns ``None`` for it — nothing resolves it to a+path because the capability owns the turn and never touches rag.Kept in its own low-level module so both :mod:`deeptutor.knowledge.manager`and the capability layer can import it without a cycle.@@ -38,9 +45,14 @@ OBSIDIAN_KB_TYPE = "obsidian"# it in place and retrieve via the bound provider — no copy, no re-index.LINKED_KB_TYPE = "linked"+# A connected subagent: a pointer to a local agent CLI (Claude Code / Codex).+# No path on disk — ``agent_kind`` names the backend, optional ``cwd`` is the+# working directory. Driven live via ``consult_subagent``; never indexed.+SUBAGENT_KB_TYPE = "subagent"+# Every pointer/connected KB type. Membership here is what makes the manager# skip the index pipeline, the orphan prune and the embedding reconcile.-CONNECTED_KB_TYPES = frozenset({OBSIDIAN_KB_TYPE, LINKED_KB_TYPE})+CONNECTED_KB_TYPES = frozenset({OBSIDIAN_KB_TYPE, LINKED_KB_TYPE, SUBAGENT_KB_TYPE})def is_connected_kb(entry: Any) -> bool:@@ -62,6 +74,7 @@ def external_root_of(entry: Any) -> str | None:__all__ = ["OBSIDIAN_KB_TYPE","LINKED_KB_TYPE",+ "SUBAGENT_KB_TYPE","CONNECTED_KB_TYPES","is_connected_kb","external_root_of",diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 67401fb4c..90bf8a410 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -20,6 +20,7 @@ from typing import Anyfrom deeptutor.knowledge.kb_types import (LINKED_KB_TYPE,OBSIDIAN_KB_TYPE,+ SUBAGENT_KB_TYPE,external_root_of,is_connected_kb,)@@ -781,6 +782,55 @@ class KnowledgeBaseManager:self._save_config()return entry+ def register_subagent_connection(+ self,+ name: str,+ agent_kind: str,+ *,+ cwd: str = "",+ description: str = "",+ ) -> dict:+ """Register a connected subagent (local Claude Code / Codex) as a KB.++ Like the other connected types this creates no folder and runs no index:+ it records a ``type: subagent`` pointer naming the backend (``agent_kind``)+ and an optional working directory (``cwd``). The subagent capability+ drives the live CLI; there is nothing on disk to retrieve or reconcile.+ Raises ``ValueError`` on a missing name/kind or a name clash.+ """+ name = (name or "").strip()+ agent_kind = (agent_kind or "").strip()+ if not name:+ raise ValueError("Connection name is required.")+ if not agent_kind:+ raise ValueError("agent_kind is required.")+ resolved_cwd = ""+ if cwd:+ folder = Path(cwd).expanduser()+ if not folder.is_dir():+ raise ValueError(f"Working directory is not a directory: {cwd}")+ resolved_cwd = str(folder.resolve())++ self.config = self._load_config()+ knowledge_bases = self.config.setdefault("knowledge_bases", {})+ if name in knowledge_bases:+ raise ValueError(f"A knowledge base named '{name}' already exists.")++ now = datetime.now().isoformat()+ entry = {+ "path": name,+ "type": SUBAGENT_KB_TYPE,+ "agent_kind": agent_kind,+ "cwd": resolved_cwd,+ "description": description or f"Connected subagent: {name}",+ "status": "ready",+ "created_at": now,+ "updated_at": now,+ }+ knowledge_bases[name] = entry+ self._save_config()+ return entry+def get_knowledge_base_path(self, name: str | None = None) -> Path:"""Get path to a knowledge base.@@ -923,6 +973,9 @@ class KnowledgeBaseManager:"type": kb_config.get("type"),"vault_path": kb_config.get("vault_path"),"external_path": kb_config.get("external_path"),+ # Subagent connection fields (None for non-subagent KBs).+ "agent_kind": kb_config.get("agent_kind"),+ "cwd": kb_config.get("cwd"),}metadata.update(self._embedding_fields(kb_config))# Remove None values@@ -1045,6 +1098,8 @@ class KnowledgeBaseManager:metadata["vault_path"] = kb_config.get("vault_path")if kb_config.get("external_path"):metadata["external_path"] = kb_config.get("external_path")+ if kb_config.get("agent_kind"):+ metadata["agent_kind"] = kb_config.get("agent_kind")metadata.update(self._embedding_fields(kb_config))@@ -1160,10 +1215,12 @@ class KnowledgeBaseManager:kb_dir = self.base_dir / namedir_exists = kb_dir.exists()- # Connected KBs (Obsidian vaults, linked indexes) point at the user's- # own external files. Deleting one must only drop our pointer entry —- # never touch the folder it references.- if is_connected_kb(config_kbs.get(name, {})):+ # Connected KBs (Obsidian vaults, linked indexes, subagent pointers)+ # reference the user's own external resource — or, for subagents, no+ # folder at all. Deleting one must only drop our pointer entry; never+ # touch what it references, and don't warn about the "missing" folder.+ connected = is_connected_kb(config_kbs.get(name, {}))+ if connected:dir_exists = Falseif not confirm:@@ -1198,7 +1255,7 @@ class KnowledgeBaseManager:)shutil.rmtree(kb_dir, onerror=_on_rmtree_error)- else:+ elif not connected:logger.warning(f"KB directory '{kb_dir}' missing on disk; cleaning up orphaned config entry.")diff --git a/deeptutor/partners/channels/telegram.py b/deeptutor/partners/channels/telegram.pyindex 451f7fc4c..e47235d0a 100644--- a/deeptutor/partners/channels/telegram.py+++ b/deeptutor/partners/channels/telegram.py@@ -707,8 +707,10 @@ class TelegramChannel(BaseChannel):returnuser = update.effective_user+ # No hard-coded brand here — the partner's own identity (its Soul) comes+ # through in conversation; the greeting just onboards the user.await update.message.reply_text(- f"👋 Hi {user.first_name}! I'm TutorBot.\n\n"+ f"👋 Hi {user.first_name}!\n\n""Send me a message and I'll respond!\n""Type /help to see available commands.")diff --git a/deeptutor/runtime/request_contracts.py b/deeptutor/runtime/request_contracts.pyindex 66c713e17..883ce92d4 100644--- a/deeptutor/runtime/request_contracts.py+++ b/deeptutor/runtime/request_contracts.py@@ -18,6 +18,10 @@ from deeptutor.agents.research.request_config import (_RUNTIME_ONLY_KEYS = {"_persist_user_message","followup_question_context",+ # Per-turn subagent consult budget (composer stepper). Not part of any+ # capability's public config schema; stripped here so it never trips+ # ``extra="forbid"`` (turn_runtime carries it through to the turn config).+ "subagent_consult_budget",}diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex bb8370e8f..cb16e75c7 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -228,6 +228,7 @@ TTS_PROVIDERS: dict[str, VoiceProviderSpec] = {"openrouter": VoiceProviderSpec(label="OpenRouter",default_api_base="https://openrouter.ai/api/v1",+ adapter="openrouter_tts",default_model="openai/gpt-4o-mini-tts",default_voice="alloy",),diff --git a/deeptutor/services/memory/__init__.py b/deeptutor/services/memory/__init__.pyindex be2436eb1..ee58e0c9d 100644--- a/deeptutor/services/memory/__init__.py+++ b/deeptutor/services/memory/__init__.py@@ -13,7 +13,7 @@ The v1 two-file `MemoryService` is gone. All callers go through"""from .ids import is_entry_id, is_trace_id, new_entry_id, new_trace_id-from .paths import L3_SLOTS, SURFACES, L3Slot, Surface+from .paths import L3_SLOTS, SURFACES, L3Slot, Surface, memory_path_service_overridefrom .store import (DocOverview,MemoryStore,@@ -34,6 +34,7 @@ __all__ = ["get_memory_store","is_entry_id","is_trace_id",+ "memory_path_service_override","migrate_partner_surface_if_needed","migrate_v1_if_needed","new_entry_id",diff --git a/deeptutor/services/memory/paths.py b/deeptutor/services/memory/paths.pyindex 052393f3d..87c44ccfa 100644--- a/deeptutor/services/memory/paths.py+++ b/deeptutor/services/memory/paths.py@@ -13,12 +13,37 @@ context (workspace_root) is picked up at call time, not import time.from __future__ import annotations+import contextlib+from contextvars import ContextVarfrom datetime import datefrom pathlib import Path-from typing import Literal, get_args+from typing import TYPE_CHECKING, Iterator, Literal, get_argsfrom deeptutor.services.path_service import get_path_service+if TYPE_CHECKING:+ from deeptutor.services.path_service import PathService++# When set, memory paths resolve through this PathService instead of the active+# user's. A partner runtime installs the *owner's* (admin) service for the+# duration of a turn so the chat agent's ``read_memory`` / ``write_memory``+# tools see the owner's memory — not the partner's own (empty) scope — while+# every *other* service (rag / skills / notebooks) stays on the partner scope.+_memory_path_service: ContextVar[PathService | None] = ContextVar(+ "memory_path_service", default=None+)+++def memory_path_service_override(service: PathService) -> Iterator[None]:+ """Resolve memory paths through *service* within this context."""+ token = _memory_path_service.set(service)+ try:+ yield+ finally:+ _memory_path_service.reset(token)++Surface = Literal["chat","notebook",@@ -35,7 +60,9 @@ L3_SLOTS: tuple[L3Slot, ...] = get_args(L3Slot)def memory_root() -> Path:- return get_path_service().get_memory_dir()+ override = _memory_path_service.get()+ service = override if override is not None else get_path_service()+ return service.get_memory_dir()def trace_dir(surface: Surface) -> Path:diff --git a/deeptutor/services/partners/commands.py b/deeptutor/services/partners/commands.pyindex 3d411ee18..7847224f7 100644--- a/deeptutor/services/partners/commands.py+++ b/deeptutor/services/partners/commands.py@@ -26,6 +26,11 @@ class PartnerCommandResult:BUILTIN_PARTNER_COMMANDS: tuple[PartnerCommandSpec, ...] = (PartnerCommandSpec("/help", "Show available partner commands."),PartnerCommandSpec("/new", "Archive this conversation and start a fresh one."),+ PartnerCommandSpec("/branch", "Archive this conversation and continue in a copy."),+ PartnerCommandSpec("/stop", "Stop the reply that's currently being generated."),+ PartnerCommandSpec("/sessions", "List this partner's conversations and their IDs."),+ PartnerCommandSpec("/resume", "Reopen an archived conversation.", "<session ID>"),+ PartnerCommandSpec("/delete", "Delete a conversation permanently.", "<session ID>"),PartnerCommandSpec("/status", "Show partner, session, model, and tool status."),PartnerCommandSpec("/history", "Show recent messages in this conversation.", "[n]"),PartnerCommandSpec("/tool", "Show or change enabled tools.", "[on|off <name>|reset]"),@@ -88,6 +93,16 @@ class PartnerCommandHandler:return PartnerCommandResult(build_partner_help_text())if command in {"/new", "/clear"}:return self._new(msg)+ if command == "/branch":+ return self._branch(msg)+ if command == "/stop":+ return PartnerCommandResult("There's nothing being generated to stop.")+ if command == "/sessions":+ return self._sessions()+ if command == "/resume":+ return self._resume(args)+ if command == "/delete":+ return self._delete(args)if command == "/status":return self._status(msg)if command == "/history":@@ -105,6 +120,49 @@ class PartnerCommandHandler:)return PartnerCommandResult("Started a new conversation. No prior messages to archive.")+ def _branch(self, msg: InboundMessage) -> PartnerCommandResult:+ # Branching to a *copy* needs a new session key, which only the web app+ # mints; on IM there is one session per chat, so degrade to /new.+ archived = self.store.archive(msg.session_key)+ if archived:+ return PartnerCommandResult(+ f"Archived this conversation as `{archived['session_key']}` and started fresh. "+ "To keep the full history in a new branch, use the web app."+ )+ return PartnerCommandResult("Nothing to branch yet.")++ def _sessions(self) -> PartnerCommandResult:+ sessions = self.store.list_sessions()+ if not sessions:+ return PartnerCommandResult("No conversations yet.")+ lines = ["Conversations:"]+ for session in sessions[:30]:+ flag = " (archived)" if session.get("archived") else ""+ title = str(session.get("title") or "").strip() or "(untitled)"+ lines.append(+ f"- `{session['session_key']}`{flag} — {title} · {session['message_count']} msg"+ )+ lines.append("\nUse /resume <session ID> or /delete <session ID>.")+ return PartnerCommandResult("\n".join(lines))++ def _resume(self, args: list[str]) -> PartnerCommandResult:+ if not args:+ return PartnerCommandResult("Usage: /resume <session ID>")+ key = args[0]+ self.store.set_archived(key, False)+ return PartnerCommandResult(+ f"Conversation `{key}` is active again. In the web app it reopens automatically."+ )++ def _delete(self, args: list[str]) -> PartnerCommandResult:+ if not args:+ return PartnerCommandResult("Usage: /delete <session ID>")+ key = args[0]+ removed = self.store.delete_session(key)+ return PartnerCommandResult(+ f"Deleted conversation `{key}`." if removed else f"No conversation `{key}` found."+ )+def _status(self, msg: InboundMessage) -> PartnerCommandResult:selection = getattr(self.config, "llm_selection", None) or {}model = (diff --git a/deeptutor/services/partners/manager.py b/deeptutor/services/partners/manager.pyindex b289c2f44..9303ead07 100644--- a/deeptutor/services/partners/manager.py+++ b/deeptutor/services/partners/manager.py@@ -126,10 +126,62 @@ class PartnerConfig:# User-toggleable system tools (same pool as the chat composer /# /settings/tools). None = all of them; [] = none; list = whitelist.enabled_tools: list[str] | None = None+ # Allowed built-in (auto-mounted) tools — rag / read_memory / web_fetch /+ # … (CONFIGURABLE_BUILTIN_TOOL_NAMES). None = no gating (all mount under+ # their usual context condition, like the product chat); [] = deny every+ # built-in; list = whitelist. Lets an owner deny e.g. memory to an+ # IM-facing partner.+ builtin_tools: list[str] | None = None# Configured MCP tools the partner may load. None = all; [] = MCP off.mcp_tools: list[str] | None = None+@dataclass+class LiveTurn:+ """A web turn decoupled from any single WebSocket connection.++ The turn runs as a task on the partner instance and fans its stream frames+ out to per-subscriber queues, buffering them too. A client that reconnects+ mid-turn (a page refresh) re-subscribes and replays the buffer, so the+ in-progress answer survives the reload instead of dying with the old+ socket. Frames are the same shapes the socket already sends+ (``stream_event`` / ``content`` / ``done`` / ``stopped`` / ``error``).+ """++ # The user message that opened the turn, so a client reattaching after a+ # refresh can re-show the question bubble (it isn't persisted until the+ # turn completes).+ user_content: str = ""+ events: list[dict[str, Any]] = field(default_factory=list)+ terminal: list[dict[str, Any]] = field(default_factory=list)+ done: bool = False+ subscribers: set[asyncio.Queue] = field(default_factory=set, repr=False)+ task: asyncio.Task | None = field(default=None, repr=False)++ def emit(self, frame: dict[str, Any]) -> None:+ self.events.append(frame)+ for queue in self.subscribers:+ queue.put_nowait(frame)++ def finish(self, frames: list[dict[str, Any]]) -> None:+ self.terminal = frames+ self.done = True+ for queue in self.subscribers:+ for frame in frames:+ queue.put_nowait(frame)+ self.subscribers.clear()++ def subscribe(self) -> asyncio.Queue:+ """Preload the backlog and register — atomically (no await between) so+ no frame is missed or duplicated at the boundary."""+ queue: asyncio.Queue = asyncio.Queue()+ for frame in (*self.events, *self.terminal):+ queue.put_nowait(frame)+ if not self.done:+ self.subscribers.add(queue)+ return queue++@dataclassclass PartnerInstance:"""A running partner and its runtime objects."""@@ -144,6 +196,9 @@ class PartnerInstance:channel_bindings: dict[str, str] = field(default_factory=dict)reload_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)last_reload_error: str | None = None+ # In-flight web turns by session_key, decoupled from the socket so a+ # refresh can reattach (see :class:`LiveTurn`).+ live_turns: dict[str, LiveTurn] = field(default_factory=dict, repr=False)@propertydef running(self) -> bool:@@ -180,6 +235,7 @@ class PartnerInstance:"avatar": self.config.avatar,"soul_origin": self.config.soul_origin,"enabled_tools": self.config.enabled_tools,+ "builtin_tools": self.config.builtin_tools,"mcp_tools": self.config.mcp_tools,"running": self.running,"started_at": self.started_at.isoformat(),@@ -236,6 +292,7 @@ class PartnerManager:"avatar","soul_origin","enabled_tools",+ "builtin_tools","mcp_tools",)@@ -258,6 +315,7 @@ class PartnerManager:avatar=str(data.get("avatar", "") or ""),soul_origin=dict(data.get("soul_origin", {}) or {}),enabled_tools=_optional_str_list(data.get("enabled_tools")),+ builtin_tools=_optional_str_list(data.get("builtin_tools")),mcp_tools=_optional_str_list(data.get("mcp_tools")),)except Exception:@@ -297,6 +355,8 @@ class PartnerManager:data["model"] = config.modelif config.enabled_tools is not None:data["enabled_tools"] = list(config.enabled_tools)+ if config.builtin_tools is not None:+ data["builtin_tools"] = list(config.builtin_tools)if config.mcp_tools is not None:data["mcp_tools"] = list(config.mcp_tools)@@ -596,6 +656,7 @@ class PartnerManager:"avatar": cfg.avatar if cfg else "","soul_origin": cfg.soul_origin if cfg else {},"enabled_tools": cfg.enabled_tools if cfg else None,+ "builtin_tools": cfg.builtin_tools if cfg else None,"mcp_tools": cfg.mcp_tools if cfg else None,"running": False,"started_at": None,@@ -663,25 +724,138 @@ class PartnerManager:session_id: str | None = None,media: list[str] | None = None,on_event: Callable[[Any], Awaitable[None]] | None = None,+ session_key: str | None = None,) -> str:- """Send a web message to a running partner and return the reply."""+ """Send a web message to a running partner and return the reply.++ ``session_key``, when given, is used verbatim (the web app drives a+ stable, colon-free key it persists locally); otherwise it is derived+ from ``session_id`` / ``chat_id`` via :meth:`web_session_key`.+ """instance = self._partners.get(partner_id)if not instance or not instance.running or not instance.runner:raise RuntimeError(f"Partner '{partner_id}' is not running")from deeptutor.partners.bus.events import InboundMessage- session_key = self.web_session_key(partner_id, chat_id=chat_id, session_id=session_id)+ resolved_key = (+ str(session_key).strip()+ if session_key+ else self.web_session_key(partner_id, chat_id=chat_id, session_id=session_id)+ )msg = InboundMessage(channel="web",sender_id="web",chat_id=session_id or chat_id,content=content,media=media or [],- session_key_override=session_key,+ session_key_override=resolved_key,)return await instance.runner.process_message(msg, on_event=on_event)+ # ── Live web turns (refresh-survivable streaming) ─────────────++ def start_web_turn(+ self,+ partner_id: str,+ session_key: str,+ content: str,+ media: list[str] | None = None,+ ) -> "LiveTurn":+ """Run a web turn as an instance-owned task and return its LiveTurn.++ If a turn is already in flight for this session, returns it (one at a+ time per session). The turn keeps running even if every socket detaches.+ """+ instance = self._partners.get(partner_id)+ if not instance or not instance.running or not instance.runner:+ raise RuntimeError(f"Partner '{partner_id}' is not running")+ existing = instance.live_turns.get(session_key)+ if existing is not None and not existing.done:+ return existing+ turn = LiveTurn(user_content=content)+ instance.live_turns[session_key] = turn+ turn.task = asyncio.create_task(+ self._drive_web_turn(partner_id, session_key, content, media or [], turn),+ name=f"partner:{partner_id}:webturn",+ )+ return turn++ def subscribe_web_turn(self, partner_id: str, session_key: str) -> "LiveTurn | None":+ """The in-flight turn for a session, or None (completed turns are read+ back from history instead)."""+ instance = self._partners.get(partner_id)+ if not instance:+ return None+ turn = instance.live_turns.get(session_key)+ return turn if turn is not None and not turn.done else None++ def stop_web_turn(self, partner_id: str, session_key: str) -> bool:+ instance = self._partners.get(partner_id)+ if not instance:+ return False+ turn = instance.live_turns.get(session_key)+ if turn is None or turn.done or turn.task is None or turn.task.done():+ return False+ turn.task.cancel()+ return True++ async def _drive_web_turn(+ self,+ partner_id: str,+ session_key: str,+ content: str,+ media: list[str],+ turn: "LiveTurn",+ ) -> None:+ async def on_event(event: Any) -> None:+ turn.emit({"type": "stream_event", "event": event.to_dict()})++ try:+ final = await self.send_message(+ partner_id,+ content,+ session_key=session_key,+ media=media,+ on_event=on_event,+ )+ turn.finish([{"type": "content", "content": final}, {"type": "done"}])+ except asyncio.CancelledError:+ turn.finish([{"type": "stopped"}])+ raise+ except RuntimeError as exc:+ turn.finish([{"type": "error", "content": str(exc)}, {"type": "done"}])+ except Exception as exc: # noqa: BLE001+ logger.exception("Web turn crashed for partner '%s'", partner_id)+ turn.finish(+ [+ {"type": "error", "content": f"Internal error ({type(exc).__name__})"},+ {"type": "done"},+ ]+ )++ # ── Session lifecycle (web management) ────────────────────────++ def resume_session(self, partner_id: str, session_key: str) -> dict[str, Any] | None:+ """Clear a session's archived flag so it becomes current again."""+ store = self.session_store(partner_id)+ store.set_archived(session_key, False)+ for session in store.list_sessions():+ if session["session_key"] == store._stem(session_key):+ return session+ return None++ def delete_session(self, partner_id: str, session_key: str) -> bool:+ return self.session_store(partner_id).delete_session(session_key)++ def branch_session(+ self, partner_id: str, source_key: str, new_key: str+ ) -> dict[str, Any] | None:+ return self.session_store(partner_id).branch(source_key, new_key)++ def archive_session(self, partner_id: str, session_key: str) -> None:+ self.session_store(partner_id).set_archived(session_key, True)+# ── Boot / shutdown ───────────────────────────────────────────async def auto_start_partners(self) -> None:diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.pyindex f4798a73c..05c44ed13 100644--- a/deeptutor/services/partners/runtime.py+++ b/deeptutor/services/partners/runtime.py@@ -158,7 +158,9 @@ class PartnerRunner:if command is not None:return command.content- final = await self._run_turn(msg, on_event=on_event, delivery_meta=delivery_meta)+ final, turn_events = await self._run_turn(+ msg, on_event=on_event, delivery_meta=delivery_meta+ )self.store.append(session_key,"user",@@ -168,7 +170,13 @@ class PartnerRunner:attachments=list((msg.metadata or {}).get("_attachment_records") or []),)if final:- self.store.append(session_key, "assistant", final, channel=msg.channel)+ self.store.append(+ session_key,+ "assistant",+ final,+ channel=msg.channel,+ events=turn_events or None,+ )return finalasync def _run_turn(@@ -177,12 +185,12 @@ class PartnerRunner:*,on_event: EventCallback | None = None,delivery_meta: dict[str, Any] | None = None,- ) -> str:+ ) -> tuple[str, list[dict[str, Any]]]:ensure_partner_workspace(self.partner_id)primary = getattr(self.config, "llm_selection", None) or Nonebackup = getattr(self.config, "backup_llm_selection", None) or None- final_text, errors = await self._execute_turn(+ final_text, errors, events = await self._execute_turn(msg, selection=primary, on_event=on_event, delivery_meta=delivery_meta)if not final_text and errors and backup and backup != primary:@@ -193,13 +201,13 @@ class PartnerRunner:)if delivery_meta is not None:delivery_meta.pop("_streamed", None)- final_text, errors = await self._execute_turn(+ final_text, errors, events = await self._execute_turn(msg, selection=backup, on_event=on_event, delivery_meta=delivery_meta)if not final_text and errors:final_text = f"Sorry, the turn failed: {errors[-1]}"- return final_text+ return final_text, eventsasync def _execute_turn(self,@@ -208,12 +216,16 @@ class PartnerRunner:selection: dict[str, str] | None,on_event: EventCallback | None = None,delivery_meta: dict[str, Any] | None = None,- ) -> tuple[str, list[str]]:- """Run one chat turn with *selection* active; returns (final, errors).+ ) -> tuple[str, list[str], list[dict[str, Any]]]:+ """Run one chat turn with *selection* active; returns (final, errors, events).- A failed turn is ``("", [error, …])`` — the caller decides whether a- backup model gets a second attempt. Exceptions are folded into the- error list so the retry policy sees them too.+ ``events`` is the turn's trace (every StreamEvent except done/session,+ as ``to_dict()`` — the exact shape the web socket forwards live), so the+ web chat can rehydrate its collapsible "Done" activity after a refresh.++ A failed turn is ``("", [error, …], events)`` — the caller decides+ whether a backup model gets a second attempt. Exceptions are folded into+ the error list so the retry policy sees them too.When the inbound message asks for streaming (``_wants_stream``, setby channels whose config enables it), every loop round's text is@@ -223,40 +235,72 @@ class PartnerRunner:becomes the reply (the final outbound is then marked ``_streamed``so the channel doesn't send it twice)."""+ from deeptutor.multi_user.paths import get_admin_path_servicefrom deeptutor.runtime.orchestrator import ChatOrchestrator+ from deeptutor.services.memory import memory_path_service_overridefrom deeptutor.services.model_selection.runtime import (activate_llm_selection,reset_llm_selection,)- context = self._build_context(msg)- turn_id = str(context.metadata.get("turn_id") or "")- send_progress = self._channel_delivery_flag(msg.channel, "send_progress", default=True)- send_tool_hints = self._channel_delivery_flag(msg.channel, "send_tool_hints", default=True)- is_im = msg.channel != "web"- # Streaming requires send_progress: narration rounds stream live as- # they happen, so with progress muted we keep buffered delivery.- wants_stream = is_im and send_progress and bool(msg.metadata.get("_wants_stream"))-final_text = ""terminator_text = ""+ turn_id = ""round_buffers: dict[str, list[str]] = {}streamed_rounds: dict[str, str] = {} # call_id → accumulated streamed textended_rounds: set[str] = set()errors: list[str] = []-- # Resolve the partner's LLM selection BEFORE entering the partner- # scope: the model catalog lives in the admin workspace. The scoped- # config rides the same async context into the orchestrator task.- _config, llm_token = activate_llm_selection(selection)+ turn_events: list[dict[str, Any]] = []++ # Turn setup (context assembly + LLM-selection resolution) runs INSIDE+ # the try so a setup failure folds into the error list instead of+ # propagating as an opaque crash. The common one is a missing active+ # LLM model: get_llm_config() raises LLMConfigError (a plain Exception,+ # not RuntimeError), which previously escaped _execute_turn and surfaced+ # as a bare "Internal error" on the web socket — masking the real+ # message and skipping the backup-model retry. Folding it here keeps the+ # actual reason ("No active LLM model is configured…") and lets+ # _run_turn fall back to the backup selection.+ #+ # activate_llm_selection still runs BEFORE the partner scope is entered:+ # the model catalog lives in the admin workspace, and the scoped config+ # rides the same async context into the orchestrator task.+ llm_token = Nonetry:- with user_context(partner_user(self.partner_id, name=self.config.name)):+ context = self._build_context(msg)+ turn_id = str(context.metadata.get("turn_id") or "")+ send_progress = self._channel_delivery_flag(msg.channel, "send_progress", default=True)+ send_tool_hints = self._channel_delivery_flag(+ msg.channel, "send_tool_hints", default=True+ )+ is_im = msg.channel != "web"+ # Streaming requires send_progress: narration rounds stream live as+ # they happen, so with progress muted we keep buffered delivery.+ wants_stream = is_im and send_progress and bool(msg.metadata.get("_wants_stream"))++ _config, llm_token = activate_llm_selection(selection)+ # Partner scope routes rag / skills / notebooks at the partner's own+ # workspace, but memory is the *owner's*: partners are anchored to+ # the admin workspace, so read_memory / write_memory must see the+ # admin's L3 (gated by the builtin-tool whitelist — an owner denies+ # memory to an IM-facing partner). Without this, the partner scope's+ # empty memory makes user_has_memory() False and read_memory never+ # mounts, so the agent falls back to notebooks to "know the user".+ with (+ user_context(partner_user(self.partner_id, name=self.config.name)),+ memory_path_service_override(get_admin_path_service()),+ ):orchestrator = ChatOrchestrator()async for event in orchestrator.handle(context):if on_event is not None:await on_event(event)meta = event.metadata or {}+ # Capture the trace for rehydration — mirror product chat's+ # persisted ``assistant_events`` (everything but done/session).+ if event.type not in (StreamEventType.DONE, StreamEventType.SESSION):+ turn_events.append(event.to_dict())+if event.type == StreamEventType.CONTENT:call_id = str(meta.get("call_id") or "")round_buffers.setdefault(call_id, []).append(event.content or "")@@ -317,7 +361,7 @@ class PartnerRunner:):delivery_meta["_streamed"] = True- return final_text, errors+ return final_text, errors, turn_events# ── context assembly ──────────────────────────────────────────@@ -382,6 +426,7 @@ class PartnerRunner:user_message=msg.content,conversation_history=history,enabled_tools=self._resolved_enabled_tools(),+ allowed_builtin_tools=self._resolved_builtin_tools(),active_capability="chat",knowledge_bases=kb_names,attachments=attachments,@@ -406,6 +451,20 @@ class PartnerRunner:return default_optional_tools()return [str(name) for name in configured]+ def _resolved_builtin_tools(self) -> list[str] | None:+ """The partner's allowed built-in (auto-mounted) tools.++ ``None`` in config means "no gating" — every built-in mounts under its+ usual context condition, exactly like the product chat (partners+ default to fully equipped). An explicit list (or ``[]``) restricts the+ built-in surface so an owner can deny e.g. memory access to an+ IM-facing partner. Flows to ``UnifiedContext.allowed_builtin_tools``.+ """+ configured = getattr(self.config, "builtin_tools", None)+ if configured is None:+ return None+ return [str(name) for name in configured]+def _build_skills_manifest(self) -> str:try:from deeptutor.services.skill.service import (diff --git a/deeptutor/services/partners/sessions.py b/deeptutor/services/partners/sessions.pyindex 0188d7378..329658c2c 100644--- a/deeptutor/services/partners/sessions.py+++ b/deeptutor/services/partners/sessions.py@@ -40,6 +40,86 @@ class PartnerSessionStore:def is_archived_key(session_key: str) -> bool:return safe_filename(session_key).startswith(_ARCHIVE_PREFIX)+ # ── session metadata (archived flag) ──────────────────────────+ #+ # The web app drives session lifecycle by key (resume / delete / branch),+ # so a web session is archived with a soft flag in this sidecar rather than+ # renamed — the file keeps its key and stays resumable. IM still uses the+ # rename-based ``archive()`` to free a chat's fixed key for a fresh start.++ @property+ def _index_path(self) -> Path:+ return self._dir / "_index.json"++ def _load_index(self) -> dict[str, Any]:+ path = self._index_path+ if not path.exists():+ return {}+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ return data if isinstance(data, dict) else {}+ except (OSError, json.JSONDecodeError):+ return {}++ def _save_index(self, index: dict[str, Any]) -> None:+ with self._write_lock:+ self._index_path.write_text(+ json.dumps(index, ensure_ascii=False, indent=2), encoding="utf-8"+ )++ def _stem(self, session_key: str) -> str:+ return safe_filename(session_key) or "default"++ def is_archived(self, session_key: str) -> bool:+ """Archived = soft flag in the index OR a legacy ``_archived_`` file."""+ stem = self._stem(session_key)+ if bool(self._load_index().get(stem, {}).get("archived")):+ return True+ return self.is_archived_key(session_key)++ def set_archived(self, session_key: str, archived: bool) -> None:+ stem = self._stem(session_key)+ index = self._load_index()+ entry = index.get(stem, {})+ if archived:+ entry["archived"] = True+ else:+ entry.pop("archived", None)+ if entry:+ index[stem] = entry+ else:+ index.pop(stem, None)+ self._save_index(index)++ def delete_session(self, session_key: str) -> bool:+ """Remove a session's file and its index entry. Returns whether it existed."""+ path = self._path(session_key)+ existed = path.exists()+ with self._write_lock:+ path.unlink(missing_ok=True)+ index = self._load_index()+ if index.pop(self._stem(session_key), None) is not None:+ self._save_index(index)+ return existed++ def branch(self, source_key: str, new_key: str) -> dict[str, Any] | None:+ """Copy *source_key*'s full history into *new_key* and archive the source.++ Returns the new session's summary, or ``None`` if the source is empty.+ The new key keeps the conversation going with the same context while the+ original is preserved (archived) and still resumable.+ """+ records = self._read_records(source_key)+ if not records:+ return None+ dest = self._path(new_key)+ with self._write_lock:+ with open(dest, "a", encoding="utf-8") as f:+ for record in records:+ f.write(json.dumps(record, ensure_ascii=False) + "\n")+ self.set_archived(source_key, True)+ return self._session_summary(dest)+# ── write ─────────────────────────────────────────────────────def append(@@ -52,6 +132,7 @@ class PartnerSessionStore:sender_id: str = "",metadata: dict[str, Any] | None = None,attachments: list[dict[str, Any]] | None = None,+ events: list[dict[str, Any]] | None = None,) -> None:record: dict[str, Any] = {"role": role,@@ -66,6 +147,11 @@ class PartnerSessionStore:record["metadata"] = metadataif attachments:record["attachments"] = attachments+ # The turn's trace (thinking / tool calls / narration) so the web chat+ # can rehydrate the collapsible "Done" activity after a refresh — the+ # IM channels never read it back, but it costs only storage there.+ if events:+ record["events"] = eventsline = json.dumps(record, ensure_ascii=False)with self._write_lock:with open(self._path(session_key), "a", encoding="utf-8") as f:@@ -168,7 +254,7 @@ class PartnerSessionStore:merged: list[tuple[str, int, dict[str, Any]]] = []sequence = 0for path in sorted(self._dir.glob("*.jsonl"), key=lambda p: p.stat().st_mtime):- if not include_archived and self.is_archived_key(path.stem):+ if not include_archived and self.is_archived(path.stem):continuekey = path.stemfor record in self._read_records(key):@@ -180,15 +266,34 @@ class PartnerSessionStore:def _session_summary(self, path: Path) -> dict[str, Any]:records = self._read_records(path.stem)last = records[-1] if records else {}- archived = self.is_archived_key(path.stem)+ archived = self.is_archived(path.stem)return {"session_key": path.stem,+ "title": self._derive_title(records),"message_count": len(records),"updated_at": datetime.fromtimestamp(path.stat().st_mtime).isoformat(),"last_message": str(last.get("content", ""))[:200],"archived": archived,}+ @staticmethod+ def _derive_title(records: list[dict[str, Any]]) -> str:+ """A short, human label for a session — its opening user message.++ The first user turn is what a conversation is "about"; fall back to the+ first record of any role. First line only, trimmed to a chip-sized+ length. Empty for an empty session (the UI shows a generic label).+ """+ opener = next(+ (r for r in records if r.get("role") == "user"),+ records[0] if records else None,+ )+ if not opener:+ return ""+ text = str(opener.get("content", "")).strip()+ first_line = text.splitlines()[0] if text else ""+ return first_line[:60].strip()+def list_sessions(self) -> list[dict[str, Any]]:return [self._session_summary(path)diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 419d44bc1..3581eedf1 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -674,6 +674,11 @@ class TurnRuntimeManager:"_regenerated_from_message_id","_superseded_turn_id","followup_question_context",+ # Per-turn subagent consult budget (composer stepper). Not part of+ # any capability's public config schema, so it rides as a runtime+ # key — stripped before validation, merged back into the turn config+ # and read by the subagent capability from context.config_overrides.+ "subagent_consult_budget",)runtime_only_config = {key: raw_config.pop(key) for key in runtime_only_keys if key in raw_configdiff --git a/deeptutor/services/skill/hub.py b/deeptutor/services/skill/hub.pyindex ff6f583d0..9829766c5 100644--- a/deeptutor/services/skill/hub.py+++ b/deeptutor/services/skill/hub.py@@ -259,6 +259,16 @@ class ClawHubProvider:"""The configured ``/api/v1`` base URL (used to derive the web origin)."""return self._base_url+ @property+ def web_origin(self) -> str:+ """The hub's website origin — ``base_url`` minus the ``/api/...`` suffix.++ Used to build "view on EduHub" links for the in-app skill browser.+ """+ marker = "/api/"+ idx = self._base_url.find(marker)+ return self._base_url[:idx] if idx != -1 else self._base_url+def _get(self, path: str, **params: Any) -> httpx.Response:url = f"{self._base_url}{path}"try:@@ -358,6 +368,86 @@ class ClawHubProvider:latest = payload["skill"].get("latestVersion")return str(latest or "").strip()+ @staticmethod+ def _listing_from_row(row: dict[str, Any]) -> dict[str, Any] | None:+ """Normalise one hub catalog/detail row into a display-ready dict."""+ slug = str(row.get("slug") or "").strip()+ if not slug:+ return None+ stats = row.get("stats") if isinstance(row.get("stats"), dict) else {}+ owner = row.get("owner") if isinstance(row.get("owner"), dict) else {}+ return {+ "slug": slug,+ "name": str(row.get("displayName") or row.get("name") or slug),+ "summary": str(row.get("summary") or row.get("description") or ""),+ "version": str(row.get("version") or ""),+ "downloads": int(stats.get("downloads") or 0),+ "stars": int(stats.get("stars") or 0),+ "owner": str(owner.get("displayName") or row.get("ownerHandle") or ""),+ "owner_url": str(owner.get("htmlUrl") or ""),+ "updated_at": row.get("updatedAt"),+ }++ def catalog(+ self, *, query: str = "", limit: int = 50, sort: str = "createdAt"+ ) -> list[dict[str, Any]]:+ """List skills published on the hub, for the in-app skill browser.++ Uses ``/search`` when a query is given (server-side relevance) and the+ plain ``/skills`` explore feed otherwise. Rows carry display name,+ summary, version, download/star counts and owner — everything the+ DeepTutor-native browser renders without a second round-trip.+ """+ if query.strip():+ response = self._get("/search", q=query.strip(), limit=limit)+ else:+ response = self._get("/skills", limit=limit, sort=sort)+ try:+ payload = response.json()+ except ValueError as exc:+ raise HubError(f"{self.name}: catalog returned invalid JSON") from exc+ rows = payload if isinstance(payload, list) else None+ if rows is None and isinstance(payload, dict):+ for key in ("results", "skills", "items"):+ if isinstance(payload.get(key), list):+ rows = payload[key]+ break+ if rows is None:+ raise HubError(f"{self.name}: unrecognised catalog response shape")+ out: list[dict[str, Any]] = []+ for row in rows:+ if isinstance(row, dict):+ listing = self._listing_from_row(row)+ if listing is not None:+ out.append(listing)+ return out++ def detail(self, slug: str) -> dict[str, Any]:+ """Full metadata + SKILL.md body for one hub skill (browser detail view)."""+ try:+ payload = self._get(f"/skills/{slug}").json()+ except ValueError as exc:+ raise HubError(f"{self.name}: skill detail returned invalid JSON") from exc+ if not isinstance(payload, dict):+ raise HubError(f"{self.name}: unrecognised skill detail shape")+ skill = payload.get("skill") if isinstance(payload.get("skill"), dict) else payload+ listing = self._listing_from_row(skill) or {"slug": slug, "name": slug}+ # Owner sometimes lives at the envelope top level, not inside ``skill``.+ if not listing.get("owner") and isinstance(payload.get("owner"), dict):+ owner = payload["owner"]+ listing["owner"] = str(owner.get("displayName") or owner.get("handle") or "")+ listing["owner_url"] = str(owner.get("htmlUrl") or "")+ dist = payload.get("distTags") if isinstance(payload.get("distTags"), dict) else {}+ listing["version"] = str(dist.get("latest") or listing.get("version") or "")+ listing["content"] = str(skill.get("description") or "")+ # EduHub's ``tags`` field is a dist-tags map; the topical labels live in+ # ``keywords``. Fall back to a list-shaped ``tags`` for other hubs.+ keywords = skill.get("keywords")+ if not isinstance(keywords, list):+ keywords = skill.get("tags") if isinstance(skill.get("tags"), list) else []+ listing["tags"] = [str(t) for t in keywords if str(t).strip()]+ return listing+def publish(self,*,@@ -613,6 +703,9 @@ def install_from_hub(rename_to=rename_to,fallback_description=fetched.ref.summary or None,force=force,+ # Stamp the source hub as a tag so imported skills are visibly+ # grouped (e.g. an ``eduhub`` tag) in the user's Skills list.+ extra_tags=[hub],origin={"hub": hub,"slug": slug,diff --git a/deeptutor/services/skill/service.py b/deeptutor/services/skill/service.pyindex 52f1b5003..8d4853e43 100644--- a/deeptutor/services/skill/service.py+++ b/deeptutor/services/skill/service.py@@ -632,6 +632,7 @@ class SkillService:fallback_description: str | None = None,origin: dict[str, Any] | None = None,force: bool = False,+ extra_tags: list[str] | None = None,) -> SkillInstallResult:"""Import an extracted skill package directory into the user layer.@@ -647,6 +648,8 @@ class SkillService:symlinks abort the import (see :meth:`_copy_support_tree`);* the tree is staged and swapped in atomically, so a failed importnever leaves a half-written skill;+ * ``extra_tags`` are merged into the package's own tags (the hub+ installer stamps the source hub, e.g. ``eduhub``, this way);* ``origin`` (hub provenance) is recorded in ``.hub-lock.json``."""source = Path(source_dir).resolve()@@ -665,7 +668,8 @@ class SkillService:if not description:raise SkillImportError("SKILL.md has no description and no fallback was provided.")tags = self._validate_tag_list(- meta.get("tags") if isinstance(meta.get("tags"), list) else None+ (meta.get("tags") if isinstance(meta.get("tags"), list) else [])+ + list(extra_tags or []))target_dir = self._skill_dir(slug)diff --git a/deeptutor/services/subagent/__init__.py b/deeptutor/services/subagent/__init__.pynew file mode 100644index 000000000..b4907191c--- /dev/null+++ b/deeptutor/services/subagent/__init__.py@@ -0,0 +1,50 @@+"""Subagent driver layer — drive a user's local agent CLI as a subagent.++DeepTutor runs on the same machine as the user's configured Claude Code / Codex,+so the backend can spawn those CLIs directly and stream back every native event.+This package is the decoupled core of that: backends that know one CLI each, a+shared streaming-subprocess primitive, and the value types that cross into the+chat capability. It knows nothing about the chat loop, KBs, or HTTP — those wire+in through the consult tool and the API.+"""++from __future__ import annotations++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import (+ CONSULT_BUDGET_MAX,+ CONSULT_BUDGET_MIN,+ DEFAULT_CONSULT_BUDGET,+ BackendConfig,+ SubagentSettings,+ get_consult_budget,+ load_subagent_settings,+ save_subagent_settings,+ settings_from_dict,+)+from deeptutor.services.subagent.registry import detect_all, get_backend, list_backend_kinds+from deeptutor.services.subagent.types import (+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++__all__ = [+ "OnEvent",+ "SubagentBackend",+ "BackendConfig",+ "SubagentSettings",+ "DEFAULT_CONSULT_BUDGET",+ "CONSULT_BUDGET_MIN",+ "CONSULT_BUDGET_MAX",+ "get_consult_budget",+ "load_subagent_settings",+ "save_subagent_settings",+ "settings_from_dict",+ "detect_all",+ "get_backend",+ "list_backend_kinds",+ "ConsultResult",+ "DetectResult",+ "SubagentEvent",+]diff --git a/deeptutor/services/subagent/base.py b/deeptutor/services/subagent/base.pynew file mode 100644index 000000000..11645eb75--- /dev/null+++ b/deeptutor/services/subagent/base.py@@ -0,0 +1,58 @@+"""The backend contract: drive one local agent CLI as a subagent.++A backend knows two things about its CLI: how to tell whether it's installed+and usable on this machine (:meth:`detect`), and how to put one question to it+and stream back every native event (:meth:`consult`). Everything CLI-specific —+flags, the JSON event schema, session resumption — lives behind this interface,+so the capability layer drives Claude Code and Codex through the exact same+three lines.+"""++from __future__ import annotations++from abc import ABC, abstractmethod+from collections.abc import Awaitable, Callable++from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.types import ConsultResult, DetectResult, SubagentEvent++# Called once per native event as it streams in. Backends must await it so+# backpressure (e.g. a slow WebSocket consumer) is respected.+OnEvent = Callable[[SubagentEvent], Awaitable[None]]+++class SubagentBackend(ABC):+ """Drive one local agent CLI (Claude Code, Codex, …) as a subagent."""++ kind: str+ display_name: str+ cli_command: str++ @abstractmethod+ async def detect(self) -> DetectResult:+ """Report whether this CLI is installed and usable on this machine."""++ @abstractmethod+ async def consult(+ self,+ question: str,+ *,+ on_event: OnEvent,+ cwd: str | None = None,+ session_id: str | None = None,+ config: BackendConfig | None = None,+ images: list[str] | None = None,+ ) -> ConsultResult:+ """Put one question to the subagent and stream every native event.++ ``session_id`` resumes the backend's prior session for this turn (so the+ subagent keeps context across DeepTutor's successive questions); the+ returned :class:`ConsultResult` carries the session id to thread into the+ next consult. ``images`` are local file paths the user forwarded with the+ question (Codex attaches them with ``-i``; Claude Code is pointed at them+ for its Read tool). Waits unconditionally for the subagent to finish —+ only its own exit (clean or error) ends the consult.+ """+++__all__ = ["OnEvent", "SubagentBackend"]diff --git a/deeptutor/services/subagent/claude_code.py b/deeptutor/services/subagent/claude_code.pynew file mode 100644index 000000000..123b3e729--- /dev/null+++ b/deeptutor/services/subagent/claude_code.py@@ -0,0 +1,374 @@+"""Claude Code backend — drive the local ``claude`` CLI in headless print mode.++Uses ``claude -p <question> --output-format stream-json --verbose``: a+newline-delimited JSON event stream that mirrors exactly what an interactive+session does — the system init, each assistant text block, every tool_use and+its tool_result, and a final ``result`` event. We map each event onto a+:class:`SubagentEvent` channel and forward it live, so the sidebar shows the+same intermediate steps the user would see in their own terminal.++Auth and config are inherited automatically: the spawned ``claude`` reads the+user's existing ``~/.claude`` credentials and settings, so no token is ever+handled here.+"""++from __future__ import annotations++import json+import logging+import os+from typing import Any++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.process import probe_version, stream_process_lines+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_REASONING,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++logger = logging.getLogger(__name__)++_MAX_FIELD_CHARS = 4000+# Single-line cap for a tool-call header (e.g. the command inside ``Bash(…)``).+_TOOL_HEADER_CHARS = 160+# Telemetry/system events that are noise in the transcript (the CLI doesn't show+# them as content either) — dropped rather than rendered as raw JSON.+_IGNORED_EVENT_TYPES = frozenset({"rate_limit_event", "control_request", "control_response"})+# The salient argument to surface in a tool header, in priority order, so a call+# reads like the CLI's ``Bash(cd …)`` / ``Read(path)`` instead of raw JSON.+_TOOL_PRIMARY_ARGS = (+ "command",+ "file_path",+ "path",+ "pattern",+ "query",+ "url",+ "prompt",+ "notebook_path",+ "description",+)+++class ClaudeCodeBackend(SubagentBackend):+ kind = "claude_code"+ display_name = "Claude Code"+ cli_command = "claude"++ async def detect(self) -> DetectResult:+ ok, text = await probe_version([self.cli_command, "--version"])+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=ok,+ version=text if ok else "",+ detail="" if ok else (text or "claude CLI not found on PATH"),+ )++ def _build_command(+ self,+ question: str,+ *,+ session_id: str | None,+ config: BackendConfig,+ images: list[str] | None = None,+ ) -> list[str]:+ # Claude Code's ``-p`` mode has no image flag (only the stream-json stdin+ # channel does), so we point it at the forwarded images on disk and let+ # its own Read tool view them — the bypass permission mode runs Read+ # without prompting.+ prompt = question+ if images:+ listing = "\n".join(images)+ prompt = (+ f"{question}\n\n[The user attached image(s) for this question. View "+ f"them with your Read tool before answering:\n{listing}]"+ )+ cmd = [+ self.cli_command,+ "-p",+ prompt,+ "--output-format",+ "stream-json",+ "--verbose",+ # Token-level streaming: emit Anthropic ``stream_event`` deltas so the+ # answer types out live in the sidebar rather than landing whole.+ "--include-partial-messages",+ ]+ if images:+ # Allow Read access to the (temp) directory the images live in, which+ # is outside the working dir.+ cmd += ["--add-dir", os.path.dirname(images[0])]+ if session_id:+ cmd += ["--resume", session_id]+ if config.permission_mode:+ cmd += ["--permission-mode", config.permission_mode]+ if config.model:+ cmd += ["--model", config.model]+ if config.effort:+ cmd += ["--effort", config.effort]+ if config.system_prompt.strip():+ cmd += ["--append-system-prompt", config.system_prompt]+ cmd += list(config.extra_args)+ return cmd++ async def consult(+ self,+ question: str,+ *,+ on_event: OnEvent,+ cwd: str | None = None,+ session_id: str | None = None,+ config: BackendConfig | None = None,+ images: list[str] | None = None,+ ) -> ConsultResult:+ config = config or BackendConfig()+ cmd = self._build_command(+ question, session_id=session_id, config=config, images=images+ )+ result = ConsultResult(session_id=session_id)+ assistant_text: list[str] = []+ # Token-streaming accumulator: per content-block running text, keyed by the+ # current message id, so partial ``stream_event`` deltas grow one row.+ stream: dict[str, Any] = {"msg_id": "", "blocks": {}}++ async def emit(+ kind: str, text: str, raw: dict[str, Any], meta: dict[str, Any] | None = None+ ) -> None:+ result.event_count += 1+ await on_event(SubagentEvent(kind=kind, text=text, raw=raw, meta=meta or {}))++ try:+ async for channel, line in stream_process_lines(cmd, cwd=cwd):+ if channel == "exit":+ if line != "0" and result.success and not result.final_text:+ result.success = False+ result.error = f"claude exited with code {line}"+ await emit(EVENT_ERROR, result.error, {"returncode": line})+ continue+ if channel == "stderr":+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stderr"})+ continue+ event = _parse_json(line)+ if event is None:+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stdout"})+ continue+ await self._handle_event(event, result, assistant_text, stream, emit)+ except Exception as exc: # pragma: no cover - defensive: surface, don't crash the turn+ logger.warning("claude consult failed: %s", exc, exc_info=True)+ result.success = False+ result.error = str(exc)+ await emit(EVENT_ERROR, str(exc), {})++ if not result.final_text and assistant_text:+ result.final_text = "\n".join(t for t in assistant_text if t).strip()+ return result++ async def _handle_event(+ self,+ event: dict[str, Any],+ result: ConsultResult,+ assistant_text: list[str],+ stream: dict[str, Any],+ emit: Any,+ ) -> None:+ sid = event.get("session_id")+ if isinstance(sid, str) and sid:+ result.session_id = sid+ etype = str(event.get("type") or "")++ if etype in _IGNORED_EVENT_TYPES:+ return++ # Token-level streaming: a partial Anthropic event. Accumulate text /+ # thinking deltas into the running block and emit the growing text under a+ # stable merge id, so the sidebar types the answer out live. The complete+ # block arrives later as a normal ``assistant`` event under the same merge+ # id and finalizes the row (no duplication).+ if etype == "stream_event":+ await self._handle_stream_event(event.get("event"), stream, emit)+ return++ if etype == "system":+ if event.get("subtype") == "init":+ model = str(event.get("model") or "")+ await emit(EVENT_LOG, f"Session started{f' · {model}' if model else ''}", event)+ return++ if etype == "assistant":+ msg_id = _message_id(event) or stream.get("msg_id") or ""+ for idx, block in enumerate(_content_blocks(event)):+ btype = str(block.get("type") or "")+ if btype == "text":+ text = str(block.get("text") or "").strip()+ if text:+ assistant_text.append(text)+ await emit(EVENT_TEXT, text, block, _merge("txt", msg_id, idx))+ elif btype == "tool_use":+ await emit(EVENT_TOOL, _render_tool_use(block), block)+ elif btype == "thinking":+ text = str(block.get("thinking") or block.get("text") or "").strip()+ if text:+ await emit(EVENT_REASONING, text, block, _merge("rsn", msg_id, idx))+ return++ if etype == "user":+ for block in _content_blocks(event):+ if str(block.get("type") or "") == "tool_result":+ await emit(EVENT_TOOL_RESULT, _render_tool_result(block), block)+ return++ if etype == "result":+ text = str(event.get("result") or "").strip()+ if text:+ result.final_text = text+ if str(event.get("subtype") or "") not in ("", "success"):+ result.success = event.get("is_error") is not True+ # The answer already streamed as the final assistant text block, so we+ # don't re-emit it (that's the old duplicate). Only when no assistant+ # text was streamed at all — a degenerate run — surface the result+ # text so the user still sees an answer.+ if text and not assistant_text:+ await emit(EVENT_TEXT, text, event)+ return++ # Unknown event type — keep it visible as a log rather than dropping it.+ await emit(EVENT_LOG, _compact(event), event)++ async def _handle_stream_event(+ self, inner: Any, stream: dict[str, Any], emit: Any+ ) -> None:+ """Accumulate a partial Anthropic streaming event into a growing row.++ ``stream_event`` wraps a raw Messages-API event. We track the message id+ and per-block running text, emitting the cumulative text under the merge+ id ``{txt|rsn}:{msg_id}:{index}`` on each delta. The frontend keeps the+ latest per merge id, so the answer types out and is finalized by the+ complete ``assistant`` block that follows (same merge id).+ """+ if not isinstance(inner, dict):+ return+ itype = str(inner.get("type") or "")+ if itype == "message_start":+ stream["msg_id"] = _message_id(inner)+ stream["blocks"] = {}+ return+ if itype == "content_block_start":+ block = inner.get("content_block")+ seed = str(block.get("text") or "") if isinstance(block, dict) else ""+ stream["blocks"][inner.get("index")] = seed+ return+ if itype != "content_block_delta":+ return+ delta = inner.get("delta")+ if not isinstance(delta, dict):+ return+ idx = inner.get("index")+ dtype = str(delta.get("type") or "")+ if dtype == "text_delta":+ acc = stream["blocks"].get(idx, "") + str(delta.get("text") or "")+ stream["blocks"][idx] = acc+ await emit(EVENT_TEXT, acc.strip(), inner, _merge("txt", stream.get("msg_id"), idx))+ elif dtype == "thinking_delta":+ acc = stream["blocks"].get(idx, "") + str(delta.get("thinking") or "")+ stream["blocks"][idx] = acc+ await emit(EVENT_REASONING, acc.strip(), inner, _merge("rsn", stream.get("msg_id"), idx))+++def _message_id(obj: dict[str, Any]) -> str:+ message = obj.get("message")+ if isinstance(message, dict) and message.get("id"):+ return str(message["id"])+ return ""+++def _merge(prefix: str, msg_id: Any, idx: Any) -> dict[str, str] | None:+ """A stable merge id for one content block, or None when unidentifiable."""+ if not msg_id:+ return None+ return {"merge_id": f"{prefix}:{msg_id}:{idx}"}+++def _parse_json(line: str) -> dict[str, Any] | None:+ line = line.strip()+ if not line or line[0] not in "{[":+ return None+ try:+ parsed = json.loads(line)+ except (ValueError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def _content_blocks(event: dict[str, Any]) -> list[dict[str, Any]]:+ message = event.get("message")+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, list):+ return []+ return [b for b in content if isinstance(b, dict)]+++def _render_tool_use(block: dict[str, Any]) -> str:+ """Render a tool call like the CLI: ``Bash(cd …)`` / ``Read(path)``.++ Surfaces the one salient argument (the command, the file, the query) on a+ single line; falls back to a compact dump only when no known arg is present.+ """+ name = str(block.get("name") or "tool")+ raw_input = block.get("input")+ if not isinstance(raw_input, dict) or not raw_input:+ return name+ for key in _TOOL_PRIMARY_ARGS:+ value = raw_input.get(key)+ if isinstance(value, str) and value.strip():+ return f"{name}({_inline(value)})"+ return f"{name}({_inline(_compact(raw_input))})"+++def _inline(text: str) -> str:+ """Collapse to a single line and cap for a tool header."""+ one_line = " ".join(text.split())+ if len(one_line) > _TOOL_HEADER_CHARS:+ return one_line[:_TOOL_HEADER_CHARS].rstrip() + " …"+ return one_line+++def _render_tool_result(block: dict[str, Any]) -> str:+ content = block.get("content")+ if isinstance(content, list):+ parts = [+ str(part.get("text") or "")+ for part in content+ if isinstance(part, dict) and part.get("type") == "text"+ ]+ text = "\n".join(p for p in parts if p)+ else:+ text = str(content or "")+ return _truncate(text) or "(empty result)"+++def _compact(obj: Any) -> str:+ try:+ text = json.dumps(obj, ensure_ascii=False)+ except (TypeError, ValueError):+ text = str(obj)+ return _truncate(text)+++def _truncate(text: str) -> str:+ text = text.strip()+ if len(text) > _MAX_FIELD_CHARS:+ return text[:_MAX_FIELD_CHARS].rstrip() + " …"+ return text+++__all__ = ["ClaudeCodeBackend"]diff --git a/deeptutor/services/subagent/claude_models.py b/deeptutor/services/subagent/claude_models.pynew file mode 100644index 000000000..111b55e16--- /dev/null+++ b/deeptutor/services/subagent/claude_models.py@@ -0,0 +1,236 @@+"""Sync Claude Code's model catalog by scraping its ``/model`` TUI.++Unlike Codex (which keeps a clean ``models_cache.json``), Claude Code exposes no+machine-readable model list — ``/model`` lives only inside its interactive+terminal UI. So on an explicit sync we drive ``claude`` in a pseudo-terminal,+open ``/model``, render the screen with an in-memory terminal emulator (``pyte``)+so the columns come out intact, parse the picker rows, and cache the result to+``data/user/settings/claude_models_cache.json`` (mirroring Codex's cache). The+options endpoint then reads that cache; if it's absent (never synced, or capture+failed) the curated fallback in :mod:`models` is used.++The capture is best-effort and POSIX-only (needs a pty); any failure returns an+empty list so the caller falls back to the curated catalog.+"""++from __future__ import annotations++from datetime import datetime, timezone+import json+import logging+import os+import re+import select+import signal+import tempfile+import time++from deeptutor.services.path_service import get_path_service++logger = logging.getLogger(__name__)++_CACHE_FILE = "claude_models_cache.json"++# Bounds for the capture: total wall-clock, and the terminal geometry (wide+# enough that description columns don't wrap into the model name).+_CAPTURE_TIMEOUT = 35.0+_COLS, _ROWS = 200, 60++# A picker row: optional cursor marker, an index, then "Name<2+ spaces>desc".+_ROW_RE = re.compile(r"^\s*(?:[❯>›*]\s*)?(\d+)\.\s+(.+?)\s*$")+_SELECT_MARKERS = "✔✓●◉※"+++def _cache_path():+ return get_path_service().get_settings_file(_CACHE_FILE)+++def load_cached_claude_models() -> tuple[list[dict[str, str]], str]:+ """Return ``(models, fetched_at)`` from the cache, or ``([], "")`` if none.++ Each model is ``{"slug", "display_name"}``. Pure read — no capture.+ """+ path = _cache_path()+ if not path.exists():+ return [], ""+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ logger.warning("failed to read %s; ignoring", path, exc_info=True)+ return [], ""+ models = [+ {"slug": str(m["slug"]), "display_name": str(m.get("display_name") or m["slug"])}+ for m in data.get("models", [])+ if isinstance(m, dict) and m.get("slug")+ ]+ return models, str(data.get("fetched_at") or "")+++async def sync_claude_models() -> tuple[list[dict[str, str]], str]:+ """Scrape ``/model`` live, cache the result, and return ``(models, fetched_at)``.++ Runs the blocking pty capture off the event loop. On any failure returns+ ``([], "")`` and leaves the existing cache untouched.+ """+ import asyncio++ try:+ screen = await asyncio.to_thread(_capture_model_screen)+ except Exception:+ logger.warning("claude /model capture failed", exc_info=True)+ return [], ""+ if not screen:+ return [], ""+ models = _parse_model_screen(screen)+ if not models:+ logger.warning("claude /model capture parsed no models")+ return [], ""+ fetched_at = datetime.now(timezone.utc).isoformat()+ _write_cache(models, fetched_at)+ return models, fetched_at+++def _write_cache(models: list[dict[str, str]], fetched_at: str) -> None:+ path = _cache_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ payload = {"fetched_at": fetched_at, "models": models}+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")+++def _parse_model_screen(text: str) -> list[dict[str, str]]:+ """Parse the rendered ``/model`` picker into ``{slug, display_name}`` entries.++ Maps each selectable row to the value ``--model`` accepts: the tier alias+ (``opus``/``sonnet``/``haiku``), with a ``[1m]`` suffix for the 1M-context+ variant. The recommended *default* row maps to the CLI default (the empty+ option the UI already offers) and disabled rows (e.g. an unavailable Fable)+ are dropped, so the list is exactly what the user can actually pick.+ """+ started = False+ out: list[dict[str, str]] = []+ seen: set[str] = set()+ for line in text.splitlines():+ if not started:+ if "select model" in line.lower():+ started = True+ continue+ match = _ROW_RE.match(line)+ if not match:+ continue # continuation / blank / footer line+ rest = match.group(2)+ parts = re.split(r"\s{2,}", rest.strip(), maxsplit=1)+ name = parts[0].translate({ord(c): None for c in _SELECT_MARKERS}).strip()+ desc = parts[1].strip() if len(parts) > 1 else ""+ low = name.lower()+ if "(disabled)" in low or "unavailable" in desc.lower():+ continue+ if "recommended" in low or low.startswith("default"):+ continue # the CLI default — already the UI's empty option+ base = re.sub(r"\(.*?\)", "", name).strip().split(" ")[0].lower()+ if base not in {"opus", "sonnet", "haiku"}:+ continue+ slug = f"{base}[1m]" if "1m context" in low else base+ if slug in seen:+ continue+ seen.add(slug)+ display = desc.split("·")[0].strip() or name+ out.append({"slug": slug, "display_name": display})+ return out+++def _capture_model_screen() -> str | None:+ """Drive ``claude``'s ``/model`` TUI in a pty and return the rendered screen.++ Returns the full screen text (one line per terminal row) once the picker is+ on screen, or ``None`` if we couldn't get there. POSIX-only; gracefully+ returns ``None`` when ``pyte`` is unavailable or the platform has no pty.+ """+ if os.name != "posix":+ return None+ try:+ import pty++ import pyte+ except Exception:+ return None++ screen = pyte.Screen(_COLS, _ROWS)+ stream = pyte.ByteStream(screen)+ workdir = tempfile.mkdtemp(prefix="dt-claude-model-")+ pid, fd = pty.fork()+ if pid == 0: # child: become the claude TUI+ os.environ["TERM"] = "xterm-256color"+ os.environ["COLUMNS"] = str(_COLS)+ os.environ["LINES"] = str(_ROWS)+ try:+ os.chdir(workdir)+ os.execvp("claude", ["claude"])+ except Exception:+ os._exit(127)++ trusted = opened = False+ settled_at: float | None = None+ start = time.time()+ try:+ while time.time() - start < _CAPTURE_TIMEOUT:+ ready, _, _ = select.select([fd], [], [], 0.3)+ if ready:+ try:+ data = os.read(fd, 65536)+ except OSError:+ break+ if not data:+ break+ stream.feed(data)+ packed = "".join(screen.display).replace(" ", "").lower()+ # 1) Accept the workspace-trust prompt for our temp dir.+ if not trusted and "trustthisfolder" in packed:+ time.sleep(0.3)+ os.write(fd, b"\r")+ trusted = True+ time.sleep(1.3)+ continue+ # 2) Once the composer is ready, open the model picker.+ if trusted and not opened and (+ "forshortcuts" in packed or "tryedit" in packed or 'try"' in packed+ ):+ os.write(fd, b"/model")+ time.sleep(0.5)+ os.write(fd, b"\r")+ opened = True+ time.sleep(1.5)+ continue+ # 3) Let the picker settle, then snapshot.+ if opened and "selectmodel" in packed and settled_at is None:+ settled_at = time.time()+ if settled_at is not None and time.time() - settled_at > 1.2:+ break+ return "\n".join(screen.display) if opened else None+ finally:+ for keys in (b"\x1b", b"\x03\x03"): # Esc, then Ctrl-C twice+ try:+ os.write(fd, keys)+ except OSError:+ pass+ try:+ os.close(fd)+ except OSError:+ pass+ try:+ os.kill(pid, signal.SIGTERM)+ except OSError:+ pass+ try:+ os.waitpid(pid, 0)+ except OSError:+ pass+ _cleanup_dir(workdir)+++def _cleanup_dir(path: str) -> None:+ import shutil++ shutil.rmtree(path, ignore_errors=True)+++__all__ = ["load_cached_claude_models", "sync_claude_models"]diff --git a/deeptutor/services/subagent/codex.py b/deeptutor/services/subagent/codex.pynew file mode 100644index 000000000..ca5a752a4--- /dev/null+++ b/deeptutor/services/subagent/codex.py@@ -0,0 +1,325 @@+"""Codex backend — drive the local ``codex`` CLI non-interactively.++Uses ``codex exec --json``: a JSONL event stream (``thread.started`` carries the+session id; ``item.*`` events carry reasoning, command executions, file changes,+MCP tool calls and the agent's messages; ``turn.completed`` / ``turn.failed``+close it out). We run sandboxed to the working directory with approvals off so a+headless run never blocks. Continuation is ``codex exec resume <session_id>``.++The Codex JSON schema is still evolving, so the event mapper is deliberately+defensive: it reads ids and item types from whatever fields are present and+renders any unrecognised item as a log line rather than dropping it — nothing+the CLI emitted is lost from the sidebar.++Auth/config come from the user's existing ``~/.codex`` — no token handled here.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.process import probe_version, stream_process_lines+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_REASONING,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++logger = logging.getLogger(__name__)++_MAX_FIELD_CHARS = 4000++# Sandbox values that mean "turn the sandbox off entirely" — mapped to the+# explicit Codex flag instead of a ``sandbox_mode`` config override.+_BYPASS_SANDBOX = frozenset(+ {"bypass", "danger-full-access-bypass", "dangerously-bypass-approvals-and-sandbox"}+)++# Item types whose start/finish render to ONE evolving row (placeholder on+# start, content filled on completion) — tagged with the item id so the UI+# merges both phases. (command_execution is intentionally NOT here: its command+# and output are two distinct rows.)+_FILL_IN_ITEMS = frozenset({"web_search"})++# Item types that stream their text incrementally ("*.updated" frames): the+# answer and its reasoning. They share one merge id across the updates and the+# completion so the row types out live and finalizes in place.+_STREAM_TEXT_ITEMS = frozenset({"agent_message", "assistant_message", "reasoning"})+++class CodexBackend(SubagentBackend):+ kind = "codex"+ display_name = "Codex"+ cli_command = "codex"++ async def detect(self) -> DetectResult:+ ok, text = await probe_version([self.cli_command, "--version"])+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=ok,+ version=text if ok else "",+ detail="" if ok else (text or "codex CLI not found on PATH"),+ )++ def _build_command(+ self,+ question: str,+ *,+ session_id: str | None,+ config: BackendConfig,+ images: list[str] | None = None,+ ) -> list[str]:+ cmd = [self.cli_command, "exec"]+ if session_id:+ cmd += ["resume", session_id]+ cmd += ["--json", "--skip-git-repo-check"]+ # ``--ephemeral`` (don't persist the session) only makes sense for a+ # fresh run, not when resuming an existing session.+ if config.ephemeral and not session_id:+ cmd.append("--ephemeral")+ sandbox = (config.sandbox or "workspace-write").strip()+ bypass = sandbox in _BYPASS_SANDBOX+ if bypass:+ cmd.append("--dangerously-bypass-approvals-and-sandbox")+ elif sandbox:+ # ``-c`` works on both ``exec`` and ``exec resume`` (resume has no+ # ``-s`` flag). Approval policy + network access are config keys too.+ cmd += ["-c", f'sandbox_mode="{sandbox}"']+ if config.approval:+ cmd += ["-c", f'approval_policy="{config.approval}"']+ if config.network_access:+ cmd += ["-c", "sandbox_workspace_write.network_access=true"]+ if config.model:+ cmd += ["-m", config.model]+ if config.effort:+ cmd += ["-c", f'model_reasoning_effort="{config.effort}"']+ # Forwarded images attach natively (``-i`` works on both ``exec`` and+ # ``exec resume``). Repeat the flag per file so the variadic form never+ # swallows the trailing prompt positional.+ for path in images or []:+ cmd += ["-i", path]+ cmd += list(config.extra_args)+ cmd.append(question)+ return cmd++ async def consult(+ self,+ question: str,+ *,+ on_event: OnEvent,+ cwd: str | None = None,+ session_id: str | None = None,+ config: BackendConfig | None = None,+ images: list[str] | None = None,+ ) -> ConsultResult:+ config = config or BackendConfig()+ cmd = self._build_command(+ question, session_id=session_id, config=config, images=images+ )+ result = ConsultResult(session_id=session_id)++ async def emit(+ kind: str, text: str, raw: dict[str, Any], meta: dict[str, Any] | None = None+ ) -> None:+ result.event_count += 1+ await on_event(SubagentEvent(kind=kind, text=text, raw=raw, meta=meta or {}))++ try:+ async for channel, line in stream_process_lines(cmd, cwd=cwd):+ if channel == "exit":+ if line != "0" and result.success and not result.final_text:+ result.success = False+ result.error = f"codex exited with code {line}"+ await emit(EVENT_ERROR, result.error, {"returncode": line})+ continue+ event = _parse_json(line)+ if event is None:+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": channel})+ continue+ await self._handle_event(event, result, emit)+ except Exception as exc: # pragma: no cover - defensive+ logger.warning("codex consult failed: %s", exc, exc_info=True)+ result.success = False+ result.error = str(exc)+ await emit(EVENT_ERROR, str(exc), {})++ return result++ async def _handle_event(self, event: dict[str, Any], result: ConsultResult, emit: Any) -> None:+ sid = _find_session_id(event)+ if sid:+ result.session_id = sid+ etype = str(event.get("type") or "")++ if etype == "thread.started":+ await emit(EVENT_LOG, "Session started", event)+ return+ if etype in ("turn.failed", "error"):+ message = _error_message(event)+ result.success = False+ result.error = message+ await emit(EVENT_ERROR, message, event)+ return+ if etype == "turn.completed":+ return # the agent_message item already carried the answer text++ item = event.get("item") if isinstance(event.get("item"), dict) else None++ # Token-level streaming: interim "*.updated" frames carry the item's+ # growing text. For streaming-text items (the answer + its reasoning) emit+ # the running text under a stable merge id so the row types out live; the+ # ".completed" frame finalizes the same row. Other item types carry+ # nothing useful mid-flight, so they're ignored until they complete.+ if item is not None and etype.endswith(".updated"):+ itype = _item_type(item)+ mid = _item_id(item)+ if mid and itype in _STREAM_TEXT_ITEMS:+ text = _item_text(item)+ if text:+ kind = EVENT_REASONING if itype == "reasoning" else EVENT_TEXT+ await emit(kind, text, item, {"merge_id": mid})+ return++ if item is not None and (etype.endswith(".completed") or etype.endswith(".started")):+ itype = _item_type(item)+ started = etype.endswith(".started")+ # ``_FILL_IN_ITEMS`` (web_search …) show a placeholder on start that+ # fills in on completion. Streaming-text items finalize, on completion,+ # the row they streamed under their item id — both correlate the two+ # phases by a merge id. ``command_execution`` shows command on start ++ # output on completion (two distinct rows). Everything else renders+ # once, on completion.+ merge_id = ""+ if itype in _FILL_IN_ITEMS or (itype in _STREAM_TEXT_ITEMS and not started):+ merge_id = _item_id(item)+ if started and itype != "command_execution" and not merge_id:+ return+ self._handle_item(item, etype, result)+ kind, text = _render_item(item, etype)+ if text:+ await emit(kind, text, item, {"merge_id": merge_id} if merge_id else None)+ return++ # No recognised item — keep raw events visible unless they are pure+ # lifecycle markers we already handle.+ if etype and not etype.startswith(("item.", "turn.")):+ await emit(EVENT_LOG, _compact(event), event)++ def _handle_item(self, item: dict[str, Any], etype: str, result: ConsultResult) -> None:+ if etype.endswith(".completed") and _item_type(item) in ("agent_message", "assistant_message"):+ text = _item_text(item)+ if text:+ result.final_text = text+++def _parse_json(line: str) -> dict[str, Any] | None:+ line = line.strip()+ if not line or line[0] not in "{[":+ return None+ try:+ parsed = json.loads(line)+ except (ValueError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def _item_type(item: dict[str, Any]) -> str:+ return str(item.get("type") or item.get("item_type") or "")+++def _item_id(item: dict[str, Any]) -> str:+ return str(item.get("id") or item.get("item_id") or "")+++def _item_text(item: dict[str, Any]) -> str:+ for key in ("text", "message", "content", "summary"):+ value = item.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""+++def _render_item(item: dict[str, Any], etype: str) -> tuple[str, str]:+ itype = _item_type(item)+ if itype in ("agent_message", "assistant_message"):+ # The answer renders as the terminal text of the run (its updates + this+ # completion collapse to one merged row); ConsultResult.final_text carries+ # it back to the chat model separately.+ return EVENT_TEXT, _item_text(item)+ if itype == "reasoning":+ return EVENT_REASONING, _item_text(item)+ if itype == "command_execution":+ command = str(item.get("command") or item.get("cmd") or "").strip()+ if etype.endswith(".started"):+ return EVENT_TOOL, f"$ {command}" if command else "command"+ output = str(item.get("aggregated_output") or item.get("output") or "").strip()+ exit_code = item.get("exit_code")+ header = f"$ {command}" if command else "command"+ suffix = f" (exit {exit_code})" if exit_code not in (None, "") else ""+ return EVENT_TOOL_RESULT, _truncate(f"{header}{suffix}\n{output}".strip())+ if itype == "file_change":+ changes = item.get("changes") or item.get("files") or item.get("path")+ return EVENT_TOOL, _truncate(f"file change · {_compact(changes)}")+ if itype in ("mcp_tool_call", "tool_call"):+ name = str(item.get("name") or item.get("tool") or "tool")+ return EVENT_TOOL, _truncate(f"{name} · {_compact(item.get('arguments') or item.get('input') or {})}")+ if itype == "web_search":+ query = str(item.get("query") or item.get("action") or "").strip()+ # Start (or no query yet) → placeholder; completion → fill in the query.+ if etype.endswith(".started") or not query:+ return EVENT_TOOL, "web search"+ return EVENT_TOOL, _truncate(f"web search · {query}")+ if itype in ("todo_list", "plan_update", "plan"):+ return EVENT_LOG, _truncate(_compact(item.get("items") or item.get("plan") or item))+ # Unknown item type: render whatever text we can find, else the raw object.+ return EVENT_LOG, _item_text(item) or _compact(item)+++def _find_session_id(event: dict[str, Any]) -> str:+ for key in ("thread_id", "session_id", "threadId", "sessionId"):+ value = event.get(key)+ if isinstance(value, str) and value:+ return value+ return ""+++def _error_message(event: dict[str, Any]) -> str:+ for key in ("message", "error", "reason", "detail"):+ value = event.get(key)+ if isinstance(value, str) and value:+ return value+ if isinstance(value, dict):+ inner = value.get("message")+ if isinstance(inner, str) and inner:+ return inner+ return "Codex reported a failure"+++def _compact(obj: Any) -> str:+ try:+ text = json.dumps(obj, ensure_ascii=False)+ except (TypeError, ValueError):+ text = str(obj)+ return _truncate(text)+++def _truncate(text: str) -> str:+ text = text.strip()+ if len(text) > _MAX_FIELD_CHARS:+ return text[:_MAX_FIELD_CHARS].rstrip() + " …"+ return text+++__all__ = ["CodexBackend"]diff --git a/deeptutor/services/subagent/config.py b/deeptutor/services/subagent/config.pynew file mode 100644index 000000000..50b02102d--- /dev/null+++ b/deeptutor/services/subagent/config.py@@ -0,0 +1,177 @@+"""Subagent settings — the consult budget and per-backend permission knobs.++Stored as ``data/user/settings/subagent.json`` (same convention as the other+runtime settings files). Everything has a safe default so the feature works the+moment a CLI is detected, with no configuration step required.++* ``consult_budget`` — the user-facing "max rounds": the maximum number of times+ DeepTutor may put a question to the subagent in one turn. Enforced+ authoritatively inside the consult tool; the chat loop's own round budget is+ only a safety ceiling.+* per-backend ``permission_mode`` / ``sandbox`` / ``approval`` — how the local+ agent runs non-interactively. The defaults are chosen to never stall waiting+ for an approval prompt (a headless agent that blocks on approval would hang+ the turn forever, since we wait unconditionally). A cautious user can dial+ these back; ``extra_args`` is an escape hatch for anything not modelled here.+"""++from __future__ import annotations++from dataclasses import dataclass, field+import json+import logging+from typing import Any++from deeptutor.services.path_service import get_path_service++logger = logging.getLogger(__name__)++_SETTINGS_FILE = "subagent.json"++DEFAULT_CONSULT_BUDGET = 5+CONSULT_BUDGET_MIN = 1+CONSULT_BUDGET_MAX = 12+++@dataclass(slots=True)+class BackendConfig:+ enabled: bool = True+ # Model + reasoning effort the agent runs with. Empty = the CLI's own+ # default. Set from the /settings page; the option lists are synced live+ # from the CLI (models/efforts change over time). CC: --model / --effort;+ # Codex: -m / -c model_reasoning_effort.+ model: str = ""+ effort: str = ""+ # Instruction injected so the agent knows it's being consulted+ # programmatically (be concise, self-contained, don't ask follow-ups).+ # CC: --append-system-prompt. Empty = none.+ system_prompt: str = ""+ # Claude Code: --permission-mode value. "bypassPermissions" never stalls and+ # lets the agent act autonomously on the user's own machine (the explicit+ # trust model of "connect my local CLI"). Codex ignores this field.+ permission_mode: str = "bypassPermissions"+ # Codex: --sandbox / approval_policy. "workspace-write" + "never" runs+ # autonomously within the working dir without blocking on approvals.+ sandbox: str = "workspace-write"+ approval: str = "never"+ # Codex: allow model-run shell commands network access (workspace-write is+ # offline by default). The built-in web_search tool is unaffected.+ network_access: bool = False+ # Codex: --ephemeral — don't persist the session under ~/.codex/sessions.+ ephemeral: bool = False+ # Forward image attachments from the chat turn to the agent (CC image input+ # / Codex -i). Off by default — the user opts in per backend.+ forward_images: bool = False+ extra_args: list[str] = field(default_factory=list)+++@dataclass(slots=True)+class SubagentSettings:+ consult_budget: int = DEFAULT_CONSULT_BUDGET+ backends: dict[str, BackendConfig] = field(default_factory=dict)++ def backend(self, kind: str) -> BackendConfig:+ return self.backends.get(kind, BackendConfig())++ def to_dict(self) -> dict[str, Any]:+ return {+ "consult_budget": self.consult_budget,+ "backends": {kind: _backend_to_dict(cfg) for kind, cfg in self.backends.items()},+ }+++def _backend_to_dict(cfg: BackendConfig) -> dict[str, Any]:+ return {+ "enabled": cfg.enabled,+ "model": cfg.model,+ "effort": cfg.effort,+ "system_prompt": cfg.system_prompt,+ "permission_mode": cfg.permission_mode,+ "sandbox": cfg.sandbox,+ "approval": cfg.approval,+ "network_access": cfg.network_access,+ "ephemeral": cfg.ephemeral,+ "forward_images": cfg.forward_images,+ "extra_args": list(cfg.extra_args),+ }+++def _coerce_budget(value: Any) -> int:+ try:+ n = int(value)+ except (TypeError, ValueError):+ return DEFAULT_CONSULT_BUDGET+ return max(CONSULT_BUDGET_MIN, min(CONSULT_BUDGET_MAX, n))+++def _coerce_backend(raw: Any) -> BackendConfig:+ base = BackendConfig()+ if not isinstance(raw, dict):+ return base+ extra = raw.get("extra_args")+ return BackendConfig(+ enabled=bool(raw.get("enabled", base.enabled)),+ model=str(raw.get("model") or "").strip(),+ effort=str(raw.get("effort") or "").strip(),+ system_prompt=str(raw.get("system_prompt") or ""),+ permission_mode=str(raw.get("permission_mode") or base.permission_mode),+ sandbox=str(raw.get("sandbox") or base.sandbox),+ approval=str(raw.get("approval") or base.approval),+ network_access=bool(raw.get("network_access", base.network_access)),+ ephemeral=bool(raw.get("ephemeral", base.ephemeral)),+ forward_images=bool(raw.get("forward_images", base.forward_images)),+ extra_args=[str(a) for a in extra] if isinstance(extra, list) else [],+ )+++def _settings_path():+ return get_path_service().get_settings_file(_SETTINGS_FILE)+++def settings_from_dict(raw: Any) -> SubagentSettings:+ """Coerce an arbitrary payload (file contents or an API body) into settings."""+ backends_raw = raw.get("backends") if isinstance(raw, dict) else None+ backends: dict[str, BackendConfig] = {}+ if isinstance(backends_raw, dict):+ for kind, cfg in backends_raw.items():+ backends[str(kind)] = _coerce_backend(cfg)+ return SubagentSettings(+ consult_budget=_coerce_budget(raw.get("consult_budget") if isinstance(raw, dict) else None),+ backends=backends,+ )+++def load_subagent_settings() -> SubagentSettings:+ """Read ``subagent.json``, falling back to defaults on any problem."""+ path = _settings_path()+ if not path.exists():+ return SubagentSettings()+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ logger.warning("failed to read %s; using defaults", path, exc_info=True)+ return SubagentSettings()+ return settings_from_dict(raw)+++def save_subagent_settings(settings: SubagentSettings) -> None:+ path = _settings_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(settings.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")+++def get_consult_budget() -> int:+ return load_subagent_settings().consult_budget+++__all__ = [+ "BackendConfig",+ "SubagentSettings",+ "DEFAULT_CONSULT_BUDGET",+ "CONSULT_BUDGET_MIN",+ "CONSULT_BUDGET_MAX",+ "settings_from_dict",+ "load_subagent_settings",+ "save_subagent_settings",+ "get_consult_budget",+]diff --git a/deeptutor/services/subagent/images.py b/deeptutor/services/subagent/images.pynew file mode 100644index 000000000..dae613cd8--- /dev/null+++ b/deeptutor/services/subagent/images.py@@ -0,0 +1,101 @@+"""Materialize image attachments to files so a subagent CLI can ingest them.++When ``forward_images`` is on for a backend, the consult tool writes the turn's+image attachments to a temp directory and hands the backend their paths — Codex+attaches them with ``-i``, Claude Code is pointed at them for its Read tool. The+bytes come from the attachment's inline base64 or, failing that, the local+:class:`AttachmentStore`; external URLs are never fetched (sync network IO in an+async path, and a request-forgery footgun).+"""++from __future__ import annotations++import base64+import logging+from pathlib import Path+import re+from typing import Any+from urllib.parse import unquote, urlparse++logger = logging.getLogger(__name__)++_LOCAL_ATTACHMENT_PREFIX = "/api/attachments/"+_EXT_BY_MIME = {+ "image/png": ".png",+ "image/jpeg": ".jpg",+ "image/jpg": ".jpg",+ "image/gif": ".gif",+ "image/webp": ".webp",+}+++def materialize_images(attachments: list[Any], dest_dir: Path) -> list[str]:+ """Write each image attachment into *dest_dir*, returning the file paths.++ Non-image attachments and ones whose bytes can't be resolved are skipped;+ the result is therefore exactly the images the backend can actually forward.+ """+ paths: list[str] = []+ for idx, att in enumerate(attachments or []):+ if getattr(att, "type", "") != "image":+ continue+ data = _image_bytes(att)+ if not data:+ continue+ target = dest_dir / f"{idx:02d}{_image_ext(att)}"+ try:+ target.write_bytes(data)+ except OSError:+ logger.warning("failed to write forwarded image %s", target, exc_info=True)+ continue+ paths.append(str(target))+ return paths+++def _image_bytes(att: Any) -> bytes | None:+ b64 = (getattr(att, "base64", "") or "").strip()+ if b64:+ if b64.startswith("data:") and "," in b64:+ b64 = b64.split(",", 1)[1]+ try:+ return base64.b64decode(b64)+ except Exception:+ logger.warning("failed to decode inline image base64", exc_info=True)+ return None+ return _local_store_bytes((getattr(att, "url", "") or "").strip())+++def _local_store_bytes(url: str) -> bytes | None:+ """Resolve a ``/api/attachments/<sid>/<aid>/<name>`` URL to its bytes."""+ if not url:+ return None+ path = urlparse(url).path or url+ if not path.startswith(_LOCAL_ATTACHMENT_PREFIX):+ return None+ parts = path[len(_LOCAL_ATTACHMENT_PREFIX) :].split("/")+ if len(parts) != 3:+ return None+ sid, aid, name = (unquote(p) for p in parts)+ try:+ from deeptutor.services.storage import get_attachment_store++ store = get_attachment_store()+ resolve = getattr(store, "resolve_path", None)+ if resolve is None:+ return None+ target = resolve(session_id=sid, attachment_id=aid, filename=name)+ return Path(target).read_bytes() if target else None+ except Exception:+ logger.warning("failed to resolve attachment %s", url, exc_info=True)+ return None+++def _image_ext(att: Any) -> str:+ mime = (getattr(att, "mime_type", "") or "").lower()+ if mime in _EXT_BY_MIME:+ return _EXT_BY_MIME[mime]+ match = re.search(r"(\.[A-Za-z0-9]{1,5})$", getattr(att, "filename", "") or "")+ return match.group(1) if match else ".png"+++__all__ = ["materialize_images"]diff --git a/deeptutor/services/subagent/models.py b/deeptutor/services/subagent/models.pynew file mode 100644index 000000000..f311af438--- /dev/null+++ b/deeptutor/services/subagent/models.py@@ -0,0 +1,204 @@+"""Backend option discovery — the synced model + reasoning-effort lists.++The /settings "Partners & Agents" page lets the user pick the model and+reasoning effort DeepTutor drives each backend with. Those lists change over+time (vendors add/retire models), so this is read live, not hard-coded, and the+page's "sync" button just re-reads it:++* **Codex** publishes an authoritative, server-synced cache at+ ``$CODEX_HOME/models_cache.json`` (slugs + per-model reasoning levels) and the+ user's current default in ``config.toml`` — we read both.+* **Claude Code** has no model-list CLI; its ``--model`` takes stable aliases+ (opus / sonnet / haiku) plus any full name, and ``--effort`` a fixed set — so+ we offer those as suggestions and the UI also allows a free-text model.+"""++from __future__ import annotations++from dataclasses import dataclass, field+import json+import logging+import os+from pathlib import Path+import re+from typing import Any++from deeptutor.services.subagent.process import probe_version+from deeptutor.services.subagent.registry import get_backend++logger = logging.getLogger(__name__)++# Claude Code: curated fallback used until a live ``/model`` sync populates the+# cache (see ``claude_models``). The aliases + ``[1m]`` variants mirror the+# ``/model`` picker; the UI also accepts a free-text model name.+_CLAUDE_MODELS = (+ ("opus", "Opus 4.8 · 1M context"),+ ("sonnet", "Sonnet 4.6"),+ ("sonnet[1m]", "Sonnet 4.6 · 1M context"),+ ("haiku", "Haiku 4.5"),+)+_CLAUDE_EFFORTS = ("low", "medium", "high", "xhigh", "max")+++@dataclass(slots=True)+class ModelOption:+ slug: str+ display_name: str+ default_effort: str = ""+ efforts: list[str] = field(default_factory=list)++ def to_dict(self) -> dict[str, Any]:+ return {+ "slug": self.slug,+ "display_name": self.display_name,+ "default_effort": self.default_effort,+ "efforts": list(self.efforts),+ }+++@dataclass(slots=True)+class BackendOptions:+ kind: str+ display_name: str+ available: bool+ version: str = ""+ default_model: str = ""+ models: list[ModelOption] = field(default_factory=list)+ # Effort scale when it isn't model-specific (Claude Code). For Codex the+ # per-model ``efforts`` are authoritative; this is a fallback/union.+ efforts: list[str] = field(default_factory=list)+ # Whether the UI should allow a free-text model (true when we can't fully+ # enumerate, e.g. Claude Code aliases + full names).+ allow_custom_model: bool = False+ # Freshness of a synced source, if any (Codex cache fetch time).+ synced_at: str = ""+ detail: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "kind": self.kind,+ "display_name": self.display_name,+ "available": self.available,+ "version": self.version,+ "default_model": self.default_model,+ "models": [m.to_dict() for m in self.models],+ "efforts": list(self.efforts),+ "allow_custom_model": self.allow_custom_model,+ "synced_at": self.synced_at,+ "detail": self.detail,+ }+++def _codex_home() -> Path:+ raw = os.environ.get("CODEX_HOME", "").strip()+ return Path(raw).expanduser() if raw else Path.home() / ".codex"+++def _codex_default_model() -> str:+ """Read ``model = "..."`` from the user's Codex config.toml (best-effort)."""+ config = _codex_home() / "config.toml"+ try:+ text = config.read_text(encoding="utf-8")+ except Exception:+ return ""+ # The default model is the top-level ``model = "..."`` (ignore nested+ # ``[profiles.*] model`` by matching only a line-start assignment).+ match = re.search(r'(?m)^\s*model\s*=\s*"([^"]+)"', text)+ return match.group(1) if match else ""+++async def _claude_options() -> BackendOptions:+ from deeptutor.services.subagent.claude_models import load_cached_claude_models++ backend = get_backend("claude_code")+ ok, text = await probe_version([backend.cli_command, "--version"]) if backend else (False, "")+ # Prefer a live-synced catalog (scraped from ``/model``); fall back to the+ # curated aliases until the user syncs.+ cached, synced_at = load_cached_claude_models()+ pairs = [(m["slug"], m["display_name"]) for m in cached] or list(_CLAUDE_MODELS)+ return BackendOptions(+ kind="claude_code",+ display_name="Claude Code",+ available=ok,+ version=text if ok else "",+ default_model="",+ models=[+ ModelOption(slug=slug, display_name=name, efforts=list(_CLAUDE_EFFORTS))+ for slug, name in pairs+ ],+ efforts=list(_CLAUDE_EFFORTS),+ allow_custom_model=True,+ synced_at=synced_at,+ detail="" if ok else (text or "claude CLI not found on PATH"),+ )+++async def _codex_options() -> BackendOptions:+ backend = get_backend("codex")+ ok, version = await probe_version([backend.cli_command, "--version"]) if backend else (False, "")+ models: list[ModelOption] = []+ synced_at = ""+ cache = _codex_home() / "models_cache.json"+ try:+ data = json.loads(cache.read_text(encoding="utf-8"))+ synced_at = str(data.get("fetched_at") or "")+ for entry in data.get("models", []):+ if not isinstance(entry, dict) or not entry.get("slug"):+ continue+ efforts = [+ str(level.get("effort"))+ for level in entry.get("supported_reasoning_levels", [])+ if isinstance(level, dict) and level.get("effort")+ ]+ models.append(+ ModelOption(+ slug=str(entry["slug"]),+ display_name=str(entry.get("display_name") or entry["slug"]),+ default_effort=str(entry.get("default_reasoning_level") or ""),+ efforts=efforts,+ )+ )+ except FileNotFoundError:+ pass+ except Exception:+ logger.warning("failed to read codex models cache", exc_info=True)+ return BackendOptions(+ kind="codex",+ display_name="Codex",+ available=ok,+ version=version if ok else "",+ default_model=_codex_default_model(),+ models=models,+ efforts=["none", "minimal", "low", "medium", "high", "xhigh"],+ allow_custom_model=True,+ synced_at=synced_at,+ detail="" if ok else (version or "codex CLI not found on PATH"),+ )+++async def list_backend_options() -> list[BackendOptions]:+ """Synced model/effort options for every backend (the /settings sync source)."""+ return [await _claude_options(), await _codex_options()]+++async def sync_backend_options(kind: str) -> BackendOptions:+ """Refresh and return one backend's options (the /settings "sync" action).++ Claude Code has no machine-readable catalog, so we actively scrape its+ ``/model`` TUI and cache the result. Codex's cache is maintained by its own+ CLI, so syncing is just a fresh read.+ """+ if kind == "claude_code":+ from deeptutor.services.subagent.claude_models import sync_claude_models++ await sync_claude_models() # writes the cache that _claude_options reads+ return await _claude_options()+ return await _codex_options()+++__all__ = [+ "BackendOptions",+ "ModelOption",+ "list_backend_options",+ "sync_backend_options",+]diff --git a/deeptutor/services/subagent/process.py b/deeptutor/services/subagent/process.pynew file mode 100644index 000000000..47d468e04--- /dev/null+++ b/deeptutor/services/subagent/process.py@@ -0,0 +1,139 @@+"""Stream a child process's stdout/stderr line-by-line as it runs.++The single low-level primitive the subagent backends share: spawn a command and+yield every stdout and stderr line the moment it arrives — so a long, multi-step+agent run surfaces live in the sidebar instead of all at once at the end — then+guarantee the process is torn down when the consumer stops early or the turn is+cancelled.++There is deliberately **no timeout** on the wait: per the product contract,+DeepTutor waits unconditionally for the subagent's own logic to finish; only the+subagent exiting (cleanly or with an error) ends the stream. Cancellation (the+user aborting the turn) propagates as ``CancelledError`` and the ``finally``+block terminates the child so no orphaned agent process is left behind.+"""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator, Mapping, Sequence+import contextlib+import logging+import os++logger = logging.getLogger(__name__)++# (channel, text) where channel is "stdout", "stderr", or "exit" (the final+# item, whose text is the integer return code as a string).+ProcessLine = tuple[str, str]++_TERMINATE_GRACE_SECONDS = 5.0+++async def stream_process_lines(+ cmd: Sequence[str],+ *,+ cwd: str | None = None,+ env: Mapping[str, str] | None = None,+) -> AsyncIterator[ProcessLine]:+ """Yield ``(channel, line)`` for each stdout/stderr line until the process exits.++ The final item is always ``("exit", "<returncode>")`` so callers can tell a+ clean finish from an early break. stdout and stderr are interleaved in+ arrival order via a shared queue.+ """+ full_env = {**os.environ, **(env or {})}+ process = await asyncio.create_subprocess_exec(+ *cmd,+ cwd=cwd or None,+ env=full_env,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )++ queue: asyncio.Queue[ProcessLine | None] = asyncio.Queue()++ async def _pump(stream: asyncio.StreamReader | None, channel: str) -> None:+ if stream is None:+ await queue.put(None)+ return+ try:+ while True:+ raw = await stream.readline()+ if not raw:+ break+ await queue.put((channel, raw.decode("utf-8", "replace").rstrip("\r\n")))+ except Exception: # pragma: no cover - defensive: a broken pipe must not hang the queue+ logger.debug("subagent %s pump failed", channel, exc_info=True)+ finally:+ await queue.put(None) # sentinel: this channel is drained++ readers = [+ asyncio.create_task(_pump(process.stdout, "stdout")),+ asyncio.create_task(_pump(process.stderr, "stderr")),+ ]+ drained = 0+ try:+ while drained < len(readers):+ item = await queue.get()+ if item is None:+ drained += 1+ continue+ yield item+ returncode = await process.wait()+ yield "exit", str(returncode)+ finally:+ for task in readers:+ task.cancel()+ with contextlib.suppress(Exception):+ await asyncio.gather(*readers, return_exceptions=True)+ await _terminate(process)+++async def _terminate(process: asyncio.subprocess.Process) -> None:+ """Best-effort teardown: terminate, wait briefly, then kill."""+ if process.returncode is not None:+ return+ with contextlib.suppress(ProcessLookupError):+ process.terminate()+ try:+ await asyncio.wait_for(process.wait(), timeout=_TERMINATE_GRACE_SECONDS)+ return+ except (TimeoutError, asyncio.TimeoutError):+ pass+ except ProcessLookupError: # pragma: no cover+ return+ with contextlib.suppress(ProcessLookupError):+ process.kill()+ with contextlib.suppress(Exception):+ await process.wait()+++async def probe_version(cmd: Sequence[str], *, timeout: float = 8.0) -> tuple[bool, str]:+ """Run a fast ``--version``-style probe; return ``(ok, stdout-or-error)``.++ Used by backend ``detect`` to answer "is this CLI installed here?" without+ the no-timeout consult semantics — a probe that hangs is a failed probe.+ """+ try:+ process = await asyncio.create_subprocess_exec(+ *cmd,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ )+ except FileNotFoundError:+ return False, "not installed"+ except Exception as exc: # pragma: no cover - defensive+ return False, str(exc)+ try:+ out, _ = await asyncio.wait_for(process.communicate(), timeout=timeout)+ except (TimeoutError, asyncio.TimeoutError):+ await _terminate(process)+ return False, "probe timed out"+ text = (out or b"").decode("utf-8", "replace").strip()+ return process.returncode == 0, text+++__all__ = ["ProcessLine", "stream_process_lines", "probe_version"]diff --git a/deeptutor/services/subagent/registry.py b/deeptutor/services/subagent/registry.pynew file mode 100644index 000000000..157f92dc8--- /dev/null+++ b/deeptutor/services/subagent/registry.py@@ -0,0 +1,52 @@+"""Backend registry — the single place that knows which subagents exist.++Add a new local agent CLI by writing a :class:`SubagentBackend` and listing it+here; the capability, API and UI all discover it through these helpers.+"""++from __future__ import annotations++import asyncio++from deeptutor.services.subagent.base import SubagentBackend+from deeptutor.services.subagent.claude_code import ClaudeCodeBackend+from deeptutor.services.subagent.codex import CodexBackend+from deeptutor.services.subagent.types import DetectResult++_BACKENDS: dict[str, SubagentBackend] = {+ backend.kind: backend+ for backend in (ClaudeCodeBackend(), CodexBackend())+}+++def list_backend_kinds() -> list[str]:+ return list(_BACKENDS.keys())+++def get_backend(kind: str) -> SubagentBackend | None:+ return _BACKENDS.get(str(kind or "").strip())+++async def detect_all() -> list[DetectResult]:+ """Probe every backend for installability on this machine, concurrently."""+ results = await asyncio.gather(+ *(backend.detect() for backend in _BACKENDS.values()),+ return_exceptions=True,+ )+ detections: list[DetectResult] = []+ for backend, result in zip(_BACKENDS.values(), results, strict=True):+ if isinstance(result, DetectResult):+ detections.append(result)+ else:+ detections.append(+ DetectResult(+ kind=backend.kind,+ display_name=backend.display_name,+ available=False,+ detail=str(result),+ )+ )+ return detections+++__all__ = ["list_backend_kinds", "get_backend", "detect_all"]diff --git a/deeptutor/services/subagent/sessions.py b/deeptutor/services/subagent/sessions.pynew file mode 100644index 000000000..a943ea56f--- /dev/null+++ b/deeptutor/services/subagent/sessions.py@@ -0,0 +1,83 @@+"""Persistent subagent session ids — continuity across DeepTutor turns.++The backend session/thread id from one consult is remembered (keyed by the chat+session + the connection) so the NEXT turn resumes the SAME local agent session:+the agent keeps the full context of everything DeepTutor — and the user, from+the sidebar — asked it earlier, instead of starting cold each turn. The consult+tool and the sidebar "message the agent directly" endpoint share this registry,+so both talk to one live session per (chat, connection).++Stored per-user under settings; entries for a connection are dropped when it is+disconnected.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from deeptutor.services.path_service import get_path_service++logger = logging.getLogger(__name__)++_FILE = "subagent_sessions.json"+_SEP = "::"+++def session_key(chat_session_id: str, connection: str) -> str:+ """The registry key for one (chat session, connection) pair."""+ return f"{chat_session_id}{_SEP}{connection}"+++def _path():+ return get_path_service().get_settings_file(_FILE)+++def _load() -> dict[str, Any]:+ path = _path()+ if not path.exists():+ return {}+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ return data if isinstance(data, dict) else {}+ except Exception:+ logger.warning("failed to read %s; ignoring", path, exc_info=True)+ return {}+++def _save(data: dict[str, Any]) -> None:+ path = _path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")+++def get_session(key: str) -> str | None:+ """The remembered backend session id for *key*, or None."""+ entry = _load().get(key)+ if isinstance(entry, dict) and entry.get("session_id"):+ return str(entry["session_id"])+ return None+++def remember_session(key: str, session_id: str, *, kind: str = "", cwd: str = "") -> None:+ """Persist the backend session id so the next turn resumes the same session."""+ if not session_id:+ return+ data = _load()+ data[key] = {"session_id": session_id, "kind": kind, "cwd": cwd}+ _save(data)+++def forget_connection(connection: str) -> None:+ """Drop every remembered session for a connection (on disconnect)."""+ data = _load()+ suffix = f"{_SEP}{connection}"+ stale = [k for k in data if k.endswith(suffix)]+ for key in stale:+ data.pop(key, None)+ if stale:+ _save(data)+++__all__ = ["session_key", "get_session", "remember_session", "forget_connection"]diff --git a/deeptutor/services/subagent/types.py b/deeptutor/services/subagent/types.pynew file mode 100644index 000000000..7b8b5d909--- /dev/null+++ b/deeptutor/services/subagent/types.py@@ -0,0 +1,106 @@+"""Value types for the subagent driver layer.++These are the only shapes that cross the boundary between a backend (which+knows how to drive one local agent CLI) and the rest of the app (the consult+tool, the API, the tests). Keeping them dependency-free lets the backends stay+small and the capability layer stay ignorant of CLI specifics.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++# Coarse channels the UI groups streamed events by. A backend maps each native+# event onto exactly one of these so the sidebar renders a CLI-faithful trace+# without knowing whether it came from Claude Code or Codex.+EVENT_TEXT = "text" # an assistant message / answer fragment+EVENT_REASONING = "reasoning" # the agent's thinking / plan+EVENT_TOOL = "tool" # the agent invoked a tool / ran a command+EVENT_TOOL_RESULT = "tool_result" # the result of that tool / command+EVENT_LOG = "log" # progress / status / stderr — the CLI's incidental logs+EVENT_RESULT = "result" # the final answer marker+EVENT_ERROR = "error" # the subagent reported a failure++KNOWN_EVENT_KINDS = frozenset(+ {+ EVENT_TEXT,+ EVENT_REASONING,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ EVENT_LOG,+ EVENT_RESULT,+ EVENT_ERROR,+ }+)+++@dataclass(slots=True)+class SubagentEvent:+ """One native event captured from a subagent's streamed output.++ ``kind`` is the coarse channel above; ``text`` is the human-readable line+ rendered in the sidebar; ``raw`` keeps the original parsed JSON object so+ nothing the CLI emitted is discarded.++ ``meta`` carries optional UI hints surfaced to the frontend. The only one+ today is ``merge_id``: a stable id correlating a tool's start/finish events+ so the transcript collapses them into one evolving row (e.g. a web search+ that shows "web search" on start, then fills in its query on completion).+ """++ kind: str+ text: str = ""+ raw: dict[str, Any] = field(default_factory=dict)+ meta: dict[str, Any] = field(default_factory=dict)+++@dataclass(slots=True)+class ConsultResult:+ """Outcome of one consult — one question put to the subagent.++ ``session_id`` is the backend's own session/thread id, threaded back into+ the next consult of the same turn so the subagent keeps its context across+ DeepTutor's successive questions.+ """++ final_text: str = ""+ session_id: str | None = None+ success: bool = True+ error: str = ""+ event_count: int = 0+++@dataclass(slots=True)+class DetectResult:+ """Whether a subagent backend is usable on the current machine."""++ kind: str+ display_name: str+ available: bool+ version: str = ""+ detail: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "kind": self.kind,+ "display_name": self.display_name,+ "available": self.available,+ "version": self.version,+ "detail": self.detail,+ }+++__all__ = [+ "EVENT_TEXT",+ "EVENT_REASONING",+ "EVENT_TOOL",+ "EVENT_TOOL_RESULT",+ "EVENT_LOG",+ "EVENT_RESULT",+ "EVENT_ERROR",+ "KNOWN_EVENT_KINDS",+ "SubagentEvent",+ "ConsultResult",+ "DetectResult",+]diff --git a/deeptutor/services/voice/adapters/__init__.py b/deeptutor/services/voice/adapters/__init__.pyindex b9aa4e50b..a8f9de99a 100644--- a/deeptutor/services/voice/adapters/__init__.py+++ b/deeptutor/services/voice/adapters/__init__.py@@ -11,11 +11,13 @@ from __future__ import annotationsfrom deeptutor.services.voice.adapters.openai_compat import (OpenAICompatSTTAdapter,OpenAICompatTTSAdapter,+ OpenRouterTTSAdapter,)from deeptutor.services.voice.base import BaseSTTAdapter, BaseTTSAdapter, VoiceProviderErrorTTS_ADAPTERS: dict[str, BaseTTSAdapter] = {"openai_compat": OpenAICompatTTSAdapter(),+ "openrouter_tts": OpenRouterTTSAdapter(),}STT_ADAPTERS: dict[str, BaseSTTAdapter] = {diff --git a/deeptutor/services/voice/adapters/openai_compat.py b/deeptutor/services/voice/adapters/openai_compat.pyindex fb0511050..db97971a8 100644--- a/deeptutor/services/voice/adapters/openai_compat.py+++ b/deeptutor/services/voice/adapters/openai_compat.py@@ -11,6 +11,8 @@ adapters keyed in ``adapters/__init__.py``.from __future__ import annotationsimport base64+import binascii+import jsonimport loggingfrom typing import Any@@ -20,6 +22,7 @@ from deeptutor.services.voice.base import (BaseSTTAdapter,BaseTTSAdapter,VoiceProviderError,+ VoiceProviderHTTPError,build_auth_headers,join_audio_path,)@@ -34,20 +37,77 @@ _FORMAT_CONTENT_TYPES = {"flac": "audio/flac","wav": "audio/wav","pcm": "audio/pcm",+ "pcm16": "audio/pcm",}+_OPENAI_TTS_VOICES = {+ "alloy",+ "ash",+ "ballad",+ "coral",+ "echo",+ "fable",+ "nova",+ "onyx",+ "sage",+ "shimmer",+ "verse",+}+++def _provider_error_message(action: str, status_code: int, body: str = "") -> str:+ detail = (body or "").strip()[:400]+ return f"{action} failed with HTTP {status_code}" + (f": {detail}" if detail else ".")+def _raise_for_provider(resp: httpx.Response, action: str) -> None:"""Surface a provider error with a trimmed body for diagnostics."""if resp.status_code < 400:returnbody = resp.text or ""- detail = body.strip()[:400]- raise VoiceProviderError(- f"{action} failed with HTTP {resp.status_code}" + (f": {detail}" if detail else ".")+ raise VoiceProviderHTTPError(+ _provider_error_message(action, resp.status_code, body),+ status_code=resp.status_code,+ body=body,)+def _join_api_path(base_url: str, suffix: str) -> str:+ """Append a generic API path to ``base_url`` while preserving query strings."""+ base = (base_url or "").strip()+ if not base:+ raise VoiceProviderError("No endpoint URL configured for this provider.")+ head, sep, query = base.partition("?")+ suffix = suffix.strip("/")+ if head.rstrip("/").endswith(f"/{suffix}"):+ return base+ joined = f"{head.rstrip('/')}/{suffix}"+ return f"{joined}?{query}" if sep else joined+++def _chat_audio_format(response_format: str) -> str:+ """Map OpenAI speech formats onto OpenRouter chat audio formats."""+ fmt = (response_format or "mp3").strip().lower()+ return "pcm16" if fmt == "pcm" else fmt+++def _openrouter_tts_hint(config: TTSConfig) -> str:+ """Return a provider/model-specific hint for opaque OpenRouter TTS errors."""+ model = (config.model or "").lower()+ voice = (config.voice or "").strip()+ if (+ config.provider_name == "openrouter"+ and "gemini" in model+ and "tts" in model+ and voice.lower() in _OPENAI_TTS_VOICES+ ):+ return (+ f" Voice `{voice}` is an OpenAI TTS voice; Gemini TTS expects Google "+ "prebuilt voice names such as `Kore` or `Puck`."+ )+ return ""++class OpenAICompatTTSAdapter(BaseTTSAdapter):"""POST ``{base}/audio/speech`` with a JSON body, returning raw audio bytes."""@@ -84,7 +144,13 @@ class OpenAICompatTTSAdapter(BaseTTSAdapter):resp = await client.post(url, headers=headers, json=payload)except httpx.HTTPError as exc:raise VoiceProviderError(f"TTS request error: {exc}") from exc- _raise_for_provider(resp, "TTS synthesis")+ try:+ _raise_for_provider(resp, "TTS synthesis")+ except VoiceProviderHTTPError as exc:+ hint = _openrouter_tts_hint(config)+ if hint:+ raise VoiceProviderError(f"{exc}{hint}") from exc+ raiseaudio = resp.contentif not audio:raise VoiceProviderError("TTS provider returned empty audio.")@@ -97,6 +163,127 @@ class OpenAICompatTTSAdapter(BaseTTSAdapter):return audio, content_type+class OpenRouterTTSAdapter(BaseTTSAdapter):+ """OpenRouter TTS with fallback for streaming chat-audio models.++ OpenRouter documents both a dedicated ``/audio/speech`` endpoint for TTS+ models and audio output through ``/chat/completions`` for models that expose+ the ``audio`` output modality. Try the dedicated endpoint first, then fall+ back to chat audio for configs pointed at audio-output chat models.+ """++ def __init__(self) -> None:+ self._speech = OpenAICompatTTSAdapter()++ async def synthesize(self, text: str, config: TTSConfig) -> tuple[bytes, str]:+ try:+ return await self._speech.synthesize(text, config)+ except VoiceProviderHTTPError as exc:+ if exc.status_code in {401, 403, 429}:+ raise+ logger.info(+ "OpenRouter /audio/speech failed with HTTP %s; trying chat audio output.",+ exc.status_code,+ )+ return await self._synthesize_chat_audio(text, config, original_error=exc)++ async def _synthesize_chat_audio(+ self,+ text: str,+ config: TTSConfig,+ *,+ original_error: VoiceProviderHTTPError,+ ) -> tuple[bytes, str]:+ if not config.base_url:+ raise VoiceProviderError("No endpoint URL configured for TTS.")+ url = _join_api_path(config.base_url, "chat/completions")+ headers = {+ "Content-Type": "application/json",+ **build_auth_headers(config.auth_style, config.api_key),+ **(config.extra_headers or {}),+ }+ audio_format = _chat_audio_format(config.response_format)+ payload: dict[str, Any] = {+ "model": config.model,+ "messages": [{"role": "user", "content": text}],+ "modalities": ["text", "audio"],+ "audio": {+ "voice": config.voice or "alloy",+ "format": audio_format,+ },+ "stream": True,+ }++ logger.debug(+ "OpenRouter chat-audio synthesize url=%s model=%s voice=%s fmt=%s chars=%d",+ url,+ config.model,+ config.voice,+ audio_format,+ len(text),+ )+ audio_chunks: list[str] = []+ try:+ async with httpx.AsyncClient(timeout=config.request_timeout) as client:+ resp = await client.post(url, headers=headers, json=payload)+ _raise_for_provider(resp, "OpenRouter chat audio synthesis")+ for line in (resp.text or "").splitlines():+ self._collect_audio_line(line, audio_chunks)+ except httpx.HTTPError as exc:+ detail = str(exc) or exc.__class__.__name__+ raise VoiceProviderError(f"TTS request error: {detail}") from exc+ except VoiceProviderHTTPError as exc:+ raise VoiceProviderError(+ f"{exc}; original /audio/speech error: {original_error}"+ ) from exc++ if not audio_chunks:+ raise VoiceProviderError(+ "OpenRouter chat audio returned no audio chunks; "+ f"original /audio/speech error: {original_error}"+ )+ try:+ audio = base64.b64decode("".join(audio_chunks))+ except binascii.Error as exc:+ raise VoiceProviderError("OpenRouter chat audio returned invalid base64.") from exc+ if not audio:+ raise VoiceProviderError("OpenRouter chat audio returned empty audio.")+ content_type = _FORMAT_CONTENT_TYPES.get(audio_format, "application/octet-stream")+ return audio, content_type++ @staticmethod+ def _collect_audio_line(line: str, audio_chunks: list[str]) -> None:+ if not line:+ return+ raw = line.strip()+ if not raw.startswith("data:"):+ return+ data = raw[len("data:") :].strip()+ if not data or data == "[DONE]":+ return+ try:+ chunk = json.loads(data)+ except json.JSONDecodeError:+ logger.debug("Ignoring malformed OpenRouter SSE line: %s", data[:160])+ return+ error = chunk.get("error")+ if isinstance(error, dict):+ message = error.get("message") or error.get("code") or "unknown error"+ raise VoiceProviderError(f"OpenRouter chat audio error: {message}")+ choices = chunk.get("choices")+ if not isinstance(choices, list):+ return+ for choice in choices:+ if not isinstance(choice, dict):+ continue+ delta = choice.get("delta") or {}+ if not isinstance(delta, dict):+ continue+ audio = delta.get("audio") or {}+ if isinstance(audio, dict) and isinstance(audio.get("data"), str):+ audio_chunks.append(audio["data"])++class OpenAICompatSTTAdapter(BaseSTTAdapter):"""POST ``{base}/audio/transcriptions``.@@ -188,4 +375,4 @@ class OpenAICompatSTTAdapter(BaseSTTAdapter):return (resp.text or "").strip()-__all__ = ["OpenAICompatTTSAdapter", "OpenAICompatSTTAdapter"]+__all__ = ["OpenAICompatTTSAdapter", "OpenRouterTTSAdapter", "OpenAICompatSTTAdapter"]diff --git a/deeptutor/services/voice/base.py b/deeptutor/services/voice/base.pyindex 7e872036a..214941f55 100644--- a/deeptutor/services/voice/base.py+++ b/deeptutor/services/voice/base.py@@ -20,6 +20,15 @@ class VoiceProviderError(RuntimeError):"""Raised when a TTS/STT provider request fails or is misconfigured."""+class VoiceProviderHTTPError(VoiceProviderError):+ """Provider returned a non-2xx HTTP response."""++ def __init__(self, message: str, *, status_code: int, body: str = "") -> None:+ super().__init__(message)+ self.status_code = status_code+ self.body = body++class BaseTTSAdapter(ABC):"""Abstract text-to-speech adapter."""@@ -126,6 +135,7 @@ def strip_markdown_for_speech(text: str, *, max_chars: int = 0) -> str:__all__ = ["VoiceProviderError",+ "VoiceProviderHTTPError","BaseTTSAdapter","BaseSTTAdapter","build_auth_headers",diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex 4ffc1186a..ea260d1c2 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -10,6 +10,7 @@ from typing import Anyfrom deeptutor.capabilities.mastery import MASTERY_TOOL_TYPESfrom deeptutor.capabilities.obsidian import OBSIDIAN_TOOL_TYPESfrom deeptutor.capabilities.solve import SOLVE_TOOL_TYPES+from deeptutor.capabilities.subagent import SUBAGENT_TOOL_TYPESfrom deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResultfrom deeptutor.tools.exec_tool import ExecToolfrom deeptutor.tools.media_gen_tool import ImagegenTool, VideogenTool@@ -1465,6 +1466,10 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (*MASTERY_TOOL_TYPES,*SOLVE_TOOL_TYPES,*OBSIDIAN_TOOL_TYPES,+ # Subagent consult tool — globally registered; the subagent knowledge+ # capability runs the turn exclusively on it when a connected agent is the+ # selected KB.+ *SUBAGENT_TOOL_TYPES,)# No tools are parked right now. When a tool's implementation is being@@ -1494,6 +1499,33 @@ USER_TOGGLEABLE_TOOL_NAMES: tuple[str, ...] = ("videogen",)+# Built-in tools the chat agent loop auto-mounts under context gates (a KB+# attached, the sandbox enabled, the user having memory/notebooks, …) rather+# than user toggles — "locked-on" in the product chat composer. Partners,+# however, can selectively allow/deny these per companion (default: all+# allowed) so an IM-facing partner can be denied e.g. memory access.+# ``tool_composition.AUTO_MOUNTED_TOOLS`` is derived from this tuple, so the+# two stay in lockstep; this ordering is the canonical display order for the+# partner config UI. Capability-owned tools (mastery/solve/obsidian/subagent)+# are intentionally absent — they are gated by capability activation, never by+# this surface.+CONFIGURABLE_BUILTIN_TOOL_NAMES: tuple[str, ...] = (+ "rag",+ "code_execution",+ "read_source",+ "read_memory",+ "write_memory",+ "read_skill",+ "list_notebook",+ "write_note",+ "web_fetch",+ "github",+ "exec",+ "load_tools",+ "cron",+ "ask_user",+)+TOOL_ALIASES: dict[str, tuple[str, dict[str, Any]]] = {"rag_hybrid": ("rag", {"mode": "hybrid"}),"rag_naive": ("rag", {"mode": "naive"}),@@ -1507,6 +1539,7 @@ __all__ = ["BUILTIN_TOOL_TYPES","COMING_SOON_TOOL_NAMES","COMING_SOON_TOOL_TYPES",+ "CONFIGURABLE_BUILTIN_TOOL_NAMES","TOOL_ALIASES","USER_TOGGLEABLE_TOOL_NAMES","AskUserTool",diff --git a/pyproject.toml b/pyproject.tomlindex 73bf6499d..3c43fc494 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -30,6 +30,7 @@ dependencies = ["typer[all]>=0.9.0","rich>=13.0.0","prompt_toolkit>=3.0.36",+ "pyte>=0.8.1", # in-memory terminal emulator: scrape Claude Code's /model TUI on sync# Full app dependencies included by default for `pip install deeptutor`."anthropic>=0.30.0","dashscope>=1.14.0",diff --git a/tests/api/test_cors_settings.py b/tests/api/test_cors_settings.pyindex b77ef9928..07cde9239 100644--- a/tests/api/test_cors_settings.py+++ b/tests/api/test_cors_settings.py@@ -2,6 +2,8 @@from __future__ import annotations+from fastapi.testclient import TestClient+from deeptutor.api import main as api_main@@ -51,3 +53,23 @@ def test_cors_normalizes_common_origin_input_mistakes(monkeypatch) -> None:assert "http://172.26.0.10:3782" in settings["allow_origins"]assert "https://learn.example.com" in settings["allow_origins"]assert "http://api.example.com" in settings["allow_origins"]+++def test_cors_preflight_allows_partner_patch_save() -> None:+ client = TestClient(api_main.app)++ response = client.options(+ "/api/v1/partners/partner",+ headers={+ "Origin": "http://localhost:3000",+ "Access-Control-Request-Method": "PATCH",+ "Access-Control-Request-Headers": "content-type",+ },+ )++ assert response.status_code == 200+ assert response.headers["access-control-allow-origin"] == "http://localhost:3000"+ allowed_methods = {+ method.strip() for method in response.headers["access-control-allow-methods"].split(",")+ }+ assert "PATCH" in allowed_methodsdiff --git a/tests/api/test_partners_router.py b/tests/api/test_partners_router.pyindex 45734767e..0966cc826 100644--- a/tests/api/test_partners_router.py+++ b/tests/api/test_partners_router.py@@ -122,6 +122,24 @@ class TestConfigAndSoul:assert body["enabled_tools"] == []assert body["mcp_tools"] == ["mcp_x_y"]+ def test_builtin_tools_create_and_patch(self, client):+ res = _create(client, builtin_tools=["rag", "read_memory"])+ assert res.status_code == 200+ assert res.json()["builtin_tools"] == ["rag", "read_memory"]+ # Default (omitted) stays null = no gating; an explicit deny persists.+ _create(client, partner_id="bob", name="Bob")+ assert client.get("/api/v1/partners/bob").json()["builtin_tools"] is None+ res = client.patch("/api/v1/partners/ada", json={"builtin_tools": []})+ assert res.status_code == 200+ assert client.get("/api/v1/partners/ada").json()["builtin_tools"] == []++ def test_tool_options_exposes_builtin_tools(self, client):+ body = client.get("/api/v1/partners/tool-options").json()+ assert {"tools", "builtin_tools", "mcp_tools"} <= set(body)+ builtin_names = {t["name"] for t in body["builtin_tools"]}+ # The memory tools are configurable built-ins now.+ assert {"rag", "read_memory", "write_memory"} <= builtin_names+def test_avatar_roundtrip_and_validation(self, client):_create(client)avatar = "data:image/png;base64,iVBORw0KGgo="@@ -219,6 +237,84 @@ class TestHistory:assert res.status_code == 200assert res.json()[0]["content"] == "hi"+ def test_history_scoped_by_web_session_id(self, client, isolated_root):+ _create(client)+ sessions = isolated_root / "partners" / "ada" / "sessions"+ sessions.mkdir(parents=True, exist_ok=True)+ # Two distinct web sessions; the endpoint must scope to the one asked for.+ (sessions / "web_s1.jsonl").write_text(+ json.dumps({"role": "user", "content": "from s1", "timestamp": "t"}) + "\n",+ encoding="utf-8",+ )+ (sessions / "web_s2.jsonl").write_text(+ json.dumps({"role": "user", "content": "from s2", "timestamp": "t"}) + "\n",+ encoding="utf-8",+ )+ res = client.get("/api/v1/partners/ada/history?session_id=s1")+ assert res.status_code == 200+ contents = [m["content"] for m in res.json()]+ assert contents == ["from s1"]++ def test_sessions_list_carries_title(self, client, isolated_root):+ _create(client)+ sessions = isolated_root / "partners" / "ada" / "sessions"+ sessions.mkdir(parents=True, exist_ok=True)+ (sessions / "web_s1.jsonl").write_text(+ json.dumps({"role": "user", "content": "what is recursion?", "timestamp": "t"}) + "\n",+ encoding="utf-8",+ )+ res = client.get("/api/v1/partners/ada/sessions")+ assert res.status_code == 200+ assert res.json()[0]["title"] == "what is recursion?"++ def _seed_session(self, isolated_root: Path, key: str, content: str) -> None:+ sessions = isolated_root / "partners" / "ada" / "sessions"+ sessions.mkdir(parents=True, exist_ok=True)+ (sessions / f"{key}.jsonl").write_text(+ json.dumps({"role": "user", "content": content, "timestamp": "t"}) + "\n",+ encoding="utf-8",+ )++ def test_archive_then_resume_roundtrip(self, client, isolated_root):+ _create(client)+ self._seed_session(isolated_root, "web-a", "hi")+ assert (+ client.post("/api/v1/partners/ada/sessions/archive", json={"session_key": "web-a"})+ ).status_code == 200+ archived = {s["session_key"]: s for s in client.get("/api/v1/partners/ada/sessions").json()}+ assert archived["web-a"]["archived"] is True+ assert (+ client.post("/api/v1/partners/ada/sessions/resume", json={"session_key": "web-a"})+ ).status_code == 200+ live = {s["session_key"]: s for s in client.get("/api/v1/partners/ada/sessions").json()}+ assert live["web-a"]["archived"] is False++ def test_branch_copies_and_archives(self, client, isolated_root):+ _create(client)+ self._seed_session(isolated_root, "web-a", "carry me")+ res = client.post(+ "/api/v1/partners/ada/sessions/branch",+ json={"source_key": "web-a", "new_key": "web-b"},+ )+ assert res.status_code == 200+ assert res.json()["session"]["session_key"] == "web-b"+ hist = client.get("/api/v1/partners/ada/history?session_key=web-b").json()+ assert [m["content"] for m in hist] == ["carry me"]+ sessions = {s["session_key"]: s for s in client.get("/api/v1/partners/ada/sessions").json()}+ assert sessions["web-a"]["archived"] is True++ def test_delete_session_endpoint(self, client, isolated_root):+ _create(client)+ self._seed_session(isolated_root, "web-a", "bye")+ assert (+ client.post("/api/v1/partners/ada/sessions/delete", json={"session_key": "web-a"})+ ).status_code == 200+ assert client.get("/api/v1/partners/ada/sessions").json() == []+ # Deleting a missing session is a 404.+ assert (+ client.post("/api/v1/partners/ada/sessions/delete", json={"session_key": "web-a"})+ ).status_code == 404+class TestChatAttachments:def test_chat_does_not_auto_start_stopped_partner(self, client):diff --git a/tests/api/test_skills_hub_router.py b/tests/api/test_skills_hub_router.pynew file mode 100644index 000000000..14f0a3963--- /dev/null+++ b/tests/api/test_skills_hub_router.py@@ -0,0 +1,106 @@+"""API tests for the in-app EduHub skill browser endpoints.++``GET /api/v1/skills/hub/catalog`` and ``/hub/detail`` proxy a hub's public+catalog so the web panel can render it in DeepTutor's own UI (no iframe, no+login). The hub provider is mocked over an ``httpx`` transport.+"""++from __future__ import annotations++import importlib++import httpx+import pytest++try:+ from fastapi import FastAPI+ from fastapi.testclient import TestClient+except Exception: # pragma: no cover - optional dependency in lightweight envs+ FastAPI = None+ TestClient = None++pytestmark = pytest.mark.skipif(+ FastAPI is None or TestClient is None, reason="fastapi not installed"+)++from deeptutor.services.skill import hub as hub_module+from deeptutor.services.skill.hub import ClawHubProvider+++def _mock_provider() -> ClawHubProvider:+ def handler(request: httpx.Request) -> httpx.Response:+ path = request.url.path+ if path == "/api/v1/skills":+ return httpx.Response(+ 200,+ json={+ "skills": [+ {+ "slug": "socratic-tutor",+ "displayName": "Socratic Tutor",+ "summary": "Teach by asking.",+ "version": "1.0.0",+ "stats": {"downloads": 8, "stars": 2},+ "owner": {+ "displayName": "DeepTutor",+ "htmlUrl": "https://deeptutor.info",+ },+ }+ ]+ },+ )+ if path == "/api/v1/skills/socratic-tutor":+ return httpx.Response(+ 200,+ json={+ "skill": {+ "slug": "socratic-tutor",+ "displayName": "Socratic Tutor",+ "summary": "Teach.",+ "description": "---\nname: socratic-tutor\n---\n\n# Body\n",+ "tags": ["tutor"],+ "stats": {"downloads": 8, "stars": 2},+ },+ "owner": {"displayName": "DeepTutor", "htmlUrl": "https://deeptutor.info"},+ "distTags": {"latest": "1.0.0"},+ },+ )+ return httpx.Response(404, text="nope")++ return ClawHubProvider(+ "eduhub",+ base_url="https://eduhub.deeptutor.info/api/v1",+ client=httpx.Client(transport=httpx.MockTransport(handler)),+ )+++def _build_app() -> FastAPI:+ router = importlib.import_module("deeptutor.api.routers.skills").router+ app = FastAPI()+ app.include_router(router, prefix="/api/v1/skills")+ return app+++def test_hub_catalog_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(hub_module, "get_hub_provider", lambda name: _mock_provider())+ client = TestClient(_build_app())+ resp = client.get("/api/v1/skills/hub/catalog")+ assert resp.status_code == 200+ data = resp.json()+ assert data["hub"] == "eduhub"+ assert data["web_url"] == "https://eduhub.deeptutor.info"+ row = data["skills"][0]+ assert row["slug"] == "socratic-tutor"+ assert row["downloads"] == 8 and row["stars"] == 2+ assert row["owner"] == "DeepTutor"+++def test_hub_detail_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(hub_module, "get_hub_provider", lambda name: _mock_provider())+ client = TestClient(_build_app())+ resp = client.get("/api/v1/skills/hub/detail", params={"slug": "socratic-tutor"})+ assert resp.status_code == 200+ data = resp.json()+ assert data["version"] == "1.0.0"+ assert "# Body" in data["content"]+ assert data["web_url"] == "https://eduhub.deeptutor.info/skills/socratic-tutor"diff --git a/tests/api/test_subagents_router.py b/tests/api/test_subagents_router.pynew file mode 100644index 000000000..9f2630b70--- /dev/null+++ b/tests/api/test_subagents_router.py@@ -0,0 +1,268 @@+"""API tests for the subagents router (detect / connect / list / disconnect).++Built on a standalone app with a fake KB manager and a stubbed detector, so it+exercises the HTTP contract without spawning a real CLI or touching the data+tree (mirrors test_knowledge_router's isolation).+"""++from __future__ import annotations++import importlib+import json+from pathlib import Path++import pytest++try:+ from fastapi import FastAPI+ from fastapi.testclient import TestClient+except Exception: # pragma: no cover - optional dependency in lightweight envs+ FastAPI = None+ TestClient = None++pytestmark = pytest.mark.skipif(+ FastAPI is None or TestClient is None, reason="fastapi not installed"+)++if FastAPI is not None and TestClient is not None:+ subagents_module = importlib.import_module("deeptutor.api.routers.subagents")+else: # pragma: no cover+ subagents_module = None+++class _FakeKBManager:+ def __init__(self) -> None:+ self.kbs: dict[str, dict] = {}++ def list_knowledge_bases(self) -> list[str]:+ return sorted(self.kbs)++ def get_metadata(self, name: str | None = None) -> dict:+ return dict(self.kbs.get(name or "", {}))++ def register_subagent_connection(self, name, agent_kind, *, cwd="", description=""):+ if name in self.kbs:+ raise ValueError(f"A knowledge base named '{name}' already exists.")+ entry = {+ "path": name,+ "type": "subagent",+ "agent_kind": agent_kind,+ "cwd": cwd,+ "description": description or f"Connected subagent: {name}",+ }+ self.kbs[name] = entry+ return entry++ def delete_knowledge_base(self, name, confirm=False):+ self.kbs.pop(name, None)+ return True+++def client(monkeypatch, tmp_path):+ manager = _FakeKBManager()+ monkeypatch.setattr(subagents_module, "current_kb_manager", lambda: manager)+ monkeypatch.setattr(subagents_module, "list_backend_kinds", lambda: ["claude_code", "codex"])+ monkeypatch.setattr(subagents_module, "assert_path_allowed", lambda p: Path(p))+ # Isolate settings persistence to a temp file — the PUT path otherwise+ # writes the developer's real data/user/settings/subagent.json.+ monkeypatch.setattr(+ "deeptutor.services.subagent.config._settings_path",+ lambda: tmp_path / "subagent.json",+ )++ async def fake_detect():+ from deeptutor.services.subagent.types import DetectResult++ return [+ DetectResult("claude_code", "Claude Code", available=True, version="2.x"),+ DetectResult("codex", "Codex", available=False, detail="not installed"),+ ]++ monkeypatch.setattr(subagents_module, "detect_all", fake_detect)++ app = FastAPI()+ app.include_router(subagents_module.router, prefix="/api/v1/subagents")+ # Settings PUT is admin-gated; bypass the auth dependency for the contract test.+ app.dependency_overrides[subagents_module.require_admin] = lambda: None+ return TestClient(app)+++def test_detect_reports_backends(client):+ res = client.get("/api/v1/subagents/detect")+ assert res.status_code == 200+ backends = {b["kind"]: b for b in res.json()["backends"]}+ assert backends["claude_code"]["available"] is True+ assert backends["codex"]["available"] is False+++def test_connect_list_and_disconnect_roundtrip(client):+ created = client.post(+ "/api/v1/subagents/connections",+ json={"name": "MyClaude", "agent_kind": "claude_code", "cwd": "/tmp"},+ )+ assert created.status_code == 200+ assert created.json()["agent_kind"] == "claude_code"++ listed = client.get("/api/v1/subagents/connections").json()["connections"]+ assert len(listed) == 1+ assert listed[0]["name"] == "MyClaude"+ assert listed[0]["agent_kind"] == "claude_code"+ assert listed[0]["cwd"] == "/tmp"++ gone = client.delete("/api/v1/subagents/connections/MyClaude")+ assert gone.status_code == 200+ assert client.get("/api/v1/subagents/connections").json()["connections"] == []+++def test_connect_rejects_unknown_kind(client):+ res = client.post(+ "/api/v1/subagents/connections",+ json={"name": "X", "agent_kind": "bogus"},+ )+ assert res.status_code == 400+++def test_disconnect_unknown_is_404(client):+ res = client.delete("/api/v1/subagents/connections/nope")+ assert res.status_code == 404+++def test_backend_options_endpoint_shape(client, monkeypatch):+ from deeptutor.services.subagent import models as models_mod+ from deeptutor.services.subagent.models import BackendOptions, ModelOption++ async def fake_options():+ return [+ BackendOptions(+ kind="codex",+ display_name="Codex",+ available=True,+ version="0.x",+ default_model="gpt-5.5",+ models=[ModelOption("gpt-5.5", "GPT-5.5", "medium", ["low", "medium", "high"])],+ efforts=["low", "medium", "high"],+ allow_custom_model=True,+ synced_at="2026-06-17T00:00:00Z",+ )+ ]++ # The route imports list_backend_options lazily from the models module.+ monkeypatch.setattr(models_mod, "list_backend_options", fake_options)++ res = client.get("/api/v1/subagents/backends/options")+ assert res.status_code == 200+ backends = res.json()["backends"]+ assert backends[0]["kind"] == "codex"+ assert backends[0]["default_model"] == "gpt-5.5"+ assert backends[0]["models"][0]["efforts"] == ["low", "medium", "high"]+ assert backends[0]["synced_at"] == "2026-06-17T00:00:00Z"+++def test_message_connection_streams_and_persists(client, monkeypatch, tmp_path):+ # Connect, then message the agent directly: the run streams as NDJSON and the+ # backend session id is remembered (keyed by chat session + connection).+ client.post(+ "/api/v1/subagents/connections",+ json={"name": "MyClaude", "agent_kind": "claude_code"},+ )++ from deeptutor.services.subagent import sessions as sess+ from deeptutor.services.subagent.types import ConsultResult, SubagentEvent++ monkeypatch.setattr(sess, "_path", lambda: tmp_path / "sessions.json")++ class _FakeBackend:+ kind = "claude_code"++ async def consult(self, message, *, on_event, cwd, session_id, config, images=None):+ await on_event(SubagentEvent(kind="text", text="hi", meta={"merge_id": "txt:m:0"}))+ return ConsultResult(final_text="hi", session_id="sess-9", success=True, event_count=1)++ monkeypatch.setattr(+ "deeptutor.services.subagent.get_backend", lambda kind: _FakeBackend()+ )++ res = client.post(+ "/api/v1/subagents/connections/MyClaude/message",+ json={"chat_session_id": "chatA", "message": "hello"},+ )+ assert res.status_code == 200+ lines = [json.loads(line) for line in res.text.splitlines() if line.strip()]++ # The user's own message heads the exchange.+ assert lines[0] == {"channel": "user_question", "text": "hello"}+ # The agent's event carries a sidebar-namespaced merge id.+ assert any(+ line.get("channel") == "text" and line.get("merge_id") == "side:txt:m:0" for line in lines+ )+ # The final line reports the session id, now persisted for the next turn.+ assert lines[-1]["done"] is True and lines[-1]["session_id"] == "sess-9"+ assert sess.get_session(sess.session_key("chatA", "MyClaude")) == "sess-9"+++def test_message_connection_unknown_is_404(client):+ res = client.post(+ "/api/v1/subagents/connections/nope/message",+ json={"chat_session_id": "x", "message": "hi"},+ )+ assert res.status_code == 404+++def test_backend_sync_endpoint(client, monkeypatch):+ from deeptutor.services.subagent import models as models_mod+ from deeptutor.services.subagent.models import BackendOptions, ModelOption++ async def fake_sync(kind):+ return BackendOptions(+ kind=kind,+ display_name="Claude Code",+ available=True,+ models=[ModelOption("opus", "Opus 4.8 · 1M context", efforts=["high"])],+ efforts=["high"],+ allow_custom_model=True,+ synced_at="2026-06-17T00:00:00Z",+ )++ monkeypatch.setattr(models_mod, "sync_backend_options", fake_sync)++ res = client.post("/api/v1/subagents/backends/claude_code/sync")+ assert res.status_code == 200+ body = res.json()+ assert body["kind"] == "claude_code"+ assert body["models"][0]["slug"] == "opus"+ assert body["synced_at"] == "2026-06-17T00:00:00Z"++ # Unknown backend is rejected.+ assert client.post("/api/v1/subagents/backends/bogus/sync").status_code == 400+++def test_settings_put_merges_per_field_and_backend(client):+ # Save one field for claude_code …+ r1 = client.put(+ "/api/v1/subagents/settings",+ json={"backends": {"claude_code": {"model": "opus"}}},+ )+ assert r1.status_code == 200+ # … then another field — the first must survive the merge.+ r2 = client.put(+ "/api/v1/subagents/settings",+ json={"backends": {"claude_code": {"effort": "high"}}},+ )+ cc = r2.json()["backends"]["claude_code"]+ assert cc["model"] == "opus" and cc["effort"] == "high"++ # Saving the OTHER backend must not clobber claude_code.+ r3 = client.put(+ "/api/v1/subagents/settings",+ json={"backends": {"codex": {"sandbox": "read-only"}}},+ )+ body = r3.json()+ assert body["backends"]["claude_code"]["model"] == "opus"+ assert body["backends"]["codex"]["sandbox"] == "read-only"++ # Updating only the budget must leave the backends intact.+ r4 = client.put("/api/v1/subagents/settings", json={"consult_budget": 7})+ body = r4.json()+ assert body["consult_budget"] == 7+ assert body["backends"]["claude_code"]["model"] == "opus"diff --git a/tests/api/test_voice_routes.py b/tests/api/test_voice_routes.pyindex 0fd47205d..288b0cc59 100644--- a/tests/api/test_voice_routes.py+++ b/tests/api/test_voice_routes.py@@ -2,7 +2,9 @@from __future__ import annotations+import iofrom typing import Any+import wavefrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -36,6 +38,28 @@ def test_tts_returns_audio_bytes(client: TestClient, monkeypatch: pytest.MonkeyPassert captured == {"text": "hello", "voice": "nova", "format": None}+def test_tts_wraps_pcm_bytes_as_browser_playable_wav(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pcm = b"\x00\x00\x01\x00" * 12++ async def fake_synth(text: str, *, voice=None, response_format=None, **_: Any):+ return pcm, "audio/pcm;rate=24000;channels=1"++ monkeypatch.setattr(voice_router, "synthesize_speech", fake_synth)+ resp = client.post("/api/v1/voice/tts", json={"text": "hello"})++ assert resp.status_code == 200+ assert resp.headers["content-type"] == "audio/wav"+ assert resp.content.startswith(b"RIFF")+ with wave.open(io.BytesIO(resp.content), "rb") as wav:+ assert wav.getframerate() == 24000+ assert wav.getnchannels() == 1+ assert wav.getsampwidth() == 2+ assert wav.readframes(wav.getnframes()) == pcm++def test_tts_rejects_empty_text(client: TestClient) -> None:resp = client.post("/api/v1/voice/tts", json={"text": ""})assert resp.status_code == 422 # pydantic min_lengthdiff --git a/tests/capabilities/test_subagent_capability.py b/tests/capabilities/test_subagent_capability.pynew file mode 100644index 000000000..616a4c4d7--- /dev/null+++ b/tests/capabilities/test_subagent_capability.py@@ -0,0 +1,251 @@+"""Tests for the subagent capability: binding, activation, tool budget/streaming.++The capability is the connected-agent twin of Obsidian — selecting a+``type: subagent`` KB runs the turn exclusively on ``consult_subagent``. These+tests stub the KB metadata resolver and the backend, so nothing spawns a real+CLI; they verify the wiring (binding, exclusivity, injected spec) and the tool's+authoritative consult-budget + session continuity + event streaming.+"""++from __future__ import annotations++import pytest++from deeptutor.agents._shared.tool_composition import ToolMountFlags, compose_enabled_tools+from deeptutor.capabilities import any_exclusive_capability_active+from deeptutor.capabilities.subagent import (+ SUBAGENT_TOOL_NAMES,+ ConsultSubagentTool,+ SubagentCapability,+ connection_for_turn,+)+from deeptutor.capabilities.subagent import binding as subagent_binding+from deeptutor.core.context import UnifiedContext+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.types import ConsultResult, SubagentEvent+++def _bind(monkeypatch, *, kind: str = "claude_code", cwd: str = "", name: str = "myagent") -> None:+ """Make ``resolve_kb_metadata`` report ``name`` as a connected subagent."""+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda ref: (+ {"name": ref, "type": "subagent", "agent_kind": kind, "cwd": cwd}+ if ref == name+ else {"name": ref, "type": None}+ ),+ )+++# ---- binding & activation ----------------------------------------------------+++def test_inactive_without_subagent_kb(monkeypatch) -> None:+ _bind(monkeypatch)+ cap = SubagentCapability()+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["plain-kb"])+ assert cap.is_active(ctx) is False+ assert cap.system_block(ctx, language="en", prompts={}) is None+++def test_active_injects_spec_and_min_rounds(monkeypatch) -> None:+ _bind(monkeypatch, kind="codex", cwd="/tmp/proj")+ cap = SubagentCapability()+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["myagent"])+ assert cap.is_active(ctx) is True+ assert tuple(cap.owned_tools) == SUBAGENT_TOOL_NAMES++ block = cap.system_block(ctx, language="en", prompts={})+ assert block is not None and "myagent" in block.content+ # The loop budget floor is lifted so the full consult budget + a finish+ # round always fit.+ assert ctx.metadata.get("_min_loop_rounds", 0) >= 2++ spec = cap.augment_kwargs("consult_subagent", {"question": "q"}, ctx)["_subagent"]+ assert spec["kind"] == "codex"+ assert spec["cwd"] == "/tmp/proj"+ assert spec["budget"] >= 1+ assert isinstance(spec["config"], BackendConfig)+ assert spec["state"] == {"count": 0, "session_id": None, "name": "myagent"}+ # Never injected for a non-owned tool.+ assert "_subagent" not in cap.augment_kwargs("rag", {}, ctx)+++def test_consult_budget_override_from_config(monkeypatch) -> None:+ _bind(monkeypatch)+ cap = SubagentCapability()+ # Per-turn override from the composer (request config) wins over the default.+ ctx = UnifiedContext(+ user_message="hi",+ knowledge_bases=["myagent"],+ config_overrides={"subagent_consult_budget": 3},+ )+ assert cap.augment_kwargs("consult_subagent", {"question": "q"}, ctx)["_subagent"]["budget"] == 3+ # Out-of-range values are clamped, not trusted.+ ctx_hi = UnifiedContext(+ user_message="hi",+ knowledge_bases=["myagent"],+ config_overrides={"subagent_consult_budget": 999},+ )+ assert (+ cap.augment_kwargs("consult_subagent", {"question": "q"}, ctx_hi)["_subagent"]["budget"]+ == 12+ )+++def test_binding_cached(monkeypatch) -> None:+ calls = {"n": 0}++ def fake(ref):+ calls["n"] += 1+ return {"name": ref, "type": "subagent", "agent_kind": "claude_code", "cwd": ""}++ monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_kb_metadata", fake)+ ctx = UnifiedContext(user_message="hi", knowledge_bases=["a"])+ subagent_binding.connection_for_turn(ctx)+ subagent_binding.connection_for_turn(ctx)+ assert calls["n"] == 1 # second call hits the per-turn cache+++# ---- exclusivity -------------------------------------------------------------+++def test_exclusive_compose_drops_everything_but_consult_and_ask_user() -> None:+ composed = compose_enabled_tools(+ registry=get_tool_registry(),+ requested_tools=["web_search", "rag"],+ optional_whitelist=["web_search", "rag"],+ mount_flags=ToolMountFlags(has_kb=True, has_code=True, has_memory=True),+ capability_owned=["consult_subagent"],+ exclusive=True,+ )+ assert set(composed) == {"consult_subagent", "ask_user"}+++def test_registry_flags_subagent_turn_as_exclusive(monkeypatch) -> None:+ _bind(monkeypatch)+ subagent_turn = UnifiedContext(user_message="hi", knowledge_bases=["myagent"])+ plain_turn = UnifiedContext(user_message="hi", knowledge_bases=["plain-kb"])+ assert any_exclusive_capability_active(subagent_turn) is True+ assert any_exclusive_capability_active(plain_turn) is False+++# ---- consult tool ------------------------------------------------------------+++class _FakeBackend:+ kind = "claude_code"++ def __init__(self) -> None:+ self.calls: list[tuple[str, str | None]] = []+ self.last_images: list[str] | None = None++ async def consult(self, question, *, on_event, cwd, session_id, config, images=None):+ self.calls.append((question, session_id))+ self.last_images = images+ await on_event(SubagentEvent(kind="tool", text="$ ls"))+ await on_event(SubagentEvent(kind="result", text=f"answer:{question}"))+ return ConsultResult(+ final_text=f"answer:{question}",+ session_id="sess-1",+ success=True,+ event_count=2,+ )+++def _spec(state: dict, *, budget: int = 2) -> dict:+ return {+ "kind": "claude_code",+ "cwd": "",+ "name": "myagent",+ "budget": budget,+ "config": BackendConfig(),+ "state": state,+ }+++async def test_consult_streams_events_and_threads_session(monkeypatch) -> None:+ backend = _FakeBackend()+ monkeypatch.setattr("deeptutor.services.subagent.get_backend", lambda kind: backend)+ tool = ConsultSubagentTool()+ state: dict = {"count": 0, "session_id": None, "name": "myagent"}+ streamed: list[tuple[str, str, str]] = []++ async def sink(event_type, message, metadata=None):+ streamed.append((event_type, message, (metadata or {}).get("subagent_channel", "")))++ res1 = await tool.execute(question="Q1", _subagent=_spec(state), event_sink=sink)+ assert res1.success is True+ assert "answer:Q1" in res1.content+ assert state["count"] == 1+ assert state["session_id"] == "sess-1" # captured for continuity+ # Every native event streamed out under the single subagent trace_kind.+ assert all(etype == "subagent_event" for etype, _, _ in streamed)+ channels = {chan for _, _, chan in streamed}+ assert "tool" in channels and "result" in channels++ # Second consult resumes the same backend session.+ await tool.execute(question="Q2", _subagent=_spec(state), event_sink=sink)+ assert backend.calls[1] == ("Q2", "sess-1")+++async def test_consult_budget_is_authoritative(monkeypatch) -> None:+ backend = _FakeBackend()+ monkeypatch.setattr("deeptutor.services.subagent.get_backend", lambda kind: backend)+ tool = ConsultSubagentTool()+ state: dict = {"count": 0, "session_id": None, "name": "myagent"}++ async def sink(*_a, **_k):+ return None++ await tool.execute(question="Q1", _subagent=_spec(state, budget=1), event_sink=sink)+ # Budget of 1 is spent → the second consult is refused without driving the backend.+ refused = await tool.execute(question="Q2", _subagent=_spec(state, budget=1), event_sink=sink)+ assert refused.success is False+ assert "budget" in refused.content.lower()+ assert len(backend.calls) == 1 # backend never invoked the second time+++async def test_consult_without_spec_is_graceful() -> None:+ res = await ConsultSubagentTool().execute(question="hi")+ assert res.success is False and "no subagent" in res.content.lower()+++async def test_session_id_persists_across_turns(monkeypatch, tmp_path) -> None:+ # A backend session id captured in one turn is remembered (keyed by chat+ # session + connection) and resumed by the next turn's augment_kwargs — so+ # the local agent keeps context across DeepTutor's separate messages.+ from deeptutor.services.subagent import sessions as sess++ monkeypatch.setattr(sess, "_path", lambda: tmp_path / "subagent_sessions.json")+ _bind(monkeypatch) # "myagent" → claude_code+ backend = _FakeBackend()+ monkeypatch.setattr("deeptutor.services.subagent.get_backend", lambda kind: backend)++ cap = SubagentCapability()+ tool = ConsultSubagentTool()++ async def sink(*_a, **_k):+ return None++ # Turn 1: nothing remembered yet → consult creates "sess-1", which persists.+ ctx1 = UnifiedContext(user_message="hi", knowledge_bases=["myagent"], session_id="chatA")+ spec1 = cap.augment_kwargs("consult_subagent", {"question": "Q1"}, ctx1)["_subagent"]+ assert spec1["state"]["session_id"] is None+ await tool.execute(question="Q1", _subagent=spec1, event_sink=sink)+ assert sess.get_session(sess.session_key("chatA", "myagent")) == "sess-1"++ # Turn 2 (fresh context): augment_kwargs seeds the remembered session.+ ctx2 = UnifiedContext(user_message="more", knowledge_bases=["myagent"], session_id="chatA")+ spec2 = cap.augment_kwargs("consult_subagent", {"question": "Q2"}, ctx2)["_subagent"]+ assert spec2["state"]["session_id"] == "sess-1"++ # A different chat session does not inherit the agent session.+ ctx3 = UnifiedContext(user_message="hi", knowledge_bases=["myagent"], session_id="chatB")+ spec3 = cap.augment_kwargs("consult_subagent", {"question": "Q"}, ctx3)["_subagent"]+ assert spec3["state"]["session_id"] is Nonediff --git a/tests/runtime/test_request_contracts_subagent.py b/tests/runtime/test_request_contracts_subagent.pynew file mode 100644index 000000000..d25f1a14a--- /dev/null+++ b/tests/runtime/test_request_contracts_subagent.py@@ -0,0 +1,27 @@+"""Regression: the per-turn subagent consult budget must pass chat-config validation.++``subagent_consult_budget`` rides in the request ``config`` (composer stepper)+but isn't part of any capability's public schema. It must be treated as a+runtime-only key, not rejected by ``extra="forbid"`` — otherwise a second turn+with a connected agent errors with "Extra inputs are not permitted".+"""++from __future__ import annotations++import pytest++from deeptutor.runtime.request_contracts import (+ validate_capability_config,+ validate_chat_request_config,+)+++def test_chat_config_allows_subagent_consult_budget() -> None:+ # Must not raise (it's stripped as a runtime-only key before validation).+ validate_chat_request_config({"subagent_consult_budget": 5})+ validate_capability_config("chat", {"subagent_consult_budget": 5})+++def test_chat_config_still_rejects_unknown_keys() -> None:+ with pytest.raises(ValueError, match="Extra inputs are not permitted"):+ validate_chat_request_config({"totally_unknown_key": 1})diff --git a/tests/services/partners/test_partner_manager_config.py b/tests/services/partners/test_partner_manager_config.pyindex a03e40959..66208a78c 100644--- a/tests/services/partners/test_partner_manager_config.py+++ b/tests/services/partners/test_partner_manager_config.py@@ -27,6 +27,7 @@ class TestConfigRoundTrip:color="#aabbcc",soul_origin={"type": "library", "id": "math-tutor"},enabled_tools=["web_search"],+ builtin_tools=["rag", "read_memory"],mcp_tools=[],)mgr.save_config("ada", config)@@ -42,6 +43,7 @@ class TestConfigRoundTrip:mgr.save_config("p1", PartnerConfig(name="P1"))loaded = mgr.load_config("p1")assert loaded.enabled_tools is None+ assert loaded.builtin_tools is Noneassert loaded.mcp_tools is Nonediff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.pyindex 0914d91f2..37078f65e 100644--- a/tests/services/partners/test_partner_runtime.py+++ b/tests/services/partners/test_partner_runtime.py@@ -2,6 +2,7 @@from __future__ import annotations+import asynciofrom typing import Anyimport pytest@@ -56,12 +57,18 @@ class _FakeOrchestrator:scripts: list[list[StreamEvent]] = []seen_contexts: list[Any] = []activated_selections: list[Any] = []+ # The memory root in effect while the turn runs — proves the partner reads+ # the owner's (admin) memory via memory_path_service_override, not its own.+ seen_memory_roots: list[Any] = []def __init__(self) -> None:passasync def handle(self, context):+ from deeptutor.services.memory.paths import memory_root+type(self).seen_contexts.append(context)+ type(self).seen_memory_roots.append(memory_root())script = type(self).scripts.pop(0) if type(self).scripts else type(self).scriptfor event in script:yield event@@ -76,6 +83,7 @@ def fake_orchestrator(monkeypatch):_FakeOrchestrator.scripts = []_FakeOrchestrator.seen_contexts = []_FakeOrchestrator.activated_selections = []+ _FakeOrchestrator.seen_memory_roots = []monkeypatch.setattr(orch_mod, "ChatOrchestrator", _FakeOrchestrator)def _record_activate(selection):@@ -222,6 +230,56 @@ class TestTurnExecution:assert "rate limited" in finalassert len(fake_orchestrator.seen_contexts) == 1+ @pytest.mark.asyncio+ async def test_llm_config_error_folds_into_graceful_reply(+ self, partners_root, fake_orchestrator, monkeypatch+ ):+ # A setup failure with no resolvable LLM model (LLMConfigError) must+ # fold into the turn's error path — an apology carrying the real reason+ # — instead of propagating as an opaque crash / bare "Internal error".+ from deeptutor.services.llm.exceptions import LLMConfigError+ from deeptutor.services.model_selection import runtime as selection_runtime++ def _raise(selection):+ raise LLMConfigError("No active LLM model is configured.")++ monkeypatch.setattr(selection_runtime, "activate_llm_selection", _raise)+ runner = _runner(partners_root)++ final = await runner.process_message(_msg("hi"))+ assert "No active LLM model is configured." in final+ # The orchestrator is never reached when LLM-selection resolution fails.+ assert fake_orchestrator.seen_contexts == []++ @pytest.mark.asyncio+ async def test_backup_retried_when_primary_selection_unresolvable(+ self, partners_root, fake_orchestrator, monkeypatch+ ):+ # Selection resolution now runs inside the turn's try, so a primary+ # model that no longer resolves falls back to the backup model instead+ # of crashing the turn outright.+ from deeptutor.services.llm.exceptions import LLMConfigError+ from deeptutor.services.model_selection import runtime as selection_runtime++ primary = {"profile_id": "p1", "model_id": "m1"}+ backup = {"profile_id": "p2", "model_id": "m2"}+ attempted: list[Any] = []++ def _activate(selection):+ attempted.append(selection)+ if selection == primary:+ raise LLMConfigError("primary profile is gone")+ return (None, None)++ monkeypatch.setattr(selection_runtime, "activate_llm_selection", _activate)+ fake_orchestrator.script = _finish("backup answer")+ config = PartnerConfig(name="Ada", llm_selection=primary, backup_llm_selection=backup)+ runner = _runner(partners_root, config)++ final = await runner.process_message(_msg())+ assert final == "backup answer"+ assert attempted == [primary, backup]+@pytest.mark.asyncioasync def test_successful_turn_never_touches_backup(self, partners_root, fake_orchestrator):backup = {"profile_id": "p2", "model_id": "m2"}@@ -364,7 +422,205 @@ class TestContextAssembly:assert "Gradient descent" in attachment["extracted_text"]+class TestBuiltinToolsAndMemory:+ @pytest.mark.asyncio+ async def test_builtin_tools_default_to_no_gating(self, partners_root, fake_orchestrator):+ fake_orchestrator.script = _finish("ok")+ runner = _runner(partners_root) # builtin_tools=None++ await runner.process_message(_msg())++ context = fake_orchestrator.seen_contexts[0]+ # None = no gating: every built-in mounts under its usual condition.+ assert context.allowed_builtin_tools is None++ @pytest.mark.asyncio+ async def test_builtin_tools_whitelist_flows_to_context(self, partners_root, fake_orchestrator):+ fake_orchestrator.script = _finish("ok")+ config = PartnerConfig(name="Ada", builtin_tools=["rag", "web_fetch"])+ runner = _runner(partners_root, config)++ await runner.process_message(_msg())++ context = fake_orchestrator.seen_contexts[0]+ assert context.allowed_builtin_tools == ["rag", "web_fetch"]++ @pytest.mark.asyncio+ async def test_turn_runs_against_owner_memory(self, partners_root, fake_orchestrator):+ """The turn resolves memory to the admin (owner) workspace, not the+ partner's own empty scope — so read_memory can know the user."""+ from deeptutor.multi_user.paths import get_admin_path_service++ fake_orchestrator.script = _finish("ok")+ runner = _runner(partners_root)++ await runner.process_message(_msg())++ admin_memory = get_admin_path_service().get_memory_dir().resolve()+ seen = fake_orchestrator.seen_memory_roots[0].resolve()+ assert seen == admin_memory+ assert "partners" not in seen.parts # NOT the partner's own scope++ @pytest.mark.asyncio+ async def test_memory_override_is_reset_after_turn(self, partners_root, fake_orchestrator):+ from deeptutor.services.memory.paths import memory_root++ fake_orchestrator.script = _finish("ok")+ runner = _runner(partners_root)+ before = memory_root()++ await runner.process_message(_msg())++ # The ContextVar override must not leak past the turn.+ assert memory_root() == before++ @pytest.mark.asyncio+ async def test_turn_trace_persisted_for_rehydration(self, partners_root, fake_orchestrator):+ fake_orchestrator.script = _narration_round("c1", "let me check") + _finish("4.")+ runner = _runner(partners_root)++ await runner.process_message(_msg("what is 2+2?"))++ records = runner.store.messages("telegram:42")+ assistant = next(r for r in records if r["role"] == "assistant")+ events = assistant.get("events")+ assert events, "assistant turn must persist its trace events"+ # done/session are excluded; the narration + finish content survive.+ assert all(e.get("type") != "done" for e in events)+ assert any(e.get("type") == "content" for e in events)++ @pytest.mark.asyncio+ async def test_session_title_is_first_user_message(self, partners_root, fake_orchestrator):+ fake_orchestrator.script = _finish("the answer is 4")+ runner = _runner(partners_root)++ await runner.process_message(_msg("what is two plus two?"))++ session = runner.store.list_sessions()[0]+ assert session["title"] == "what is two plus two?"+++class TestSessionStoreOps:+ def test_archive_flag_is_soft_and_reversible(self, partners_root):+ store = PartnerSessionStore(_runner(partners_root).store._dir)+ store.append("web-a", "user", "hi")+ assert store.is_archived("web-a") is False+ store.set_archived("web-a", True)+ assert store.is_archived("web-a") is True+ # File is untouched (still resumable) and excluded from the merged view.+ assert store._path("web-a").exists()+ assert store.merged_messages() == []+ store.set_archived("web-a", False)+ assert store.is_archived("web-a") is False++ def test_branch_copies_history_and_archives_source(self, partners_root):+ store = PartnerSessionStore(_runner(partners_root).store._dir)+ store.append("web-a", "user", "q1")+ store.append("web-a", "assistant", "a1", events=[{"type": "content"}])+ summary = store.branch("web-a", "web-b")+ assert summary is not None and summary["message_count"] == 2+ assert store.is_archived("web-a") is True+ assert [m["content"] for m in store.messages("web-b")] == ["q1", "a1"]+ # Events ride along so the branched copy rehydrates its trace too.+ assert store.messages("web-b")[1].get("events")++ def test_delete_removes_file_and_index(self, partners_root):+ store = PartnerSessionStore(_runner(partners_root).store._dir)+ store.append("web-a", "user", "hi")+ store.set_archived("web-a", True)+ assert store.delete_session("web-a") is True+ assert store.delete_session("web-a") is False+ assert store.list_sessions() == []+++class TestLiveTurn:+ def test_buffer_replays_for_late_subscriber(self):+ from deeptutor.services.partners.manager import LiveTurn++ turn = LiveTurn(user_content="q")+ turn.emit({"type": "stream_event", "event": {"i": 1}})+ turn.emit({"type": "stream_event", "event": {"i": 2}})+ # A client that reconnects mid-turn replays the whole backlog...+ late = turn.subscribe()+ assert [late.get_nowait()["event"]["i"] for _ in range(2)] == [1, 2]+ # ...and keeps receiving new frames after subscribing.+ turn.emit({"type": "stream_event", "event": {"i": 3}})+ assert late.get_nowait()["event"]["i"] == 3++ def test_finish_pushes_terminal_and_marks_done(self):+ from deeptutor.services.partners.manager import LiveTurn++ turn = LiveTurn()+ q = turn.subscribe()+ turn.finish([{"type": "content", "content": "hi"}, {"type": "done"}])+ assert turn.done is True+ assert q.get_nowait()["type"] == "content"+ assert q.get_nowait()["type"] == "done"+ # A subscriber arriving after completion still replays the full turn.+ post = turn.subscribe()+ kinds = [post.get_nowait()["type"] for _ in range(post.qsize())]+ assert kinds == ["content", "done"]++ @pytest.mark.asyncio+ async def test_web_turn_runs_on_instance_and_survives_resubscribe(+ self, partners_root, fake_orchestrator+ ):+ from deeptutor.services.partners.manager import PartnerManager++ fake_orchestrator.script = _narration_round("c1", "working") + _finish("done!")+ mgr = PartnerManager()+ mgr.save_config("ada", PartnerConfig(name="Ada"), auto_start=True)+ await mgr.start_partner("ada")+ try:+ turn = mgr.start_web_turn("ada", "web-x", "hello", [])+ queue = turn.subscribe()+ frames: list[dict] = []+ while True:+ frame = await asyncio.wait_for(queue.get(), timeout=5)+ frames.append(frame)+ if frame["type"] in {"done", "stopped"}:+ break+ assert any(f["type"] == "content" and f["content"] == "done!" for f in frames)+ assert turn.done is True+ # Reconnect after completion → no live turn to attach to (history+ # serves it); a still-running turn would return the LiveTurn.+ assert mgr.subscribe_web_turn("ada", "web-x") is None+ # The completed turn persisted to the session store.+ assert mgr.session_store("ada").messages("web-x")[-1]["content"] == "done!"+ finally:+ await mgr.stop_partner("ada")++class TestPartnerCommands:+ @pytest.mark.asyncio+ async def test_sessions_resume_delete_commands(self, partners_root, fake_orchestrator):+ from deeptutor.services.partners.commands import PartnerCommandHandler++ runner = _runner(partners_root)+ fake_orchestrator.script = _finish("ok")+ await runner.process_message(_msg("hello")) # creates telegram:42++ handler = PartnerCommandHandler(partner_id="ada", config=runner.config, store=runner.store)+ listed = handler.dispatch(_msg("/sessions"))+ assert listed is not None and "telegram_42" in listed.content++ # /delete an existing key, /resume clears an archived flag.+ runner.store.set_archived("telegram:42", True)+ resumed = handler.dispatch(_msg("/resume telegram:42"))+ assert resumed is not None and not runner.store.is_archived("telegram:42")+ deleted = handler.dispatch(_msg("/delete telegram:42"))+ assert deleted is not None and "Deleted" in deleted.content+ assert handler.dispatch(_msg("/delete telegram:42")).content.startswith("No conversation")++ @pytest.mark.asyncio+ async def test_stop_command_is_a_noop_on_im(self, partners_root, fake_orchestrator):+ from deeptutor.services.partners.commands import PartnerCommandHandler++ runner = _runner(partners_root)+ handler = PartnerCommandHandler(partner_id="ada", config=runner.config, store=runner.store)+ result = handler.dispatch(_msg("/stop"))+ assert result is not None and "nothing" in result.content.lower()+@pytest.mark.asyncioasync def test_new_archives_current_session_without_calling_orchestrator(self, partners_root, fake_orchestratordiff --git a/tests/services/skill/test_skill_hub.py b/tests/services/skill/test_skill_hub.pyindex 979932c3e..f535c818f 100644--- a/tests/services/skill/test_skill_hub.py+++ b/tests/services/skill/test_skill_hub.py@@ -273,6 +273,91 @@ def test_clawhub_verify_states() -> None:assert offline.verify("demo").status == "unknown"+# ── ClawHubProvider: in-app browser (catalog / detail / web origin) ────────+++def _browse_client() -> httpx.Client:+ def handler(request: httpx.Request) -> httpx.Response:+ path = request.url.path+ if path == "/api/v1/skills":+ return httpx.Response(+ 200,+ json={+ "skills": [+ {+ "slug": "socratic-tutor",+ "displayName": "Socratic Tutor",+ "summary": "Teach by asking.",+ "version": "1.0.0",+ "stats": {"downloads": 8, "stars": 2},+ "ownerHandle": "deeptutor",+ "owner": {+ "displayName": "DeepTutor",+ "htmlUrl": "https://deeptutor.info",+ },+ },+ {"slug": "", "displayName": "blank"}, # dropped: no slug+ ]+ },+ )+ if path == "/api/v1/search":+ return httpx.Response(+ 200,+ json={"results": [{"slug": "socratic-tutor", "displayName": "Socratic Tutor"}]},+ )+ if path == "/api/v1/skills/socratic-tutor":+ return httpx.Response(+ 200,+ json={+ "skill": {+ "slug": "socratic-tutor",+ "displayName": "Socratic Tutor",+ "summary": "Teach.",+ "description": "---\nname: socratic-tutor\n---\n\n# Body\n",+ # EduHub stores dist-tags under `tags`; topical labels+ # live in `keywords`.+ "tags": {"latest": "1.0.0"},+ "keywords": ["tutor", "socratic"],+ "stats": {"downloads": 8, "stars": 2},+ },+ "owner": {"displayName": "DeepTutor", "htmlUrl": "https://deeptutor.info"},+ "distTags": {"latest": "1.0.0"},+ },+ )+ return httpx.Response(404, text="nope")++ return httpx.Client(transport=httpx.MockTransport(handler))+++def test_clawhub_catalog_normalises_rows() -> None:+ rows = ClawHubProvider(client=_browse_client()).catalog()+ assert len(rows) == 1 # the blank-slug row is dropped+ row = rows[0]+ assert (row["slug"], row["name"]) == ("socratic-tutor", "Socratic Tutor")+ assert (row["downloads"], row["stars"]) == (8, 2)+ assert row["owner"] == "DeepTutor"+ assert row["owner_url"] == "https://deeptutor.info"+++def test_clawhub_catalog_uses_search_when_queried() -> None:+ rows = ClawHubProvider(client=_browse_client()).catalog(query="socratic")+ assert rows and rows[0]["slug"] == "socratic-tutor"+++def test_clawhub_detail_includes_body_version_and_tags() -> None:+ detail = ClawHubProvider(client=_browse_client()).detail("socratic-tutor")+ assert detail["version"] == "1.0.0" # resolved from distTags+ # topical labels come from `keywords`, not EduHub's dist-tags `tags` map+ assert detail["tags"] == ["tutor", "socratic"]+ assert "# Body" in detail["content"]+ assert detail["owner"] == "DeepTutor" # lifted from the envelope top level+++def test_clawhub_web_origin_strips_api_suffix() -> None:+ provider = ClawHubProvider("eduhub", base_url="https://eduhub.deeptutor.info/api/v1")+ assert provider.web_origin == "https://eduhub.deeptutor.info"++# ── orchestration ────────────────────────────────────────────────────────@@ -346,6 +431,17 @@ def test_install_from_hub_uses_registry_summary_as_fallback(assert outcome.result.info.description == "registry summary"+def test_install_from_hub_stamps_source_hub_as_tag(tmp_path: Path, svc: SkillService) -> None:+ pkg = _make_package(tmp_path / "pkg", frontmatter="name: demo\ndescription: d\ntags: [tutor]\n")+ provider = _FakeProvider(pkg, HubVerdict(status="ok"))+ outcome = install_from_hub("fakehub:demo", service=svc, provider=provider)+ # the source hub rides along as a tag, alongside the package's own tags+ assert "fakehub" in outcome.result.info.tags+ assert "tutor" in outcome.result.info.tags+ meta, _ = svc._parse_frontmatter(svc.get_detail("demo").content)+ assert "fakehub" in meta["tags"]++# ── CommandProvider ──────────────────────────────────────────────────────diff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.pynew file mode 100644index 000000000..1c43463c2--- /dev/null+++ b/tests/services/test_subagent_backends.py@@ -0,0 +1,594 @@+"""Tests for the subagent driver layer: command building, event parsing,+the streaming-subprocess primitive, and settings.++Event parsing is exercised by feeding crafted CLI events straight into each+backend's handler — no real ``claude`` / ``codex`` process is spawned, so the+suite is fast and deterministic. The one live subprocess test drives ``python``+to prove the streaming primitive surfaces stdout/stderr in order with an exit.+"""++from __future__ import annotations++import sys++import pytest++from deeptutor.services.subagent.claude_code import ClaudeCodeBackend+from deeptutor.services.subagent.codex import CodexBackend+from deeptutor.services.subagent.config import (+ CONSULT_BUDGET_MAX,+ DEFAULT_CONSULT_BUDGET,+ BackendConfig,+ SubagentSettings,+ settings_from_dict,+)+from deeptutor.services.subagent.process import stream_process_lines+from deeptutor.services.subagent.types import ConsultResult++# ---- command building --------------------------------------------------------+++def test_claude_command_build_fresh_and_resume() -> None:+ backend = ClaudeCodeBackend()+ cfg = BackendConfig(permission_mode="acceptEdits", extra_args=["--foo"])+ fresh = backend._build_command("hi", session_id=None, config=cfg)+ assert fresh[:3] == ["claude", "-p", "hi"]+ assert "--output-format" in fresh and "stream-json" in fresh and "--verbose" in fresh+ assert "--permission-mode" in fresh and "acceptEdits" in fresh+ assert "--resume" not in fresh+ assert fresh[-1] == "--foo"++ resumed = backend._build_command("again", session_id="sess-1", config=cfg)+ assert "--resume" in resumed and "sess-1" in resumed+++def test_codex_command_build_sandbox_and_resume() -> None:+ backend = CodexBackend()+ cfg = BackendConfig(sandbox="workspace-write")+ fresh = backend._build_command("hi", session_id=None, config=cfg)+ assert fresh[:2] == ["codex", "exec"]+ assert "resume" not in fresh+ assert "--json" in fresh and "--skip-git-repo-check" in fresh+ assert "-c" in fresh and 'sandbox_mode="workspace-write"' in fresh+ assert fresh[-1] == "hi" # prompt is the trailing positional++ resumed = backend._build_command("again", session_id="abc", config=cfg)+ assert resumed[1:3] == ["exec", "resume"] and "abc" in resumed+++def test_claude_command_applies_model_effort_system_prompt() -> None:+ backend = ClaudeCodeBackend()+ cfg = BackendConfig(model="opus", effort="high", system_prompt="consulted by DeepTutor")+ cmd = backend._build_command("hi", session_id=None, config=cfg)+ assert "--model" in cmd and "opus" in cmd+ assert "--effort" in cmd and "high" in cmd+ assert "--append-system-prompt" in cmd and "consulted by DeepTutor" in cmd+++def test_codex_command_applies_model_effort_network_ephemeral() -> None:+ backend = CodexBackend()+ cfg = BackendConfig(+ model="gpt-5-codex",+ effort="high",+ network_access=True,+ ephemeral=True,+ approval="never",+ sandbox="workspace-write",+ )+ fresh = backend._build_command("hi", session_id=None, config=cfg)+ assert "-m" in fresh and "gpt-5-codex" in fresh+ assert 'model_reasoning_effort="high"' in fresh+ assert 'approval_policy="never"' in fresh+ assert "sandbox_workspace_write.network_access=true" in fresh+ assert "--ephemeral" in fresh+ # --ephemeral is a fresh-only flag — resuming an existing session omits it.+ resumed = backend._build_command("hi", session_id="s1", config=cfg)+ assert "--ephemeral" not in resumed+++def test_codex_command_bypass_uses_real_flag() -> None:+ backend = CodexBackend()+ cmd = backend._build_command("hi", session_id=None, config=BackendConfig(sandbox="bypass"))+ assert "--dangerously-bypass-approvals-and-sandbox" in cmd+ assert "-c" not in cmd # bypass replaces the sandbox_mode override+++def test_claude_command_forwards_images_via_read() -> None:+ # CC's -p has no image flag, so we point its Read tool at the files and grant+ # their directory with --add-dir.+ backend = ClaudeCodeBackend()+ imgs = ["/tmp/dt-x/00_a.png", "/tmp/dt-x/01_b.png"]+ cmd = backend._build_command("look", session_id=None, config=BackendConfig(), images=imgs)+ prompt = cmd[2]+ assert "Read tool" in prompt+ assert "/tmp/dt-x/00_a.png" in prompt and "/tmp/dt-x/01_b.png" in prompt+ assert "--add-dir" in cmd and "/tmp/dt-x" in cmd+++def test_codex_command_attaches_images_with_repeated_flag() -> None:+ # Repeated -i (not the variadic form) so the trailing prompt is never swallowed.+ backend = CodexBackend()+ imgs = ["/tmp/dt-y/00_a.png", "/tmp/dt-y/01_b.png"]+ cmd = backend._build_command("look", session_id=None, config=BackendConfig(), images=imgs)+ assert cmd.count("-i") == 2+ assert cmd[cmd.index("-i") + 1] == "/tmp/dt-y/00_a.png"+ assert cmd[-1] == "look" # prompt stays the trailing positional+++# ---- Claude Code event parsing -----------------------------------------------+++async def _drive(backend, events):+ """Feed crafted events through a backend handler, collecting emitted events."""+ result = ConsultResult()+ emitted: list[tuple[str, str]] = []++ async def emit(kind, text, raw, meta=None):+ emitted.append((kind, text))++ if isinstance(backend, ClaudeCodeBackend):+ assistant_text: list[str] = []+ stream: dict = {"msg_id": "", "blocks": {}}+ for ev in events:+ await backend._handle_event(ev, result, assistant_text, stream, emit)+ if not result.final_text and assistant_text:+ result.final_text = "\n".join(assistant_text)+ else:+ for ev in events:+ await backend._handle_event(ev, result, emit)+ return result, emitted+++async def test_claude_event_parsing_captures_session_text_and_tools() -> None:+ backend = ClaudeCodeBackend()+ events = [+ {"type": "system", "subtype": "init", "session_id": "s1", "model": "opus"},+ {+ "type": "assistant",+ "session_id": "s1",+ "message": {+ "content": [+ {"type": "text", "text": "Looking into it."},+ {"type": "tool_use", "name": "Read", "input": {"file": "a.py"}},+ ]+ },+ },+ {+ "type": "user",+ "message": {"content": [{"type": "tool_result", "content": "file body"}]},+ },+ # The final answer arrives as an assistant text block …+ {+ "type": "assistant",+ "session_id": "s1",+ "message": {"content": [{"type": "text", "text": "Final answer."}]},+ },+ # … and the result event mirrors it (we don't re-emit — no duplicate row).+ {"type": "result", "subtype": "success", "result": "Final answer.", "session_id": "s1"},+ ]+ result, emitted = await _drive(backend, events)+ assert result.session_id == "s1"+ assert result.final_text == "Final answer."+ kinds = [k for k, _ in emitted]+ assert "text" in kinds and "tool" in kinds and "tool_result" in kinds+ # The answer text is emitted exactly once (as the assistant block, not again+ # as a separate result event).+ assert [t for k, t in emitted if t == "Final answer."] == ["Final answer."]+++async def test_claude_falls_back_to_assistant_text_without_result() -> None:+ backend = ClaudeCodeBackend()+ events = [+ {+ "type": "assistant",+ "message": {"content": [{"type": "text", "text": "Partial thought."}]},+ },+ ]+ result, _ = await _drive(backend, events)+ assert result.final_text == "Partial thought."+++async def test_claude_partial_messages_stream_cumulative_text() -> None:+ # --include-partial-messages emits stream_event deltas; we accumulate them+ # into cumulative text under one merge id, and the complete assistant block+ # finalizes the same row (no duplicate). The frontend keeps the latest.+ backend = ClaudeCodeBackend()+ captured: list[tuple[str, str, str]] = []++ async def emit(kind, text, raw, meta=None):+ captured.append((kind, text, (meta or {}).get("merge_id", "")))++ result = ConsultResult()+ assistant_text: list[str] = []+ stream: dict = {"msg_id": "", "blocks": {}}+ events = [+ {"type": "stream_event", "event": {"type": "message_start", "message": {"id": "msg_1"}}},+ {+ "type": "stream_event",+ "event": {"type": "content_block_start", "index": 0,+ "content_block": {"type": "text", "text": ""}},+ },+ {+ "type": "stream_event",+ "event": {"type": "content_block_delta", "index": 0,+ "delta": {"type": "text_delta", "text": "Hel"}},+ },+ {+ "type": "stream_event",+ "event": {"type": "content_block_delta", "index": 0,+ "delta": {"type": "text_delta", "text": "lo"}},+ },+ {"type": "assistant", "message": {"id": "msg_1", "content": [{"type": "text", "text": "Hello"}]}},+ ]+ for ev in events:+ await backend._handle_event(ev, result, assistant_text, stream, emit)++ texts = [(t, mid) for k, t, mid in captured if k == "text"]+ assert texts == [+ ("Hel", "txt:msg_1:0"),+ ("Hello", "txt:msg_1:0"),+ ("Hello", "txt:msg_1:0"),+ ]+++async def test_claude_result_without_assistant_text_is_surfaced() -> None:+ # Degenerate run: the answer arrives only in the result event (no assistant+ # text block streamed) — surface it so the user still sees an answer.+ backend = ClaudeCodeBackend()+ result, emitted = await _drive(+ backend, [{"type": "result", "subtype": "success", "result": "Only here."}]+ )+ assert result.final_text == "Only here."+ assert ("text", "Only here.") in emitted+++# ---- Codex event parsing -----------------------------------------------------+++async def test_codex_event_parsing_thread_items_and_final() -> None:+ backend = CodexBackend()+ events = [+ {"type": "thread.started", "thread_id": "t1"},+ {"type": "turn.started"},+ {"type": "item.started", "item": {"type": "command_execution", "command": "ls"}},+ {+ "type": "item.completed",+ "item": {"type": "command_execution", "command": "ls", "exit_code": 0, "output": "a\nb"},+ },+ {"type": "item.completed", "item": {"type": "agent_message", "text": "All done."}},+ {"type": "turn.completed", "usage": {}},+ ]+ result, emitted = await _drive(backend, events)+ assert result.session_id == "t1"+ assert result.final_text == "All done."+ kinds = [k for k, _ in emitted]+ # The answer renders as the terminal text of the run (not a separate result).+ assert "tool" in kinds and "tool_result" in kinds and "text" in kinds+++async def test_codex_web_search_start_and_finish_share_merge_id() -> None:+ # web_search streams a start placeholder then a filled finish; both carry+ # the SAME merge id so the UI collapses them into one evolving row (rather+ # than two lines, one empty). command_execution is unaffected (two rows).+ backend = CodexBackend()+ captured: list[tuple[str, str]] = []++ async def emit(kind, text, raw, meta=None):+ captured.append((text, (meta or {}).get("merge_id", "")))++ result = ConsultResult()+ for ev in (+ {"type": "item.started", "item": {"id": "ws_1", "type": "web_search", "query": ""}},+ {+ "type": "item.completed",+ "item": {"id": "ws_1", "type": "web_search", "query": "agentic RAG"},+ },+ ):+ await backend._handle_event(ev, result, emit)++ web = [(t, mid) for t, mid in captured if "web search" in t]+ assert [t for t, _ in web] == ["web search", "web search · agentic RAG"]+ assert {mid for _, mid in web} == {"ws_1"} # both phases share the merge id+++async def test_codex_non_web_items_render_once_on_completion() -> None:+ # agent_message has no meaningful start line → renders once, on completion.+ backend = CodexBackend()+ events = [+ {"type": "item.started", "item": {"id": "m1", "type": "agent_message", "text": ""}},+ {"type": "item.completed", "item": {"id": "m1", "type": "agent_message", "text": "done"}},+ ]+ result, emitted = await _drive(backend, events)+ assert [t for _k, t in emitted] == ["done"]+++async def test_codex_item_updated_streams_cumulative_answer() -> None:+ # "*.updated" frames carry the answer's growing text; we stream the running+ # text under the item id, and ".completed" finalizes the same merged row.+ backend = CodexBackend()+ captured: list[tuple[str, str, str]] = []++ async def emit(kind, text, raw, meta=None):+ captured.append((kind, text, (meta or {}).get("merge_id", "")))++ result = ConsultResult()+ events = [+ {"type": "item.started", "item": {"id": "m1", "type": "agent_message", "text": ""}},+ {"type": "item.updated", "item": {"id": "m1", "type": "agent_message", "text": "The ans"}},+ {"type": "item.updated", "item": {"id": "m1", "type": "agent_message", "text": "The answer"}},+ {"type": "item.completed", "item": {"id": "m1", "type": "agent_message", "text": "The answer is 42"}},+ ]+ for ev in events:+ await backend._handle_event(ev, result, emit)++ texts = [(t, mid) for k, t, mid in captured if k == "text"]+ assert texts == [+ ("The ans", "m1"),+ ("The answer", "m1"),+ ("The answer is 42", "m1"),+ ]+ assert result.final_text == "The answer is 42"+++async def test_codex_turn_failed_marks_error() -> None:+ backend = CodexBackend()+ result, emitted = await _drive(+ backend, [{"type": "turn.failed", "message": "boom"}]+ )+ assert result.success is False and result.error == "boom"+ assert ("error", "boom") in emitted+++# ---- streaming subprocess primitive ------------------------------------------+++async def test_stream_process_lines_interleaves_and_reports_exit() -> None:+ script = "import sys; print('out1'); print('err1', file=sys.stderr); print('out2')"+ seen: list[tuple[str, str]] = []+ async for channel, line in stream_process_lines([sys.executable, "-c", script]):+ seen.append((channel, line))+ assert ("stdout", "out1") in seen+ assert ("stdout", "out2") in seen+ assert ("stderr", "err1") in seen+ assert seen[-1] == ("exit", "0")+++async def test_stream_process_lines_reports_nonzero_exit() -> None:+ seen = [+ item+ async for item in stream_process_lines([sys.executable, "-c", "import sys; sys.exit(3)"])+ ]+ assert seen[-1] == ("exit", "3")+++# ---- settings ----------------------------------------------------------------+++def test_settings_from_dict_clamps_budget_and_reads_backends() -> None:+ s = settings_from_dict(+ {+ "consult_budget": 999,+ "backends": {"codex": {"sandbox": "read-only", "enabled": False}},+ }+ )+ assert s.consult_budget == CONSULT_BUDGET_MAX+ assert s.backend("codex").sandbox == "read-only"+ assert s.backend("codex").enabled is False+ # Unknown backend → defaults.+ assert s.backend("claude_code").permission_mode == BackendConfig().permission_mode+++def test_settings_defaults() -> None:+ assert SubagentSettings().consult_budget == DEFAULT_CONSULT_BUDGET+ assert settings_from_dict({}).consult_budget == DEFAULT_CONSULT_BUDGET+++# ---- image forwarding (materialization) --------------------------------------+++def test_materialize_images_writes_only_resolvable_images(tmp_path) -> None:+ import base64 as _b64+ from pathlib import Path++ from deeptutor.core.context import Attachment+ from deeptutor.services.subagent.images import materialize_images++ atts = [+ Attachment(type="image", base64=_b64.b64encode(b"\x89PNGdata").decode(), mime_type="image/png"),+ Attachment(+ type="image",+ base64="data:image/jpeg;base64," + _b64.b64encode(b"JPEGdata").decode(),+ filename="shot.jpg",+ ),+ Attachment(type="file", base64=_b64.b64encode(b"x").decode()), # not an image+ Attachment(type="image", url="https://example.com/remote.png"), # external, unresolvable+ ]+ paths = materialize_images(atts, tmp_path)++ assert len(paths) == 2 # the two inline images only+ assert paths[0].endswith(".png") and paths[1].endswith(".jpg")+ assert Path(paths[0]).read_bytes() == b"\x89PNGdata"+ assert Path(paths[1]).read_bytes() == b"JPEGdata"+++# ---- Claude Code /model scraping (live model sync) ---------------------------++# A faithful render of the ``/model`` picker (as pyte produces it: real columns,+# a ❯ cursor, a ✔ on the active row, wrapped description continuation lines).+_CLAUDE_MODEL_SCREEN = """\+ Select model+ Switch between Claude models. Your pick becomes the default for new+ sessions. For other/previous model names, specify with --model.+ 1. Default (recommended) Opus 4.8 with 1M context · Best for everyday,+ complex tasks+ ❯ 2. Opus ✔ Opus 4.8 with 1M context · Best for everyday,+ complex tasks+ 3. Sonnet Sonnet 4.6 · Efficient for routine tasks+ 4. Sonnet (1M context) Sonnet 4.6 with 1M context · Draws from usage+ credits · $3/$15 per Mtok+ 5. Haiku Haiku 4.5 · Fastest for quick answers+ 6. Fable (disabled) Claude Fable 5 is currently unavailable. Learn+ more: https://www.anthropic.com/news/fable+ ◉ xHigh effort ←/→ to adjust+ Enter to set as default · s to use this session only · Esc to cancel+"""+++def test_parse_claude_model_screen() -> None:+ from deeptutor.services.subagent.claude_models import _parse_model_screen++ models = _parse_model_screen(_CLAUDE_MODEL_SCREEN)+ # Default (recommended) → CLI default (skipped); Fable (disabled) → skipped.+ # Sonnet's 1M variant maps to the [1m] alias.+ assert models == [+ {"slug": "opus", "display_name": "Opus 4.8 with 1M context"},+ {"slug": "sonnet", "display_name": "Sonnet 4.6"},+ {"slug": "sonnet[1m]", "display_name": "Sonnet 4.6 with 1M context"},+ {"slug": "haiku", "display_name": "Haiku 4.5"},+ ]+++def test_claude_models_cache_roundtrip(monkeypatch, tmp_path) -> None:+ from deeptutor.services.subagent import claude_models as cm++ monkeypatch.setattr(cm, "_cache_path", lambda: tmp_path / "claude_models_cache.json")+ assert cm.load_cached_claude_models() == ([], "")++ cm._write_cache([{"slug": "opus", "display_name": "Opus 4.8"}], "2026-06-17T00:00:00Z")+ models, fetched = cm.load_cached_claude_models()+ assert models == [{"slug": "opus", "display_name": "Opus 4.8"}]+ assert fetched == "2026-06-17T00:00:00Z"+++async def test_claude_options_prefers_synced_cache(monkeypatch) -> None:+ """When a /model sync has cached a catalog, _claude_options uses it over the+ curated fallback."""+ from deeptutor.services.subagent import claude_models as cm+ from deeptutor.services.subagent import models as models_mod++ monkeypatch.setattr(+ cm,+ "load_cached_claude_models",+ lambda: ([{"slug": "opus", "display_name": "Opus 4.8 (synced)"}], "2026-06-17T00:00:00Z"),+ )++ async def fake_probe(cmd):+ return True, "claude x.y"++ monkeypatch.setattr(models_mod, "probe_version", fake_probe)++ opts = await models_mod._claude_options()+ assert [m.slug for m in opts.models] == ["opus"]+ assert opts.models[0].display_name == "Opus 4.8 (synced)"+ assert opts.synced_at == "2026-06-17T00:00:00Z"+++# ---- persistent session registry (cross-turn continuity) ---------------------+++def test_session_registry_roundtrip(monkeypatch, tmp_path) -> None:+ from deeptutor.services.subagent import sessions as sess++ monkeypatch.setattr(sess, "_path", lambda: tmp_path / "subagent_sessions.json")+ key = sess.session_key("chat1", "agentX")+ assert sess.get_session(key) is None++ sess.remember_session(key, "sid-9", kind="codex", cwd="/p")+ sess.remember_session("chat1::other", "sid-2")+ assert sess.get_session(key) == "sid-9"++ # Disconnecting agentX drops only its sessions.+ sess.forget_connection("agentX")+ assert sess.get_session(key) is None+ assert sess.get_session("chat1::other") == "sid-2"++ # Empty session id is a no-op (never persisted).+ sess.remember_session("chat1::agentZ", "")+ assert sess.get_session("chat1::agentZ") is None+++# ---- backend options (models.py, the /settings sync source) ------------------+++async def test_list_backend_options_reads_codex_cache(monkeypatch, tmp_path) -> None:+ """Codex options come from the live models_cache.json + config.toml default;+ Claude Code falls back to its aliases and allows a free-text model."""+ import json++ from deeptutor.services.subagent import models as models_mod++ home = tmp_path / "codex"+ home.mkdir()+ (home / "models_cache.json").write_text(+ json.dumps(+ {+ "fetched_at": "2026-06-17T00:00:00Z",+ "models": [+ {+ "slug": "gpt-5.5",+ "display_name": "GPT-5.5",+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {"effort": "low"},+ {"effort": "medium"},+ {"effort": "high"},+ ],+ }+ ],+ }+ ),+ encoding="utf-8",+ )+ (home / "config.toml").write_text('model = "gpt-5.5"\n', encoding="utf-8")+ monkeypatch.setenv("CODEX_HOME", str(home))++ async def fake_probe(cmd): # never spawn a real CLI in tests+ return True, f"{cmd[0]} x.y"++ monkeypatch.setattr(models_mod, "probe_version", fake_probe)++ options = {o.kind: o for o in await models_mod.list_backend_options()}++ codex = options["codex"]+ assert codex.default_model == "gpt-5.5"+ assert codex.synced_at == "2026-06-17T00:00:00Z"+ assert codex.models[0].slug == "gpt-5.5"+ assert codex.models[0].default_effort == "medium"+ assert codex.models[0].efforts == ["low", "medium", "high"]++ claude = options["claude_code"]+ assert claude.allow_custom_model is True+ assert {m.slug for m in claude.models} >= {"opus", "sonnet", "haiku"}+ assert "high" in claude.efforts+++async def test_codex_options_tolerate_missing_cache(monkeypatch, tmp_path) -> None:+ """No models_cache.json → empty model list, still allows a custom model."""+ from deeptutor.services.subagent import models as models_mod++ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "empty-codex"))++ async def fake_probe(cmd):+ return False, "codex CLI not found on PATH"++ monkeypatch.setattr(models_mod, "probe_version", fake_probe)++ options = {o.kind: o for o in await models_mod.list_backend_options()}+ codex = options["codex"]+ assert codex.available is False+ assert codex.models == []+ assert codex.allow_custom_model is Truediff --git a/tests/services/test_voice.py b/tests/services/test_voice.pyindex b4150f9c5..e56de99a3 100644--- a/tests/services/test_voice.py+++ b/tests/services/test_voice.py@@ -7,6 +7,8 @@ config resolution.from __future__ import annotations+import base64+import jsonfrom typing import Anyimport httpx@@ -20,6 +22,7 @@ from deeptutor.services.voice import synthesize_speech, transcribe_audiofrom deeptutor.services.voice.adapters.openai_compat import (OpenAICompatSTTAdapter,OpenAICompatTTSAdapter,+ OpenRouterTTSAdapter,)from deeptutor.services.voice.base import (build_auth_headers,@@ -131,6 +134,90 @@ async def test_tts_adapter_raises_on_http_error(monkeypatch: pytest.MonkeyPatch)await OpenAICompatTTSAdapter().synthesize("hi", config)+async def test_openrouter_tts_falls_back_to_chat_audio_stream(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ post_calls: list[dict[str, Any]] = []++ async def fake_post(self: httpx.AsyncClient, url: str, **kwargs: Any) -> httpx.Response:+ post_calls.append(+ {+ "url": url,+ "json": kwargs.get("json"),+ "headers": kwargs.get("headers"),+ }+ )+ if len(post_calls) == 1:+ response = httpx.Response(+ 500,+ json={"error": {"message": "Internal Server Error"}},+ )+ else:+ chunk = {+ "choices": [+ {+ "delta": {+ "audio": {+ "data": base64.b64encode(b"pcm-audio").decode("ascii"),+ "transcript": "hi",+ }+ }+ }+ ]+ }+ response = httpx.Response(+ 200,+ text=f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n",+ headers={"content-type": "text/event-stream"},+ )+ response.request = httpx.Request("POST", url)+ return response++ monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)++ config = TTSConfig(+ model="openai/gpt-4o-mini-tts",+ provider_name="openrouter",+ base_url="https://openrouter.ai/api/v1",+ api_key="or-key",+ voice="alloy",+ response_format="pcm",+ )++ audio, content_type = await OpenRouterTTSAdapter().synthesize("hello", config)++ assert audio == b"pcm-audio"+ assert content_type == "audio/pcm"+ assert post_calls[0]["url"] == "https://openrouter.ai/api/v1/audio/speech"+ assert post_calls[1]["url"] == "https://openrouter.ai/api/v1/chat/completions"+ assert post_calls[1]["json"]["modalities"] == ["text", "audio"]+ assert post_calls[1]["json"]["audio"] == {"voice": "alloy", "format": "pcm16"}+ assert post_calls[1]["headers"]["Authorization"] == "Bearer or-key"+++async def test_openrouter_gemini_tts_openai_voice_gets_clear_hint(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from deeptutor.services.voice.base import VoiceProviderError++ _capture_post(+ monkeypatch,+ httpx.Response(500, json={"error": {"message": "Internal Server Error"}}),+ )+ config = TTSConfig(+ model="google/gemini-3.1-flash-tts-preview",+ provider_name="openrouter",+ base_url="https://openrouter.ai/api/v1",+ api_key="or-key",+ voice="alloy",+ response_format="pcm",+ )+ with pytest.raises(VoiceProviderError, match="Kore"):+ await OpenRouterTTSAdapter().synthesize("hello", config)++# ── STT adapter ───────────────────────────────────────────────────────────@@ -229,6 +316,17 @@ def test_resolve_stt_config_picks_openrouter_base64_style() -> None:assert cfg.base_url == "https://openrouter.ai/api/v1"+def test_resolve_tts_config_picks_openrouter_adapter() -> None:+ catalog = _voice_catalog()+ catalog["services"]["tts"]["profiles"][0]["binding"] = "openrouter"+ catalog["services"]["tts"]["profiles"][0]["models"][0]["model"] = (+ "google/gemini-3.1-flash-tts-preview"+ )+ cfg = resolve_tts_runtime_config(catalog=catalog)+ assert cfg.provider_name == "openrouter"+ assert cfg.adapter == "openrouter_tts"++def test_resolve_tts_config_raises_without_model() -> None:catalog = {"version": 1, "services": {"tts": {"profiles": []}}}with pytest.raises(ValueError, match="No active TTS model"):diff --git a/web/app/(utility)/agents/layout.tsx b/web/app/(utility)/agents/layout.tsxnew file mode 100644index 000000000..6581fc2ee--- /dev/null+++ b/web/app/(utility)/agents/layout.tsx@@ -0,0 +1,13 @@+// Bare shell — the page owns its own padding + scroll (a scrollable hub with a+// max-width container), matching the other top-level consoles (memory).+export default function AgentsLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <main className="flex h-full min-h-0 flex-col bg-[var(--background)]">+ {children}+ </main>+ );+}diff --git a/web/app/(utility)/agents/page.tsx b/web/app/(utility)/agents/page.tsxnew file mode 100644index 000000000..a672c266a--- /dev/null+++ b/web/app/(utility)/agents/page.tsx@@ -0,0 +1,11 @@+import AgentsHub from "@/components/agents/AgentsHub";++export default function AgentsPage() {+ return (+ <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">+ <div className="mx-auto max-w-6xl px-6 py-10 pb-16 md:px-10">+ <AgentsHub />+ </div>+ </div>+ );+}diff --git a/web/app/(utility)/settings/agents/claude-code/page.tsx b/web/app/(utility)/settings/agents/claude-code/page.tsxnew file mode 100644index 000000000..e504a4fa1--- /dev/null+++ b/web/app/(utility)/settings/agents/claude-code/page.tsx@@ -0,0 +1,7 @@+"use client";++import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++export default function ClaudeCodeAgentSettingsPage() {+ return <SubagentSettingsEditor kind="claude_code" />;+}diff --git a/web/app/(utility)/settings/agents/codex/page.tsx b/web/app/(utility)/settings/agents/codex/page.tsxnew file mode 100644index 000000000..55dba43dc--- /dev/null+++ b/web/app/(utility)/settings/agents/codex/page.tsx@@ -0,0 +1,7 @@+"use client";++import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++export default function CodexAgentSettingsPage() {+ return <SubagentSettingsEditor kind="codex" />;+}diff --git a/web/app/(utility)/settings/agents/page.tsx b/web/app/(utility)/settings/agents/page.tsxnew file mode 100644index 000000000..4091a41dc--- /dev/null+++ b/web/app/(utility)/settings/agents/page.tsx@@ -0,0 +1,7 @@+"use client";++import SettingsSectionGrid from "@/components/settings/SettingsSectionGrid";++export default function AgentsSettingsPage() {+ return <SettingsSectionGrid categoryKey="agents" />;+}diff --git a/web/app/(utility)/space/agents/page.tsx b/web/app/(utility)/space/agents/page.tsxdeleted file mode 100644index 7448a8e94..000000000--- a/web/app/(utility)/space/agents/page.tsx+++ /dev/null@@ -1,5 +0,0 @@-import MyAgentsSection from "@/components/space/MyAgentsSection";--export default function SpaceAgentsPage() {- return <MyAgentsSection />;-}diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 389787b44..a33e6cfdb 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -96,6 +96,7 @@ import {type OutlineItem,} from "@/lib/research-types";import { listKnowledgeBases } from "@/lib/knowledge-api";+import { getSubagentSettings } from "@/lib/subagents-api";import { listLLMOptions, type LLMOption } from "@/lib/llm-options";import {getEnabledOptionalTools,@@ -281,6 +282,12 @@ const CAPABILITIES: CapabilityDef[] = [interface KnowledgeBase {name: string;is_default?: boolean;+ metadata?: {+ /** Connected-source kind, e.g. "obsidian" | "subagent". */+ type?: string;+ /** Backend of a connected subagent: "claude_code" | "codex". */+ agent_kind?: string;+ };}interface PendingAttachment {@@ -1372,6 +1379,11 @@ export default function ChatPage() {if (!researchValidation.valid) return;config = buildResearchWSConfig(researchConfig);}+ // When a connected agent is selected, carry the per-turn consult budget+ // (how many times DeepTutor may ask it) so the subagent capability uses it.+ if (selectedAgent && subagentBudget) {+ config = { ...(config ?? {}), subagent_consult_budget: subagentBudget };+ }const memoryPayload = [...memoryReferencesPayload];const messageContent =@@ -1497,6 +1509,57 @@ export default function ChatPage() {},[setKBs, state.knowledgeBases],);++ // Connected subagents are stored as ``type: subagent`` KBs (so selection+ // rides the same knowledge_bases path), but in the composer they get their+ // own single-select Bot chip — distinct from real knowledge bases.+ const agentNameSet = useMemo(+ () =>+ new Set(+ knowledgeBases+ .filter((kb) => kb.metadata?.type === "subagent")+ .map((kb) => kb.name),+ ),+ [knowledgeBases],+ );+ const kbOptions = useMemo(+ () => knowledgeBases.filter((kb) => kb.metadata?.type !== "subagent"),+ [knowledgeBases],+ );+ const agentOptions = useMemo(+ () =>+ knowledgeBases+ .filter((kb) => kb.metadata?.type === "subagent")+ .map((kb) => ({ name: kb.name, kind: kb.metadata?.agent_kind })),+ [knowledgeBases],+ );+ const selectedKbOnly = useMemo(+ () => state.knowledgeBases.filter((n) => !agentNameSet.has(n)),+ [state.knowledgeBases, agentNameSet],+ );+ const selectedAgent = useMemo(+ () => state.knowledgeBases.find((n) => agentNameSet.has(n)) ?? null,+ [state.knowledgeBases, agentNameSet],+ );+ const handleSelectAgent = useCallback(+ (name: string | null) => {+ // Single-select: clear any selected agent, then set the new one (if any).+ const withoutAgents = state.knowledgeBases.filter(+ (n) => !agentNameSet.has(n),+ );+ setKBs(name ? [...withoutAgents, name] : withoutAgents);+ },+ [setKBs, state.knowledgeBases, agentNameSet],+ );+ // How many times DeepTutor may consult the selected agent this turn. Seeded+ // from the configured default; the composer's stepper overrides it per turn+ // (sent in the request config, read by the subagent capability).+ const [subagentBudget, setSubagentBudget] = useState<number | null>(null);+ useEffect(() => {+ void getSubagentSettings()+ .then((s) => setSubagentBudget(s.consult_budget))+ .catch(() => undefined);+ }, []);const handleSelectNotebookPicker = useCallback(() => {setShowNotebookPicker(true);}, []);@@ -1626,6 +1689,10 @@ export default function ChatPage() {<GeogebraTabProvider><QuizFollowupBridge viewerPanelRef={viewerPanelRef} /><GeogebraTabBridge viewerPanelRef={viewerPanelRef} />+ <SubagentTabWatcher+ messages={state.messages}+ viewerPanelRef={viewerPanelRef}+ /><div// When the preview drawer is open AND the viewport is wide enough,// push the chat content to the left by the drawer's width so the two@@ -1782,7 +1849,12 @@ export default function ChatPage() {attachments={attachments}attachmentError={attachmentError}activeCap={activeCap}- knowledgeBases={knowledgeBases}+ knowledgeBases={kbOptions}+ connectedAgents={agentOptions}+ selectedAgent={selectedAgent}+ onSelectAgent={handleSelectAgent}+ subagentBudget={subagentBudget}+ onSubagentBudgetChange={setSubagentBudget}llmOptions={llmOptions}activeLLMDefault={activeLLMDefault}llmSelection={state.llmSelection}@@ -1796,7 +1868,7 @@ export default function ChatPage() {notebookReferenceGroups={notebookReferenceGroups}selectedPersona={null}selectedMemoryFiles={selectedMemoryFiles}- selectedKnowledgeBases={state.knowledgeBases}+ selectedKnowledgeBases={selectedKbOnly}isStreaming={state.isStreaming}isVisualizeMode={isVisualizeMode}capabilityNeedsConfig={capabilityNeedsConfig}@@ -1947,6 +2019,50 @@ function GeogebraTabBridge({return null;}+/**+ * Watches the turn's messages for connected-subagent runs and mirrors each+ * (grouped by the consult's call id) into its own side-viewer tab — opening ++ * focusing the panel when a consult starts, then live-refreshing as the+ * agent's native events stream in. Keeps the chat trace compact while the full+ * run shows in the sidebar.+ */+function SubagentTabWatcher({+ messages,+ viewerPanelRef,+}: {+ messages: { events?: StreamEvent[] }[];+ viewerPanelRef: React.MutableRefObject<SessionViewerPanelHandle | null>;+}) {+ useEffect(() => {+ // Group by turn so all of one turn's consults (DeepTutor may ask the agent+ // several questions in a row, each its own tool call) land in one tab as a+ // single running dialogue; fall back to the call id when no turn is set.+ const groups = new Map<string, { label: string; events: StreamEvent[] }>();+ for (const msg of messages) {+ for (const ev of msg.events ?? []) {+ const meta = (ev.metadata ?? {}) as Record<string, unknown>;+ if (meta.trace_kind !== "subagent_event") continue;+ const key = String(meta.turn_id || meta.call_id || meta.trace_id || "");+ if (!key) continue;+ const existing = groups.get(key);+ const label = String(+ meta.subagent_name || existing?.label || "Subagent",+ );+ if (existing) {+ existing.label = label;+ existing.events.push(ev);+ } else {+ groups.set(key, { label, events: [ev] });+ }+ }+ }+ for (const [key, group] of groups) {+ viewerPanelRef.current?.openSubagentTab(key, group.label, group.events);+ }+ }, [messages, viewerPanelRef]);+ return null;+}+/*** Header action button that auto-collapses to icon-only when the chat* column gets squeezed (Viewer panel open, narrow viewport, etc.). Thediff --git a/web/app/(workspace)/partners/[partnerId]/page.tsx b/web/app/(workspace)/partners/[partnerId]/page.tsxindex c4196b12c..edf28fefa 100644--- a/web/app/(workspace)/partners/[partnerId]/page.tsx+++ b/web/app/(workspace)/partners/[partnerId]/page.tsx@@ -33,6 +33,10 @@ import {downloadChatMarkdown,type ExportableMessage,} from "@/lib/chat-export";+import {+ loadPartnerSessionKey,+ persistPartnerSessionKey,+} from "@/lib/partner-session";import PartnerAvatar from "@/components/partners/PartnerAvatar";import PartnerChat from "@/components/partners/PartnerChat";import PartnerChannels from "@/components/partners/PartnerChannels";@@ -69,6 +73,19 @@ function PartnerDetail() {[],);const [showSaveModal, setShowSaveModal] = useState(false);+ // The active web session key lives here so the Archive tab's Resume can+ // point the (always-mounted) Chat tab at a different conversation.+ const [sessionKey, setSessionKey] = useState("");+ useEffect(() => {+ setSessionKey(loadPartnerSessionKey(partnerId));+ }, [partnerId]);+ const changeSessionKey = useCallback(+ (key: string) => {+ persistPartnerSessionKey(partnerId, key);+ setSessionKey(key);+ },+ [partnerId],+ );useEffect(() => {if (!toast) return;@@ -314,9 +331,10 @@ function PartnerDetail() {</button></div>- {/* Body */}+ {/* Body. Chat stays mounted (hidden off-tab) so an in-progress turn —+ its WebSocket and live trace — survives switching to another tab. */}<div className="min-h-0 flex-1">- {tab === "chat" ? (+ <div className={tab === "chat" ? "h-full" : "hidden"}><div className="mx-auto h-full max-w-3xl px-5"><PartnerChatpartnerId={partnerId}@@ -325,30 +343,38 @@ function PartnerDetail() {color={partner.color}avatar={partner.avatar}running={partner.running}+ sessionKey={sessionKey}+ onSessionKeyChange={changeSessionKey}+ onToast={setToast}onMessagesChange={setChatMessages}/></div>- ) : tab === "archive" ? (+ </div>+ {tab === "archive" ? (<div className="mx-auto h-full max-w-5xl overflow-hidden px-5 py-5"><PartnerArchivespartnerId={partnerId}onToast={setToast}onMessagesChange={setArchiveMessages}+ onResume={(key) => {+ changeSessionKey(key);+ setTab("chat");+ }}/></div>- ) : (+ ) : tab === "configure" ? (<div className="mx-auto h-full max-w-3xl overflow-y-auto px-5 py-5">- {tab === "configure" ? (- <PartnerConfigure- partner={partner}- onToast={setToast}- onUpdated={() => void load()}- />- ) : (- <PartnerChannels partnerId={partnerId} onToast={setToast} />- )}+ <PartnerConfigure+ partner={partner}+ onToast={setToast}+ onUpdated={() => void load()}+ /></div>- )}+ ) : tab === "channels" ? (+ <div className="mx-auto h-full max-w-3xl overflow-y-auto px-5 py-5">+ <PartnerChannels partnerId={partnerId} onToast={setToast} />+ </div>+ ) : null}</div><SaveToNotebookModaldiff --git a/web/app/(workspace)/partners/new/page.tsx b/web/app/(workspace)/partners/new/page.tsxindex 858fc085a..cdfd52d3e 100644--- a/web/app/(workspace)/partners/new/page.tsx+++ b/web/app/(workspace)/partners/new/page.tsx@@ -79,6 +79,7 @@ export default function NewPartnerPage() {const [toolOptions, setToolOptions] = useState<ToolOptions | null>(null);const [enabledTools, setEnabledTools] = useState<string[]>([]);+ const [builtinTools, setBuiltinTools] = useState<string[]>([]);const [mcpTools, setMcpTools] = useState<string[]>([]);const [toolsTouched, setToolsTouched] = useState(false);@@ -101,6 +102,7 @@ export default function NewPartnerPage() {.then((options) => {setToolOptions(options);setEnabledTools(options.tools.map((tool) => tool.name));+ setBuiltinTools(options.builtin_tools.map((tool) => tool.name));setMcpTools(options.mcp_tools.map((tool) => tool.name));}).catch(() => {});@@ -120,6 +122,8 @@ export default function NewPartnerPage() {setError("");try {const allTools = toolOptions?.tools.map((tool) => tool.name) ?? [];+ const allBuiltin =+ toolOptions?.builtin_tools.map((tool) => tool.name) ?? [];const allMcp = toolOptions?.mcp_tools.map((tool) => tool.name) ?? [];const result = await createPartner({name: name.trim(),@@ -138,6 +142,11 @@ export default function NewPartnerPage() {: enabledTools.length === allTools.length? null: enabledTools,+ builtin_tools: toolsTouched+ ? builtinTools+ : builtinTools.length === allBuiltin.length+ ? null+ : builtinTools,mcp_tools: toolsTouched? mcpTools: mcpTools.length === allMcp.length@@ -392,11 +401,16 @@ export default function NewPartnerPage() {<ToolPickeroptions={toolOptions}enabledTools={enabledTools}+ builtinTools={builtinTools}mcpTools={mcpTools}onChangeEnabledTools={(next) => {setToolsTouched(true);setEnabledTools(next);}}+ onChangeBuiltinTools={(next) => {+ setToolsTouched(true);+ setBuiltinTools(next);+ }}onChangeMcpTools={(next) => {setToolsTouched(true);setMcpTools(next);diff --git a/web/components/agents/AgentsHub.tsx b/web/components/agents/AgentsHub.tsxnew file mode 100644index 000000000..9f691f9c6--- /dev/null+++ b/web/components/agents/AgentsHub.tsx@@ -0,0 +1,18 @@+"use client";++import ConnectedAgents from "@/components/agents/ConnectedAgents";+import MyAgentsSection from "@/components/space/MyAgentsSection";++/**+ * "My Agents" hub — the top-level page. Two complementary halves: live agents+ * connected to the local Claude Code / Codex (consult them in chat now), and+ * the imported-history agents (replay and continue past transcripts).+ */+export default function AgentsHub() {+ return (+ <div className="space-y-12">+ <ConnectedAgents />+ <MyAgentsSection />+ </div>+ );+}diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsxnew file mode 100644index 000000000..b39f9acf9--- /dev/null+++ b/web/components/agents/ConnectedAgents.tsx@@ -0,0 +1,339 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Cpu, Loader2, Plug, Plus, Trash2, X } from "lucide-react";++import { agentGlyph } from "@/components/agents/agent-icons";+import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";+import {+ connectSubagent,+ detectSubagents,+ disconnectSubagent,+ listSubagentConnections,+ type SubagentBackendInfo,+ type SubagentConnection,+} from "@/lib/subagents-api";++/**+ * Connected agents — live Claude Code / Codex on the user's machine, registered+ * as pointers the chat composer can select and consult in real time. Distinct+ * from the imported-history agents below it: those replay past transcripts,+ * these drive the local CLI now. Detection is machine-global (is the CLI+ * installed here); if nothing is detected the connect action stays out of the+ * way with a one-line hint.+ */++type Lang = { zh: string; en: string };++function backendLabel(kind: string): string {+ if (kind === "claude_code") return "Claude Code";+ if (kind === "codex") return "Codex";+ return kind;+}++export default function ConnectedAgents() {+ const { i18n } = useTranslation();+ const zh = i18n.language?.toLowerCase().startsWith("zh");+ const tr = useCallback((l: Lang) => (zh ? l.zh : l.en), [zh]);++ const [backends, setBackends] = useState<SubagentBackendInfo[]>([]);+ const [connections, setConnections] = useState<SubagentConnection[]>([]);+ const [loading, setLoading] = useState(true);+ const [modalOpen, setModalOpen] = useState(false);+ const [busyName, setBusyName] = useState<string | null>(null);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const [detected, conns] = await Promise.all([+ detectSubagents().catch(() => [] as SubagentBackendInfo[]),+ listSubagentConnections().catch(() => [] as SubagentConnection[]),+ ]);+ setBackends(detected);+ setConnections(conns);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void load();+ }, [load]);++ const available = useMemo(+ () => backends.filter((b) => b.available),+ [backends],+ );++ const handleDisconnect = useCallback(+ async (name: string) => {+ if (+ !window.confirm(+ tr({+ zh: `断开「${name}」?这只会移除连接,不影响本机的智能体配置。`,+ en: `Disconnect “${name}”? This only removes the connection; your local agent is untouched.`,+ }),+ )+ )+ return;+ setBusyName(name);+ try {+ await disconnectSubagent(name);+ await load();+ } finally {+ setBusyName(null);+ }+ },+ [load, tr],+ );++ return (+ <section className="space-y-4">+ <SpaceSectionHeader+ icon={Plug}+ title={tr({ zh: "连接的智能体", en: "Connected agents" })}+ description={tr({+ zh: "把本机已配置的 Claude Code / Codex 接进来,在对话中选中后直接向它提问 —— 它的完整运行过程会实时展示。",+ en: "Bring in the Claude Code / Codex configured on this machine — select one in chat to consult it directly, with its full run shown live.",+ })}+ action={+ available.length > 0 ? (+ <button+ type="button"+ onClick={() => setModalOpen(true)}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] shadow-sm transition-opacity hover:opacity-90"+ >+ <Plus className="h-3.5 w-3.5" />+ {tr({ zh: "连接智能体", en: "Connect agent" })}+ </button>+ ) : null+ }+ />++ {loading ? (+ <div className="flex items-center gap-2 px-1 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {tr({ zh: "检测本机智能体…", en: "Detecting local agents…" })}+ </div>+ ) : available.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {tr({+ zh: "未在本机检测到 Claude Code 或 Codex。安装并登录其中任一 CLI 后即可连接。",+ en: "No Claude Code or Codex detected on this machine. Install and log in to either CLI to connect one.",+ })}+ </div>+ ) : connections.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {tr({+ zh: "尚未连接任何智能体。点击「连接智能体」把本机的 Claude Code / Codex 接进来。",+ en: "No agents connected yet. Click “Connect agent” to bring in your local Claude Code / Codex.",+ })}+ </div>+ ) : (+ <div className="grid gap-3 sm:grid-cols-2">+ {connections.map((conn) => {+ const Glyph = agentGlyph(conn.agent_kind);+ return (+ <div+ key={conn.name}+ className="group flex items-center gap-3 rounded-2xl border border-[var(--border)] bg-[var(--card)] px-4 py-3"+ >+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-[var(--border)]/60 bg-[var(--background)] text-[var(--foreground)]">+ {Glyph ? <Glyph size={20} /> : <Cpu size={18} strokeWidth={1.6} />}+ </span>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13.5px] font-semibold tracking-tight text-[var(--foreground)]">+ {conn.name}+ </div>+ <div className="mt-0.5 truncate text-[11.5px] text-[var(--muted-foreground)]">+ {backendLabel(conn.agent_kind)}+ {conn.cwd ? ` · ${conn.cwd}` : ""}+ </div>+ </div>+ <button+ type="button"+ onClick={() => void handleDisconnect(conn.name)}+ disabled={busyName === conn.name}+ title={tr({ zh: "断开", en: "Disconnect" })}+ aria-label={tr({ zh: "断开", en: "Disconnect" })}+ className="rounded-lg border border-[var(--border)]/50 p-2 text-[var(--muted-foreground)] transition-colors hover:border-red-300 hover:text-red-600 disabled:opacity-50 dark:hover:border-red-900 dark:hover:text-red-400"+ >+ {busyName === conn.name ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Trash2 className="h-3.5 w-3.5" />+ )}+ </button>+ </div>+ );+ })}+ </div>+ )}++ {modalOpen && (+ <ConnectModal+ backends={available}+ existingNames={connections.map((c) => c.name)}+ tr={tr}+ onClose={() => setModalOpen(false)}+ onConnected={() => {+ setModalOpen(false);+ void load();+ }}+ />+ )}+ </section>+ );+}++function ConnectModal({+ backends,+ existingNames,+ tr,+ onClose,+ onConnected,+}: {+ backends: SubagentBackendInfo[];+ existingNames: string[];+ tr: (l: Lang) => string;+ onClose: () => void;+ onConnected: () => void;+}) {+ const [kind, setKind] = useState(backends[0]?.kind ?? "");+ const [name, setName] = useState("");+ const [cwd, setCwd] = useState("");+ const [error, setError] = useState("");+ const [submitting, setSubmitting] = useState(false);++ const submit = useCallback(async () => {+ const trimmed = name.trim();+ if (!trimmed) {+ setError(tr({ zh: "请填写名称。", en: "Please enter a name." }));+ return;+ }+ if (existingNames.includes(trimmed)) {+ setError(tr({ zh: "已存在同名连接。", en: "A connection with this name already exists." }));+ return;+ }+ setSubmitting(true);+ setError("");+ try {+ await connectSubagent({ name: trimmed, agent_kind: kind, cwd: cwd.trim() });+ onConnected();+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setSubmitting(false);+ }+ }, [name, kind, cwd, existingNames, onConnected, tr]);++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4 backdrop-blur-sm"+ onClick={onClose}+ >+ <div+ className="w-full max-w-md rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-2xl"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="mb-4 flex items-center justify-between">+ <h2 className="font-serif text-[16px] font-semibold tracking-tight text-[var(--foreground)]">+ {tr({ zh: "连接智能体", en: "Connect an agent" })}+ </h2>+ <button+ type="button"+ onClick={onClose}+ className="rounded-lg p-1 text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"+ aria-label={tr({ zh: "关闭", en: "Close" })}+ >+ <X size={16} />+ </button>+ </div>++ <div className="space-y-3.5">+ <div>+ <label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">+ {tr({ zh: "智能体", en: "Agent" })}+ </label>+ <div className="flex gap-2">+ {backends.map((b) => {+ const Glyph = agentGlyph(b.kind);+ return (+ <button+ key={b.kind}+ type="button"+ onClick={() => setKind(b.kind)}+ className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-[12.5px] font-medium transition-colors ${+ kind === b.kind+ ? "border-[var(--primary)] bg-[var(--primary)]/[0.07] text-[var(--foreground)]"+ : "border-[var(--border)] text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)]"+ }`}+ >+ {Glyph ? <Glyph size={15} /> : null}+ {b.display_name}+ </button>+ );+ })}+ </div>+ </div>++ <div>+ <label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">+ {tr({ zh: "名称", en: "Name" })}+ </label>+ <input+ autoFocus+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={tr({ zh: "例如:我的代码助手", en: "e.g. My coding agent" })}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"+ />+ </div>++ <div>+ <label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">+ {tr({ zh: "工作目录(可选)", en: "Working directory (optional)" })}+ </label>+ <input+ value={cwd}+ onChange={(e) => setCwd(e.target.value)}+ placeholder={tr({+ zh: "例如:/Users/you/project —— 智能体将在此目录运行",+ en: "e.g. /Users/you/project — the agent runs here",+ })}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"+ />+ </div>++ {error && (+ <p className="text-[12px] text-red-600 dark:text-red-400">{error}</p>+ )}+ </div>++ <div className="mt-5 flex justify-end gap-2">+ <button+ type="button"+ onClick={onClose}+ className="rounded-lg px-3 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ {tr({ zh: "取消", en: "Cancel" })}+ </button>+ <button+ type="button"+ onClick={() => void submit()}+ disabled={submitting}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--background)] shadow-sm transition-opacity hover:opacity-90 disabled:opacity-50"+ >+ {submitting ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Plug className="h-3.5 w-3.5" />+ )}+ {tr({ zh: "连接", en: "Connect" })}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/web/components/agents/agent-icons.tsx b/web/components/agents/agent-icons.tsxnew file mode 100644index 000000000..d498f3e26--- /dev/null+++ b/web/components/agents/agent-icons.tsx@@ -0,0 +1,78 @@+"use client";++import { type ComponentType, type SVGProps, useId } from "react";++/**+ * Brand glyphs for connected-agent backends. The real marks (Claude's sunburst,+ * Codex's gradient app icon) so a connected agent reads as itself everywhere it+ * appears — selector chip, cards, message references. Rendered in brand colours+ * (not `currentColor`) so they look authentic rather than tinted. Resolve a+ * backend kind to its glyph with `agentGlyph(kind)`; unknown kinds return null+ * and callers fall back to a generic icon.+ */++type GlyphProps = { size?: number } & Omit<SVGProps<SVGSVGElement>, "width" | "height">;++// Claude / Anthropic sunburst, in the brand clay.+export function ClaudeGlyph({ size = 16, ...props }: GlyphProps) {+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="#D97757"+ aria-hidden+ {...props}+ >+ <path d="m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z" />+ </svg>+ );+}++// Official Codex app icon (white tile + blue→purple gradient cloud with a+// terminal prompt). Gradient id is per-instance (useId) so multiple icons on a+// page don't collide.+export function CodexGlyph({ size = 16, ...props }: GlyphProps) {+ const gradientId = useId();+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden+ {...props}+ >+ <path+ d="M19.503 0H4.496A4.496 4.496 0 000 4.496v15.007A4.496 4.496 0 004.496 24h15.007A4.496 4.496 0 0024 19.503V4.496A4.496 4.496 0 0019.503 0z"+ fill="#fff"+ />+ <path+ d="M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z"+ fill={`url(#${gradientId})`}+ />+ <defs>+ <linearGradient+ gradientUnits="userSpaceOnUse"+ id={gradientId}+ x1="12"+ x2="12"+ y1="3"+ y2="21"+ >+ <stop stopColor="#B1A7FF" />+ <stop offset=".5" stopColor="#7A9DFF" />+ <stop offset="1" stopColor="#3941FF" />+ </linearGradient>+ </defs>+ </svg>+ );+}++export type AgentGlyph = ComponentType<GlyphProps>;++export function agentGlyph(kind: string | undefined): AgentGlyph | null {+ if (kind === "claude_code") return ClaudeGlyph;+ if (kind === "codex") return CodexGlyph;+ return null;+}diff --git a/web/components/chat/home/AgentSelector.tsx b/web/components/chat/home/AgentSelector.tsxnew file mode 100644index 000000000..bcd885a40--- /dev/null+++ b/web/components/chat/home/AgentSelector.tsx@@ -0,0 +1,171 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Bot, Check, ChevronDown, Minus, Plus } from "lucide-react";+import { useTranslation } from "react-i18next";+import { agentGlyph } from "@/components/agents/agent-icons";+import { useLingerExpand } from "@/hooks/use-linger-expand";++const BUDGET_MIN = 1;+const BUDGET_MAX = 12;++/**+ * Connected-agent selector (composer toolbar).+ *+ * Sibling of KnowledgeSelector, but single-select: a turn consults at most one+ * connected agent (Claude Code / Codex). Picking one routes the whole turn+ * through the subagent capability — the chat model consults the live local+ * agent instead of retrieving from a KB. Selecting the active one again clears+ * it. A selection tints the bot icon primary so the active agent stays visible+ * when collapsed.+ */+export default function AgentSelector({+ agents,+ selected,+ onSelect,+ budget = null,+ onBudgetChange,+ placement = "top",+}: {+ agents: { name: string; kind?: string }[];+ selected: string | null;+ onSelect: (name: string | null) => void;+ /** Max times DeepTutor may consult the agent this turn. */+ budget?: number | null;+ onBudgetChange?: (budget: number) => void;+ placement?: "top" | "bottom";+}) {+ const { t } = useTranslation();+ const [open, setOpenState] = useState(false);+ const { expanded, linger, triggerProps: lingerProps } = useLingerExpand(open);+ const setOpen = (next: boolean) => {+ setOpenState(next);+ if (!next) linger();+ };+ const rootRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!open) return;+ const handler = (event: MouseEvent) => {+ const target = event.target as Node;+ if (rootRef.current && !rootRef.current.contains(target)) {+ setOpen(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ const label = selected ?? t("Agent");+ const menuPlacementClass =+ placement === "bottom" ? "top-full mt-1.5" : "bottom-full mb-1.5";+ const SelectedGlyph = agentGlyph(+ agents.find((a) => a.name === selected)?.kind,+ );++ return (+ <div ref={rootRef} className="relative">+ <button+ type="button"+ onClick={() => setOpen(!open)}+ aria-label={t("Select a connected agent")}+ aria-expanded={open}+ {...lingerProps}+ className={`inline-flex h-8 shrink-0 items-center rounded-lg px-2 text-[14px] font-medium transition-[background-color,color,transform] duration-150 active:scale-[0.97] ${+ open+ ? "bg-[var(--muted)] text-[var(--foreground)]"+ : selected+ ? "text-[var(--primary)] hover:bg-[var(--primary)]/[0.07]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"+ }`}+ >+ {SelectedGlyph ? (+ <SelectedGlyph size={16} className="shrink-0" />+ ) : (+ <Bot size={16} strokeWidth={1.7} className="shrink-0" />+ )}+ <span+ className={`flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap transition-[max-width,opacity,margin-left] duration-300 ease-out ${+ expanded ? "ml-1.5 max-w-[160px] opacity-100" : "ml-0 max-w-0 opacity-0"+ }`}+ >+ <span className="min-w-0 truncate">{label}</span>+ <ChevronDown+ size={13}+ className={`shrink-0 transition-transform ${open ? "rotate-180" : ""}`}+ />+ </span>+ </button>++ {open && (+ <div+ className={`dt-popup-up absolute right-0 z-50 ${menuPlacementClass} w-[min(280px,calc(100vw-32px))] overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--popover)] shadow-lg backdrop-blur-md`}+ >+ <div className="max-h-[280px] overflow-y-auto py-1">+ {agents.map((agent) => {+ const active = selected === agent.name;+ const RowGlyph = agentGlyph(agent.kind) ?? Bot;+ return (+ <button+ key={agent.name}+ type="button"+ onClick={() => {+ onSelect(active ? null : agent.name);+ setOpen(false);+ }}+ className={`flex w-full items-center gap-2.5 px-3 py-1.5 text-left transition-colors active:bg-[var(--muted)]/70 ${+ active ? "bg-[var(--primary)]/[0.06]" : "hover:bg-[var(--muted)]/45"+ }`}+ >+ <RowGlyph size={15} className="shrink-0" />+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-[var(--foreground)]">+ {agent.name}+ </span>+ {active && (+ <Check size={14} strokeWidth={2} className="shrink-0 text-[var(--primary)]" />+ )}+ </button>+ );+ })}+ </div>++ {onBudgetChange && (+ <div className="flex items-center justify-between gap-2 border-t border-[var(--border)] px-3 py-2">+ <span className="min-w-0 text-[11.5px] text-[var(--muted-foreground)]">+ {t("Max rounds DeepTutor may ask")}+ </span>+ <div className="flex shrink-0 items-center gap-1">+ <button+ type="button"+ aria-label={t("Fewer rounds")}+ disabled={(budget ?? BUDGET_MIN) <= BUDGET_MIN}+ onClick={() =>+ onBudgetChange(Math.max(BUDGET_MIN, (budget ?? BUDGET_MIN) - 1))+ }+ className="flex h-5 w-5 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)] disabled:opacity-40"+ >+ <Minus size={12} />+ </button>+ <span className="w-5 text-center text-[12.5px] font-semibold tabular-nums text-[var(--foreground)]">+ {budget ?? "–"}+ </span>+ <button+ type="button"+ aria-label={t("More rounds")}+ disabled={(budget ?? BUDGET_MAX) >= BUDGET_MAX}+ onClick={() =>+ onBudgetChange(Math.min(BUDGET_MAX, (budget ?? BUDGET_MIN) + 1))+ }+ className="flex h-5 w-5 items-center justify-center rounded-md text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)] disabled:opacity-40"+ >+ <Plus size={12} />+ </button>+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex 6e85550fe..8c5f88e33 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -45,6 +45,7 @@ import type { LLMOption } from "@/lib/llm-options";import ChatSpaceMenu from "@/components/chat/space/ChatSpaceMenu";import type { SpaceMemoryFile } from "@/lib/space-items";import type { SelectedBookReference } from "@/lib/book-references";+import AgentSelector from "./AgentSelector";import KnowledgeSelector from "./KnowledgeSelector";import ModelSelector from "./ModelSelector";import PersonaSelector from "./PersonaSelector";@@ -150,6 +151,11 @@ export default memo(function ChatComposer({attachmentError,activeCap,knowledgeBases,+ connectedAgents = [],+ selectedAgent = null,+ onSelectAgent,+ subagentBudget = null,+ onSubagentBudgetChange,llmOptions,activeLLMDefault,llmSelection,@@ -221,6 +227,14 @@ export default memo(function ChatComposer({attachmentError: string | null;activeCap: CapabilityDef;knowledgeBases: KnowledgeBase[];+ /** Connected local subagents (Claude Code / Codex) selectable for this turn. */+ connectedAgents?: { name: string; kind?: string }[];+ /** The connected agent selected for this turn, if any (single-select). */+ selectedAgent?: string | null;+ onSelectAgent?: (name: string | null) => void;+ /** Max times DeepTutor may consult the selected agent this turn. */+ subagentBudget?: number | null;+ onSubagentBudgetChange?: (budget: number) => void;llmOptions: LLMOption[];activeLLMDefault: LLMSelection | null;llmSelection: LLMSelection | null;@@ -609,6 +623,9 @@ export default memo(function ChatComposer({onSend={doSend}onInputChange={handleInputChange}onPaste={onPaste}+ connectedAgents={connectedAgents}+ selectedAgent={selectedAgent}+ onSelectAgent={onSelectAgent}selectedCounts={spaceSelectionCounts}knowledgeAvailable={false}personaAvailable={!onPersonaSelectionChange}@@ -918,6 +935,15 @@ export default memo(function ChatComposer({</div><div className="ml-auto flex shrink-0 items-center gap-1.5">+ {connectedAgents.length > 0 && onSelectAgent ? (+ <AgentSelector+ agents={connectedAgents}+ selected={selectedAgent}+ onSelect={onSelectAgent}+ budget={subagentBudget}+ onBudgetChange={onSubagentBudgetChange}+ />+ ) : null}{knowledgeBases.length > 0 ? (<KnowledgeSelectorknowledgeBases={knowledgeBases}diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex b7a8403f6..cb24a3e61 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -61,6 +61,8 @@ import ContextReferenceTree, {type ContextTreeItem,} from "./ContextReferenceTree";import { AssistantActivity } from "./TracePanels";+import { agentGlyph } from "@/components/agents/agent-icons";+import { useConnectedAgentKinds } from "@/hooks/useConnectedAgentKinds";const MathAnimatorViewer = dynamic(() => import("@/components/math-animator/MathAnimatorViewer"),@@ -874,6 +876,10 @@ const UserMessage = memo(function UserMessage({const { t } = useTranslation();const [editing, setEditing] = useState(false);const [draft, setDraft] = useState(msg.content);+ // Connected subagents ride in knowledge_bases (same selection path) but are+ // agents, not KBs — this maps a selected name to its backend kind so the+ // reference chip can badge it with the agent's brand icon.+ const agentKinds = useConnectedAgentKinds();if (msg.content.startsWith("[Quiz Performance]")) return null;// ``msg.id`` can be a negative client-side sentinel for optimistic// (just-sent, not yet reconciled with the server) rows. We still allow@@ -920,14 +926,25 @@ const UserMessage = memo(function UserMessage({onClick: onPreviewAttachment ? () => onPreviewAttachment(a) : undefined,};}),- ...(snap?.knowledgeBases ?? []).map(- (name): ContextTreeItem => ({+ ...(snap?.knowledgeBases ?? []).map((name): ContextTreeItem => {+ const agentKind = agentKinds[name];+ if (agentKind) {+ return {+ key: `agent-${name}`,+ // Brand SVG marks share the lucide call signature (size/strokeWidth/+ // className); cast bridges the structural-variance gap.+ icon: (agentGlyph(agentKind) ?? Bot) as unknown as LucideIcon,+ kind: t("Agent"),+ label: name,+ };+ }+ return {key: `kb-${name}`,icon: Database,kind: t("Knowledge"),label: name,- }),- ),+ };+ }),...(snap?.bookReferences ?? []).map((ref): ContextTreeItem => ({key: `book-${ref.book_id}`,diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsxindex 93e7524b4..7c43041bf 100644--- a/web/components/chat/home/ComposerInput.tsx+++ b/web/components/chat/home/ComposerInput.tsx@@ -11,10 +11,11 @@ import {type RefObject,} from "react";import { useTranslation } from "react-i18next";-import { UserRound } from "lucide-react";+import { Bot, Check, UserRound } from "lucide-react";import ChatSpaceMenu, {type ChatSpaceSelectionCounts,} from "@/components/chat/space/ChatSpaceMenu";+import { agentGlyph } from "@/components/agents/agent-icons";import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";@@ -37,6 +38,14 @@ interface ComposerInputProps {knowledgeAvailable: boolean;/** Hide the Persona entry (main chat: persona has its own selector). */personaAvailable: boolean;+ /**+ * Connected subagents selectable via the ``@`` mention. When provided, ``@``+ * opens an agent picker (the main-chat behavior) instead of the Space menu;+ * surfaces that omit this (e.g. the quiz follow-up) keep the Space menu on @.+ */+ connectedAgents?: { name: string; kind?: string }[];+ selectedAgent?: string | null;+ onSelectAgent?: (name: string | null) => void;onSelectAttach: () => void;onSelectKnowledge?: () => void;onSelectNotebookPicker: () => void;@@ -90,6 +99,12 @@ export function stripTrailingAtMention(value: string): string {return value.replace(/(^|\s)@[^\s]*$/, "$1").replace(/\s+$/, "");}+/** The text typed after a trailing ``@`` (the agent-mention query), or "". */+export function atMentionQuery(value: string, cursorPos: number): string {+ const match = /(^|\s)@([^\s]*)$/.exec(value.slice(0, cursorPos));+ return match ? match[2] : "";+}+/*** `/persona` slash-command detection (Codex-style: command position is the* very start of the input, not mid-text like @ mentions). Active while the@@ -118,6 +133,9 @@ export const ComposerInput = memo(selectedCounts,knowledgeAvailable,personaAvailable,+ connectedAgents = [],+ selectedAgent = null,+ onSelectAgent,onSelectAttach,onSelectKnowledge,onSelectNotebookPicker,@@ -138,7 +156,16 @@ export const ComposerInput = memo(const [input, setInput] = useState("");const [showAtPopup, setShowAtPopup] = useState(false);const [showSlashPopup, setShowSlashPopup] = useState(false);+ const [atQuery, setAtQuery] = useState("");const slashEnabled = Boolean(onOpenPersonaSelector);+ // Main chat passes ``onSelectAgent`` → ``@`` picks a connected agent. Other+ // surfaces (quiz follow-up) omit it and keep the @ Space menu.+ const agentMentionMode = Boolean(onSelectAgent);+ const filteredAgents = agentMentionMode+ ? connectedAgents.filter((a) =>+ a.name.toLowerCase().includes(atQuery.toLowerCase()),+ )+ : [];// Latest text mirrored into a ref by the change handlers (never updated// during render). The @space handlers and the imperative handle read@@ -187,7 +214,9 @@ export const ComposerInput = memo(const cursorPos = e.target.selectionStart ?? value.length;setInputBoth(value);onInputChange(value);- setShowAtPopup(shouldOpenAtPopup(value, cursorPos));+ const atOpen = shouldOpenAtPopup(value, cursorPos);+ setShowAtPopup(atOpen);+ setAtQuery(atOpen ? atMentionQuery(value, cursorPos) : "");setShowSlashPopup(slashEnabled && shouldOpenSlashPopup(value, cursorPos),);@@ -199,7 +228,9 @@ export const ComposerInput = memo((e: React.MouseEvent<HTMLTextAreaElement>) => {const target = e.currentTarget;const cursorPos = target.selectionStart ?? target.value.length;- setShowAtPopup(shouldOpenAtPopup(target.value, cursorPos));+ const atOpen = shouldOpenAtPopup(target.value, cursorPos);+ setShowAtPopup(atOpen);+ setAtQuery(atOpen ? atMentionQuery(target.value, cursorPos) : "");setShowSlashPopup(slashEnabled && shouldOpenSlashPopup(target.value, cursorPos),);@@ -228,6 +259,22 @@ export const ComposerInput = memo(setShowSlashPopup(false);}, [canSendEmpty, onSend, setInputBoth, onInputChange]);+ const clearTrailingMention = useCallback(() => {+ const next = stripTrailingAtMention(inputRef.current);+ setInputBoth(next);+ onInputChange(next);+ }, [setInputBoth, onInputChange]);++ const handleSelectAgentMention = useCallback(+ (name: string) => {+ clearTrailingMention();+ setShowAtPopup(false);+ setAtQuery("");+ onSelectAgent?.(name);+ },+ [clearTrailingMention, onSelectAgent],+ );+const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {// With the slash popup open, Enter/Tab confirm the command instead@@ -241,6 +288,18 @@ export const ComposerInput = memo(handleSelectSlashPersona();return;}+ // With the agent-mention popup open, Enter/Tab confirm the first match.+ if (+ showAtPopup &&+ agentMentionMode &&+ filteredAgents.length > 0 &&+ !isComposingRef.current &&+ (e.key === "Enter" || e.key === "Tab")+ ) {+ e.preventDefault();+ handleSelectAgentMention(filteredAgents[0].name);+ return;+ }if (shouldSubmitOnEnter(e, isComposingRef.current)) {e.preventDefault();doSend();@@ -249,7 +308,15 @@ export const ComposerInput = memo(setShowSlashPopup(false);}},- [doSend, showSlashPopup, handleSelectSlashPersona],+ [+ doSend,+ showSlashPopup,+ handleSelectSlashPersona,+ showAtPopup,+ agentMentionMode,+ filteredAgents,+ handleSelectAgentMention,+ ],);const handleCompositionStart = useCallback(() => {@@ -264,12 +331,6 @@ export const ComposerInput = memo(}, 0);}, []);- const clearTrailingMention = useCallback(() => {- const next = stripTrailingAtMention(inputRef.current);- setInputBoth(next);- onInputChange(next);- }, [setInputBoth, onInputChange]);-const handleSelectSpaceItem = useCallback((key:@@ -333,7 +394,63 @@ export const ComposerInput = memo(return (<div className="px-4 pt-3.5 pb-2">- {showAtPopup && (+ {showAtPopup && agentMentionMode && (+ <div+ ref={popupRef}+ className="absolute bottom-full left-0 z-[70] mb-2"+ >+ <div+ role="listbox"+ aria-label={t("Talk to an agent")}+ className="w-[300px] overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"+ >+ <div className="px-3 pb-1 pt-1.5 text-[11px] font-medium uppercase tracking-[0.05em] text-[var(--muted-foreground)]">+ {t("Talk to an agent")}+ </div>+ {filteredAgents.length === 0 ? (+ <div className="px-3 py-2 text-[12px] text-[var(--muted-foreground)]">+ {connectedAgents.length === 0+ ? t("No connected agents — connect one in My Agents.")+ : t("No matching agent")}+ </div>+ ) : (+ <div className="max-h-[260px] overflow-y-auto">+ {filteredAgents.map((agent) => {+ const Glyph = agentGlyph(agent.kind) ?? Bot;+ const active = selectedAgent === agent.name;+ return (+ <button+ key={agent.name}+ type="button"+ role="option"+ aria-selected={active}+ onClick={() => handleSelectAgentMention(agent.name)}+ className={`flex w-full items-center gap-2.5 px-3 py-1.5 text-left transition-colors active:bg-[var(--muted)]/70 ${+ active+ ? "bg-[var(--primary)]/[0.06]"+ : "hover:bg-[var(--muted)]/45"+ }`}+ >+ <Glyph size={15} className="shrink-0" />+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-[var(--foreground)]">+ {agent.name}+ </span>+ {active && (+ <Check+ size={14}+ strokeWidth={2}+ className="shrink-0 text-[var(--primary)]"+ />+ )}+ </button>+ );+ })}+ </div>+ )}+ </div>+ </div>+ )}+ {showAtPopup && !agentMentionMode && (<divref={popupRef}className="absolute bottom-full left-0 z-[70] mb-2"diff --git a/web/components/chat/home/ContextReferenceTree.tsx b/web/components/chat/home/ContextReferenceTree.tsxindex 22876010c..26aaffc75 100644--- a/web/components/chat/home/ContextReferenceTree.tsx+++ b/web/components/chat/home/ContextReferenceTree.tsx@@ -11,6 +11,8 @@ import { useTranslation } from "react-i18next";*/export interface ContextTreeItem {key: string;+ // A lucide icon, or any glyph with the same call signature (brand SVG marks+ // are cast to this at the call site).icon: LucideIcon;/** Type prefix ("Book", "Notebook", ...), already translated. */kind: string;diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsxindex 4679d4f6a..bc4787668 100644--- a/web/components/chat/home/SessionViewerPanel.tsx+++ b/web/components/chat/home/SessionViewerPanel.tsx@@ -50,10 +50,12 @@ import {type SessionActivity,} from "@/components/chat/home/SessionActivityPanel";import QuizFollowupTabBody from "@/components/quiz/QuizFollowupTabBody";+import SubagentTabBody from "@/components/chat/home/SubagentTabBody";import type { QuizFollowupTabContext } from "@/context/QuizFollowupContext";import type { GeogebraTabPayload } from "@/context/GeogebraTabContext";import { apiUrl } from "@/lib/api";import type { MessageAttachment } from "@/context/UnifiedChatContext";+import type { StreamEvent } from "@/lib/unified-ws";const PdfPreview = dynamic(() => import("@/components/chat/preview/previewers/PdfPreview"),@@ -138,6 +140,13 @@ type ViewerTab =id: string;label: string;script: string;+ }+ | {+ kind: "subagent";+ id: string;+ label: string;+ callId: string;+ events: StreamEvent[];};export interface SessionViewerPanelHandle {@@ -147,6 +156,8 @@ export interface SessionViewerPanelHandle {openQuizFollowupTab(context: QuizFollowupTabContext): void;/** Opens (or focuses) an interactive GeoGebra applet tab. */openGeogebraTab(payload: GeogebraTabPayload): void;+ /** Opens (first time) or live-updates a connected subagent's run tab. */+ openSubagentTab(callId: string, label: string, events: StreamEvent[]): void;/** Opens the panel and switches to the Activity home (where the* capability-config card lives). */focusActivityHome(): void;@@ -179,6 +190,10 @@ function geogebraTabIdFor(payloadId: string): string {return `geogebra:${payloadId}`;}+function subagentTabIdFor(callId: string): string {+ return `subagent:${callId}`;+}+function hostnameFor(url: string): string {try {return new URL(url).hostname.replace(/^www\./, "");@@ -393,6 +408,33 @@ function SessionViewerPanelInner([onAutoOpen],);+ // A connected subagent's run streams into its own tab. The first call (when+ // the consult starts) reveals + focuses the tab; later calls only refresh its+ // events, so live streaming never yanks the user off whatever they're viewing.+ const subagentSeenRef = useRef<Set<string>>(new Set());+ const openSubagentTab = useCallback(+ (callId: string, label: string, events: StreamEvent[]) => {+ const id = subagentTabIdFor(callId);+ const isNew = !subagentSeenRef.current.has(callId);+ subagentSeenRef.current.add(callId);+ setTabs((prev) => {+ const existingIdx = prev.findIndex((tab) => tab.id === id);+ const tab: ViewerTab = { kind: "subagent", id, label, callId, events };+ if (existingIdx >= 0) {+ const next = [...prev];+ next[existingIdx] = tab;+ return next;+ }+ return [...prev, tab];+ });+ if (isNew) {+ setActiveTabId(id);+ onAutoOpen();+ }+ },+ [onAutoOpen],+ );+// Open the panel and return to the Activity home (where the// capability-config card surfaces). Used by the send-gate.const focusActivityHome = useCallback(() => {@@ -407,6 +449,7 @@ function SessionViewerPanelInner(openWebTab,openQuizFollowupTab,openGeogebraTab,+ openSubagentTab,focusActivityHome,}),[@@ -414,6 +457,7 @@ function SessionViewerPanelInner(openWebTab,openQuizFollowupTab,openGeogebraTab,+ openSubagentTab,focusActivityHome,],);@@ -523,6 +567,12 @@ function SessionViewerPanelInner(/>) : activeTab?.kind === "geogebra" ? (<GeogebraTabBody key={activeTab.id} script={activeTab.script} />+ ) : activeTab?.kind === "subagent" ? (+ <SubagentTabBody+ key={activeTab.id}+ tabEvents={activeTab.events}+ sessionId={sessionId}+ />) : (<ActivityHomeactivity={activity}diff --git a/web/components/chat/home/SubagentRunTranscript.tsx b/web/components/chat/home/SubagentRunTranscript.tsxnew file mode 100644index 000000000..f7a7f32f5--- /dev/null+++ b/web/components/chat/home/SubagentRunTranscript.tsx@@ -0,0 +1,181 @@+"use client";++import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import type { StreamEvent } from "@/lib/unified-ws";+import { getTraceMeta } from "./TracePanels";++/**+ * A connected subagent's native run, rendered close to how its own CLI shows it:+ * each of DeepTutor's questions heads a round, then the agent's reply streams as+ * "●"-bulleted steps — its messages in a neutral bullet, tool calls in an amber+ * bullet — with command output in a muted block (collapsed when long). Text and+ * reasoning stream token-by-token: deltas sharing a merge id collapse to one row+ * that grows in place, so the answer types out and renders exactly once.+ *+ * Set in a Monaco/CJK monospace face (the CLI aesthetic) and the app's theme+ * tokens, so it matches the side viewer and follows light/dark theme.+ */+const MONO_FONT =+ 'Monaco, Menlo, Consolas, "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", monospace';+const RESULT_PREVIEW_LINES = 3;++export default function SubagentRunTranscript({+ events,+ className = "",+}: {+ events: StreamEvent[];+ className?: string;+}) {+ const visible = useMemo(() => {+ // Events sharing a merge id collapse to ONE evolving row, rendered at the+ // first occurrence's position with the latest content. This drives two+ // things uniformly: a fill-in tool (web search shows "web search" on start,+ // fills in its query on finish) and token-level streaming (each text/think+ // delta carries the cumulative text under one id, so the row types out and+ // the final block finalizes it in place — the answer renders exactly once).+ const latestByMerge = new Map<string, StreamEvent>();+ for (const e of events) {+ const id = getTraceMeta(e).subagent_merge_id;+ if (id) latestByMerge.set(id, e);+ }+ const seenMerge = new Set<string>();+ const out: StreamEvent[] = [];+ for (const e of events) {+ const mergeId = getTraceMeta(e).subagent_merge_id;+ if (mergeId) {+ if (seenMerge.has(mergeId)) continue;+ seenMerge.add(mergeId);+ out.push(latestByMerge.get(mergeId) ?? e);+ continue;+ }+ out.push(e);+ }+ return out;+ }, [events]);++ return (+ <div+ className={`space-y-2.5 px-4 py-3.5 text-[13px] ${className}`}+ style={{ fontFamily: MONO_FONT }}+ >+ {visible.length === 0 ? (+ <div className="text-[var(--muted-foreground)]/70">…</div>+ ) : (+ visible.map((event, idx) => (+ <SubagentLine+ key={`sa-${idx}`}+ channel={String(getTraceMeta(event).subagent_channel || "log")}+ text={event.content}+ />+ ))+ )}+ </div>+ );+}++/** A "●"-bulleted step line (the agent's messages and tool calls). */+function BulletLine({+ bulletClass,+ children,+}: {+ bulletClass: string;+ children: React.ReactNode;+}) {+ return (+ <div className="flex gap-2 leading-[1.65] text-[var(--foreground)]">+ <span className={`mt-[3px] shrink-0 text-[10px] leading-[1.5] ${bulletClass}`}>+ ●+ </span>+ <span className="min-w-0 flex-1 whitespace-pre-wrap break-words">+ {children}+ </span>+ </div>+ );+}++function SubagentLine({ channel, text }: { channel: string; text: string }) {+ const { t } = useTranslation();+ switch (channel) {+ case "question":+ case "user_question":+ // Heads each round: the question DeepTutor (or the user, from the sidebar)+ // put to the agent.+ return (+ <div className="mt-1 border-t border-[var(--border)]/60 pt-2.5 first:mt-0 first:border-t-0 first:pt-0">+ <div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.06em] text-[var(--primary)]">+ {channel === "user_question" ? t("You ask") : t("DeepTutor asks")}+ </div>+ <div className="whitespace-pre-wrap break-words leading-[1.6] text-[var(--foreground)]">+ {text}+ </div>+ </div>+ );+ case "text":+ case "result":+ return <BulletLine bulletClass="text-[var(--foreground)]/70">{text}</BulletLine>;+ case "tool":+ return (+ <BulletLine bulletClass="text-amber-500">+ <span className="break-all">{text}</span>+ </BulletLine>+ );+ case "reasoning":+ return (+ <div className="whitespace-pre-wrap break-words pl-4 text-[12px] italic leading-[1.6] text-[var(--muted-foreground)]">+ {text}+ </div>+ );+ case "tool_result":+ return <ToolResultBlock text={text} />;+ case "error":+ return (+ <div className="whitespace-pre-wrap break-words pl-4 leading-[1.55] text-red-600 dark:text-red-400">+ {text}+ </div>+ );+ default:+ return (+ <div className="whitespace-pre-wrap break-all pl-4 text-[12px] leading-[1.55] text-[var(--muted-foreground)]/70">+ {text}+ </div>+ );+ }+}++function ToolResultBlock({ text }: { text: string }) {+ const { i18n } = useTranslation();+ const zh = i18n.language?.toLowerCase().startsWith("zh");+ const [open, setOpen] = useState(false);+ const lines = text.split("\n");+ const overflow = lines.length > RESULT_PREVIEW_LINES;+ const shown = open || !overflow ? lines : lines.slice(0, RESULT_PREVIEW_LINES);+ const hidden = lines.length - RESULT_PREVIEW_LINES;+ return (+ <div className="ml-4 rounded-md border border-[var(--border)]/60 bg-[var(--muted)]/50 px-2.5 py-1.5">+ <pre+ className={`m-0 whitespace-pre-wrap break-all text-[12px] leading-[1.55] text-[var(--muted-foreground)] ${+ open ? "" : "max-h-20 overflow-hidden"+ }`}+ style={{ fontFamily: MONO_FONT }}+ >+ {shown.join("\n")}+ </pre>+ {overflow && (+ <button+ type="button"+ onClick={() => setOpen(!open)}+ className="mt-1 text-[11px] text-[var(--muted-foreground)]/80 transition-colors hover:text-[var(--foreground)]"+ >+ {open+ ? zh+ ? "收起"+ : "collapse"+ : zh+ ? `… 展开 +${hidden} 行`+ : `… +${hidden} lines`}+ </button>+ )}+ </div>+ );+}diff --git a/web/components/chat/home/SubagentTabBody.tsx b/web/components/chat/home/SubagentTabBody.tsxnew file mode 100644index 000000000..6c4727688--- /dev/null+++ b/web/components/chat/home/SubagentTabBody.tsx@@ -0,0 +1,140 @@+"use client";++import { useCallback, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { ArrowUp, Loader2 } from "lucide-react";++import SubagentRunTranscript from "@/components/chat/home/SubagentRunTranscript";+import { getTraceMeta } from "@/components/chat/home/TracePanels";+import { streamSubagentMessage } from "@/lib/subagents-api";+import type { StreamEvent } from "@/lib/unified-ws";++/**+ * A connected subagent's run tab: the streamed transcript plus an input box to+ * message the agent directly. Sent messages resume the SAME live session+ * DeepTutor consults (shared via the cross-turn registry), so the agent keeps+ * full context — the sidebar and the chat loop talk to one agent session.+ *+ * Events from the chat loop arrive as ``tabEvents`` (refreshed by the parent);+ * sidebar-originated events live in local state and are concatenated, so the+ * transcript shows the whole exchange in order.+ */+export default function SubagentTabBody({+ tabEvents,+ sessionId,+}: {+ tabEvents: StreamEvent[];+ sessionId: string | null;+}) {+ const { t } = useTranslation();+ const [localEvents, setLocalEvents] = useState<StreamEvent[]>([]);+ const [draft, setDraft] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const seqRef = useRef(0);++ // The connection's name/kind come from the streamed events' metadata.+ const { name } = useMemo(() => {+ for (let i = tabEvents.length - 1; i >= 0; i--) {+ const meta = getTraceMeta(tabEvents[i]);+ if (meta.subagent_name) {+ return { name: String(meta.subagent_name) };+ }+ }+ return { name: "" };+ }, [tabEvents]);++ const allEvents = useMemo(+ () => [...tabEvents, ...localEvents],+ [tabEvents, localEvents],+ );++ const append = useCallback(+ (channel: string, text: string, mergeId?: string) => {+ const event: StreamEvent = {+ type: "progress",+ source: "subagent",+ stage: "",+ content: text,+ metadata: {+ trace_kind: "subagent_event",+ subagent_channel: channel,+ subagent_name: name,+ ...(mergeId ? { subagent_merge_id: mergeId } : {}),+ },+ timestamp: seqRef.current++,+ };+ setLocalEvents((prev) => [...prev, event]);+ },+ [name],+ );++ const send = useCallback(async () => {+ const message = draft.trim();+ if (!message || busy || !name) return;+ setDraft("");+ setError(null);+ setBusy(true);+ try {+ for await (const line of streamSubagentMessage(name, {+ chat_session_id: sessionId ?? "",+ message,+ })) {+ if (line.done) break;+ if (line.channel) append(line.channel, line.text ?? "", line.merge_id);+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ }, [draft, busy, name, sessionId, append]);++ return (+ <div className="flex h-full flex-col">+ <div className="min-h-0 flex-1 overflow-y-auto">+ <SubagentRunTranscript events={allEvents} className="min-h-full" />+ </div>+ <div className="shrink-0 border-t border-[var(--border)] bg-[var(--background)] px-3 py-2.5">+ {error && (+ <div className="mb-1.5 text-[11.5px] text-red-600 dark:text-red-400">+ {error}+ </div>+ )}+ <div className="flex items-end gap-2">+ <textarea+ rows={1}+ value={draft}+ disabled={busy || !name}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void send();+ }+ }}+ placeholder={+ name+ ? t("Message {{name}} directly…", { name })+ : t("Message the agent directly…")+ }+ className="max-h-32 min-h-[36px] flex-1 resize-none rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--ring)] disabled:opacity-60"+ />+ <button+ type="button"+ onClick={() => void send()}+ disabled={busy || !draft.trim() || !name}+ aria-label={t("Send")}+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-[var(--foreground)] text-[var(--background)] transition-opacity disabled:opacity-40"+ >+ {busy ? (+ <Loader2 size={16} className="animate-spin" />+ ) : (+ <ArrowUp size={16} />+ )}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsxindex d9b2da8a3..699c8fce8 100644--- a/web/components/chat/home/TracePanels.tsx+++ b/web/components/chat/home/TracePanels.tsx@@ -58,6 +58,15 @@ type TraceMetadata = {section_index?: number | string;section_count?: number | string;section_title?: string;+ // Set on each native event streamed from a connected subagent+ // (trace_kind="subagent_event"): the channel it came from and which consult.+ subagent_channel?: string;+ subagent_kind?: string;+ subagent_name?: string;+ consult_index?: number;+ // Correlates a fill-in tool's start/finish events (e.g. a web search) so the+ // transcript collapses them into one evolving row.+ subagent_merge_id?: string;};type ResearchStageId = "understand" | "decompose" | "evidence" | "result";@@ -905,6 +914,12 @@ function TraceRowBody({const renderableBodyBlocks = bodyBlocks.filter((text): text is string => Boolean(text) && text.trim().length > 0,);+ // A connected subagent's native run streams in as ``subagent_event`` progress+ // lines, but those are shown in the side viewer's per-agent tab — keep the+ // inline trace compact (the question + the agent's final reply).+ const plainSummaryEvents = summaryProgressEvents.filter(+ (event) => getTraceMeta(event).trace_kind !== "subagent_event",+ );const inlineSources = callEvents.flatMap((event) => getTraceMeta(event).sources ?? [],);@@ -971,9 +986,9 @@ function TraceRowBody({</div>) : (<div className="space-y-1">- {summaryProgressEvents.length > 0 && (+ {plainSummaryEvents.length > 0 && (<div className="space-y-0.5">- {summaryProgressEvents.map((event, idx) => (+ {plainSummaryEvents.map((event, idx) => (<div key={`${callId}-progress-${idx}`} className="opacity-70">{event.content}</div>@@ -1232,6 +1247,17 @@ function TraceRowItem({chip = descriptor.chip? { text: descriptor.chip, mono: descriptor.mono }: null;+ // Name the consult after the agent it targets (e.g. "Consult Subagent+ // test-cc"); the name rides on the streamed subagent events in the group.+ if (toolName === "consult_subagent") {+ const agentName = String(+ callEvents.map((e) => getTraceMeta(e).subagent_name).find(Boolean) ||+ "",+ );+ headline = agentName+ ? `${t("Consult Subagent")} ${agentName}`+ : t("Consult Subagent");+ }} else if (isRetrieve) {resolvedIcon = KnowledgeMark;headline = header;diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsxindex 9ab9eb7fd..67b8db582 100644--- a/web/components/knowledge/KnowledgePage.tsx+++ b/web/components/knowledge/KnowledgePage.tsx@@ -20,7 +20,7 @@ export default function KnowledgePage() {const initialEngine = searchParams.get("engine");const {- kbs,+ kbs: allKbs,providers,uploadPolicy,loading,@@ -40,6 +40,14 @@ export default function KnowledgePage() {connectLinkedFolder,} = useKnowledgeBases();+ // Connected subagents are stored as ``type: subagent`` KBs so the chat+ // composer can select them, but they are agents, not knowledge bases — keep+ // them out of the Knowledge Center entirely.+ const kbs = useMemo(+ () => allKbs.filter((kb) => kb.metadata?.type !== "subagent"),+ [allKbs],+ );+const [explicitSelection, setExplicitSelection] = useState<string | null>(initialKb,);diff --git a/web/components/partners/PartnerArchives.tsx b/web/components/partners/PartnerArchives.tsxindex 081f9f17c..16da6b3d6 100644--- a/web/components/partners/PartnerArchives.tsx+++ b/web/components/partners/PartnerArchives.tsx@@ -1,11 +1,20 @@"use client";import { useCallback, useEffect, useMemo, useState } from "react";-import { Archive, Clock3, MessageSquareText, RefreshCw } from "lucide-react";+import {+ Archive,+ Clock3,+ MessageSquareText,+ RefreshCw,+ RotateCcw,+ Trash2,+} from "lucide-react";import { useTranslation } from "react-i18next";import {+ deletePartnerSession,getPartnerHistory,getPartnerSessions,+ resumePartnerSession,type PartnerSessionInfo,} from "@/lib/partners-api";import type { ExportableMessage } from "@/lib/chat-export";@@ -33,12 +42,15 @@ export default function PartnerArchives({partnerId,onToast,onMessagesChange,+ onResume,}: {partnerId: string;onToast: (message: string) => void;/** Lifts the selected conversation up so the page header can export it.* Empty array when nothing is selected (or while loading). */onMessagesChange?: (messages: ExportableMessage[]) => void;+ /** Continue a conversation in the Chat tab (un-archives it first). */+ onResume?: (sessionKey: string) => void;}) {const { t } = useTranslation();const [sessions, setSessions] = useState<PartnerSessionInfo[]>([]);@@ -78,6 +90,34 @@ export default function PartnerArchives({void loadSessions();}, [loadSessions]);+ const handleResume = useCallback(+ async (session: PartnerSessionInfo) => {+ try {+ if (session.archived) {+ await resumePartnerSession(partnerId, session.session_key);+ }+ onResume?.(session.session_key);+ } catch (e) {+ onToast(e instanceof Error ? e.message : t("Load failed"));+ }+ },+ [partnerId, onResume, onToast, t],+ );++ const handleDelete = useCallback(+ async (session: PartnerSessionInfo) => {+ try {+ await deletePartnerSession(partnerId, session.session_key);+ if (selectedKey === session.session_key) setSelectedKey("");+ onToast(t("Conversation deleted"));+ await loadSessions();+ } catch (e) {+ onToast(e instanceof Error ? e.message : t("Delete failed"));+ }+ },+ [partnerId, selectedKey, loadSessions, onToast, t],+ );+useEffect(() => {if (!selectedKey) {setMessages([]);@@ -158,12 +198,13 @@ export default function PartnerArchives({><div className="flex items-center gap-2">{session.archived ? (- <Archive className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />+ <Archive className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />) : (- <MessageSquareText className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />+ <MessageSquareText className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />)}<span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-[var(--foreground)]">- {session.archived ? t("Archived") : t("Current")}+ {session.title ||+ (session.archived ? t("Archived") : t("New conversation"))}</span><span className="text-[11px] text-[var(--muted-foreground)]">{session.message_count}@@ -193,19 +234,40 @@ export default function PartnerArchives({<div className="mx-auto max-w-2xl pb-4"><div className="sticky top-0 z-10 border-b border-[var(--border)] bg-[var(--background)] py-2"><div className="flex items-center justify-between gap-3">- <div>- <h3 className="text-[13px] font-medium text-[var(--foreground)]">- {selected.archived- ? t("Archived conversation")- : t("Current conversation")}+ <div className="min-w-0">+ <h3 className="truncate text-[13px] font-medium text-[var(--foreground)]">+ {selected.title ||+ (selected.archived+ ? t("Archived conversation")+ : t("New conversation"))}</h3><p className="text-[11.5px] text-[var(--muted-foreground)]">- {formatTime(selected.updated_at)}+ {(selected.archived ? `${t("Archived")} · ` : "") ++ formatTime(selected.updated_at)}</p></div>- <span className="rounded-md bg-[var(--muted)] px-2 py-1 text-[11px] text-[var(--muted-foreground)]">- {t("{{count}} messages", { count: selected.message_count })}- </span>+ <div className="flex shrink-0 items-center gap-2">+ <span className="rounded-md bg-[var(--muted)] px-2 py-1 text-[11px] text-[var(--muted-foreground)]">+ {t("{{count}} messages", { count: selected.message_count })}+ </span>+ <button+ type="button"+ onClick={() => void handleResume(selected)}+ title={t("Continue this conversation")}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-[11px] text-[var(--foreground)] hover:bg-[var(--muted)]"+ >+ <RotateCcw className="h-3 w-3" />+ {t("Continue")}+ </button>+ <button+ type="button"+ onClick={() => void handleDelete(selected)}+ title={t("Delete conversation")}+ className="inline-flex h-[26px] w-[26px] items-center justify-center rounded-md text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-red-500"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </div></div></div>diff --git a/web/components/partners/PartnerChannels.tsx b/web/components/partners/PartnerChannels.tsxindex fe2dc4bb5..c65158111 100644--- a/web/components/partners/PartnerChannels.tsx+++ b/web/components/partners/PartnerChannels.tsx@@ -144,6 +144,8 @@ export default function PartnerChannels({const err = (await res.json().catch(() => ({}))) as { detail?: string };onToast(err.detail ?? t("Save failed"));}+ } catch (error) {+ onToast(error instanceof Error ? error.message : t("Save failed"));} finally {setSaving(false);}diff --git a/web/components/partners/PartnerChat.tsx b/web/components/partners/PartnerChat.tsxindex eb59792e1..e9a7b3dc3 100644--- a/web/components/partners/PartnerChat.tsx+++ b/web/components/partners/PartnerChat.tsx@@ -16,7 +16,15 @@ import { useTranslation } from "react-i18next";import dynamic from "next/dynamic";import { Paperclip } from "lucide-react";import { wsUrl } from "@/lib/api";-import { getPartnerHistory } from "@/lib/partners-api";+import {+ archivePartnerSession,+ branchPartnerSession,+ deletePartnerSession,+ getPartnerHistory,+ getPartnerSessions,+ resumePartnerSession,+} from "@/lib/partners-api";+import { freshPartnerSessionKey } from "@/lib/partner-session";import type { ExportableMessage } from "@/lib/chat-export";import type { StreamEvent } from "@/lib/unified-ws";import { docIconFor, formatBytes, isSvgFilename } from "@/lib/doc-attachments";@@ -54,9 +62,32 @@ interface PartnerMessageAttachment {previewUrl?: string;}-function resetsVisibleConversation(content: string) {- const command = content.trim().split(/\s+/, 1)[0]?.toLowerCase();- return command === "/new" || command === "/clear";+// Commands the web client handles itself (they change client state — the+// active session, or the in-flight turn — which a server text reply can't do).+const CLIENT_COMMANDS = new Set([+ "/new",+ "/clear",+ "/branch",+ "/resume",+ "/delete",+ "/sessions",+ "/stop",+]);++function parseClientCommand(+ content: string,+): { command: string; arg: string } | null {+ const trimmed = content.trim();+ if (!trimmed.startsWith("/")) return null;+ const [head, ...rest] = trimmed.split(/\s+/);+ const command = head.toLowerCase();+ if (!CLIENT_COMMANDS.has(command)) return null;+ return { command, arg: rest.join(" ").trim() };+}++function normalizeHistoryEvents(value: unknown): StreamEvent[] | undefined {+ if (!Array.isArray(value) || value.length === 0) return undefined;+ return value as StreamEvent[];}function normalizeHistoryAttachments(@@ -159,6 +190,9 @@ export default function PartnerChat({color,avatar,running,+ sessionKey,+ onSessionKeyChange,+ onToast,onMessagesChange,}: {partnerId: string;@@ -167,6 +201,12 @@ export default function PartnerChat({color?: string;avatar?: string;running: boolean;+ /** The active web session key (canonical id), owned by the page so the+ * Archive tab can switch which conversation the Chat tab is on. */+ sessionKey: string;+ /** Rotate to a different session (new / branch / resume / delete-current). */+ onSessionKeyChange: (key: string) => void;+ onToast?: (message: string) => void;/** Lifts the settled conversation up so the page header can export it.* Fires only on discrete message events (send / turn done / clear), not* per streamed token — the live `draft` is intentionally excluded. */@@ -185,12 +225,24 @@ export default function PartnerChat({} | null>(null);const wsRef = useRef<WebSocket | null>(null);const scrollRef = useRef<HTMLDivElement | null>(null);- const sessionIdRef = useRef<string>("");+ // Mirror the active session into a ref so the socket's onopen (which closes+ // over the effect's first render) attaches to the CURRENT session.+ const sessionKeyRef = useRef(sessionKey);+ sessionKeyRef.current = sessionKey;+ // Attach to an in-flight turn only AFTER history has loaded, so the replay's+ // echoed question + answer aren't clobbered by the history replace. Attach+ // once per socket connection.+ const historyReadyRef = useRef(false);+ const attachedRef = useRef(false);- useEffect(() => {- if (!sessionIdRef.current) {- sessionIdRef.current = `web-${Math.random().toString(36).slice(2, 10)}`;- }+ const tryAttach = useCallback(() => {+ if (attachedRef.current) return;+ if (!historyReadyRef.current || !sessionKeyRef.current) return;+ if (wsRef.current?.readyState !== WebSocket.OPEN) return;+ attachedRef.current = true;+ wsRef.current.send(+ JSON.stringify({ action: "attach", session_key: sessionKeyRef.current }),+ );}, []);const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => {@@ -202,10 +254,18 @@ export default function PartnerChat({});}, []);- // Restore recent history (all sessions merged → the partner's memory feel).+ // Restore the active session's history (scoped to it — the cross-channel+ // "memory feel" is served by the read_memory tool now, not by merging raw+ // transcripts). Re-runs when the page switches the active session (resume /+ // branch). Persisted turn events rehydrate the collapsible "Done" activity.useEffect(() => {+ if (!sessionKey) return;let cancelled = false;- void getPartnerHistory(partnerId, { limit: 60 })+ historyReadyRef.current = false;+ void getPartnerHistory(partnerId, {+ sessionKey,+ limit: 60,+ }).then((history) => {if (cancelled) return;setMessages(@@ -217,15 +277,23 @@ export default function PartnerChat({attachments: normalizeHistoryAttachments((m as Record<string, unknown>).attachments,),+ events: normalizeHistoryEvents(+ (m as Record<string, unknown>).events,+ ),})),);+ historyReadyRef.current = true;+ tryAttach();requestAnimationFrame(() => scrollToBottom("instant"));})- .catch(() => {});+ .catch(() => {+ historyReadyRef.current = true;+ tryAttach();+ });return () => {cancelled = true;};- }, [partnerId, scrollToBottom]);+ }, [partnerId, sessionKey, scrollToBottom, tryAttach]);useEffect(() => {if (!running) {@@ -237,9 +305,17 @@ export default function PartnerChat({return;}+ attachedRef.current = false;const ws = new WebSocket(wsUrl(`/api/v1/partners/${partnerId}/ws`));wsRef.current = ws;- ws.onopen = () => setConnected(true);+ ws.onopen = () => {+ setConnected(true);+ // Reattach to an in-flight turn (survives a page refresh): the server+ // replays its buffered stream, so a mid-answer reload keeps streaming.+ // Sequenced after history load via tryAttach so the replay isn't+ // clobbered by the history replace.+ tryAttach();+ };// Authoritative live-turn accumulator. Lives in the effect scope so// socket handlers can mutate it cheaply; renders see snapshots only.@@ -256,6 +332,22 @@ export default function PartnerChat({content?: string;event?: StreamEvent;};+ if (data.type === "resuming") {+ // Server is about to replay an in-flight turn (after a refresh).+ live = { events: [], content: "" };+ setStreaming(true);+ publish();+ return;+ }+ if (data.type === "user_echo") {+ // The question that opened the replayed turn (not yet persisted).+ setMessages((msgs) => [+ ...msgs,+ { role: "user", content: data.content ?? "" },+ ]);+ scrollToBottom();+ return;+ }if (data.type === "stream_event" && data.event) {const event = data.event;live ??= { events: [], content: "" };@@ -288,6 +380,23 @@ export default function PartnerChat({setStreaming(false);live = null;publish();+ } else if (data.type === "stopped") {+ // Server cancelled the turn (/stop or the stop button). Keep any+ // partial answer the user already saw; drop the live draft.+ const finished = live;+ live = null;+ if (finished && (finished.content || finished.events.length)) {+ setMessages((msgs) => [+ ...msgs,+ {+ role: "assistant",+ content: finished.content,+ events: finished.events.length ? finished.events : undefined,+ },+ ]);+ }+ setStreaming(false);+ publish();} else if (data.type === "proactive") {setMessages((msgs) => [...msgs,@@ -314,7 +423,7 @@ export default function PartnerChat({ws.close();wsRef.current = null;};- }, [partnerId, running, scrollToBottom]);+ }, [partnerId, running, scrollToBottom, tryAttach]);// Report the settled transcript to the parent for header export controls.useEffect(() => {@@ -331,15 +440,128 @@ export default function PartnerChat({);}, [messages, onMessagesChange]);+ const sendStop = useCallback(() => {+ if (wsRef.current?.readyState === WebSocket.OPEN) {+ wsRef.current.send(+ JSON.stringify({ action: "stop", session_key: sessionKey }),+ );+ }+ }, [sessionKey]);++ // Session-management commands run client-side: they switch the active+ // session or stop the turn — things a server text reply can't do. Returns+ // true when handled (so the caller skips the normal send).+ const runClientCommand = useCallback(+ async (command: string, arg: string): Promise<void> => {+ switch (command) {+ case "/new":+ case "/clear": {+ await archivePartnerSession(partnerId, sessionKey).catch(() => {});+ setMessages([]);+ onSessionKeyChange(freshPartnerSessionKey());+ break;+ }+ case "/branch": {+ const next = freshPartnerSessionKey();+ try {+ await branchPartnerSession(partnerId, sessionKey, next);+ onToast?.(+ t("Branched — the original is archived as {{id}}", {+ id: sessionKey,+ }),+ );+ onSessionKeyChange(next); // history reload picks up the copy+ } catch {+ onToast?.(t("Nothing to branch yet."));+ }+ break;+ }+ case "/resume": {+ if (!arg) {+ onToast?.(t("Usage: /resume <session ID>"));+ break;+ }+ try {+ await resumePartnerSession(partnerId, arg);+ onSessionKeyChange(arg);+ } catch {+ onToast?.(t("Session not found"));+ }+ break;+ }+ case "/delete": {+ if (!arg) {+ onToast?.(t("Usage: /delete <session ID>"));+ break;+ }+ try {+ await deletePartnerSession(partnerId, arg);+ onToast?.(t("Conversation deleted"));+ if (arg === sessionKey) {+ setMessages([]);+ onSessionKeyChange(freshPartnerSessionKey());+ }+ } catch {+ onToast?.(t("Session not found"));+ }+ break;+ }+ case "/sessions": {+ try {+ const sessions = await getPartnerSessions(partnerId);+ const lines = sessions+ .slice(0, 30)+ .map(+ (s) =>+ `- \`${s.session_key}\`${s.archived ? ` (${t("Archived")})` : ""} — ${+ s.title || t("New conversation")+ } · ${s.message_count}`,+ )+ .join("\n");+ setMessages((msgs) => [+ ...msgs,+ {+ role: "assistant",+ content: `${t("Conversations:")}\n${lines}\n\n${t(+ "Use /resume <session ID> or /delete <session ID>.",+ )}`,+ },+ ]);+ scrollToBottom();+ } catch {+ onToast?.(t("Load failed"));+ }+ break;+ }+ case "/stop": {+ sendStop();+ break;+ }+ }+ },+ [+ partnerId,+ sessionKey,+ onSessionKeyChange,+ onToast,+ scrollToBottom,+ sendStop,+ t,+ ],+ );+const handleSend = useCallback((content: string, attachments: PartnerPendingAttachment[]) => {- if (- streaming ||- !running ||- !wsRef.current ||- wsRef.current.readyState !== WebSocket.OPEN- )+ if (streaming || !running) return;++ const command =+ attachments.length === 0 ? parseClientCommand(content) : null;+ if (command) {+ void runClientCommand(command.command, command.arg);return;+ }++ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;const visibleContent =content ||(attachments.every((item) => item.type === "image")@@ -348,7 +570,7 @@ export default function PartnerChat({wsRef.current.send(JSON.stringify({content: visibleContent,- session_id: sessionIdRef.current,+ session_key: sessionKey,attachments: attachments.map((item) => ({type: item.type,filename: item.filename,@@ -357,23 +579,19 @@ export default function PartnerChat({})),}),);- if (resetsVisibleConversation(visibleContent)) {- setMessages([]);- } else {- setMessages((msgs) => [- ...msgs,- {- role: "user",- content: visibleContent,- attachments: sentAttachmentsForMessage(attachments),- },- ]);- }+ setMessages((msgs) => [+ ...msgs,+ {+ role: "user",+ content: visibleContent,+ attachments: sentAttachmentsForMessage(attachments),+ },+ ]);setDraft({ events: [], content: "" });setStreaming(true);scrollToBottom();},- [running, streaming, scrollToBottom, t],+ [sessionKey, running, streaming, scrollToBottom, runClientCommand, t],);return (@@ -485,7 +703,9 @@ export default function PartnerChat({) : null}<PartnerComposeronSend={handleSend}- disabled={streaming || !connected || !running}+ onStop={sendStop}+ streaming={streaming}+ disabled={!connected || !running}/></div></div>diff --git a/web/components/partners/PartnerComposer.tsx b/web/components/partners/PartnerComposer.tsxindex 568f01d1c..e875b2715 100644--- a/web/components/partners/PartnerComposer.tsx+++ b/web/components/partners/PartnerComposer.tsx@@ -6,10 +6,14 @@* picker, paste, and drag/drop.*/-import { memo, useCallback, useRef, useState } from "react";-import { ArrowUp, Paperclip, X } from "lucide-react";+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { ArrowUp, Info, Paperclip, Square, X } from "lucide-react";import { useTranslation } from "react-i18next";import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";+import {+ getPartnerCommands,+ type PartnerCommandInfo,+} from "@/lib/partners-api";import {ATTACHMENT_ACCEPT,MAX_ATTACHMENT_BYTES,@@ -36,11 +40,15 @@ export interface PartnerPendingAttachment {export const PartnerComposer = memo(function PartnerComposer({onSend,+ onStop,disabled,+ streaming,placeholder,}: {onSend: (content: string, attachments: PartnerPendingAttachment[]) => void;+ onStop?: () => void;disabled?: boolean;+ streaming?: boolean;placeholder?: string;}) {const { t } = useTranslation();@@ -50,6 +58,10 @@ export const PartnerComposer = memo(function PartnerComposer({);const [dragging, setDragging] = useState(false);const [attachmentError, setAttachmentError] = useState<string | null>(null);+ const [commands, setCommands] = useState<PartnerCommandInfo[]>([]);+ const [slashClosed, setSlashClosed] = useState(false);+ const [slashIndex, setSlashIndex] = useState(0);+ const [showHelp, setShowHelp] = useState(false);const textareaRef = useRef<HTMLTextAreaElement | null>(null);const fileInputRef = useRef<HTMLInputElement | null>(null);const dragCounterRef = useRef(0);@@ -58,6 +70,44 @@ export const PartnerComposer = memo(function PartnerComposer({useAutoSizedTextarea(textareaRef, input, { min: 24, max: 180 });+ // Slash commands (same 5 the IM channels expose) — fetched once; the palette+ // is partner-independent so no id is needed.+ useEffect(() => {+ let cancelled = false;+ void getPartnerCommands()+ .then((next) => {+ if (!cancelled) setCommands(next);+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, []);++ // The menu is active while the input is a bare "/word" (no space yet) and the+ // user hasn't dismissed it. Typing reopens it; Escape / accept closes it.+ const slashMatch = /^\/([a-z]*)$/i.exec(input);+ const slashQuery = slashMatch ? slashMatch[1].toLowerCase() : null;+ const slashMatches = useMemo(+ () =>+ slashQuery !== null+ ? commands.filter((c) =>+ c.command.slice(1).toLowerCase().startsWith(slashQuery),+ )+ : [],+ [commands, slashQuery],+ );+ const slashOpen = !slashClosed && slashMatches.length > 0;+ const boundedSlashIndex = Math.min(slashIndex, slashMatches.length - 1);++ const acceptCommand = useCallback((command: PartnerCommandInfo) => {+ // Arg-taking commands keep the menu out of the way with a trailing space;+ // zero-arg ones are left ready to send.+ setInput(command.arg_hint ? `${command.command} ` : command.command);+ setSlashClosed(true);+ requestAnimationFrame(() => textareaRef.current?.focus());+ }, []);+const showAttachmentError = useCallback((message: string) => {setAttachmentError(message);if (errorTimerRef.current) clearTimeout(errorTimerRef.current);@@ -152,12 +202,44 @@ export const PartnerComposer = memo(function PartnerComposer({const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ // When the slash menu is open it owns the arrow/enter/tab/escape keys.+ if (slashOpen && !isComposingRef.current) {+ if (e.key === "ArrowDown") {+ e.preventDefault();+ setSlashIndex((i) => Math.min(i + 1, slashMatches.length - 1));+ return;+ }+ if (e.key === "ArrowUp") {+ e.preventDefault();+ setSlashIndex((i) => Math.max(i - 1, 0));+ return;+ }+ if (e.key === "Enter" || e.key === "Tab") {+ e.preventDefault();+ acceptCommand(slashMatches[boundedSlashIndex]);+ return;+ }+ if (e.key === "Escape") {+ e.preventDefault();+ setSlashClosed(true);+ return;+ }+ }if (shouldSubmitOnEnter(e, isComposingRef.current)) {e.preventDefault();submit();}},- [submit],+ [acceptCommand, boundedSlashIndex, slashMatches, slashOpen, submit],+ );++ const handleInputChange = useCallback(+ (e: React.ChangeEvent<HTMLTextAreaElement>) => {+ setInput(e.target.value);+ setSlashClosed(false); // typing always re-arms the menu+ setSlashIndex(0);+ },+ [],);const handlePaste = useCallback(@@ -228,7 +310,8 @@ export const PartnerComposer = memo(function PartnerComposer({setAttachments((prev) => prev.filter((_, i) => i !== index));}, []);- const canSend = (!!input.trim() || attachments.length > 0) && !disabled;+ const canSend =+ (!!input.trim() || attachments.length > 0) && !disabled && !streaming;return (<div@@ -267,10 +350,44 @@ export const PartnerComposer = memo(function PartnerComposer({tabIndex={-1}/>+ {slashOpen && (+ <div className="absolute bottom-full left-0 z-20 mb-2 w-full max-w-sm overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-lg">+ {slashMatches.map((command, index) => (+ <button+ key={command.command}+ type="button"+ // onMouseDown (not onClick) so the textarea doesn't blur first.+ onMouseDown={(e) => {+ e.preventDefault();+ acceptCommand(command);+ }}+ onMouseEnter={() => setSlashIndex(index)}+ className={`flex w-full items-baseline gap-2 px-3 py-2 text-left transition-colors ${+ index === boundedSlashIndex+ ? "bg-[var(--muted)]"+ : "hover:bg-[var(--muted)]/60"+ }`}+ >+ <span className="font-mono text-[12.5px] text-[var(--foreground)]">+ {command.command}+ </span>+ {command.arg_hint && (+ <span className="font-mono text-[11px] text-[var(--muted-foreground)]">+ {command.arg_hint}+ </span>+ )}+ <span className="ml-auto truncate pl-3 text-[11.5px] text-[var(--muted-foreground)]">+ {command.description}+ </span>+ </button>+ ))}+ </div>+ )}+<textarearef={textareaRef}value={input}- onChange={(e) => setInput(e.target.value)}+ onChange={handleInputChange}onKeyDown={handleKeyDown}onPaste={handlePaste}onCompositionStart={() => {@@ -284,7 +401,7 @@ export const PartnerComposer = memo(function PartnerComposer({placeholder={placeholder ?? t("Type a message...")}rows={1}maxLength={32000}- disabled={disabled}+ disabled={disabled || streaming}className="block w-full resize-none bg-transparent px-3.5 pt-3 pb-1 text-[14px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)] disabled:opacity-50"/>@@ -363,25 +480,69 @@ export const PartnerComposer = memo(function PartnerComposer({)}<div className="flex items-center justify-between px-2 pb-2">- <button- type="button"- onClick={() => fileInputRef.current?.click()}- disabled={disabled}- aria-label={t("Attach files")}- title={t("Attach files")}- className="flex h-7 w-7 items-center justify-center rounded-full text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-30"- >- <Paperclip className="h-4 w-4" strokeWidth={1.9} />- </button>- <button- type="button"- onClick={submit}- disabled={!canSend}- aria-label={t("Send")}- className="flex h-7 w-7 items-center justify-center rounded-full bg-[var(--primary)] text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-30"- >- <ArrowUp className="h-4 w-4" strokeWidth={2.2} />- </button>+ <div className="flex items-center gap-0.5">+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={disabled || streaming}+ aria-label={t("Attach files")}+ title={t("Attach files")}+ className="flex h-7 w-7 items-center justify-center rounded-full text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-30"+ >+ <Paperclip className="h-4 w-4" strokeWidth={1.9} />+ </button>+ <div+ className="relative flex items-center"+ onMouseEnter={() => setShowHelp(true)}+ onMouseLeave={() => setShowHelp(false)}+ >+ <button+ type="button"+ aria-label={t("Tips")}+ className="flex h-7 w-7 items-center justify-center rounded-full text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <Info className="h-4 w-4" strokeWidth={1.9} />+ </button>+ {showHelp && (+ <div className="absolute bottom-full left-0 z-20 mb-2 w-64 rounded-xl border border-[var(--border)] bg-[var(--card)] p-3 text-[11.5px] leading-relaxed text-[var(--muted-foreground)] shadow-lg">+ <p className="mb-1 font-medium text-[var(--foreground)]">+ {t("Tips")}+ </p>+ <p>+ {t(+ "Type / to see commands — start a new conversation, view history, toggle tools, and more.",+ )}+ </p>+ <p className="mt-1.5">+ {t(+ "Attach images or documents with the clip, or just drag them in.",+ )}+ </p>+ </div>+ )}+ </div>+ </div>+ {streaming ? (+ <button+ type="button"+ onClick={onStop}+ aria-label={t("Stop")}+ title={t("Stop")}+ className="flex h-7 w-7 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] transition-opacity hover:opacity-90"+ >+ <Square className="h-3 w-3" strokeWidth={2.2} fill="currentColor" />+ </button>+ ) : (+ <button+ type="button"+ onClick={submit}+ disabled={!canSend}+ aria-label={t("Send")}+ className="flex h-7 w-7 items-center justify-center rounded-full bg-[var(--primary)] text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-30"+ >+ <ArrowUp className="h-4 w-4" strokeWidth={2.2} />+ </button>+ )}</div></div>);diff --git a/web/components/partners/PartnerConfigure.tsx b/web/components/partners/PartnerConfigure.tsxindex 7ca5cfe7c..de69390ee 100644--- a/web/components/partners/PartnerConfigure.tsx+++ b/web/components/partners/PartnerConfigure.tsx@@ -107,6 +107,7 @@ export default function PartnerConfigure({// Toolsconst [toolOptions, setToolOptions] = useState<ToolOptions | null>(null);const [enabledTools, setEnabledTools] = useState<string[]>([]);+ const [builtinTools, setBuiltinTools] = useState<string[]>([]);const [mcpTools, setMcpTools] = useState<string[]>([]);const [savingTools, setSavingTools] = useState(false);@@ -148,6 +149,10 @@ export default function PartnerConfigure({setEnabledTools(partner.enabled_tools ?? options.tools.map((tool) => tool.name),);+ setBuiltinTools(+ partner.builtin_tools ??+ options.builtin_tools.map((tool) => tool.name),+ );setMcpTools(partner.mcp_tools ?? options.mcp_tools.map((tool) => tool.name),);@@ -215,6 +220,7 @@ export default function PartnerConfigure({try {await updatePartner(partnerId, {enabled_tools: enabledTools,+ builtin_tools: builtinTools,mcp_tools: mcpTools,});onToast(t("Tools updated — applies from the next message"));@@ -439,8 +445,10 @@ export default function PartnerConfigure({<ToolPickeroptions={toolOptions}enabledTools={enabledTools}+ builtinTools={builtinTools}mcpTools={mcpTools}onChangeEnabledTools={setEnabledTools}+ onChangeBuiltinTools={setBuiltinTools}onChangeMcpTools={setMcpTools}/></Section>diff --git a/web/components/partners/ToolPicker.tsx b/web/components/partners/ToolPicker.tsxindex 2c677afd4..c6f604e6c 100644--- a/web/components/partners/ToolPicker.tsx+++ b/web/components/partners/ToolPicker.tsx@@ -48,14 +48,18 @@ function ToggleRow({export default function ToolPicker({options,enabledTools,+ builtinTools,mcpTools,onChangeEnabledTools,+ onChangeBuiltinTools,onChangeMcpTools,}: {options: ToolOptions | null;enabledTools: string[];+ builtinTools: string[];mcpTools: string[];onChangeEnabledTools: (next: string[]) => void;+ onChangeBuiltinTools: (next: string[]) => void;onChangeMcpTools: (next: string[]) => void;}) {const { t } = useTranslation();@@ -124,6 +128,54 @@ export default function ToolPicker({</div></div>+ {options.builtin_tools.length > 0 && (+ <div>+ <div className="mb-1.5 flex items-baseline justify-between">+ <h4 className="text-[13px] font-medium text-[var(--muted-foreground)]">+ {t("Built-in tools")}+ </h4>+ <div className="flex gap-2 text-[12px]">+ <button+ type="button"+ className="text-[var(--primary)] hover:underline"+ onClick={() =>+ onChangeBuiltinTools(+ options.builtin_tools.map((tl) => tl.name),+ )+ }+ >+ {t("All")}+ </button>+ <button+ type="button"+ className="text-[var(--muted-foreground)] hover:underline"+ onClick={() => onChangeBuiltinTools([])}+ >+ {t("None")}+ </button>+ </div>+ </div>+ <p className="mb-1.5 px-2 text-[11.5px] text-[var(--muted-foreground)]">+ {t(+ "Mounted automatically when the context calls for it — a knowledge base attached, memory available, the sandbox enabled. Deny any you don't want this partner to have.",+ )}+ </p>+ <div className="grid grid-cols-1 gap-0.5 sm:grid-cols-2">+ {options.builtin_tools.map((tool) => (+ <ToggleRow+ key={tool.name}+ name={tool.name}+ description={tool.description}+ checked={builtinTools.includes(tool.name)}+ onToggle={() =>+ toggle(builtinTools, tool.name, onChangeBuiltinTools)+ }+ />+ ))}+ </div>+ </div>+ )}+{options.mcp_tools.length > 0 && (<div><div className="mb-1.5 flex items-baseline justify-between">diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsxindex 65bb8c81c..dfccb8c3e 100644--- a/web/components/settings/SettingsContext.tsx+++ b/web/components/settings/SettingsContext.tsx@@ -128,12 +128,27 @@ export type EmbeddingCapabilities = {active_dim_source?: string;};+export type DiagnosticsResult = {+ state: "success" | "failed";+ message: string;+ profileId: string | null;+ modelId: string | null;+};++export type ServiceReadiness =+ | "not_configured"+ | "untested"+ | "passed"+ | "failed";+type SettingsPayload = {ui: UiSettings;catalog?: Catalog;providers?: Record<ServiceName, ProviderOption[]>;};+const DIAGNOSTICS_RESULTS_KEY = "deeptutor.settings.diagnosticsResults.v1";+// ─── Tour ──────────────────────────────────────────────────────────────────//// The tour now spans routes — each step names the sub-page it lives on so the@@ -275,6 +290,47 @@ export function getActiveModel();}+export function serviceConfigured(+ catalog: Catalog,+ serviceName: ServiceName,+): boolean {+ return serviceName === "search"+ ? Boolean(getActiveProfile(catalog, serviceName)?.provider)+ : Boolean(getActiveModel(catalog, serviceName)?.model);+}++export function currentDiagnosticsResult(+ catalog: Catalog,+ serviceName: ServiceName,+ diagnosticsResults: Partial<Record<ServiceName, DiagnosticsResult>>,+): DiagnosticsResult | null {+ const service = catalog.services[serviceName];+ const diagnostics = diagnosticsResults[serviceName];+ if (!diagnostics) return null;+ const profileId = service.active_profile_id ?? null;+ const modelId =+ serviceName === "search" ? null : (service.active_model_id ?? null);+ return diagnostics.profileId === profileId && diagnostics.modelId === modelId+ ? diagnostics+ : null;+}++export function serviceReadiness(+ catalog: Catalog,+ serviceName: ServiceName,+ diagnosticsResults: Partial<Record<ServiceName, DiagnosticsResult>>,+): ServiceReadiness {+ if (!serviceConfigured(catalog, serviceName)) return "not_configured";+ const diagnostics = currentDiagnosticsResult(+ catalog,+ serviceName,+ diagnosticsResults,+ );+ if (diagnostics?.state === "failed") return "failed";+ if (diagnostics?.state === "success") return "passed";+ return "untested";+}+export function servicePendingApply(catalog: Catalog,draft: Catalog,@@ -299,6 +355,20 @@ function nextModelName(return `${prefix}${index}`;}+function readStoredDiagnosticsResults(): Partial<+ Record<ServiceName, DiagnosticsResult>+> {+ if (typeof window === "undefined") return {};+ try {+ const parsed = JSON.parse(+ window.sessionStorage.getItem(DIAGNOSTICS_RESULTS_KEY) || "{}",+ ) as Partial<Record<ServiceName, DiagnosticsResult>>;+ return parsed && typeof parsed === "object" ? parsed : {};+ } catch {+ return {};+ }+}+// ─── Context ───────────────────────────────────────────────────────────────export interface SettingsExtension {@@ -366,6 +436,7 @@ type SettingsContextValue = {// Diagnosticslogs: string;testRunning: ServiceName | null;+ diagnosticsResults: Partial<Record<ServiceName, DiagnosticsResult>>;embeddingCapabilities: EmbeddingCapabilities | null;runDetailedTest: (service: ServiceName) => Promise<void>;@@ -421,6 +492,9 @@ export function SettingsProvider({ children }: { children: ReactNode }) {// literal here — older code did, then read it back via .startsWith.const [logs, setLogs] = useState<string>("");const [testRunning, setTestRunning] = useState<ServiceName | null>(null);+ const [diagnosticsResults, setDiagnosticsResults] = useState<+ Partial<Record<ServiceName, DiagnosticsResult>>+ >(() => readStoredDiagnosticsResults());const [llmContextDetection, setLlmContextDetection] =useState<LlmContextWindowDetection | null>(null);const [embeddingCapabilities, setEmbeddingCapabilities] =@@ -527,6 +601,17 @@ export function SettingsProvider({ children }: { children: ReactNode }) {return () => clearTimeout(timer);}, [toast]);+ useEffect(() => {+ try {+ window.sessionStorage.setItem(+ DIAGNOSTICS_RESULTS_KEY,+ JSON.stringify(diagnosticsResults),+ );+ } catch {+ // Session storage is an enhancement for cross-route feedback only.+ }+ }, [diagnosticsResults]);+// ── UI preferences ──────────────────────────────────────────────────────const persistUi = useCallback(async (@@ -874,10 +959,15 @@ export function SettingsProvider({ children }: { children: ReactNode }) {}setLogs(t("Preparing {{service}} diagnostics...", { service }) + "\n");setTestRunning(service);- const runProfileId =- service === "llm" ? draft.services.llm.active_profile_id : null;+ const target = draft.services[service];+ const runProfileId = target.active_profile_id ?? null;const runModelId =- service === "llm" ? (draft.services.llm.active_model_id ?? null) : null;+ service === "search" ? null : (target.active_model_id ?? null);+ setDiagnosticsResults((current) => {+ const next = { ...current };+ delete next[service];+ return next;+ });if (service === "llm") setLlmContextDetection(null);if (service === "embedding") setEmbeddingCapabilities(null);try {@@ -954,6 +1044,15 @@ export function SettingsProvider({ children }: { children: ReactNode }) {source.close();eventSourceRef.current = null;setTestRunning(null);+ setDiagnosticsResults((current) => ({+ ...current,+ [service]: {+ state: entry.type === "completed" ? "success" : "failed",+ message: entry.message,+ profileId: runProfileId,+ modelId: runModelId,+ },+ }));setToast(entry.message);}};@@ -965,6 +1064,15 @@ export function SettingsProvider({ children }: { children: ReactNode }) {(current) =>`${current}[failed] ${t("Diagnostics stream disconnected.")}\n`,);+ setDiagnosticsResults((current) => ({+ ...current,+ [service]: {+ state: "failed",+ message: t("Diagnostics stream disconnected."),+ profileId: runProfileId,+ modelId: runModelId,+ },+ }));setToast(t("Diagnostics stream disconnected"));};} catch (error) {@@ -973,6 +1081,15 @@ export function SettingsProvider({ children }: { children: ReactNode }) {? error.message: t("Could not start diagnostics.");setLogs((current) => `${current}[failed] ${message}\n`);+ setDiagnosticsResults((current) => ({+ ...current,+ [service]: {+ state: "failed",+ message,+ profileId: runProfileId,+ modelId: runModelId,+ },+ }));setToast(message);setTestRunning(null);}@@ -1070,6 +1187,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {registerExtension,logs,testRunning,+ diagnosticsResults,embeddingCapabilities,runDetailedTest,embeddingDefaultDim,@@ -1087,6 +1205,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {applying,catalog,catalogEditable,+ diagnosticsResults,draft,embeddingCapabilities,embeddingDefaultDim,diff --git a/web/components/settings/SettingsHub.tsx b/web/components/settings/SettingsHub.tsxindex 0b1115967..a24450b0b 100644--- a/web/components/settings/SettingsHub.tsx+++ b/web/components/settings/SettingsHub.tsx@@ -7,9 +7,9 @@ import { ChevronRight, Rocket, type LucideIcon } from "lucide-react";import { apiFetch, apiUrl } from "@/lib/api";import {- getActiveModel,- getActiveProfile,+ serviceReadiness,useSettings,+ type ServiceReadiness,} from "@/components/settings/SettingsContext";import SettingsStatusPanel from "@/components/settings/SettingsStatusPanel";import {@@ -37,24 +37,33 @@ export default function SettingsHub() {const zh = i18n.language?.toLowerCase().startsWith("zh");const tr = useCallback((l: Lang) => (zh ? l.zh : l.en), [zh]);- const { catalog, catalogEditable, startTour } = useSettings();+ const { catalog, catalogEditable, diagnosticsResults, startTour } =+ useSettings();// Model preview: how many of the model-service leaves are configured.const modelStats = useMemo(() => {const cat = SETTINGS_CATEGORIES.find((c) => c.key === "models");const services = (cat?.children ?? []).filter((l) => l.service);- if (catalogEditable !== true) return { total: services.length, done: -1 };- let done = 0;- for (const leaf of services) {- const svc = leaf.service!;- const ok =- svc === "search"- ? Boolean(getActiveProfile(catalog, svc)?.provider)- : Boolean(getActiveModel(catalog, svc)?.model);- if (ok) done += 1;+ if (catalogEditable !== true) {+ return {+ total: services.length,+ configured: -1,+ passed: 0,+ failed: 0,+ states: [] as ServiceReadiness[],+ };}- return { total: services.length, done };- }, [catalog, catalogEditable]);+ const states = services.map((leaf) =>+ serviceReadiness(catalog, leaf.service!, diagnosticsResults),+ );+ return {+ total: services.length,+ configured: states.filter((state) => state !== "not_configured").length,+ passed: states.filter((state) => state === "passed").length,+ failed: states.filter((state) => state === "failed").length,+ states,+ };+ }, [catalog, catalogEditable, diagnosticsResults]);// Network preview: a guarded peek at the effective browser API base. Fails// quietly (non-admins get 403) → the block falls back to its blurb.@@ -128,7 +137,13 @@ function CategoryBlock({}: {category: SettingsCategory;tr: (l: Lang) => string;- modelStats?: { total: number; done: number };+ modelStats?: {+ total: number;+ configured: number;+ passed: number;+ failed: number;+ states: ServiceReadiness[];+ };network?: NetworkPreview | null;}) {const Icon: LucideIcon = category.icon;@@ -176,12 +191,18 @@ function ModelPreview({blurb,tr,}: {- stats: { total: number; done: number };+ stats: {+ total: number;+ configured: number;+ passed: number;+ failed: number;+ states: ServiceReadiness[];+ };blurb: string;tr: (l: Lang) => string;}) {// Restricted deployments (no editable catalog) can't know — show the blurb.- if (stats.done < 0) {+ if (stats.configured < 0) {return (<p className="text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">{blurb}@@ -191,22 +212,36 @@ function ModelPreview({return (<div className="flex items-center gap-2.5"><div className="flex items-center gap-1">- {Array.from({ length: stats.total }).map((_, i) => (+ {stats.states.map((state, i) => (<spankey={i}className={`h-1.5 w-1.5 rounded-full ${- i < stats.done+ state === "passed"? "bg-emerald-500"- : "bg-[var(--muted-foreground)]/25"+ : state === "failed"+ ? "bg-red-500"+ : state === "untested"+ ? "bg-zinc-400 dark:bg-zinc-500"+ : "bg-zinc-300/60 dark:bg-zinc-700"}`}/>))}</div><span className="text-[12px] tabular-nums text-[var(--muted-foreground)]">- {tr({- zh: `${stats.done}/${stats.total} 已配置`,- en: `${stats.done}/${stats.total} configured`,- })}+ {stats.failed > 0+ ? tr({+ zh: `${stats.configured}/${stats.total} 已配置 · ${stats.failed} 个失败`,+ en: `${stats.configured}/${stats.total} configured · ${stats.failed} failed`,+ })+ : stats.passed > 0+ ? tr({+ zh: `${stats.configured}/${stats.total} 已配置 · ${stats.passed} 个通过`,+ en: `${stats.configured}/${stats.total} configured · ${stats.passed} passed`,+ })+ : tr({+ zh: `${stats.configured}/${stats.total} 已配置`,+ en: `${stats.configured}/${stats.total} configured`,+ })}</span></div>);diff --git a/web/components/settings/SettingsSectionGrid.tsx b/web/components/settings/SettingsSectionGrid.tsxindex b29c0f56a..378fa27fe 100644--- a/web/components/settings/SettingsSectionGrid.tsx+++ b/web/components/settings/SettingsSectionGrid.tsx@@ -7,8 +7,7 @@ import { ArrowUpRight } from "lucide-react";import { fetchAuthStatus } from "@/lib/auth";import {- getActiveModel,- getActiveProfile,+ serviceReadiness,useSettings,} from "@/components/settings/SettingsContext";import {@@ -32,7 +31,7 @@ export default function SettingsSectionGrid({const zh = i18n.language?.toLowerCase().startsWith("zh");const tr = useCallback((l: Lang) => (zh ? l.zh : l.en), [zh]);- const { catalog, catalogEditable } = useSettings();+ const { catalog, catalogEditable, diagnosticsResults } = useSettings();const category = SETTINGS_CATEGORIES.find((c) => c.key === categoryKey);@@ -49,21 +48,44 @@ export default function SettingsSectionGrid({}, []);const chipFor = useCallback(- (leaf: SettingsLeaf): { ok: boolean; label: Lang } | null => {+ (+ leaf: SettingsLeaf,+ ): { label: Lang; tone: "ok" | "bad" | "neutral"; dot: boolean } | null => {if (!leaf.service) return null;if (catalogEditable !== true) return null;- const configured =- leaf.service === "search"- ? Boolean(getActiveProfile(catalog, leaf.service)?.provider)- : Boolean(getActiveModel(catalog, leaf.service)?.model);+ const readiness = serviceReadiness(+ catalog,+ leaf.service,+ diagnosticsResults,+ );+ if (readiness === "failed") {+ return {+ tone: "bad",+ dot: true,+ label: { zh: "测试失败", en: "Test failed" },+ };+ }+ if (readiness === "passed") {+ return {+ tone: "ok",+ dot: true,+ label: { zh: "测试通过", en: "Test passed" },+ };+ }+ if (readiness === "untested") {+ return {+ tone: "neutral",+ dot: true,+ label: { zh: "已配置", en: "Configured" },+ };+ }return {- ok: configured,- label: configured- ? { zh: "已配置", en: "Configured" }- : { zh: "未配置", en: "Not set" },+ tone: "neutral",+ dot: false,+ label: { zh: "未配置", en: "Not set" },};},- [catalog, catalogEditable],+ [catalog, catalogEditable, diagnosticsResults],);if (!category?.children) return null;@@ -98,10 +120,11 @@ function LeafCard({tr,}: {leaf: SettingsLeaf;- chip: { ok: boolean; label: Lang } | null;+ chip: { label: Lang; tone: "ok" | "bad" | "neutral"; dot: boolean } | null;tr: (l: Lang) => string;}) {const Icon = leaf.icon;+ const tone = chip?.tone ?? "neutral";return (<Linkhref={leaf.href}@@ -121,19 +144,29 @@ function LeafCard({</h3>{chip && (<span- className={`inline-flex shrink-0 items-center gap-1 rounded-full px-1.5 py-0.5 text-[10.5px] font-medium ${- chip.ok- ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"- : "bg-[var(--muted)]/60 text-[var(--muted-foreground)]"+ className={`inline-flex shrink-0 items-center gap-1 text-[10.5px] font-medium ${+ chip.dot+ ? `rounded-full px-1.5 py-0.5 ${+ tone === "bad"+ ? "bg-red-500/10 text-red-600 dark:text-red-400"+ : tone === "ok"+ ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ : "bg-zinc-500/10 text-zinc-600 dark:text-zinc-300"+ }`+ : "text-[var(--muted-foreground)]"}`}>- <span- className={`h-1.5 w-1.5 rounded-full ${- chip.ok- ? "bg-emerald-500"- : "bg-[var(--muted-foreground)]/50"- }`}- />+ {chip.dot && (+ <span+ className={`h-1.5 w-1.5 rounded-full ${+ tone === "bad"+ ? "bg-red-500"+ : tone === "ok"+ ? "bg-emerald-500"+ : "bg-zinc-400 dark:bg-zinc-500"+ }`}+ />+ )}{tr(chip.label)}</span>)}diff --git a/web/components/settings/SubagentSettingsEditor.tsx b/web/components/settings/SubagentSettingsEditor.tsxnew file mode 100644index 000000000..928503812--- /dev/null+++ b/web/components/settings/SubagentSettingsEditor.tsx@@ -0,0 +1,532 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { CheckCircle2, Loader2, RefreshCw, XCircle } from "lucide-react";+import { useTranslation } from "react-i18next";++import {+ SettingRow,+ SettingSection,+ SettingsPageHeader,+ selectClass,+ inputClass,+} from "@/components/settings/shared";+import { Toggle } from "@/components/settings/Toggle";+import { agentGlyph } from "@/components/agents/agent-icons";+import {+ getBackendOptions,+ getSubagentSettings,+ syncBackendOptions,+ updateSubagentSettings,+ type SubagentBackendConfig,+ type SubagentBackendOptions,+} from "@/lib/subagents-api";++type Lang = { zh: string; en: string };++/** The CLI default sentinel — empty model/effort means "let the CLI decide". */+const CUSTOM = "__custom__";++// Defaults mirror BackendConfig in deeptutor/services/subagent/config.py so the+// form shows the same starting state the backend would synthesize.+const DEFAULTS: Required<+ Pick<+ SubagentBackendConfig,+ | "enabled"+ | "model"+ | "effort"+ | "system_prompt"+ | "permission_mode"+ | "sandbox"+ | "approval"+ | "network_access"+ | "ephemeral"+ | "forward_images"+ >+> = {+ enabled: true,+ model: "",+ effort: "",+ system_prompt: "",+ permission_mode: "bypassPermissions",+ sandbox: "workspace-write",+ approval: "never",+ network_access: false,+ ephemeral: false,+ forward_images: false,+};++const PERMISSION_MODES: { value: string; label: Lang }[] = [+ { value: "bypassPermissions", label: { zh: "绕过权限 · 全自主(推荐)", en: "Bypass permissions · autonomous (recommended)" } },+ { value: "acceptEdits", label: { zh: "自动接受编辑", en: "Accept edits automatically" } },+ { value: "default", label: { zh: "默认 · 可能等待确认", en: "Default · may wait for prompts" } },+ { value: "plan", label: { zh: "计划模式 · 只读", en: "Plan mode · read-only" } },+];++const SANDBOXES: { value: string; label: Lang }[] = [+ { value: "read-only", label: { zh: "只读", en: "Read-only" } },+ { value: "workspace-write", label: { zh: "工作目录可写(推荐)", en: "Workspace write (recommended)" } },+ { value: "danger-full-access", label: { zh: "完全访问", en: "Full access" } },+ { value: "bypass", label: { zh: "绕过沙箱与审批", en: "Bypass sandbox & approvals" } },+];++const APPROVALS: { value: string; label: Lang }[] = [+ { value: "never", label: { zh: "从不询问(推荐)", en: "Never ask (recommended)" } },+ { value: "on-failure", label: { zh: "失败时询问", en: "On failure" } },+ { value: "on-request", label: { zh: "按需询问", en: "On request" } },+ { value: "untrusted", label: { zh: "不可信命令时询问", en: "Untrusted commands" } },+];++export function SubagentSettingsEditor({ kind }: { kind: string }) {+ const { i18n } = useTranslation();+ const zh = i18n.language?.toLowerCase().startsWith("zh");+ const tr = useCallback((l: Lang) => (zh ? l.zh : l.en), [zh]);++ const [options, setOptions] = useState<SubagentBackendOptions | null>(null);+ const [config, setConfig] = useState<SubagentBackendConfig>({ ...DEFAULTS });+ const [customModel, setCustomModel] = useState(false);+ const [loading, setLoading] = useState(true);+ const [syncing, setSyncing] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const Glyph = agentGlyph(kind);++ const fetchOptions = useCallback(async () => {+ const all = await getBackendOptions();+ return all.find((o) => o.kind === kind) ?? null;+ }, [kind]);++ const load = useCallback(async () => {+ setError(null);+ try {+ const [opts, settings] = await Promise.all([+ fetchOptions(),+ getSubagentSettings(),+ ]);+ setOptions(opts);+ const stored = settings.backends?.[kind] ?? {};+ setConfig({ ...DEFAULTS, ...stored });+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setLoading(false);+ }+ }, [fetchOptions, kind]);++ useEffect(() => {+ void load();+ }, [load]);++ const sync = useCallback(async () => {+ setSyncing(true);+ setError(null);+ try {+ // Actively re-pull this backend's catalog (CC scrapes /model live).+ setOptions(await syncBackendOptions(kind));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSyncing(false);+ }+ }, [kind]);++ // Persist a patch for THIS backend only; the API merges per field, so we send+ // just what changed and never clobber the other backend or unsent fields.+ const save = useCallback(+ async (patch: Partial<SubagentBackendConfig>) => {+ setConfig((prev) => ({ ...prev, ...patch }));+ setBusy(true);+ setError(null);+ try {+ await updateSubagentSettings({ backends: { [kind]: patch } });+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ },+ [kind],+ );++ const isCodex = kind === "codex";+ const knownSlugs = useMemo(+ () => new Set((options?.models ?? []).map((m) => m.slug)),+ [options],+ );+ const showCustomModel =+ customModel || (config.model !== "" && !knownSlugs.has(config.model ?? ""));++ // Effort choices: per-model for Codex (its cache carries each model's levels),+ // global for Claude Code. Falls back to the backend's union when the chosen+ // model isn't a known slug (custom / default).+ const effortChoices = useMemo(() => {+ if (isCodex && config.model && knownSlugs.has(config.model)) {+ const m = options?.models.find((x) => x.slug === config.model);+ if (m?.efforts?.length) return m.efforts;+ }+ return options?.efforts ?? [];+ }, [isCodex, config.model, knownSlugs, options]);++ const onModelSelect = useCallback(+ (value: string) => {+ if (value === CUSTOM) {+ setCustomModel(true);+ return;+ }+ setCustomModel(false);+ // Reset an effort the newly chosen model doesn't support (Codex).+ const m = options?.models.find((x) => x.slug === value);+ const patch: Partial<SubagentBackendConfig> = { model: value };+ if (+ isCodex &&+ config.effort &&+ m?.efforts?.length &&+ !m.efforts.includes(config.effort)+ ) {+ patch.effort = "";+ }+ void save(patch);+ },+ [options, isCodex, config.effort, save],+ );++ const displayName = options?.display_name ?? (isCodex ? "Codex" : "Claude Code");++ return (+ <div>+ <SettingsPageHeader+ title={displayName}+ description={tr({+ zh: `DeepTutor 通过 consult_subagent 调用本机 ${displayName} 时使用的模型、推理强度与运行参数。设置后即覆盖 CLI 的默认值;留空表示沿用 CLI 默认。`,+ en: `Model, reasoning effort, and run parameters DeepTutor drives the local ${displayName} with when consulting it. These override the CLI defaults; leave blank to keep the CLI's own default.`,+ })}+ />++ {loading && (+ <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ {tr({ zh: "加载中…", en: "Loading…" })}+ </div>+ )}++ {!loading && error && (+ <div className="mb-5 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-[13px] text-red-600 dark:text-red-300">+ {error}+ </div>+ )}++ {!loading && options && (+ <>+ {/* Availability + sync. The model/effort lists change over time, so+ the user can re-pull them on demand. */}+ <SettingSection+ title={tr({ zh: "连接与同步", en: "Connection & sync" })}+ description={tr({+ zh: "供应商会不定期增删模型与推理档位——随时点同步即可重新拉取最新列表。",+ en: "Vendors add and retire models and effort levels over time — sync any time to re-pull the latest lists.",+ })}+ >+ <SettingRow+ title={tr({ zh: "本机状态", en: "On this machine" })}+ description={+ options.available+ ? options.version+ : options.detail ||+ tr({ zh: "未在 PATH 上找到该 CLI。", en: "CLI not found on PATH." })+ }+ control={+ <span+ className={`inline-flex items-center gap-1.5 text-[12px] ${+ options.available+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-amber-600 dark:text-amber-400"+ }`}+ >+ {Glyph ? <Glyph size={15} /> : null}+ {options.available ? (+ <CheckCircle2 className="h-3.5 w-3.5" />+ ) : (+ <XCircle className="h-3.5 w-3.5" />+ )}+ {options.available+ ? tr({ zh: "已安装", en: "Installed" })+ : tr({ zh: "未检测到", en: "Not detected" })}+ </span>+ }+ />+ <SettingRow+ title={tr({ zh: "模型列表", en: "Model list" })}+ description={+ options.synced_at+ ? tr({+ zh: `上次同步:${formatTs(options.synced_at, zh)}`,+ en: `Last synced: ${formatTs(options.synced_at, zh)}`,+ })+ : tr({+ zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",+ en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",+ })+ }+ control={+ <button+ type="button"+ disabled={syncing}+ onClick={() => void sync()}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/40 disabled:opacity-60"+ >+ <RefreshCw+ className={`h-3.5 w-3.5 ${syncing ? "animate-spin" : ""}`}+ />+ {tr({ zh: "同步", en: "Sync" })}+ </button>+ }+ />+ </SettingSection>++ <SettingSection+ title={tr({ zh: "模型", en: "Model" })}+ description={tr({+ zh: "DeepTutor 调用该智能体时使用的模型与推理强度。",+ en: "The model and reasoning effort DeepTutor consults this agent with.",+ })}+ >+ <SettingRow+ title={tr({ zh: "启用", en: "Enabled" })}+ description={tr({+ zh: "关闭后,DeepTutor 不会在对话中调用该智能体。",+ en: "When off, DeepTutor won't consult this agent in chat.",+ })}+ control={+ <Toggle+ checked={config.enabled !== false}+ disabled={busy}+ onChange={(v) => void save({ enabled: v })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "模型", en: "Model" })}+ control={+ <div className="flex w-[260px] flex-col items-end gap-2">+ <select+ className={selectClass}+ disabled={busy}+ value={showCustomModel ? CUSTOM : (config.model ?? "")}+ onChange={(e) => onModelSelect(e.target.value)}+ >+ <option value="">+ {tr({ zh: "CLI 默认", en: "CLI default" })}+ </option>+ {options.models.map((m) => (+ <option key={m.slug} value={m.slug}>+ {m.display_name}+ </option>+ ))}+ {options.allow_custom_model && (+ <option value={CUSTOM}>+ {tr({ zh: "自定义…", en: "Custom…" })}+ </option>+ )}+ </select>+ {showCustomModel && (+ <input+ className={inputClass}+ disabled={busy}+ placeholder={tr({+ zh: "输入模型名",+ en: "Enter a model name",+ })}+ value={config.model ?? ""}+ onChange={(e) =>+ setConfig((p) => ({ ...p, model: e.target.value }))+ }+ onBlur={(e) => void save({ model: e.target.value.trim() })}+ />+ )}+ </div>+ }+ />+ <SettingRow+ title={tr({ zh: "推理强度", en: "Reasoning effort" })}+ control={+ <select+ className={`${selectClass} w-[260px]`}+ disabled={busy || effortChoices.length === 0}+ value={config.effort ?? ""}+ onChange={(e) => void save({ effort: e.target.value })}+ >+ <option value="">+ {tr({ zh: "CLI 默认", en: "CLI default" })}+ </option>+ {effortChoices.map((eff) => (+ <option key={eff} value={eff}>+ {eff}+ </option>+ ))}+ </select>+ }+ />+ </SettingSection>++ {!isCodex && (+ <SettingSection+ title={tr({ zh: "系统提示", en: "System prompt" })}+ description={tr({+ zh: "追加到该智能体的系统提示(--append-system-prompt)。留空则使用 DeepTutor 的默认委派提示。",+ en: "Appended to the agent's system prompt (--append-system-prompt). Blank uses DeepTutor's default delegate instruction.",+ })}+ >+ <div className="py-4">+ <textarea+ className={`${inputClass} min-h-[96px] resize-y leading-relaxed`}+ disabled={busy}+ placeholder={tr({+ zh: "(留空使用默认委派提示)",+ en: "(blank uses the default delegate instruction)",+ })}+ value={config.system_prompt ?? ""}+ onChange={(e) =>+ setConfig((p) => ({ ...p, system_prompt: e.target.value }))+ }+ onBlur={(e) => void save({ system_prompt: e.target.value })}+ />+ </div>+ </SettingSection>+ )}++ <SettingSection+ title={tr({ zh: "运行参数", en: "Run parameters" })}+ description={tr({+ zh: "DeepTutor 无人值守地驱动该智能体——默认值确保它不会卡在等待确认上。",+ en: "DeepTutor drives the agent unattended — the defaults ensure it never stalls waiting for an approval prompt.",+ })}+ >+ {!isCodex && (+ <SettingRow+ title={tr({ zh: "权限模式", en: "Permission mode" })}+ description={tr({+ zh: "非「绕过权限」的模式可能让无人值守的运行卡住等待确认。",+ en: "Modes other than bypass may stall an unattended run waiting for a prompt.",+ })}+ control={+ <select+ className={`${selectClass} w-[260px]`}+ disabled={busy}+ value={config.permission_mode ?? DEFAULTS.permission_mode}+ onChange={(e) =>+ void save({ permission_mode: e.target.value })+ }+ >+ {PERMISSION_MODES.map((o) => (+ <option key={o.value} value={o.value}>+ {tr(o.label)}+ </option>+ ))}+ </select>+ }+ />+ )}++ {isCodex && (+ <>+ <SettingRow+ title={tr({ zh: "沙箱", en: "Sandbox" })}+ control={+ <select+ className={`${selectClass} w-[260px]`}+ disabled={busy}+ value={config.sandbox ?? DEFAULTS.sandbox}+ onChange={(e) => void save({ sandbox: e.target.value })}+ >+ {SANDBOXES.map((o) => (+ <option key={o.value} value={o.value}>+ {tr(o.label)}+ </option>+ ))}+ </select>+ }+ />+ <SettingRow+ title={tr({ zh: "审批策略", en: "Approval policy" })}+ description={tr({+ zh: "非「从不询问」可能让无人值守的运行卡住。",+ en: "Anything but never may stall an unattended run.",+ })}+ control={+ <select+ className={`${selectClass} w-[260px]`}+ disabled={busy}+ value={config.approval ?? DEFAULTS.approval}+ onChange={(e) => void save({ approval: e.target.value })}+ >+ {APPROVALS.map((o) => (+ <option key={o.value} value={o.value}>+ {tr(o.label)}+ </option>+ ))}+ </select>+ }+ />+ <SettingRow+ title={tr({ zh: "命令联网", en: "Command network access" })}+ description={tr({+ zh: "允许模型运行的 shell 命令访问网络(工作目录可写模式默认离线)。内置 web search 不受影响。",+ en: "Let the model's shell commands reach the network (workspace-write is offline by default). The built-in web search is unaffected.",+ })}+ control={+ <Toggle+ checked={Boolean(config.network_access)}+ disabled={busy}+ onChange={(v) => void save({ network_access: v })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "临时会话", en: "Ephemeral session" })}+ description={tr({+ zh: "不在 ~/.codex/sessions 下持久化本次会话。",+ en: "Don't persist the session under ~/.codex/sessions.",+ })}+ control={+ <Toggle+ checked={Boolean(config.ephemeral)}+ disabled={busy}+ onChange={(v) => void save({ ephemeral: v })}+ />+ }+ />+ </>+ )}++ <SettingRow+ title={tr({ zh: "转发图片", en: "Forward images" })}+ description={tr({+ zh: "允许 DeepTutor 把本轮对话中的图片附件转发给该智能体。",+ en: "Let DeepTutor forward image attachments from the chat turn to this agent.",+ })}+ control={+ <Toggle+ checked={Boolean(config.forward_images)}+ disabled={busy}+ onChange={(v) => void save({ forward_images: v })}+ />+ }+ />+ </SettingSection>+ </>+ )}+ </div>+ );+}++function formatTs(value: string, zh: boolean): string {+ const parsed = new Date(value);+ if (Number.isNaN(parsed.getTime())) return value;+ return parsed.toLocaleString(zh ? "zh-CN" : "en-US", {+ dateStyle: "medium",+ timeStyle: "short",+ });+}++export default SubagentSettingsEditor;diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsxindex b13e8adec..d3ba45f1a 100644--- a/web/components/sidebar/SidebarShell.tsx+++ b/web/components/sidebar/SidebarShell.tsx@@ -8,6 +8,7 @@ import { useAppShell } from "@/context/AppShellContext";import {BookOpen,BookText,+ Bot,Brain,ChevronDown,Github,@@ -54,6 +55,16 @@ const PRIMARY_NAV: NavEntry[] = [tooltipKey: "Partners tooltip",requires: "llm",},+ {+ // My Agents is its own top-level feature (pulled out of the Learning+ // Space): connect a live local Claude Code / Codex to consult in chat,+ // and manage imported agent conversations. Ungated — managing connections+ // and imports needs no per-user model grant.+ href: "/agents",+ label: "My Agents",+ icon: Bot,+ tooltipKey: "Agents tooltip",+ },{href: "/co-writer",label: "Co-Writer",diff --git a/web/components/space/EduHubImportModal.tsx b/web/components/space/EduHubImportModal.tsxindex 5f831a579..ef3a4358d 100644--- a/web/components/space/EduHubImportModal.tsx+++ b/web/components/space/EduHubImportModal.tsx@@ -1,105 +1,169 @@"use client";import { useCallback, useEffect, useMemo, useState } from "react";+import dynamic from "next/dynamic";import { useTranslation } from "react-i18next";-import { AlertTriangle, CheckCircle2, Loader2, Store, X } from "lucide-react";--import { installSkillFromHub } from "@/lib/skills-api";--// The live EduHub skill registry. Overridable for local dev (point both this-// and the backend `eduhub` hub at the same local server to test end-to-end).-const EDUHUB_BASE = (- process.env.NEXT_PUBLIC_EDUHUB_URL || "https://eduhub.deeptutor.info"-).replace(/\/+$/, "");--interface InstallMessage {- source: "eduhub";- type: "install";- slug: string;- version?: string;- name?: string;-}+import {+ AlertTriangle,+ ArrowLeft,+ CheckCircle2,+ Download,+ ExternalLink,+ Loader2,+ RefreshCw,+ Search,+ Star,+ Store,+ Wand2,+ X,+} from "lucide-react";-function isInstallMessage(data: unknown): data is InstallMessage {- if (typeof data !== "object" || data === null) return false;- const d = data as Record<string, unknown>;- return (- d.source === "eduhub" &&- d.type === "install" &&- typeof d.slug === "string" &&- d.slug.length > 0- );+import {+ fetchHubCatalog,+ fetchHubSkillDetail,+ installSkillFromHub,+ type HubSkillDetail,+ type HubSkillListing,+} from "@/lib/skills-api";++// Where the EduHub site lives, for "view on EduHub" links. The catalog+// response carries the authoritative origin; this only backstops a failed load.+const EDUHUB_FALLBACK = "https://eduhub.deeptutor.info";++// Lazy-load the markdown renderer so the heavier deps only ship when a user+// opens a skill's detail view (matches the Skills viewer in SkillsSection).+const SkillMarkdown = dynamic(+ () => import("@/components/common/SimpleMarkdownRenderer"),+ { ssr: false },+);++/** Drop the YAML frontmatter block so the detail view shows just the playbook. */+function stripFrontmatter(md: string): string {+ const match = md.match(/^---\s*\n[\s\S]*?\n---\s*\n?/);+ return match ? md.slice(match[0].length) : md;}-type Status =- | { kind: "idle" }- | { kind: "installing"; name: string }- | { kind: "done"; name: string; version: string; verdict: string }- | { kind: "error"; name: string; message: string };+type InstallState =+ | { kind: "installing" }+ | { kind: "done"; verdict: string }+ | { kind: "error"; message: string };export default function EduHubImportModal({onClose,onInstalled,+ installedNames,}: {onClose: () => void;onInstalled: () => void;+ /** Names of skills already installed locally — shown as "已导入". */+ installedNames?: Set<string>;}) {const { i18n } = useTranslation();const zh = i18n.language?.toLowerCase().startsWith("zh");const tr = useCallback((cn: string, en: string) => (zh ? cn : en), [zh]);- const [status, setStatus] = useState<Status>({ kind: "idle" });+ const [skills, setSkills] = useState<HubSkillListing[] | null>(null);+ const [webUrl, setWebUrl] = useState<string>(EDUHUB_FALLBACK);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [query, setQuery] = useState("");++ const [selected, setSelected] = useState<HubSkillListing | null>(null);+ const [detail, setDetail] = useState<HubSkillDetail | null>(null);+ const [detailLoading, setDetailLoading] = useState(false);+ const [detailError, setDetailError] = useState<string | null>(null);- const origin = useMemo(() => {+ const [installState, setInstallState] = useState<+ Record<string, InstallState>+ >({});+ // Slugs imported during this session, merged with the names passed from the+ // Skills list, so freshly-downloaded skills flip to "已导入" without a reload.+ const [installedLocal, setInstalledLocal] = useState<Set<string>>(+ () => new Set(installedNames ?? []),+ );++ const loadCatalog = useCallback(async () => {+ setLoading(true);+ setError(null);try {- return new URL(EDUHUB_BASE).origin;- } catch {- return "";+ const catalog = await fetchHubCatalog({ limit: 100 });+ setSkills(catalog.skills);+ if (catalog.webUrl) setWebUrl(catalog.webUrl);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setLoading(false);}}, []);- const iframeSrc = `${EDUHUB_BASE}/skills?embed=deeptutor`;-- // Install requests arrive as postMessages from the embedded EduHub page.useEffect(() => {- async function onMessage(event: MessageEvent) {- if (origin && event.origin !== origin) return;- if (!isInstallMessage(event.data)) return;- const { slug, version, name } = event.data;- const label = name || slug;- // Build the ref ourselves (hardcoded `eduhub:` hub) so a spoofed message- // can never redirect the install to a different registry.- const ref = `eduhub:${slug}${version ? `@${version}` : ""}`;- setStatus({ kind: "installing", name: label });- try {- const result = await installSkillFromHub(ref);- setStatus({- kind: "done",- name: result.name || label,- version: result.version,- verdict: result.verdict.status,- });- onInstalled();- } catch (err) {- setStatus({- kind: "error",- name: label,- message: err instanceof Error ? err.message : String(err),- });- }- }- window.addEventListener("message", onMessage);- return () => window.removeEventListener("message", onMessage);- }, [origin, onInstalled]);+ void loadCatalog();+ }, [loadCatalog]);- // Escape closes.+ // Escape closes (the detail view first, then the modal).useEffect(() => {function onKey(e: KeyboardEvent) {- if (e.key === "Escape") onClose();+ if (e.key !== "Escape") return;+ if (selected) setSelected(null);+ else onClose();}window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);- }, [onClose]);+ }, [onClose, selected]);++ const filtered = useMemo(() => {+ if (!skills) return [];+ const q = query.trim().toLowerCase();+ if (!q) return skills;+ return skills.filter(+ (s) =>+ s.name.toLowerCase().includes(q) ||+ s.slug.toLowerCase().includes(q) ||+ s.summary.toLowerCase().includes(q),+ );+ }, [skills, query]);++ const openDetail = useCallback(async (skill: HubSkillListing) => {+ setSelected(skill);+ setDetail(null);+ setDetailError(null);+ setDetailLoading(true);+ try {+ setDetail(await fetchHubSkillDetail(skill.slug));+ } catch (err) {+ setDetailError(err instanceof Error ? err.message : String(err));+ } finally {+ setDetailLoading(false);+ }+ }, []);++ const install = useCallback(+ async (slug: string, opts?: { force?: boolean }) => {+ setInstallState((s) => ({ ...s, [slug]: { kind: "installing" } }));+ try {+ // The `eduhub:` hub is hardcoded so the install can never be redirected+ // to another registry, and the slug comes from our own proxied catalog.+ const result = await installSkillFromHub(`eduhub:${slug}`, {+ force: opts?.force,+ });+ setInstallState((s) => ({+ ...s,+ [slug]: { kind: "done", verdict: result.verdict.status },+ }));+ setInstalledLocal((prev) => new Set(prev).add(slug));+ onInstalled();+ } catch (err) {+ setInstallState((s) => ({+ ...s,+ [slug]: {+ kind: "error",+ message: err instanceof Error ? err.message : String(err),+ },+ }));+ }+ },+ [onInstalled],+ );return (<div@@ -112,81 +176,408 @@ export default function EduHubImportModal({className="flex h-[88vh] w-full max-w-5xl flex-col overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)] shadow-2xl"onClick={(e) => e.stopPropagation()}>- <div className="flex items-center justify-between border-b border-[var(--border)] px-5 py-3">- <div className="flex items-center gap-2">- <Store size={15} className="text-[var(--muted-foreground)]" />- <h3 className="text-[14px] font-semibold text-[var(--foreground)]">+ {/* Header */}+ <div className="flex items-center justify-between gap-3 border-b border-[var(--border)] px-5 py-3">+ <div className="flex min-w-0 items-center gap-2">+ <Store+ size={15}+ className="shrink-0 text-[var(--muted-foreground)]"+ />+ <h3 className="truncate text-[14px] font-semibold text-[var(--foreground)]">{tr("从 EduHub 导入技能", "Import skills from EduHub")}</h3></div>- <button- onClick={onClose}- aria-label={tr("关闭", "Close")}- className="rounded-md p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <X size={16} />- </button>+ <div className="flex shrink-0 items-center gap-1">+ <a+ href={`${webUrl}/skills`}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ExternalLink size={13} />+ {tr("在 EduHub 打开", "Open EduHub")}+ </a>+ <button+ onClick={onClose}+ aria-label={tr("关闭", "Close")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <X size={16} />+ </button>+ </div></div>- <StatusBanner status={status} tr={tr} />-- <iframe- src={iframeSrc}- title="EduHub"- className="min-h-0 flex-1 border-0 bg-white"- />+ {selected ? (+ <DetailView+ skill={selected}+ detail={detail}+ loading={detailLoading}+ error={detailError}+ installState={installState[selected.slug]}+ installed={installedLocal.has(selected.slug)}+ webUrl={webUrl}+ tr={tr}+ onBack={() => setSelected(null)}+ onInstall={install}+ />+ ) : (+ <ListView+ skills={filtered}+ total={skills?.length ?? 0}+ loading={loading}+ error={error}+ query={query}+ installState={installState}+ installedLocal={installedLocal}+ tr={tr}+ onQueryChange={setQuery}+ onRetry={loadCatalog}+ onOpen={openDetail}+ onInstall={install}+ />+ )}</div></div>);}-function StatusBanner({- status,+// ── list view ──────────────────────────────────────────────────────────────++function ListView({+ skills,+ total,+ loading,+ error,+ query,+ installState,+ installedLocal,tr,+ onQueryChange,+ onRetry,+ onOpen,+ onInstall,}: {- status: Status;+ skills: HubSkillListing[];+ total: number;+ loading: boolean;+ error: string | null;+ query: string;+ installState: Record<string, InstallState>;+ installedLocal: Set<string>;tr: (cn: string, en: string) => string;+ onQueryChange: (q: string) => void;+ onRetry: () => void;+ onOpen: (skill: HubSkillListing) => void;+ onInstall: (slug: string, opts?: { force?: boolean }) => void;}) {- if (status.kind === "idle") return null;+ return (+ <>+ {/* Search */}+ <div className="border-b border-[var(--border)] px-5 py-3">+ <div className="relative">+ <Search+ size={14}+ className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]"+ />+ <input+ value={query}+ onChange={(e) => onQueryChange(e.target.value)}+ placeholder={tr("搜索技能名称或描述…", "Search skills…")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] py-2 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)]/70 focus:border-[var(--foreground)]/30"+ />+ </div>+ </div>- if (status.kind === "installing") {- return (- <div className="flex items-center gap-2 border-b border-[var(--border)] bg-[var(--muted)]/40 px-5 py-2.5 text-[12.5px] text-[var(--foreground)]">- <Loader2- size={14}- className="animate-spin text-[var(--muted-foreground)]"- />- {tr(`正在导入 ${status.name}…`, `Importing ${status.name}…`)}+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">+ {loading ? (+ <div className="flex items-center justify-center py-16 text-[var(--muted-foreground)]">+ <Loader2 size={20} className="animate-spin" />+ </div>+ ) : error ? (+ <div className="mx-auto max-w-md rounded-lg border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-center text-[12.5px] text-amber-700 dark:text-amber-400">+ <AlertTriangle size={16} className="mx-auto mb-1.5" />+ <p>{tr("无法连接 EduHub。", "Couldn't reach EduHub.")}</p>+ <p className="mt-0.5 break-words text-[11.5px] opacity-80">+ {error}+ </p>+ <button+ onClick={onRetry}+ className="mt-2.5 inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-3 py-1 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <RefreshCw size={12} />+ {tr("重试", "Retry")}+ </button>+ </div>+ ) : skills.length === 0 ? (+ <div className="py-16 text-center text-[13px] text-[var(--muted-foreground)]">+ {total === 0+ ? tr("EduHub 上暂时还没有技能。", "No skills on EduHub yet.")+ : tr("没有匹配的技能。", "No skills match your search.")}+ </div>+ ) : (+ <ul className="grid gap-3 sm:grid-cols-2">+ {skills.map((skill) => (+ <SkillCard+ key={skill.slug}+ skill={skill}+ state={installState[skill.slug]}+ installed={installedLocal.has(skill.slug)}+ tr={tr}+ onOpen={() => onOpen(skill)}+ onInstall={onInstall}+ />+ ))}+ </ul>+ )}</div>- );- }+ </>+ );+}- if (status.kind === "done") {- return (- <div className="flex items-center gap-2 border-b border-emerald-500/20 bg-emerald-500/10 px-5 py-2.5 text-[12.5px] text-emerald-700 dark:text-emerald-400">- <CheckCircle2 size={14} className="shrink-0" />- <span>- {tr(- `已导入 ${status.name}${status.version ? `(${status.version})` : ""}`,- `Imported ${status.name}${status.version ? ` (${status.version})` : ""}`,- )}- {status.verdict === "unknown" &&- tr(- " · 此包未经验证,使用前请自行确认。",- " · unverified package — review before use.",- )}+function SkillCard({+ skill,+ state,+ installed,+ tr,+ onOpen,+ onInstall,+}: {+ skill: HubSkillListing;+ state?: InstallState;+ installed: boolean;+ tr: (cn: string, en: string) => string;+ onOpen: () => void;+ onInstall: (slug: string, opts?: { force?: boolean }) => void;+}) {+ return (+ <li+ role="button"+ tabIndex={0}+ onClick={onOpen}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onOpen();+ }+ }}+ title={tr("查看详情", "View details")}+ className="group relative flex cursor-pointer flex-col rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm transition-all hover:border-[var(--foreground)]/30 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"+ >+ <div className="flex items-start gap-2.5">+ <span className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-[var(--border)]/60 bg-[var(--background)] text-[var(--muted-foreground)]">+ <Wand2 size={13} strokeWidth={1.6} /></span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="truncate text-[14px] font-semibold tracking-tight text-[var(--foreground)]">+ {skill.name}+ </span>+ {installed ? (+ <span className="inline-flex shrink-0 items-center gap-1 rounded-md bg-emerald-500/12 px-1.5 py-0.5 text-[10px] font-medium text-emerald-600 dark:text-emerald-400">+ <CheckCircle2 size={9} />+ {tr("已导入", "Installed")}+ </span>+ ) : null}+ </div>+ {skill.summary ? (+ <p className="mt-0.5 line-clamp-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {skill.summary}+ </p>+ ) : (+ <p className="mt-0.5 text-[12px] italic text-[var(--muted-foreground)]/60">+ {tr("暂无描述。", "No description.")}+ </p>+ )}+ </div>+ </div>++ <div className="mt-3 flex items-center justify-between gap-2 pt-2">+ <div className="flex min-w-0 items-center gap-2.5 text-[11px] text-[var(--muted-foreground)]">+ <span className="inline-flex items-center gap-1">+ <Download size={11} />+ {skill.downloads}+ </span>+ <span className="inline-flex items-center gap-1">+ <Star size={11} />+ {skill.stars}+ </span>+ {skill.owner ? (+ <span className="truncate">· {skill.owner}</span>+ ) : null}+ </div>+ <InstallButton+ state={state}+ installed={installed}+ tr={tr}+ onClick={(force) => onInstall(skill.slug, { force })}+ />+ </div>++ {state?.kind === "error" ? (+ <p className="mt-2 line-clamp-2 text-[11px] text-amber-700 dark:text-amber-400">+ {state.message}+ </p>+ ) : null}+ </li>+ );+}++// ── detail view ──────────────────────────────────────────────────────────────++function DetailView({+ skill,+ detail,+ loading,+ error,+ installState,+ installed,+ webUrl,+ tr,+ onBack,+ onInstall,+}: {+ skill: HubSkillListing;+ detail: HubSkillDetail | null;+ loading: boolean;+ error: string | null;+ installState?: InstallState;+ installed: boolean;+ webUrl: string;+ tr: (cn: string, en: string) => string;+ onBack: () => void;+ onInstall: (slug: string, opts?: { force?: boolean }) => void;+}) {+ const version = detail?.version || skill.version;+ return (+ <>+ <div className="flex items-center justify-between gap-3 border-b border-[var(--border)] px-5 py-2.5">+ <button+ onClick={onBack}+ className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[12.5px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ArrowLeft size={13} />+ {tr("返回", "Back")}+ </button>+ <div className="flex items-center gap-1.5">+ <a+ href={detail?.webUrl || `${webUrl}/skills/${skill.slug}`}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <ExternalLink size={13} />+ {tr("在 EduHub 查看", "View on EduHub")}+ </a>+ <InstallButton+ state={installState}+ installed={installed}+ tr={tr}+ onClick={(force) => onInstall(skill.slug, { force })}+ />+ </div>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">+ <div className="mb-1 flex items-center gap-2">+ <h2 className="text-[18px] font-semibold tracking-tight text-[var(--foreground)]">+ {skill.name}+ </h2>+ {version ? (+ <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">+ v{version}+ </span>+ ) : null}+ </div>+ <div className="mb-4 flex flex-wrap items-center gap-3 text-[11.5px] text-[var(--muted-foreground)]">+ <span className="inline-flex items-center gap-1">+ <Download size={12} />+ {skill.downloads} {tr("次下载", "downloads")}+ </span>+ <span className="inline-flex items-center gap-1">+ <Star size={12} />+ {skill.stars}+ </span>+ {skill.owner ? <span>· {skill.owner}</span> : null}+ </div>++ {detail?.tags && detail.tags.length > 0 ? (+ <div className="mb-4 flex flex-wrap gap-1.5">+ {detail.tags.map((tag) => (+ <span+ key={tag}+ className="inline-flex items-center rounded-full border border-[var(--border)]/60 bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]"+ >+ {tag}+ </span>+ ))}+ </div>+ ) : null}++ {installState?.kind === "error" ? (+ <div className="mb-4 rounded-lg border border-amber-500/20 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-700 dark:text-amber-400">+ {tr("导入失败:", "Import failed: ")}+ {installState.message}+ </div>+ ) : null}++ {loading ? (+ <div className="flex items-center justify-center py-12 text-[var(--muted-foreground)]">+ <Loader2 size={18} className="animate-spin" />+ </div>+ ) : error ? (+ <div className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-3 py-2 text-[12.5px] text-amber-700 dark:text-amber-400">+ {error}+ </div>+ ) : detail ? (+ <div className="prose-skill text-[13.5px] leading-relaxed text-[var(--foreground)]">+ <SkillMarkdown content={stripFrontmatter(detail.content)} />+ </div>+ ) : null}</div>+ </>+ );+}++// ── shared install button ───────────────────────────────────────────────────++function InstallButton({+ state,+ installed,+ tr,+ onClick,+}: {+ state?: InstallState;+ installed: boolean;+ tr: (cn: string, en: string) => string;+ onClick: (force: boolean) => void;+}) {+ if (state?.kind === "installing") {+ return (+ <span className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--muted)] px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)]">+ <Loader2 size={12} className="animate-spin" />+ {tr("下载中…", "Downloading…")}+ </span>);}+ const label =+ state?.kind === "error"+ ? tr("重试", "Retry")+ : installed+ ? tr("重新下载", "Re-download")+ : tr("下载", "Download");+ const Icon = installed ? RefreshCw : Download;+return (- <div className="flex items-center gap-2 border-b border-amber-500/20 bg-amber-500/10 px-5 py-2.5 text-[12.5px] text-amber-700 dark:text-amber-400">- <AlertTriangle size={14} className="shrink-0" />- <span>- {tr(`导入 ${status.name} 失败:`, `Could not import ${status.name}: `)}- {status.message}- </span>- </div>+ <button+ onClick={(e) => {+ e.stopPropagation();+ onClick(installed);+ }}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] shadow-sm transition-colors hover:bg-[var(--muted)]/60"+ >+ <Icon size={12} strokeWidth={2} />+ {label}+ </button>);}diff --git a/web/components/space/MyAgentsSection.tsx b/web/components/space/MyAgentsSection.tsxindex eb51abe93..a9e16e0a8 100644--- a/web/components/space/MyAgentsSection.tsx+++ b/web/components/space/MyAgentsSection.tsx@@ -15,6 +15,7 @@ import {} from "lucide-react";import { useTranslation } from "react-i18next";import SessionList from "@/components/SessionList";+import { agentGlyph } from "@/components/agents/agent-icons";import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";import ImportWizard from "@/components/space/ImportWizard";import ScopeEditorModal from "@/components/space/ScopeEditorModal";@@ -271,7 +272,7 @@ export default function MyAgentsSection() {<div className="space-y-6"><SpaceSectionHeadericon={Bot}- title={t("My Agents")}+ title={t("Imported conversations")}description={t("Your Claude Code and Codex conversations as named agents — open one to keep chatting, edit what each imports, or refresh to pull in new conversations.",)}@@ -414,6 +415,9 @@ function AgentCard({const { t } = useTranslation();const [menuOpen, setMenuOpen] = useState(false);const menuRef = useRef<HTMLDivElement>(null);+ // Member-expression render (``glyph.Icon``) — a bare local capitalized+ // component trips react-hooks/static-components; this doesn't.+ const glyph = { Icon: agentGlyph(agent.source) ?? Bot };useEffect(() => {if (!menuOpen) return;@@ -445,7 +449,7 @@ function AgentCard({}`}><span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-[var(--border)]/60 bg-[var(--background)] text-[var(--foreground)]">- <Bot size={18} strokeWidth={1.6} />+ <glyph.Icon size={20} strokeWidth={1.6} /></span><div className="min-w-0 flex-1">{renaming ? (@@ -615,6 +619,7 @@ function UngroupedCard({onReadd: () => void;}) {const { t } = useTranslation();+ const glyph = { Icon: agentGlyph(source) ?? Bot };return (<divrole="button"@@ -633,7 +638,7 @@ function UngroupedCard({}`}><span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-[var(--border)]/60 bg-[var(--background)] text-[var(--muted-foreground)]">- <Bot size={18} strokeWidth={1.6} />+ <glyph.Icon size={20} strokeWidth={1.6} /></span><div className="min-w-0 flex-1"><div className="truncate text-[13.5px] font-semibold tracking-tight text-[var(--foreground)]">diff --git a/web/components/space/SkillsSection.tsx b/web/components/space/SkillsSection.tsxindex 776e534b5..b925ea405 100644--- a/web/components/space/SkillsSection.tsx+++ b/web/components/space/SkillsSection.tsx@@ -977,6 +977,7 @@ export default function SkillsSection() {<EduHubImportModalonClose={() => setImportOpen(false)}onInstalled={() => void load()}+ installedNames={new Set(skills.map((s) => s.name))}/>)}</div>diff --git a/web/components/space/SpaceDashboard.tsx b/web/components/space/SpaceDashboard.tsxindex 24dbcff52..c8df3a345 100644--- a/web/components/space/SpaceDashboard.tsx+++ b/web/components/space/SpaceDashboard.tsx@@ -5,7 +5,6 @@ import Link from "next/link";import { useTranslation } from "react-i18next";import {ArrowUpRight,- Bot,ClipboardList,GraduationCap,History,@@ -15,8 +14,7 @@ import {type LucideIcon,} from "lucide-react";-import { listSessions, type SessionSummary } from "@/lib/session-api";-import { listImportedSessions } from "@/lib/imports-api";+import { listSessions } from "@/lib/session-api";import { listNotebooks, listNotebookEntries } from "@/lib/notebook-api";import { listPersonas } from "@/lib/personas-api";import { listSkills } from "@/lib/skills-api";@@ -35,7 +33,6 @@ type Lang = { zh: string; en: string };type DashKey =| "chat_history"- | "agents"| "notebooks"| "question_bank"| "personas"@@ -60,16 +57,6 @@ interface DashboardGroup {items: DashboardItem[];}-function distinctAgentSources(sessions: SessionSummary[]): number {- const seen = new Set<string>();- for (const s of sessions) {- const src = (s.preferences as { import?: { source?: string } } | undefined)- ?.import?.source;- if (src === "claude_code" || src === "codex") seen.add(src);- }- return seen.size;-}-const GROUPS: DashboardGroup[] = [{label: { zh: "对话与资料", en: "Conversations & Materials" },@@ -87,22 +74,6 @@ const GROUPS: DashboardGroup[] = [tile: "bg-sky-500/10 text-sky-600 dark:text-sky-400",load: async () => (await listSessions(200, 0, { force: true })).length,},- {- key: "agents",- href: "/space/agents",- icon: Bot,- title: { zh: "我的智能体", en: "My Agents" },- blurb: {- zh: "续聊导入的 Claude Code 与 Codex 对话。",- en: "Chat with imported Claude Code and Codex agents.",- },- unit: { zh: "个智能体", en: "agents" },- tile: "bg-violet-500/10 text-violet-600 dark:text-violet-400",- load: async () =>- distinctAgentSources(- await listImportedSessions(200, 0, { force: true }),- ),- },{key: "notebooks",href: "/space/notebooks",diff --git a/web/hooks/useConnectedAgentKinds.ts b/web/hooks/useConnectedAgentKinds.tsnew file mode 100644index 000000000..c1f20d8b2--- /dev/null+++ b/web/hooks/useConnectedAgentKinds.ts@@ -0,0 +1,51 @@+"use client";++import { useEffect, useState } from "react";+import { listSubagentConnections } from "@/lib/subagents-api";++/**+ * Shared, lazily-fetched `connection name → backend kind` map for connected+ * subagents. Used to badge a selected agent (a `type: subagent` KB) with its+ * real brand icon instead of the generic knowledge-base icon wherever only the+ * KB name is known (e.g. the sent-message reference chip).+ *+ * Module-cached so it fetches once across all consumers; returns `{}` until+ * loaded, so callers degrade gracefully to the default icon.+ */+let cache: Record<string, string> | null = null;+let inflight: Promise<void> | null = null;+const listeners = new Set<(map: Record<string, string>) => void>();++function ensureLoaded(): void {+ if (cache || inflight) return;+ inflight = listSubagentConnections()+ .then((conns) => {+ cache = Object.fromEntries(conns.map((c) => [c.name, c.agent_kind]));+ for (const l of listeners) l(cache);+ })+ .catch(() => {+ cache = {};+ })+ .finally(() => {+ inflight = null;+ });+}++export function useConnectedAgentKinds(): Record<string, string> {+ const [map, setMap] = useState<Record<string, string>>(() => cache ?? {});+ useEffect(() => {+ listeners.add(setMap);+ if (cache) {+ // Loaded by another consumer between our render and this effect — deliver+ // it off the effect body (avoids a synchronous setState-in-effect).+ const loaded = cache;+ queueMicrotask(() => setMap(loaded));+ } else {+ ensureLoaded();+ }+ return () => {+ listeners.delete(setMap);+ };+ }, []);+ return map;+}diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex e10d2f3b3..ee79c437f 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -54,10 +54,12 @@ export interface KnowledgeBase {embedding_model?: string;embedding_dim?: number;embedding_mismatch?: boolean;- /** Connected-source kind (e.g. "obsidian"); absent for ordinary indexed KBs. */+ /** Connected-source kind (e.g. "obsidian", "subagent"); absent for ordinary indexed KBs. */type?: string;/** Absolute path of a connected Obsidian vault (when type === "obsidian"). */vault_path?: string;+ /** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex". */+ agent_kind?: string;};progress?: ProgressInfo;statistics?: {diff --git a/web/lib/partner-session.ts b/web/lib/partner-session.tsnew file mode 100644index 000000000..039def598--- /dev/null+++ b/web/lib/partner-session.ts@@ -0,0 +1,34 @@+/**+ * Per-partner web session key, persisted in localStorage so a refresh / tab+ * switch / navigation reattaches to the SAME conversation. The key is the+ * canonical session id the backend stores under (colon-free, so it doubles as+ * the filename stem and the id used by resume / delete / branch).+ */++function storageKey(partnerId: string): string {+ return `partner-session:${partnerId}`;+}++export function freshPartnerSessionKey(): string {+ return `web-${Math.random().toString(36).slice(2, 10)}`;+}++export function loadPartnerSessionKey(partnerId: string): string {+ try {+ const existing = window.localStorage.getItem(storageKey(partnerId));+ if (existing) return existing;+ const fresh = freshPartnerSessionKey();+ window.localStorage.setItem(storageKey(partnerId), fresh);+ return fresh;+ } catch {+ return freshPartnerSessionKey();+ }+}++export function persistPartnerSessionKey(partnerId: string, key: string): void {+ try {+ window.localStorage.setItem(storageKey(partnerId), key);+ } catch {+ /* private mode / storage disabled — in-memory only */+ }+}diff --git a/web/lib/partners-api.ts b/web/lib/partners-api.tsindex 87af6844c..0ba0766c8 100644--- a/web/lib/partners-api.ts+++ b/web/lib/partners-api.ts@@ -18,6 +18,7 @@ export interface PartnerInfo {avatar?: string;soul_origin?: { type?: string; id?: string };enabled_tools?: string[] | null;+ builtin_tools?: string[] | null;mcp_tools?: string[] | null;running: boolean;started_at: string | null;@@ -53,6 +54,8 @@ export interface McpToolOption extends ToolOption {export interface ToolOptions {tools: ToolOption[];+ /** Auto-mounted built-in tools an owner may allow/deny (default: all). */+ builtin_tools: ToolOption[];mcp_tools: McpToolOption[];}@@ -64,6 +67,8 @@ export interface PartnerAssets {export interface PartnerSessionInfo {session_key: string;+ /** Opening user message, trimmed — the conversation's human label. */+ title?: string;message_count: number;updated_at: string;last_message: string;@@ -95,6 +100,7 @@ export interface CreatePartnerPayload {color?: string;avatar?: string;enabled_tools?: string[] | null;+ builtin_tools?: string[] | null;mcp_tools?: string[] | null;assets?: {knowledge_bases?: string[];@@ -323,7 +329,7 @@ export async function getChannelSchemas(): Promise<ChannelsSchemaResponse> {export async function getPartnerHistory(partnerId: string,- options?: { sessionKey?: string; limit?: number },+ options?: { sessionKey?: string; sessionId?: string; limit?: number },): Promise<{role: string;@@ -331,10 +337,13 @@ export async function getPartnerHistory(timestamp?: string;channel?: string;attachments?: Record<string, unknown>[];+ /** Persisted turn trace (assistant rows only) for rehydrating activity. */+ events?: Record<string, unknown>[];}[]> {const params = new URLSearchParams();if (options?.sessionKey) params.set("session_key", options.sessionKey);+ if (options?.sessionId) params.set("session_id", options.sessionId);if (options?.limit) params.set("limit", String(options.limit));const query = params.toString() ? `?${params.toString()}` : "";return json(@@ -356,3 +365,51 @@ export async function getPartnerSessions(),);}++async function postSessionAction(+ partnerId: string,+ action: "archive" | "resume" | "delete",+ sessionKey: string,+): Promise<void> {+ await apiFetch(+ apiUrl(+ `/api/v1/partners/${encodeURIComponent(partnerId)}/sessions/${action}`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_key: sessionKey }),+ },+ );+}++export function archivePartnerSession(partnerId: string, sessionKey: string) {+ return postSessionAction(partnerId, "archive", sessionKey);+}++export function resumePartnerSession(partnerId: string, sessionKey: string) {+ return postSessionAction(partnerId, "resume", sessionKey);+}++export function deletePartnerSession(partnerId: string, sessionKey: string) {+ return postSessionAction(partnerId, "delete", sessionKey);+}++export async function branchPartnerSession(+ partnerId: string,+ sourceKey: string,+ newKey: string,+): Promise<{ session: PartnerSessionInfo }> {+ return json(+ await apiFetch(+ apiUrl(+ `/api/v1/partners/${encodeURIComponent(partnerId)}/sessions/branch`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ source_key: sourceKey, new_key: newKey }),+ },+ ),+ );+}diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.tsindex c75968c05..e274be0bc 100644--- a/web/lib/settings-nav.ts+++ b/web/lib/settings-nav.ts@@ -2,6 +2,7 @@import {AudioLines,+ Bot,Boxes,Brain,BrainCircuit,@@ -21,6 +22,7 @@ import {type LucideIcon,} from "lucide-react";+import { ClaudeGlyph, CodexGlyph } from "@/components/agents/agent-icons";import type { ServiceName } from "@/components/settings/SettingsContext";/**@@ -186,6 +188,34 @@ const CHAT_CHILDREN: SettingsLeaf[] = [},];+const AGENT_CHILDREN: SettingsLeaf[] = [+ {+ key: "agent-claude-code",+ href: "/settings/agents/claude-code",+ label: { zh: "Claude Code", en: "Claude Code" },+ blurb: {+ zh: "DeepTutor 调用本机 Claude Code 时的模型、推理强度与运行参数。",+ en: "Model, reasoning effort, and run params for the local Claude Code.",+ },+ // Brand glyph shares the lucide call signature (size/className).+ icon: ClaudeGlyph as unknown as LucideIcon,+ tile: "bg-orange-500/10 text-orange-600 dark:text-orange-400",+ adminOnly: true,+ },+ {+ key: "agent-codex",+ href: "/settings/agents/codex",+ label: { zh: "Codex", en: "Codex" },+ blurb: {+ zh: "DeepTutor 调用本机 Codex 时的模型、推理强度与运行参数。",+ en: "Model, reasoning effort, and run params for the local Codex.",+ },+ icon: CodexGlyph as unknown as LucideIcon,+ tile: "bg-blue-500/10 text-blue-600 dark:text-blue-400",+ adminOnly: true,+ },+];+export const SETTINGS_CATEGORIES: SettingsCategory[] = [{key: "appearance",@@ -233,6 +263,17 @@ export const SETTINGS_CATEGORIES: SettingsCategory[] = [href: "/settings/chat",children: CHAT_CHILDREN,},+ {+ key: "agents",+ label: { zh: "伙伴和智能体", en: "Partners & Agents" },+ blurb: {+ zh: "配置可在对话中调用的子智能体",+ en: "Configure the subagents you can call on in chat",+ },+ icon: Bot,+ href: "/settings/agents",+ children: AGENT_CHILDREN,+ },{key: "memory",label: { zh: "记忆", en: "Memory" },@@ -276,6 +317,8 @@ const STORAGE_PATHS: Record<string, string> = {"/settings/mcp": "data/user/settings/mcp.json","/settings/capabilities": "data/user/settings/main.yaml · agents.yaml","/settings/memory": "data/user/settings/main.yaml",+ "/settings/agents/claude-code": "data/user/settings/subagent.json",+ "/settings/agents/codex": "data/user/settings/subagent.json",};export function storagePathFor(pathname: string): string | null {diff --git a/web/lib/skills-api.ts b/web/lib/skills-api.tsindex 83a883bdb..cd4bd7324 100644--- a/web/lib/skills-api.ts+++ b/web/lib/skills-api.ts@@ -152,6 +152,95 @@ export async function installSkillFromHub(};}+// ── EduHub / hub browsing ───────────────────────────────────────────────+// Powers the in-app "Import from EduHub" browser. The backend proxies the+// hub's public catalog (no login, no iframe), so the panel can render hub+// skills in DeepTutor's own UI and download them with one click.++export interface HubSkillListing {+ slug: string;+ name: string;+ summary: string;+ version: string;+ downloads: number;+ stars: number;+ owner: string;+ ownerUrl: string;+}++export interface HubCatalog {+ hub: string;+ /** The hub's website origin (for a "view on EduHub" link out). */+ webUrl: string;+ skills: HubSkillListing[];+}++export interface HubSkillDetail extends HubSkillListing {+ content: string;+ tags: string[];+ /** Direct link to this skill's page on the hub site. */+ webUrl: string;+}++function normalizeHubListing(item: Record<string, unknown>): HubSkillListing {+ return {+ slug: String(item?.slug ?? ""),+ name: String(item?.name ?? item?.slug ?? ""),+ summary: String(item?.summary ?? ""),+ version: String(item?.version ?? ""),+ downloads: Number(item?.downloads ?? 0),+ stars: Number(item?.stars ?? 0),+ owner: String(item?.owner ?? ""),+ ownerUrl: String(item?.owner_url ?? ""),+ };+}++/** List skills available on a hub (default EduHub). `query` filters server-side. */+export async function fetchHubCatalog(options?: {+ hub?: string;+ query?: string;+ limit?: number;+}): Promise<HubCatalog> {+ const params = new URLSearchParams();+ if (options?.hub) params.set("hub", options.hub);+ if (options?.query) params.set("q", options.query);+ if (options?.limit) params.set("limit", String(options.limit));+ const qs = params.toString();+ const response = await apiFetch(+ apiUrl(`/api/v1/skills/hub/catalog${qs ? `?${qs}` : ""}`),+ { cache: "no-store" },+ );+ const data = await asJson(response);+ const skills = Array.isArray(data?.skills) ? data.skills : [];+ return {+ hub: String(data?.hub ?? "eduhub"),+ webUrl: String(data?.web_url ?? ""),+ skills: skills.map((item: Record<string, unknown>) =>+ normalizeHubListing(item),+ ),+ };+}++/** Full metadata + rendered SKILL.md body for one hub skill. */+export async function fetchHubSkillDetail(+ slug: string,+ options?: { hub?: string },+): Promise<HubSkillDetail> {+ const params = new URLSearchParams({ slug });+ if (options?.hub) params.set("hub", options.hub);+ const response = await apiFetch(+ apiUrl(`/api/v1/skills/hub/detail?${params.toString()}`),+ { cache: "no-store" },+ );+ const data = await asJson(response);+ return {+ ...normalizeHubListing(data),+ content: String(data?.content ?? ""),+ tags: normalizeTags(data?.tags),+ webUrl: String(data?.web_url ?? ""),+ };+}+export async function createSkill(payload: CreateSkillPayload,): Promise<SkillInfo> {diff --git a/web/lib/subagents-api.ts b/web/lib/subagents-api.tsnew file mode 100644index 000000000..6646431f0--- /dev/null+++ b/web/lib/subagents-api.ts@@ -0,0 +1,201 @@+import { apiFetch, apiUrl } from "@/lib/api";++/** One agent CLI backend's installability on this machine. */+export interface SubagentBackendInfo {+ kind: string;+ display_name: string;+ available: boolean;+ version: string;+ detail: string;+}++/** A connected subagent the user can consult in chat. */+export interface SubagentConnection {+ name: string;+ agent_kind: string;+ cwd: string;+ description?: string;+ created_at?: string;+ updated_at?: string | null;+}++export async function detectSubagents(): Promise<SubagentBackendInfo[]> {+ const res = await apiFetch(apiUrl("/api/v1/subagents/detect"), {+ cache: "no-store",+ });+ if (!res.ok) throw new Error(`Detect failed: ${res.status}`);+ const data = (await res.json()) as { backends: SubagentBackendInfo[] };+ return data.backends ?? [];+}++export async function listSubagentConnections(): Promise<SubagentConnection[]> {+ const res = await apiFetch(apiUrl("/api/v1/subagents/connections"), {+ cache: "no-store",+ });+ if (!res.ok) throw new Error(`Request failed: ${res.status}`);+ const data = (await res.json()) as { connections: SubagentConnection[] };+ return data.connections ?? [];+}++export async function connectSubagent(payload: {+ name: string;+ agent_kind: string;+ cwd?: string;+}): Promise<SubagentConnection> {+ const res = await apiFetch(apiUrl("/api/v1/subagents/connections"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ if (!res.ok) {+ const detail = await res+ .json()+ .then((d) => (d as { detail?: string }).detail)+ .catch(() => "");+ throw new Error(detail || `Connect failed: ${res.status}`);+ }+ return (await res.json()) as SubagentConnection;+}++export async function disconnectSubagent(name: string): Promise<void> {+ const res = await apiFetch(+ apiUrl(`/api/v1/subagents/connections/${encodeURIComponent(name)}`),+ { method: "DELETE" },+ );+ if (!res.ok) throw new Error(`Disconnect failed: ${res.status}`);+}++export interface SubagentModelOption {+ slug: string;+ display_name: string;+ default_effort: string;+ efforts: string[];+}++export interface SubagentBackendOptions {+ kind: string;+ display_name: string;+ available: boolean;+ version: string;+ default_model: string;+ models: SubagentModelOption[];+ efforts: string[];+ allow_custom_model: boolean;+ synced_at: string;+ detail: string;+}++export async function getBackendOptions(): Promise<SubagentBackendOptions[]> {+ const res = await apiFetch(apiUrl("/api/v1/subagents/backends/options"), {+ cache: "no-store",+ });+ if (!res.ok) throw new Error(`Request failed: ${res.status}`);+ const data = (await res.json()) as { backends: SubagentBackendOptions[] };+ return data.backends ?? [];+}++/**+ * Re-pull one backend's model catalog (the settings "sync" button). For Claude+ * Code this scrapes its `/model` TUI live (can take a few seconds); for Codex it+ * re-reads the CLI's cache.+ */+export async function syncBackendOptions(+ kind: string,+): Promise<SubagentBackendOptions> {+ const res = await apiFetch(+ apiUrl(`/api/v1/subagents/backends/${encodeURIComponent(kind)}/sync`),+ { method: "POST" },+ );+ if (!res.ok) throw new Error(`Sync failed: ${res.status}`);+ return (await res.json()) as SubagentBackendOptions;+}++export interface SubagentBackendConfig {+ enabled?: boolean;+ model?: string;+ effort?: string;+ system_prompt?: string;+ permission_mode?: string;+ sandbox?: string;+ approval?: string;+ network_access?: boolean;+ ephemeral?: boolean;+ forward_images?: boolean;+ extra_args?: string[];+}++export interface SubagentSettings {+ consult_budget: number;+ backends: Record<string, SubagentBackendConfig>;+}++/** One streamed line from the "message the agent directly" endpoint. */+export interface SubagentStreamLine {+ channel?: string;+ text?: string;+ merge_id?: string;+ done?: boolean;+ success?: boolean;+ session_id?: string;+}++/**+ * Send a message straight to a connected subagent and stream its run as+ * newline-delimited JSON. Resumes the same live session DeepTutor consults+ * (shared via the cross-turn registry), so the agent keeps context.+ */+export async function* streamSubagentMessage(+ name: string,+ body: { chat_session_id: string; message: string },+ signal?: AbortSignal,+): AsyncGenerator<SubagentStreamLine> {+ const res = await apiFetch(+ apiUrl(`/api/v1/subagents/connections/${encodeURIComponent(name)}/message`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ signal,+ },+ );+ if (!res.ok || !res.body) throw new Error(`Message failed: ${res.status}`);+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buf = "";+ const flush = function* (chunk: string): Generator<SubagentStreamLine> {+ buf += chunk;+ let nl: number;+ while ((nl = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, nl).trim();+ buf = buf.slice(nl + 1);+ if (line) yield JSON.parse(line) as SubagentStreamLine;+ }+ };+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ yield* flush(decoder.decode(value, { stream: true }));+ }+ const tail = buf.trim();+ if (tail) yield JSON.parse(tail) as SubagentStreamLine;+}++export async function getSubagentSettings(): Promise<SubagentSettings> {+ const res = await apiFetch(apiUrl("/api/v1/subagents/settings"), {+ cache: "no-store",+ });+ if (!res.ok) throw new Error(`Request failed: ${res.status}`);+ return (await res.json()) as SubagentSettings;+}++export async function updateSubagentSettings(+ payload: Partial<SubagentSettings>,+): Promise<SubagentSettings> {+ const res = await apiFetch(apiUrl("/api/v1/subagents/settings"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ if (!res.ok) throw new Error(`Update failed: ${res.status}`);+ return (await res.json()) as SubagentSettings;+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex cce9264c6..15c546231 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -889,6 +889,9 @@"Send a message to start the conversation.": "Send a message to start the conversation.","Chat with {{name}}": "Chat with {{name}}","Type a message...": "Type a message...",+ "Tips": "Tips",+ "Type / to see commands — start a new conversation, view history, toggle tools, and more.": "Type / to see commands — start a new conversation, view history, toggle tools, and more.",+ "Attach images or documents with the clip, or just drag them in.": "Attach images or documents with the clip, or just drag them in.","Thinking ({{count}} steps)": "Thinking ({{count}} steps)","Working...": "Working...","Playground": "Playground",@@ -925,6 +928,19 @@"Extra constraints, style, focus areas...": "Extra constraints, style, focus areas...","Try": "Try","No conversations yet": "No conversations yet",+ "New conversation": "New conversation",+ "Archived": "Archived",+ "Archived conversation": "Archived conversation",+ "Continue this conversation": "Continue this conversation",+ "Delete conversation": "Delete conversation",+ "Conversation deleted": "Conversation deleted",+ "Session not found": "Session not found",+ "Conversations:": "Conversations:",+ "Nothing to branch yet.": "Nothing to branch yet.",+ "Branched — the original is archived as {{id}}": "Branched — the original is archived as {{id}}",+ "Usage: /resume <session ID>": "Usage: /resume <session ID>",+ "Usage: /delete <session ID>": "Usage: /delete <session ID>",+ "Use /resume <session ID> or /delete <session ID>.": "Use /resume <session ID> or /delete <session ID>.","Save title": "Save title","Rename chat": "Rename chat","Delete chat": "Delete chat",@@ -2316,6 +2332,8 @@"# Soul\nDescribe who this partner is, how it speaks, what it values…": "# Soul\nDescribe who this partner is, how it speaks, what it values…","Loading tools…": "Loading tools…","System tools": "System tools",+ "Built-in tools": "Built-in tools",+ "Mounted automatically when the context calls for it — a knowledge base attached, memory available, the sandbox enabled. Deny any you don't want this partner to have.": "Mounted automatically when the context calls for it — a knowledge base attached, memory available, the sandbox enabled. Deny any you don't want this partner to have.","MCP tools": "MCP tools","Loading your library…": "Loading your library…","No knowledge bases available.": "No knowledge bases available.",@@ -2568,6 +2586,17 @@"Done": "Done","Try again": "Try again","My Agents": "My Agents",+ "Imported conversations": "Imported conversations",+ "Agent": "Agent",+ "Select a connected agent": "Select a connected agent",+ "Consult Subagent": "Consult Subagent",+ "DeepTutor asks": "DeepTutor asks",+ "Max rounds DeepTutor may ask": "Max rounds DeepTutor may ask",+ "Talk to an agent": "Talk to an agent",+ "No connected agents — connect one in My Agents.": "No connected agents — connect one in My Agents.",+ "No matching agent": "No matching agent",+ "Fewer rounds": "Fewer rounds",+ "More rounds": "More rounds","Add agent": "Add agent","No agents yet": "No agents yet","Your Claude Code and Codex sessions, organized by source — open one to keep chatting, or refresh to pull in new conversations.": "Your Claude Code and Codex sessions, organized by source — open one to keep chatting, or refresh to pull in new conversations.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 65814a06d..967ac0d42 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -824,6 +824,9 @@"Send a message to start the conversation.": "发送消息开始对话。","Chat with {{name}}": "与 {{name}} 聊天","Type a message...": "输入消息…",+ "Tips": "用法提示",+ "Type / to see commands — start a new conversation, view history, toggle tools, and more.": "输入 / 查看命令——开启新对话、查看历史、切换工具等。",+ "Attach images or documents with the clip, or just drag them in.": "点回形针添加图片或文档,或直接拖拽进来。","Thinking ({{count}} steps)": "思考中({{count}} 步)","Working...": "处理中…","Thinking...": "思考中…",@@ -942,6 +945,19 @@"default": "默认","Try": "试试","No conversations yet": "暂无对话",+ "New conversation": "新对话",+ "Archived": "已归档",+ "Archived conversation": "已归档对话",+ "Continue this conversation": "继续这个对话",+ "Delete conversation": "删除对话",+ "Conversation deleted": "对话已删除",+ "Session not found": "未找到该会话",+ "Conversations:": "对话列表:",+ "Nothing to branch yet.": "暂时没有可分支的内容。",+ "Branched — the original is archived as {{id}}": "已分支——原对话已归档为 {{id}}",+ "Usage: /resume <session ID>": "用法:/resume <会话 ID>",+ "Usage: /delete <session ID>": "用法:/delete <会话 ID>",+ "Use /resume <session ID> or /delete <session ID>.": "使用 /resume <会话 ID> 或 /delete <会话 ID>。","Save title": "保存标题","Rename chat": "重命名对话","Delete chat": "删除对话",@@ -2316,6 +2332,8 @@"# Soul\nDescribe who this partner is, how it speaks, what it values…": "# 灵魂\n描述这个伙伴是谁、如何说话、看重什么……","Loading tools…": "正在加载工具…","System tools": "系统工具",+ "Built-in tools": "内置工具",+ "Mounted automatically when the context calls for it — a knowledge base attached, memory available, the sandbox enabled. Deny any you don't want this partner to have.": "在上下文需要时自动挂载——挂载了知识库、有可用记忆、开启了沙箱等。不想让这个伙伴拥有的可以关闭。","MCP tools": "MCP 工具","Loading your library…": "正在加载你的资料库…","No knowledge bases available.": "暂无可用知识库。",@@ -2568,6 +2586,17 @@"Done": "完成","Try again": "重试","My Agents": "我的智能体",+ "Imported conversations": "导入的对话",+ "Agent": "智能体",+ "Select a connected agent": "选择已连接的智能体",+ "Consult Subagent": "咨询子代理",+ "DeepTutor asks": "DeepTutor 问",+ "Max rounds DeepTutor may ask": "DeepTutor 最多提问轮数",+ "Talk to an agent": "与智能体对话",+ "No connected agents — connect one in My Agents.": "尚未连接智能体 —— 请在「我的智能体」中连接。",+ "No matching agent": "没有匹配的智能体",+ "Fewer rounds": "减少",+ "More rounds": "增加","Add agent": "添加智能体","No agents yet": "还没有智能体","Your Claude Code and Codex sessions, organized by source — open one to keep chatting, or refresh to pull in new conversations.": "你的 Claude Code 与 Codex 对话,按来源归类——打开任意一条继续聊,或刷新以拉取新对话。",