Skip to content

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

release: v1.4.0 — release notes, version bump, repo hygiene

Bingxi Zhao (Frank)6153d8c09293
diff --git a/.env.example_CN b/.env.example_CN
deleted file mode 100644
index 4679fbf9a..000000000
--- a/.env.example_CN
+++ /dev/null
@@ -1,215 +0,0 @@
-# =====================================================================
-# DeepTutor 环境变量模板(中文)
-# =====================================================================
-# 复制本文件为 `.env` 后再填写。
-#
-# 分组:
-# 1. 端口
-# 2. LLM (聊天必填)
-# 3. Embedding (知识库 / RAG 必填)
-# 4. 网页搜索 (可选)
-# 5. 网络与前端 (Docker / 远程部署)
-# 6. 安全
-# 7. 认证与多用户
-# 8. PocketBase 边车 (可选的认证 + 存储后端)
-# 9. 附件存储 (可选)
-#
-# 实际启动时只有 LLM_* 是强制的,其它都有默认值。请按需取消注释、填值即可,
-# 不需要的留空。
-
-# ---------------------------------------------------------------------
-# 1. 端口
-# ---------------------------------------------------------------------
-BACKEND_PORT=8001
-FRONTEND_PORT=3782
-# 仅 docker-compose 用来对外暴露 PocketBase 容器的端口。Python 后端连接
-# PocketBase 时使用下面的 POCKETBASE_URL,而不是这个变量。
-POCKETBASE_PORT=8090
-
-# ---------------------------------------------------------------------
-# 2. LLM(必填)
-# ---------------------------------------------------------------------
-# 支持的 binding:openai, anthropic, deepseek, gemini, azure_openai,
-# lm_studio, ollama, vllm, openrouter, siliconflow, dashscope, ...
-# 完整列表请运行:`deeptutor provider list`
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
-# Azure OpenAI 必填;其它情况留空。
-LLM_API_VERSION=
-# 可选:控制推理 / 思考强度。
-# DeepSeek: "high" / "max" 开启思考;"minimal" 关闭
-# OpenAI o 系列: "low" / "medium" / "high"
-# 留空则根据模型名自动判断。
-LLM_REASONING_EFFORT=
-
-# ---------------------------------------------------------------------
-# 3. Embedding(知识库 / RAG 必填)
-# ---------------------------------------------------------------------
-# 支持的 binding:openai, azure_openai, cohere, jina, ollama, vllm,
-# siliconflow, aliyun, gemini, custom.
-#
-# 重要(v1.3.0+):EMBEDDING_HOST 必须填写「完整 endpoint URL」,会被
-# 原样调用,不会自动追加路径。(上面的 LLM_HOST 仍然是聊天接口的 base
-# URL。)示例:
-# OpenAI: https://api.openai.com/v1/embeddings
-# Gemini: https://generativelanguage.googleapis.com/v1beta/openai/embeddings
-# Cohere v4: https://api.cohere.com/v2/embed
-# Jina: https://api.jina.ai/v1/embeddings
-# Ollama: http://localhost:11434/api/embed
-# SiliconFlow: https://api.siliconflow.cn/v1/embeddings
-# Aliyun: https://dashscope.aliyuncs.com/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-# Azure embedding 部署需要填写;其它情况留空。
-EMBEDDING_API_VERSION=
-# 建议留空,让 DeepTutor 在首次「Test connection」成功时自动识别维度。
-# 只有需要强制指定 Matryoshka 维度时才手动填写,例如 Qwen3-Embedding 的
-# 1024/1536/2048/2560/4096,或 OpenAI text-embedding-3-large 的 3072。
-EMBEDDING_DIMENSION=
-# 是否在请求体中携带 `dimensions` 参数:
-# true -> 总是发送(OpenAI text-embedding-3*, Qwen3-Embedding,
-# Qwen3-VL-Embedding)
-# false -> 永不发送(如果提供商在收到该参数时返回 HTTP 400,请设为
-# false)
-# 留空 / 未设置 -> 自动:根据模型家族判断
-EMBEDDING_SEND_DIMENSIONS=
-
-# 各 embedding 提供商的 API Key 兜底值。当前 embedding profile 没有单独
-# 配置 api_key 时会使用这些值;首次打开设置页时也会读取它们,避免重复
-# 输入。
-SILICONFLOW_API_KEY=
-DASHSCOPE_API_KEY=
-COHERE_API_KEY=
-JINA_API_KEY=
-GEMINI_API_KEY=
-
-# ⚠️ Docker + 本地模型(LM Studio / Ollama / vLLM)
-# ────────────────────────────────────────────────────────────────────
-# 当 DeepTutor 以 Docker 方式运行、而 LLM / embedding 模型运行在宿主机
-# 上时:
-# - 不要使用 "localhost" 或 "127.0.0.1"——容器内这些地址指向容器自身,
-# 而不是宿主机。
-# - macOS / Windows (Docker Desktop):
-# http://host.docker.internal:<端口>/v1
-# - Linux:使用宿主机的局域网 IP,例如 http://192.168.1.100:<端口>/v1
-# (或使用 --network=host 启动 Docker)
-#
-# 示例(LM Studio 监听 1234 端口):
-# LLM_BINDING=lm_studio
-# LLM_HOST=http://host.docker.internal:1234/v1
-# EMBEDDING_BINDING=lm_studio
-# EMBEDDING_HOST=http://host.docker.internal:1234/v1/embeddings
-
-# ---------------------------------------------------------------------
-# 4. 网页搜索(可选)
-# ---------------------------------------------------------------------
-# 可用 provider:brave, tavily, serper, jina, perplexity, searxng, duckduckgo
-SEARCH_PROVIDER=
-SEARCH_API_KEY=
-# 自托管 SearXNG 必填;其它需要显式 base URL 的提供商可选。
-SEARCH_BASE_URL=
-# 可选:搜索流量走 HTTP/HTTPS 代理时填写。
-SEARCH_PROXY=
-
-# ---------------------------------------------------------------------
-# 5. 网络与前端(Docker / 远程部署)
-# ---------------------------------------------------------------------
-# 远程部署时,浏览器访问后端的公网地址(前端与后端不在同一台机器时使用)。
-NEXT_PUBLIC_API_BASE_EXTERNAL=
-# 当 Next.js 客户端访问的后端不是 http://localhost:${BACKEND_PORT} 时,
-# 使用这个变量覆盖。本地常规启动可留空。
-NEXT_PUBLIC_API_BASE=
-# 可选:追加到 FastAPI CORS 白名单的额外 Origin(例如自定义域名)。
-# localhost / 127.0.0.1 / Docker host 始终被允许。
-CORS_ORIGIN=
-
-# ---------------------------------------------------------------------
-# 6. 安全
-# ---------------------------------------------------------------------
-# 是否跳过出站 HTTP 的 TLS 校验。生产环境请保持 false——只在使用本地自签
-# 证书或离线测试时才打开。
-DISABLE_SSL_VERIFY=false
-
-# ---------------------------------------------------------------------
-# 7. 认证与多用户
-# ---------------------------------------------------------------------
-# 公网部署时设为 true 启用登录;本地 / localhost 使用保持 false 即可,
-# 无需登录。
-AUTH_ENABLED=false
-
-# 用于签名 JWT 的密钥。留空时 DeepTutor 会在
-# multi-user/_system/auth/auth_secret 处生成并复用一个稳定密钥。生产环境
-# (尤其是多 worker 部署)建议显式设置。生成命令:
-# python -c "import secrets; print(secrets.token_hex(32))"
-AUTH_SECRET=
-
-# 登录会话的有效时长,单位:小时。
-AUTH_TOKEN_EXPIRE_HOURS=24
-
-# 通过 HTTPS 提供服务时设为 true,让认证 Cookie 携带 Secure 标记。
-AUTH_COOKIE_SECURE=false
-
-# 前端覆盖项;留空让 Web 端从 AUTH_ENABLED 自动派生——start_web.py 已经
-# 把 AUTH_ENABLED 同步到这里供 Next.js 中间件使用。
-NEXT_PUBLIC_AUTH_ENABLED=
-
-# --- 多用户配置(推荐) ---
-# 当 AUTH_ENABLED=true 且未设置 AUTH_USERNAME / AUTH_PASSWORD_HASH 时,
-# 在浏览器中访问 /register。第一位注册者自动成为管理员,可以在
-# /admin/users 中管理其他用户;公开的 /register 端点会在管理员创建后
-# 自动关闭。用户数据保存在 multi-user/_system/auth/users.json。
-
-# --- 单用户环境变量配置(旧版 / 简单) ---
-# 也可以直接设置 AUTH_USERNAME 与 AUTH_PASSWORD_HASH,该用户始终被视为
-# 管理员。当 multi-user/_system/auth/users.json 已经存在时,它的优先级
-# 高于这两个变量,这些设置会被忽略。
-
-# 单用户模式下的管理员用户名。
-AUTH_USERNAME=
-
-# 密码的 Bcrypt 哈希,生成命令:
-# python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
-AUTH_PASSWORD_HASH=
-
-# ---------------------------------------------------------------------
-# 8. PocketBase 边车(可选认证 + 存储)
-# ---------------------------------------------------------------------
-# POCKETBASE_URL 留空时使用内置的 SQLite/JSON 后端(默认);填写后认证、
-# 会话、知识库存储都改走 PocketBase。
-#
-# 通过 docker compose 启动时,PocketBase 容器始终会启动;只有这里填了
-# POCKETBASE_URL,后端才会真正使用它。
-#
-# 注意:PocketBase 模式当前仅支持单用户。默认 schema 的 users 表没有
-# `role` 字段(所有登录都解析为 role=user,无法创建 admin),并且
-# session/message/turn 查询也不会按 user_id 过滤。多用户部署必须留空,
-# 使用默认的 JSON/SQLite 后端。
-#
-# 本地 Docker: POCKETBASE_URL=http://pocketbase:8090
-# 本地裸机: POCKETBASE_URL=http://localhost:8090
-POCKETBASE_URL=
-
-# Python 后端用于管理 PocketBase 集合的管理员账号。在 PocketBase UI 中
-# 创建管理员之后再填这两项。
-POCKETBASE_ADMIN_EMAIL=
-POCKETBASE_ADMIN_PASSWORD=
-
-# 远程服务器部署时,OAuth 重定向使用的 PocketBase 公网 URL。本机
-# 浏览器访问 Docker 时留空即可。
-POCKETBASE_EXTERNAL_URL=
-
-# ---------------------------------------------------------------------
-# 9. 附件存储(可选)
-# ---------------------------------------------------------------------
-# 聊天运行时会把用户上传的 PDF、DOCX、图片等文件持久化到这里,方便
-# 预览抽屉在内存 base64 被释放后仍能重新读取原文件。
-#
-# 默认路径为 <project>/data/user/workspace/chat/attachments;
-# docker-compose.yml 已经把对应目录挂载为持久化 volume。普通 Docker /
-# Linux 部署留空即可。只有在多个后端实例共用共享存储(例如 NFS)时才
-# 需要覆盖。
-CHAT_ATTACHMENT_DIR=
diff --git a/.gitignore b/.gitignore
index 215ac085b..b3747f0f7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -103,6 +103,7 @@ cache/
**/cache/
.cache/
.ruff_cache
+.playwright-cli/
# Log files
*.log
diff --git a/.playwright-cli/page-2026-05-22T09-15-47-989Z.yml b/.playwright-cli/page-2026-05-22T09-15-47-989Z.yml
deleted file mode 100644
index 2d1dc21b7..000000000
--- a/.playwright-cli/page-2026-05-22T09-15-47-989Z.yml
+++ /dev/null
@@ -1,205 +0,0 @@
-- generic [active] [ref=e1]:
- - banner [ref=e2]:
- - generic [ref=e3]:
- - link "DeepTutor" [ref=e4] [cursor=pointer]:
- - /url: /
- - generic [ref=e5]: DeepTutor
- - navigation [ref=e6]:
- - link "Docs" [ref=e7] [cursor=pointer]:
- - /url: /docs/
- - link "GitHub" [ref=e8] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - generic "Preferences" [ref=e9]:
- - generic [ref=e10]:
- - generic [ref=e11]: Language
- - combobox "Language" [ref=e12] [cursor=pointer]:
- - option "English" [selected]
- - option "简体中文"
- - generic [ref=e13]:
- - generic [ref=e14]: Theme
- - combobox "Theme" [ref=e15] [cursor=pointer]:
- - option "Auto" [selected]
- - option "Light"
- - option "Dark"
- - link "Get Started →" [ref=e16] [cursor=pointer]:
- - /url: /docs/get-started/
- - main [ref=e17]:
- - generic [ref=e18]:
- - generic [ref=e19]: Open-source · v1.4.0-beta now available
- - img "DeepTutor" [ref=e21]
- - heading "Personal tutoring, reimagined." [level=1] [ref=e22]:
- - text: Personal tutoring,
- - emphasis [ref=e23]: reimagined.
- - paragraph [ref=e24]: An agent-native learning companion — five modes in one workspace, autonomous TutorBots, and a knowledge hub that grows with you.
- - generic [ref=e25]:
- - link "Get Started" [ref=e26] [cursor=pointer]:
- - /url: /docs/get-started/
- - link "View on GitHub" [ref=e27] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - text: View on GitHub
- - img [ref=e28]
- - generic [ref=e30]:
- - generic [ref=e31]:
- - strong [ref=e32]: Apache 2.0
- - text: · MIT-style permissive
- - generic [ref=e33]: ·
- - generic [ref=e34]:
- - text: Built at
- - strong [ref=e35]: HKU Data Intelligence Lab
- - generic [ref=e36]: ·
- - generic [ref=e37]: Python 3.11 · Next.js 16
- - generic [ref=e39]:
- - generic [ref=e44]: DeepTutor — Chat Workspace
- - img "DeepTutor chat workspace — Chat / TutorBot / Co-Writer / Book / Knowledge / Space / Memory in the sidebar; greeting and composer in the main area." [ref=e45]
- - generic [ref=e46]:
- - generic [ref=e47]: § I
- - generic [ref=e48]:
- - generic [ref=e49]: What's inside
- - heading "Six pillars, one running context." [level=2] [ref=e50]:
- - text: Six pillars,
- - emphasis [ref=e51]: one
- - text: running context.
- - paragraph [ref=e52]: Every surface reads from — and writes back to — the same memory, knowledge base, and tutor. Switching contexts no longer means losing your place.
- - generic [ref=e53]:
- - link "I Chat Workspace Five modes — Chat, Solve, Quiz, Research, Visualize — share one session, knowledge base, and citation history. Escalate mid-thread without losing context." [ref=e54] [cursor=pointer]:
- - /url: /docs/explore/chat-workspace/
- - generic [ref=e55]: I
- - heading "Chat Workspace" [level=3] [ref=e56]
- - paragraph [ref=e57]: Five modes — Chat, Solve, Quiz, Research, Visualize — share one session, knowledge base, and citation history. Escalate mid-thread without losing context.
- - img [ref=e59]
- - link "II Co-Writer A split-view Markdown workbench where AI is a first-class collaborator. Select, rewrite, expand — grounded in your knowledge base." [ref=e61] [cursor=pointer]:
- - /url: /docs/explore/co-writer/
- - generic [ref=e62]: II
- - heading "Co-Writer" [level=3] [ref=e63]
- - paragraph [ref=e64]: A split-view Markdown workbench where AI is a first-class collaborator. Select, rewrite, expand — grounded in your knowledge base.
- - img [ref=e66]
- - link "III Book Engine A multi-agent pipeline compiles your materials into interactive living books — 13 block types, including a GeoGebra viewer and animations." [ref=e68] [cursor=pointer]:
- - /url: /docs/explore/book/
- - generic [ref=e69]: III
- - heading "Book Engine" [level=3] [ref=e70]
- - paragraph [ref=e71]: A multi-agent pipeline compiles your materials into interactive living books — 13 block types, including a GeoGebra viewer and animations.
- - img [ref=e73]
- - link "IV Knowledge Versioned RAG-ready document libraries on LlamaIndex end-to-end. Every (re-)index is tracked, comparable, and rollback-able." [ref=e75] [cursor=pointer]:
- - /url: /docs/explore/knowledge/
- - generic [ref=e76]: IV
- - heading "Knowledge" [level=3] [ref=e77]
- - paragraph [ref=e78]: Versioned RAG-ready document libraries on LlamaIndex end-to-end. Every (re-)index is tracked, comparable, and rollback-able.
- - img [ref=e80]
- - link "V Space Your personal library — chat history, notebooks, question bank, and authored skills. The read-and-review counterpart to every active surface." [ref=e82] [cursor=pointer]:
- - /url: /docs/explore/space/
- - generic [ref=e83]: V
- - heading "Space" [level=3] [ref=e84]
- - paragraph [ref=e85]: Your personal library — chat history, notebooks, question bank, and authored skills. The read-and-review counterpart to every active surface.
- - img [ref=e87]
- - link "VI Memory Append-only L1 traces, L2 curated facts with citations, L3 cross-surface synthesis. A Memory Graph lets you audit why DeepTutor knows what it knows." [ref=e89] [cursor=pointer]:
- - /url: /docs/explore/memory/
- - generic [ref=e90]: VI
- - heading "Memory" [level=3] [ref=e91]
- - paragraph [ref=e92]: Append-only L1 traces, L2 curated facts with citations, L3 cross-surface synthesis. A Memory Graph lets you audit why DeepTutor knows what it knows.
- - img [ref=e94]
- - generic [ref=e96]:
- - generic [ref=e97]: § II
- - generic [ref=e98]:
- - generic [ref=e99]: Install
- - heading "Up and running in minutes." [level=2] [ref=e100]:
- - text: Up and running in
- - emphasis [ref=e101]: minutes
- - text: .
- - paragraph [ref=e102]: Four ways to install — pick the one that fits. Every path lands at the same configured workspace.
- - generic [ref=e103]:
- - tablist [ref=e104]:
- - tab "$ pip install -U deeptutor PyPI" [selected] [ref=e105] [cursor=pointer]:
- - generic [ref=e106]: $
- - generic [ref=e107]: pip install -U deeptutor
- - generic [ref=e108]: PyPI
- - tab "$ docker run … ghcr.io/hkuds/deeptutor Docker" [ref=e109] [cursor=pointer]:
- - generic [ref=e110]: $
- - generic [ref=e111]: docker run … ghcr.io/hkuds/deeptutor
- - generic [ref=e112]: Docker
- - tab "$ git clone … && pip install -e . Source" [ref=e113] [cursor=pointer]:
- - generic [ref=e114]: $
- - generic [ref=e115]: git clone … && pip install -e .
- - generic [ref=e116]: Source
- - tab "$ pip install -e ./packaging/deeptutor-cli CLI" [ref=e117] [cursor=pointer]:
- - generic [ref=e118]: $
- - generic [ref=e119]: pip install -e ./packaging/deeptutor-cli
- - generic [ref=e120]: CLI
- - tabpanel [ref=e122]:
- - paragraph [ref=e123]: Smoothest path. Full local Web app + CLI, no clone required.
- - code [ref=e125]: "# 1. Create a workspace directory mkdir -p my-deeptutor && cd my-deeptutor # 2. Install, configure, launch pip install -U deeptutor deeptutor init deeptutor start"
- - generic [ref=e126]:
- - generic [ref=e127]: Then open 127.0.0.1:3782
- - link "Full guide" [ref=e128] [cursor=pointer]:
- - /url: /docs/get-started/pypi/
- - text: Full guide
- - img [ref=e129]
- - generic [ref=e131]:
- - generic [ref=e132]: § III
- - generic [ref=e133]:
- - generic [ref=e134]: Ecosystem
- - heading "Built alongside." [level=2] [ref=e135]:
- - text: Built
- - emphasis [ref=e136]: alongside
- - text: .
- - paragraph [ref=e137]: DeepTutor stands on a small family of open-source primitives from the HKU Data Intelligence Lab.
- - generic [ref=e138]:
- - link "nanobot Ultra-lightweight AI agent runtime" [ref=e139] [cursor=pointer]:
- - /url: https://github.com/HKUDS/nanobot
- - generic [ref=e140]: nanobot
- - generic [ref=e141]: Ultra-lightweight AI agent runtime
- - img [ref=e143]
- - link "LightRAG Simple, fast retrieval-augmented generation" [ref=e145] [cursor=pointer]:
- - /url: https://github.com/HKUDS/LightRAG
- - generic [ref=e146]: LightRAG
- - generic [ref=e147]: Simple, fast retrieval-augmented generation
- - img [ref=e149]
- - link "AutoAgent Zero-code agent framework" [ref=e151] [cursor=pointer]:
- - /url: https://github.com/HKUDS/AutoAgent
- - generic [ref=e152]: AutoAgent
- - generic [ref=e153]: Zero-code agent framework
- - img [ref=e155]
- - link "AI-Researcher Automated research workflows" [ref=e157] [cursor=pointer]:
- - /url: https://github.com/HKUDS/AI-Researcher
- - generic [ref=e158]: AI-Researcher
- - generic [ref=e159]: Automated research workflows
- - img [ref=e161]
- - generic [ref=e163]:
- - generic [ref=e164]:
- - link "DeepTutor" [ref=e165] [cursor=pointer]:
- - /url: /
- - generic [ref=e166]: DeepTutor
- - generic [ref=e167]:
- - generic [ref=e168]:
- - heading "Docs" [level=4] [ref=e169]
- - link "Get Started" [ref=e170] [cursor=pointer]:
- - /url: /docs/get-started/
- - link "Explore DeepTutor" [ref=e171] [cursor=pointer]:
- - /url: /docs/explore/
- - link "Explore TutorBot" [ref=e172] [cursor=pointer]:
- - /url: /docs/tutorbot/
- - link "CLI" [ref=e173] [cursor=pointer]:
- - /url: /docs/cli/
- - generic [ref=e174]:
- - heading "Community" [level=4] [ref=e175]
- - link "Discord" [ref=e176] [cursor=pointer]:
- - /url: https://discord.gg/eRsjPgMU4t
- - link "WeChat" [ref=e177] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues/78
- - link "Discussions" [ref=e178] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/discussions
- - link "Issues" [ref=e179] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues
- - generic [ref=e180]:
- - heading "Project" [level=4] [ref=e181]
- - link "GitHub" [ref=e182] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - link "License" [ref=e183] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/blob/main/LICENSE
- - link "arXiv" [ref=e184] [cursor=pointer]:
- - /url: https://arxiv.org/abs/2604.26962
- - generic [ref=e186]:
- - generic [ref=e187]:
- - text: © 2026
- - link "Data Intelligence Lab @ HKU" [ref=e188] [cursor=pointer]:
- - /url: https://github.com/HKUDS
- - generic [ref=e189]: Released under the Apache 2.0 License
\ No newline at end of file
diff --git a/.playwright-cli/page-2026-05-22T09-17-34-416Z.yml b/.playwright-cli/page-2026-05-22T09-17-34-416Z.yml
deleted file mode 100644
index cd9e5f633..000000000
--- a/.playwright-cli/page-2026-05-22T09-17-34-416Z.yml
+++ /dev/null
@@ -1,205 +0,0 @@
-- generic [active] [ref=e1]:
- - banner [ref=e2]:
- - generic [ref=e3]:
- - link "DeepTutor" [ref=e4] [cursor=pointer]:
- - /url: /zh-cn/
- - generic [ref=e5]: DeepTutor
- - navigation [ref=e6]:
- - link "文档" [ref=e7] [cursor=pointer]:
- - /url: /zh-cn/docs/
- - link "GitHub" [ref=e8] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - generic "偏好设置" [ref=e9]:
- - generic [ref=e10]:
- - generic [ref=e11]: 语言
- - combobox "语言" [ref=e12] [cursor=pointer]:
- - option "English"
- - option "简体中文" [selected]
- - generic [ref=e13]:
- - generic [ref=e14]: 主题
- - combobox "主题" [ref=e15] [cursor=pointer]:
- - option "自动" [selected]
- - option "浅色"
- - option "深色"
- - link "开始使用 →" [ref=e16] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/
- - main [ref=e17]:
- - generic [ref=e18]:
- - generic [ref=e19]: 开源 · v1.4.0-beta 已发布
- - img "DeepTutor" [ref=e21]
- - heading "个性化学习, 重新想象。" [level=1] [ref=e22]:
- - text: 个性化学习,
- - emphasis [ref=e23]: 重新想象。
- - paragraph [ref=e24]: 一个 agent-native 的学习伴侣 —— 五种模式共享一个工作区,自主 TutorBot, 以及和你一起成长的知识中枢。
- - generic [ref=e25]:
- - link "开始使用" [ref=e26] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/
- - link "在 GitHub 上查看" [ref=e27] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - text: 在 GitHub 上查看
- - img [ref=e28]
- - generic [ref=e30]:
- - generic [ref=e31]:
- - strong [ref=e32]: Apache 2.0
- - text: · 类 MIT 宽松协议
- - generic [ref=e33]: ·
- - generic [ref=e34]:
- - text: 由
- - strong [ref=e35]: 香港大学数据智能实验室
- - text: 构建
- - generic [ref=e36]: ·
- - generic [ref=e37]: Python 3.11 · Next.js 16
- - generic [ref=e39]:
- - generic [ref=e44]: DeepTutor —— 聊天工作台
- - img "DeepTutor 聊天工作台 —— 侧栏 Chat / TutorBot / Co-Writer / Book / 知识库 / Space / 记忆;主区域显示问候语和输入框。" [ref=e45]
- - generic [ref=e46]:
- - generic [ref=e47]: § I
- - generic [ref=e48]:
- - generic [ref=e49]: 里面是什么
- - heading "六根支柱,同一份运行时上下文。" [level=2] [ref=e50]:
- - text: 六根支柱,
- - emphasis [ref=e51]: 同一份
- - text: 运行时上下文。
- - paragraph [ref=e52]: 每个界面都从同一份记忆、知识库、导师那里读写。 切换上下文不再意味着丢失当前位置。
- - generic [ref=e53]:
- - link "I 聊天工作台 五种模式 —— Chat / Solve / Quiz / Research / Visualize —— 共享同一个 session、知识库和引用历史,对话中段切换不丢上下文。" [ref=e54] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/chat-workspace/
- - generic [ref=e55]: I
- - heading "聊天工作台" [level=3] [ref=e56]
- - paragraph [ref=e57]: 五种模式 —— Chat / Solve / Quiz / Research / Visualize —— 共享同一个 session、知识库和引用历史,对话中段切换不丢上下文。
- - img [ref=e59]
- - link "II Co-Writer 双栏 Markdown 工作台,AI 是一等公民协作者。选中、改写、扩展,全部基于你的知识库。" [ref=e61] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/co-writer/
- - generic [ref=e62]: II
- - heading "Co-Writer" [level=3] [ref=e63]
- - paragraph [ref=e64]: 双栏 Markdown 工作台,AI 是一等公民协作者。选中、改写、扩展,全部基于你的知识库。
- - img [ref=e66]
- - link "III Book Engine 多 agent 流水线把你的材料编成可交互的「活书」—— 13 种 block,含 GeoGebra viewer 和动画。" [ref=e68] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/book/
- - generic [ref=e69]: III
- - heading "Book Engine" [level=3] [ref=e70]
- - paragraph [ref=e71]: 多 agent 流水线把你的材料编成可交互的「活书」—— 13 种 block,含 GeoGebra viewer 和动画。
- - img [ref=e73]
- - link "IV 知识库 端到端 LlamaIndex 的带版本管理 RAG 文档库。每一次(重新)索引都可追溯、可对比、可回滚。" [ref=e75] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/knowledge/
- - generic [ref=e76]: IV
- - heading "知识库" [level=3] [ref=e77]
- - paragraph [ref=e78]: 端到端 LlamaIndex 的带版本管理 RAG 文档库。每一次(重新)索引都可追溯、可对比、可回滚。
- - img [ref=e80]
- - link "V Space 你的个人图书馆 —— chat history、notebook、question bank、自定义 skill。每个活跃界面的「阅读 / 回顾」对偶面。" [ref=e82] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/space/
- - generic [ref=e83]: V
- - heading "Space" [level=3] [ref=e84]
- - paragraph [ref=e85]: 你的个人图书馆 —— chat history、notebook、question bank、自定义 skill。每个活跃界面的「阅读 / 回顾」对偶面。
- - img [ref=e87]
- - link "VI 记忆系统 Append-only 的 L1 trace、带引用的 L2 精炼事实、跨界面综合的 L3。Memory Graph 让你随时审计 DeepTutor 为什么知道某件事。" [ref=e89] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/memory/
- - generic [ref=e90]: VI
- - heading "记忆系统" [level=3] [ref=e91]
- - paragraph [ref=e92]: Append-only 的 L1 trace、带引用的 L2 精炼事实、跨界面综合的 L3。Memory Graph 让你随时审计 DeepTutor 为什么知道某件事。
- - img [ref=e94]
- - generic [ref=e96]:
- - generic [ref=e97]: § II
- - generic [ref=e98]:
- - generic [ref=e99]: 安装
- - heading "几分钟就能跑起来。" [level=2] [ref=e100]:
- - text: 几
- - emphasis [ref=e101]: 分钟
- - text: 就能跑起来。
- - paragraph [ref=e102]: 四种安装方式 —— 挑一个适合你的。 最终都落到同一个配置好的工作区。
- - generic [ref=e103]:
- - tablist [ref=e104]:
- - tab "$ pip install -U deeptutor PyPI" [selected] [ref=e105] [cursor=pointer]:
- - generic [ref=e106]: $
- - generic [ref=e107]: pip install -U deeptutor
- - generic [ref=e108]: PyPI
- - tab "$ docker run … ghcr.io/hkuds/deeptutor Docker" [ref=e109] [cursor=pointer]:
- - generic [ref=e110]: $
- - generic [ref=e111]: docker run … ghcr.io/hkuds/deeptutor
- - generic [ref=e112]: Docker
- - tab "$ git clone … && pip install -e . 源码" [ref=e113] [cursor=pointer]:
- - generic [ref=e114]: $
- - generic [ref=e115]: git clone … && pip install -e .
- - generic [ref=e116]: 源码
- - tab "$ pip install -e ./packaging/deeptutor-cli CLI" [ref=e117] [cursor=pointer]:
- - generic [ref=e118]: $
- - generic [ref=e119]: pip install -e ./packaging/deeptutor-cli
- - generic [ref=e120]: CLI
- - tabpanel [ref=e122]:
- - paragraph [ref=e123]: 最顺滑的路径:完整本地 Web 应用 + CLI,无需 clone。
- - code [ref=e125]: "# 1. 准备一个工作区目录 mkdir -p my-deeptutor && cd my-deeptutor # 2. 安装、配置、启动 pip install -U deeptutor deeptutor init deeptutor start"
- - generic [ref=e126]:
- - generic [ref=e127]: 然后打开 127.0.0.1:3782
- - link "完整指南" [ref=e128] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/pypi/
- - text: 完整指南
- - img [ref=e129]
- - generic [ref=e131]:
- - generic [ref=e132]: § III
- - generic [ref=e133]:
- - generic [ref=e134]: 生态
- - heading "共同构建。" [level=2] [ref=e135]:
- - emphasis [ref=e136]: 共同构建
- - text: 。
- - paragraph [ref=e137]: DeepTutor 站在港大数据智能实验室 (HKU Data Intelligence Lab) 的一小组开源原语之上。
- - generic [ref=e138]:
- - link "nanobot 极简 AI agent 运行时" [ref=e139] [cursor=pointer]:
- - /url: https://github.com/HKUDS/nanobot
- - generic [ref=e140]: nanobot
- - generic [ref=e141]: 极简 AI agent 运行时
- - img [ref=e143]
- - link "LightRAG 简单、快速的检索增强生成" [ref=e145] [cursor=pointer]:
- - /url: https://github.com/HKUDS/LightRAG
- - generic [ref=e146]: LightRAG
- - generic [ref=e147]: 简单、快速的检索增强生成
- - img [ref=e149]
- - link "AutoAgent 零代码 agent 框架" [ref=e151] [cursor=pointer]:
- - /url: https://github.com/HKUDS/AutoAgent
- - generic [ref=e152]: AutoAgent
- - generic [ref=e153]: 零代码 agent 框架
- - img [ref=e155]
- - link "AI-Researcher 自动化研究工作流" [ref=e157] [cursor=pointer]:
- - /url: https://github.com/HKUDS/AI-Researcher
- - generic [ref=e158]: AI-Researcher
- - generic [ref=e159]: 自动化研究工作流
- - img [ref=e161]
- - generic [ref=e163]:
- - generic [ref=e164]:
- - link "DeepTutor" [ref=e165] [cursor=pointer]:
- - /url: /zh-cn/
- - generic [ref=e166]: DeepTutor
- - generic [ref=e167]:
- - generic [ref=e168]:
- - heading "文档" [level=4] [ref=e169]
- - link "快速上手" [ref=e170] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/
- - link "探索 DeepTutor" [ref=e171] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/
- - link "TutorBot 渠道" [ref=e172] [cursor=pointer]:
- - /url: /zh-cn/docs/tutorbot/
- - link "CLI" [ref=e173] [cursor=pointer]:
- - /url: /zh-cn/docs/cli/
- - generic [ref=e174]:
- - heading "社区" [level=4] [ref=e175]
- - link "Discord" [ref=e176] [cursor=pointer]:
- - /url: https://discord.gg/eRsjPgMU4t
- - link "微信社区" [ref=e177] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues/78
- - link "讨论区" [ref=e178] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/discussions
- - link "Issues" [ref=e179] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues
- - generic [ref=e180]:
- - heading "项目" [level=4] [ref=e181]
- - link "GitHub" [ref=e182] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - link "协议" [ref=e183] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/blob/main/LICENSE
- - link "arXiv" [ref=e184] [cursor=pointer]:
- - /url: https://arxiv.org/abs/2604.26962
- - generic [ref=e186]:
- - generic [ref=e187]:
- - text: © 2026
- - link "港大数据智能实验室" [ref=e188] [cursor=pointer]:
- - /url: https://github.com/HKUDS
- - generic [ref=e189]: 基于 Apache 2.0 协议发布
\ No newline at end of file
diff --git a/.playwright-cli/page-2026-05-22T09-17-50-672Z.yml b/.playwright-cli/page-2026-05-22T09-17-50-672Z.yml
deleted file mode 100644
index a86fc7be6..000000000
--- a/.playwright-cli/page-2026-05-22T09-17-50-672Z.yml
+++ /dev/null
@@ -1,205 +0,0 @@
-- generic [active] [ref=e1]:
- - banner [ref=e2]:
- - generic [ref=e3]:
- - link "DeepTutor" [ref=e4] [cursor=pointer]:
- - /url: /zh-cn/
- - generic [ref=e5]: DeepTutor
- - navigation [ref=e6]:
- - link "文档" [ref=e7] [cursor=pointer]:
- - /url: /zh-cn/docs/
- - link "GitHub" [ref=e8] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - generic "偏好设置" [ref=e9]:
- - generic [ref=e10]:
- - generic [ref=e11]: 语言
- - combobox "语言" [ref=e12] [cursor=pointer]:
- - option "English"
- - option "简体中文" [selected]
- - generic [ref=e13]:
- - generic [ref=e14]: 主题
- - combobox "主题" [ref=e15] [cursor=pointer]:
- - option "自动"
- - option "浅色"
- - option "深色" [selected]
- - link "开始使用 →" [ref=e16] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/
- - main [ref=e17]:
- - generic [ref=e18]:
- - generic [ref=e19]: 开源 · v1.4.0-beta 已发布
- - img "DeepTutor" [ref=e21]
- - heading "个性化学习, 重新想象。" [level=1] [ref=e22]:
- - text: 个性化学习,
- - emphasis [ref=e23]: 重新想象。
- - paragraph [ref=e24]: 一个 agent-native 的学习伴侣 —— 五种模式共享一个工作区,自主 TutorBot, 以及和你一起成长的知识中枢。
- - generic [ref=e25]:
- - link "开始使用" [ref=e26] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/
- - link "在 GitHub 上查看" [ref=e27] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - text: 在 GitHub 上查看
- - img [ref=e28]
- - generic [ref=e30]:
- - generic [ref=e31]:
- - strong [ref=e32]: Apache 2.0
- - text: · 类 MIT 宽松协议
- - generic [ref=e33]: ·
- - generic [ref=e34]:
- - text: 由
- - strong [ref=e35]: 香港大学数据智能实验室
- - text: 构建
- - generic [ref=e36]: ·
- - generic [ref=e37]: Python 3.11 · Next.js 16
- - generic [ref=e39]:
- - generic [ref=e44]: DeepTutor —— 聊天工作台
- - img "DeepTutor 聊天工作台 —— 侧栏 Chat / TutorBot / Co-Writer / Book / 知识库 / Space / 记忆;主区域显示问候语和输入框。" [ref=e45]
- - generic [ref=e46]:
- - generic [ref=e47]: § I
- - generic [ref=e48]:
- - generic [ref=e49]: 里面是什么
- - heading "六根支柱,同一份运行时上下文。" [level=2] [ref=e50]:
- - text: 六根支柱,
- - emphasis [ref=e51]: 同一份
- - text: 运行时上下文。
- - paragraph [ref=e52]: 每个界面都从同一份记忆、知识库、导师那里读写。 切换上下文不再意味着丢失当前位置。
- - generic [ref=e53]:
- - link "I 聊天工作台 五种模式 —— Chat / Solve / Quiz / Research / Visualize —— 共享同一个 session、知识库和引用历史,对话中段切换不丢上下文。" [ref=e54] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/chat-workspace/
- - generic [ref=e55]: I
- - heading "聊天工作台" [level=3] [ref=e56]
- - paragraph [ref=e57]: 五种模式 —— Chat / Solve / Quiz / Research / Visualize —— 共享同一个 session、知识库和引用历史,对话中段切换不丢上下文。
- - img [ref=e59]
- - link "II Co-Writer 双栏 Markdown 工作台,AI 是一等公民协作者。选中、改写、扩展,全部基于你的知识库。" [ref=e61] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/co-writer/
- - generic [ref=e62]: II
- - heading "Co-Writer" [level=3] [ref=e63]
- - paragraph [ref=e64]: 双栏 Markdown 工作台,AI 是一等公民协作者。选中、改写、扩展,全部基于你的知识库。
- - img [ref=e66]
- - link "III Book Engine 多 agent 流水线把你的材料编成可交互的「活书」—— 13 种 block,含 GeoGebra viewer 和动画。" [ref=e68] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/book/
- - generic [ref=e69]: III
- - heading "Book Engine" [level=3] [ref=e70]
- - paragraph [ref=e71]: 多 agent 流水线把你的材料编成可交互的「活书」—— 13 种 block,含 GeoGebra viewer 和动画。
- - img [ref=e73]
- - link "IV 知识库 端到端 LlamaIndex 的带版本管理 RAG 文档库。每一次(重新)索引都可追溯、可对比、可回滚。" [ref=e75] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/knowledge/
- - generic [ref=e76]: IV
- - heading "知识库" [level=3] [ref=e77]
- - paragraph [ref=e78]: 端到端 LlamaIndex 的带版本管理 RAG 文档库。每一次(重新)索引都可追溯、可对比、可回滚。
- - img [ref=e80]
- - link "V Space 你的个人图书馆 —— chat history、notebook、question bank、自定义 skill。每个活跃界面的「阅读 / 回顾」对偶面。" [ref=e82] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/space/
- - generic [ref=e83]: V
- - heading "Space" [level=3] [ref=e84]
- - paragraph [ref=e85]: 你的个人图书馆 —— chat history、notebook、question bank、自定义 skill。每个活跃界面的「阅读 / 回顾」对偶面。
- - img [ref=e87]
- - link "VI 记忆系统 Append-only 的 L1 trace、带引用的 L2 精炼事实、跨界面综合的 L3。Memory Graph 让你随时审计 DeepTutor 为什么知道某件事。" [ref=e89] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/memory/
- - generic [ref=e90]: VI
- - heading "记忆系统" [level=3] [ref=e91]
- - paragraph [ref=e92]: Append-only 的 L1 trace、带引用的 L2 精炼事实、跨界面综合的 L3。Memory Graph 让你随时审计 DeepTutor 为什么知道某件事。
- - img [ref=e94]
- - generic [ref=e96]:
- - generic [ref=e97]: § II
- - generic [ref=e98]:
- - generic [ref=e99]: 安装
- - heading "几分钟就能跑起来。" [level=2] [ref=e100]:
- - text: 几
- - emphasis [ref=e101]: 分钟
- - text: 就能跑起来。
- - paragraph [ref=e102]: 四种安装方式 —— 挑一个适合你的。 最终都落到同一个配置好的工作区。
- - generic [ref=e103]:
- - tablist [ref=e104]:
- - tab "$ pip install -U deeptutor PyPI" [selected] [ref=e105] [cursor=pointer]:
- - generic [ref=e106]: $
- - generic [ref=e107]: pip install -U deeptutor
- - generic [ref=e108]: PyPI
- - tab "$ docker run … ghcr.io/hkuds/deeptutor Docker" [ref=e109] [cursor=pointer]:
- - generic [ref=e110]: $
- - generic [ref=e111]: docker run … ghcr.io/hkuds/deeptutor
- - generic [ref=e112]: Docker
- - tab "$ git clone … && pip install -e . 源码" [ref=e113] [cursor=pointer]:
- - generic [ref=e114]: $
- - generic [ref=e115]: git clone … && pip install -e .
- - generic [ref=e116]: 源码
- - tab "$ pip install -e ./packaging/deeptutor-cli CLI" [ref=e117] [cursor=pointer]:
- - generic [ref=e118]: $
- - generic [ref=e119]: pip install -e ./packaging/deeptutor-cli
- - generic [ref=e120]: CLI
- - tabpanel [ref=e122]:
- - paragraph [ref=e123]: 最顺滑的路径:完整本地 Web 应用 + CLI,无需 clone。
- - code [ref=e125]: "# 1. 准备一个工作区目录 mkdir -p my-deeptutor && cd my-deeptutor # 2. 安装、配置、启动 pip install -U deeptutor deeptutor init deeptutor start"
- - generic [ref=e126]:
- - generic [ref=e127]: 然后打开 127.0.0.1:3782
- - link "完整指南" [ref=e128] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/pypi/
- - text: 完整指南
- - img [ref=e129]
- - generic [ref=e131]:
- - generic [ref=e132]: § III
- - generic [ref=e133]:
- - generic [ref=e134]: 生态
- - heading "共同构建。" [level=2] [ref=e135]:
- - emphasis [ref=e136]: 共同构建
- - text: 。
- - paragraph [ref=e137]: DeepTutor 站在港大数据智能实验室 (HKU Data Intelligence Lab) 的一小组开源原语之上。
- - generic [ref=e138]:
- - link "nanobot 极简 AI agent 运行时" [ref=e139] [cursor=pointer]:
- - /url: https://github.com/HKUDS/nanobot
- - generic [ref=e140]: nanobot
- - generic [ref=e141]: 极简 AI agent 运行时
- - img [ref=e143]
- - link "LightRAG 简单、快速的检索增强生成" [ref=e145] [cursor=pointer]:
- - /url: https://github.com/HKUDS/LightRAG
- - generic [ref=e146]: LightRAG
- - generic [ref=e147]: 简单、快速的检索增强生成
- - img [ref=e149]
- - link "AutoAgent 零代码 agent 框架" [ref=e151] [cursor=pointer]:
- - /url: https://github.com/HKUDS/AutoAgent
- - generic [ref=e152]: AutoAgent
- - generic [ref=e153]: 零代码 agent 框架
- - img [ref=e155]
- - link "AI-Researcher 自动化研究工作流" [ref=e157] [cursor=pointer]:
- - /url: https://github.com/HKUDS/AI-Researcher
- - generic [ref=e158]: AI-Researcher
- - generic [ref=e159]: 自动化研究工作流
- - img [ref=e161]
- - generic [ref=e163]:
- - generic [ref=e164]:
- - link "DeepTutor" [ref=e165] [cursor=pointer]:
- - /url: /zh-cn/
- - generic [ref=e166]: DeepTutor
- - generic [ref=e167]:
- - generic [ref=e168]:
- - heading "文档" [level=4] [ref=e169]
- - link "快速上手" [ref=e170] [cursor=pointer]:
- - /url: /zh-cn/docs/get-started/
- - link "探索 DeepTutor" [ref=e171] [cursor=pointer]:
- - /url: /zh-cn/docs/explore/
- - link "TutorBot 渠道" [ref=e172] [cursor=pointer]:
- - /url: /zh-cn/docs/tutorbot/
- - link "CLI" [ref=e173] [cursor=pointer]:
- - /url: /zh-cn/docs/cli/
- - generic [ref=e174]:
- - heading "社区" [level=4] [ref=e175]
- - link "Discord" [ref=e176] [cursor=pointer]:
- - /url: https://discord.gg/eRsjPgMU4t
- - link "微信社区" [ref=e177] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues/78
- - link "讨论区" [ref=e178] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/discussions
- - link "Issues" [ref=e179] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues
- - generic [ref=e180]:
- - heading "项目" [level=4] [ref=e181]
- - link "GitHub" [ref=e182] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - link "协议" [ref=e183] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/blob/main/LICENSE
- - link "arXiv" [ref=e184] [cursor=pointer]:
- - /url: https://arxiv.org/abs/2604.26962
- - generic [ref=e186]:
- - generic [ref=e187]:
- - text: © 2026
- - link "港大数据智能实验室" [ref=e188] [cursor=pointer]:
- - /url: https://github.com/HKUDS
- - generic [ref=e189]: 基于 Apache 2.0 协议发布
\ No newline at end of file
diff --git a/.playwright-cli/page-2026-05-22T09-18-05-984Z.yml b/.playwright-cli/page-2026-05-22T09-18-05-984Z.yml
deleted file mode 100644
index 7d6893c19..000000000
--- a/.playwright-cli/page-2026-05-22T09-18-05-984Z.yml
+++ /dev/null
@@ -1,286 +0,0 @@
-- generic [active] [ref=e1]:
- - link "Skip to content" [ref=e2] [cursor=pointer]:
- - /url: "#_top"
- - generic [ref=e3]:
- - banner [ref=e4]:
- - generic [ref=e5]:
- - link "DeepTutor" [ref=e7] [cursor=pointer]:
- - /url: /
- - generic [ref=e8]: DeepTutor
- - button "Search" [ref=e11] [cursor=pointer]:
- - img [ref=e12]
- - generic [ref=e14]: Search
- - generic [ref=e15]:
- - generic [ref=e16]: ⌘
- - generic [ref=e17]: K
- - generic [ref=e18]:
- - generic [ref=e20]:
- - link "Report issue" [ref=e21] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues/new?template=docs.yml&page=https%3A%2F%2Fdeeptutor.info%2Fdocs%2F
- - img [ref=e22]
- - generic [ref=e24]: Report issue
- - link "GitHub" [ref=e25] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - generic [ref=e26]: GitHub
- - img [ref=e27]
- - link "Discord" [ref=e29] [cursor=pointer]:
- - /url: https://discord.gg/eRsjPgMU4t
- - generic [ref=e30]: Discord
- - img [ref=e31]
- - link "WeChat community" [ref=e33] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues/78
- - img [ref=e34]
- - generic [ref=e37]:
- - generic [ref=e38]: Select theme
- - img
- - combobox "Select theme" [ref=e39] [cursor=pointer]:
- - option "Dark" [selected]
- - option "Light"
- - option "Auto"
- - img
- - generic [ref=e41]:
- - generic [ref=e42]: Select language
- - img
- - combobox "Select language" [ref=e43] [cursor=pointer]:
- - option "English" [selected]
- - option "简体中文"
- - img
- - navigation "Main":
- - list [ref=e47]:
- - listitem [ref=e48]:
- - group [ref=e49]:
- - generic "Overview" [ref=e50] [cursor=pointer]:
- - generic [ref=e51]: Overview
- - img [ref=e52]
- - list [ref=e54]:
- - listitem [ref=e55]:
- - link "Documentation home" [ref=e56] [cursor=pointer]:
- - /url: /docs/
- - listitem [ref=e57]:
- - link "Contributing" [ref=e58] [cursor=pointer]:
- - /url: /docs/contributing/
- - listitem [ref=e59]:
- - group [ref=e60]:
- - generic "Get Started" [ref=e61] [cursor=pointer]:
- - generic [ref=e62]: Get Started
- - img [ref=e63]
- - list [ref=e65]:
- - listitem [ref=e66]:
- - link "Overview" [ref=e67] [cursor=pointer]:
- - /url: /docs/get-started/
- - listitem [ref=e68]:
- - link "1 · Install from PyPI" [ref=e69] [cursor=pointer]:
- - /url: /docs/get-started/pypi/
- - listitem [ref=e70]:
- - link "2 · Install from Source" [ref=e71] [cursor=pointer]:
- - /url: /docs/get-started/from-source/
- - listitem [ref=e72]:
- - link "3 · Docker" [ref=e73] [cursor=pointer]:
- - /url: /docs/get-started/docker/
- - listitem [ref=e74]:
- - link "4 · CLI-Only Install" [ref=e75] [cursor=pointer]:
- - /url: /docs/get-started/cli-only/
- - listitem [ref=e76]:
- - link "Multi-User Deployment" [ref=e77] [cursor=pointer]:
- - /url: /docs/get-started/multi-user/
- - listitem [ref=e78]:
- - link "Providers" [ref=e79] [cursor=pointer]:
- - /url: /docs/get-started/providers/
- - listitem [ref=e80]:
- - link "Troubleshooting" [ref=e81] [cursor=pointer]:
- - /url: /docs/get-started/troubleshooting/
- - listitem [ref=e82]:
- - group [ref=e83]:
- - generic "Explore DeepTutor" [ref=e84] [cursor=pointer]:
- - generic [ref=e85]: Explore DeepTutor
- - img [ref=e86]
- - list [ref=e88]:
- - listitem [ref=e89]:
- - link "Overview" [ref=e90] [cursor=pointer]:
- - /url: /docs/explore/
- - listitem [ref=e91]:
- - link "Chat Workspace" [ref=e92] [cursor=pointer]:
- - /url: /docs/explore/chat-workspace/
- - listitem [ref=e93]:
- - link "Co-Writer" [ref=e94] [cursor=pointer]:
- - /url: /docs/explore/co-writer/
- - listitem [ref=e95]:
- - link "Book Engine" [ref=e96] [cursor=pointer]:
- - /url: /docs/explore/book/
- - listitem [ref=e97]:
- - link "Knowledge" [ref=e98] [cursor=pointer]:
- - /url: /docs/explore/knowledge/
- - listitem [ref=e99]:
- - link "Space" [ref=e100] [cursor=pointer]:
- - /url: /docs/explore/space/
- - listitem [ref=e101]:
- - link "Memory" [ref=e102] [cursor=pointer]:
- - /url: /docs/explore/memory/
- - listitem [ref=e103]:
- - link "Settings" [ref=e104] [cursor=pointer]:
- - /url: /docs/explore/settings/
- - listitem [ref=e105]:
- - group [ref=e106]:
- - generic "Explore TutorBot" [ref=e107] [cursor=pointer]:
- - generic [ref=e108]: Explore TutorBot
- - img [ref=e109]
- - list [ref=e111]:
- - listitem [ref=e112]:
- - link "Overview" [ref=e113] [cursor=pointer]:
- - /url: /docs/tutorbot/
- - listitem [ref=e114]:
- - link "Telegram" [ref=e115] [cursor=pointer]:
- - /url: /docs/tutorbot/telegram/
- - listitem [ref=e116]:
- - link "Discord" [ref=e117] [cursor=pointer]:
- - /url: /docs/tutorbot/discord/
- - listitem [ref=e118]:
- - link "Slack" [ref=e119] [cursor=pointer]:
- - /url: /docs/tutorbot/slack/
- - listitem [ref=e120]:
- - link "Matrix" [ref=e121] [cursor=pointer]:
- - /url: /docs/tutorbot/matrix/
- - listitem [ref=e122]:
- - link "Zulip" [ref=e123] [cursor=pointer]:
- - /url: /docs/tutorbot/zulip/
- - listitem [ref=e124]:
- - link "Feishu / Lark" [ref=e125] [cursor=pointer]:
- - /url: /docs/tutorbot/feishu/
- - listitem [ref=e126]:
- - link "WeCom" [ref=e127] [cursor=pointer]:
- - /url: /docs/tutorbot/wecom/
- - listitem [ref=e128]:
- - link "DingTalk" [ref=e129] [cursor=pointer]:
- - /url: /docs/tutorbot/dingtalk/
- - listitem [ref=e130]:
- - link "QQ" [ref=e131] [cursor=pointer]:
- - /url: /docs/tutorbot/qq/
- - listitem [ref=e132]:
- - link "WhatsApp" [ref=e133] [cursor=pointer]:
- - /url: /docs/tutorbot/whatsapp/
- - listitem [ref=e134]:
- - link "Email" [ref=e135] [cursor=pointer]:
- - /url: /docs/tutorbot/email/
- - listitem [ref=e136]:
- - link "Mochat" [ref=e137] [cursor=pointer]:
- - /url: /docs/tutorbot/mochat/
- - listitem [ref=e138]:
- - group [ref=e139]:
- - generic "DeepTutor CLI" [ref=e140] [cursor=pointer]:
- - generic [ref=e141]: DeepTutor CLI
- - img [ref=e142]
- - list [ref=e144]:
- - listitem [ref=e145]:
- - link "Overview" [ref=e146] [cursor=pointer]:
- - /url: /docs/cli/
- - listitem [ref=e147]:
- - link "Command Reference" [ref=e148] [cursor=pointer]:
- - /url: /docs/cli/commands/
- - listitem [ref=e149]:
- - link "Interactive REPL" [ref=e150] [cursor=pointer]:
- - /url: /docs/cli/chat-repl/
- - listitem [ref=e151]:
- - link "Agent Handoff" [ref=e152] [cursor=pointer]:
- - /url: /docs/cli/agent-handoff/
- - listitem [ref=e153]:
- - link "Server API" [ref=e154] [cursor=pointer]:
- - /url: /docs/cli/server-api/
- - generic [ref=e156]:
- - complementary [ref=e157]:
- - navigation "On this page" [ref=e162]:
- - heading "On this page" [level=2] [ref=e163]
- - list [ref=e164]:
- - listitem [ref=e165]:
- - link "Overview" [ref=e166] [cursor=pointer]:
- - /url: "#_top"
- - listitem [ref=e167]:
- - link "Where to start" [ref=e168] [cursor=pointer]:
- - /url: "#where-to-start"
- - listitem [ref=e169]:
- - link "What is DeepTutor" [ref=e170] [cursor=pointer]:
- - /url: "#what-is-deeptutor"
- - listitem [ref=e171]:
- - link "Help & community" [ref=e172] [cursor=pointer]:
- - /url: "#help--community"
- - main [ref=e174]:
- - heading "Documentation" [level=1] [ref=e177]
- - generic [ref=e179]:
- - generic [ref=e180]:
- - paragraph [ref=e181]: Welcome to the DeepTutor documentation. Pick a path below, or use the left sidebar.
- - generic [ref=e182]:
- - heading "Where to start" [level=2] [ref=e183]
- - link "Section titled “Where to start”" [ref=e184] [cursor=pointer]:
- - /url: "#where-to-start"
- - img [ref=e186]
- - generic [ref=e188]: Section titled “Where to start”
- - list [ref=e189]:
- - listitem [ref=e190]:
- - strong [ref=e191]:
- - link "Get Started" [ref=e192] [cursor=pointer]:
- - /url: /docs/get-started/
- - text: "— Four install paths: PyPI, From Source, Docker, CLI-Only."
- - listitem [ref=e193]:
- - strong [ref=e194]:
- - link "Explore DeepTutor" [ref=e195] [cursor=pointer]:
- - /url: /docs/explore/
- - text: — Tour the five core surfaces (Chat, Co-Writer, Book, Knowledge, Space) plus Memory and Settings.
- - listitem [ref=e196]:
- - strong [ref=e197]:
- - link "Explore TutorBot" [ref=e198] [cursor=pointer]:
- - /url: /docs/tutorbot/
- - text: — Connect persistent AI tutors to Telegram, Slack, Feishu, Matrix, and more.
- - listitem [ref=e199]:
- - strong [ref=e200]:
- - link "DeepTutor CLI" [ref=e201] [cursor=pointer]:
- - /url: /docs/cli/
- - text: — Drive every capability from the terminal, or hand it to an AI agent.
- - listitem [ref=e202]:
- - strong [ref=e203]:
- - link "Providers" [ref=e204] [cursor=pointer]:
- - /url: /docs/get-started/providers/
- - text: — Set up LLM, embedding, and search providers.
- - generic [ref=e205]:
- - heading "What is DeepTutor" [level=2] [ref=e206]
- - link "Section titled “What is DeepTutor”" [ref=e207] [cursor=pointer]:
- - /url: "#what-is-deeptutor"
- - img [ref=e209]
- - generic [ref=e211]: Section titled “What is DeepTutor”
- - paragraph [ref=e212]:
- - text: An open-source, agent-native learning companion.
- - strong [ref=e213]: Five modes
- - text: (Chat, Solve, Quiz, Research, Visualize) share one session, knowledge base, and citation history.
- - strong [ref=e214]: TutorBots
- - text: carry your context out to Telegram, Slack, Feishu, and other channels. A
- - strong [ref=e215]: three-layer Memory
- - text: with an inspectable workbench and a Memory Graph lets you audit
- - emphasis [ref=e216]: why
- - text: the system knows what it knows.
- - paragraph [ref=e217]: Built at HKU Data Intelligence Lab. Apache 2.0 license.
- - generic [ref=e218]:
- - heading "Help & community" [level=2] [ref=e219]
- - link "Section titled “Help & community”" [ref=e220] [cursor=pointer]:
- - /url: "#help--community"
- - img [ref=e222]
- - generic [ref=e224]: Section titled “Help & community”
- - list [ref=e225]:
- - listitem [ref=e226]:
- - link "Discord" [ref=e227] [cursor=pointer]:
- - /url: https://discord.gg/eRsjPgMU4t
- - text: — fastest place to ask questions
- - listitem [ref=e228]:
- - link "GitHub Discussions" [ref=e229] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/discussions
- - text: — long-form Q&A and design proposals
- - listitem [ref=e230]:
- - link "Issue tracker" [ref=e231] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues
- - text: — bug reports and feature requests
- - listitem [ref=e232]:
- - link "SKILL.md" [ref=e233] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/blob/main/SKILL.md
- - text: — the canonical handover document for AI agents driving DeepTutor
- - link "Next Contributing →" [ref=e236] [cursor=pointer]:
- - /url: /docs/contributing/
- - generic [ref=e237]:
- - text: Next
- - generic [ref=e238]: Contributing →
\ No newline at end of file
diff --git a/.playwright-cli/page-2026-05-22T09-20-16-418Z.yml b/.playwright-cli/page-2026-05-22T09-20-16-418Z.yml
deleted file mode 100644
index 003fbaef4..000000000
--- a/.playwright-cli/page-2026-05-22T09-20-16-418Z.yml
+++ /dev/null
@@ -1,51 +0,0 @@
-- generic [active] [ref=e1]:
- - link "Skip to content" [ref=e2] [cursor=pointer]:
- - /url: "#_top"
- - generic [ref=e3]:
- - banner [ref=e4]:
- - generic [ref=e5]:
- - link "DeepTutor" [ref=e7] [cursor=pointer]:
- - /url: /
- - generic [ref=e8]: DeepTutor
- - button "Search" [ref=e11] [cursor=pointer]:
- - img [ref=e12]
- - generic [ref=e14]: Search
- - generic [ref=e15]:
- - generic [ref=e16]: ⌘
- - generic [ref=e17]: K
- - generic [ref=e18]:
- - generic [ref=e20]:
- - link "Report issue" [ref=e21] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues/new?template=docs.yml&page=https%3A%2F%2Fdeeptutor.info%2F404%2F
- - img [ref=e22]
- - generic [ref=e24]: Report issue
- - link "GitHub" [ref=e25] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor
- - generic [ref=e26]: GitHub
- - img [ref=e27]
- - link "Discord" [ref=e29] [cursor=pointer]:
- - /url: https://discord.gg/eRsjPgMU4t
- - generic [ref=e30]: Discord
- - img [ref=e31]
- - link "WeChat community" [ref=e33] [cursor=pointer]:
- - /url: https://github.com/HKUDS/DeepTutor/issues/78
- - img [ref=e34]
- - generic [ref=e37]:
- - generic [ref=e38]: Select theme
- - img
- - combobox "Select theme" [ref=e39] [cursor=pointer]:
- - option "Dark" [selected]
- - option "Light"
- - option "Auto"
- - img
- - generic [ref=e41]:
- - generic [ref=e42]: Select language
- - img
- - combobox "Select language" [ref=e43] [cursor=pointer]:
- - option "English"
- - option "简体中文" [selected]
- - img
- - main [ref=e47]:
- - generic [ref=e52]:
- - heading "404" [level=1] [ref=e53]
- - generic [ref=e54]: Page not found. Check the URL or try using the search bar.
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
index 890909e16..582924651 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,9 +2,10 @@
## Overview
-DeepTutor is an **agent-native** intelligent learning companion built around
-a two-layer plugin model (Tools + Capabilities) with three entry points:
-CLI, WebSocket API, and Python SDK.
+DeepTutor is an **agent-native** intelligent learning companion organized
+around a two-layer plugin model — single-shot **Tools** invoked by the
+LLM, and multi-stage **Capabilities** that take over a turn — exposed
+through three entry points: CLI, WebSocket API, and Python SDK.
## Architecture
@@ -13,8 +14,8 @@ Entry Points: CLI (Typer) | WebSocket /api/v1/ws | Python SDK
↓ ↓ ↓
┌─────────────────────────────────────────────────┐
│ ChatOrchestrator │
- │ routes to ChatCapability (default) │
- │ or a selected deep Capability │
+ │ routes UnifiedContext → selected Capability │
+ │ (defaults to `chat`) │
└──────────┬──────────────┬───────────────────────┘
│ │
┌──────────▼──┐ ┌────────▼──────────┐
@@ -23,122 +24,90 @@ Entry Points: CLI (Typer) | WebSocket /api/v1/ws | Python SDK
└──────────────┘ └────────────────────┘
```
-### Level 1 — Tools
+All capabilities emit on a shared `StreamBus`; the orchestrator fans
+events out to consumers. Runtime settings live in
+`data/user/settings/*.json` — project-root `.env` files are intentionally
+ignored.
-Lightweight single-function tools the LLM calls on demand:
+### Level 1 — Tools
-| Tool | Description |
-| ------------------- | ---------------------------------------------- |
-| `rag` | Knowledge base retrieval (RAG) |
-| `web_search` | Web search with citations |
-| `code_execution` | Sandboxed Python execution |
-| `reason` | Dedicated deep-reasoning LLM call |
-| `brainstorm` | Breadth-first idea exploration with rationale |
-| `paper_search` | arXiv academic paper search |
-| `geogebra_analysis` | Image → GeoGebra commands (4-stage vision pipeline) |
+Single-function tools the LLM picks on demand. The chat capability auto-mounts
+context-gated tools (rag, read_source, read_memory, write_memory, list_notebook,
+write_note, web_fetch, github, ask_user); five user-toggleable tools surface in
+`/settings/tools`:
-### Level 2 — Capabilities
+| Tool | Description |
+| ---------------- | -------------------------------------------------------- |
+| `brainstorm` | Breadth-first idea exploration with rationale |
+| `web_search` | Web search with citations |
+| `paper_search` | arXiv preprint search |
+| `code_execution` | Sandboxed Python (NL intent → code → run) |
+| `reason` | Dedicated deep-reasoning LLM call |
-Multi-step agent pipelines that take over the conversation:
+Always-on, context-gated tools: `rag`, `read_source`, `read_memory`,
+`write_memory`, `web_fetch`, `list_notebook`, `write_note`, `github`,
+`ask_user` (pauses the turn and resumes with the user's reply).
+`geogebra_analysis` is parked under `COMING_SOON_TOOL_TYPES`.
-| Capability | Stages |
-| ---------------- | ---------------------------------------------- |
-| `chat` | responding (default, tool-augmented) |
-| `deep_solve` | planning → reasoning → writing |
-| `deep_question` | ideation → evaluation → generation → validation |
+### Level 2 — Capabilities
-### Playground Plugins
+Multi-stage pipelines that own the turn:
-Extended features in `deeptutor/plugins/`:
+| Capability | Stages |
+| ---------------- | ----------------------------------------------------- |
+| `chat` | thinking → acting → observing → responding (agentic loop, default) |
+| `auto` | analyzing → delegating → synthesizing (routes to another capability) |
+| `deep_solve` | planning → reasoning → writing |
+| `deep_question` | ideation → generation |
+| `deep_research` | rephrasing → decomposing → researching → reporting |
+| `visualize` | analyzing → generating → reviewing (SVG / Chart.js / Mermaid / HTML; or routes to Manim sub-stages via `render_type`) |
+| `math_animator` | concept_analysis → concept_design → code_generation → code_retry → summary → render_output |
-| Plugin | Type | Description |
-| ----------------- | ---------- | ------------------------------------ |
-| `deep_research` | playground | Multi-agent research + reporting |
+All capabilities converge on `emit_capability_result()` in
+`deeptutor/capabilities/_shared.py` so every turn emits the same envelope
+(response payload + `cost_summary` from `UsageTracker`). Status copy and
+prompts are i18n'd via `capabilities/prompts/{en,zh}/<name>.yaml`.
## CLI Usage
```bash
-# Install full app or CLI-only
-pip install deeptutor
-# or: pip install deeptutor-cli
+# Install
+pip install deeptutor # Full app (CLI + Web/API + packaged Web assets)
+pip install deeptutor-cli # CLI-only
-# Run any capability (agent-first entry point)
+# Run any capability
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2=4" -t rag --kb my-kb
-deeptutor run deep_question "Linear algebra" --config num_questions=5
+deeptutor run auto "Animate sine wave" # picks the right capability
# Interactive REPL
deeptutor chat
# (inside the REPL: /regenerate or /retry re-runs the last user message)
-# Knowledge bases
+# Knowledge bases, memory, server
deeptutor kb list
deeptutor kb create my-kb --doc textbook.pdf
-
-# Plugins & memory
-deeptutor plugin list
deeptutor memory show
-
-# API server (included in `pip install deeptutor`)
deeptutor serve --port 8001
```
## Key Files
-| Path | Purpose |
-| ----------------------------- | ------------------------------------ |
-| `deeptutor/runtime/orchestrator.py` | ChatOrchestrator — unified entry |
-| `deeptutor/core/stream.py` | StreamEvent protocol |
-| `deeptutor/core/stream_bus.py` | Async event fan-out |
-| `deeptutor/core/tool_protocol.py` | BaseTool abstract class |
-| `deeptutor/core/capability_protocol.py` | BaseCapability abstract class |
-| `deeptutor/core/context.py` | UnifiedContext dataclass |
-| `deeptutor/runtime/registry/tool_registry.py` | Tool discovery & registration |
-| `deeptutor/runtime/registry/capability_registry.py` | Capability discovery & registration |
-| `deeptutor/runtime/mode.py` | RunMode (CLI vs SERVER) |
-| `deeptutor/capabilities/` | Built-in capability wrappers |
-| `deeptutor/tools/builtin/` | Built-in tool wrappers |
-| `deeptutor/plugins/` | Playground plugins |
-| `deeptutor/plugins/loader.py` | Plugin discovery from manifest.yaml |
-| `deeptutor_cli/main.py` | Typer CLI entry point |
-| `deeptutor/api/routers/unified_ws.py` | Unified WebSocket endpoint |
-
-## Plugin Development
-
-Create a directory under `deeptutor/plugins/<name>/` with:
-
-```
-manifest.yaml # name, version, type, description, stages
-capability.py # class extending BaseCapability
-```
-
-Minimal `manifest.yaml`:
-```yaml
-name: my_plugin
-version: 0.1.0
-type: playground
-description: "My custom plugin"
-stages: [step1, step2]
-```
-
-Minimal `capability.py`:
-```python
-from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
-from deeptutor.core.context import UnifiedContext
-from deeptutor.core.stream_bus import StreamBus
-
-class MyPlugin(BaseCapability):
- manifest = CapabilityManifest(
- name="my_plugin",
- description="My custom plugin",
- stages=["step1", "step2"],
- )
-
- async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
- async with stream.stage("step1", source=self.name):
- await stream.content("Working on step 1...", source=self.name)
- await stream.result({"response": "Done!"}, source=self.name)
-```
+| Path | Purpose |
+| ------------------------------------------ | ------------------------------------ |
+| `deeptutor/runtime/orchestrator.py` | `ChatOrchestrator` — unified entry |
+| `deeptutor/runtime/launcher.py` | Backend + frontend lifecycle / port discovery |
+| `deeptutor/runtime/registry/` | Tool + Capability registries |
+| `deeptutor/runtime/bootstrap/builtin_capabilities.py` | Built-in capability class paths |
+| `deeptutor/services/config/runtime_settings.py` | JSON settings + process-env overrides |
+| `deeptutor/core/stream.py`, `stream_bus.py` | StreamEvent protocol + async fan-out |
+| `deeptutor/core/tool_protocol.py` | `BaseTool` + `ToolDefinition` |
+| `deeptutor/core/capability_protocol.py` | `BaseCapability` + `CapabilityManifest` |
+| `deeptutor/core/context.py` | `UnifiedContext` dataclass |
+| `deeptutor/tools/builtin/__init__.py` | All built-in tool wrappers |
+| `deeptutor/capabilities/` | Built-in capability implementations |
+| `deeptutor_cli/main.py` | Typer CLI entry point |
+| `deeptutor/api/routers/unified_ws.py` | Unified WebSocket endpoint |
## Dependency Layers
@@ -151,7 +120,7 @@ pip install deeptutor-cli — CLI-only (LLM + RAG + providers + document parsin
pip install -e . — Source install for development
.[tutorbot] — Full app + TutorBot agent engine + channel SDKs
.[matrix] — Matrix channel for TutorBot (matrix-nio[e2e]; needs libolm)
-.[math-animator] — Manim addon (for `deeptutor animate`)
+.[math-animator] — Manim addon (powers `visualize` Manim renders + `deeptutor animate`)
.[dev] — Full app + test/lint tools
.[all] — Everything above
```
diff --git a/DeepTutor.code-workspace b/DeepTutor.code-workspace
deleted file mode 100644
index 57097327f..000000000
--- a/DeepTutor.code-workspace
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "folders": [
- {
- "path": "."
- }
- ],
- "settings": {}
-}
diff --git a/README.md b/README.md
index 764045f44..d87940a00 100644
--- a/README.md
+++ b/README.md
@@ -44,17 +44,19 @@
### 📦 Releases
+> **[2026.5.22]** [v1.4.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.0) — GA cut of v1.4: Auto Mode, three-layer Memory, agentic Deep Research / Solve / Question, LlamaIndex RAG refactor, Visualize/Animator merge, plus reasoning-effort normalization, tool-schema fallback, and restart-safe turn runtime.
+
> **[2026.5.21]** [v1.4.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.0-beta) — Three-layer Memory workbench (L1/L2/L3), every chat capability rebuilt on a single agentic engine, LlamaIndex-only RAG, and a unified Settings + Capabilities surface.
> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Remote Docker CORS recovery, `DISABLE_SSL_VERIFY` across SDK providers, safer code-block citations, and optional Matrix E2EE add-on.
> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot Zulip and NVIDIA NIM support, safer thinking-model routing, `deeptutor start`, sidebar tooltips, and session-store parity.
-> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Optional multi-user deployments with isolated user workspaces, admin grants, auth routes, and scoped runtime access.
-
<details>
<summary><b>Past releases (more than 2 weeks ago)</b></summary>
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Optional multi-user deployments with isolated user workspaces, admin grants, auth routes, and scoped runtime access.
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Thinking-model/provider fixes, visible Knowledge index history, and safer Co-Writer clear/template editing.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Catalog-based model selection for chat and TutorBot, safer RAG re-indexing, OpenAI Responses token-limit fixes, and Skills editor validation.
@@ -164,7 +166,7 @@
DeepTutor ships four installation paths. They all share one workspace layout: settings live in `data/user/settings/` under the directory you launch from (or under `DEEPTUTOR_HOME` / `deeptutor start --home` if you set one explicitly). For the full app, the recommended flow is **pick a workspace directory → install → `deeptutor init` → `deeptutor start`**.
-> 🧪 **Trying the v1.4.0 beta?** PyPI normalizes `1.4.0-beta` to `1.4.0b0`, so plain `pip install -U deeptutor` stays on stable. Opt in with `pip install --pre -U deeptutor`, or pin exactly with `pip install -U deeptutor==1.4.0b0`.
+> ✨ **v1.4.0 is live.** `pip install -U deeptutor` picks up the latest stable. Pre-releases (when available) opt in with `pip install --pre -U deeptutor`.
### Option 1 — Install From PyPI
diff --git a/assets/releases/ver1-4-0.md b/assets/releases/ver1-4-0.md
new file mode 100644
index 000000000..228ffa7ef
--- /dev/null
+++ b/assets/releases/ver1-4-0.md
@@ -0,0 +1,119 @@
+# DeepTutor v1.4.0 Release Notes
+
+**Release Date:** 2026.05.22
+
+v1.4.0 is the GA cut of the v1.4 line. It carries the full v1.4.0-beta scope
+(Auto Mode, three-layer Memory workbench, agentic Deep Research / Deep Solve /
+Question, LlamaIndex chat refactor, unified capabilities infrastructure +
+i18n, Visualize/Animator merge, new chat tools, settings split, multi-user
+isolation hardening, and the `deeptutor start` / `deeptutor init` launcher)
+and adds a focused set of agent-engine and runtime hardening fixes on top.
+For the full beta scope see [v1.4.0-beta](ver1-4-0-beta.md).
+
+## What's New Since v1.4.0-beta
+
+### Reasoning Effort + Provider Thinking Flags
+The agentic engine now normalizes "reasoning effort" across providers in one
+place, instead of each pipeline re-deriving it.
+
+- **`build_provider_extra_kwargs`** in `deeptutor/core/agentic/client.py`
+ resolves `reasoning_effort` against `provider_registry`, maps `minimal` /
+ `minimum` to the right wire shape (DashScope uses `minimum`), and routes
+ the on/off intent through provider thinking-style toggles —
+ `thinking_type` (DeepSeek), `enable_thinking` (Qwen-style), or
+ `reasoning_split`. Known reasoning models default to `high`; the
+ `deepseek-v4-flash` shape gets thinking disabled by default.
+- **`LLMClientConfig.reasoning_effort`** is plumbed end-to-end. All four
+ pipelines — agentic chat, question, research, solve — pass the binding +
+ effort into `build_completion_kwargs`, so a single user-level setting
+ controls reasoning behavior across capabilities.
+
+### Tool-Schema Fallback For Strict Providers
+Some OpenAI-compatible providers reject native function-calling schemas with
+a non-standard error. `run_labeled_step` now detects that case, strips
+`tools` / `tool_choice` from the request, retries once, and emits a warning
+progress event so the user knows the call ran in tool-less prose mode.
+Behavior is unchanged for providers that accept tool schemas normally.
+
+### Restart-Safe Turn Runtime
+A server or container restart used to leave the database row for an
+in-flight turn stuck on `running`, blocking the next message in that
+session and leaving the UI hanging on an event stream that would never
+complete.
+
+- **Orphan detection** — `TurnRuntimeManager` now checks whether this
+ process still owns the turn's in-memory runner. If not, the persisted
+ turn is marked `failed` with `"Turn interrupted by server restart.
+ Please retry your message."`
+- **`start_turn`** sweeps stale active turns for the session before
+ creating a new turn, so the user can immediately retry after a restart.
+- **`subscribe_turn`** synthesizes a terminal `error` + `done` event for
+ the orphaned turn so the frontend cleanly closes its streaming state
+ instead of waiting indefinitely.
+
+### Frontend API Base — Docker Placeholder Hardening
+`web/lib/api.ts` switched from exact-match to substring-token detection of
+the `NEXT_PUBLIC_API_BASE` placeholder, and exposes `isApiBasePlaceholder()`
+for reuse. This survives small changes to the Docker placeholder shape that
+previously slipped through and produced a blank Settings page with no
+visible error. The unused auto-generated `web/.env.local` shipped with the
+beta is removed.
+
+### LLM Config Probe — Clearer Status Copy
+The `/settings/llm` probe now emits an explicit "Basic LLM completion
+succeeded. Chat additionally validates streaming and provider tool
+compatibility at runtime." line after the smoke completion, so users know
+the probe deliberately doesn't cover the streaming / tool-call paths that
+chat exercises.
+
+### CLI Chat REPL — Config Surface Aligned With Docs
+The `deeptutor chat` REPL surface was tightened so it matches the public
+docs at [deeptutor.info](https://deeptutor.info).
+
+- `deeptutor chat --config key=value` and `--config-json '<json>'` seed
+ the initial config without entering the REPL first.
+- `/config set key value` and `/config set key=value` are both accepted;
+ JSON values (`[…]`, `{…}`) are parsed correctly via `shlex`.
+- Backslash-continuation lets you send multi-line prompts in one turn.
+- `/refs` prints a structured state snapshot (session, capability, tools,
+ KB, history, notebooks, language, config) instead of a single dim line.
+- `deeptutor plugin info <name>` now also returns `cli_aliases` and the
+ capability `availability` block.
+
+### Repo & Docs Hygiene
+- New issue template for the public docs site (`.github/ISSUE_TEMPLATE/docs.yml`).
+- `AGENTS.md` modernized to reflect Auto Mode, tool gating, and the
+ current capability stages.
+- `.gitignore` covers `.playwright-cli/`; stale `.playwright-cli/`
+ captures, `.env.example_CN`, and `DeepTutor.code-workspace` removed.
+
+## Tests
+- New `tests/core/test_agentic_client_provider_kwargs.py` covering the
+ reasoning-effort + provider thinking-style matrix.
+- New `tests/core/test_labeled_step_tool_fallback.py` exercising the
+ tool-schema retry path end-to-end against a scripted client.
+- `tests/services/session/test_turn_runtime_subscribe.py` adds coverage
+ for orphan-running-turn recovery on both subscribe and start_turn.
+- `tests/cli/test_chat_cli.py` adds REPL config/backslash tests and a
+ plugin-info contract check.
+- New `tests/cli/test_docs_contract.py` keeps the public site docs in
+ sync with the CLI surface (links + `deeptutor …` examples).
+- `tests/scripts/test_docker_compose.py` + `web/tests/api-resolve-base.test.ts`
+ cover the new placeholder detection.
+
+## Upgrade Notes
+- **From v1.4.0-beta:** drop-in. PyPI installs with `pip install -U deeptutor`
+ (PyPI normalizes `1.4.0` over `1.4.0b0`). Docker users pull
+ `ghcr.io/hkuds/deeptutor:latest`.
+- **Reasoning effort** is now read from `LLMConfig.reasoning_effort`. If
+ you previously set provider thinking flags manually in `extra_body`,
+ the agent will still respect them, but the recommended path is to set
+ `reasoning_effort` and let the engine map it.
+- **Restart recovery** is automatic. After upgrading, any existing
+ database rows stuck on `running` from previous crashes will be
+ finalized the next time their session is opened.
+- **Beta artifact cleanup:** `web/.env.local` was auto-generated by the
+ legacy launcher and is no longer needed. If you rebuilt the frontend
+ manually with that file, delete it before the next build.
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.4.0-beta...v1.4.0
diff --git a/deeptutor/__version__.py b/deeptutor/__version__.py
index aaab2524f..c82d232df 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 this
file directly.
"""
-__version__ = "1.4.0-beta"
+__version__ = "1.4.0"
__all__ = ("__version__",)
diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py
index b62e0a78d..b1e6a12db 100644
--- a/deeptutor/agents/_shared/tool_composition.py
+++ b/deeptutor/agents/_shared/tool_composition.py
@@ -26,7 +26,6 @@ from typing import Any
from deeptutor.tools.builtin import 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
@@ -135,7 +134,10 @@ def user_has_memory() -> bool:
from deeptutor.services.memory import get_memory_store
store = get_memory_store()
- return any(store.read_raw("L3", slot).strip() for slot in ("recent", "profile", "scope", "preferences"))
+ return any(
+ store.read_raw("L3", slot).strip()
+ for slot in ("recent", "profile", "scope", "preferences")
+ )
except Exception:
return False
diff --git a/deeptutor/agents/question/history.py b/deeptutor/agents/question/history.py
index ec569bd6d..3b9fa278d 100644
--- a/deeptutor/agents/question/history.py
+++ b/deeptutor/agents/question/history.py
@@ -60,9 +60,7 @@ async def load_session_quiz_history(
offset=0,
)
except Exception:
- logger.warning(
- "Failed to load quiz history for session %s", session_id, exc_info=True
- )
+ logger.warning("Failed to load quiz history for session %s", session_id, exc_info=True)
return []
items: list[dict[str, Any]] = list(result.get("items") or [])
diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py
index cc8f4225f..98cbec586 100644
--- a/deeptutor/agents/question/pipeline.py
+++ b/deeptutor/agents/question/pipeline.py
@@ -138,6 +138,7 @@ FINALIZATION_REPAIR_ATTEMPTS = 2
DEFAULT_TOOL_SUMMARIZER_MAX_TOKENS = 800
TOOL_SUMMARIZER_TEMPERATURE = 0.2
+
class QuestionType(StrEnum):
"""Canonical question-type taxonomy. Source of truth for the planner,
quiz-step prompt schema, and the normalizer / validator below."""
@@ -190,9 +191,7 @@ def _normalize_type_list(types: list[str] | None) -> list[str]:
return out
-def _normalize_per_type_counts(
- counts: dict[str, int] | None, allowed: list[str]
-) -> dict[str, int]:
+def _normalize_per_type_counts(counts: dict[str, int] | None, allowed: list[str]) -> dict[str, int]:
"""Validate and clamp a per-type count map.
Keys outside the canonical taxonomy — or outside ``allowed`` when
@@ -264,9 +263,7 @@ def _normalize_per_type_counts(
"""
if not raw:
return {}
- accepted: frozenset[str] = (
- frozenset(allowed_types) if allowed_types else _VALID_QUESTION_TYPES
- )
+ accepted: frozenset[str] = frozenset(allowed_types) if allowed_types else _VALID_QUESTION_TYPES
out: dict[str, int] = {}
for key, value in raw.items():
canonical = str(key or "").strip().lower()
@@ -599,9 +596,7 @@ class QuestionPipeline:
result_payload = self._build_result_payload(
plan, qa_pairs, is_mimic=is_mimic, finish_text=finish_text
)
- await emit_capability_result(
- stream, result_payload, source=SOURCE, usage=self.usage
- )
+ await emit_capability_result(stream, result_payload, source=SOURCE, usage=self.usage)
return result_payload
# ------------------------------------------------------------------
@@ -648,8 +643,7 @@ class QuestionPipeline:
per_type_counts=_format_per_type_counts(per_type_counts),
difficulty=difficulty or "auto",
attachments_summary=self._render_attachments_summary(attachments),
- conversation_context=conversation_context
- or self._t("empty.no_conversation"),
+ conversation_context=conversation_context or self._t("empty.no_conversation"),
quiz_history=self._render_quiz_history(quiz_history),
)
messages = self._build_system_user_messages(
@@ -661,9 +655,7 @@ class QuestionPipeline:
initial_message_count = len(messages)
tool_schemas = (
- self._build_llm_tool_schemas(context)
- if self._use_native_tools(context)
- else None
+ self._build_llm_tool_schemas(context) if self._use_native_tools(context) else None
)
host = _ExploreLoopHost(pipeline=self, stream=stream, context=context, client=client)
@@ -861,9 +853,7 @@ class QuestionPipeline:
)
tool_schemas = (
- self._build_llm_tool_schemas(context)
- if self._use_native_tools(context)
- else None
+ self._build_llm_tool_schemas(context) if self._use_native_tools(context) else None
)
host = _QuizLoopHost(
pipeline=self,
@@ -1140,9 +1130,7 @@ class QuestionPipeline:
raw_args = function.get("arguments") or "{}"
try:
parsed_args = json.loads(raw_args)
- args_display = json.dumps(
- parsed_args, ensure_ascii=False, indent=2
- )
+ args_display = json.dumps(parsed_args, ensure_ascii=False, indent=2)
except Exception:
args_display = str(raw_args)
header = self._t(
@@ -1204,7 +1192,7 @@ class QuestionPipeline:
stripped = text.lstrip()
for label in ("``THINK``", "``TOOL``", "``FINISH``"):
if stripped.startswith(label):
- return stripped[len(label):].lstrip("\n").lstrip()
+ return stripped[len(label) :].lstrip("\n").lstrip()
return text
# ------------------------------------------------------------------
@@ -1366,9 +1354,7 @@ class QuestionPipeline:
return normalized
@classmethod
- def _collect_quiz_issues(
- cls, template: QuizTemplate, payload: dict[str, Any]
- ) -> list[str]:
+ def _collect_quiz_issues(cls, template: QuizTemplate, payload: dict[str, Any]) -> list[str]:
issues: list[str] = []
question = str(payload.get("question") or "").strip()
correct = str(payload.get("correct_answer") or "").strip()
@@ -1485,9 +1471,7 @@ class QuestionPipeline:
):
return step.text, True, calls
messages.append({"role": "assistant", "content": step.text[:500]})
- messages.append(
- {"role": "user", "content": self._t("protocol.force_finish_repair")}
- )
+ messages.append({"role": "user", "content": self._t("protocol.force_finish_repair")})
return self._t("protocol.fallback_final"), False, calls
# ------------------------------------------------------------------
@@ -2027,9 +2011,7 @@ class _ExploreLoopHost(_BaseLoopHost):
iteration: int,
tool_calls: list[dict[str, Any]],
) -> DispatchOutcome:
- outcome = await super().dispatch_tools(
- iteration=iteration, tool_calls=tool_calls
- )
+ outcome = await super().dispatch_tools(iteration=iteration, tool_calls=tool_calls)
if not self._pipeline.tool_summarizer_enabled or not outcome.tool_messages:
return outcome
@@ -2068,9 +2050,7 @@ class _ExploreLoopHost(_BaseLoopHost):
pause_tool_call_id=outcome.pause_tool_call_id,
)
- def build_iteration_trace_meta(
- self, iteration: int
- ) -> tuple[dict[str, Any], dict[str, Any]]:
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
iter_call_id = new_call_id(f"quiz-explore-iter-{iteration}")
iter_meta = build_trace_metadata(
call_id=iter_call_id,
@@ -2151,9 +2131,7 @@ class _QuizLoopHost(_BaseLoopHost):
self._template = template
self._trace_id_prefix = f"quiz-{template.question_id}-iter"
- def build_iteration_trace_meta(
- self, iteration: int
- ) -> tuple[dict[str, Any], dict[str, Any]]:
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
iter_call_id = new_call_id(f"quiz-{self._template.question_id}-iter-{iteration}")
iter_meta = build_trace_metadata(
call_id=iter_call_id,
diff --git a/deeptutor/agents/question/request_config.py b/deeptutor/agents/question/request_config.py
index 8a552ca0e..310d1af4e 100644
--- a/deeptutor/agents/question/request_config.py
+++ b/deeptutor/agents/question/request_config.py
@@ -46,18 +46,14 @@ def build_question_runtime_config(
everything else in ``base_config`` is currently ignored by question.
"""
base = base_config if isinstance(base_config, dict) else {}
- capabilities = (
- base.get("capabilities") if isinstance(base.get("capabilities"), dict) else {}
- )
+ capabilities = base.get("capabilities") if isinstance(base.get("capabilities"), dict) else {}
question_root = (
capabilities.get("deep_question")
if isinstance(capabilities.get("deep_question"), dict)
else {}
)
exploring_root = (
- question_root.get("exploring")
- if isinstance(question_root.get("exploring"), dict)
- else {}
+ question_root.get("exploring") if isinstance(question_root.get("exploring"), dict) else {}
)
summarizer_root = (
exploring_root.get("tool_summarizer")
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.py
index be7210309..3f8c540e4 100644
--- a/deeptutor/agents/research/pipeline.py
+++ b/deeptutor/agents/research/pipeline.py
@@ -194,9 +194,7 @@ _PROTOCOL_NOTE = LabelProtocol(
# Tools whose results get summarised + recorded in the citation manager.
# Any tool whose results carry source documents / external evidence
# should be added here.
-CITABLE_TOOLS: frozenset[str] = frozenset(
- {"rag", "web_search", "paper_search", "code_execution"}
-)
+CITABLE_TOOLS: frozenset[str] = frozenset({"rag", "web_search", "paper_search", "code_execution"})
# Token budget for the note summarization sidecar.
DEFAULT_NOTE_MAX_TOKENS = 1500
@@ -206,7 +204,9 @@ NOTE_RAW_INPUT_TRUNCATE_CHARS = 8000
# ---------------------------------------------------------------------------
# Defaults — preserved from the legacy presets so refactor is config-stable.
# ---------------------------------------------------------------------------
-DEFAULT_REPHRASE_MAX_ITERATIONS = 8 # Inner loop iter cap; ask_user round cap is enforced separately.
+DEFAULT_REPHRASE_MAX_ITERATIONS = (
+ 8 # Inner loop iter cap; ask_user round cap is enforced separately.
+)
DEFAULT_REPHRASE_MAX_ROUNDS = 3
DEFAULT_REPHRASE_MAX_QUESTIONS_PER_ROUND = 3
DEFAULT_BLOCK_MAX_ITERATIONS = 5
@@ -417,9 +417,7 @@ class ResearchPipeline:
a structure) and runs Phase 3+4 directly.
"""
attachments = list(attachments or [])
- image_attachments = [
- a for a in attachments if getattr(a, "type", "") == "image"
- ]
+ image_attachments = [a for a in attachments if getattr(a, "type", "") == "image"]
client = self._build_client()
try:
@@ -501,9 +499,7 @@ class ResearchPipeline:
"output_dir": "",
"outline_preview": True,
"topic": refined_topic,
- "sub_topics": [
- {"title": st.title, "overview": st.overview} for st in outline
- ],
+ "sub_topics": [{"title": st.title, "overview": st.overview} for st in outline],
}
return preview_payload
@@ -555,9 +551,7 @@ class ResearchPipeline:
"citation_count": len(citations.get_all_citations()),
},
}
- await emit_capability_result(
- stream, result_payload, source=SOURCE, usage=self.usage
- )
+ await emit_capability_result(stream, result_payload, source=SOURCE, usage=self.usage)
return result_payload
async def _emit_visible_failure(self, stream: StreamBus, exc: BaseException) -> None:
@@ -778,20 +772,19 @@ class ResearchPipeline:
native_block_tools = self._use_native_block_tools(block_tool_names)
prompt_tool_names = block_tool_names if native_block_tools else []
effective_max_iterations = (
- max(self.block_max_iterations, 4)
- if prompt_tool_names
- else self.block_max_iterations
+ max(self.block_max_iterations, 4) if prompt_tool_names else self.block_max_iterations
)
tool_schemas = (
- self._build_block_tool_schemas(prompt_tool_names)
- if native_block_tools
- else None
+ self._build_block_tool_schemas(prompt_tool_names) if native_block_tools else None
+ )
+ tool_list = (
+ self.registry.build_prompt_text(
+ prompt_tool_names,
+ format="list_with_usage",
+ language=self.language,
+ )
+ or self._fallback_empty_tool_list()
)
- tool_list = self.registry.build_prompt_text(
- prompt_tool_names,
- format="list_with_usage",
- language=self.language,
- ) or self._fallback_empty_tool_list()
kb_note = self._kb_system_note()
system_prompt = self._t(
@@ -850,9 +843,7 @@ class ResearchPipeline:
implicit_think_label=LABEL_THINK,
)
except Exception as exc:
- logger.exception(
- "Research block %s failed: %s", block.block_id, exc
- )
+ logger.exception("Research block %s failed: %s", block.block_id, exc)
queue.mark_failed(block.block_id)
return ResearchedBlock(block=block, knowledge="")
@@ -911,17 +902,13 @@ class ResearchPipeline:
if result.label == LABEL_FINISH and result.text.strip():
return result.text, True, calls
messages.append({"role": "assistant", "content": result.text[:500]})
- messages.append(
- {"role": "user", "content": self._t("protocol.force_finish_repair")}
- )
+ messages.append({"role": "user", "content": self._t("protocol.force_finish_repair")})
return self._t("protocol.fallback_final"), False, calls
# ------------------------------------------------------------------
# Per-block rendering helpers
# ------------------------------------------------------------------
- def _render_sibling_topics(
- self, queue: DynamicTopicQueue, current_block: TopicBlock
- ) -> str:
+ def _render_sibling_topics(self, queue: DynamicTopicQueue, current_block: TopicBlock) -> str:
"""Compact list of other topics in the queue so APPEND can dedup
against them at prompt-time (in addition to the runtime check)."""
siblings = [
@@ -976,9 +963,7 @@ class ResearchPipeline:
if not pending:
break
batch_size = (
- 1
- if str(self.execution_mode).lower() == "series"
- else self.max_parallel_topics
+ 1 if str(self.execution_mode).lower() == "series" else self.max_parallel_topics
)
batch = pending[:batch_size]
results = await asyncio.gather(
@@ -998,14 +983,10 @@ class ResearchPipeline:
)
for block, result in zip(batch, results, strict=True):
if isinstance(result, BaseException):
- logger.exception(
- "Block %s research failed: %s", block.block_id, result
- )
+ logger.exception("Block %s research failed: %s", block.block_id, result)
if block.status == TopicStatus.RESEARCHING:
queue.mark_failed(block.block_id)
- researched_by_id[block.block_id] = ResearchedBlock(
- block=block, knowledge=""
- )
+ researched_by_id[block.block_id] = ResearchedBlock(block=block, knowledge="")
continue
researched_by_id[block.block_id] = result
@@ -1022,8 +1003,7 @@ class ResearchPipeline:
ordered: list[ResearchedBlock] = []
for block in queue.blocks:
ordered.append(
- researched_by_id.get(block.block_id)
- or ResearchedBlock(block=block, knowledge="")
+ researched_by_id.get(block.block_id) or ResearchedBlock(block=block, knowledge="")
)
return ordered
@@ -1059,9 +1039,7 @@ class ResearchPipeline:
response = await client.chat.completions.create(
model=self.model, messages=messages, stream=False, **kwargs
)
- content = (
- response.choices[0].message.content if response.choices else ""
- ) or ""
+ content = (response.choices[0].message.content if response.choices else "") or ""
parsed = classify_label(
content,
allowed_labels=(LABEL_FINISH,),
@@ -1093,8 +1071,11 @@ class ResearchPipeline:
client: Any,
) -> str:
outline = await self._gen_report_outline(
- topic=topic, blocks=blocks, citations=citations,
- stream=stream, client=client,
+ topic=topic,
+ blocks=blocks,
+ citations=citations,
+ stream=stream,
+ client=client,
)
# Global numbering: introduction is 1, sub-topic sections are 2..N+1,
@@ -1121,9 +1102,7 @@ class ResearchPipeline:
)
section_texts.append(title_block)
- intro = await self._write_intro(
- topic=topic, outline=outline, stream=stream, client=client
- )
+ intro = await self._write_intro(topic=topic, outline=outline, stream=stream, client=client)
if intro:
if section_texts:
await self._stream_report_separator(stream)
@@ -1168,12 +1147,9 @@ class ResearchPipeline:
)
used_citation_ids = _citation_ids_in_first_appearance(body, citations)
citation_numbers = {
- citation_id: index
- for index, citation_id in enumerate(used_citation_ids, start=1)
+ citation_id: index for index, citation_id in enumerate(used_citation_ids, start=1)
}
- body = self._linkify_report_citations(
- body, citations, citation_numbers=citation_numbers
- )
+ body = self._linkify_report_citations(body, citations, citation_numbers=citation_numbers)
references = self._render_reference_list(
citations,
citation_ids=used_citation_ids,
@@ -1223,9 +1199,7 @@ class ResearchPipeline:
return (
'<details id="references" open>\n'
f"<summary>{heading}</summary>\n"
- "<ol>\n"
- + "\n".join(entries)
- + "\n</ol>\n"
+ "<ol>\n" + "\n".join(entries) + "\n</ol>\n"
"</details>"
)
@@ -1347,9 +1321,7 @@ class ResearchPipeline:
block_summaries = []
for rb in blocks:
preview = (rb.knowledge or "").strip().split("\n\n")[0][:400]
- block_summaries.append(
- f"- [{rb.block.block_id}] {rb.block.sub_topic}\n {preview}"
- )
+ block_summaries.append(f"- [{rb.block.block_id}] {rb.block.sub_topic}\n {preview}")
system_prompt = self._t("report.outline.system")
user_prompt = self._t(
"report.outline.user_template",
@@ -1461,9 +1433,7 @@ class ResearchPipeline:
repaired: list[ReportSectionPlan] = []
for section in sections:
- ids = tuple(
- dict.fromkeys(bid for bid in section.block_ids if bid in valid_ids)
- )
+ ids = tuple(dict.fromkeys(bid for bid in section.block_ids if bid in valid_ids))
if not ids:
best = _best_block_for_section(section, blocks, exclude=covered)
if best is not None:
@@ -1488,14 +1458,11 @@ class ResearchPipeline:
)
if addendum:
- addendum_title = self._t(
- "labels.addendum_title", default="Additional findings"
- )
+ addendum_title = self._t("labels.addendum_title", default="Additional findings")
addendum_intent = self._t(
"labels.addendum_intent",
default=(
- "Covers researched blocks that did not fit cleanly "
- "into the earlier sections."
+ "Covers researched blocks that did not fit cleanly into the earlier sections."
),
)
repaired.append(
@@ -1558,9 +1525,7 @@ class ResearchPipeline:
evidence = self._render_section_evidence(
section=section, blocks=blocks, citations=citations
)
- system_prompt = self._t(
- "report.section.system", section_number=section_number
- )
+ system_prompt = self._t("report.section.system", section_number=section_number)
user_prompt = self._t(
"report.section.user_template",
topic=topic,
@@ -1577,10 +1542,7 @@ class ResearchPipeline:
protocol=_PROTOCOL_REPORT_SECTION,
stream=stream,
client=client,
- label=(
- f"{self._t('labels.report_section', default='Section')}: "
- f"{section.title}"
- ),
+ label=(f"{self._t('labels.report_section', default='Section')}: {section.title}"),
call_id_root=f"research-report-section-{section.id}",
max_tokens=DEFAULT_REPORT_SECTION_MAX_TOKENS,
extra_meta={
@@ -1610,9 +1572,7 @@ class ResearchPipeline:
for sec, body in zip(outline.sections, section_bodies, strict=False):
snippet = (body or "").strip().split("\n\n", 1)[0]
recap_chunks.append(f"### {sec.title}\n{snippet[:300]}")
- system_prompt = self._t(
- "report.conclusion.system", section_number=section_number
- )
+ system_prompt = self._t("report.conclusion.system", section_number=section_number)
user_prompt = self._t(
"report.conclusion.user_template",
topic=topic,
@@ -1775,8 +1735,7 @@ class ResearchPipeline:
return [
name
for name in composed
- if name in RESEARCH_BLOCK_TOOL_ALLOWLIST
- and self._tool_in_registry(name)
+ if name in RESEARCH_BLOCK_TOOL_ALLOWLIST and self._tool_in_registry(name)
]
def _build_block_tool_schemas(
@@ -1852,9 +1811,7 @@ class ResearchPipeline:
def _use_native_block_tools(self, tool_names: list[str] | None = None) -> bool:
names = self._block_tool_names() if tool_names is None else tool_names
- return bool(names) and can_use_native_tool_calling(
- binding=self.binding, model=self.model
- )
+ return bool(names) and can_use_native_tool_calling(binding=self.binding, model=self.model)
def _tool_in_registry(self, name: str) -> bool:
try:
@@ -2000,12 +1957,8 @@ _REPORT_STOPWORDS = {
}
-_REPORT_CITATION_MARKER_RE = re.compile(
- r"`?\[(?P<id>CIT-\d+-\d+|PLAN-\d+)\]`?(?!\s*\()"
-)
-_REPORT_CITATION_LINK_RE = re.compile(
- r"`?\[(?P<id>CIT-\d+-\d+|PLAN-\d+)\]`?\([^)]*\)"
-)
+_REPORT_CITATION_MARKER_RE = re.compile(r"`?\[(?P<id>CIT-\d+-\d+|PLAN-\d+)\]`?(?!\s*\()")
+_REPORT_CITATION_LINK_RE = re.compile(r"`?\[(?P<id>CIT-\d+-\d+|PLAN-\d+)\]`?\([^)]*\)")
_MARKDOWN_HEADING_RE = re.compile(r"^(?P<hashes>#{1,6})\s+(?P<title>.+?)\s*$")
_LEADING_HEADING_MARKERS_RE = re.compile(r"^(?:#{1,6}\s+)+")
_LEADING_SECTION_ID_RE = re.compile(r"^(?:[\[\(]?S\d+[\]\)]?\s*[::\-]\s*)+", re.I)
@@ -2083,9 +2036,7 @@ def _citation_source_preview(citation: dict[str, Any]) -> str:
for source in sources[:3]:
if not isinstance(source, dict):
continue
- title = str(
- source.get("title") or source.get("source_file") or ""
- ).strip()
+ title = str(source.get("title") or source.get("source_file") or "").strip()
page = str(source.get("page") or "").strip()
if title:
hints.append(f"{title} p.{page}" if page else title)
@@ -2223,6 +2174,7 @@ def _read_int(cfg: Any, *, key: str, default: int) -> int:
except (TypeError, ValueError):
return default
+
# ---------------------------------------------------------------------------
# _BlockLoopHost — per-block research loop callbacks
# ---------------------------------------------------------------------------
@@ -2275,13 +2227,9 @@ class _BlockLoopHost:
# Per-block budgets keep messages bounded; no trimming for v1.
return None
- def build_iteration_trace_meta(
- self, iteration: int
- ) -> tuple[dict[str, Any], dict[str, Any]]:
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
status_meta = _research_topic_status_meta(self._block)
- iter_call_id = new_call_id(
- f"research-{self._block.block_id}-iter-{iteration}"
- )
+ iter_call_id = new_call_id(f"research-{self._block.block_id}-iter-{iteration}")
iter_meta = build_trace_metadata(
call_id=iter_call_id,
phase="researching",
@@ -2575,9 +2523,7 @@ class _BlockLoopHost:
),
)
- new_block = self._queue.append_child(
- parent=self._block, sub_topic=title, overview=overview
- )
+ new_block = self._queue.append_child(parent=self._block, sub_topic=title, overview=overview)
if new_block is None:
return self._pipeline._t(
"notices.append_rejected_full",
@@ -2646,9 +2592,7 @@ class _RephraseLoopHost:
async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:
return None
- def build_iteration_trace_meta(
- self, iteration: int
- ) -> tuple[dict[str, Any], dict[str, Any]]:
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
iter_meta = build_trace_metadata(
call_id=self._shared_iter_call_id,
phase="rephrasing",
@@ -2716,9 +2660,7 @@ class _RephraseLoopHost:
}
for tc in allowed
]
- return DispatchOutcome(
- sources=[], tool_messages=cap_messages + rejected
- )
+ return DispatchOutcome(sources=[], tool_messages=cap_messages + rejected)
if not allowed:
return DispatchOutcome(sources=[], tool_messages=rejected)
@@ -2790,9 +2732,7 @@ class _RephraseLoopHost:
}
if answers:
progress_meta["answers"] = list(answers)
- await self._stream.progress(
- "", source=SOURCE, stage="rephrasing", metadata=progress_meta
- )
+ await self._stream.progress("", source=SOURCE, stage="rephrasing", metadata=progress_meta)
return True
async def emit_terminator(self, payload: dict[str, Any] | None) -> None:
diff --git a/deeptutor/agents/solve/pipeline.py b/deeptutor/agents/solve/pipeline.py
index 1a7426e30..9653ffcff 100644
--- a/deeptutor/agents/solve/pipeline.py
+++ b/deeptutor/agents/solve/pipeline.py
@@ -481,17 +481,13 @@ class SolvePipeline:
combined_text = (
f"{finish_text}\n\n{explanation}" if explanation else finish_text
)
- attempt_finishes.append(
- StepFinish(step=step, text=combined_text)
- )
+ attempt_finishes.append(StepFinish(step=step, text=combined_text))
if not replanned:
step_finishes = attempt_finishes
break
# ----- Phase 3 (synthesize) -----
- logger.info(
- "SolvePipeline synthesize: %d completed steps", len(step_finishes)
- )
+ logger.info("SolvePipeline synthesize: %d completed steps", len(step_finishes))
final_text = ""
async with stream.stage("writing", source=SOURCE):
final_text = await self._synthesize(
@@ -513,9 +509,7 @@ class SolvePipeline:
"plan_revisions": replan_count,
},
}
- await emit_capability_result(
- stream, result_payload, source=SOURCE, usage=self.usage
- )
+ await emit_capability_result(stream, result_payload, source=SOURCE, usage=self.usage)
return result_payload
# ------------------------------------------------------------------
@@ -592,11 +586,7 @@ class SolvePipeline:
queries = payload.get("queries", [])
else:
queries = []
- cleaned = [
- q.strip()
- for q in queries
- if isinstance(q, str) and q.strip()
- ]
+ cleaned = [q.strip() for q in queries if isinstance(q, str) and q.strip()]
return cleaned[: self.num_queries] or [question]
async def _parallel_retrieve(
@@ -644,9 +634,7 @@ class SolvePipeline:
logger.warning("Retrieval failed for query %r: %s", query[:60], exc)
return {"query": query, "answer": ""}
- return await asyncio.gather(
- *[_one(q, i + 1) for i, q in enumerate(queries)]
- )
+ return await asyncio.gather(*[_one(q, i + 1) for i, q in enumerate(queries)])
async def _aggregate_retrieval_results(
self,
@@ -724,8 +712,7 @@ class SolvePipeline:
previous_attempt=self._render_step_finishes(previous_attempt)
if previous_attempt
else self._t("empty.no_previous_attempt"),
- replan_reason=(replan_reason or "").strip()
- or self._t("empty.no_previous_attempt"),
+ replan_reason=(replan_reason or "").strip() or self._t("empty.no_previous_attempt"),
)
messages = self._build_system_user_messages(
system_prompt, user_prompt, image_attachments=image_attachments
@@ -856,11 +843,14 @@ class SolvePipeline:
) -> str:
tone_key = self._tone_key(step_index, total_steps)
tone_guidance = self._t(f"solve_step.tone.{tone_key}")
- tool_list = self.registry.build_prompt_text(
- self._resolved_tools(),
- format="list_with_usage",
- language=self.language,
- ) or self._fallback_empty_tool_list()
+ tool_list = (
+ self.registry.build_prompt_text(
+ self._resolved_tools(),
+ format="list_with_usage",
+ language=self.language,
+ )
+ or self._fallback_empty_tool_list()
+ )
kb_note = self._kb_system_note()
system = self._t(
"solve_step.system",
@@ -941,9 +931,7 @@ class SolvePipeline:
await self._emit_step_final(stream, step_result.text, final_meta)
return step_result.text, True, calls
messages.append({"role": "assistant", "content": step_result.text[:500]})
- messages.append(
- {"role": "user", "content": self._t("protocol.force_finish_repair")}
- )
+ messages.append({"role": "user", "content": self._t("protocol.force_finish_repair")})
return self._t("protocol.fallback_final"), False, calls
async def _emit_step_final(
@@ -1115,7 +1103,9 @@ class SolvePipeline:
step_goal=step.goal,
finish_text=finish_text,
explain_focus=explain_focus
- or self._t("empty.no_explain_focus", default="(no specific focus — pick the most useful angle)"),
+ or self._t(
+ "empty.no_explain_focus", default="(no specific focus — pick the most useful angle)"
+ ),
)
if not system_prompt or not user_prompt:
return ""
@@ -1149,9 +1139,7 @@ class SolvePipeline:
# AND folded into the returned text (so the persisted response /
# downstream synthesize input keeps the same collapsible structure).
summary_label = self._t("labels.explain_summary", default="Deep explanation")
- summary_text = (
- f"{summary_label}: {explain_focus}" if explain_focus else summary_label
- )
+ summary_text = f"{summary_label}: {explain_focus}" if explain_focus else summary_label
details_open = f"<details open>\n<summary>{summary_text}</summary>\n\n"
details_close = "\n\n</details>"
wrapper_meta = merge_trace_metadata(
@@ -1550,9 +1538,7 @@ class _StepLoopHost:
# buffer is reset per step, so it never grows like chat's.
return
- def build_iteration_trace_meta(
- self, iteration: int
- ) -> tuple[dict[str, Any], dict[str, Any]]:
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
iter_call_id = new_call_id(f"solve-{self._step.id}-iter-{iteration}")
iter_meta = build_trace_metadata(
call_id=iter_call_id,
diff --git a/deeptutor/api/routers/quiz_judge.py b/deeptutor/api/routers/quiz_judge.py
index dc3881951..7fb6db9c8 100644
--- a/deeptutor/api/routers/quiz_judge.py
+++ b/deeptutor/api/routers/quiz_judge.py
@@ -93,9 +93,7 @@ def _build_judge_user_prompt(
if image_count > 1
else "学习者另附了一张图片作为作答内容"
)
- parts.append(
- f"{count_text},请结合图片中的文字/公式/草图一并判定。"
- )
+ parts.append(f"{count_text},请结合图片中的文字/公式/草图一并判定。")
parts.append("请针对该学习者的具体作答给出 AI 评判。")
else:
parts = [
@@ -337,9 +335,7 @@ async def websocket_quiz_judge(websocket: WebSocket):
has_image = bool(image_records)
options_value = data.get("options") if isinstance(data.get("options"), dict) else None
- system_prompt = _JUDGE_SYSTEM_PROMPTS.get(
- requested_language, _JUDGE_SYSTEM_PROMPTS["en"]
- )
+ system_prompt = _JUDGE_SYSTEM_PROMPTS.get(requested_language, _JUDGE_SYSTEM_PROMPTS["en"])
user_prompt = _build_judge_user_prompt(
language=requested_language,
question=question_text,
@@ -356,9 +352,7 @@ async def websocket_quiz_judge(websocket: WebSocket):
await safe_send(
{
"type": "error",
- "content": (
- "No answer to judge — submit a typed answer or attach an image."
- ),
+ "content": ("No answer to judge — submit a typed answer or attach an image."),
}
)
try:
diff --git a/deeptutor/api/routers/tools.py b/deeptutor/api/routers/tools.py
index cbd6029f7..dca67979f 100644
--- a/deeptutor/api/routers/tools.py
+++ b/deeptutor/api/routers/tools.py
@@ -84,7 +84,9 @@ class ToolsListResponse(BaseModel):
enabled_optional_tools: list[str]
-def _serialise_definition(definition: ToolDefinition) -> tuple[str, str, list[ToolParameterPayload]]:
+def _serialise_definition(
+ definition: ToolDefinition,
+) -> tuple[str, str, list[ToolParameterPayload]]:
params = [
ToolParameterPayload(
name=p.name,
@@ -176,9 +178,7 @@ async def list_builtin_tools() -> ToolsListResponse:
)
)
except Exception:
- logger.exception(
- "Failed to serialise coming-soon tool %s", tool_type.__name__
- )
+ logger.exception("Failed to serialise coming-soon tool %s", tool_type.__name__)
# Guard against the unlikely case of name collision (e.g. someone
# accidentally registers the same tool both as built-in and coming-soon).
seen: set[str] = set()
diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.py
index 5cefd6820..9f56a1b16 100644
--- a/deeptutor/core/agentic/client.py
+++ b/deeptutor/core/agentic/client.py
@@ -49,9 +49,7 @@ def build_openai_client(config: LLMClientConfig) -> Any:
if load_system_settings()["disable_ssl_verify"]:
http_client = httpx.AsyncClient(verify=False) # nosec B501
default_headers = config.extra_headers or None
- if config.binding == "azure_openai" or (
- config.binding == "openai" and config.api_version
- ):
+ if config.binding == "azure_openai" or (config.binding == "openai" and config.api_version):
return AsyncAzureOpenAI(
api_key=config.api_key or "sk-no-key-required",
azure_endpoint=config.base_url,
diff --git a/deeptutor/core/agentic/labeled_step.py b/deeptutor/core/agentic/labeled_step.py
index 8fbf3419c..cbbfc7bf2 100644
--- a/deeptutor/core/agentic/labeled_step.py
+++ b/deeptutor/core/agentic/labeled_step.py
@@ -547,9 +547,7 @@ async def run_labeled_step(
reasoning_text,
source=source,
stage=stage,
- metadata=merge_trace_metadata(
- iter_meta, {"trace_kind": "llm_chunk"}
- ),
+ metadata=merge_trace_metadata(iter_meta, {"trace_kind": "llm_chunk"}),
)
if delta.content:
@@ -659,9 +657,7 @@ async def run_labeled_step(
# cleanup so downstream consumers (assistant messages, final-response
# text) aren't polluted with the prelude markers.
implicit_think_resolved = bool(
- saw_pre_label_think
- and implicit_think_label
- and label == implicit_think_label
+ saw_pre_label_think and implicit_think_label and label == implicit_think_label
)
if (binding or saw_pre_label_think) and not implicit_think_resolved:
text = clean_thinking_tags(text, binding, model)
diff --git a/deeptutor/core/agentic/loop.py b/deeptutor/core/agentic/loop.py
index 495509e32..c0882eaab 100644
--- a/deeptutor/core/agentic/loop.py
+++ b/deeptutor/core/agentic/loop.py
@@ -85,9 +85,7 @@ class LoopHost(Protocol):
async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:
"""Optionally trim ``messages`` to keep within the model's window."""
- def build_iteration_trace_meta(
- self, iteration: int
- ) -> tuple[dict[str, Any], dict[str, Any]]:
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
"""Allocate ``(iter_meta, final_meta)`` for one iteration."""
async def dispatch_tools(
diff --git a/deeptutor/core/agentic/tool_dispatch.py b/deeptutor/core/agentic/tool_dispatch.py
index f9a34d1bb..dc4ca0cd5 100644
--- a/deeptutor/core/agentic/tool_dispatch.py
+++ b/deeptutor/core/agentic/tool_dispatch.py
@@ -19,7 +19,7 @@ messages, accumulated sources, and pause/terminate signals for the loop.
from __future__ import annotations
import asyncio
-from collections.abc import Awaitable, Callable
+from collections.abc import Callable
from dataclasses import dataclass, field
import json
import logging
@@ -42,9 +42,7 @@ MAX_PARALLEL_TOOL_CALLS = 8
KwargAugmenter = Callable[[str, dict[str, Any], UnifiedContext], dict[str, Any]]
-RetrieveMetaFactory = Callable[
- [dict[str, Any], str, dict[str, Any]], dict[str, Any] | None
-]
+RetrieveMetaFactory = Callable[[dict[str, Any], str, dict[str, Any]], dict[str, Any] | None]
UnknownErrorMessageFactory = Callable[[str], str]
@@ -117,9 +115,7 @@ async def dispatch_tool_calls(
# also hidden from the user-facing trace stream to avoid duplicate Ask
# Me rows/cards during the live turn.
duplicate_of = _detect_duplicate_calls(prepared)
- suppress_ui_indices = {
- idx for idx in duplicate_of if prepared[idx][1] == "ask_user"
- }
+ suppress_ui_indices = {idx for idx in duplicate_of if prepared[idx][1] == "ask_user"}
per_tool_trace_meta = _build_per_tool_trace_meta(
prepared,
context=context,
@@ -294,9 +290,7 @@ def _build_per_tool_trace_meta(
own sub-trace row in the frontend's CallTracePanel."""
metas: list[dict[str, Any]] = []
for tool_index, (tool_call_id, tool_name, _exec_args) in enumerate(prepared):
- trace_call_id = new_call_id(
- f"{trace_id_prefix}-{iteration_index}-tool-{tool_index}"
- )
+ trace_call_id = new_call_id(f"{trace_id_prefix}-{iteration_index}-tool-{tool_index}")
base_meta = build_trace_metadata(
call_id=trace_call_id,
phase=stage,
@@ -459,12 +453,8 @@ async def _collect_outcome(
):
result_text = str(result["result_text"])
tool_meta = per_tool_trace_meta[tool_index]
- tool_extra_meta = (
- result.get("metadata") if isinstance(result, dict) else None
- )
- result_event_meta = merge_trace_metadata(
- tool_meta, {"trace_kind": "tool_result"}
- )
+ tool_extra_meta = result.get("metadata") if isinstance(result, dict) else None
+ result_event_meta = merge_trace_metadata(tool_meta, {"trace_kind": "tool_result"})
if isinstance(tool_extra_meta, dict) and tool_extra_meta:
result_event_meta = merge_trace_metadata(
result_event_meta,
diff --git a/deeptutor/core/agentic/usage.py b/deeptutor/core/agentic/usage.py
index 831eb8a6f..c0bf401e1 100644
--- a/deeptutor/core/agentic/usage.py
+++ b/deeptutor/core/agentic/usage.py
@@ -83,10 +83,9 @@ class UsageTracker:
from deeptutor.logging.stats.llm_stats import get_pricing
pricing = get_pricing(self.model)
- cost_usd = (
- (self.prompt_tokens / 1000.0) * pricing.get("input", 0.0)
- + (self.completion_tokens / 1000.0) * pricing.get("output", 0.0)
- )
+ cost_usd = (self.prompt_tokens / 1000.0) * pricing.get("input", 0.0) + (
+ self.completion_tokens / 1000.0
+ ) * pricing.get("output", 0.0)
return {
"total_cost_usd": cost_usd,
"total_tokens": self.total_tokens,
diff --git a/deeptutor/services/config/capabilities_settings.py b/deeptutor/services/config/capabilities_settings.py
index 42b4d3f84..52e01f971 100644
--- a/deeptutor/services/config/capabilities_settings.py
+++ b/deeptutor/services/config/capabilities_settings.py
@@ -34,7 +34,6 @@ from deeptutor.services.config.loader import (
)
from deeptutor.utils.config_manager import ConfigManager
-
# ── Schema definition ────────────────────────────────────────────────────
@@ -181,9 +180,7 @@ def _build_chat_block(agents_cfg: dict[str, Any]) -> dict[str, Any]:
_deep_merge(merged, DEFAULT_CHAT_PARAMS)
_deep_merge(merged, chat_cfg)
return {
- "temperature": _coerce_float(
- merged.get("temperature"), DEFAULT_CHAT_PARAMS["temperature"]
- ),
+ "temperature": _coerce_float(merged.get("temperature"), DEFAULT_CHAT_PARAMS["temperature"]),
"max_iterations": _coerce_int(
merged.get("max_iterations"), DEFAULT_CHAT_PARAMS["max_iterations"], lo=1, hi=100
),
@@ -199,9 +196,7 @@ def _build_chat_block(agents_cfg: dict[str, Any]) -> dict[str, Any]:
}
-def _build_simple_llm_block(
- agents_cfg: dict[str, Any], capability: str
-) -> dict[str, Any]:
+def _build_simple_llm_block(agents_cfg: dict[str, Any], capability: str) -> dict[str, Any]:
defaults = _SIMPLE_LLM_DEFAULTS[capability]
section = _get_at(agents_cfg, _AGENTS_YAML_CAPABILITY_SECTIONS[capability])
return {
@@ -235,9 +230,15 @@ def _build_main_runtime_block(main_cfg: dict[str, Any], capability: str) -> dict
d = defaults["researching"]
return {
"researching": {
- "note_agent_mode": str(researching_cfg.get("note_agent_mode") or d["note_agent_mode"]),
- "tool_timeout": _coerce_int(researching_cfg.get("tool_timeout"), d["tool_timeout"], lo=1, hi=600),
- "tool_max_retries": _coerce_int(researching_cfg.get("tool_max_retries"), d["tool_max_retries"], lo=0, hi=10),
+ "note_agent_mode": str(
+ researching_cfg.get("note_agent_mode") or d["note_agent_mode"]
+ ),
+ "tool_timeout": _coerce_int(
+ researching_cfg.get("tool_timeout"), d["tool_timeout"], lo=1, hi=600
+ ),
+ "tool_max_retries": _coerce_int(
+ researching_cfg.get("tool_max_retries"), d["tool_max_retries"], lo=0, hi=10
+ ),
"paper_search_years_limit": _coerce_int(
researching_cfg.get("paper_search_years_limit"),
d["paper_search_years_limit"],
@@ -292,7 +293,9 @@ def _apply_chat_into_agents_yaml(agents_cfg: dict[str, Any], block: dict[str, An
current = _get_at(agents_cfg, ("capabilities", "chat"))
new_chat: dict[str, Any] = dict(current) if isinstance(current, dict) else {}
if "temperature" in block:
- new_chat["temperature"] = _coerce_float(block.get("temperature"), DEFAULT_CHAT_PARAMS["temperature"])
+ new_chat["temperature"] = _coerce_float(
+ block.get("temperature"), DEFAULT_CHAT_PARAMS["temperature"]
+ )
if "max_iterations" in block:
new_chat["max_iterations"] = _coerce_int(
block.get("max_iterations"), DEFAULT_CHAT_PARAMS["max_iterations"], lo=1, hi=100
@@ -320,13 +323,17 @@ def _apply_simple_llm_into_agents_yaml(
current = _get_at(agents_cfg, section_path)
new_section: dict[str, Any] = dict(current) if isinstance(current, dict) else {}
if "temperature" in block:
- new_section["temperature"] = _coerce_float(block.get("temperature"), defaults["temperature"])
+ new_section["temperature"] = _coerce_float(
+ block.get("temperature"), defaults["temperature"]
+ )
if "max_tokens" in block:
new_section["max_tokens"] = _coerce_int(block.get("max_tokens"), defaults["max_tokens"])
_set_at(agents_cfg, section_path, new_section)
-def _apply_main_runtime(main_payload: dict[str, Any], capability: str, block: dict[str, Any]) -> None:
+def _apply_main_runtime(
+ main_payload: dict[str, Any], capability: str, block: dict[str, Any]
+) -> None:
defaults = _MAIN_YAML_RUNTIME_DEFAULTS.get(capability)
if defaults is None:
return
@@ -354,7 +361,9 @@ def _apply_main_runtime(main_payload: dict[str, Any], capability: str, block: di
main_payload.setdefault("capabilities", {}).setdefault("research", {})["researching"] = {
"note_agent_mode": str(r.get("note_agent_mode") or d["note_agent_mode"]),
"tool_timeout": _coerce_int(r.get("tool_timeout"), d["tool_timeout"], lo=1, hi=600),
- "tool_max_retries": _coerce_int(r.get("tool_max_retries"), d["tool_max_retries"], lo=0, hi=10),
+ "tool_max_retries": _coerce_int(
+ r.get("tool_max_retries"), d["tool_max_retries"], lo=0, hi=10
+ ),
"paper_search_years_limit": _coerce_int(
r.get("paper_search_years_limit"), d["paper_search_years_limit"], lo=1, hi=50
),
@@ -364,7 +373,9 @@ def _apply_main_runtime(main_payload: dict[str, Any], capability: str, block: di
e = block["exploring"]
sm = e.get("tool_summarizer") if isinstance(e.get("tool_summarizer"), dict) else {}
main_payload.setdefault("capabilities", {}).setdefault("question", {})["exploring"] = {
- "max_iterations": _coerce_int(e.get("max_iterations"), d["max_iterations"], lo=1, hi=50),
+ "max_iterations": _coerce_int(
+ e.get("max_iterations"), d["max_iterations"], lo=1, hi=50
+ ),
"tool_summarizer": {
"enabled": _coerce_bool(sm.get("enabled"), d["tool_summarizer"]["enabled"]),
"max_tokens": _coerce_int(sm.get("max_tokens"), d["tool_summarizer"]["max_tokens"]),
diff --git a/deeptutor/services/memory/consolidator/chunker.py b/deeptutor/services/memory/consolidator/chunker.py
index 90f73cb68..5b98eb9fe 100644
--- a/deeptutor/services/memory/consolidator/chunker.py
+++ b/deeptutor/services/memory/consolidator/chunker.py
@@ -12,12 +12,11 @@ Pure functions: no I/O, no LLM. Easy to unit-test.
from __future__ import annotations
+from dataclasses import dataclass
import math
import re
-from dataclasses import dataclass
from typing import Literal
-
Boundary = Literal["paragraph", "sentence"]
# Paragraph boundary: one or more blank lines.
@@ -113,9 +112,7 @@ def chunk_with_boundary(
# ── Internals ───────────────────────────────────────────────────────────
-def _expand_to_boundary(
- text: str, target_end: int, boundary: Boundary, *, limit: int
-) -> int:
+def _expand_to_boundary(text: str, target_end: int, boundary: Boundary, *, limit: int) -> int:
"""Push ``target_end`` forward to the next natural boundary.
The search is bounded by ``limit`` (exclusive). If no boundary is
diff --git a/deeptutor/services/memory/consolidator/guards.py b/deeptutor/services/memory/consolidator/guards.py
index 7681efc73..abc0e9b4b 100644
--- a/deeptutor/services/memory/consolidator/guards.py
+++ b/deeptutor/services/memory/consolidator/guards.py
@@ -8,9 +8,9 @@ which meant rejection was a silent drop.
from __future__ import annotations
+from dataclasses import dataclass
import logging
import re
-from dataclasses import dataclass
from typing import Iterable
from deeptutor.services.memory.ops import Op
@@ -46,6 +46,7 @@ BANNED_PHRASES: tuple[str, ...] = (
"从来不",
)
+
# Per-loop budgets. Beyond these the dispatcher emits a hint observation
# instead of executing the action; the prompt nudges the model to finish.
@dataclass(frozen=True)
diff --git a/deeptutor/services/memory/consolidator/line_doc.py b/deeptutor/services/memory/consolidator/line_doc.py
index 5549a6bcf..79760976d 100644
--- a/deeptutor/services/memory/consolidator/line_doc.py
+++ b/deeptutor/services/memory/consolidator/line_doc.py
@@ -29,10 +29,10 @@ Public API
from __future__ import annotations
+from dataclasses import dataclass, field
import json
import logging
import re
-from dataclasses import dataclass, field
from typing import Iterable, Literal, Union
from deeptutor.services.memory.document import Document, Entry
@@ -45,11 +45,11 @@ LineKind = Literal["title", "blank", "section", "bullet"]
@dataclass(frozen=True)
class Line:
- number: int # 1-based, matches what the LLM sees
+ number: int # 1-based, matches what the LLM sees
kind: LineKind
- text: str # rendered text (no leading "n: ")
- entry_id: str | None = None # for bullet lines, the m_xxx id
- section: str | None = None # for bullet lines, owning section name
+ text: str # rendered text (no leading "n: ")
+ entry_id: str | None = None # for bullet lines, the m_xxx id
+ section: str | None = None # for bullet lines, owning section name
@dataclass(frozen=True)
@@ -63,9 +63,7 @@ class LineView:
def render(self, *, with_numbers: bool = True) -> str:
if with_numbers:
width = max(2, len(str(len(self.lines))))
- return "\n".join(
- f"{l.number:>{width}}: {l.text}" for l in self.lines
- )
+ return "\n".join(f"{l.number:>{width}}: {l.text}" for l in self.lines)
return "\n".join(l.text for l in self.lines)
def line(self, number: int) -> Line | None:
@@ -87,7 +85,7 @@ class ReplaceLineOp:
@dataclass(frozen=True)
class DeleteLinesOp:
line_start: int
- line_end: int # inclusive
+ line_end: int # inclusive
reason: str = ""
op: Literal["delete"] = "delete"
@@ -141,9 +139,7 @@ def render_view(doc: Document) -> LineView:
for section_name, entries in doc.sections:
if not entries:
continue
- lines.append(
- Line(number=len(lines) + 1, kind="section", text=f"## {section_name}")
- )
+ lines.append(Line(number=len(lines) + 1, kind="section", text=f"## {section_name}"))
for entry in entries:
lines.append(
Line(
@@ -202,9 +198,7 @@ def apply_edits(doc: Document, edits: Iterable[Edit]) -> tuple[Document, EditRep
report.applied.append(EditResult(op=edit, status="applied", detail=detail))
except _Reject as exc:
logger.warning("line-edit rejected: %s — %s", _short(edit), exc)
- report.rejected.append(
- EditResult(op=edit, status="rejected", detail=str(exc))
- )
+ report.rejected.append(EditResult(op=edit, status="rejected", detail=str(exc)))
_drop_empty_sections(new_doc)
return new_doc, report
@@ -430,9 +424,9 @@ def _section_entries(doc: Document, name: str) -> list[Entry]:
for section, entries in doc.sections:
if section == name:
return entries
- entries: list[Entry] = []
- doc.sections.append((name, entries))
- return entries
+ new_entries: list[Entry] = []
+ doc.sections.append((name, new_entries))
+ return new_entries
def _drop_empty_sections(doc: Document) -> None:
diff --git a/deeptutor/services/memory/consolidator/meta.py b/deeptutor/services/memory/consolidator/meta.py
index e673df48d..65bf3c8fc 100644
--- a/deeptutor/services/memory/consolidator/meta.py
+++ b/deeptutor/services/memory/consolidator/meta.py
@@ -32,13 +32,13 @@ Atomic writes via temp + rename. Missing files behave as "first run".
from __future__ import annotations
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
import json
import logging
import os
-import tempfile
-from dataclasses import dataclass, field
-from datetime import datetime, timezone
from pathlib import Path
+import tempfile
from deeptutor.services.memory import paths
from deeptutor.services.memory.paths import L3Slot, Surface
@@ -107,9 +107,7 @@ def save_l3_meta(
path = l3_meta_path(slot)
meta = L3Meta(
last_update_at=_now_iso(),
- seen_l2_entry_ids={
- surface: set(ids) for surface, ids in seen_l2_entry_ids.items()
- },
+ seen_l2_entry_ids={surface: set(ids) for surface, ids in seen_l2_entry_ids.items()},
)
_atomic_write_json(
path,
@@ -117,8 +115,7 @@ def save_l3_meta(
"version": _META_VERSION,
"last_update_at": meta.last_update_at,
"seen_l2_entry_ids": {
- surface: sorted(ids)
- for surface, ids in meta.seen_l2_entry_ids.items()
+ surface: sorted(ids) for surface, ids in meta.seen_l2_entry_ids.items()
},
},
)
@@ -149,8 +146,7 @@ def _load_meta_l3(path: Path) -> L3Meta:
return L3Meta(
last_update_at=data.get("last_update_at"),
seen_l2_entry_ids={
- surface: set(ids) if isinstance(ids, list) else set()
- for surface, ids in raw.items()
+ surface: set(ids) if isinstance(ids, list) else set() for surface, ids in raw.items()
},
)
diff --git a/deeptutor/services/memory/consolidator/modes/__init__.py b/deeptutor/services/memory/consolidator/modes/__init__.py
index 444c473f3..7c3499f2a 100644
--- a/deeptutor/services/memory/consolidator/modes/__init__.py
+++ b/deeptutor/services/memory/consolidator/modes/__init__.py
@@ -12,14 +12,14 @@ stays stable while the implementation switches under the hood.
from __future__ import annotations
-from deeptutor.services.memory.consolidator.modes.audit import run_audit
-from deeptutor.services.memory.consolidator.modes.dedup import run_dedup
-from deeptutor.services.memory.consolidator.modes.merge import run_merge
-from deeptutor.services.memory.consolidator.modes.update import run_update
from deeptutor.services.memory.consolidator.modes._shims import (
consolidate_l2,
consolidate_l3,
)
+from deeptutor.services.memory.consolidator.modes.audit import run_audit
+from deeptutor.services.memory.consolidator.modes.dedup import run_dedup
+from deeptutor.services.memory.consolidator.modes.merge import run_merge
+from deeptutor.services.memory.consolidator.modes.update import run_update
__all__ = [
"consolidate_l2",
diff --git a/deeptutor/services/memory/consolidator/modes/_shims.py b/deeptutor/services/memory/consolidator/modes/_shims.py
index 136717f2a..3a7ccae00 100644
--- a/deeptutor/services/memory/consolidator/modes/_shims.py
+++ b/deeptutor/services/memory/consolidator/modes/_shims.py
@@ -29,14 +29,14 @@ from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable
+from deeptutor.services.memory import paths
from deeptutor.services.memory.consolidator.modes.update import (
UpdateResult,
run_update,
)
from deeptutor.services.memory.document import parse, serialize
-from deeptutor.services.memory.ops import ApplyReport, Op, OpResult
+from deeptutor.services.memory.ops import ApplyReport, Op
from deeptutor.services.memory.paths import L3Slot, Surface
-from deeptutor.services.memory import paths
OnEvent = Callable[[dict[str, Any]], Awaitable[None]]
diff --git a/deeptutor/services/memory/consolidator/modes/audit.py b/deeptutor/services/memory/consolidator/modes/audit.py
index f8f90b213..2f71397fc 100644
--- a/deeptutor/services/memory/consolidator/modes/audit.py
+++ b/deeptutor/services/memory/consolidator/modes/audit.py
@@ -93,7 +93,9 @@ async def run_audit(
try:
_config, token = activate_llm_selection(llm_selection)
except Exception as exc: # noqa: BLE001
- logger.warning("memory audit: ignoring unresolvable llm_selection %s: %s", llm_selection, exc)
+ logger.warning(
+ "memory audit: ignoring unresolvable llm_selection %s: %s", llm_selection, exc
+ )
token = None
try:
if layer == "L2":
diff --git a/deeptutor/services/memory/consolidator/modes/dedup.py b/deeptutor/services/memory/consolidator/modes/dedup.py
index 6450f15a2..f490f0315 100644
--- a/deeptutor/services/memory/consolidator/modes/dedup.py
+++ b/deeptutor/services/memory/consolidator/modes/dedup.py
@@ -72,7 +72,9 @@ async def run_dedup(
try:
_config, token = activate_llm_selection(llm_selection)
except Exception as exc: # noqa: BLE001
- logger.warning("memory dedup: ignoring unresolvable llm_selection %s: %s", llm_selection, exc)
+ logger.warning(
+ "memory dedup: ignoring unresolvable llm_selection %s: %s", llm_selection, exc
+ )
token = None
try:
return await _run_dedup_inner(
@@ -91,16 +93,19 @@ async def _run_dedup_inner(
user_label: str,
on_event: OnEvent | None,
) -> DedupResult:
-
path = _path_for(layer, key)
if not path.exists():
await emit(on_event, {"stage": "done", "no_doc": True, "edits_applied": 0})
- return DedupResult(layer=layer, key=key, iterations_run=0, edits_applied=0, converged_early=True)
+ return DedupResult(
+ layer=layer, key=key, iterations_run=0, edits_applied=0, converged_early=True
+ )
doc = load_doc(path, default_title=_default_title(layer, key))
if not doc.all_entries():
await emit(on_event, {"stage": "done", "no_doc": True, "edits_applied": 0})
- return DedupResult(layer=layer, key=key, iterations_run=0, edits_applied=0, converged_early=True)
+ return DedupResult(
+ layer=layer, key=key, iterations_run=0, edits_applied=0, converged_early=True
+ )
prompt = load_prompt("dedup", language)
total_applied = 0
diff --git a/deeptutor/services/memory/consolidator/modes/update.py b/deeptutor/services/memory/consolidator/modes/update.py
index ba4df4aef..90393c59c 100644
--- a/deeptutor/services/memory/consolidator/modes/update.py
+++ b/deeptutor/services/memory/consolidator/modes/update.py
@@ -104,7 +104,9 @@ async def run_update(
try:
_config, token = activate_llm_selection(llm_selection)
except Exception as exc: # noqa: BLE001
- logger.warning("memory update: ignoring unresolvable llm_selection %s: %s", llm_selection, exc)
+ logger.warning(
+ "memory update: ignoring unresolvable llm_selection %s: %s", llm_selection, exc
+ )
token = None
try:
if layer == "L2":
@@ -279,7 +281,9 @@ async def _run_update_l2(
},
)
continue
- kept_in_chunk.append(ExtractedFact(text=fact.text, refs=kept_refs, section=fact.section))
+ kept_in_chunk.append(
+ ExtractedFact(text=fact.text, refs=kept_refs, section=fact.section)
+ )
added_now = _append_facts_to_doc(doc, kept_in_chunk, sections)
facts_added += len(added_now)
@@ -508,7 +512,9 @@ async def _run_update_l3(
},
)
continue
- kept_in_chunk.append(ExtractedFact(text=fact.text, refs=kept_refs, section=fact.section))
+ kept_in_chunk.append(
+ ExtractedFact(text=fact.text, refs=kept_refs, section=fact.section)
+ )
added_now = _append_facts_to_doc(doc, kept_in_chunk, sections)
facts_added += len(added_now)
diff --git a/deeptutor/services/memory/consolidator/parse.py b/deeptutor/services/memory/consolidator/parse.py
index 38ea02299..e83e4fe60 100644
--- a/deeptutor/services/memory/consolidator/parse.py
+++ b/deeptutor/services/memory/consolidator/parse.py
@@ -15,10 +15,10 @@ think out loud without invalidating the run.
from __future__ import annotations
+from dataclasses import dataclass
import json
import logging
import re
-from dataclasses import dataclass
from typing import Any
from deeptutor.services.memory.ops import AddOp, DeleteOp, EditOp, Op
diff --git a/deeptutor/services/memory/consolidator/references.py b/deeptutor/services/memory/consolidator/references.py
index 6c91910ee..d25191c0a 100644
--- a/deeptutor/services/memory/consolidator/references.py
+++ b/deeptutor/services/memory/consolidator/references.py
@@ -172,9 +172,7 @@ _ENTITY_HEADER_FMT = "=== {marker} ==="
# would have been ``"=== @l2 m_xxx ==="``.
-def render_traces_for_concat(
- entities: list[Entity], *, surface: str
-) -> str:
+def render_traces_for_concat(entities: list[Entity], *, surface: str) -> str:
"""Concatenate a list of L2 raw-trace entities into one timeline string.
The chunk-pool detector relies on the marker line being unique per
@@ -308,11 +306,7 @@ def _entity_marker(surface: str, entity_id: str) -> str:
def _format_meta(ent: Entity) -> str:
if not ent.metadata:
return ""
- bits = [
- f"{k}={v}"
- for k, v in ent.metadata.items()
- if v not in (None, "", [], {})
- ]
+ bits = [f"{k}={v}" for k, v in ent.metadata.items() if v not in (None, "", [], {})]
return " ".join(bits)
diff --git a/deeptutor/services/memory/consolidator/runs.py b/deeptutor/services/memory/consolidator/runs.py
index 1c575f063..3201ea841 100644
--- a/deeptutor/services/memory/consolidator/runs.py
+++ b/deeptutor/services/memory/consolidator/runs.py
@@ -45,8 +45,8 @@ _MAX_HISTORY = 200
@dataclass
class RunEvent:
- seq: int # 0-based, monotonic per run
- ts: str # ISO-8601 UTC
+ seq: int # 0-based, monotonic per run
+ ts: str # ISO-8601 UTC
payload: dict[str, Any]
@@ -172,9 +172,7 @@ class RunManager:
"""
async with self._lock:
if self.active_for(layer, key) is not None:
- raise RunBusyError(
- f"a run is already in progress for {layer}/{key}"
- )
+ raise RunBusyError(f"a run is already in progress for {layer}/{key}")
run = Run(
id=uuid.uuid4().hex,
layer=layer,
@@ -270,6 +268,7 @@ class RunManager:
run.status = "running"
await self._emit(run, {"stage": "run_started", "run_id": run.id, "mode": run.mode})
try:
+
async def on_event(evt: dict[str, Any]) -> None:
await self._emit(run, evt)
diff --git a/deeptutor/services/memory/document.py b/deeptutor/services/memory/document.py
index acf7ff418..f87e7b251 100644
--- a/deeptutor/services/memory/document.py
+++ b/deeptutor/services/memory/document.py
@@ -89,9 +89,9 @@ class Document:
for section, entries in self.sections:
if section == name:
return entries
- entries: list[Entry] = []
- self.sections.append((name, entries))
- return entries
+ new_entries: list[Entry] = []
+ self.sections.append((name, new_entries))
+ return new_entries
def remove(self, entry_id: str) -> bool:
for _, entries in self.sections:
@@ -214,9 +214,7 @@ def serialize(doc: Document) -> str:
# ``, ``-separate markers so the rendered superscripts read
# "¹, ²" not "¹²" — important when the same bullet cites two
# different sources.
- markers = ", ".join(
- f"[^{ref_to_label[r]}]" for r in entry.refs if r in ref_to_label
- )
+ markers = ", ".join(f"[^{ref_to_label[r]}]" for r in entry.refs if r in ref_to_label)
text = entry.text.rstrip()
if markers:
lines.append(f"- {text} {markers} <!--{entry.id}-->")
diff --git a/deeptutor/services/memory/ids.py b/deeptutor/services/memory/ids.py
index 282cd8ead..30cc9cf93 100644
--- a/deeptutor/services/memory/ids.py
+++ b/deeptutor/services/memory/ids.py
@@ -33,9 +33,7 @@ _SNAPSHOT_RE = re.compile(r"^[a-z][a-z0-9_-]*:[A-Za-z0-9_.:\-]+$")
# refs need no id portion. Whitelist (not a loose regex) so a malformed
# ref like ``not-an-id`` doesn't accidentally validate. Mirrors
# :data:`paths.SURFACES`; if you add a surface, add it here too.
-_SHORTNAME_REFS = frozenset(
- {"chat", "notebook", "quiz", "kb", "book", "tutorbot", "cowriter"}
-)
+_SHORTNAME_REFS = frozenset({"chat", "notebook", "quiz", "kb", "book", "tutorbot", "cowriter"})
def _encode(n: int, length: int) -> str:
diff --git a/deeptutor/services/memory/ops.py b/deeptutor/services/memory/ops.py
index c9a9d99e0..553f0bdeb 100644
--- a/deeptutor/services/memory/ops.py
+++ b/deeptutor/services/memory/ops.py
@@ -107,9 +107,7 @@ def _validate(doc: Document, ops: list[Op]) -> None:
if doc.find(op.target_id) is None:
raise OpValidationError(f"delete: target_id {op.target_id} not found")
if op.reason not in _DELETE_REASONS:
- raise OpValidationError(
- f"delete: reason must be one of {sorted(_DELETE_REASONS)}"
- )
+ raise OpValidationError(f"delete: reason must be one of {sorted(_DELETE_REASONS)}")
if op.target_id in edits:
raise OpValidationError(
f"batch conflict: edit and delete on same id {op.target_id}"
diff --git a/deeptutor/services/memory/settings.py b/deeptutor/services/memory/settings.py
index 758370a5c..a5346331e 100644
--- a/deeptutor/services/memory/settings.py
+++ b/deeptutor/services/memory/settings.py
@@ -128,12 +128,14 @@ def _from_dict(cls: type, raw: Any) -> Any:
for f in fields(cls):
provided = raw.get(f.name)
default = getattr(instance_defaults, f.name)
- if is_dataclass(f.type) if isinstance(f.type, type) else False:
+ if isinstance(f.type, type) and is_dataclass(f.type):
kwargs[f.name] = _from_dict(f.type, provided) if provided is not None else default
continue
# nested dataclass detection through the actual default type
if is_dataclass(default):
- kwargs[f.name] = _from_dict(type(default), provided) if provided is not None else default
+ kwargs[f.name] = (
+ _from_dict(type(default), provided) if provided is not None else default
+ )
continue
kwargs[f.name] = _coerce_scalar(f.name, provided, default)
return cls(**kwargs)
@@ -146,21 +148,21 @@ def _coerce_scalar(name: str, raw: Any, default: Any) -> Any:
return bool(raw)
if isinstance(default, int):
try:
- value = int(raw)
+ int_value = int(raw)
except (TypeError, ValueError):
return default
- return _clamp_int(name, value, default)
+ return _clamp_int(name, int_value, default)
if isinstance(default, float):
try:
- value = float(raw)
+ float_value = float(raw)
except (TypeError, ValueError):
return default
- return _clamp_float(name, value, default)
+ return _clamp_float(name, float_value, default)
if isinstance(default, str):
- value = str(raw)
- if name == "boundary" and value not in _BOUNDARIES:
+ str_value = str(raw)
+ if name == "boundary" and str_value not in _BOUNDARIES:
return default
- return value
+ return str_value
return raw
diff --git a/deeptutor/services/memory/snapshot/__init__.py b/deeptutor/services/memory/snapshot/__init__.py
index d4cf3921b..89d11f2d6 100644
--- a/deeptutor/services/memory/snapshot/__init__.py
+++ b/deeptutor/services/memory/snapshot/__init__.py
@@ -29,9 +29,7 @@ def read_snapshot(surface: Surface) -> list[Entity]:
return adapters.read_entities(surface)
-def pending_changes(
- surface: Surface, entities: list[Entity] | None = None
-) -> list[ChangeEntry]:
+def pending_changes(surface: Surface, entities: list[Entity] | None = None) -> list[ChangeEntry]:
"""Compute the diff between current workspace and the last persisted state.
Pure / read-only: never writes to ``state.json`` or ``changes.jsonl``.
@@ -69,9 +67,7 @@ def refresh_snapshot(surface: Surface) -> list[ChangeEntry]:
return changes
-def read_changes(
- surface: Surface, *, limit: int = 200, offset: int = 0
-) -> list[ChangeEntry]:
+def read_changes(surface: Surface, *, limit: int = 200, offset: int = 0) -> list[ChangeEntry]:
bound = max(1, min(limit, 1000))
all_changes: list[ChangeEntry] = list(store.iter_changes(surface))
# Most recent first — the file is append-order, reverse it.
diff --git a/deeptutor/services/memory/snapshot/adapters.py b/deeptutor/services/memory/snapshot/adapters.py
index d3166a6d0..8b4e9a915 100644
--- a/deeptutor/services/memory/snapshot/adapters.py
+++ b/deeptutor/services/memory/snapshot/adapters.py
@@ -12,12 +12,11 @@ across refreshes.
from __future__ import annotations
+from datetime import datetime, timezone
import hashlib
import json
import logging
import sqlite3
-from datetime import datetime, timezone
-from pathlib import Path
from deeptutor.services.memory.paths import Surface
from deeptutor.services.memory.snapshot.entity import Entity
@@ -30,7 +29,7 @@ logger = logging.getLogger(__name__)
def _sha1(*parts: object) -> str:
- h = hashlib.sha1()
+ h = hashlib.sha1(usedforsecurity=False)
for part in parts:
if part is None:
continue
@@ -210,9 +209,7 @@ def read_book_entities() -> list[Entity]:
"knowledge_bases": m.get("knowledge_bases", []),
"status": m.get("status", ""),
},
- fingerprint=_sha1(
- title, description, m.get("updated_at"), len(page_titles)
- ),
+ fingerprint=_sha1(title, description, m.get("updated_at"), len(page_titles)),
)
)
return out
@@ -276,11 +273,7 @@ def read_kb_entities() -> list[Entity]:
kb_data = {}
description = kb_data.get("description", "") or ""
versions = kb_data.get("index_versions") or []
- sigs = sorted(
- v.get("signature", "")
- for v in versions
- if isinstance(v, dict)
- )
+ sigs = sorted(v.get("signature", "") for v in versions if isinstance(v, dict))
earliest_created = min(
(
v.get("created_at", "")
@@ -326,8 +319,7 @@ def read_chat_entities() -> list[Entity]:
with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
conn.row_factory = sqlite3.Row
sessions = conn.execute(
- "SELECT id, title, created_at, updated_at FROM sessions "
- "ORDER BY updated_at DESC"
+ "SELECT id, title, created_at, updated_at FROM sessions ORDER BY updated_at DESC"
).fetchall()
for sess in sessions:
sid = sess["id"]
@@ -414,9 +406,7 @@ def read_quiz_entities() -> list[Entity]:
"is_correct": is_correct,
"bookmarked": bool(int(r["bookmarked"] or 0)),
},
- fingerprint=_sha1(
- question, user_answer, correct, is_correct
- ),
+ fingerprint=_sha1(question, user_answer, correct, is_correct),
)
)
except sqlite3.Error as exc:
@@ -450,4 +440,4 @@ def read_entities(surface: Surface) -> list[Entity]:
return []
-SUPPORTED_SURFACES: tuple[Surface, ...] = tuple(_READERS.keys()) # type: ignore[assignment]
+SUPPORTED_SURFACES: tuple[Surface, ...] = tuple(_READERS.keys()) # type: ignore[arg-type,assignment]
diff --git a/deeptutor/services/memory/snapshot/diff.py b/deeptutor/services/memory/snapshot/diff.py
index 7f02ab39d..ef427b043 100644
--- a/deeptutor/services/memory/snapshot/diff.py
+++ b/deeptutor/services/memory/snapshot/diff.py
@@ -41,9 +41,7 @@ def diff_snapshots(
)
)
for entity_id in sorted(prev_keys - curr_keys):
- prior_label = (
- (prev_label_map or {}).get(entity_id, "") or entity_id
- )
+ prior_label = (prev_label_map or {}).get(entity_id, "") or entity_id
out.append(
ChangeEntry(
ts=ts,
diff --git a/deeptutor/services/memory/snapshot/store.py b/deeptutor/services/memory/snapshot/store.py
index 94465d9f4..ca8444da0 100644
--- a/deeptutor/services/memory/snapshot/store.py
+++ b/deeptutor/services/memory/snapshot/store.py
@@ -14,9 +14,9 @@ line-by-line, which is naturally atomic on POSIX filesystems.
from __future__ import annotations
+from dataclasses import asdict
import json
import os
-from dataclasses import asdict
from pathlib import Path
from typing import Iterator
diff --git a/deeptutor/services/memory/store.py b/deeptutor/services/memory/store.py
index ab4cffb0d..0ac6e0ebe 100644
--- a/deeptutor/services/memory/store.py
+++ b/deeptutor/services/memory/store.py
@@ -9,12 +9,12 @@ lazily via context variables.
from __future__ import annotations
import asyncio
-import logging
-import shutil
from dataclasses import dataclass
from datetime import datetime, timezone
+import logging
from pathlib import Path
-from typing import Any, Literal
+import shutil
+from typing import Literal
from deeptutor.services.memory import consolidator, paths, trace
from deeptutor.services.memory.consolidator import ConsolidateResult, OnEvent
@@ -29,7 +29,9 @@ logger = logging.getLogger(__name__)
Layer = Literal["L2", "L3"]
_V1_FILES = ("PROFILE.md", "SUMMARY.md")
-_NO_MEMORY = "(No memory available — interact with DeepTutor and update from the Memory page to build one.)"
+_NO_MEMORY = (
+ "(No memory available — interact with DeepTutor and update from the Memory page to build one.)"
+)
@dataclass
diff --git a/deeptutor/services/memory/trace.py b/deeptutor/services/memory/trace.py
index 179d170fa..d9f26d0bd 100644
--- a/deeptutor/services/memory/trace.py
+++ b/deeptutor/services/memory/trace.py
@@ -9,10 +9,10 @@ don't interleave JSON lines.
from __future__ import annotations
import asyncio
-import json
-import logging
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
+import json
+import logging
from pathlib import Path
from typing import Any, Iterator
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 5ccc59ce8..48a4e7592 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -570,9 +570,7 @@ class TurnRuntimeManager:
# not falsely fail a turn that is still owned by this process.
return execution.task is None or not execution.task.done()
- async def _fail_orphan_running_turn(
- self, turn: dict[str, Any] | None
- ) -> dict[str, Any] | None:
+ async def _fail_orphan_running_turn(self, turn: dict[str, Any] | None) -> dict[str, Any] | None:
"""Finalize a persisted running turn that has no local execution.
Running turns are process-local: after a server/container restart the
@@ -1011,9 +1009,7 @@ class TurnRuntimeManager:
}
@staticmethod
- def _synthesize_error_event(
- turn_id: str, turn: dict[str, Any] | None
- ) -> dict[str, Any] | None:
+ def _synthesize_error_event(turn_id: str, turn: dict[str, Any] | None) -> dict[str, Any] | None:
"""Build a terminal ERROR event from a failed persisted turn."""
error = str((turn or {}).get("error") or "").strip()
if not error:
diff --git a/deeptutor/tools/ask_user.py b/deeptutor/tools/ask_user.py
index b1e2bd005..9dd5e225b 100644
--- a/deeptutor/tools/ask_user.py
+++ b/deeptutor/tools/ask_user.py
@@ -16,7 +16,7 @@ normalised to a single-element list internally.
from __future__ import annotations
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from typing import Any
MAX_QUESTIONS = 3
@@ -122,9 +122,7 @@ def _coerce_questions(questions: Any, question: Any, options: Any) -> list[Any]
return []
-def _build_question(
- raw: Any, idx: int, used_ids: set[str]
-) -> AskUserQuestion | str:
+def _build_question(raw: Any, idx: int, used_ids: set[str]) -> AskUserQuestion | str:
if not isinstance(raw, dict):
return f"Question #{idx + 1} must be an object."
diff --git a/deeptutor/tools/github_query.py b/deeptutor/tools/github_query.py
index d6ec8fc4c..05b878147 100644
--- a/deeptutor/tools/github_query.py
+++ b/deeptutor/tools/github_query.py
@@ -26,10 +26,10 @@ system" message that it can relay to the user.
from __future__ import annotations
import asyncio
+from dataclasses import dataclass
import logging
import shutil
-from dataclasses import dataclass
-from typing import Any, Awaitable, Callable
+from typing import Awaitable, Callable
logger = logging.getLogger(__name__)
@@ -42,9 +42,7 @@ QueryType = str # "pr" | "issue" | "run" | "repo" | "api"
# template — no mutation verbs.
_PR_FIELDS = "title,state,statusCheckRollup,reviews,url,author,createdAt,body"
_ISSUE_FIELDS = "title,state,body,comments,url,author,createdAt,labels"
-_REPO_FIELDS = (
- "description,defaultBranchRef,stargazerCount,forkCount,visibility,url"
-)
+_REPO_FIELDS = "description,defaultBranchRef,stargazerCount,forkCount,visibility,url"
_RUN_FIELDS = "name,status,conclusion,workflowName,event,createdAt,url"
@@ -89,9 +87,7 @@ async def run_github_query(
if not q:
return GithubOutcome(ok=False, error="query_type is required.")
if not t:
- return GithubOutcome(
- ok=False, query_type=q, error="target is required."
- )
+ return GithubOutcome(ok=False, query_type=q, error="target is required.")
is_available = gh_available or _default_gh_available
if not is_available():
@@ -112,10 +108,7 @@ async def run_github_query(
ok=False,
query_type=q,
target=t,
- error=(
- f"Unsupported query_type {q!r}. "
- "Choose one of: pr, issue, run, repo, api."
- ),
+ error=(f"Unsupported query_type {q!r}. Choose one of: pr, issue, run, repo, api."),
)
runner = command_runner or _default_command_runner
@@ -159,25 +152,42 @@ async def run_github_query(
def _build_argv(query_type: str, target: str) -> list[str] | None:
if query_type == "pr":
return [
- "gh", "pr", "view", target,
- "--json", _PR_FIELDS,
+ "gh",
+ "pr",
+ "view",
+ target,
+ "--json",
+ _PR_FIELDS,
]
if query_type == "issue":
return [
- "gh", "issue", "view", target,
- "--json", _ISSUE_FIELDS,
+ "gh",
+ "issue",
+ "view",
+ target,
+ "--json",
+ _ISSUE_FIELDS,
]
if query_type == "run":
return [
- "gh", "run", "list",
- "--repo", target,
- "--limit", "10",
- "--json", _RUN_FIELDS,
+ "gh",
+ "run",
+ "list",
+ "--repo",
+ target,
+ "--limit",
+ "10",
+ "--json",
+ _RUN_FIELDS,
]
if query_type == "repo":
return [
- "gh", "repo", "view", target,
- "--json", _REPO_FIELDS,
+ "gh",
+ "repo",
+ "view",
+ target,
+ "--json",
+ _REPO_FIELDS,
]
if query_type == "api":
# ``gh api`` defaults to GET; we never pass ``--method`` so even
@@ -191,9 +201,7 @@ def _default_gh_available() -> bool:
return shutil.which("gh") is not None
-async def _default_command_runner(
- argv: list[str], timeout_s: float
-) -> tuple[int, str, str]:
+async def _default_command_runner(argv: list[str], timeout_s: float) -> tuple[int, str, str]:
"""Run ``argv`` as a subprocess, time-bounded, capturing stdout+stderr."""
proc = await asyncio.create_subprocess_exec(
*argv,
@@ -201,9 +209,7 @@ async def _default_command_runner(
stderr=asyncio.subprocess.PIPE,
)
try:
- stdout_b, stderr_b = await asyncio.wait_for(
- proc.communicate(), timeout=timeout_s
- )
+ stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=timeout_s)
except asyncio.TimeoutError:
proc.kill()
await proc.wait()
diff --git a/deeptutor/tools/list_notebook.py b/deeptutor/tools/list_notebook.py
index 7d3a3fcb3..db52a60a1 100644
--- a/deeptutor/tools/list_notebook.py
+++ b/deeptutor/tools/list_notebook.py
@@ -17,9 +17,9 @@ quote the rendered list back to the user without reformatting.
from __future__ import annotations
+from dataclasses import dataclass
import datetime as _dt
import logging
-from dataclasses import dataclass
from typing import Any
logger = logging.getLogger(__name__)
@@ -115,23 +115,14 @@ def _render_records(manager: Any, notebook_id: str) -> ListOutcome:
# error message can tell the model the right ids to choose from.
notebooks = manager.list_notebooks() or []
matched = next(
- (
- nb
- for nb in notebooks
- if str(nb.get("id") or "").strip() == notebook_id
- ),
+ (nb for nb in notebooks if str(nb.get("id") or "").strip() == notebook_id),
None,
)
if matched is None:
- valid_ids = ", ".join(
- f"`{nb.get('id')}`" for nb in notebooks if nb.get("id")
- )
+ valid_ids = ", ".join(f"`{nb.get('id')}`" for nb in notebooks if nb.get("id"))
return ListOutcome(
ok=False,
- error=(
- f"Unknown notebook_id {notebook_id!r}. "
- f"Valid ids: {valid_ids or '(none)'}."
- ),
+ error=(f"Unknown notebook_id {notebook_id!r}. Valid ids: {valid_ids or '(none)'}."),
)
try:
@@ -178,9 +169,7 @@ def _render_records(manager: Any, notebook_id: str) -> ListOutcome:
if summary:
lines.append(f" {summary}")
if total > len(sliced):
- lines.append(
- f"\n_(showing {len(sliced)} most-recent of {total} records.)_"
- )
+ lines.append(f"\n_(showing {len(sliced)} most-recent of {total} records.)_")
return ListOutcome(
ok=True,
text="\n".join(lines),
diff --git a/deeptutor/tools/web_fetch.py b/deeptutor/tools/web_fetch.py
index 3dc6e1ad5..a82c0dd2c 100644
--- a/deeptutor/tools/web_fetch.py
+++ b/deeptutor/tools/web_fetch.py
@@ -23,11 +23,11 @@ arguments, not a human):
from __future__ import annotations
+from dataclasses import dataclass
import ipaddress
import logging
import re
import socket
-from dataclasses import dataclass
from typing import Any
from urllib.parse import urlparse
@@ -138,9 +138,7 @@ async def fetch_url_as_markdown(
if len(body) > max_chars:
body = body[:max_chars].rstrip() + "\n…[truncated]"
truncated = True
- return FetchOutcome(
- ok=True, markdown=body, url=final_url, title=title, truncated=truncated
- )
+ return FetchOutcome(ok=True, markdown=body, url=final_url, title=title, truncated=truncated)
# ---------------------------------------------------------------------------
diff --git a/deeptutor/tools/write_note.py b/deeptutor/tools/write_note.py
index c03e6beb5..307134b42 100644
--- a/deeptutor/tools/write_note.py
+++ b/deeptutor/tools/write_note.py
@@ -23,8 +23,8 @@ wires in the live values via ``_augment_tool_kwargs``.
from __future__ import annotations
-import logging
from dataclasses import dataclass
+import logging
from typing import Any, Iterable
logger = logging.getLogger(__name__)
@@ -110,16 +110,11 @@ def write_note(
None,
)
if matched is None:
- valid_ids = ", ".join(
- f"`{nb.get('id')}`" for nb in notebooks if nb.get("id")
- )
+ valid_ids = ", ".join(f"`{nb.get('id')}`" for nb in notebooks if nb.get("id"))
return WriteOutcome(
ok=False,
mode=cleaned_mode,
- error=(
- f"Unknown notebook_id {nid!r}. "
- f"Valid ids: {valid_ids or '(none)'}."
- ),
+ error=(f"Unknown notebook_id {nid!r}. Valid ids: {valid_ids or '(none)'}."),
)
notebook_name = str(matched.get("name") or matched.get("title") or nid)
@@ -212,15 +207,11 @@ def _do_append(
body_parts.append(transcript)
cleaned_content = "\n\n---\n\n".join(body_parts).strip()
if len(cleaned_content) > MAX_CONTENT_CHARS:
- cleaned_content = (
- cleaned_content[:MAX_CONTENT_CHARS].rstrip() + "\n…[truncated]"
- )
+ cleaned_content = cleaned_content[:MAX_CONTENT_CHARS].rstrip() + "\n…[truncated]"
from deeptutor.services.notebook.service import RecordType
- user_query_for_record = current_user_message or _last_user_message(
- conversation_history
- )
+ user_query_for_record = current_user_message or _last_user_message(conversation_history)
try:
outcome = manager.add_record(
@@ -321,9 +312,7 @@ def _do_edit(
cleaned_title = cleaned_title[:MAX_TITLE_CHARS].rstrip() + "…"
cleaned_content = (content or "").strip()
if cleaned_content and len(cleaned_content) > MAX_CONTENT_CHARS:
- cleaned_content = (
- cleaned_content[:MAX_CONTENT_CHARS].rstrip() + "\n…[truncated]"
- )
+ cleaned_content = cleaned_content[:MAX_CONTENT_CHARS].rstrip() + "\n…[truncated]"
cleaned_note = (note or "").strip()
if cleaned_note and len(cleaned_note) > MAX_NOTE_CHARS:
cleaned_note = cleaned_note[:MAX_NOTE_CHARS].rstrip() + "…"
@@ -334,10 +323,7 @@ def _do_edit(
mode="edit",
notebook_id=notebook_id,
notebook_name=notebook_name,
- error=(
- "edit mode requires at least one of `title`, `content`, "
- "or `note` to change."
- ),
+ error=("edit mode requires at least one of `title`, `content`, or `note` to change."),
)
update_kwargs: dict[str, Any] = {}
diff --git a/deeptutor_cli/_tool_result.py b/deeptutor_cli/_tool_result.py
index 987169e4a..a4afafc76 100644
--- a/deeptutor_cli/_tool_result.py
+++ b/deeptutor_cli/_tool_result.py
@@ -82,7 +82,7 @@ class ToolResultEntry:
index: int # 1-based, monotonically increasing per REPL session
label: str # tool name as reported by the stream
- body: str # untruncated text
+ body: str # untruncated text
@dataclass(slots=True)
diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.py
index 790d912e4..557dc7d5c 100644
--- a/deeptutor_cli/chat.py
+++ b/deeptutor_cli/chat.py
@@ -232,10 +232,7 @@ def _apply_command(raw: str, state: ChatState) -> bool:
elif subcommand == "set":
parsed = _parse_config_assignment(parts)
if parsed is None:
- console.print(
- "[yellow]Usage:[/] /config set key=value "
- "or /config set key value"
- )
+ console.print("[yellow]Usage:[/] /config set key=value or /config set key value")
return True
key, value = parsed
state.config[key] = _parse_config_value(value)
diff --git a/deeptutor_cli/init_wizard.py b/deeptutor_cli/init_wizard.py
index 551edd752..a026e6f57 100644
--- a/deeptutor_cli/init_wizard.py
+++ b/deeptutor_cli/init_wizard.py
@@ -25,7 +25,6 @@ import typer
from deeptutor.services.provider_registry import PROVIDERS, ProviderSpec, find_by_name
-
# --- Featured selection ------------------------------------------------------
# Hand-picked, in display order, for the LLM step. Everything else is reachable
# via the "Show all" option. Names match ProviderSpec.name in provider_registry.
@@ -112,6 +111,7 @@ EMBEDDING_FALLBACK_MODELS: dict[str, tuple[str, ...]] = {
# ``deeptutor.services.config.provider_runtime``. Each entry below describes
# how the wizard captures the credentials/config for that provider.
+
@dataclass(frozen=True)
class SearchProviderSpec:
"""How the init wizard handles one search provider."""
@@ -231,7 +231,9 @@ class SearchChoice:
def step_header(console: Console, label: str) -> None:
console.print()
bar = "─" * 8
- console.print(f"[bright_cyan]{bar}[/bright_cyan] [bold]{label}[/bold] [bright_cyan]{bar}[/bright_cyan]")
+ console.print(
+ f"[bright_cyan]{bar}[/bright_cyan] [bold]{label}[/bold] [bright_cyan]{bar}[/bright_cyan]"
+ )
console.print()
@@ -288,6 +290,7 @@ def select_from_options(
table.add_column(style="bright_cyan", justify="right")
table.add_column(style="bold")
table.add_column(style="dim")
+
# Rich Table cells parse markup, so e.g. `[s]` would be eaten as a
# nonexistent tag. Wrap markers in Text so they render verbatim.
def _marker(text: str) -> Text:
@@ -533,7 +536,9 @@ def capture_api_key(
if typer.confirm(offer, default=True):
return from_env
- return typer.prompt(strings["init.api_key_prompt"], default="", hide_input=True, show_default=False)
+ return typer.prompt(
+ strings["init.api_key_prompt"], default="", hide_input=True, show_default=False
+ )
# --- Live /models fetch --------------------------------------------------------
@@ -600,7 +605,12 @@ def fetch_models(
names.append(name)
# Dedupe preserving order
seen: set[str] = set()
- deduped = [n for n in names if not (n in seen or seen.add(n))]
+ deduped: list[str] = []
+ for n in names:
+ if n in seen:
+ continue
+ seen.add(n)
+ deduped.append(n)
if deduped:
ok(console, strings["init.fetch_models_ok"].format(count=len(deduped)))
return deduped
@@ -705,7 +715,12 @@ def fetch_embedding_models(
return []
seen: set[str] = set()
- deduped = [n for n in filtered if not (n in seen or seen.add(n))]
+ deduped: list[str] = []
+ for n in filtered:
+ if n in seen:
+ continue
+ seen.add(n)
+ deduped.append(n)
ok(console, strings["init.fetch_models_ok"].format(count=len(deduped)))
return deduped
@@ -867,9 +882,7 @@ def render_review_panel(
if backend_port is not None and frontend_port is not None:
_row(
strings["init.review_ports"],
- strings["init.review_ports_value"].format(
- backend=backend_port, frontend=frontend_port
- ),
+ strings["init.review_ports_value"].format(backend=backend_port, frontend=frontend_port),
)
console.print(
Panel(
diff --git a/tests/agents/question/test_pipeline.py b/tests/agents/question/test_pipeline.py
index 4b1d30cc4..45906d153 100644
--- a/tests/agents/question/test_pipeline.py
+++ b/tests/agents/question/test_pipeline.py
@@ -18,14 +18,13 @@ import pytest
from deeptutor.agents.question.pipeline import (
CALL_KIND_QUIZ_QUESTION,
+ STAGE_QUIZZING,
QuestionPipeline,
QuizPair,
QuizPlan,
QuizTemplate,
- STAGE_QUIZZING,
)
-
# ---------------------------------------------------------------------------
# Test helpers
# ---------------------------------------------------------------------------
@@ -268,9 +267,7 @@ def test_emit_quiz_question_structures_metadata() -> None:
topic="algebra",
difficulty="easy",
)
- asyncio.run(
- pipeline._emit_quiz_question(stream=bus, qa_pair=qa_pair, index=1, total=3)
- )
+ asyncio.run(pipeline._emit_quiz_question(stream=bus, qa_pair=qa_pair, index=1, total=3))
assert len(bus.contents) == 1
event = bus.contents[0]
assert event["source"] == "deep_question"
@@ -666,9 +663,12 @@ def test_strip_protocol_label_removes_only_leading_label() -> None:
Only the leading protocol label should be stripped; later occurrences
(e.g., the model referencing ``THINK`` inside its own prose) must stay
so the rendered trace remains faithful."""
- assert QuestionPipeline._strip_protocol_label(
- "``THINK``\nfirst I need to check ``TOOL`` mounting."
- ) == "first I need to check ``TOOL`` mounting."
+ assert (
+ QuestionPipeline._strip_protocol_label(
+ "``THINK``\nfirst I need to check ``TOOL`` mounting."
+ )
+ == "first I need to check ``TOOL`` mounting."
+ )
assert QuestionPipeline._strip_protocol_label("``FINISH``\nDone.") == "Done."
assert QuestionPipeline._strip_protocol_label("no label here") == "no label here"
@@ -964,12 +964,8 @@ def test_parse_exam_paper_to_templates_happy_path(monkeypatch, tmp_path: Path) -
)
)
- monkeypatch.setattr(
- mimic_source, "parse_pdf_with_mineru", lambda *a, **k: True
- )
- monkeypatch.setattr(
- mimic_source, "extract_questions_from_paper", lambda *a, **k: True
- )
+ monkeypatch.setattr(mimic_source, "parse_pdf_with_mineru", lambda *a, **k: True)
+ monkeypatch.setattr(mimic_source, "extract_questions_from_paper", lambda *a, **k: True)
templates, trace = asyncio.run(
mimic_source.parse_exam_paper_to_templates(
diff --git a/tests/agents/research/test_block_loop_host_append.py b/tests/agents/research/test_block_loop_host_append.py
index 4a4876ec6..51a37dc8d 100644
--- a/tests/agents/research/test_block_loop_host_append.py
+++ b/tests/agents/research/test_block_loop_host_append.py
@@ -22,8 +22,8 @@ from deeptutor.agents.research.pipeline import (
LABEL_APPEND,
LABEL_FINISH,
LABEL_THINK,
- ResearchPipeline,
ResearchedBlock,
+ ResearchPipeline,
_BlockLoopHost,
)
from deeptutor.agents.research.utils.citation_manager import CitationManager
@@ -43,9 +43,7 @@ def _make_pipeline(monkeypatch: pytest.MonkeyPatch) -> ResearchPipeline:
api_version = None
extra_headers = {}
- monkeypatch.setattr(
- "deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM()
- )
+ monkeypatch.setattr("deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM())
monkeypatch.setattr(
"deeptutor.agents.research.pipeline.get_tool_registry", lambda: _FakeRegistry()
)
@@ -84,11 +82,7 @@ class _ToolRegistry:
return SimpleNamespace(name=name) if name in self.names else None
def get_enabled(self, names):
- return [
- SimpleNamespace(name=name)
- for name in names
- if name in self.names
- ]
+ return [SimpleNamespace(name=name) for name in names if name in self.names]
class _FakeCitationManager:
@@ -160,18 +154,10 @@ def _make_pipeline_with_registry(
api_version = None
extra_headers = {}
- monkeypatch.setattr(
- "deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM()
- )
- monkeypatch.setattr(
- "deeptutor.agents.research.pipeline.get_tool_registry", lambda: registry
- )
- monkeypatch.setattr(
- "deeptutor.agents.research.pipeline.user_has_memory", lambda: False
- )
- monkeypatch.setattr(
- "deeptutor.agents.research.pipeline.user_has_notebooks", lambda: False
- )
+ monkeypatch.setattr("deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM())
+ monkeypatch.setattr("deeptutor.agents.research.pipeline.get_tool_registry", lambda: registry)
+ monkeypatch.setattr("deeptutor.agents.research.pipeline.user_has_memory", lambda: False)
+ monkeypatch.setattr("deeptutor.agents.research.pipeline.user_has_notebooks", lambda: False)
return ResearchPipeline(
language="en",
runtime_config={"queue": {"max_length": 5}},
@@ -228,9 +214,7 @@ async def test_block_host_rejects_finish_before_tool_when_tools_available(
bus = StreamBus()
host, _parent = _make_host(pipeline, queue, bus)
- assert await host.validate_terminal(LABEL_FINISH, "direct answer") == (
- "finish_without_tool"
- )
+ assert await host.validate_terminal(LABEL_FINISH, "direct answer") == ("finish_without_tool")
host._tool_rounds_used = 1
assert await host.validate_terminal(LABEL_FINISH, "after evidence") is None
@@ -403,9 +387,7 @@ async def test_on_intermediate_append_adds_block_and_returns_confirmation(
assert new_block.metadata.get("parent_block_id") == parent.block_id
queue_append_events = [
- e
- for e in events
- if (e.metadata or {}).get("trace_kind") == "queue_append"
+ e for e in events if (e.metadata or {}).get("trace_kind") == "queue_append"
]
assert queue_append_events
assert queue_append_events[-1].metadata["new_block_id"] == new_block.block_id
@@ -422,9 +404,7 @@ async def test_on_intermediate_append_rejects_duplicate(
events, consumer = await _drain_bus(bus)
host, _parent = _make_host(pipeline, queue, bus)
- feedback = await host.on_intermediate(
- LABEL_APPEND, "quantum entanglement basics"
- )
+ feedback = await host.on_intermediate(LABEL_APPEND, "quantum entanglement basics")
await bus.close()
await consumer
@@ -433,9 +413,7 @@ async def test_on_intermediate_append_rejects_duplicate(
# Queue size unchanged.
assert len(queue.blocks) == 1
rejected = [
- e
- for e in events
- if (e.metadata or {}).get("trace_kind") == "queue_append_rejected"
+ e for e in events if (e.metadata or {}).get("trace_kind") == "queue_append_rejected"
]
assert rejected
assert rejected[-1].metadata.get("reason") == "duplicate"
@@ -461,9 +439,7 @@ async def test_on_intermediate_append_rejects_when_queue_full(
# No new block added.
assert len(queue.blocks) == 2
rejected = [
- e
- for e in events
- if (e.metadata or {}).get("trace_kind") == "queue_append_rejected"
+ e for e in events if (e.metadata or {}).get("trace_kind") == "queue_append_rejected"
]
assert rejected
# The retained host emits ``"full"`` as the reason value. (Older
@@ -551,9 +527,7 @@ def test_report_outline_parser_repairs_missing_block_coverage(
blocks,
)
- covered = {
- block_id for section in outline.sections for block_id in section.block_ids
- }
+ covered = {block_id for section in outline.sections for block_id in section.block_ids}
assert covered == {"block_1", "block_2", "block_3"}
assert all(section.block_ids for section in outline.sections)
assert outline.sections[1].title == "Deployment"
diff --git a/tests/agents/research/test_rephrase_loop_host.py b/tests/agents/research/test_rephrase_loop_host.py
index f501f86b8..a78898ec4 100644
--- a/tests/agents/research/test_rephrase_loop_host.py
+++ b/tests/agents/research/test_rephrase_loop_host.py
@@ -43,9 +43,7 @@ class _FakeRegistry:
def _make_pipeline(monkeypatch: pytest.MonkeyPatch) -> ResearchPipeline:
- monkeypatch.setattr(
- "deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM()
- )
+ monkeypatch.setattr("deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM())
monkeypatch.setattr(
"deeptutor.agents.research.pipeline.get_tool_registry", lambda: _FakeRegistry()
)
@@ -117,9 +115,7 @@ async def test_rephrase_force_finalize_returns_empty_text(
pipeline = _make_pipeline(monkeypatch)
host = _make_host(pipeline, max_rounds=3)
- text, completed, calls = await host.force_finalize(
- messages=[], start_iteration=10
- )
+ text, completed, calls = await host.force_finalize(messages=[], start_iteration=10)
assert text == ""
assert completed is False
assert calls == 0
diff --git a/tests/agents/solve/test_pipeline.py b/tests/agents/solve/test_pipeline.py
index 91a06630c..38f882c35 100644
--- a/tests/agents/solve/test_pipeline.py
+++ b/tests/agents/solve/test_pipeline.py
@@ -21,17 +21,16 @@ from typing import Any
import pytest
from deeptutor.agents.solve.pipeline import (
+ _PROTOCOL_STEP,
Plan,
PlanStep,
SolvePipeline,
StepFinish,
- _PROTOCOL_STEP,
)
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.stream_bus import StreamBus
-
# ---------------------------------------------------------------------------
# Plumbing
# ---------------------------------------------------------------------------
@@ -89,9 +88,7 @@ class _ScriptedChatClient:
class _Completions:
async def create(self, **kwargs: Any):
- outer.calls.append(
- {**kwargs, "messages": list(kwargs.get("messages") or [])}
- )
+ outer.calls.append({**kwargs, "messages": list(kwargs.get("messages") or [])})
if not outer._script:
raise RuntimeError("Scripted client exhausted")
return _async_stream(outer._script.pop(0))
@@ -247,9 +244,7 @@ async def test_one_step_happy_path_emits_plan_finish_synthesize(
# Phase 1: planner emits ``PLAN`` + JSON
[
_llm_chunk(content="``PLAN``\n"),
- _llm_chunk(
- content='{"analysis":"single","steps":[{"id":"S1","goal":"answer"}]}'
- ),
+ _llm_chunk(content='{"analysis":"single","steps":[{"id":"S1","goal":"answer"}]}'),
],
# Phase 2: step S1 emits ``FINISH`` directly
[
@@ -406,9 +401,7 @@ async def test_replan_back_edge_reruns_planner(
# First plan
[
_llm_chunk(content="``PLAN``\n"),
- _llm_chunk(
- content='{"analysis":"v1","steps":[{"id":"S1","goal":"old approach"}]}'
- ),
+ _llm_chunk(content='{"analysis":"v1","steps":[{"id":"S1","goal":"old approach"}]}'),
],
# Step S1 of plan v1: REPLAN
[
@@ -418,9 +411,7 @@ async def test_replan_back_edge_reruns_planner(
# Plan v2 (with replan reason in prompt)
[
_llm_chunk(content="``PLAN``\n"),
- _llm_chunk(
- content='{"analysis":"v2","steps":[{"id":"S1","goal":"new approach"}]}'
- ),
+ _llm_chunk(content='{"analysis":"v2","steps":[{"id":"S1","goal":"new approach"}]}'),
],
# Step S1 of plan v2: FINISH
[
@@ -484,9 +475,7 @@ async def test_replan_budget_exhausted_keeps_reason_as_step_content(
[
[
_llm_chunk(content="``PLAN``\n"),
- _llm_chunk(
- content='{"analysis":"a","steps":[{"id":"S1","goal":"go"}]}'
- ),
+ _llm_chunk(content='{"analysis":"a","steps":[{"id":"S1","goal":"go"}]}'),
],
[
_llm_chunk(content="``REPLAN``\n"),
@@ -549,7 +538,11 @@ async def test_step_finish_streams_chunks_live(
# Explain triage → SKIP
[_llm_chunk(content="``SKIP``\n")],
# Synthesize: also chunked
- [_llm_chunk(content="``FINISH``\n"), _llm_chunk(content="Wrap "), _llm_chunk(content="up.")],
+ [
+ _llm_chunk(content="``FINISH``\n"),
+ _llm_chunk(content="Wrap "),
+ _llm_chunk(content="up."),
+ ],
]
)
monkeypatch.setattr(pipeline, "_build_client", lambda: client)
@@ -598,8 +591,26 @@ async def test_step_finish_streams_many_small_chunks(
pipeline = _make_pipeline(monkeypatch)
# 20 chunks of 1–4 chars each.
step_chunks = [
- "L", "et", "'s ", "f", "irst", " ex", "pl", "ore",
- " the", " co", "n", "ce", "pt", ".", " ", "T", "h", "en", ":", " done.",
+ "L",
+ "et",
+ "'s ",
+ "f",
+ "irst",
+ " ex",
+ "pl",
+ "ore",
+ " the",
+ " co",
+ "n",
+ "ce",
+ "pt",
+ ".",
+ " ",
+ "T",
+ "h",
+ "en",
+ ":",
+ " done.",
]
expected_full_text = "".join(step_chunks)
@@ -627,9 +638,7 @@ async def test_step_finish_streams_many_small_chunks(
language="en",
metadata={"turn_id": "t-many"},
)
- payload = await pipeline.run(
- context=context, question=context.user_message, stream=bus
- )
+ payload = await pipeline.run(context=context, question=context.user_message, stream=bus)
await asyncio.sleep(0)
await bus.close()
await consumer
@@ -659,8 +668,7 @@ async def test_step_finish_streams_many_small_chunks(
section_breaks = [
e
for e in events
- if e.type == StreamEventType.CONTENT
- and (e.metadata or {}).get("section_break")
+ if e.type == StreamEventType.CONTENT and (e.metadata or {}).get("section_break")
]
assert section_breaks, "expected at least one section-break event between sections"
assert all(e.content == "\n\n" for e in section_breaks)
@@ -699,7 +707,9 @@ async def test_explain_triage_explain_path_streams_under_finish(
# Deep explain → FINISH with the expansion
[
_llm_chunk(content="``FINISH``\n"),
- _llm_chunk(content="**Intuition:** odd integrand over a symmetric domain integrates to zero."),
+ _llm_chunk(
+ content="**Intuition:** odd integrand over a symmetric domain integrates to zero."
+ ),
],
# Synthesize
[
@@ -757,9 +767,7 @@ async def test_explain_triage_explain_path_streams_under_finish(
assert "</details>" in body
# The wrapping events carry a ``details_wrapper`` flag so the frontend
# / tests can distinguish them from the LLM body.
- wrapper_events = [
- e for e in events if (e.metadata or {}).get("details_wrapper")
- ]
+ wrapper_events = [e for e in events if (e.metadata or {}).get("details_wrapper")]
assert len(wrapper_events) == 2, (
f"Expected exactly 2 details-wrapper events (open + close), got {len(wrapper_events)}"
)
@@ -771,8 +779,7 @@ async def test_explain_triage_explain_path_streams_under_finish(
section_breaks = [
e
for e in events
- if e.type == StreamEventType.CONTENT
- and (e.metadata or {}).get("section_break")
+ if e.type == StreamEventType.CONTENT and (e.metadata or {}).get("section_break")
]
assert len(section_breaks) == 2, (
f"Expected 2 section breaks (after FINISH, after EXPLAIN), got {len(section_breaks)}"
@@ -799,9 +806,7 @@ async def test_pipeline_failure_surfaces_visible_error_and_reraises(
async def create(self, **kwargs: Any):
raise RuntimeError("simulated upstream failure")
- failing_client = SimpleNamespace(
- chat=SimpleNamespace(completions=_FailingCompletions())
- )
+ failing_client = SimpleNamespace(chat=SimpleNamespace(completions=_FailingCompletions()))
monkeypatch.setattr(pipeline, "_build_client", lambda: failing_client)
bus = StreamBus()
diff --git a/tests/api/test_memory_resolver.py b/tests/api/test_memory_resolver.py
index 744c05e82..3e14c2474 100644
--- a/tests/api/test_memory_resolver.py
+++ b/tests/api/test_memory_resolver.py
@@ -48,9 +48,7 @@ def _seed_l2(tmp_path: Path, surface: str, entry_id: str) -> None:
),
],
)
- (tmp_path / "L2" / f"{surface}.md").write_text(
- document_mod.serialize(doc), encoding="utf-8"
- )
+ (tmp_path / "L2" / f"{surface}.md").write_text(document_mod.serialize(doc), encoding="utf-8")
def test_resolve_entry_returns_owning_surface(client: TestClient, tmp_path: Path) -> None:
diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py
index c35a1e8c5..c2ff35335 100644
--- a/tests/cli/test_chat_cli.py
+++ b/tests/cli/test_chat_cli.py
@@ -116,7 +116,7 @@ def test_chat_repl_config_commands_match_docs_syntax(monkeypatch) -> None:
["chat", "--config", "initial=true"],
input=(
"/config set num_questions 5\n"
- "/config set question_types '[\"short_answer\",\"mcq\"]'\n"
+ '/config set question_types \'["short_answer","mcq"]\'\n'
"/refs\n"
"Generate questions\n"
"/quit\n"
diff --git a/tests/core/test_agentic_labels.py b/tests/core/test_agentic_labels.py
index d9b116457..1e7baf4c4 100644
--- a/tests/core/test_agentic_labels.py
+++ b/tests/core/test_agentic_labels.py
@@ -1,6 +1,5 @@
from deeptutor.core.agentic.labels import classify_label, find_inline_labels
-
_ALLOWED = ("FINISH", "TOOL", "THINK", "PAUSE")
@@ -56,7 +55,10 @@ def test_find_inline_labels_detects_tolerated_label_variants() -> None:
def test_find_inline_labels_ignores_prose_mentions() -> None:
- assert find_inline_labels(
- "I should use ``TOOL`` next, then finish with ``FINISH``.",
- allowed_labels=_ALLOWED,
- ) == []
+ assert (
+ find_inline_labels(
+ "I should use ``TOOL`` next, then finish with ``FINISH``.",
+ allowed_labels=_ALLOWED,
+ )
+ == []
+ )
diff --git a/tests/core/test_agentic_loop_intermediate.py b/tests/core/test_agentic_loop_intermediate.py
index f8f034be8..e6753ca92 100644
--- a/tests/core/test_agentic_loop_intermediate.py
+++ b/tests/core/test_agentic_loop_intermediate.py
@@ -20,17 +20,12 @@ from deeptutor.core.agentic.loop import LabelProtocol, run_agentic_loop
from deeptutor.core.agentic.tool_dispatch import DispatchOutcome
from deeptutor.core.stream_bus import StreamBus
-
# --------------------------- scripted LLM client ---------------------------
def _llm_chunk(content: str) -> SimpleNamespace:
return SimpleNamespace(
- choices=[
- SimpleNamespace(
- delta=SimpleNamespace(content=content, tool_calls=None)
- )
- ]
+ choices=[SimpleNamespace(delta=SimpleNamespace(content=content, tool_calls=None))]
)
@@ -75,9 +70,7 @@ class _BaseHost:
async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:
return None
- def build_iteration_trace_meta(
- self, iteration: int
- ) -> tuple[dict[str, Any], dict[str, Any]]:
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
return ({"iter": iteration}, {"iter": iteration, "final": True})
async def dispatch_tools(self, *, iteration, tool_calls): # pragma: no cover
@@ -199,9 +192,7 @@ async def test_loop_calls_on_intermediate_and_injects_feedback() -> None:
(a) be called with the label + text, and
(b) have its non-empty return value injected as a user message
visible to the next LLM iteration."""
- client = _ScriptedClient(
- _script_for_two_iterations("APPEND", "Quantum entanglement basics")
- )
+ client = _ScriptedClient(_script_for_two_iterations("APPEND", "Quantum entanglement basics"))
host = _AppendHost()
bus = StreamBus()
@@ -236,14 +227,10 @@ async def test_loop_calls_on_intermediate_and_injects_feedback() -> None:
# Iteration 2's messages must include both the assistant APPEND
# prose AND a user feedback note carrying the host's confirmation.
iter2_msgs = client.calls[1]
- assistant_texts = [
- m.get("content") or "" for m in iter2_msgs if m.get("role") == "assistant"
- ]
+ assistant_texts = [m.get("content") or "" for m in iter2_msgs if m.get("role") == "assistant"]
user_texts = [m.get("content") or "" for m in iter2_msgs if m.get("role") == "user"]
assert any("Quantum entanglement basics" in t for t in assistant_texts)
- assert any(
- "Appended block #1: Quantum entanglement basics" in t for t in user_texts
- )
+ assert any("Appended block #1: Quantum entanglement basics" in t for t in user_texts)
@pytest.mark.asyncio
@@ -300,9 +287,7 @@ async def test_loop_validate_terminal_can_repair_premature_finish() -> None:
assert outcome.completed is True
assert outcome.final_text.strip() == "Evidence-backed synthesis"
assert host.rejections == 1
- iter2_user_texts = [
- m.get("content") or "" for m in client.calls[1] if m.get("role") == "user"
- ]
+ iter2_user_texts = [m.get("content") or "" for m in client.calls[1] if m.get("role") == "user"]
assert any("repair:finish_without_tool" in t for t in iter2_user_texts)
@@ -376,9 +361,7 @@ async def test_intermediate_label_in_final_set_streams_body_and_continues() -> N
assert host.emit_final_calls[1].strip() == "here is the answer"
# The PAUSE prose is also kept as assistant context for iteration 2.
iter2_msgs = client.calls[1]
- assistant_texts = [
- m.get("content") or "" for m in iter2_msgs if m.get("role") == "assistant"
- ]
+ assistant_texts = [m.get("content") or "" for m in iter2_msgs if m.get("role") == "assistant"]
assert any("let me check first" in t for t in assistant_texts)
@@ -444,12 +427,8 @@ async def test_before_iteration_hook_runs_each_iteration() -> None:
# Fired twice — once per iteration, with the right counters.
assert host.fired == [(0, 5), (1, 5)]
# Both LLM calls saw a marker in their messages tail.
- iter1_markers = [
- m for m in client.calls[0] if "[marker]" in (m.get("content") or "")
- ]
- iter2_markers = [
- m for m in client.calls[1] if "[marker]" in (m.get("content") or "")
- ]
+ iter1_markers = [m for m in client.calls[0] if "[marker]" in (m.get("content") or "")]
+ iter2_markers = [m for m in client.calls[1] if "[marker]" in (m.get("content") or "")]
assert any("1/5" in m.get("content", "") for m in iter1_markers)
assert any("2/5" in m.get("content", "") for m in iter2_markers)
diff --git a/tests/core/test_labeled_step_think_prelude.py b/tests/core/test_labeled_step_think_prelude.py
index 275d4b703..25fe52d85 100644
--- a/tests/core/test_labeled_step_think_prelude.py
+++ b/tests/core/test_labeled_step_think_prelude.py
@@ -31,11 +31,7 @@ from deeptutor.core.stream_bus import StreamBus
def _chunk(content: str | None = None, tool_calls: Any = None) -> SimpleNamespace:
return SimpleNamespace(
- choices=[
- SimpleNamespace(
- delta=SimpleNamespace(content=content, tool_calls=tool_calls)
- )
- ],
+ choices=[SimpleNamespace(delta=SimpleNamespace(content=content, tool_calls=tool_calls))],
usage=None,
)
@@ -342,9 +338,7 @@ async def test_prelude_then_tool_call_routes_correctly() -> None:
)
assert result.label == "TOOL"
- assert result.tool_calls == [
- {"id": "call_1", "name": "search", "arguments": '{"q": "x"}'}
- ]
+ assert result.tool_calls == [{"id": "call_1", "name": "search", "arguments": '{"q": "x"}'}]
assert result.text == "Calling search now."
joined_think = "".join(_thinking_texts(events))
assert "need to look this up" in joined_think
@@ -364,9 +358,7 @@ async def test_tool_calls_mid_prelude_close_prelude_synthetically() -> None:
)
assert result.label == "TOOL"
- assert result.tool_calls == [
- {"id": "call_a", "name": "lookup", "arguments": '{"k":1}'}
- ]
+ assert result.tool_calls == [{"id": "call_a", "name": "lookup", "arguments": '{"k":1}'}]
# Even though </think> never arrived, the returned text must not leak
# the prelude content (clean_thinking_tags strips the synthesized block).
assert "<think>" not in result.text
diff --git a/tests/services/memory/test_chunker.py b/tests/services/memory/test_chunker.py
index 4415377a7..baf748e41 100644
--- a/tests/services/memory/test_chunker.py
+++ b/tests/services/memory/test_chunker.py
@@ -11,8 +11,18 @@ from deeptutor.services.memory.consolidator.chunker import (
def test_empty_input_returns_no_chunks() -> None:
- assert chunk_with_boundary("", budget=5, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=1000) == []
- assert chunk_with_boundary(" \n\n", budget=5, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=1000) == []
+ assert (
+ chunk_with_boundary(
+ "", budget=5, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=1000
+ )
+ == []
+ )
+ assert (
+ chunk_with_boundary(
+ " \n\n", budget=5, overlap_ratio=0.1, min_chunk_chars=100, max_chunk_chars=1000
+ )
+ == []
+ )
def test_short_input_yields_one_chunk_covering_everything() -> None:
@@ -27,7 +37,12 @@ def test_short_input_yields_one_chunk_covering_everything() -> None:
def test_paragraph_boundary_extends_right_edge() -> None:
text = "A" * 100 + "\n\n" + "B" * 100 + "\n\n" + "C" * 100
chunks = chunk_with_boundary(
- text, budget=2, overlap_ratio=0.0, min_chunk_chars=50, max_chunk_chars=400, boundary="paragraph"
+ text,
+ budget=2,
+ overlap_ratio=0.0,
+ min_chunk_chars=50,
+ max_chunk_chars=400,
+ boundary="paragraph",
)
# First chunk's end should land at a paragraph boundary (or end of text when budget=1).
assert chunks[0].text.endswith("\n\n") or chunks[0].end == len(text)
@@ -52,7 +67,7 @@ def test_sentence_boundary_used_when_configured() -> None:
def test_budget_caps_chunk_count() -> None:
- text = ("paragraph body. " * 20 + "\n\n") * 30 # ~ 10k chars
+ text = ("paragraph body. " * 20 + "\n\n") * 30 # ~ 10k chars
chunks = chunk_with_boundary(
text, budget=5, overlap_ratio=0.1, min_chunk_chars=200, max_chunk_chars=8000
)
@@ -88,6 +103,7 @@ def test_max_chunk_chars_protects_against_huge_chunks() -> None:
assert len(chunks) > 1
assert all(c.end - c.start <= 5000 * 2 for c in chunks) # boundary extension may push over
+
@pytest.mark.parametrize("budget", [1, 5, 20, 100])
def test_no_data_loss_chunks_cover_full_text(budget: int) -> None:
text = "\n\n".join(f"para {i}: " + "x" * 50 for i in range(50))
diff --git a/tests/services/memory/test_line_doc.py b/tests/services/memory/test_line_doc.py
index 6e77487cd..aa9889fe0 100644
--- a/tests/services/memory/test_line_doc.py
+++ b/tests/services/memory/test_line_doc.py
@@ -22,14 +22,29 @@ def _doc_with_three_entries() -> tuple[Document, list[str]]:
(
"Themes",
[
- Entry(id=ids[0], section="Themes", text="uses spaced repetition", refs=["notebook:r1"]),
- Entry(id=ids[1], section="Themes", text="prefers Anki over Quizlet", refs=["notebook:r2"]),
+ Entry(
+ id=ids[0],
+ section="Themes",
+ text="uses spaced repetition",
+ refs=["notebook:r1"],
+ ),
+ Entry(
+ id=ids[1],
+ section="Themes",
+ text="prefers Anki over Quizlet",
+ refs=["notebook:r2"],
+ ),
],
),
(
"Open questions",
[
- Entry(id=ids[2], section="Open questions", text="ε-δ geometric meaning", refs=["notebook:r3"]),
+ Entry(
+ id=ids[2],
+ section="Open questions",
+ text="ε-δ geometric meaning",
+ refs=["notebook:r3"],
+ ),
],
),
],
diff --git a/tests/services/memory/test_meta_settings.py b/tests/services/memory/test_meta_settings.py
index 2435ab044..bd9e4ebc1 100644
--- a/tests/services/memory/test_meta_settings.py
+++ b/tests/services/memory/test_meta_settings.py
@@ -29,9 +29,16 @@ def test_settings_defaults_match_spec() -> None:
def test_settings_partial_payload_falls_back_to_defaults() -> None:
- with patch.object(load_memory_settings.__wrapped__ if hasattr(load_memory_settings, "__wrapped__") else load_memory_settings, "__call__", create=True):
+ with patch.object(
+ load_memory_settings.__wrapped__
+ if hasattr(load_memory_settings, "__wrapped__")
+ else load_memory_settings,
+ "__call__",
+ create=True,
+ ):
pass # no-op; the next assertion exercises the real coercion path
from deeptutor.services.memory.settings import _from_dict
+
merged = _from_dict(
MemorySettings,
{"update": {"l2_budget": 42}, "chunking": {"overlap_ratio": 0.25}},
@@ -44,6 +51,7 @@ def test_settings_partial_payload_falls_back_to_defaults() -> None:
def test_settings_clamps_out_of_range_values() -> None:
from deeptutor.services.memory.settings import _from_dict
+
merged = _from_dict(
MemorySettings,
{
diff --git a/tests/services/memory/test_modes.py b/tests/services/memory/test_modes.py
index 9120bbaf3..bbe4c0d0b 100644
--- a/tests/services/memory/test_modes.py
+++ b/tests/services/memory/test_modes.py
@@ -14,9 +14,9 @@ from unittest.mock import patch
import pytest
from deeptutor.services.memory import paths as paths_mod
-from deeptutor.services.memory.consolidator.modes import update as update_mod
from deeptutor.services.memory.consolidator.modes import audit as audit_mod
from deeptutor.services.memory.consolidator.modes import dedup as dedup_mod
+from deeptutor.services.memory.consolidator.modes import update as update_mod
from deeptutor.services.memory.document import Document, Entry, parse, serialize
from deeptutor.services.memory.ids import new_entry_id
from deeptutor.services.memory.snapshot.entity import Entity
@@ -63,9 +63,16 @@ async def test_update_l2_appends_facts_from_chunk(memory_dir, monkeypatch):
return '{"facts": []}'
# Force a tiny chunker so each entity ends up in its own chunk.
- with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=fake_llm), \
- patch.object(update_mod, "load_memory_settings") as mock_settings:
- from deeptutor.services.memory.settings import MemorySettings, ChunkingSettings, DedupSettings
+ with (
+ patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=fake_llm),
+ patch.object(update_mod, "load_memory_settings") as mock_settings,
+ ):
+ from deeptutor.services.memory.settings import (
+ ChunkingSettings,
+ DedupSettings,
+ MemorySettings,
+ )
+
mock_settings.return_value = MemorySettings(
chunking=ChunkingSettings(min_chunk_chars=200, max_chunk_chars=400, overlap_ratio=0.0),
dedup=DedupSettings(auto_after_update=False),
@@ -91,9 +98,15 @@ async def test_update_l2_idempotent_when_no_new_entities(memory_dir, monkeypatch
async def llm_returns_one(*, system_prompt, user_prompt, **kwargs):
return '{"facts": [{"text": "uses Anki", "section": "Topics", "refs": ["chat:01ABC"]}]}'
- with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=llm_returns_one), \
- patch.object(update_mod, "load_memory_settings") as mock_settings:
- from deeptutor.services.memory.settings import MemorySettings, DedupSettings
+ with (
+ patch(
+ "deeptutor.services.memory.consolidator.modes.update.call_llm",
+ side_effect=llm_returns_one,
+ ),
+ patch.object(update_mod, "load_memory_settings") as mock_settings,
+ ):
+ from deeptutor.services.memory.settings import DedupSettings, MemorySettings
+
mock_settings.return_value = MemorySettings(dedup=DedupSettings(auto_after_update=False))
first = await update_mod.run_update("L2", "chat", language="en")
assert first.facts_added >= 0
@@ -106,9 +119,15 @@ async def test_update_l2_idempotent_when_no_new_entities(memory_dir, monkeypatch
llm_called.append(1)
return '{"facts": []}'
- with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=llm_should_not_run), \
- patch.object(update_mod, "load_memory_settings") as mock_settings:
- from deeptutor.services.memory.settings import MemorySettings, DedupSettings
+ with (
+ patch(
+ "deeptutor.services.memory.consolidator.modes.update.call_llm",
+ side_effect=llm_should_not_run,
+ ),
+ patch.object(update_mod, "load_memory_settings") as mock_settings,
+ ):
+ from deeptutor.services.memory.settings import DedupSettings, MemorySettings
+
mock_settings.return_value = MemorySettings(dedup=DedupSettings(auto_after_update=False))
second = await update_mod.run_update("L2", "chat", language="en")
assert second.no_new_input is True
@@ -125,11 +144,20 @@ async def test_update_l2_drops_facts_with_out_of_pool_refs(memory_dir, monkeypat
async def fake_llm(*, system_prompt, user_prompt, **kwargs):
# Return one fact with a ref not in the chunk pool.
- return '{"facts": [{"text": "uses Anki", "section": "Topics", "refs": ["chat:NOT_IN_CHUNK"]}]}'
+ return (
+ '{"facts": [{"text": "uses Anki", "section": "Topics", "refs": ["chat:NOT_IN_CHUNK"]}]}'
+ )
+
+ with (
+ patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=fake_llm),
+ patch.object(update_mod, "load_memory_settings") as mock_settings,
+ ):
+ from deeptutor.services.memory.settings import (
+ DedupSettings,
+ MemorySettings,
+ ReferenceSettings,
+ )
- with patch("deeptutor.services.memory.consolidator.modes.update.call_llm", side_effect=fake_llm), \
- patch.object(update_mod, "load_memory_settings") as mock_settings:
- from deeptutor.services.memory.settings import MemorySettings, DedupSettings, ReferenceSettings
mock_settings.return_value = MemorySettings(
dedup=DedupSettings(auto_after_update=False),
reference=ReferenceSettings(enforce_required=True, drop_invalid_refs=True),
@@ -150,7 +178,9 @@ async def test_audit_l2_applies_replace_edit(memory_dir, monkeypatch):
ids = [new_entry_id()]
doc = Document(
title="chat memory",
- sections=[("Topics", [Entry(id=ids[0], section="Topics", text="claims X", refs=["chat:01ABC"])])],
+ sections=[
+ ("Topics", [Entry(id=ids[0], section="Topics", text="claims X", refs=["chat:01ABC"])])
+ ],
)
path = memory_dir / "L2" / "chat.md"
path.write_text(serialize(doc), encoding="utf-8")
@@ -210,10 +240,15 @@ async def test_dedup_early_stop_when_no_edits(memory_dir, monkeypatch):
llm_calls.append(1)
return '{"edits": []}'
- with patch("deeptutor.services.memory.consolidator.modes.dedup.call_llm", side_effect=fake_llm), \
- patch.object(dedup_mod, "load_memory_settings") as mock_settings:
- from deeptutor.services.memory.settings import MemorySettings, DedupSettings
- mock_settings.return_value = MemorySettings(dedup=DedupSettings(iterations=5, auto_after_update=False))
+ with (
+ patch("deeptutor.services.memory.consolidator.modes.dedup.call_llm", side_effect=fake_llm),
+ patch.object(dedup_mod, "load_memory_settings") as mock_settings,
+ ):
+ from deeptutor.services.memory.settings import DedupSettings, MemorySettings
+
+ mock_settings.return_value = MemorySettings(
+ dedup=DedupSettings(iterations=5, auto_after_update=False)
+ )
result = await dedup_mod.run_dedup("L2", "chat", language="en")
assert result.converged_early is True
@@ -264,10 +299,15 @@ async def test_dedup_applies_delete_then_stops(memory_dir, monkeypatch):
)
return '{"edits": []}'
- with patch("deeptutor.services.memory.consolidator.modes.dedup.call_llm", side_effect=fake_llm), \
- patch.object(dedup_mod, "load_memory_settings") as mock_settings:
- from deeptutor.services.memory.settings import MemorySettings, DedupSettings
- mock_settings.return_value = MemorySettings(dedup=DedupSettings(iterations=3, auto_after_update=False))
+ with (
+ patch("deeptutor.services.memory.consolidator.modes.dedup.call_llm", side_effect=fake_llm),
+ patch.object(dedup_mod, "load_memory_settings") as mock_settings,
+ ):
+ from deeptutor.services.memory.settings import DedupSettings, MemorySettings
+
+ mock_settings.return_value = MemorySettings(
+ dedup=DedupSettings(iterations=3, auto_after_update=False)
+ )
result = await dedup_mod.run_dedup("L2", "chat", language="en")
assert result.edits_applied >= 1
diff --git a/tests/services/memory/test_ops.py b/tests/services/memory/test_ops.py
index 09b133a0e..0b7bca411 100644
--- a/tests/services/memory/test_ops.py
+++ b/tests/services/memory/test_ops.py
@@ -3,7 +3,6 @@ from __future__ import annotations
from deeptutor.services.memory.document import Document, Entry, parse
from deeptutor.services.memory.ops import AddOp, ApplyReport, DeleteOp, EditOp, apply
-
_BASE_MD = """\
# Chat memory
diff --git a/tests/services/memory/test_runs.py b/tests/services/memory/test_runs.py
index ace1cc585..a732ab772 100644
--- a/tests/services/memory/test_runs.py
+++ b/tests/services/memory/test_runs.py
@@ -24,9 +24,7 @@ async def test_start_runs_to_completion_and_buffers_events(manager: RunManager)
await on_event({"stage": "progress", "turn": 1})
await on_event({"stage": "progress", "turn": 2})
- run = await manager.start(
- layer="L2", key="chat", mode="update", runner=runner
- )
+ run = await manager.start(layer="L2", key="chat", mode="update", runner=runner)
if run._task is not None:
await run._task
assert run.status == "done"
@@ -120,9 +118,7 @@ async def test_run_records_error_when_runner_raises(manager: RunManager) -> None
@pytest.mark.asyncio
-async def test_undo_last_restores_previous_document(
- manager: RunManager, tmp_path
-) -> None:
+async def test_undo_last_restores_previous_document(manager: RunManager, tmp_path) -> None:
path = tmp_path / "chat.md"
path.write_text("before", encoding="utf-8")
diff --git a/tests/tools/test_ask_user.py b/tests/tools/test_ask_user.py
index 3d0c78a13..a90385247 100644
--- a/tests/tools/test_ask_user.py
+++ b/tests/tools/test_ask_user.py
@@ -14,7 +14,6 @@ from deeptutor.tools.ask_user import (
build_ask_user_payload,
)
-
# ----------------------------- legacy shape -----------------------------
@@ -162,9 +161,7 @@ def test_v2_rejects_non_array_questions() -> None:
def test_v2_accepts_question_alias_for_prompt() -> None:
"""LLMs sometimes use ``question`` instead of ``prompt`` inside a v2 item."""
- payload, err = build_ask_user_payload(
- questions=[{"question": "what?", "options": ["a", "b"]}]
- )
+ payload, err = build_ask_user_payload(questions=[{"question": "what?", "options": ["a", "b"]}])
assert err is None
assert payload is not None
assert payload.questions[0].prompt == "what?"
@@ -186,9 +183,7 @@ def test_v2_allow_free_text_can_be_disabled() -> None:
def test_v2_placeholder_stored() -> None:
- payload, _ = build_ask_user_payload(
- questions=[{"prompt": "x", "placeholder": "type here"}]
- )
+ payload, _ = build_ask_user_payload(questions=[{"prompt": "x", "placeholder": "type here"}])
assert payload is not None
assert payload.questions[0].placeholder == "type here"
diff --git a/tests/tools/test_github_query.py b/tests/tools/test_github_query.py
index 28342a2b8..79a731b45 100644
--- a/tests/tools/test_github_query.py
+++ b/tests/tools/test_github_query.py
@@ -12,8 +12,8 @@ from typing import Any
import pytest
from deeptutor.tools.github_query import (
- GithubOutcome,
MAX_OUTPUT_CHARS,
+ GithubOutcome,
run_github_query,
)
@@ -105,8 +105,16 @@ async def test_pr_argv_is_view_only() -> None:
gh_available=lambda: True,
command_runner=_runner(stdout='{"title":"x"}', record=record),
)
- assert record == [["gh", "pr", "view", "owner/repo#42", "--json",
- "title,state,statusCheckRollup,reviews,url,author,createdAt,body"]]
+ assert record == [
+ [
+ "gh",
+ "pr",
+ "view",
+ "owner/repo#42",
+ "--json",
+ "title,state,statusCheckRollup,reviews,url,author,createdAt,body",
+ ]
+ ]
@pytest.mark.asyncio
@@ -128,7 +136,7 @@ async def test_run_argv_uses_list_subcommand() -> None:
query_type="run",
target="owner/repo",
gh_available=lambda: True,
- command_runner=_runner(stdout='[]', record=record),
+ command_runner=_runner(stdout="[]", record=record),
)
assert record[0][:5] == ["gh", "run", "list", "--repo", "owner/repo"]
@@ -142,7 +150,7 @@ async def test_api_argv_does_not_set_method() -> None:
query_type="api",
target="repos/owner/repo/issues",
gh_available=lambda: True,
- command_runner=_runner(stdout='[]', record=record),
+ command_runner=_runner(stdout="[]", record=record),
)
assert "--method" not in record[0]
assert "-X" not in record[0]
diff --git a/tests/tools/test_list_notebook.py b/tests/tools/test_list_notebook.py
index 810880480..4443e7e28 100644
--- a/tests/tools/test_list_notebook.py
+++ b/tests/tools/test_list_notebook.py
@@ -86,9 +86,7 @@ def test_drilldown_rejects_unknown_notebook_id() -> None:
manager = _FakeManager(
notebooks=[{"id": "nb-1", "name": "Math"}],
)
- outcome = list_notebooks_or_records(
- notebook_id="bogus", notebook_manager=manager
- )
+ outcome = list_notebooks_or_records(notebook_id="bogus", notebook_manager=manager)
assert outcome.ok is False
assert "Unknown notebook_id" in outcome.error
assert "`nb-1`" in outcome.error # tells the LLM the right id to use
diff --git a/tests/tools/test_web_fetch.py b/tests/tools/test_web_fetch.py
index 1d2c5553c..0884c445a 100644
--- a/tests/tools/test_web_fetch.py
+++ b/tests/tools/test_web_fetch.py
@@ -12,7 +12,6 @@ from deeptutor.tools.web_fetch import (
fetch_url_as_markdown,
)
-
# ---------------------------------------------------------------------------
# Host validation
# ---------------------------------------------------------------------------
@@ -21,8 +20,14 @@ from deeptutor.tools.web_fetch import (
@pytest.mark.parametrize(
"host",
[
- "127.0.0.1", "localhost", "10.0.0.1", "192.168.1.1",
- "169.254.1.1", "::1", "[::1]", "metadata.local",
+ "127.0.0.1",
+ "localhost",
+ "10.0.0.1",
+ "192.168.1.1",
+ "169.254.1.1",
+ "::1",
+ "[::1]",
+ "metadata.local",
],
)
def test_is_disallowed_host_blocks_private_addresses(host: str) -> None:
@@ -171,9 +176,7 @@ async def test_fetch_truncates_at_max_chars() -> None:
async def test_fetch_propagates_http_error_as_outcome_not_exception() -> None:
outcome = await fetch_url_as_markdown(
"https://example.com/missing",
- client_factory=_factory_returning(
- _StubResponse(status=404, body=b"<p>missing</p>")
- ),
+ client_factory=_factory_returning(_StubResponse(status=404, body=b"<p>missing</p>")),
host_validator=_ALLOW_ALL,
)
assert outcome.ok is False
diff --git a/tests/tools/test_write_note.py b/tests/tools/test_write_note.py
index 9bf08918c..962c5c948 100644
--- a/tests/tools/test_write_note.py
+++ b/tests/tools/test_write_note.py
@@ -187,9 +187,7 @@ def test_append_refuses_empty_history_without_content() -> None:
def test_append_surfaces_manager_errors_as_outcome() -> None:
- manager = _FakeManager(
- notebooks=[{"id": "nb-1", "name": "N"}], raise_on_add=True
- )
+ manager = _FakeManager(notebooks=[{"id": "nb-1", "name": "N"}], raise_on_add=True)
outcome = write_note(
mode="append",
notebook_id="nb-1",
diff --git a/web/app/(utility)/memory/l2/[surface]/page.tsx b/web/app/(utility)/memory/l2/[surface]/page.tsx
index c2724d4fc..a2764b547 100644
--- a/web/app/(utility)/memory/l2/[surface]/page.tsx
+++ b/web/app/(utility)/memory/l2/[surface]/page.tsx
@@ -5,7 +5,15 @@ import { Suspense } from "react";
import MemoryWorkbench from "@/components/memory/MemoryWorkbench";
-const SURFACES = ["chat", "notebook", "quiz", "kb", "book", "tutorbot", "cowriter"];
+const SURFACES = [
+ "chat",
+ "notebook",
+ "quiz",
+ "kb",
+ "book",
+ "tutorbot",
+ "cowriter",
+];
function L2WorkbenchInner() {
// ``?focus=m_xxx`` is the deep-link contract used by the resolver
@@ -18,7 +26,9 @@ function L2WorkbenchInner() {
notFound();
}
const focus = search.get("focus") || undefined;
- return <MemoryWorkbench layer="L2" initialKey={surface} initialFocus={focus} />;
+ return (
+ <MemoryWorkbench layer="L2" initialKey={surface} initialFocus={focus} />
+ );
}
export default function MemoryL2WorkbenchPage() {
diff --git a/web/app/(utility)/memory/resolve/page.tsx b/web/app/(utility)/memory/resolve/page.tsx
index c6f967077..147c60f6d 100644
--- a/web/app/(utility)/memory/resolve/page.tsx
+++ b/web/app/(utility)/memory/resolve/page.tsx
@@ -38,7 +38,10 @@ function ResolveInner() {
if (cancelled) return;
setError(
res.status === 404
- ? t("Entry {{id}} not found in any L2 doc — it may have been deleted.", { id })
+ ? t(
+ "Entry {{id}} not found in any L2 doc — it may have been deleted.",
+ { id },
+ )
: t("Resolver failed ({{code}})", { code: res.status }),
);
return;
diff --git a/web/app/(utility)/settings/capabilities/page.tsx b/web/app/(utility)/settings/capabilities/page.tsx
index e55a336c5..102ecbf27 100644
--- a/web/app/(utility)/settings/capabilities/page.tsx
+++ b/web/app/(utility)/settings/capabilities/page.tsx
@@ -62,7 +62,9 @@ interface CapabilitiesSettingsDTO {
math_animator: SimpleLLMBlock;
}
-function isValidCapabilitiesDTO(value: unknown): value is CapabilitiesSettingsDTO {
+function isValidCapabilitiesDTO(
+ value: unknown,
+): value is CapabilitiesSettingsDTO {
if (!value || typeof value !== "object") return false;
const v = value as Record<string, unknown>;
const chat = v.chat as Record<string, unknown> | undefined;
@@ -83,7 +85,9 @@ function isValidCapabilitiesDTO(value: unknown): value is CapabilitiesSettingsDT
export default function CapabilitiesSettingsPage() {
const { t } = useTranslation();
const { registerExtension } = useSettings();
- const [settings, setSettings] = useState<CapabilitiesSettingsDTO | null>(null);
+ const [settings, setSettings] = useState<CapabilitiesSettingsDTO | null>(
+ null,
+ );
const [serverSnapshot, setServerSnapshot] =
useState<CapabilitiesSettingsDTO | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
@@ -114,7 +118,9 @@ export default function CapabilitiesSettingsPage() {
setLoadError(null);
} catch (err) {
setLoadError(
- err instanceof Error ? err.message : t("Failed to load capability settings."),
+ err instanceof Error
+ ? err.message
+ : t("Failed to load capability settings."),
);
}
}, [t]);
@@ -158,10 +164,7 @@ export default function CapabilitiesSettingsPage() {
return () => registerExtension("capabilities", null);
}, [dirty, save, registerExtension]);
- function patchChat<K extends keyof ChatBlock>(
- key: K,
- value: ChatBlock[K],
- ) {
+ function patchChat<K extends keyof ChatBlock>(key: K, value: ChatBlock[K]) {
if (!settings) return;
setSettings({ ...settings, chat: { ...settings.chat, [key]: value } });
}
@@ -198,9 +201,7 @@ export default function CapabilitiesSettingsPage() {
setSettings({ ...settings, research: { ...settings.research, ...value } });
}
- function patchResearching(
- value: Partial<ResearchExtras["researching"]>,
- ) {
+ function patchResearching(value: Partial<ResearchExtras["researching"]>) {
if (!settings) return;
setSettings({
...settings,
@@ -216,9 +217,7 @@ export default function CapabilitiesSettingsPage() {
setSettings({ ...settings, question: { ...settings.question, ...value } });
}
- function patchExploring(
- value: Partial<QuestionExtras["exploring"]>,
- ) {
+ function patchExploring(value: Partial<QuestionExtras["exploring"]>) {
if (!settings) return;
setSettings({
...settings,
@@ -333,7 +332,9 @@ export default function CapabilitiesSettingsPage() {
<SettingSection
title={t("Solve")}
- description={t("Deep solve pipeline: chained THINK / TOOL / FINISH / REPLAN loop.")}
+ description={t(
+ "Deep solve pipeline: chained THINK / TOOL / FINISH / REPLAN loop.",
+ )}
>
<NumberRow
label={t("Temperature")}
@@ -364,7 +365,9 @@ export default function CapabilitiesSettingsPage() {
/>
<NumberRow
label={t("Max replans")}
- help={t("How many times the planner may revise the plan within one turn.")}
+ help={t(
+ "How many times the planner may revise the plan within one turn.",
+ )}
value={settings.solve.max_replans}
onChange={(n) => patchSolveExtras({ max_replans: n })}
min={0}
diff --git a/web/app/(utility)/settings/memory/page.tsx b/web/app/(utility)/settings/memory/page.tsx
index 47713b915..f92bcc0cc 100644
--- a/web/app/(utility)/settings/memory/page.tsx
+++ b/web/app/(utility)/settings/memory/page.tsx
@@ -37,9 +37,8 @@ export default function MemorySettingsPage() {
const { t } = useTranslation();
const { registerExtension } = useSettings();
const [settings, setSettings] = useState<MemorySettingsDTO | null>(null);
- const [serverSnapshot, setServerSnapshot] = useState<MemorySettingsDTO | null>(
- null,
- );
+ const [serverSnapshot, setServerSnapshot] =
+ useState<MemorySettingsDTO | null>(null);
const load = useCallback(async () => {
const res = await apiFetch(apiUrl("/api/v1/memory/settings"));
@@ -214,7 +213,9 @@ export default function MemorySettingsPage() {
{ value: "paragraph", label: t("Paragraph") },
{ value: "sentence", label: t("Sentence") },
]}
- onChange={(v) => patch("chunking", { boundary: v as "paragraph" | "sentence" })}
+ onChange={(v) =>
+ patch("chunking", { boundary: v as "paragraph" | "sentence" })
+ }
/>
<NumberRow
label={t("Min chunk chars")}
@@ -250,7 +251,9 @@ export default function MemorySettingsPage() {
/>
<ToggleRow
label={t("Drop invalid refs (vs reject the whole fact)")}
- help={t("On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.")}
+ help={t(
+ "On: keep the fact, drop only out-of-pool refs. Off: any bad ref rejects the fact.",
+ )}
value={settings.reference.drop_invalid_refs}
onChange={(v) => patch("reference", { drop_invalid_refs: v })}
/>
diff --git a/web/app/(utility)/settings/status/page.tsx b/web/app/(utility)/settings/status/page.tsx
index 55bd25a5e..a5798d405 100644
--- a/web/app/(utility)/settings/status/page.tsx
+++ b/web/app/(utility)/settings/status/page.tsx
@@ -123,7 +123,10 @@ export default function StatusSettingsPage() {
{profileName}
</div>
{serviceStatus?.error && (
- <p className="mt-2 truncate text-[11px] text-red-500" title={serviceStatus.error}>
+ <p
+ className="mt-2 truncate text-[11px] text-red-500"
+ title={serviceStatus.error}
+ >
{serviceStatus.error}
</p>
)}
diff --git a/web/app/(utility)/settings/tools/page.tsx b/web/app/(utility)/settings/tools/page.tsx
index 633d3aab8..644e5f021 100644
--- a/web/app/(utility)/settings/tools/page.tsx
+++ b/web/app/(utility)/settings/tools/page.tsx
@@ -207,185 +207,185 @@ export default function ToolsSettingsPage() {
const list = grouped[category];
if (list.length === 0) return null;
return (
- <section key={category}>
- <header className="mb-3 flex items-baseline justify-between gap-3">
- <div className="min-w-0">
- <h2 className="text-[14px] font-semibold tracking-tight text-[var(--foreground)]">
- {categoryLabel(category)}
- </h2>
- <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">
- {categoryHint(category)}
- </p>
- </div>
- <span className="shrink-0 text-[11px] text-[var(--muted-foreground)]">
- {list.length}
- </span>
- </header>
- <div className="overflow-hidden rounded-xl border border-[var(--border)]/60 bg-[var(--card)]/40">
- {list.map((tool, idx) => {
- const isOpen = expanded.has(tool.name);
- const hints = tool.hints[language];
- const isPending = pending.has(tool.name);
- const isComingSoon = !!tool.coming_soon;
- const isEnabled =
- !isComingSoon &&
- (tool.toggleable ? enabled.has(tool.name) : true);
- return (
- <div
- key={tool.name}
- className={
- idx > 0
- ? "border-t border-[var(--border)]/50"
- : undefined
- }
- >
- <div className="flex w-full items-start gap-3 px-5 py-4">
- <Wrench
- className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${
- isComingSoon
- ? "text-[var(--muted-foreground)]/40"
- : "text-[var(--muted-foreground)]"
- }`}
- />
- <button
- type="button"
- onClick={() => toggleExpanded(tool.name)}
- className="flex min-w-0 flex-1 items-start gap-3 text-left"
- aria-expanded={isOpen}
- >
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span
- className={`font-mono text-[13px] font-medium ${
+ <section key={category}>
+ <header className="mb-3 flex items-baseline justify-between gap-3">
+ <div className="min-w-0">
+ <h2 className="text-[14px] font-semibold tracking-tight text-[var(--foreground)]">
+ {categoryLabel(category)}
+ </h2>
+ <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">
+ {categoryHint(category)}
+ </p>
+ </div>
+ <span className="shrink-0 text-[11px] text-[var(--muted-foreground)]">
+ {list.length}
+ </span>
+ </header>
+ <div className="overflow-hidden rounded-xl border border-[var(--border)]/60 bg-[var(--card)]/40">
+ {list.map((tool, idx) => {
+ const isOpen = expanded.has(tool.name);
+ const hints = tool.hints[language];
+ const isPending = pending.has(tool.name);
+ const isComingSoon = !!tool.coming_soon;
+ const isEnabled =
+ !isComingSoon &&
+ (tool.toggleable ? enabled.has(tool.name) : true);
+ return (
+ <div
+ key={tool.name}
+ className={
+ idx > 0
+ ? "border-t border-[var(--border)]/50"
+ : undefined
+ }
+ >
+ <div className="flex w-full items-start gap-3 px-5 py-4">
+ <Wrench
+ className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${
+ isComingSoon
+ ? "text-[var(--muted-foreground)]/40"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ />
+ <button
+ type="button"
+ onClick={() => toggleExpanded(tool.name)}
+ className="flex min-w-0 flex-1 items-start gap-3 text-left"
+ aria-expanded={isOpen}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span
+ className={`font-mono text-[13px] font-medium ${
+ isComingSoon
+ ? "text-[var(--foreground)]/60"
+ : "text-[var(--foreground)]"
+ }`}
+ >
+ {tool.name}
+ </span>
+ {tool.aliases.length > 0 && (
+ <span className="text-[10.5px] text-[var(--muted-foreground)]/70">
+ {tool.aliases.join(" · ")}
+ </span>
+ )}
+ {isComingSoon && (
+ <span className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {language === "zh"
+ ? "敬请期待"
+ : "Coming soon"}
+ </span>
+ )}
+ </div>
+ <p
+ className={`mt-1 text-[12.5px] leading-relaxed ${
isComingSoon
- ? "text-[var(--foreground)]/60"
- : "text-[var(--foreground)]"
+ ? "text-[var(--muted-foreground)]/70"
+ : "text-[var(--muted-foreground)]"
}`}
>
- {tool.name}
- </span>
- {tool.aliases.length > 0 && (
- <span className="text-[10.5px] text-[var(--muted-foreground)]/70">
- {tool.aliases.join(" · ")}
- </span>
- )}
- {isComingSoon && (
- <span className="inline-flex items-center gap-1 rounded-full border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
- {language === "zh"
- ? "敬请期待"
- : "Coming soon"}
- </span>
- )}
+ {hints.short_description || tool.description}
+ </p>
</div>
- <p
- className={`mt-1 text-[12.5px] leading-relaxed ${
- isComingSoon
- ? "text-[var(--muted-foreground)]/70"
- : "text-[var(--muted-foreground)]"
+ <ChevronDown
+ className={`mt-1 h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${
+ isOpen ? "rotate-180" : ""
}`}
- >
- {hints.short_description || tool.description}
- </p>
- </div>
- <ChevronDown
- className={`mt-1 h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${
- isOpen ? "rotate-180" : ""
- }`}
- />
- </button>
- <div className="mt-0.5 flex shrink-0 items-center gap-2">
- {isComingSoon ? (
- <ToolToggle
- checked={false}
- disabled
- onChange={() => {
- /* locked */
- }}
- label={
- language === "zh"
- ? "敬请期待"
- : "Coming soon"
- }
/>
- ) : tool.toggleable ? (
- <ToolToggle
- checked={isEnabled}
- disabled={isPending}
- onChange={() => handleToggleEnabled(tool.name)}
- label={t(isEnabled ? "On" : "Off")}
- />
- ) : (
- <span
- className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] text-[var(--muted-foreground)]"
- title={t(
- "Auto-mounted by the agent when needed. Not user-toggleable.",
- )}
- >
- <Lock className="h-3 w-3" />
- {t("Always on")}
- </span>
- )}
+ </button>
+ <div className="mt-0.5 flex shrink-0 items-center gap-2">
+ {isComingSoon ? (
+ <ToolToggle
+ checked={false}
+ disabled
+ onChange={() => {
+ /* locked */
+ }}
+ label={
+ language === "zh" ? "敬请期待" : "Coming soon"
+ }
+ />
+ ) : tool.toggleable ? (
+ <ToolToggle
+ checked={isEnabled}
+ disabled={isPending}
+ onChange={() => handleToggleEnabled(tool.name)}
+ label={t(isEnabled ? "On" : "Off")}
+ />
+ ) : (
+ <span
+ className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] text-[var(--muted-foreground)]"
+ title={t(
+ "Auto-mounted by the agent when needed. Not user-toggleable.",
+ )}
+ >
+ <Lock className="h-3 w-3" />
+ {t("Always on")}
+ </span>
+ )}
+ </div>
</div>
- </div>
- {isOpen && (
- <div className="space-y-4 border-t border-[var(--border)]/40 bg-[var(--background)]/40 px-5 py-4 text-[12.5px] leading-relaxed">
- {hints.when_to_use && (
- <Field
- label={t("When to use")}
- body={hints.when_to_use}
- />
- )}
- {hints.input_format && (
- <Field
- label={t("Input format")}
- body={hints.input_format}
- mono
- />
- )}
- {hints.guideline && (
- <Field
- label={t("Guideline")}
- body={hints.guideline}
- />
- )}
- {hints.note && (
- <Field label={t("Note")} body={hints.note} />
- )}
- {tool.parameters.length > 0 && (
- <div>
- <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">
- {t("Parameters")}
- </div>
- <ul className="space-y-1.5">
- {tool.parameters.map((p) => (
- <li
- key={p.name}
- className="flex items-baseline gap-2"
- >
- <span className="font-mono text-[12px] text-[var(--foreground)]">
- {p.name}
- </span>
- <span className="text-[10.5px] text-[var(--muted-foreground)]/70">
- {p.type}
- {p.required ? "" : ` · ${t("optional")}`}
- </span>
- {p.description && (
- <span className="text-[12px] text-[var(--muted-foreground)]">
- — {p.description}
+ {isOpen && (
+ <div className="space-y-4 border-t border-[var(--border)]/40 bg-[var(--background)]/40 px-5 py-4 text-[12.5px] leading-relaxed">
+ {hints.when_to_use && (
+ <Field
+ label={t("When to use")}
+ body={hints.when_to_use}
+ />
+ )}
+ {hints.input_format && (
+ <Field
+ label={t("Input format")}
+ body={hints.input_format}
+ mono
+ />
+ )}
+ {hints.guideline && (
+ <Field
+ label={t("Guideline")}
+ body={hints.guideline}
+ />
+ )}
+ {hints.note && (
+ <Field label={t("Note")} body={hints.note} />
+ )}
+ {tool.parameters.length > 0 && (
+ <div>
+ <div className="mb-1 text-[10.5px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]/80">
+ {t("Parameters")}
+ </div>
+ <ul className="space-y-1.5">
+ {tool.parameters.map((p) => (
+ <li
+ key={p.name}
+ className="flex items-baseline gap-2"
+ >
+ <span className="font-mono text-[12px] text-[var(--foreground)]">
+ {p.name}
</span>
- )}
- </li>
- ))}
- </ul>
- </div>
- )}
- </div>
- )}
- </div>
- );
- })}
- </div>
- </section>
+ <span className="text-[10.5px] text-[var(--muted-foreground)]/70">
+ {p.type}
+ {p.required
+ ? ""
+ : ` · ${t("optional")}`}
+ </span>
+ {p.description && (
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ — {p.description}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </section>
);
})}
</div>
diff --git a/web/components/Geogebra.tsx b/web/components/Geogebra.tsx
index dac77fc39..7209e5e18 100644
--- a/web/components/Geogebra.tsx
+++ b/web/components/Geogebra.tsx
@@ -13,7 +13,10 @@ interface GeogebraProps {
declare global {
interface Window {
- GGBApplet?: new (params: Record<string, unknown>, html5: boolean) => {
+ GGBApplet?: new (
+ params: Record<string, unknown>,
+ html5: boolean,
+ ) => {
inject: (containerId: string) => void;
};
}
diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsx
index b0e9f2a70..4ebd64b13 100644
--- a/web/components/chat/home/AskUserOptions.tsx
+++ b/web/components/chat/home/AskUserOptions.tsx
@@ -99,7 +99,9 @@ export function extractAskUserPayload(
continue;
}
if (event.type === "progress" && meta.ask_user_resolved) {
- const answersRaw = Array.isArray(meta.answers) ? (meta.answers as unknown[]) : [];
+ const answersRaw = Array.isArray(meta.answers)
+ ? (meta.answers as unknown[])
+ : [];
resolution = {
toolCallId:
typeof meta.ask_user_tool_call_id === "string"
@@ -115,14 +117,19 @@ export function extractAskUserPayload(
})
.filter((a): a is AskUserAnswer => a !== null),
text:
- typeof meta.reply_preview === "string" ? (meta.reply_preview as string) : "",
+ typeof meta.reply_preview === "string"
+ ? (meta.reply_preview as string)
+ : "",
};
}
}
if (!latest) return null;
- if (resolution && (resolution.toolCallId === latest.toolCallId || latest.toolCallId === null)) {
+ if (
+ resolution &&
+ (resolution.toolCallId === latest.toolCallId || latest.toolCallId === null)
+ ) {
const answers =
resolution.answers.length > 0
? resolution.answers
@@ -158,7 +165,12 @@ export function extractAskUserPayload(
*/
export type MessageSegment =
| { kind: "text"; text: string; key: string }
- | { kind: "ask_user"; data: AskUserCardData; toolCallId: string | null; key: string };
+ | {
+ kind: "ask_user";
+ data: AskUserCardData;
+ toolCallId: string | null;
+ key: string;
+ };
export function extractMessageSegments(
events: StreamEvent[] | undefined,
@@ -227,7 +239,7 @@ export function extractMessageSegments(
// Match by tool_call_id; fall back to the most recent unresolved
// ask_user segment if the resolver did not echo the id back.
let targetIdx =
- replyToolCallId !== null ? byToolCall.get(replyToolCallId) ?? -1 : -1;
+ replyToolCallId !== null ? (byToolCall.get(replyToolCallId) ?? -1) : -1;
if (targetIdx < 0) {
for (let i = segments.length - 1; i >= 0; i--) {
const s = segments[i];
@@ -240,7 +252,9 @@ export function extractMessageSegments(
if (targetIdx < 0) continue;
const target = segments[targetIdx];
if (target.kind !== "ask_user") continue;
- const answersRaw = Array.isArray(meta.answers) ? (meta.answers as unknown[]) : [];
+ const answersRaw = Array.isArray(meta.answers)
+ ? (meta.answers as unknown[])
+ : [];
const answers: AskUserAnswer[] = answersRaw
.map((entry) => {
if (!entry || typeof entry !== "object") return null;
@@ -251,7 +265,9 @@ export function extractMessageSegments(
})
.filter((a): a is AskUserAnswer => a !== null);
const replyText =
- typeof meta.reply_preview === "string" ? (meta.reply_preview as string) : "";
+ typeof meta.reply_preview === "string"
+ ? (meta.reply_preview as string)
+ : "";
const finalAnswers =
answers.length > 0
? answers
@@ -265,7 +281,11 @@ export function extractMessageSegments(
: [];
segments[targetIdx] = {
...target,
- data: { payload: target.data.payload, answers: finalAnswers, resolved: true },
+ data: {
+ payload: target.data.payload,
+ answers: finalAnswers,
+ resolved: true,
+ },
};
}
}
@@ -398,23 +418,28 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({
const [customText, setCustomText] = useState<Record<string, string>>({});
// Whether the free-text input is the active choice for a question.
// Drives both textarea visibility and the "picked" visual state.
- const [customSelected, setCustomSelected] = useState<Record<string, boolean>>({});
+ const [customSelected, setCustomSelected] = useState<Record<string, boolean>>(
+ {},
+ );
const [activeIdx, setActiveIdx] = useState(0);
const [submitted, setSubmitted] = useState(false);
const activeQuestion = payload.questions[activeIdx] ?? payload.questions[0];
const allAnswered = useMemo(
- () => payload.questions.every((q) => (answers[q.id] ?? "").trim().length > 0),
+ () =>
+ payload.questions.every((q) => (answers[q.id] ?? "").trim().length > 0),
[payload.questions, answers],
);
const handleSubmit = useCallback(() => {
if (submitted) return;
setSubmitted(true);
- const list: Array<{ questionId: string; text: string }> = payload.questions.map(
- (q) => ({ questionId: q.id, text: (answers[q.id] ?? "").trim() }),
- );
+ const list: Array<{ questionId: string; text: string }> =
+ payload.questions.map((q) => ({
+ questionId: q.id,
+ text: (answers[q.id] ?? "").trim(),
+ }));
// Always include a flat ``text`` synopsis for back-compat with any
// older server path that only looks at ``text``.
const flat = list
@@ -458,7 +483,9 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({
{submitted
? t("Sending your answers…")
: totalQuestions > 1
- ? t("{{count}} questions — tap a tab to switch.", { count: totalQuestions })
+ ? t("{{count}} questions — tap a tab to switch.", {
+ count: totalQuestions,
+ })
: t("Pick an option or type your own to continue.")}
</div>
</div>
@@ -763,10 +790,7 @@ const ResolvedAskUserCard = memo(function ResolvedAskUserCard({
{payload.questions.map((q, index) => {
const value = (byId.get(q.id) ?? "").trim();
return (
- <div
- key={q.id}
- className="flex items-start gap-2 px-3 py-1.5"
- >
+ <div key={q.id} className="flex items-start gap-2 px-3 py-1.5">
<span className="mt-[3px] w-4 shrink-0 text-center text-[11px] font-medium tabular-nums leading-tight text-[var(--muted-foreground)]/30">
{index + 1}
</span>
diff --git a/web/components/memory/MemoryGraph.tsx b/web/components/memory/MemoryGraph.tsx
index 432e031c6..3393784fe 100644
--- a/web/components/memory/MemoryGraph.tsx
+++ b/web/components/memory/MemoryGraph.tsx
@@ -159,18 +159,15 @@ export default function MemoryGraph() {
[view],
);
- const onPointerMove = useCallback(
- (e: ReactPointerEvent<HTMLDivElement>) => {
- const d = dragRef.current;
- if (!d || d.pointerId !== e.pointerId) return;
- setView((v) => ({
- ...v,
- tx: d.origTx + (e.clientX - d.startX),
- ty: d.origTy + (e.clientY - d.startY),
- }));
- },
- [],
- );
+ const onPointerMove = useCallback((e: ReactPointerEvent<HTMLDivElement>) => {
+ const d = dragRef.current;
+ if (!d || d.pointerId !== e.pointerId) return;
+ setView((v) => ({
+ ...v,
+ tx: d.origTx + (e.clientX - d.startX),
+ ty: d.origTy + (e.clientY - d.startY),
+ }));
+ }, []);
const endDrag = useCallback(() => {
dragRef.current = null;
@@ -320,7 +317,9 @@ function Header({
className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] disabled:opacity-50"
disabled={loading}
>
- <RefreshCw className={loading ? "h-3.5 w-3.5 animate-spin" : "h-3.5 w-3.5"} />
+ <RefreshCw
+ className={loading ? "h-3.5 w-3.5 animate-spin" : "h-3.5 w-3.5"}
+ />
{t("Refresh")}
</button>
</div>
@@ -398,13 +397,15 @@ function GraphView({
</radialGradient>
<radialGradient id="halo-l1" cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor="var(--foreground)" stopOpacity="0.08" />
- <stop offset="100%" stopColor="var(--foreground)" stopOpacity="0.01" />
+ <stop
+ offset="100%"
+ stopColor="var(--foreground)"
+ stopOpacity="0.01"
+ />
</radialGradient>
</defs>
- <g
- transform={`translate(${view.tx} ${view.ty}) scale(${view.scale})`}
- >
+ <g transform={`translate(${view.tx} ${view.ty}) scale(${view.scale})`}>
{/* Concentric ring guides (faint). */}
<g pointerEvents="none">
{(["L1", "L2", "L3"] as const).map((layer) => {
@@ -583,7 +584,8 @@ function GraphView({
const t2 = nodeIdx.get(e.target);
if (!s || !t2) return null;
const dim =
- highlight !== null && !highlight.has(e.source) &&
+ highlight !== null &&
+ !highlight.has(e.source) &&
!highlight.has(e.target);
const focused =
highlight !== null &&
@@ -968,12 +970,16 @@ function nodeMeta(
if (n.layer === "L2") {
return {
layerLabel: t("L2 · curated"),
- clusterLabel: t(SURFACE_LABEL[cluster as keyof typeof SURFACE_LABEL] || cluster),
+ clusterLabel: t(
+ SURFACE_LABEL[cluster as keyof typeof SURFACE_LABEL] || cluster,
+ ),
};
}
return {
layerLabel: t("L1 · raw trace"),
- clusterLabel: t(SURFACE_LABEL[cluster as keyof typeof SURFACE_LABEL] || cluster),
+ clusterLabel: t(
+ SURFACE_LABEL[cluster as keyof typeof SURFACE_LABEL] || cluster,
+ ),
};
}
diff --git a/web/components/memory/MemoryHub.tsx b/web/components/memory/MemoryHub.tsx
index f8dd07042..b026f6064 100644
--- a/web/components/memory/MemoryHub.tsx
+++ b/web/components/memory/MemoryHub.tsx
@@ -83,8 +83,7 @@ export default function MemoryHub() {
);
const l2Total = l2Docs.reduce((acc, d) => acc + d.entry_count, 0);
const l3Total = l3Docs.reduce((acc, d) => acc + d.entry_count, 0);
- const latestBackup =
- overview?.backups?.[overview.backups.length - 1] ?? null;
+ const latestBackup = overview?.backups?.[overview.backups.length - 1] ?? null;
return (
<div className="space-y-10">
@@ -108,7 +107,9 @@ export default function MemoryHub() {
onClick={() => void load()}
className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 transition hover:bg-[var(--muted)]"
>
- <RefreshCw className={loading ? "h-3 w-3 animate-spin" : "h-3 w-3"} />
+ <RefreshCw
+ className={loading ? "h-3 w-3 animate-spin" : "h-3 w-3"}
+ />
{t("Refresh")}
</button>
<Link
@@ -139,7 +140,9 @@ export default function MemoryHub() {
title={t("L2 · Per-surface summaries")}
tag={t("Curated")}
stat={l2Total.toLocaleString()}
- statLabel={t("facts across {{n}} surfaces", { n: l2Docs.length || SURFACES.length })}
+ statLabel={t("facts across {{n}} surfaces", {
+ n: l2Docs.length || SURFACES.length,
+ })}
detail={t(
"Surface-specific facts extracted by the consolidator. Run Update / Audit / Dedup per doc.",
)}
@@ -150,7 +153,9 @@ export default function MemoryHub() {
title={t("L3 · Cross-surface knowledge")}
tag={t("Synthesis")}
stat={l3Total.toLocaleString()}
- statLabel={t("propositions across {{n}} slots", { n: l3Docs.length || L3_VISIBLE.length })}
+ statLabel={t("propositions across {{n}} slots", {
+ n: l3Docs.length || L3_VISIBLE.length,
+ })}
detail={t(
"Cross-surface synthesis: profile, recent timeline, knowledge scope. Hedged claims with L2 evidence.",
)}
diff --git a/web/components/memory/MemoryL1Workbench.tsx b/web/components/memory/MemoryL1Workbench.tsx
index a0ec6f19c..41bb9a8df 100644
--- a/web/components/memory/MemoryL1Workbench.tsx
+++ b/web/components/memory/MemoryL1Workbench.tsx
@@ -66,9 +66,15 @@ export default function MemoryL1Workbench({
// highlight on first mount. The URL only drives initial state; once the
// user clicks around the rail it's all local state again.
const [surface, setSurface] = useState<Surface>(initialSurface || "notebook");
- const [counts, setCounts] = useState<Record<Surface, number>>({} as Record<Surface, number>);
- const [pending, setPending] = useState<Record<Surface, number>>({} as Record<Surface, number>);
- const [focusRef, setFocusRef] = useState<string | null>(initialFocusRef ?? null);
+ const [counts, setCounts] = useState<Record<Surface, number>>(
+ {} as Record<Surface, number>,
+ );
+ const [pending, setPending] = useState<Record<Surface, number>>(
+ {} as Record<Surface, number>,
+ );
+ const [focusRef, setFocusRef] = useState<string | null>(
+ initialFocusRef ?? null,
+ );
const [toast, setToast] = useState("");
// Fetch counts + pending badges for the left rail in parallel.
@@ -89,10 +95,16 @@ export default function MemoryL1Workbench({
}),
);
setCounts(
- Object.fromEntries(entries.map(([k, n]) => [k, n])) as Record<Surface, number>,
+ Object.fromEntries(entries.map(([k, n]) => [k, n])) as Record<
+ Surface,
+ number
+ >,
);
setPending(
- Object.fromEntries(entries.map(([k, , p]) => [k, p])) as Record<Surface, number>,
+ Object.fromEntries(entries.map(([k, , p]) => [k, p])) as Record<
+ Surface,
+ number
+ >,
);
}, []);
@@ -121,13 +133,10 @@ export default function MemoryL1Workbench({
return () => clearTimeout(id);
}, [toast]);
- const nicelabel = useMemo(
- () => {
- const entry = L1_NAV.find((n) => n.key === surface);
- return entry ? t(entry.label) : surface;
- },
- [surface, t],
- );
+ const nicelabel = useMemo(() => {
+ const entry = L1_NAV.find((n) => n.key === surface);
+ return entry ? t(entry.label) : surface;
+ }, [surface, t]);
return (
<div className="flex h-full min-h-0 flex-col gap-3 px-6 py-4 md:px-10">
@@ -209,7 +218,12 @@ export default function MemoryL1Workbench({
function LayerSwitcher({ t }: { t: (k: string) => string }) {
// L1 is the current page, so it stays as a non-link pill; L2 + L3
// link to their respective hubs.
- const entries: { key: "L1" | "L2" | "L3"; href: string; icon: LucideIcon; label: string }[] = [
+ const entries: {
+ key: "L1" | "L2" | "L3";
+ href: string;
+ icon: LucideIcon;
+ label: string;
+ }[] = [
{ key: "L1", href: "/memory/l1", icon: Layers, label: t("L1") },
{ key: "L2", href: "/memory/l2", icon: Workflow, label: t("L2") },
{ key: "L3", href: "/memory/l3", icon: Network, label: t("L3") },
@@ -244,13 +258,7 @@ function LayerSwitcher({ t }: { t: (k: string) => string }) {
);
}
-function Breadcrumb({
- label,
- t,
-}: {
- label: string;
- t: (k: string) => string;
-}) {
+function Breadcrumb({ label, t }: { label: string; t: (k: string) => string }) {
return (
<div className="flex items-center gap-2 text-[12.5px]">
<Link
diff --git a/web/components/memory/MemoryRunPanel.tsx b/web/components/memory/MemoryRunPanel.tsx
index d60e15f7a..c914bcebb 100644
--- a/web/components/memory/MemoryRunPanel.tsx
+++ b/web/components/memory/MemoryRunPanel.tsx
@@ -77,13 +77,11 @@ export default function MemoryRunPanel({
const budgetOverride = mode === "dedup" ? null : overrides[mode];
const iterationsOverride = mode === "dedup" ? overrides.dedup : null;
const setBudgetOverride = useCallback(
- (v: number | null) =>
- setOverrides((prev) => ({ ...prev, [mode]: v })),
+ (v: number | null) => setOverrides((prev) => ({ ...prev, [mode]: v })),
[mode],
);
const setIterationsOverride = useCallback(
- (v: number | null) =>
- setOverrides((prev) => ({ ...prev, dedup: v })),
+ (v: number | null) => setOverrides((prev) => ({ ...prev, dedup: v })),
[],
);
const [selection, setSelection] = useState<LLMSelection | null>(null);
@@ -119,10 +117,14 @@ export default function MemoryRunPanel({
const defaultBudget = useMemo(() => {
if (!settings) return null;
if (mode === "update") {
- return layer === "L2" ? settings.update.l2_budget : settings.update.l3_budget;
+ return layer === "L2"
+ ? settings.update.l2_budget
+ : settings.update.l3_budget;
}
if (mode === "audit") {
- return layer === "L2" ? settings.audit.l2_budget : settings.audit.l3_budget;
+ return layer === "L2"
+ ? settings.audit.l2_budget
+ : settings.audit.l3_budget;
}
return null;
}, [settings, mode, layer]);
@@ -130,7 +132,6 @@ export default function MemoryRunPanel({
const budget = budgetOverride ?? defaultBudget ?? ("" as const);
const iterations = iterationsOverride ?? defaultIterations ?? ("" as const);
-
const effectiveSelection = useMemo(
() => selection ?? activeDefault ?? null,
[selection, activeDefault],
@@ -158,7 +159,15 @@ export default function MemoryRunPanel({
language: i18n.language || "en",
});
}
- }, [isRunning, mode, iterations, budget, effectiveSelection, i18n.language, start]);
+ }, [
+ isRunning,
+ mode,
+ iterations,
+ budget,
+ effectiveSelection,
+ i18n.language,
+ start,
+ ]);
// Notify parent when a run finishes (success or otherwise) so the doc
// preview can refresh.
@@ -184,7 +193,8 @@ export default function MemoryRunPanel({
.reverse()
.find(
(ev) =>
- ev.payload.stage === "doc_updated" || ev.payload.stage === "undo_applied",
+ ev.payload.stage === "doc_updated" ||
+ ev.payload.stage === "undo_applied",
);
if (!latest || lastDocEvent.current === latest.seq) return;
lastDocEvent.current = latest.seq;
@@ -196,7 +206,8 @@ export default function MemoryRunPanel({
for (const ev of events) {
const value = ev.payload.undo_depth;
if (
- (ev.payload.stage === "doc_updated" || ev.payload.stage === "undo_applied") &&
+ (ev.payload.stage === "doc_updated" ||
+ ev.payload.stage === "undo_applied") &&
typeof value === "number"
) {
depth = value;
@@ -222,7 +233,9 @@ export default function MemoryRunPanel({
if (!ok) return;
try {
const res = await apiFetch(
- apiUrl(`/api/v1/memory/doc/${layer}/${encodeURIComponent(docKey)}/reset`),
+ apiUrl(
+ `/api/v1/memory/doc/${layer}/${encodeURIComponent(docKey)}/reset`,
+ ),
{ method: "POST" },
);
if (!res.ok) {
@@ -399,7 +412,18 @@ export default function MemoryRunPanel({
type Turn =
| { kind: "system"; id: string; ts: string; payload: RunEvent["payload"] }
- | { kind: "llm"; id: string; ts: string; turn: number; chunkIndex: number | null; system_prompt: string; user_prompt: string; response: string; error: string | null; label: string | null };
+ | {
+ kind: "llm";
+ id: string;
+ ts: string;
+ turn: number;
+ chunkIndex: number | null;
+ system_prompt: string;
+ user_prompt: string;
+ response: string;
+ error: string | null;
+ label: string | null;
+ };
function groupByTurn(events: RunEvent[]): Turn[] {
const out: Turn[] = [];
@@ -409,7 +433,8 @@ function groupByTurn(events: RunEvent[]): Turn[] {
const stage = String(p.stage || "");
if (stage === "llm_io_start") {
const turn = typeof p.turn === "number" ? p.turn : 0;
- const chunkIndex = typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
+ const chunkIndex =
+ typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
const key = `${turn}:${chunkIndex}:${ev.seq}`;
const card: Turn & { kind: "llm" } = {
kind: "llm",
@@ -429,7 +454,8 @@ function groupByTurn(events: RunEvent[]): Turn[] {
}
if (stage === "llm_io_end") {
const turn = typeof p.turn === "number" ? p.turn : 0;
- const chunkIndex = typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
+ const chunkIndex =
+ typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
const card = pending[`${turn}:${chunkIndex}`];
if (card) {
card.response = String(p.response || "");
@@ -440,7 +466,8 @@ function groupByTurn(events: RunEvent[]): Turn[] {
}
if (stage === "llm_io_delta") {
const turn = typeof p.turn === "number" ? p.turn : 0;
- const chunkIndex = typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
+ const chunkIndex =
+ typeof p.chunk_index === "number" ? (p.chunk_index as number) : null;
const card = pending[`${turn}:${chunkIndex}`];
if (card) {
card.response += String(p.delta || "");
@@ -491,7 +518,9 @@ function SystemEventRow({
{display.title}
</div>
{display.detail && (
- <div className="mt-0.5 break-words leading-snug">{display.detail}</div>
+ <div className="mt-0.5 break-words leading-snug">
+ {display.detail}
+ </div>
)}
</div>
</li>
@@ -502,16 +531,24 @@ function systemEventDisplay(
stage: string,
event: RunEvent["payload"],
t: (k: string) => string,
-):
- | { icon: LucideIcon; title: string; detail: string; tone: "ok" | "warn" | "muted" }
- | null {
+): {
+ icon: LucideIcon;
+ title: string;
+ detail: string;
+ tone: "ok" | "warn" | "muted";
+} | null {
const num = (k: string) =>
typeof event[k] === "number" ? String(event[k]) : null;
const str = (k: string) =>
typeof event[k] === "string" ? String(event[k]) : null;
switch (stage) {
case "run_started":
- return { icon: PlayCircle, title: t("Run started"), detail: `${event.mode}`, tone: "muted" };
+ return {
+ icon: PlayCircle,
+ title: t("Run started"),
+ detail: `${event.mode}`,
+ tone: "muted",
+ };
case "trace_loaded": {
const total = num("total") ?? num("total_l2_entries");
const fresh = num("new") ?? num("new_l2_entries");
@@ -519,7 +556,12 @@ function systemEventDisplay(
total ? `total=${total}` : null,
fresh ? `new=${fresh}` : null,
].filter(Boolean);
- return { icon: PlayCircle, title: t("Traces loaded"), detail: parts.join(" · "), tone: "muted" };
+ return {
+ icon: PlayCircle,
+ title: t("Traces loaded"),
+ detail: parts.join(" · "),
+ tone: "muted",
+ };
}
case "chunked":
return {
@@ -529,13 +571,20 @@ function systemEventDisplay(
num("chunks") ? `chunks=${num("chunks")}` : null,
num("budget") ? `budget=${num("budget")}` : null,
num("chars") ? `chars=${num("chars")}` : null,
- ].filter(Boolean).join(" · "),
+ ]
+ .filter(Boolean)
+ .join(" · "),
tone: "muted",
};
case "progress": {
const turn = num("turn");
const total = num("total");
- return { icon: PlayCircle, title: t("Progress"), detail: turn && total ? `${turn}/${total}` : "", tone: "muted" };
+ return {
+ icon: PlayCircle,
+ title: t("Progress"),
+ detail: turn && total ? `${turn}/${total}` : "",
+ tone: "muted",
+ };
}
case "facts_extracted":
return {
@@ -544,7 +593,9 @@ function systemEventDisplay(
detail: [
num("kept") ? `kept=${num("kept")}` : null,
num("added") ? `added=${num("added")}` : null,
- ].filter(Boolean).join(" · "),
+ ]
+ .filter(Boolean)
+ .join(" · "),
tone: "ok",
};
case "refs_dropped":
@@ -576,7 +627,9 @@ function systemEventDisplay(
str("action"),
num("turn") ? `turn=${num("turn")}` : null,
num("undo_depth") ? `undo=${num("undo_depth")}` : null,
- ].filter(Boolean).join(" · "),
+ ]
+ .filter(Boolean)
+ .join(" · "),
tone: "ok",
};
case "undo_applied":
@@ -586,7 +639,9 @@ function systemEventDisplay(
detail: [
str("action"),
num("undo_depth") ? `remaining=${num("undo_depth")}` : "remaining=0",
- ].filter(Boolean).join(" · "),
+ ]
+ .filter(Boolean)
+ .join(" · "),
tone: "warn",
};
case "done":
@@ -597,7 +652,9 @@ function systemEventDisplay(
num("facts_added") ? `+${num("facts_added")} facts` : null,
num("edits_applied") ? `+${num("edits_applied")} edits` : null,
num("refs_dropped") ? `dropped=${num("refs_dropped")}` : null,
- ].filter(Boolean).join(" · "),
+ ]
+ .filter(Boolean)
+ .join(" · "),
tone: "ok",
};
case "run_ended":
@@ -608,9 +665,19 @@ function systemEventDisplay(
tone: "muted",
};
case "cancelled":
- return { icon: CircleSlash, title: t("Cancelled"), detail: "", tone: "warn" };
+ return {
+ icon: CircleSlash,
+ title: t("Cancelled"),
+ detail: "",
+ tone: "warn",
+ };
case "error":
- return { icon: AlertCircle, title: t("Error"), detail: str("message") || "", tone: "warn" };
+ return {
+ icon: AlertCircle,
+ title: t("Error"),
+ detail: str("message") || "",
+ tone: "warn",
+ };
default:
return null;
}
@@ -625,7 +692,10 @@ function LLMTurnCard({
}) {
const [systemOpen, setSystemOpen] = useState(false);
const [userOpen, setUserOpen] = useState(false);
- const tag = turn.chunkIndex !== null ? `t${turn.turn} · chunk ${turn.chunkIndex + 1}` : `t${turn.turn}`;
+ const tag =
+ turn.chunkIndex !== null
+ ? `t${turn.turn} · chunk ${turn.chunkIndex + 1}`
+ : `t${turn.turn}`;
return (
<li className="space-y-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-2">
<div className="flex items-center gap-2 text-[10.5px] uppercase tracking-wide text-[var(--muted-foreground)]">
@@ -687,7 +757,11 @@ function Disclosure({
onClick={() => setOpen(!open)}
className="inline-flex items-center gap-1 rounded px-1 py-0.5 hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
>
- {open ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
+ {open ? (
+ <ChevronDown className="h-3 w-3" />
+ ) : (
+ <ChevronRight className="h-3 w-3" />
+ )}
{label}
<span className="opacity-60">·&nbsp;{body.length}</span>
</button>
@@ -793,7 +867,11 @@ function ModelPill({
type="button"
disabled={inactive}
onClick={() => setOpen(!open)}
- title={selectedOption ? `${selectedOption.profile_name} | ${selectedOption.provider}` : label}
+ title={
+ selectedOption
+ ? `${selectedOption.profile_name} | ${selectedOption.provider}`
+ : label
+ }
className={
"flex w-full min-w-0 items-center gap-1 rounded-full border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[11.5px] text-[var(--foreground)] transition hover:bg-[var(--muted)]/60 disabled:opacity-50 " +
(open ? "border-[var(--primary)]/40" : "")
@@ -813,7 +891,10 @@ function ModelPill({
key={llmSelectionKey(opt)}
type="button"
onClick={() => {
- onChange({ profile_id: opt.profile_id, model_id: opt.model_id });
+ onChange({
+ profile_id: opt.profile_id,
+ model_id: opt.model_id,
+ });
setOpen(false);
}}
className={
@@ -824,8 +905,12 @@ function ModelPill({
}
>
<span className="flex min-w-0 flex-1 items-baseline gap-2">
- <span className="truncate text-[var(--foreground)]">{opt.model_name}</span>
- <span className="shrink-0 text-[10px] opacity-60">{opt.provider}</span>
+ <span className="truncate text-[var(--foreground)]">
+ {opt.model_name}
+ </span>
+ <span className="shrink-0 text-[10px] opacity-60">
+ {opt.provider}
+ </span>
</span>
{opt.is_active_default && (
<span className="shrink-0 rounded bg-[var(--primary)]/10 px-1 py-0.5 text-[9.5px] uppercase text-[var(--primary)]">
diff --git a/web/components/memory/MemoryWorkbench.tsx b/web/components/memory/MemoryWorkbench.tsx
index 7d22e0c7a..ba9b6e6e6 100644
--- a/web/components/memory/MemoryWorkbench.tsx
+++ b/web/components/memory/MemoryWorkbench.tsx
@@ -43,8 +43,7 @@ type Layer = "L2" | "L3";
// * the rendered output is visually empty (zero-width span)
// * ``#m_xxx`` hash navigation works within the doc
// Requires ``allowHtml`` on the markdown renderer (we set it below).
-const _ENTRY_ANCHOR_RE =
- /\s*<!--\s*(m_[0-9A-HJKMNP-TV-Z]{26})\s*-->/g;
+const _ENTRY_ANCHOR_RE = /\s*<!--\s*(m_[0-9A-HJKMNP-TV-Z]{26})\s*-->/g;
// Rewrite footnote definitions so the ref text becomes a markdown link.
//
@@ -260,7 +259,9 @@ export default function MemoryWorkbench({
useEffect(() => {
if (!pendingFocus || editing) return;
if (!content || !previewRef.current) return;
- const anchorId = pendingFocus.startsWith("m_") ? pendingFocus : `m_${pendingFocus}`;
+ const anchorId = pendingFocus.startsWith("m_")
+ ? pendingFocus
+ : `m_${pendingFocus}`;
let cancelled = false;
const id = window.setTimeout(() => {
if (cancelled) return;
@@ -326,13 +327,10 @@ export default function MemoryWorkbench({
}
}, [editorValue, layer, docKey, t, loadLines]);
- const nicelabel = useMemo(
- () => {
- const entry = nav.find((n) => n.key === docKey);
- return entry ? t(entry.label) : docKey;
- },
- [docKey, nav, t],
- );
+ const nicelabel = useMemo(() => {
+ const entry = nav.find((n) => n.key === docKey);
+ return entry ? t(entry.label) : docKey;
+ }, [docKey, nav, t]);
const handleRunComplete = useCallback(() => {
void loadDoc();
@@ -520,7 +518,12 @@ function LayerSwitcher({
}) {
// L1 page is a single workbench (no per-key route); L2/L3 hubs land
// on /memory/l2 and /memory/l3 which list the surfaces / slots.
- const entries: { key: "L1" | Layer; href: string; icon: LucideIcon; label: string }[] = [
+ const entries: {
+ key: "L1" | Layer;
+ href: string;
+ icon: LucideIcon;
+ label: string;
+ }[] = [
{ key: "L1", href: "/memory/l1", icon: Layers, label: t("L1") },
{ key: "L2", href: "/memory/l2", icon: Workflow, label: t("L2") },
{ key: "L3", href: "/memory/l3", icon: Network, label: t("L3") },
@@ -608,7 +611,9 @@ function LineNumberedView({
<div
key={line.number}
className={
- muted ? "text-[var(--muted-foreground)]" : "text-[var(--foreground)]"
+ muted
+ ? "text-[var(--muted-foreground)]"
+ : "text-[var(--foreground)]"
}
>
<span className="select-none pr-3 text-[var(--muted-foreground)]">
diff --git a/web/components/memory/useMemoryRun.ts b/web/components/memory/useMemoryRun.ts
index dc323a26a..882b4c553 100644
--- a/web/components/memory/useMemoryRun.ts
+++ b/web/components/memory/useMemoryRun.ts
@@ -98,7 +98,13 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
initialisedFor.current = tag;
close();
cursorRef.current = 0;
- setState({ run: null, events: [], status: "idle", error: null, reconnecting: false });
+ setState({
+ run: null,
+ events: [],
+ status: "idle",
+ error: null,
+ reconnecting: false,
+ });
void (async () => {
const persistedId = readPersistedRunId(layer, key);
@@ -112,11 +118,15 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
}
if (!runId) {
const res = await apiFetch(
- apiUrl(`/api/v1/memory/runs?layer=${layer}&key=${encodeURIComponent(key)}`),
+ apiUrl(
+ `/api/v1/memory/runs?layer=${layer}&key=${encodeURIComponent(key)}`,
+ ),
);
if (res.ok) {
const data = (await res.json()) as { runs: RunHandle[] };
- const active = data.runs.find((r) => r.status === "running" || r.status === "queued");
+ const active = data.runs.find(
+ (r) => r.status === "running" || r.status === "queued",
+ );
if (active) {
runId = active.id;
writePersistedRunId(layer, key, runId);
@@ -148,7 +158,12 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
return;
}
const run = (await res.json()) as RunHandle;
- setState((s) => ({ ...s, run, status: run.status, reconnecting: false }));
+ setState((s) => ({
+ ...s,
+ run,
+ status: run.status,
+ reconnecting: false,
+ }));
} catch {
return;
}
@@ -181,15 +196,24 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
if (line) {
try {
const parsed = JSON.parse(line);
- const seq = typeof parsed.seq === "number" ? parsed.seq : cursorRef.current;
- const ts = typeof parsed.ts === "string" ? parsed.ts : new Date().toISOString();
+ const seq =
+ typeof parsed.seq === "number"
+ ? parsed.seq
+ : cursorRef.current;
+ const ts =
+ typeof parsed.ts === "string"
+ ? parsed.ts
+ : new Date().toISOString();
const { seq: _s, ts: _t, ...payload } = parsed;
cursorRef.current = seq + 1;
setState((s) => {
const undoDepth =
- typeof payload.undo_depth === "number" ? payload.undo_depth : null;
+ typeof payload.undo_depth === "number"
+ ? payload.undo_depth
+ : null;
const endedStatus =
- payload.stage === "run_ended" && typeof payload.status === "string"
+ payload.stage === "run_ended" &&
+ typeof payload.status === "string"
? (payload.status as RunStatus)
: null;
return {
@@ -204,10 +228,16 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
: s.run,
events: s.events.some((ev) => ev.seq === seq)
? s.events
- : [...s.events, { seq, ts, payload: payload as RunEventPayload }],
+ : [
+ ...s.events,
+ { seq, ts, payload: payload as RunEventPayload },
+ ],
};
});
- if (payload.stage === "run_ended" && typeof payload.status === "string") {
+ if (
+ payload.stage === "run_ended" &&
+ typeof payload.status === "string"
+ ) {
writePersistedRunId(layer, key, null);
}
} catch {
@@ -248,7 +278,8 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
if (!res.ok) {
const detail = await res.text();
throw new Error(
- detail || i18n.t("start failed: {{status}}", { status: res.status }),
+ detail ||
+ i18n.t("start failed: {{status}}", { status: res.status }),
);
}
const run = (await res.json()) as RunHandle;
@@ -279,9 +310,12 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
const undo = useCallback(async (): Promise<boolean> => {
if (!state.run) return false;
try {
- const res = await apiFetch(apiUrl(`/api/v1/memory/runs/${state.run.id}/undo`), {
- method: "POST",
- });
+ const res = await apiFetch(
+ apiUrl(`/api/v1/memory/runs/${state.run.id}/undo`),
+ {
+ method: "POST",
+ },
+ );
if (!res.ok) {
const detail = await res.text();
throw new Error(
@@ -325,7 +359,13 @@ export function useMemoryRun(layer: "L2" | "L3", key: string) {
}, [state.run]);
const clear = useCallback(() => {
- setState({ run: null, events: [], status: "idle", error: null, reconnecting: false });
+ setState({
+ run: null,
+ events: [],
+ status: "idle",
+ error: null,
+ reconnecting: false,
+ });
writePersistedRunId(layer, key, null);
close();
}, [layer, key, close]);
diff --git a/web/components/quiz/FollowupChatComposer.tsx b/web/components/quiz/FollowupChatComposer.tsx
index 7291f8cdd..e61fb5163 100644
--- a/web/components/quiz/FollowupChatComposer.tsx
+++ b/web/components/quiz/FollowupChatComposer.tsx
@@ -431,7 +431,9 @@ function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {
);
}, []);
const handleRemoveBookReference = useCallback((bookId: string) => {
- setSelectedBookReferences((prev) => prev.filter((b) => b.bookId !== bookId));
+ setSelectedBookReferences((prev) =>
+ prev.filter((b) => b.bookId !== bookId),
+ );
}, []);
const handleRemoveNotebook = useCallback((notebookId: string) => {
setSelectedNotebookRecords((prev) =>
@@ -503,8 +505,7 @@ function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {
if (!hasContent && !hasReferences) return;
if (thread.isStreaming) return;
- const isFirstSend =
- !thread.sessionId && thread.messages.length === 0;
+ const isFirstSend = !thread.sessionId && thread.messages.length === 0;
const answerImageAttachments = isFirstSend
? context.answerImages
.map((image) => {
@@ -538,9 +539,7 @@ function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {
mime_type: a.mimeType,
}));
- const skillsPayload = skillsAutoMode
- ? ["auto"]
- : [...selectedSkills];
+ const skillsPayload = skillsAutoMode ? ["auto"] : [...selectedSkills];
const baseConfig = buildQuizFollowupConfig(
context.question,
diff --git a/web/components/quiz/QuizFollowupTabBody.tsx b/web/components/quiz/QuizFollowupTabBody.tsx
index a9daafea5..b1a031b05 100644
--- a/web/components/quiz/QuizFollowupTabBody.tsx
+++ b/web/components/quiz/QuizFollowupTabBody.tsx
@@ -144,7 +144,8 @@ export default function QuizFollowupTabBody({
<div className="text-[13px] leading-relaxed text-[var(--foreground)]">
<MarkdownRenderer
content={
- isCoding && !context.userAnswer.trimStart().startsWith("```")
+ isCoding &&
+ !context.userAnswer.trimStart().startsWith("```")
? `\`\`\`python\n${context.userAnswer}\n\`\`\``
: context.userAnswer
}
@@ -210,10 +211,7 @@ export default function QuizFollowupTabBody({
visibleMessages.map((message, index) => {
if (message.role === "user") {
return (
- <div
- key={`user-${index}`}
- className="flex justify-end"
- >
+ <div key={`user-${index}`} className="flex justify-end">
<div className="max-w-[88%] whitespace-pre-wrap break-words rounded-[14px] rounded-br-md bg-[var(--primary)] px-3 py-2 text-[13px] leading-[1.6] text-[var(--primary-foreground)]">
{message.content}
</div>
@@ -235,10 +233,7 @@ export default function QuizFollowupTabBody({
message={message}
isStreaming={isStreamingThis}
onSubmitUserReply={(reply) =>
- controller.submitAskUserReply(
- context.questionKey,
- reply,
- )
+ controller.submitAskUserReply(context.questionKey, reply)
}
/>
);
diff --git a/web/components/settings/DimensionField.tsx b/web/components/settings/DimensionField.tsx
index 2abedae79..c15cb6969 100644
--- a/web/components/settings/DimensionField.tsx
+++ b/web/components/settings/DimensionField.tsx
@@ -3,10 +3,7 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
-import type {
- CatalogModel,
- EmbeddingCapabilities,
-} from "./SettingsContext";
+import type { CatalogModel, EmbeddingCapabilities } from "./SettingsContext";
import { nativeSelectClass, selectOptionClass } from "./shared";
const CUSTOM_DIM_SENTINEL = "__custom__";
diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsx
index 598f7dfe5..d1d1ff380 100644
--- a/web/components/settings/ServiceConfigEditor.tsx
+++ b/web/components/settings/ServiceConfigEditor.tsx
@@ -190,31 +190,18 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
{t("Profiles")}
</div>
<div className="space-y-0.5">
- {draft.services[service].profiles.map((profile) => {
- const isActive =
- profile.id === draft.services[service].active_profile_id;
- const profileDetail = activeProfileDetail(profile, service, t);
- const isEditing = editingProfileId === profile.id;
- return (
- <div
- key={profile.id}
- role="button"
- tabIndex={isEditing ? -1 : 0}
- onClick={() => {
- if (isEditing) return;
- mutateCatalog((next) => {
- next.services[service].active_profile_id = profile.id;
- if (service !== "search") {
- next.services[service].active_model_id =
- profile.models[0]?.id ?? null;
- }
- });
- }}
- onDoubleClick={() => startProfileRename(profile)}
- onKeyDown={(e) => {
- if (isEditing) return;
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
+ {draft.services[service].profiles.map((profile) => {
+ const isActive =
+ profile.id === draft.services[service].active_profile_id;
+ const profileDetail = activeProfileDetail(profile, service, t);
+ const isEditing = editingProfileId === profile.id;
+ return (
+ <div
+ key={profile.id}
+ role="button"
+ tabIndex={isEditing ? -1 : 0}
+ onClick={() => {
+ if (isEditing) return;
mutateCatalog((next) => {
next.services[service].active_profile_id = profile.id;
if (service !== "search") {
@@ -222,54 +209,65 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
profile.models[0]?.id ?? null;
}
});
- }
- }}
- title={
- isEditing ? undefined : t("Double-click to rename")
- }
- className={`group relative cursor-pointer rounded-lg px-3 py-2 text-left transition-colors ${
- isActive
- ? "bg-[var(--muted)]/70 text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/30"
- }`}
- >
- {isActive && (
- <span className="absolute inset-y-2 left-0 w-0.5 rounded-r-full bg-[var(--foreground)]/80" />
- )}
- {isEditing ? (
- <input
- autoFocus
- className="block w-full rounded border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-[13px] font-medium text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
- value={editingProfileName}
- onChange={(e) => setEditingProfileName(e.target.value)}
- onBlur={() => commitProfileRename(profile.id)}
- onClick={(e) => e.stopPropagation()}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.currentTarget.blur();
- }
- if (e.key === "Escape") {
- e.preventDefault();
- cancelProfileRename();
- }
- }}
- aria-label={t("Rename profile")}
- />
- ) : (
- <div
- className={`truncate text-[13px] leading-tight ${
- isActive ? "font-semibold" : "font-medium"
- }`}
- >
- {profile.name}
+ }}
+ onDoubleClick={() => startProfileRename(profile)}
+ onKeyDown={(e) => {
+ if (isEditing) return;
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ mutateCatalog((next) => {
+ next.services[service].active_profile_id = profile.id;
+ if (service !== "search") {
+ next.services[service].active_model_id =
+ profile.models[0]?.id ?? null;
+ }
+ });
+ }
+ }}
+ title={isEditing ? undefined : t("Double-click to rename")}
+ className={`group relative cursor-pointer rounded-lg px-3 py-2 text-left transition-colors ${
+ isActive
+ ? "bg-[var(--muted)]/70 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/30"
+ }`}
+ >
+ {isActive && (
+ <span className="absolute inset-y-2 left-0 w-0.5 rounded-r-full bg-[var(--foreground)]/80" />
+ )}
+ {isEditing ? (
+ <input
+ autoFocus
+ className="block w-full rounded border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-[13px] font-medium text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
+ value={editingProfileName}
+ onChange={(e) => setEditingProfileName(e.target.value)}
+ onBlur={() => commitProfileRename(profile.id)}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.currentTarget.blur();
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ cancelProfileRename();
+ }
+ }}
+ aria-label={t("Rename profile")}
+ />
+ ) : (
+ <div
+ className={`truncate text-[13px] leading-tight ${
+ isActive ? "font-semibold" : "font-medium"
+ }`}
+ >
+ {profile.name}
+ </div>
+ )}
+ <div className="mt-0.5 truncate text-[11px] leading-tight text-[var(--muted-foreground)]/70">
+ {profileDetail}
</div>
- )}
- <div className="mt-0.5 truncate text-[11px] leading-tight text-[var(--muted-foreground)]/70">
- {profileDetail}
</div>
- </div>
- );
- })}
+ );
+ })}
</div>
<div className="mt-2 border-t border-[var(--border)]/40 pt-2">
<button
@@ -349,8 +347,7 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
<div className="mb-4 flex flex-wrap items-center gap-1.5">
{activeProfile.models.map((model, index) => {
const isActive =
- model.id ===
- draft.services[service].active_model_id;
+ model.id === draft.services[service].active_model_id;
const label =
(model.name || "").trim() ||
defaultModelLabel(language, index + 1);
@@ -468,9 +465,7 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
<input
type="checkbox"
className="h-3 w-3 cursor-pointer accent-[var(--foreground)]"
- checked={
- activeModel.send_dimensions !== false
- }
+ checked={activeModel.send_dimensions !== false}
onChange={(e) =>
updateModelBoolField(
service,
@@ -687,9 +682,7 @@ function ContextWindowDetectionBanner({
return (
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/30 px-3 py-2 sm:col-span-2">
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5 text-[12px]">
- <span className="text-[var(--muted-foreground)]">
- {t("Detected")}:
- </span>
+ <span className="text-[var(--muted-foreground)]">{t("Detected")}:</span>
<span className="font-mono text-[13px] font-medium text-[var(--foreground)] tabular-nums">
{detectedFormatted}
</span>
@@ -848,9 +841,7 @@ function ProfileFields({
type="button"
onClick={() => setShowApiKey((prev) => !prev)}
className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- aria-label={
- showApiKey ? t("Hide API key") : t("Show API key")
- }
+ aria-label={showApiKey ? t("Hide API key") : t("Show API key")}
title={showApiKey ? t("Hide API key") : t("Show API key")}
>
{showApiKey ? (
diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsx
index 2c98727d9..ddb31c4c7 100644
--- a/web/components/settings/SettingsContext.tsx
+++ b/web/components/settings/SettingsContext.tsx
@@ -458,13 +458,14 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
// Only surface this when settings itself loaded; otherwise the
// settings-fetch error already explains the disconnect.
if (settingsLoaded) {
- setSettingsError((current) =>
- current ??
- (err instanceof Error
- ? t("System status unavailable: {{message}}", {
- message: err.message,
- })
- : t("System status unavailable.")),
+ setSettingsError(
+ (current) =>
+ current ??
+ (err instanceof Error
+ ? t("System status unavailable: {{message}}", {
+ message: err.message,
+ })
+ : t("System status unavailable.")),
);
}
}
@@ -519,16 +520,13 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
);
// ── Catalog mutators ────────────────────────────────────────────────────
- const mutateCatalog = useCallback(
- (mutator: (next: Catalog) => void) => {
- setDraft((current) => {
- const next = cloneCatalog(current);
- mutator(next);
- return next;
- });
- },
- [],
- );
+ const mutateCatalog = useCallback((mutator: (next: Catalog) => void) => {
+ setDraft((current) => {
+ const next = cloneCatalog(current);
+ mutator(next);
+ return next;
+ });
+ }, []);
const embeddingDefaultDim = useCallback(
(binding?: string) => {
@@ -547,10 +545,13 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
const profileId = `${service}-profile-${Date.now()}`;
const defaultBinding = service === "search" ? undefined : "openai";
const defaultProvider = service === "search" ? "brave" : undefined;
- const providerKey = service === "search" ? defaultProvider : defaultBinding;
+ const providerKey =
+ service === "search" ? defaultProvider : defaultBinding;
const providerLabel =
(providers[service] || []).find((p) => p.value === providerKey)
- ?.label ?? providerKey ?? "New Profile";
+ ?.label ??
+ providerKey ??
+ "New Profile";
const profile: CatalogProfile = {
id: profileId,
name: providerLabel,
@@ -799,7 +800,10 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
}
return null;
});
- }, [draft.services.llm.active_profile_id, draft.services.llm.active_model_id]);
+ }, [
+ draft.services.llm.active_profile_id,
+ draft.services.llm.active_model_id,
+ ]);
const runDetailedTest = useCallback(
async (service: ServiceName) => {
@@ -813,7 +817,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
const runProfileId =
service === "llm" ? draft.services.llm.active_profile_id : null;
const runModelId =
- service === "llm" ? draft.services.llm.active_model_id ?? null : null;
+ service === "llm" ? (draft.services.llm.active_model_id ?? null) : null;
if (service === "llm") setLlmContextDetection(null);
if (service === "embedding") setEmbeddingCapabilities(null);
try {
diff --git a/web/components/settings/SettingsLoadStatusBanner.tsx b/web/components/settings/SettingsLoadStatusBanner.tsx
index bed011abd..ddceda8e7 100644
--- a/web/components/settings/SettingsLoadStatusBanner.tsx
+++ b/web/components/settings/SettingsLoadStatusBanner.tsx
@@ -45,9 +45,7 @@ export function SettingsLoadStatusBanner() {
<div className="font-medium">
{t("Could not load settings from the backend.")}
</div>
- <div className="mt-1 text-xs opacity-90">
- {settingsError}
- </div>
+ <div className="mt-1 text-xs opacity-90">{settingsError}</div>
<div className="mt-1 text-xs opacity-75">
{t(
"Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.",
@@ -60,9 +58,7 @@ export function SettingsLoadStatusBanner() {
disabled={retrying}
className="inline-flex items-center gap-1 rounded-md border border-amber-300 bg-amber-100 px-2 py-1 text-xs font-medium text-amber-900 hover:bg-amber-200 disabled:opacity-60 dark:border-amber-500/40 dark:bg-amber-500/20 dark:text-amber-100"
>
- <RefreshCw
- className={retrying ? "h-3 w-3 animate-spin" : "h-3 w-3"}
- />
+ <RefreshCw className={retrying ? "h-3 w-3 animate-spin" : "h-3 w-3"} />
{t("Retry")}
</button>
</div>
diff --git a/web/components/settings/SettingsMiniNav.tsx b/web/components/settings/SettingsMiniNav.tsx
index a8f8de043..2ba5545ac 100644
--- a/web/components/settings/SettingsMiniNav.tsx
+++ b/web/components/settings/SettingsMiniNav.tsx
@@ -17,7 +17,9 @@ export default function SettingsMiniNav() {
{t("Settings")}
</h1>
<p className="mt-1.5 text-[12.5px] leading-snug text-[var(--muted-foreground)]/80">
- {t("Tune the app, configure model services, and inspect built-in tools.")}
+ {t(
+ "Tune the app, configure model services, and inspect built-in tools.",
+ )}
</p>
</div>
diff --git a/web/components/settings/ThemePreviewCard.tsx b/web/components/settings/ThemePreviewCard.tsx
index fe738dda5..38eb5d882 100644
--- a/web/components/settings/ThemePreviewCard.tsx
+++ b/web/components/settings/ThemePreviewCard.tsx
@@ -70,11 +70,7 @@ const PALETTES: Record<Theme, Palette> = {
function MiniPreview({ palette }: { palette: Palette }) {
const { bg, fg, card, primary, muted, border, glass } = palette;
return (
- <svg
- viewBox="0 0 160 96"
- className="block h-full w-full"
- aria-hidden
- >
+ <svg viewBox="0 0 160 96" className="block h-full w-full" aria-hidden>
{/* Outer frame */}
<rect x="0" y="0" width="160" height="96" rx="6" fill={bg} />
{glass && (
@@ -85,20 +81,67 @@ function MiniPreview({ palette }: { palette: Palette }) {
<stop offset="100%" stopColor="rgba(168,85,247,0)" />
</radialGradient>
</defs>
- <rect x="0" y="0" width="160" height="96" rx="6" fill="url(#glass-shine)" />
+ <rect
+ x="0"
+ y="0"
+ width="160"
+ height="96"
+ rx="6"
+ fill="url(#glass-shine)"
+ />
</>
)}
{/* Sidebar */}
<rect x="0" y="0" width="44" height="96" fill={muted} />
{/* Sidebar nav rows */}
- <rect x="8" y="14" width="28" height="3" rx="1.5" fill={fg} opacity="0.45" />
+ <rect
+ x="8"
+ y="14"
+ width="28"
+ height="3"
+ rx="1.5"
+ fill={fg}
+ opacity="0.45"
+ />
<rect x="6" y="26" width="32" height="10" rx="3" fill={card} />
- <rect x="10" y="30" width="20" height="2.5" rx="1.25" fill={fg} opacity="0.9" />
+ <rect
+ x="10"
+ y="30"
+ width="20"
+ height="2.5"
+ rx="1.25"
+ fill={fg}
+ opacity="0.9"
+ />
<circle cx="40" cy="31" r="1.5" fill={primary} />
- <rect x="8" y="44" width="24" height="2.5" rx="1.25" fill={fg} opacity="0.45" />
- <rect x="8" y="54" width="26" height="2.5" rx="1.25" fill={fg} opacity="0.45" />
- <rect x="8" y="64" width="22" height="2.5" rx="1.25" fill={fg} opacity="0.45" />
+ <rect
+ x="8"
+ y="44"
+ width="24"
+ height="2.5"
+ rx="1.25"
+ fill={fg}
+ opacity="0.45"
+ />
+ <rect
+ x="8"
+ y="54"
+ width="26"
+ height="2.5"
+ rx="1.25"
+ fill={fg}
+ opacity="0.45"
+ />
+ <rect
+ x="8"
+ y="64"
+ width="22"
+ height="2.5"
+ rx="1.25"
+ fill={fg}
+ opacity="0.45"
+ />
{/* Sidebar divider */}
<line x1="44" y1="0" x2="44" y2="96" stroke={border} strokeWidth="0.5" />
@@ -115,11 +158,43 @@ function MiniPreview({ palette }: { palette: Palette }) {
strokeWidth="0.5"
/>
{/* Title line */}
- <rect x="62" y="22" width="40" height="3.5" rx="1.5" fill={fg} opacity="0.85" />
+ <rect
+ x="62"
+ y="22"
+ width="40"
+ height="3.5"
+ rx="1.5"
+ fill={fg}
+ opacity="0.85"
+ />
{/* Body lines */}
- <rect x="62" y="34" width="78" height="2.5" rx="1.25" fill={fg} opacity="0.35" />
- <rect x="62" y="42" width="64" height="2.5" rx="1.25" fill={fg} opacity="0.35" />
- <rect x="62" y="50" width="72" height="2.5" rx="1.25" fill={fg} opacity="0.35" />
+ <rect
+ x="62"
+ y="34"
+ width="78"
+ height="2.5"
+ rx="1.25"
+ fill={fg}
+ opacity="0.35"
+ />
+ <rect
+ x="62"
+ y="42"
+ width="64"
+ height="2.5"
+ rx="1.25"
+ fill={fg}
+ opacity="0.35"
+ />
+ <rect
+ x="62"
+ y="50"
+ width="72"
+ height="2.5"
+ rx="1.25"
+ fill={fg}
+ opacity="0.35"
+ />
{/* Accent button */}
<rect x="62" y="64" width="22" height="9" rx="2.5" fill={primary} />
</svg>
@@ -151,7 +226,10 @@ export function ThemePreviewCard({
>
<div
className="relative overflow-hidden rounded-lg ring-1"
- style={{ aspectRatio: "5 / 3", boxShadow: `inset 0 0 0 1px ${palette.border}` }}
+ style={{
+ aspectRatio: "5 / 3",
+ boxShadow: `inset 0 0 0 1px ${palette.border}`,
+ }}
>
<MiniPreview palette={palette} />
{selected && (
diff --git a/web/components/settings/shared.tsx b/web/components/settings/shared.tsx
index 5d6177e67..6a73df650 100644
--- a/web/components/settings/shared.tsx
+++ b/web/components/settings/shared.tsx
@@ -11,7 +11,8 @@ export const nativeSelectClass = `${fieldControlClass} bg-[var(--background)] cu
export const selectClass = `${nativeSelectClass} appearance-none`;
-export const selectOptionClass = "bg-[var(--background)] text-[var(--foreground)]";
+export const selectOptionClass =
+ "bg-[var(--background)] text-[var(--foreground)]";
export const supportedSearchProviders = [
"brave",
@@ -29,7 +30,9 @@ export const deprecatedSearchProviders = new Set([
"openrouter",
]);
-export function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {
+export function stringifyExtraHeaders(
+ value: CatalogProfile["extra_headers"],
+): string {
if (!value) return "";
if (typeof value === "string") return value;
try {
diff --git a/web/context/QuizFollowupContext.tsx b/web/context/QuizFollowupContext.tsx
index bfff662a7..8f761b1e8 100644
--- a/web/context/QuizFollowupContext.tsx
+++ b/web/context/QuizFollowupContext.tsx
@@ -172,7 +172,10 @@ export interface QuizFollowupController {
questionKey: string,
reply:
| string
- | { text?: string; answers?: Array<{ questionId: string; text: string }> },
+ | {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ },
): void;
/** Tab open helper — forwards to whoever registered an open handler. */
openFollowupTab(context: QuizFollowupTabContext): void;
@@ -200,9 +203,9 @@ const QuizFollowupCtx = createContext<QuizFollowupController | null>(null);
// Public access to the threads state for components that want to react to
// thread updates without keeping their own snapshot. Updating the inner
// state triggers re-renders of subscribers via React's normal mechanism.
-const QuizFollowupStateCtx = createContext<
- Record<string, FollowupThreadState>
->({});
+const QuizFollowupStateCtx = createContext<Record<string, FollowupThreadState>>(
+ {},
+);
interface ProviderProps {
children: ReactNode;
@@ -323,7 +326,11 @@ export function QuizFollowupProvider({ children }: ProviderProps) {
};
}
last = messages[messages.length - 1];
- if (last && last.role === "assistant" && shouldAppendEventContent(event)) {
+ if (
+ last &&
+ last.role === "assistant" &&
+ shouldAppendEventContent(event)
+ ) {
messages[messages.length - 1] = {
...last,
content: `${last.content}${event.content}`,
@@ -434,7 +441,10 @@ export function QuizFollowupProvider({ children }: ProviderProps) {
key: string,
reply:
| string
- | { text?: string; answers?: Array<{ questionId: string; text: string }> },
+ | {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ },
) => {
const current = threadsRef.current[key];
const turnId = current?.activeTurnId;
@@ -478,11 +488,7 @@ export function QuizFollowupProvider({ children }: ProviderProps) {
}, []);
const hydrateThread = useCallback(
- (
- key: string,
- sessionId: string,
- messages: HydratedFollowupMessage[],
- ) => {
+ (key: string, sessionId: string, messages: HydratedFollowupMessage[]) => {
// Skip when the thread already holds local state — we never
// overwrite an active conversation with a stale snapshot. The
// ``sessionId`` check covers the case where the in-memory thread
diff --git a/web/lib/ask-user-state.ts b/web/lib/ask-user-state.ts
index 108652649..178a23686 100644
--- a/web/lib/ask-user-state.ts
+++ b/web/lib/ask-user-state.ts
@@ -10,12 +10,17 @@ function asRecord(value: unknown): Record<string, unknown> | null {
: null;
}
-function eventBelongsToTurn(event: StreamEvent, turnId?: string | null): boolean {
+function eventBelongsToTurn(
+ event: StreamEvent,
+ turnId?: string | null,
+): boolean {
if (!turnId) return true;
return !event.turn_id || event.turn_id === turnId;
}
-function askUserPayloadFrom(event: StreamEvent): Record<string, unknown> | null {
+function askUserPayloadFrom(
+ event: StreamEvent,
+): Record<string, unknown> | null {
const meta = asRecord(event.metadata);
const toolMetadata = asRecord(meta?.tool_metadata);
return asRecord(toolMetadata?.ask_user) ?? asRecord(meta?.ask_user);
diff --git a/web/lib/memory-graph.ts b/web/lib/memory-graph.ts
index 932448287..f1141ef5f 100644
--- a/web/lib/memory-graph.ts
+++ b/web/lib/memory-graph.ts
@@ -259,15 +259,17 @@ export async function fetchMemorySnapshot(): Promise<RawMemorySnapshot> {
}
});
- const l3Promises = L3_SLOTS.map(async (slot): Promise<[L3Slot, ParsedDoc]> => {
- try {
- const res = await apiFetch(apiUrl(`/api/v1/memory/doc/L3/${slot}`));
- const data = (await res.json()) as DocResponse;
- return [slot, parseDoc(data?.content ?? "")];
- } catch {
- return [slot, { title: "", entries: [] }];
- }
- });
+ const l3Promises = L3_SLOTS.map(
+ async (slot): Promise<[L3Slot, ParsedDoc]> => {
+ try {
+ const res = await apiFetch(apiUrl(`/api/v1/memory/doc/L3/${slot}`));
+ const data = (await res.json()) as DocResponse;
+ return [slot, parseDoc(data?.content ?? "")];
+ } catch {
+ return [slot, { title: "", entries: [] }];
+ }
+ },
+ );
const [l1Entries, l2Entries, l3Entries] = await Promise.all([
Promise.all(l1Promises),
@@ -336,7 +338,10 @@ export function buildGraph(
// render. Quiz L1 is the offender today — one row per question
// variant, with the same composite ``unified_xxx:q_N`` id appearing
// twice or more in the same snapshot.
- const dedupedL1: Record<Surface, L1Entity[]> = {} as Record<Surface, L1Entity[]>;
+ const dedupedL1: Record<Surface, L1Entity[]> = {} as Record<
+ Surface,
+ L1Entity[]
+ >;
for (const s of SURFACES) {
const seen = new Set<string>();
dedupedL1[s] = snap.l1[s].filter((e) => {
@@ -345,7 +350,10 @@ export function buildGraph(
return true;
});
}
- const dedupedL2: Record<Surface, ParsedEntry[]> = {} as Record<Surface, ParsedEntry[]>;
+ const dedupedL2: Record<Surface, ParsedEntry[]> = {} as Record<
+ Surface,
+ ParsedEntry[]
+ >;
for (const s of SURFACES) {
const seen = new Set<string>();
dedupedL2[s] = snap.l2[s].entries.filter((e) => {
@@ -354,7 +362,10 @@ export function buildGraph(
return true;
});
}
- const dedupedL3: Record<L3Slot, ParsedEntry[]> = {} as Record<L3Slot, ParsedEntry[]>;
+ const dedupedL3: Record<L3Slot, ParsedEntry[]> = {} as Record<
+ L3Slot,
+ ParsedEntry[]
+ >;
for (const slot of L3_SLOTS) {
const seen = new Set<string>();
dedupedL3[slot] = snap.l3[slot].entries.filter((e) => {
@@ -372,9 +383,7 @@ export function buildGraph(
const l3MinFrac = 0.12; // 43° floor — keeps even empty slots labelable
const l3MinPool = l3MinFrac * L3_SLOTS.length;
const l3ElasticPool = Math.max(0, 1 - l3MinPool);
- const l3Frac = l3Counts.map(
- (c) => l3MinFrac + (c / l3Total) * l3ElasticPool,
- );
+ const l3Frac = l3Counts.map((c) => l3MinFrac + (c / l3Total) * l3ElasticPool);
const l3FracSum = l3Frac.reduce((a, b) => a + b, 0);
for (let i = 0; i < l3Frac.length; i++) l3Frac[i] /= l3FracSum;
@@ -410,7 +419,9 @@ export function buildGraph(
// Each surface gets a minimum slice so tiny ones (book, tutorbot)
// still register visually.
const minSliceFraction = 0.025; // ≈ 9° floor
- const rawWeights = SURFACES.map((s) => dedupedL1[s].length + dedupedL2[s].length);
+ const rawWeights = SURFACES.map(
+ (s) => dedupedL1[s].length + dedupedL2[s].length,
+ );
const totalRaw = rawWeights.reduce((a, b) => a + b, 0) || 1;
const minPool = minSliceFraction * SURFACES.length;
const elasticPool = Math.max(0, 1 - minPool);
@@ -419,7 +430,8 @@ export function buildGraph(
);
// Renormalise (rounding can drift it off 1.0).
const sumFrac = surfaceFraction.reduce((a, b) => a + b, 0);
- for (let i = 0; i < surfaceFraction.length; i++) surfaceFraction[i] /= sumFrac;
+ for (let i = 0; i < surfaceFraction.length; i++)
+ surfaceFraction[i] /= sumFrac;
const l2ClusterMap = new Map<string, ClusterMeta>();
const l1ClusterMap = new Map<string, ClusterMeta>();
@@ -684,7 +696,9 @@ function placeNodesInSlice<T extends { x: number; y: number; r: number }>(
for (let r = 0; r < rows; r++) {
const rowCols = Math.max(
1,
- Math.round((count * (rowMidR(r) * sliceSpan)) / (densityCell * totalCapacity)),
+ Math.round(
+ (count * (rowMidR(r) * sliceSpan)) / (densityCell * totalCapacity),
+ ),
);
for (let c = 0; c < rowCols; c++) {
slots.push({ row: r, col: c, cols: rowCols });
@@ -696,7 +710,11 @@ function placeNodesInSlice<T extends { x: number; y: number; r: number }>(
// outermost row.
while (slots.length < count) {
const r = rows - 1;
- slots.push({ row: r, col: slots.length, cols: slots[slots.length - 1].cols + 1 });
+ slots.push({
+ row: r,
+ col: slots.length,
+ cols: slots[slots.length - 1].cols + 1,
+ });
}
// Deterministic pseudo-random for jitter, indexed by item id.
const hash = (n: number) => {
@@ -711,10 +729,12 @@ function placeNodesInSlice<T extends { x: number; y: number; r: number }>(
// Hex offset: alternate rows shift by half a column.
const colShift = slot.row % 2 === 0 ? 0 : 0.5 / slot.cols;
const a =
- cluster.startAngle + sliceSpan * (colFrac + colShift) +
+ cluster.startAngle +
+ sliceSpan * (colFrac + colShift) +
(hash(i) - 0.5) * (sliceSpan / slot.cols) * 0.45;
const r =
- rowMid + (hash(i + 9311) - 0.5) * Math.min(densityCell * 0.85, thickness / rows);
+ rowMid +
+ (hash(i + 9311) - 0.5) * Math.min(densityCell * 0.85, thickness / rows);
const node = factory(i);
node.x = center.x + Math.cos(a) * r;
node.y = center.y + Math.sin(a) * r;
diff --git a/web/tests/ask-user-state.test.ts b/web/tests/ask-user-state.test.ts
index 7492372f7..ac33a0052 100644
--- a/web/tests/ask-user-state.test.ts
+++ b/web/tests/ask-user-state.test.ts
@@ -1,6 +1,9 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { hasPendingAskUser, hasPendingAskUserInMessages } from "../lib/ask-user-state";
+import {
+ hasPendingAskUser,
+ hasPendingAskUserInMessages,
+} from "../lib/ask-user-state";
import type { StreamEvent } from "../lib/unified-ws";
function event(
@@ -40,7 +43,9 @@ test("hasPendingAskUser clears the matching card after ask_user_resolved", () =>
const events = [
event("tool_result", {
tool_call_id: "call-1",
- tool_metadata: { ask_user: { questions: [{ id: "scope", prompt: "Scope?" }] } },
+ tool_metadata: {
+ ask_user: { questions: [{ id: "scope", prompt: "Scope?" }] },
+ },
}),
event("progress", {
ask_user_resolved: true,
@@ -59,7 +64,9 @@ test("hasPendingAskUserInMessages ignores ask_user cards from other turns", () =
"tool_result",
{
tool_call_id: "call-old",
- tool_metadata: { ask_user: { questions: [{ id: "q", prompt: "Old?" }] } },
+ tool_metadata: {
+ ask_user: { questions: [{ id: "q", prompt: "Old?" }] },
+ },
},
"turn-old",
),