diff --git a/README.md b/README.md
index 1a78e881..5e1b102c 100644
--- a/README.md
+++ b/README.md
@@ -91,6 +91,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques
| [本机大盘 · Local Market Board](plugins/jzlikewei/kurumi-monitor/) | Watch your own machine as a stock terminal: CPU, GPU, temperature, memory, disk, network and every running process become listed stocks with live candlesticks, moving averages, a watchlist, a leaderboard and a trade tape, on macOS and Windows. Requires minimax Code 3.1.2 or later | [jzlikewei](https://github.com/jzlikewei) |
| [Quota Bottle](plugins/7723qqq/quota-bottle/) | An octopus-shaped glass bottle that floats on your desktop and shows the remaining Token Plan quota from a login you configure yourself, with the liquid level and opacity following the remaining share, and a device-code login plus an opt-in local token-usage estimate as fallbacks | [7723qqq](https://github.com/7723qqq) |
| [Site QA](plugins/lonelyguy-se1/site-qa/) | Check local HTML/robots/sitemap for SEO and accessibility gaps, then ask the agent to fix them (Mini App + skill/CLI). Requires MiniMax Code 3.1.6 or later | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) |
+| [Learn Workbench](plugins/meisijiya/learn-workbench/) | A teach-method learning workbench: mission, curriculum, per-lesson branch sessions, annotations, notes and a code-link panel; lesson file links open the matching lines in an in-app panel | [meisijiya](https://github.com/meisijiya) |
| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/) | Turn one sentence into verified 4K images: it plans the shot list, searches for reference images, generates, reviews each image by looking at it, corrects colour cast, runs a bounded fix loop and delivers the result with an acceptance report; multi-image runs generate a character sheet first so the same subject stays the same subject. Needs an H3-Image endpoint and key you configure yourself. Requires MiniMax Code 3.1.6 or later | [liddalidd](https://github.com/liddalidd) |
| [Express Media](plugins/andre-1998/express-media/) | Compress a video to the size each platform accepts and report whether it fits; the bundled limits table shows where every number comes from | [Andre-1998](https://github.com/Andre-1998) |
| [FactScribe Paper Workbench](plugins/unclemoc/factscribe/) | A local workbench for writing papers: open your manuscript projects, read the check report, the fact ledger and the knowledge base, and let the assistant propose edits you approve before anything reaches the file. 17 MCP tools, read-mostly by design; every write is gated by your confirmation. Requires MiniMax Code 3.1.2 or later | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 19c1ac99..4e930985 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -91,6 +91,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求
| [本机大盘](plugins/jzlikewei/kurumi-monitor/README.zh-CN.md) | 把本机当成行情终端来看:CPU、GPU、温度、内存、磁盘、网络与每个运行中的进程都是一只个股,实时 K 线、均线、自选行情、主力动向与逐笔成交,支持 macOS 与 Windows。需要 minimax Code 3.1.2 或更高版本 | [jzlikewei](https://github.com/jzlikewei) |
| [额度瓶](plugins/7723qqq/quota-bottle/README.zh-CN.md) | 一只悬浮在桌面上的章鱼形玻璃瓶,用你自己配置的登录读取 Token Plan 剩余额度;液面与透明度按剩余占比走,拿不到实时额度时回退到设备码登录或手填总额与可选的本机本月用量 | [7723qqq](https://github.com/7723qqq) |
| [Site QA](plugins/lonelyguy-se1/site-qa/) | 检查本地 HTML/robots/sitemap 的 SEO / 无障碍问题,再让 Agent 修复(Mini App + skill/CLI)。需要 MiniMax Code 3.1.6 或更高版本(说明文档为英文) | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) |
+| [学习工作台](plugins/meisijiya/learn-workbench/README.zh-CN.md) | 按 teach 方法管理学习目录:使命、课纲、每课独立分支会话、划词批注与笔记提炼;课程里的文件链接会在应用内打开对应行 | [meisijiya](https://github.com/meisijiya) |
| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/README.zh-CN.md) | 把一句话需求跑成经过校验的 4K 图片:规划分镜、检索参考图、生成、看图评审、色偏校正、有限次修正,最后交付图片和验收报告;多图任务会先生成角色设定图锁定主体外观。需要自备 H3-Image 接口地址和 Key。需要 MiniMax Code 3.1.6 或更高版本 | [liddalidd](https://github.com/liddalidd) |
| [急件 · 视频投递](plugins/andre-1998/express-media/README.zh-CN.md) | 把视频压到各平台能收的体积,并如实告诉你发不发得出去;内置上限表标明每个数字的来源 | [Andre-1998](https://github.com/Andre-1998) |
| [FactScribe 论文工作台](plugins/unclemoc/factscribe/README.zh-CN.md) | 写论文的本地工作台:打开你的稿盘,看检查报告、事实账与知识库,助手给的改动先成提议单,你在页面上点采纳才落盘。17 个 MCP 工具以只读为主,写盘一律由你确认。需要 MiniMax Code 3.1.2 或更高版本 | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) |
diff --git a/plugins/meisijiya/learn-workbench/.minimax-plugin/plugin.json b/plugins/meisijiya/learn-workbench/.minimax-plugin/plugin.json
new file mode 100644
index 00000000..3ee34fdb
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/.minimax-plugin/plugin.json
@@ -0,0 +1,18 @@
+{
+ "schemaVersion": 1,
+ "name": "learn-workbench",
+ "displayName": "学习工作台",
+ "version": "1.0.0",
+ "description": "A teach-method learning workbench: mission, curriculum, per-lesson branch sessions, annotations, notes and a code-link panel.",
+ "author": "meisijiya",
+ "icon": "icon.png",
+ "category": "Education",
+ "exampleQueries": [
+ "打开学习工作台,继续第 3 课",
+ "为这个主题生成课纲,每节课开一个独立会话",
+ "把第 1–3 课结合我的批注提炼成笔记"
+ ],
+ "apps": [],
+ "mcpServers": [],
+ "skills": []
+}
diff --git a/plugins/meisijiya/learn-workbench/LICENSE b/plugins/meisijiya/learn-workbench/LICENSE
new file mode 100644
index 00000000..32a54759
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 meisijiya
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/meisijiya/learn-workbench/README.md b/plugins/meisijiya/learn-workbench/README.md
new file mode 100644
index 00000000..2f3993d9
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/README.md
@@ -0,0 +1,51 @@
+# Learn Workbench
+
+A teach-method learning workbench for MiniMax Code. You pick a learning folder; the workbench keeps its mission, curriculum, lessons, references, learning records and notes, and gives every lesson its own branch conversation with the Agent.
+
+The page is in Chinese, like the learning method it follows (Matt Pocock's teach approach).
+
+## What it does
+
+- **Setup**: a setup conversation interviews you and writes `MISSION.md`, `RESOURCES.md`, `GLOSSARY.md` and `NOTES.md` into the folder you chose.
+- **Curriculum**: the main conversation writes a 3–6 module curriculum into `.workbench/curriculum.json` plus a human-readable `CURRICULUM.md`. Regenerating it keeps existing lesson titles, claimed files and statuses.
+- **Lessons**: each lesson has a branch conversation that writes one self-contained HTML lesson into `lessons/`. Every lesson is required to stand alone: when it needs earlier knowledge, it recaps it in one or two sentences and links back.
+- **Annotations and notes**: select text in a lesson to annotate it; a note conversation distils chosen lessons and annotations into Markdown under `notes/`.
+- **Code links**: a file link inside a lesson (`main.py:608`, `main.py:46–48`) opens a floating code panel at that line, without leaving the app.
+- **Workspace management**: create or import learning folders, regenerate a lesson, clean generated artifacts, and switch models.
+
+## Install
+
+- **From Git (MiniMax Code 3.1.11 or later)**: in the plugin marketplace choose **Create → Mini App → Import from Git repository**, then enter `https://github.com/meisijiya/learn-workbench-miniapp`.
+- **Manual copy**: copy this folder to `~/.minimax/plugins/learn-workbench/` (`%USERPROFILE%\.minimax\plugins\learn-workbench\` on Windows), restart MiniMax Code, and make sure the plugin is enabled.
+
+The package declares `agentAccess`, `agentConcurrency` and `surface.window`, whose minimum client is MiniMax Code 3.1.2.
+
+## Use
+
+1. Open 学习工作台 from the plugin list.
+2. Choose or create a learning folder.
+3. Finish the setup conversation, then generate the curriculum from the main conversation.
+4. Open a lesson; its branch conversation writes and revises that lesson.
+5. Annotate the text you care about, and distil notes when you want them.
+
+## Tested environment
+
+- MiniMax Code 3.1.19 on Windows 11 (10.0.26200), using the Node runtime provided by the app.
+- Tested: setup; curriculum generation and regeneration; lesson generation, rewrite and clean-then-regenerate; annotations and highlights; note extraction; the code-link panel; workspace create, import and remove.
+- Not tested: macOS, Linux, clients older than 3.1.19, and very long conversations.
+
+## Data & access
+
+- **Files read and written**: only the learning folder you choose. The app creates and edits `MISSION.md`, `RESOURCES.md`, `GLOSSARY.md`, `NOTES.md`, `CURRICULUM.md`, `lessons/*.html`, `reference/*.html`, `learning-records/*.md`, `notes/*.md`, `assets/course.css`, and the `.workbench/` state folder (`workspace.json`, `curriculum.json`, `curriculum.backup.json`, `sessions.json`, `annotations.json`, `notes.json`, `rules/teach.md`, `context/`).
+- **Where state is stored**: the workspace folder above, plus a workspace registry (`registry.json`) in the Host-provided `context.dataDir`.
+- **Network**: the Mini App makes no external network requests. The page talks only to its own local Node service on the Host-assigned port. Agent turns it starts may use the Host's own tools and network under the Host's permissions.
+- **Agent turns**: it starts Agent sessions for setup, the main conversation (curriculum), each lesson branch, and note extraction. It reads and writes only its own session records inside the selected folder; it does not read other conversations.
+- **Tools**: no MCP endpoints; it declares `agentAccess: ["session.run"]`.
+- **Processes**: it does not spawn processes beyond the Host starting its own Node entry.
+- **Microphone, camera, notifications**: not used.
+- **Host navigation read**: no. It does not read which MiniMax Code page you are on.
+- **Code files**: clicking a file link reads a text or code file inside the learning folder (no `..`, 512 KB limit) and shows it in a panel.
+
+## License
+
+MIT — see `LICENSE`.
diff --git a/plugins/meisijiya/learn-workbench/README.zh-CN.md b/plugins/meisijiya/learn-workbench/README.zh-CN.md
new file mode 100644
index 00000000..56d90108
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/README.zh-CN.md
@@ -0,0 +1,49 @@
+# 学习工作台
+
+给 MiniMax Code 用的 teach 方法学习工作台。你选一个学习目录;工作台在这里维护使命、课纲、课程、速查、学习记录与笔记,并给每节课一个独立的分支会话。
+
+## 它能做什么
+
+- **前置配置**:配置会话采访你,把 `MISSION.md`、`RESOURCES.md`、`GLOSSARY.md`、`NOTES.md` 写进你选的目录。
+- **课纲**:主会话写 3–6 个模块的课纲到 `.workbench/curriculum.json`,同时写人类可读的 `CURRICULUM.md`。重新生成会保留已有课程标题、已认领文件与状态。
+- **课程**:每节课有自己的分支会话,写出一份自包含的 HTML 到 `lessons/`。每节课都要求能单独阅读;需要前置知识时,用一两句话回顾并链接回那一课。
+- **批注与笔记**:在课程里划词添加批注;提炼会话把选中的课程与批注整理成 `notes/` 下的 Markdown。
+- **代码链接**:课程里的文件链接(`main.py:608`、`main.py:46–48`)会在应用内弹出代码面板并定位到对应行。
+- **工作台管理**:新建/导入学习目录、逐课重新生成、清理产物、切换模型。
+
+## 安装
+
+- **从 Git 导入(MiniMax Code 3.1.11 起)**:插件市场 →「创建」→「Mini App」→「从 Git 仓库导入」,填 `https://github.com/meisijiya/learn-workbench-miniapp`。
+- **手动复制**:把本目录复制到 `~/.minimax/plugins/learn-workbench/`(Windows 为 `%USERPROFILE%\.minimax\plugins\learn-workbench\`),重启 MiniMax Code,确认插件已启用。
+
+包声明了 `agentAccess`、`agentConcurrency` 与 `surface.window`,最低客户端为 MiniMax Code 3.1.2。
+
+## 使用
+
+1. 从插件列表打开「学习工作台」。
+2. 选择或新建一个学习目录。
+3. 完成配置会话,再从主会话生成课纲。
+4. 打开一节课,让它的分支会话写课、改课。
+5. 划词批注,需要时提炼笔记。
+
+## 测试环境
+
+- MiniMax Code 3.1.19,Windows 11(10.0.26200),使用应用自带的 Node 运行时。
+- 已验证:配置;课纲生成与重新生成;课程生成、整节重写、清理后重新生成;批注与高亮;笔记提炼;代码链接面板;工作台新建、导入与移除。
+- 未验证:macOS、Linux、3.1.19 之前的客户端、超长会话。
+
+## 数据与访问
+
+- **读写文件**:只读写你选择的学习目录。应用会创建/修改 `MISSION.md`、`RESOURCES.md`、`GLOSSARY.md`、`NOTES.md`、`CURRICULUM.md`、`lessons/*.html`、`reference/*.html`、`learning-records/*.md`、`notes/*.md`、`assets/course.css`,以及 `.workbench/` 状态目录(`workspace.json`、`curriculum.json`、`curriculum.backup.json`、`sessions.json`、`annotations.json`、`notes.json`、`rules/teach.md`、`context/`)。
+- **状态存放**:上述学习目录,以及宿主提供的 `context.dataDir` 里的工作台注册表(`registry.json`)。
+- **网络**:Mini App 不发起外部网络请求;页面只访问宿主分配端口上的本地 Node 服务。它启动的 Agent 轮次可能按宿主权限使用宿主自己的工具与网络。
+- **Agent 轮次**:会为配置、主会话(课纲)、每节课的分支、笔记提炼启动 Agent 会话;只读写所选目录里自己的会话记录,不读取其他对话。
+- **工具**:没有 MCP endpoint;声明 `agentAccess: ["session.run"]`。
+- **进程**:除宿主启动自己的 Node 入口外,不额外启动进程。
+- **麦克风、摄像头、通知**:不使用。
+- **读取宿主页面**:不读取你当前在 MiniMax Code 的哪个页面。
+- **代码文件**:点击课程里的文件链接时,读取学习目录内的文本/代码文件(禁止 `..`,上限 512 KB)并在面板里显示。
+
+## 许可证
+
+MIT,见 `LICENSE`。
diff --git a/plugins/meisijiya/learn-workbench/icon.png b/plugins/meisijiya/learn-workbench/icon.png
new file mode 100644
index 00000000..299a26cb
Binary files /dev/null and b/plugins/meisijiya/learn-workbench/icon.png differ
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/app.css b/plugins/meisijiya/learn-workbench/miniapp/client/app.css
new file mode 100644
index 00000000..1888cf14
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/app.css
@@ -0,0 +1,896 @@
+:root,
+[data-theme='light'] {
+ --mcode-bg: #ffffff;
+ --mcode-bg-secondary: #f5f5f5;
+ --mcode-surface: #ffffff;
+ --mcode-surface-muted: #fafafa;
+ --mcode-text: #171717;
+ --mcode-text-muted: #666666;
+ --mcode-text-subtle: #a3a3a3;
+ --mcode-border: #0a0a0a14;
+ --mcode-border-strong: #0a0a0a2e;
+ --mcode-accent: #0094fc;
+ --mcode-accent-soft: #0094fc14;
+ --mcode-success: #04b54b;
+ --mcode-warning: #f56811;
+ --mcode-danger: #f73646;
+ --mcode-primary-action-bg: #171717;
+ --mcode-primary-action-text: #ffffff;
+ --paper: #fbfaf7;
+ --ink: #1c1b19;
+ --shadow: 0 0 20px rgb(10 10 10 / 8%);
+ --overlay: rgb(10 10 10 / 28%);
+}
+[data-theme='dark'] {
+ --mcode-bg: #171717;
+ --mcode-bg-secondary: #1c1c1c;
+ --mcode-surface: #262626;
+ --mcode-surface-muted: #202020;
+ --mcode-text: #ededed;
+ --mcode-text-muted: #949494;
+ --mcode-text-subtle: #6b6b6b;
+ --mcode-border: #ffffff14;
+ --mcode-border-strong: #ffffff2e;
+ --mcode-accent: #5eb0ff;
+ --mcode-accent-soft: #5eb0ff1a;
+ --mcode-success: #22c55e;
+ --mcode-warning: #f59e0b;
+ --mcode-danger: #f87171;
+ --mcode-primary-action-bg: #ffffff;
+ --mcode-primary-action-text: #171717;
+ --paper: #1e1d1b;
+ --ink: #ece9e2;
+ --shadow: 0 0 24px rgb(0 0 0 / 45%);
+ --overlay: rgb(0 0 0 / 55%);
+}
+
+.talk-meta {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ margin-top: 4px;
+}
+.model-pick {
+ max-width: 190px;
+ border: 1px solid var(--mcode-border-strong);
+ border-radius: 6px;
+ background: var(--mcode-surface);
+ color: var(--mcode-text);
+ font-size: 11px;
+ padding: 1px 4px;
+}
+.model-pick:disabled { opacity: 0.55; }
+.talk-stat {
+ font-size: 11px;
+ color: var(--mcode-text-subtle);
+ white-space: nowrap;
+}
+
+* { box-sizing: border-box; }
+html, body { height: 100%; }
+body {
+ margin: 0;
+ background: var(--mcode-bg);
+ color: var(--mcode-text);
+ font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', 'PingFang SC',
+ 'Microsoft YaHei', Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ line-height: 1.55;
+ -webkit-font-smoothing: antialiased;
+}
+button, input, textarea, select { font: inherit; color: inherit; }
+button { cursor: pointer; background: none; border: 0; padding: 0; }
+a { color: var(--mcode-accent); text-decoration: none; }
+a:hover { text-decoration: underline; }
+::-webkit-scrollbar { width: 10px; height: 10px; }
+::-webkit-scrollbar-thumb {
+ background: var(--mcode-border-strong);
+ border-radius: 999px;
+ border: 3px solid transparent;
+ background-clip: content-box;
+}
+.mono {
+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.92em;
+}
+.muted { color: var(--mcode-text-muted); }
+.subtle { color: var(--mcode-text-subtle); }
+.label {
+ font-size: 11px;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--mcode-text-subtle);
+}
+.hidden { display: none !important; }
+.grow { flex: 1; }
+.row { display: flex; align-items: center; gap: 8px; }
+.stack { display: flex; flex-direction: column; gap: 8px; }
+
+.icon {
+ width: 15px;
+ height: 15px;
+ stroke: currentColor;
+ fill: none;
+ stroke-width: 1.6;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ flex: none;
+}
+
+.chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 20px;
+ padding: 0 7px;
+ border-radius: 999px;
+ font-size: 11px;
+ line-height: 1;
+ border: 1px solid var(--mcode-border);
+ color: var(--mcode-text-muted);
+ background: var(--mcode-surface-muted);
+ white-space: nowrap;
+}
+.chip.ok {
+ color: var(--mcode-success);
+ background: color-mix(in srgb, var(--mcode-success) 10%, transparent);
+ border-color: transparent;
+}
+.chip.live {
+ color: var(--mcode-warning);
+ background: color-mix(in srgb, var(--mcode-warning) 12%, transparent);
+ border-color: transparent;
+}
+.chip.todo { color: var(--mcode-text-subtle); }
+
+.btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ height: 32px;
+ padding: 0 12px;
+ border-radius: 8px;
+ border: 1px solid var(--mcode-border);
+ background: var(--mcode-surface);
+ color: var(--mcode-text);
+ font-size: 13px;
+ white-space: nowrap;
+ transition: background 150ms ease-out, border-color 150ms ease-out, opacity 150ms ease-out;
+}
+.btn:hover { background: var(--mcode-surface-muted); }
+.btn:focus-visible { outline: 2px solid var(--mcode-accent); outline-offset: 2px; }
+.btn[disabled] { opacity: 0.5; cursor: default; }
+.btn.primary {
+ background: var(--mcode-primary-action-bg);
+ color: var(--mcode-primary-action-text);
+ border-color: transparent;
+}
+.btn.primary:hover { opacity: 0.88; background: var(--mcode-primary-action-bg); }
+.btn.ghost { border-color: transparent; background: transparent; color: var(--mcode-text-muted); }
+.btn.ghost:hover { background: var(--mcode-surface-muted); color: var(--mcode-text); }
+.btn.danger { color: var(--mcode-danger); }
+.btn.sm { height: 26px; padding: 0 9px; font-size: 12px; }
+.btn.icon { width: 30px; height: 30px; padding: 0; }
+
+.field {
+ width: 100%;
+ min-height: 34px;
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ background: var(--mcode-surface);
+ padding: 7px 10px;
+ font-size: 13px;
+ resize: vertical;
+ outline: none;
+}
+.field:focus {
+ border-color: var(--mcode-border-strong);
+ box-shadow: 0 0 0 3px var(--mcode-accent-soft);
+}
+.field::placeholder { color: var(--mcode-text-subtle); }
+select.field { height: 32px; min-height: 32px; padding: 0 8px; }
+
+.progressbar {
+ height: 4px;
+ border-radius: 999px;
+ background: var(--mcode-border);
+ overflow: hidden;
+}
+.progressbar > i {
+ display: block;
+ height: 100%;
+ background: var(--mcode-success);
+ border-radius: 999px;
+ transition: width 300ms ease-out;
+}
+
+/* ------------------------------------------------------------------ app */
+
+.app {
+ height: 100vh;
+ display: grid;
+ grid-template-columns: 248px minmax(0, 1fr) 344px;
+ grid-template-rows: 52px minmax(0, 1fr);
+ grid-template-areas:
+ 'top top top'
+ 'rail center talk';
+}
+.app.no-talk { grid-template-columns: 248px minmax(0, 1fr) 0; }
+.app.no-talk .talk { display: none; }
+
+.top {
+ grid-area: top;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0 14px;
+ border-bottom: 1px solid var(--mcode-border);
+ min-width: 0;
+}
+.ws-mark {
+ width: 26px;
+ height: 26px;
+ border-radius: 7px;
+ background: var(--mcode-primary-action-bg);
+ color: var(--mcode-primary-action-text);
+ display: grid;
+ place-items: center;
+ font-size: 11px;
+ font-weight: 600;
+ flex: none;
+}
+.ws-name {
+ font-size: 13.5px;
+ font-weight: 600;
+ line-height: 1.2;
+ max-width: 220px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ws-path {
+ font-size: 11px;
+ color: var(--mcode-text-subtle);
+ max-width: 300px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ws-switch {
+ height: 30px;
+ max-width: 190px;
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ background: var(--mcode-surface);
+ font-size: 12px;
+ padding: 0 6px;
+}
+
+.rail {
+ grid-area: rail;
+ border-right: 1px solid var(--mcode-border);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+.rail-head { padding: 12px 14px 8px; display: flex; flex-direction: column; gap: 8px; }
+.rail-head .progress-line { display: flex; align-items: center; gap: 8px; font-size: 11.5px; color: var(--mcode-text-muted); }
+.tree { flex: 1; overflow-y: auto; padding: 2px 8px 16px; }
+.mod {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 10px 6px 4px;
+}
+.mod .mname { font-size: 12px; font-weight: 600; }
+.mod .mcount { font-size: 10.5px; color: var(--mcode-text-subtle); }
+.lesson-row {
+ display: grid;
+ grid-template-columns: 22px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ text-align: left;
+ padding: 7px 8px;
+ border-radius: 8px;
+ color: var(--mcode-text-muted);
+ border: 1px solid transparent;
+}
+.lesson-row:hover { background: var(--mcode-surface-muted); }
+.lesson-row.active {
+ background: var(--mcode-accent-soft);
+ border-color: color-mix(in srgb, var(--mcode-accent) 24%, transparent);
+ color: var(--mcode-text);
+}
+.lesson-row .no { font-size: 11px; color: var(--mcode-text-subtle); font-variant-numeric: tabular-nums; }
+.lesson-row .nm { font-size: 12.5px; line-height: 1.35; overflow: hidden; text-overflow: ellipsis; }
+.lesson-row.active .nm { font-weight: 600; color: var(--mcode-text); }
+.lesson-row .marks { display: flex; align-items: center; gap: 5px; }
+.dotstate { width: 6px; height: 6px; border-radius: 999px; background: var(--mcode-border-strong); }
+.dotstate.done { background: var(--mcode-success); }
+.dotstate.active { background: var(--mcode-warning); }
+.annocount { font-size: 10px; color: var(--mcode-text-subtle); }
+.unread { width: 5px; height: 5px; border-radius: 999px; background: var(--mcode-accent); }
+.rail-foot { border-top: 1px solid var(--mcode-border); padding: 8px; display: flex; flex-direction: column; gap: 2px; }
+.rail-foot button {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 7px 8px;
+ border-radius: 7px;
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ text-align: left;
+}
+.rail-foot button:hover { background: var(--mcode-surface-muted); color: var(--mcode-text); }
+.rail-foot .count { margin-left: auto; font-size: 11px; color: var(--mcode-text-subtle); }
+
+.center { grid-area: center; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
+.center-head { padding: 12px 20px 0; }
+.center-head .row1 { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.center-head h2 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+ letter-spacing: -0.005em;
+ white-space: nowrap;
+}
+.center-head .objective {
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ margin-top: 3px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.tabs { display: flex; gap: 18px; margin-top: 8px; }
+.tabs button {
+ padding: 0 0 9px;
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ border-bottom: 2px solid transparent;
+ margin-bottom: -1px;
+}
+.tabs button.on { color: var(--mcode-text); border-color: var(--mcode-text); }
+.center-body { flex: 1; overflow-y: auto; min-height: 0; }
+.center-body.flush { overflow: hidden; }
+.frame-wrap { height: 100%; background: #fff; }
+.frame-wrap iframe { width: 100%; height: 100%; border: 0; display: block; background: #fff; }
+
+.empty {
+ max-width: 460px;
+ margin: 48px auto;
+ text-align: center;
+ color: var(--mcode-text-muted);
+ font-size: 13px;
+ line-height: 1.7;
+}
+.empty h3 { margin: 10px 0 4px; font-size: 14px; color: var(--mcode-text); font-weight: 600; }
+.empty .icon { width: 22px; height: 22px; color: var(--mcode-text-subtle); }
+.empty .actions { margin-top: 14px; display: flex; gap: 8px; justify-content: center; }
+
+/* overview */
+.pane { padding: 20px 22px 60px; max-width: 760px; }
+.card {
+ border: 1px solid var(--mcode-border);
+ border-radius: 12px;
+ background: var(--mcode-surface);
+ padding: 14px 16px;
+}
+.card + .card { margin-top: 12px; }
+.card h3 { margin: 0 0 6px; font-size: 13px; font-weight: 600; }
+.card .card-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
+.card .card-head h3 { margin: 0; }
+.prose {
+ font-size: 13px;
+ line-height: 1.75;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+.prose.long { max-height: 220px; overflow: auto; }
+.stat-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
+.stat {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ padding: 11px 13px;
+ background: var(--mcode-surface);
+}
+.stat .k { font-size: 11px; color: var(--mcode-text-subtle); }
+.stat .v { font-size: 22px; font-weight: 600; letter-spacing: -0.01em; margin-top: 2px; line-height: 1.2; }
+.stat .v small { font-size: 12px; font-weight: 400; color: var(--mcode-text-muted); }
+.list-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 7px 0;
+ font-size: 12.5px;
+ line-height: 1.5;
+}
+.list-row + .list-row { border-top: 1px solid var(--mcode-border); }
+.list-row .t { color: var(--mcode-text); }
+.list-row .m { color: var(--mcode-text-subtle); font-size: 11px; }
+
+/* annotations */
+.anno-pane { padding: 18px 22px 60px; }
+.anno {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ padding: 10px 12px;
+ background: var(--mcode-surface);
+}
+.anno + .anno { margin-top: 8px; }
+.anno.flash { border-color: var(--mcode-accent); box-shadow: 0 0 0 3px var(--mcode-accent-soft); }
+.anno .quote {
+ font-family: ui-serif, Georgia, 'Songti SC', serif;
+ font-size: 12.5px;
+ color: var(--mcode-text-muted);
+ border-left: 2px solid var(--mcode-warning);
+ padding-left: 8px;
+ margin-bottom: 6px;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.anno .note { font-size: 13px; line-height: 1.6; white-space: pre-wrap; }
+.anno .meta { display: flex; align-items: center; gap: 8px; margin-top: 6px; font-size: 11px; color: var(--mcode-text-subtle); }
+.anno .meta .grow { flex: 1; }
+
+/* notes */
+.note-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ width: 100%;
+ text-align: left;
+ padding: 10px 12px;
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ background: var(--mcode-surface);
+}
+.note-row + .note-row { margin-top: 8px; }
+.note-row:hover { border-color: var(--mcode-border-strong); }
+.note-row .nt { font-size: 13px; font-weight: 600; }
+.note-row .nm { font-size: 11.5px; color: var(--mcode-text-subtle); margin-top: 2px; }
+.md { font-size: 13.5px; line-height: 1.75; max-width: 720px; }
+.md h1 { font-size: 20px; margin: 0 0 0.5em; }
+.md h2 { font-size: 15px; margin: 1.6em 0 0.3em; }
+.md h3 { font-size: 13.5px; margin: 1.2em 0 0.2em; }
+.md p { margin: 0 0 0.8em; }
+.md ul, .md ol { padding-left: 1.3em; margin: 0 0 0.8em; }
+.md li { margin: 0.15em 0; }
+.md code {
+ font-family: 'JetBrains Mono', ui-monospace, Menlo, monospace;
+ font-size: 0.88em;
+ background: var(--mcode-surface-muted);
+ border-radius: 4px;
+ padding: 0.1em 0.32em;
+}
+.md pre {
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ padding: 10px 12px;
+ overflow: auto;
+ font-size: 12.5px;
+}
+.md pre code { background: none; padding: 0; }
+.md blockquote {
+ margin: 0.8em 0;
+ padding-left: 12px;
+ border-left: 2px solid var(--mcode-border-strong);
+ color: var(--mcode-text-muted);
+}
+.md a { border-bottom: 1px solid currentColor; }
+.md hr { border: 0; border-top: 1px solid var(--mcode-border); margin: 1.4em 0; }
+.md table {
+ border-collapse: collapse;
+ font-size: 12.5px;
+ margin: 0.4em 0 1em;
+ display: block;
+ overflow-x: auto;
+ max-width: 100%;
+}
+.md th,
+.md td {
+ border: 1px solid var(--mcode-border);
+ padding: 6px 9px;
+ text-align: left;
+ vertical-align: top;
+}
+.md th {
+ background: var(--mcode-surface-muted);
+ font-weight: 600;
+ color: var(--mcode-text-muted);
+}
+
+/* chat */
+.talk {
+ grid-area: talk;
+ border-left: 1px solid var(--mcode-border);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+.talk-head {
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--mcode-border);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 50px;
+}
+.talk-head .t {
+ font-size: 12.5px;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.talk-head .s { font-size: 11px; color: var(--mcode-text-subtle); }
+.chat-scroll {
+ flex: 1;
+ overflow-y: auto;
+ min-height: 0;
+ padding: 14px 14px 6px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+.msg { display: flex; flex-direction: column; gap: 5px; }
+.msg .who { font-size: 11px; color: var(--mcode-text-subtle); display: flex; align-items: center; gap: 6px; }
+.msg .bubble { font-size: 13px; line-height: 1.68; white-space: pre-wrap; word-break: break-word; }
+.msg.user .bubble {
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ padding: 9px 11px;
+}
+.msg.user .bubble.prompt-seed {
+ font-size: 12px;
+ color: var(--mcode-text-muted);
+}
+.msg.assistant .bubble { padding: 0 1px; }
+.msg.assistant .bubble h1, .msg.assistant .bubble h2, .msg.assistant .bubble h3 {
+ font-size: 13px;
+ margin: 0.8em 0 0.2em;
+}
+.msg.assistant .bubble p { margin: 0 0 0.6em; }
+.msg.assistant .bubble ul, .msg.assistant .bubble ol { margin: 0 0 0.6em; padding-left: 1.2em; }
+.msg.assistant .bubble code {
+ font-family: 'JetBrains Mono', ui-monospace, Menlo, monospace;
+ font-size: 0.88em;
+ background: var(--mcode-surface-muted);
+ border-radius: 4px;
+ padding: 0.1em 0.3em;
+}
+.msg.assistant .bubble pre {
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ padding: 9px 11px;
+ overflow: auto;
+ font-size: 12px;
+}
+.msg.assistant .bubble pre code { background: none; padding: 0; }
+.msg .bubble a { border-bottom: 1px solid currentColor; }
+.msg.system .bubble {
+ font-size: 11.5px;
+ color: var(--mcode-text-muted);
+ background: var(--mcode-surface-muted);
+ border-radius: 8px;
+ padding: 6px 9px;
+}
+.msg.system.error .bubble { color: var(--mcode-danger); }
+.msg .bubble .pending-dots::after {
+ content: '···';
+ letter-spacing: 0.1em;
+ color: var(--mcode-text-subtle);
+}
+.tool-line {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 11.5px;
+ color: var(--mcode-text-muted);
+ background: var(--mcode-surface-muted);
+ border: 1px solid var(--mcode-border);
+ border-radius: 8px;
+ padding: 5px 9px;
+}
+.tool-line .mono { color: var(--mcode-text); }
+.composer { border-top: 1px solid var(--mcode-border); padding: 10px 12px 12px; }
+.composer .box {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ padding: 8px 9px;
+ background: var(--mcode-surface);
+}
+.composer .box:focus-within { border-color: var(--mcode-border-strong); box-shadow: 0 0 0 3px var(--mcode-accent-soft); }
+.composer textarea {
+ width: 100%;
+ border: 0;
+ background: none;
+ outline: none;
+ resize: none;
+ font-size: 13px;
+ line-height: 1.5;
+ min-height: 40px;
+ max-height: 120px;
+}
+.composer .row { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px; }
+.composer .hint { font-size: 11px; color: var(--mcode-text-subtle); }
+.composer .actions { display: flex; align-items: center; gap: 6px; }
+
+/* interaction cards */
+.card-interact {
+ border: 1px solid var(--mcode-border-strong);
+ border-radius: 10px;
+ background: var(--mcode-surface);
+ padding: 10px 11px;
+ font-size: 12.5px;
+}
+.card-interact h4 { margin: 0 0 4px; font-size: 12px; font-weight: 600; }
+.card-interact p { margin: 0 0 8px; color: var(--mcode-text-muted); line-height: 1.55; }
+.card-interact .opts { display: flex; flex-direction: column; gap: 5px; margin-bottom: 8px; }
+.card-interact .opt {
+ display: flex;
+ gap: 7px;
+ align-items: flex-start;
+ border: 1px solid var(--mcode-border);
+ border-radius: 7px;
+ padding: 6px 8px;
+ cursor: pointer;
+ background: var(--mcode-surface-muted);
+ font-size: 12.5px;
+ line-height: 1.45;
+}
+.card-interact .opt input { margin-top: 2px; flex: none; }
+.card-interact .opt .d { display: block; color: var(--mcode-text-muted); font-size: 11.5px; }
+.card-interact .step + .step { margin-top: 10px; }
+.card-interact .step-q { font-weight: 600; margin-bottom: 5px; }
+.card-interact .plan {
+ background: var(--mcode-surface-muted);
+ border-radius: 8px;
+ padding: 9px 10px;
+ max-height: 260px;
+ overflow: auto;
+ white-space: pre-wrap;
+ font-size: 12px;
+ margin-bottom: 8px;
+}
+
+/* modal */
+.modal-backdrop {
+ position: fixed;
+ inset: 0;
+ background: var(--overlay);
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ z-index: 60;
+}
+.modal {
+ width: min(560px, 100%);
+ max-height: min(760px, calc(100vh - 48px));
+ background: var(--mcode-bg);
+ border: 1px solid var(--mcode-border);
+ border-radius: 12px;
+ box-shadow: 0 18px 60px rgb(0 0 0 / 22%);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+.modal.wide { width: min(720px, 100%); }
+.modal-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 13px 16px;
+ border-bottom: 1px solid var(--mcode-border);
+}
+.modal-head h3 { margin: 0; font-size: 14px; font-weight: 600; }
+.modal-body { padding: 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 12px; }
+.modal-foot {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 12px 16px;
+ border-top: 1px solid var(--mcode-border);
+}
+.modal-foot .left { margin-right: auto; }
+
+/* directory picker */
+.crumbs {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11.5px;
+ color: var(--mcode-text-muted);
+ overflow: hidden;
+}
+.crumbs .path {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ direction: rtl;
+ text-align: left;
+ flex: 1;
+}
+.dir-list {
+ border: 1px solid var(--mcode-border);
+ border-radius: 10px;
+ max-height: 250px;
+ overflow-y: auto;
+ padding: 4px;
+ background: var(--mcode-surface);
+}
+.dir {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ text-align: left;
+ padding: 6px 8px;
+ border-radius: 7px;
+ font-size: 12.5px;
+}
+.dir:hover { background: var(--mcode-surface-muted); }
+.dir .n { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.dir.hidden-dir { opacity: 0.55; }
+.dir .badge {
+ margin-left: auto;
+ font-size: 10px;
+ color: var(--mcode-success);
+ border: 1px solid color-mix(in srgb, var(--mcode-success) 40%, transparent);
+ border-radius: 999px;
+ padding: 0 6px;
+}
+.checkline { display: flex; align-items: center; gap: 7px; font-size: 12.5px; color: var(--mcode-text-muted); }
+.checkline input { margin: 0; }
+.form-label { font-size: 11.5px; color: var(--mcode-text-muted); margin-bottom: 4px; display: block; }
+.hint-line { font-size: 11.5px; color: var(--mcode-text-subtle); line-height: 1.6; }
+.hint-line.warn { color: var(--mcode-warning); }
+
+/* lesson file panel: a code window opened from a link inside a lesson */
+.modal.wide:has(.file-view) { width: min(1000px, 100%); }
+.modal-body:has(.file-view) { padding: 0; }
+.file-view {
+ max-height: min(62vh, 640px);
+ overflow: auto;
+ font: 12px/1.6 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+}
+.file-row { display: flex; gap: 12px; padding: 0 14px; white-space: pre; }
+.file-row .ln { flex: 0 0 52px; text-align: right; color: var(--mcode-text-subtle); user-select: none; }
+.file-row .lc { flex: 1 0 auto; white-space: pre; }
+.file-row.hit { background: color-mix(in srgb, var(--mcode-warning) 15%, transparent); }
+
+/* notes picker */
+.pick-group + .pick-group { margin-top: 10px; }
+.pick-group .g-title { font-size: 11.5px; font-weight: 600; color: var(--mcode-text-muted); margin-bottom: 4px; }
+.pick-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 7px;
+ border-radius: 7px;
+ font-size: 12.5px;
+}
+.pick-row:hover { background: var(--mcode-surface-muted); }
+.pick-row input { margin: 0; }
+.pick-row .t { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.pick-row .c { font-size: 10.5px; color: var(--mcode-text-subtle); }
+.manage-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 9px 2px;
+ border-top: 1px solid var(--mcode-border);
+}
+.manage-row:first-child { border-top: 0; }
+.manage-row .nt { font-size: 13px; font-weight: 600; }
+.manage-row .nm { font-size: 11px; color: var(--mcode-text-subtle); word-break: break-all; }
+.clean-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ font-size: 12.5px;
+ line-height: 1.55;
+ padding: 3px 0;
+ cursor: pointer;
+}
+.clean-row input { margin: 3px 0 0; flex: none; }
+
+/* landing */
+.landing {
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 40px 24px;
+ background: var(--mcode-bg);
+}
+.landing-inner { width: min(680px, 100%); }
+.landing h1 { font-size: 22px; font-weight: 600; letter-spacing: -0.01em; margin: 0 0 4px; }
+.landing .sub { color: var(--mcode-text-muted); font-size: 13px; margin-bottom: 22px; }
+.landing .actions { display: flex; gap: 8px; margin-bottom: 26px; }
+.recent { border-top: 1px solid var(--mcode-border); padding-top: 14px; }
+.recent h2 { font-size: 12px; color: var(--mcode-text-subtle); font-weight: 500; margin: 0 0 8px; }
+.recent-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ text-align: left;
+ padding: 9px 10px;
+ border-radius: 9px;
+ border: 1px solid transparent;
+}
+.recent-row:hover { background: var(--mcode-surface-muted); border-color: var(--mcode-border); }
+.recent-row .nm { font-size: 13px; font-weight: 600; }
+.recent-row .pt { font-size: 11px; color: var(--mcode-text-subtle); }
+
+/* toast */
+.toast {
+ position: fixed;
+ left: 50%;
+ bottom: 22px;
+ transform: translateX(-50%);
+ background: var(--mcode-primary-action-bg);
+ color: var(--mcode-primary-action-text);
+ border-radius: 999px;
+ padding: 7px 14px;
+ font-size: 12.5px;
+ box-shadow: 0 8px 24px rgb(0 0 0 / 20%);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 180ms ease-out, transform 180ms ease-out;
+ z-index: 80;
+ max-width: 80vw;
+}
+.toast.show { opacity: 1; transform: translateX(-50%) translateY(-2px); }
+.toast.error { background: var(--mcode-danger); color: #fff; }
+
+/* annotation modal */
+.quote-box {
+ border-left: 2px solid var(--mcode-warning);
+ background: var(--mcode-surface-muted);
+ border-radius: 0 8px 8px 0;
+ padding: 9px 11px;
+ font-family: ui-serif, Georgia, 'Songti SC', serif;
+ font-size: 13px;
+ line-height: 1.7;
+ max-height: 130px;
+ overflow: auto;
+}
+.note-input { min-height: 96px; }
+
+@media (max-width: 1120px) {
+ .app { grid-template-columns: 232px minmax(0, 1fr); grid-template-areas: 'top top' 'rail center'; }
+ .talk {
+ position: fixed;
+ right: 0;
+ top: 52px;
+ bottom: 0;
+ width: min(380px, 88vw);
+ background: var(--mcode-bg);
+ box-shadow: -14px 0 40px rgb(10 10 10 / 12%);
+ z-index: 30;
+ }
+ .app.no-talk .talk { display: none; }
+}
+@media (max-width: 760px) {
+ .app { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'center'; }
+ .rail { display: none; }
+ .top { gap: 6px; }
+ .ws-path { display: none; }
+ .stat-grid { grid-template-columns: 1fr 1fr; }
+ .center-head { padding: 10px 14px 0; }
+ .pane, .anno-pane { padding: 16px 14px 60px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ * { transition: none !important; animation: none !important; }
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/app.js b/plugins/meisijiya/learn-workbench/miniapp/client/app.js
new file mode 100644
index 00000000..a6559da2
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/app.js
@@ -0,0 +1,2573 @@
+(function () {
+ 'use strict';
+
+ /* ------------------------------------------------------------- helpers */
+
+ const $ = (selector, root = document) => root.querySelector(selector);
+ const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector));
+
+ const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
+ const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ESCAPES[char]);
+
+ const ICONS = {
+ book: '',
+ chat: '',
+ note: '',
+ play: '',
+ check: '',
+ plus: '',
+ x: '',
+ dots: '',
+ send: '',
+ open: '',
+ folder: '',
+ spark: '',
+ up: '',
+ left: '',
+ stop: '',
+ refresh: '',
+ trash: '',
+ };
+ const icon = (name) => ``;
+
+ const ERROR_TEXT = {
+ BUSY: '这一轮还在进行,等它结束再发。',
+ ANSWER_PENDING: '先回答右侧会话里待回答的问题,再重新生成这一课。',
+ NOT_PERMITTED: '这个能力在插件设置里被关掉了,打开后再试。',
+ NO_QUESTION: '这个问题已经结束,刷新一下会话。',
+ NO_PERMISSION: '这次授权请求已经结束。',
+ NOT_FOUND: '对象不存在,可能已被移动或删除。',
+ TARGET_NOT_EMPTY: '目标文件夹不是空的,换一个名字或目录。',
+ NOT_A_WORKSPACE: '这个目录里没有学习工作台(缺少 .workbench/workspace.json)。',
+ SETUP_REQUIRED: '先完成前置配置,再生成课纲。',
+ PARENT_NOT_FOUND: '目录不存在。',
+ HOME_NOT_ALLOWED: '别把工作台建在用户主目录,请选一个具体项目文件夹。',
+ DRIVE_ROOT_NOT_ALLOWED: '别把工作台建在磁盘根目录,请选一个项目文件夹。',
+ not_a_directory: '这个路径不是一个文件夹。',
+ path_must_be_absolute: '要填完整路径,例如 D:\\代码\\项目名。',
+ NO_LESSONS: '选中的课程还没有生成文件,先生成课程。',
+ SESSION_CREATE_FAILED: '无法创建会话,检查插件权限后重试。',
+ internal_error: '内部错误,看一下插件诊断。',
+ };
+
+ function errorText(error) {
+ const code = error && error.code;
+ return ERROR_TEXT[code] || (error && error.message) || '操作失败';
+ }
+
+ async function api(path, options) {
+ const opts = options || {};
+ const response = await fetch(path, {
+ method: opts.method || 'GET',
+ headers: opts.body ? { 'content-type': 'application/json' } : undefined,
+ body: opts.body ? JSON.stringify(opts.body) : undefined,
+ });
+ const text = await response.text();
+ let data = null;
+ try {
+ data = text ? JSON.parse(text) : null;
+ } catch {
+ data = null;
+ }
+ if (!response.ok) {
+ const error = new Error((data && (data.message || data.error)) || `HTTP ${response.status}`);
+ error.code = (data && data.error) || 'http_error';
+ error.status = response.status;
+ throw error;
+ }
+ return data;
+ }
+
+ let toastTimer = 0;
+ function toast(message, kind) {
+ const node = $('#toast');
+ if (!node) return;
+ node.textContent = message;
+ node.className = `toast show${kind === 'error' ? ' error' : ''}`;
+ window.clearTimeout(toastTimer);
+ toastTimer = window.setTimeout(() => {
+ node.className = 'toast';
+ }, 2800);
+ }
+
+ function timeLabel(ms) {
+ if (!ms) return '';
+ const date = new Date(ms);
+ const pad = (n) => String(n).padStart(2, '0');
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
+ }
+
+ /* --------------------------------------------------------- mini markdown */
+
+ function md(text) {
+ const source = esc(String(text ?? '')).replace(/\r\n/g, '\n');
+ const lines = source.split('\n');
+ const out = [];
+ let index = 0;
+
+ const inline = (value) =>
+ value
+ .replace(/`([^`]+)`/g, '$1')
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
+ .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '$1')
+ .replace(/(^|[\s(])(https?:\/\/[^\s<)]+)/g, '$1$2');
+
+ while (index < lines.length) {
+ const line = lines[index];
+
+ if (/^```/.test(line)) {
+ const lang = line.slice(3).trim();
+ const buffer = [];
+ index += 1;
+ while (index < lines.length && !/^```/.test(lines[index])) {
+ buffer.push(lines[index]);
+ index += 1;
+ }
+ index += 1;
+ out.push(
+ `
${buffer.join('\n')}
`,
+ );
+ continue;
+ }
+
+ if (!line.trim()) {
+ index += 1;
+ continue;
+ }
+
+ const heading = line.match(/^(#{1,4})\s+(.*)$/);
+ if (heading) {
+ const level = Math.min(3, heading[1].length);
+ out.push(`${inline(heading[2])}`);
+ index += 1;
+ continue;
+ }
+
+ if (/^(\s*)(---|\*\*\*|___)\s*$/.test(line)) {
+ out.push('
');
+ index += 1;
+ continue;
+ }
+
+ if (/^\s*\|/.test(line) && /^\s*\|?[\s:-]+\|/.test(lines[index + 1] || '')) {
+ const header = line.split('|').map((cell) => cell.trim()).filter(Boolean);
+ index += 2;
+ const rows = [];
+ while (index < lines.length && /^\s*\|/.test(lines[index])) {
+ const cells = lines[index].split('|').map((cell) => cell.trim());
+ if (cells.length && cells[0] === '') cells.shift();
+ if (cells.length && cells[cells.length - 1] === '') cells.pop();
+ rows.push(cells);
+ index += 1;
+ }
+ out.push(
+ `${header.map((cell) => `| ${inline(cell)} | `).join('')}
${rows
+ .map((cells) => `${cells.map((cell) => `| ${inline(cell)} | `).join('')}
`)
+ .join('')}
`,
+ );
+ continue;
+ }
+
+ if (/^\s*>\s?/.test(line)) {
+ const buffer = [];
+ while (index < lines.length && /^\s*>\s?/.test(lines[index])) {
+ buffer.push(lines[index].replace(/^\s*>\s?/, ''));
+ index += 1;
+ }
+ out.push(`${buffer.map(inline).join('
')}
`);
+ continue;
+ }
+
+ if (/^\s*([-*]|\d+\.)\s+/.test(line)) {
+ const ordered = /^\s*\d+\./.test(line);
+ const buffer = [];
+ while (index < lines.length && /^\s*([-*]|\d+\.)\s+/.test(lines[index])) {
+ buffer.push(lines[index].replace(/^\s*([-*]|\d+\.)\s+/, ''));
+ index += 1;
+ }
+ const tag = ordered ? 'ol' : 'ul';
+ out.push(`<${tag}>${buffer.map((item) => `${inline(item)}`).join('')}${tag}>`);
+ continue;
+ }
+
+ const buffer = [];
+ while (
+ index < lines.length &&
+ lines[index].trim() &&
+ !/^```/.test(lines[index]) &&
+ !/^(#{1,4})\s+/.test(lines[index]) &&
+ !/^\s*([-*]|\d+\.)\s+/.test(lines[index]) &&
+ !/^\s*>\s?/.test(lines[index]) &&
+ !/^(\s*)(---|\*\*\*|___)\s*$/.test(lines[index]) &&
+ !/^\s*\|/.test(lines[index])
+ ) {
+ buffer.push(lines[index]);
+ index += 1;
+ }
+ out.push(`${buffer.map(inline).join('
')}
`);
+ }
+
+ return out.join('\n');
+ }
+
+ /* ---------------------------------------------------------------- state */
+
+ const S = {
+ boot: null,
+ wsId: null,
+ snap: null,
+ lessonId: null,
+ sessionId: null,
+ center: 'lesson',
+ tab: 'lesson',
+ noteId: null,
+ noteText: '',
+ transcripts: new Map(),
+ drafts: new Map(),
+ live: new Map(),
+ tools: new Map(),
+ loads: new Map(),
+ unread: new Set(),
+ talkOpen: true,
+ centerSig: '',
+ railSig: '',
+ topSig: '',
+ snapKey: '',
+ sending: false,
+ talkError: '',
+ pendingQuote: '',
+ pendingAnnoId: '',
+ picker: null,
+ es: null,
+ };
+
+ /** Every derived view reads this key; nothing hand-picks snapshot fields. */
+ function setSnapshot(next) {
+ S.snap = next;
+ S.snapKey = next ? JSON.stringify(next) : '';
+ }
+
+ const lessonsOf = () =>
+ S.snap ? S.snap.curriculum.modules.flatMap((module) => module.lessons) : [];
+ const findLesson = (id) => lessonsOf().find((lesson) => lesson.id === id) || null;
+ const lessonByFile = (rel) =>
+ lessonsOf().find((lesson) => lesson.file && lesson.file === rel) || null;
+ const currentLesson = () => findLesson(S.lessonId);
+ const lessonHasFile = (lesson) =>
+ Boolean(lesson && lesson.file && S.snap && S.snap.lessonFiles.includes(lesson.file));
+ const annotationsOf = (lessonId) =>
+ S.snap ? S.snap.annotations.filter((item) => item.lessonId === lessonId) : [];
+ const currentSession = () => (S.sessionId ? S.transcripts.get(S.sessionId) : null);
+
+ function pickLesson() {
+ const all = lessonsOf();
+ if (!all.length) return null;
+ const stored = localStorage.getItem(`wb.lesson.${S.wsId}`);
+ if (stored && all.some((lesson) => lesson.id === stored)) return stored;
+ const active = all.find((lesson) => lesson.status === 'active');
+ const planned = all.find((lesson) => lesson.status === 'planned');
+ return (active || planned || all[0]).id;
+ }
+
+ function lessonNumberList(ids) {
+ const numbers = ids
+ .map((id) => findLesson(id))
+ .filter(Boolean)
+ .map((lesson) => lesson.no)
+ .sort((a, b) => a - b);
+ if (!numbers.length) return '';
+ if (numbers.length === 1) return `第 ${numbers[0]} 课`;
+ const contiguous = numbers.every((n, i) => i === 0 || n === numbers[i - 1] + 1);
+ return contiguous ? `第 ${numbers[0]}–${numbers[numbers.length - 1]} 课` : `第 ${numbers.join('、')} 课`;
+ }
+
+ /* ----------------------------------------------------------------- theme */
+
+ function applyTheme(theme) {
+ document.documentElement.dataset.theme = theme === 'dark' ? 'dark' : 'light';
+ const frame = $('#lesson-frame');
+ if (frame && frame.contentWindow) {
+ frame.contentWindow.postMessage(
+ { source: 'host', type: 'theme', theme: theme === 'dark' ? 'dark' : 'light' },
+ '*',
+ );
+ }
+ }
+
+ function initTheme() {
+ const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ applyTheme(prefersDark ? 'dark' : 'light');
+ const host = window.mcode && window.mcode.miniapp && window.mcode.miniapp.host;
+ if (host && host.ui && host.ui.subscribe) {
+ try {
+ const subscription = host.ui.subscribe(
+ (state) => applyTheme(state.theme),
+ { onError: () => undefined },
+ );
+ window.addEventListener(
+ 'pagehide',
+ () => {
+ if (subscription && subscription.dispose) subscription.dispose();
+ },
+ { once: true },
+ );
+ } catch {
+ /* keep the system theme */
+ }
+ }
+ }
+
+ /* --------------------------------------------------------------- landing */
+
+ function renderLanding() {
+ const host = $('#app');
+ const list = (S.boot && S.boot.workspaces) || [];
+ host.innerHTML = `
+
+
+
学习工作台
+
按 teach 方法管理学习目录与课纲;每节课有独立的分支会话,批注和笔记跟着课程走。
+
+
+
+ ${list.length ? `` : ''}
+
+ ${
+ list.length
+ ? `
+
最近
+ ${list
+ .map(
+ (workspace) => `
`,
+ )
+ .join('')}
+
`
+ : `
还没有工作台
选一个目录,工作台会在里面创建 MISSION.md、lessons/、reference/ 等 teach 结构。
`
+ }
+
+
`;
+ connectEvents();
+ }
+
+ /* ------------------------------------------------------------ workspace */
+
+ async function openWorkspace(id) {
+ S.wsId = id;
+ S.transcripts.clear();
+ S.drafts.clear();
+ S.live.clear();
+ S.tools.clear();
+ S.unread.clear();
+ S.sessionId = null;
+ S.noteId = null;
+ S.centerSig = '';
+ S.railSig = '';
+ try {
+ setSnapshot(await api(`/api/ws/${encodeURIComponent(id)}`));
+ } catch (error) {
+ toast(errorText(error), 'error');
+ localStorage.removeItem('wb.last');
+ S.boot = await api('/api/bootstrap').catch(() => S.boot);
+ S.wsId = null;
+ renderLanding();
+ return;
+ }
+ localStorage.setItem('wb.last', id);
+ S.lessonId = pickLesson();
+ const setupPending = S.snap.workspace.configured === false;
+ S.center = setupPending || !S.snap.curriculum.modules.length ? 'overview' : 'lesson';
+ renderShell(true);
+ connectEvents();
+ if (setupPending) {
+ S.talkOpen = true;
+ renderShell(false);
+ await openSetupSession();
+ return;
+ }
+ if (S.lessonId) {
+ await selectLesson(S.lessonId, { seed: false, silent: true });
+ } else {
+ const recent = (S.snap.sessions || []).find((session) => session.kind === 'main') || (S.snap.sessions || [])[0];
+ if (recent) await openSession(recent.id);
+ else updateTalk();
+ }
+ }
+
+ async function openSetupSession() {
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/setup/open`, {
+ method: 'POST',
+ body: {},
+ });
+ S.talkOpen = true;
+ renderShell(false);
+ if (result && result.sessionId) await openSession(result.sessionId);
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function shellHtml() {
+ return `
+ `;
+ }
+
+ function renderShell(force) {
+ const host = $('#app');
+ const existing = $('#app .app');
+ if (!force && existing && existing.dataset.ws === S.wsId) {
+ existing.classList.toggle('no-talk', !S.talkOpen);
+ updateTop();
+ updateRail();
+ updateCenter();
+ updateTalk();
+ return;
+ }
+ host.innerHTML = shellHtml();
+ bindComposer();
+ updateTop();
+ updateRail();
+ updateCenter();
+ updateTalk();
+ }
+
+ function bindComposer() {
+ const form = $('#talk-form');
+ const input = $('#talk-input');
+ if (!form || !input) return;
+ form.addEventListener('submit', (event) => {
+ event.preventDefault();
+ void sendCurrent();
+ });
+ input.addEventListener('keydown', (event) => {
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
+ event.preventDefault();
+ void sendCurrent();
+ }
+ });
+ input.addEventListener('input', () => {
+ if (S.sessionId) S.drafts.set(S.sessionId, input.value);
+ autoSize(input);
+ });
+ }
+
+ function autoSize(input) {
+ input.style.height = 'auto';
+ input.style.height = `${Math.min(120, input.scrollHeight)}px`;
+ }
+
+ /* ------------------------------------------------------------------- top */
+
+ function updateTop() {
+ const node = $('#top');
+ if (!node || !S.snap) return;
+ const summary = S.snap.summary;
+ const sig = `${S.wsId}|${S.snapKey}|${(S.boot && S.boot.workspaces ? S.boot.workspaces.map((w) => w.name).join(",") : '')}`;
+ if (sig === S.topSig) return;
+ S.topSig = sig;
+ const workspaces = (S.boot && S.boot.workspaces) || [];
+ node.innerHTML = `
+ 学
+
+
${esc(S.snap.workspace.name)}
+
${esc(S.snap.workspace.root)}
+
+
+ 已学 ${summary.done}/${summary.total} 课
+ ${
+ workspaces.length > 1
+ ? ``
+ : ''
+ }
+
+
+
+
+
+ `;
+ const select = $('#ws-switch');
+ if (select) {
+ select.addEventListener('change', () => {
+ S.talkOpen = window.innerWidth > 1120;
+ void openWorkspace(select.value);
+ });
+ }
+ }
+
+ /* ------------------------------------------------------------------ rail */
+
+ function updateRail() {
+ const node = $('#rail');
+ if (!node || !S.snap) return;
+ const lessons = lessonsOf();
+ const sig = JSON.stringify([S.snapKey, S.lessonId, Array.from(S.unread).sort()]);
+ if (sig === S.railSig) return;
+ S.railSig = sig;
+ const total = lessons.length || 0;
+ const done = S.snap.summary.done;
+ node.innerHTML = `
+
+
+ ${
+ total
+ ? S.snap.curriculum.modules
+ .map(
+ (module) => `
+
${esc(module.title)}${module.lessons.length} 课
+ ${module.lessons
+ .map((lesson) => {
+ const count = annotationsOf(lesson.id).length;
+ return `
`;
+ })
+ .join('')}`,
+ )
+ .join('')
+ : `
还没有课纲。先在概览里让主会话写一份。
`
+ }
+
+ `;
+ }
+
+ /* ---------------------------------------------------------------- center */
+
+ function centerSignature() {
+ return JSON.stringify([S.snapKey, S.center, S.lessonId, S.tab, S.noteId, S.talkOpen]);
+ }
+
+ function updateCenter() {
+ const head = $('#center-head');
+ const body = $('#center-body');
+ if (!head || !body || !S.snap) return;
+ const sig = centerSignature();
+ if (sig === S.centerSig) return;
+ S.centerSig = sig;
+ body.classList.toggle('flush', S.center === 'lesson' && lessonHasFile(currentLesson()));
+
+ if (S.center === 'overview') {
+ head.innerHTML = `
+ 使命、课纲与资源都在这个目录里,随时可以改。
`;
+ body.innerHTML = overviewHtml();
+ return;
+ }
+
+ if (S.center === 'notes' || S.center === 'note') {
+ head.innerHTML = `
+ 按你选的课程范围,结合课程内容与批注,交给她在独立会话里完成。
`;
+ body.innerHTML = S.center === 'note' ? noteHtml() : notesHtml();
+ return;
+ }
+
+ const lesson = currentLesson();
+ if (!lesson) {
+ head.innerHTML = `课程
`;
+ body.innerHTML = `${icon('book')}
还没有课程
先在概览里生成课纲。
+
`;
+ return;
+ }
+
+ const annoCount = annotationsOf(lesson.id).length;
+ head.innerHTML = `
+
+
第 ${String(lesson.no).padStart(2, '0')} 课
+
${
+ lesson.status === 'done' ? '已完成' : lesson.status === 'active' ? '进行中' : '未开始'
+ }
+
约 ${lesson.minutes} 分钟
+
+ ${
+ lessonHasFile(lesson)
+ ? `
`
+ : ''
+ }
+
+
+
+ ${esc(lesson.objective || lesson.title)}
+
+
+
+
`;
+
+ if (S.tab === 'anno') {
+ body.classList.remove('flush');
+ body.innerHTML = annotationPaneHtml(lesson);
+ return;
+ }
+
+ if (!lessonHasFile(lesson)) {
+ body.classList.remove('flush');
+ body.innerHTML = `${icon('spark')}
这一课还没有生成
+
课程分支会话会读使命、课纲和前几课的学习记录,再写这节课的 HTML。
+
+
+
+
`;
+ return;
+ }
+
+ const src = `/w/${encodeURIComponent(S.wsId)}/${lesson.file
+ .split('/')
+ .map(encodeURIComponent)
+ .join('/')}?v=${S.snap.curriculum.updatedAt}`;
+ body.innerHTML = ``;
+ }
+
+ function overviewHtml() {
+ const summary = S.snap.summary;
+ const issues = S.snap.curriculum.issues || [];
+ const hasLessons = summary.total > 0;
+ const setupPending = S.snap.workspace.configured === false;
+ const titleMissing = !setupPending && !S.snap.missionTitle;
+ return `
+
+
已掌握
${summary.done} / ${summary.total} 课
+
+
+
+
+
+
前置配置
+
${setupPending ? '进行中' : '已就绪'}
+
+ ${
+ setupPending
+ ? `
`
+ : `
`
+ }
+
+ ${
+ setupPending
+ ? `
配置会话会在右侧问你几个问题,然后把使命、来源与规则写进这个目录。这一步只搭前置环境,不产出课程和课纲。
`
+ : `
${esc((S.snap.missionExcerpt || '').slice(0, 600) || '使命已写入 MISSION.md。')}
`
+ }
+ ${
+ titleMissing
+ ? `
+ MISSION.md 的第一行不是「# Mission: 主题」,工作台名字仍按目录名显示。改成这个格式后点「重新读取」,就会按标题命名。
+
+
`
+ : ''
+ }
+
+
+
+
课纲
+
${hasLessons ? `${summary.total} 课` : '未生成'}
+
+
+
+ ${
+ hasLessons
+ ? `
${esc(
+ S.snap.curriculum.modules
+ .map(
+ (module) =>
+ `${module.title}:${module.lessons
+ .map((lesson) => `${String(lesson.no).padStart(2, '0')} ${lesson.title}`)
+ .join(' · ')}`,
+ )
+ .join('\n'),
+ )}
`
+ : setupPending
+ ? `
前置配置完成后,主会话才能按使命写课纲。
`
+ : `
主会话会按使命写 3–6 个模块,每节课 15–25 分钟。生成过程在右侧会话里可见。
`
+ }
+ ${issues.length ? `
${esc(issues.join(';'))}
` : ''}
+ ${
+ S.snap.curriculumError
+ ? `
+ 课纲文件无法解析(${esc(S.snap.curriculumError)})。让主会话修复格式,或点「重新读取」。
+
+
`
+ : ''
+ }
+
+
+
+
+ ${
+ S.snap.records.length
+ ? S.snap.records
+ .map(
+ (record) =>
+ `
${icon('check')}
${esc(record.title)}
${esc(record.rel)}
`,
+ )
+ .join('')
+ : `
还没有学习记录。老师说清一个概念、你做出一次正确判断之后,才会写一条。
`
+ }
+
+
+
+
目录与规则
+
+
+
+
${esc(S.snap.workspace.root)}
+
规则文件:.workbench/rules/teach.md · 课纲:.workbench/curriculum.json · 课件:lessons/
+
+
`;
+ }
+
+ function annotationPaneHtml(lesson) {
+ const items = annotationsOf(lesson.id);
+ return `
+
+
本课批注
+
+
+
+ ${
+ items.length
+ ? items
+ .map(
+ (item) => `
+ ${item.quote ? `
${esc(item.quote)}
` : ''}
+
${esc(item.note)}
+
+
`,
+ )
+ .join('')
+ : `
在左侧课程里选中一句话,点浮动按钮就能批注;也可以点上面的「整节批注」。
`
+ }
+
`;
+ }
+
+ function notesHtml() {
+ const items = S.snap.notes;
+ if (!items.length) {
+ return `${icon('note')}
还没有笔记
+
选几节课,她会在独立会话里把课程内容和你写在课上的批注一起提炼成 Markdown。
+
`;
+ }
+ return `
+ ${items
+ .map((note) => {
+ const scope = lessonNumberList(note.lessonIds);
+ const statusChip =
+ note.status === 'ready'
+ ? '
已生成'
+ : note.status === 'running'
+ ? '
生成中'
+ : '
未完成';
+ return `
`;
+ })
+ .join('')}
+
笔记写入 notes/*.md,可以继续编辑;再提炼时会重新生成一份。
+
`;
+ }
+
+ function noteHtml() {
+ const note = S.snap.notes.find((item) => item.id === S.noteId);
+ if (!note) {
+ return `${icon('note')}
笔记不存在
`;
+ }
+ return `
+
+
+
+
${esc(note.path)}
+
+
${md(S.noteText)}
+
`;
+ }
+
+ /* ------------------------------------------------------------------ talk */
+
+ const modelCatalog = () =>
+ S.boot && S.boot.models && Array.isArray(S.boot.models.models) ? S.boot.models.models : [];
+ const fmtChars = (value) => (value >= 10000 ? (value / 1000).toFixed(1) + 'k' : String(value));
+ const countTurns = (session) =>
+ session && Array.isArray(session.messages)
+ ? session.messages.filter((message) => message.role === 'assistant').length
+ : 0;
+ const countChars = (session) =>
+ session && Array.isArray(session.messages)
+ ? session.messages.reduce((sum, message) => sum + String(message.text ?? '').length, 0)
+ : 0;
+
+ async function switchModel(model) {
+ if (!S.sessionId) return;
+ const url =
+ '/api/ws/' +
+ encodeURIComponent(S.wsId) +
+ '/sessions/' +
+ encodeURIComponent(S.sessionId) +
+ '/model';
+ try {
+ const result = await api(url, { method: 'POST', body: { model } });
+ const known = S.transcripts.get(S.sessionId);
+ if (known && result && result.session) {
+ known.model = result.session.model;
+ known.turns = result.session.turns;
+ known.chars = result.session.chars;
+ }
+ updateTalk();
+ const option = modelCatalog().find(
+ (item) => item.providerId === model.providerId && item.modelId === model.modelId,
+ );
+ toast('已切到 ' + ((option && option.displayName) || model.modelId) + ',下一轮生效');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ updateTalk();
+ }
+ }
+
+ function updateTalk() {
+ const head = $('#talk-head');
+ const body = $('#talk-body');
+ const input = $('#talk-input');
+ const form = $('#talk-form');
+ if (!head || !body || !input) return;
+
+ if (!S.sessionId) {
+ head.innerHTML = ``;
+ body.innerHTML = `${icon('chat')}
还没有会话
点左侧任意一节课,她会带着使命和课纲开始备课。
`;
+ input.disabled = true;
+ input.placeholder = '先选一节课';
+ $('#talk-send').disabled = true;
+ return;
+ }
+
+ const session = S.transcripts.get(S.sessionId);
+ const lesson = currentLesson();
+ const isMain = session && session.kind === 'main';
+ const isNote = session && session.kind === 'note';
+ const isSetup = session && session.kind === 'setup';
+ const title = session ? session.title : '会话';
+ const running = session && (session.running || S.live.get(S.sessionId));
+ const catalog = modelCatalog();
+ const currentModel = (session && session.model) || (S.boot.models && S.boot.models.default) || null;
+ const modelOptions =
+ catalog.length && currentModel
+ ? catalog
+ .map((item) => {
+ const value = item.providerId + '|' + item.modelId;
+ const selected =
+ currentModel.providerId === item.providerId && currentModel.modelId === item.modelId;
+ return '';
+ })
+ .join('')
+ : '';
+ const turns = session && typeof session.turns === 'number' ? session.turns : countTurns(session);
+ const chars = session && typeof session.chars === 'number' ? session.chars : countChars(session);
+ head.innerHTML = `
+
+
${esc(title)}
+
${
+ isSetup
+ ? '前置配置 · 只搭环境,不产出课程与课纲'
+ : isMain
+ ? '使命、课纲与全局配置'
+ : isNote
+ ? '独立提炼会话 · 只读课程与批注'
+ : '分支会话 · 只改这一课'
+ }${running ? ' · 正在生成' : ''}
+
+ ${
+ modelOptions
+ ? ''
+ : ''
+ }
+ ${turns} 轮 · 约 ${fmtChars(chars)} 字
+
+
+
+ ${
+ !isSetup && !isMain && !isNote
+ ? ''
+ : ''
+ }
+ `;
+ const pick = head.querySelector('#model-pick');
+ if (pick) {
+ pick.addEventListener('change', () => {
+ const parts = pick.value.split('|');
+ void switchModel({ providerId: parts[0], modelId: parts[1] });
+ });
+ }
+
+ const draft = S.drafts.get(S.sessionId);
+ if (document.activeElement !== input) {
+ input.value = draft || '';
+ autoSize(input);
+ }
+ const hasPending = Boolean(
+ session && (session.pending || (session.permissions || []).length),
+ );
+ const notStarted = Boolean(session && !(session.messages || []).length && !session.running);
+ input.disabled = !session || notStarted;
+ input.placeholder = notStarted
+ ? '先让老师开始'
+ : hasPending
+ ? '先回答上面的问题…'
+ : isSetup
+ ? '和老师讨论你想从这个目录学到什么…'
+ : isMain
+ ? '和主会话讨论使命、课纲或全局设置…'
+ : isNote
+ ? '补充提炼要求,或追问这份笔记…'
+ : lesson
+ ? `追问第 ${lesson.no} 课…`
+ : '追问…';
+ $('#talk-send').disabled =
+ !session || notStarted || S.sending || Boolean(session.running) || hasPending;
+ $('#talk-hint').textContent = S.sending
+ ? '正在发送…'
+ : notStarted
+ ? '这一课还没有开始'
+ : session.running
+ ? '正在生成 · 可随时停止'
+ : hasPending
+ ? '回答上面的问题后继续'
+ : 'Enter 发送 · Shift+Enter 换行';
+ $('#talk-stop').classList.toggle('hidden', !running);
+
+ if (!session) {
+ body.innerHTML = `${icon('chat')}
正在建立会话
稍等一下。
`;
+ return;
+ }
+
+ const stick = body.scrollHeight - body.scrollTop - body.clientHeight < 90;
+ const hadPending = Boolean(body.querySelector('.card-interact'));
+ renderTalkBody(body, session);
+ if (hadPending !== Boolean(body.querySelector('.card-interact')) && body.querySelector('.card-interact')) {
+ const card = body.querySelector('.card-interact');
+ if (card) {
+ const top = card.getBoundingClientRect().top - body.getBoundingClientRect().top + body.scrollTop;
+ body.scrollTop = Math.max(0, top - 10);
+ return;
+ }
+ }
+ if (stick) body.scrollTop = body.scrollHeight;
+ }
+
+ function renderTalkBody(body, session) {
+ const sid = session.id;
+ const parts = [];
+ const messages = session.messages || [];
+
+ if (!messages.length && !S.live.get(sid)) {
+ parts.push(emptyTalkHtml(session));
+ }
+
+ for (const message of messages) {
+ parts.push(messageHtml(message, session.kind));
+ }
+
+ const live = S.live.get(sid);
+ if (live) {
+ parts.push(`
+
${icon('spark')}老师
+
${md(live)}
+
`);
+ } else if (session.running) {
+ parts.push(`
+
${icon('spark')}老师
+
思考中
+
`);
+ }
+
+ const tools = S.tools.get(sid) || [];
+ for (const tool of tools.slice(-3)) {
+ parts.push(
+ `${icon(tool.ok ? 'check' : 'x')}${tool.phase === 'start' ? '调用' : '完成'}${esc(tool.name)}
`,
+ );
+ }
+
+ for (const permission of session.permissions || []) {
+ parts.push(permissionHtml(permission));
+ }
+ if (session.pending) parts.push(pendingHtml(session.pending));
+
+ body.innerHTML = parts.join('');
+ }
+
+ function emptyTalkHtml(session) {
+ if (session.kind === 'setup') {
+ return `${icon('spark')}
还没开始配置
+
老师会看你选的目录,问你三个问题,然后把使命、来源和规则写好。这一轮不产出课程。
+
`;
+ }
+ if (session.kind === 'main') {
+ return `${icon('spark')}
主会话还没开始
+
她会先问你为什么学,再把使命写进 MISSION.md,然后才生成课纲。
+
`;
+ }
+ if (session.kind === 'note') {
+ return `${icon('note')}
准备提炼
+
她正在读课程与批注。完成后笔记会出现在「笔记」里。
`;
+ }
+ return `${icon('spark')}
这一课还没开始
+
点下面的按钮,她会先读使命、课纲和资源清单,再开始备课。
+
`;
+ }
+
+ function messageHtml(message, sessionKind) {
+ if (message.kind === 'seed' || message.kind === 'task' || message.kind === 'rewrite') {
+ const label =
+ message.kind === 'task'
+ ? '已交给主会话:生成课纲'
+ : message.kind === 'rewrite'
+ ? '已让老师整节重写这一课'
+ : sessionKind === 'setup'
+ ? '已把目录与规则交给配置会话'
+ : sessionKind === 'note'
+ ? '已把课程与批注交给提炼会话'
+ : sessionKind === 'main'
+ ? '已把工作台的规则与现状交给主会话'
+ : '已把这一课的上下文交给老师';
+ return `${label}
${esc(
+ message.text,
+ )} `;
+ }
+ if (message.role === 'system') {
+ return ``;
+ }
+ if (message.role === 'user') {
+ return ``;
+ }
+ const clean = String(message.text || '')
+ .replace(/[\s\S]*?<\/deliver-assets>/gi, '')
+ .trim();
+ return `${icon('spark')}老师
${md(
+ clean,
+ )}
`;
+ }
+
+ function permissionHtml(pending) {
+ return `
+
需要授权:${esc(pending.toolName)}
+
${esc(pending.reason || '这次工具调用超出自动授权范围。')}
+
+
+
+
+
`;
+ }
+
+ function pendingHtml(pending) {
+ const request = pending.request || { steps: [] };
+ const plan =
+ request.mode === 'plan' && request.modePayload
+ ? request.modePayload.markdown || request.modePayload.text || ''
+ : '';
+ return `
+
${esc(request.title || '需要你的回答')}
+ ${plan ? `
${esc(plan)}
` : ''}
+ ${(request.steps || [])
+ .map(
+ (step) => `
+
${esc(step.question)}
+
+ ${(step.options || [])
+ .map(
+ (option) => ``,
+ )
+ .join('')}
+
+
+
`,
+ )
+ .join('')}
+
+
+
+
+
`;
+ }
+
+ /* ------------------------------------------------------------- workspace */
+
+ async function selectLesson(lessonId, options) {
+ const opts = options || {};
+ S.lessonId = lessonId;
+ S.center = 'lesson';
+ S.tab = 'lesson';
+ S.centerSig = '';
+ S.talkError = '';
+ localStorage.setItem(`wb.lesson.${S.wsId}`, lessonId);
+ updateCenter();
+ updateRail();
+ if (opts.silent && !S.talkOpen) return;
+ try {
+ const result = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/lessons/${encodeURIComponent(lessonId)}/open`,
+ { method: 'POST', body: { seed: Boolean(opts.seed) } },
+ );
+ if (result && result.sessionId) {
+ await openSession(result.sessionId);
+ } else {
+ updateTalk();
+ }
+ } catch (error) {
+ if (opts.seed && (error.code === 'ANSWER_PENDING' || error.code === 'BUSY')) {
+ // The lesson's session is waiting for an answer or still running: open it
+ // as it stands instead of starting a turn over it.
+ return selectLesson(lessonId, { seed: false });
+ }
+ S.talkError = errorText(error);
+ toast(errorText(error), 'error');
+ updateTalk();
+ }
+ }
+
+ async function openSession(sessionId) {
+ S.sessionId = sessionId;
+ S.unread.delete(sessionId);
+ await loadTranscript(sessionId);
+ updateTalk();
+ updateRail();
+ }
+
+ async function renewLesson() {
+ const lesson = currentLesson();
+ closeModal();
+ if (!lesson) return;
+ try {
+ const result = await api(
+ '/api/ws/' + encodeURIComponent(S.wsId) + '/lessons/' + encodeURIComponent(lesson.id) + '/renew',
+ { method: 'POST', body: {} },
+ );
+ S.boot = await api('/api/bootstrap');
+ S.centerSig = '';
+ await refreshSnapshot();
+ if (result && result.sessionId) {
+ S.talkOpen = true;
+ renderShell(false);
+ await openSession(result.sessionId);
+ }
+ toast('已新开追问,这一课的上下文重新带上');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function regenerateLesson() {
+ const lesson = currentLesson();
+ closeModal();
+ if (!lesson) return;
+ try {
+ const result = await api(
+ '/api/ws/' + encodeURIComponent(S.wsId) + '/lessons/' + encodeURIComponent(lesson.id) + '/regenerate',
+ { method: 'POST', body: {} },
+ );
+ S.talkOpen = true;
+ S.centerSig = '';
+ renderShell(false);
+ if (result && result.sessionId) await openSession(result.sessionId);
+ await refreshSnapshot();
+ toast('正在整节重写这一课');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function loadTranscript(sessionId) {
+ const token = (S.loads.get(sessionId) || 0) + 1;
+ S.loads.set(sessionId, token);
+ try {
+ const data = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(sessionId)}`,
+ );
+ if (S.loads.get(sessionId) !== token) return;
+ S.transcripts.set(sessionId, data);
+ if (!data.running) S.live.delete(sessionId);
+ } catch (error) {
+ if (S.loads.get(sessionId) !== token) return;
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function sendCurrent() {
+ const input = $('#talk-input');
+ if (!input || !S.sessionId || S.sending) return;
+ const text = input.value.trim();
+ if (!text) return;
+ const sid = S.sessionId;
+ S.sending = true;
+ const transcript = S.transcripts.get(sid);
+ if (transcript) {
+ transcript.messages = transcript.messages.concat({
+ id: `tmp_${Date.now()}`,
+ role: 'user',
+ text,
+ at: Date.now(),
+ });
+ }
+ S.drafts.delete(sid);
+ input.value = '';
+ autoSize(input);
+ S.live.delete(sid);
+ updateTalk();
+ $('#talk-send').disabled = true;
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(sid)}/send`, {
+ method: 'POST',
+ body: { text },
+ });
+ if (transcript) transcript.running = true;
+ } catch (error) {
+ toast(errorText(error), 'error');
+ S.drafts.set(sid, text);
+ input.value = text;
+ autoSize(input);
+ } finally {
+ S.sending = false;
+ updateTalk();
+ }
+ }
+
+ async function submitAnswers(skip) {
+ const session = currentSession();
+ if (!session || !session.pending || session.pending.kind !== 'question') return;
+ const pending = session.pending;
+ const body = $('#talk-body');
+ const steps = (pending.request && pending.request.steps) || [];
+ const answers = steps.map((step) => {
+ const inputs = $$(`[data-step="${cssEscape(step.id)}"]`, body).filter((node) => node.checked);
+ const other = $(`[data-other="${cssEscape(step.id)}"]`, body);
+ const otherText = other && other.value.trim();
+ return {
+ stepId: step.id,
+ selectedOptionIds: skip ? [] : inputs.map((node) => node.value),
+ selectedOther: Boolean(otherText),
+ otherText: otherText || undefined,
+ skipped: Boolean(skip),
+ };
+ });
+ try {
+ await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(session.id)}/answer`,
+ { method: 'POST', body: { requestId: pending.requestId, answers } },
+ );
+ session.pending = null;
+ updateTalk();
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function cssEscape(value) {
+ return String(value).replace(/["\\]/g, '\\$&');
+ }
+
+ async function replyPermission(requestId, decision) {
+ const session = currentSession();
+ if (!session) return;
+ try {
+ await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(session.id)}/reply`,
+ { method: 'POST', body: { requestId, decision } },
+ );
+ session.permissions = (session.permissions || []).filter((item) => item.requestId !== requestId);
+ updateTalk();
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function cancelTurn() {
+ const session = currentSession();
+ if (!session) return;
+ try {
+ await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/sessions/${encodeURIComponent(session.id)}/cancel`,
+ { method: 'POST', body: {} },
+ );
+ toast('已请求停止这一轮');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function openMain(options) {
+ void options;
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/main/open`, {
+ method: 'POST',
+ body: {},
+ });
+ if (result && result.sessionId) {
+ S.talkOpen = true;
+ renderShell(false);
+ await openSession(result.sessionId);
+ toast('已打开主会话(右侧栏)');
+ }
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function generateCurriculum() {
+ if (S.snap.workspace.configured === false) {
+ toast('先完成前置配置,再生成课纲');
+ await openSetupSession();
+ return;
+ }
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/curriculum`, {
+ method: 'POST',
+ body: {},
+ });
+ S.talkOpen = true;
+ renderShell(false);
+ if (result && result.sessionId) await openSession(result.sessionId);
+ toast('主会话正在写课纲,完成后课纲会自动出现');
+ } catch (error) {
+ if (error && error.code === 'SETUP_REQUIRED') {
+ toast('先完成前置配置,再生成课纲');
+ await openSetupSession();
+ return;
+ }
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function refreshSnapshot() {
+ if (!S.wsId) return;
+ try {
+ setSnapshot(await api(`/api/ws/${encodeURIComponent(S.wsId)}`));
+ } catch {
+ return;
+ }
+ const bootEntry = ((S.boot && S.boot.workspaces) || []).find((workspace) => workspace.id === S.wsId);
+ if (bootEntry && bootEntry.name !== S.snap.workspace.name) bootEntry.name = S.snap.workspace.name;
+ if (S.lessonId && !findLesson(S.lessonId)) S.lessonId = pickLesson();
+ if ((S.center === 'note' || S.center === 'notes') && !S.snap.notes.length) S.center = 'overview';
+ if (S.center === 'note' && S.noteId && !S.snap.notes.some((note) => note.id === S.noteId)) {
+ S.center = 'notes';
+ }
+ S.centerSig = '';
+ updateTop();
+ updateRail();
+ updateCenter();
+ updateTalk();
+ }
+
+ async function markLesson(status) {
+ if (!S.lessonId) return;
+ try {
+ const result = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/lessons/${encodeURIComponent(S.lessonId)}/status`,
+ { method: 'POST', body: { status } },
+ );
+ if (result && result.snapshot) setSnapshot(result.snapshot);
+ S.centerSig = '';
+ updateRail();
+ updateCenter();
+ toast(status === 'done' ? '已标记完成' : '已标记未完成');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function openNote(noteId) {
+ const note = S.snap.notes.find((item) => item.id === noteId);
+ if (!note) return;
+ if (note.status !== 'ready') {
+ if (note.sessionId) {
+ S.center = 'notes';
+ S.centerSig = '';
+ updateCenter();
+ S.talkOpen = true;
+ renderShell(false);
+ await openSession(note.sessionId);
+ toast(note.status === 'running' ? '这份笔记还在生成,下面是提炼会话' : '这份笔记没写成功,可以在会话里追问');
+ }
+ return;
+ }
+ try {
+ const result = await api(
+ `/api/ws/${encodeURIComponent(S.wsId)}/file?rel=${encodeURIComponent(note.path)}`,
+ );
+ S.noteId = noteId;
+ S.noteText = result.text || '';
+ S.center = 'note';
+ S.centerSig = '';
+ updateCenter();
+ if (note.sessionId) await openSession(note.sessionId);
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* --------------------------------------------------------------- modals */
+
+ function openModal(config) {
+ const root = $('#modal-root');
+ root.innerHTML = `
+
+
${esc(config.title)}
+
+
+
${config.body || ''}
+ ${config.footer ? `` : ''}
+
+
`;
+ if (config.onMount) config.onMount(root);
+ window.setTimeout(() => {
+ const focusable = root.querySelector('input, textarea, button.primary');
+ if (focusable) focusable.focus();
+ }, 40);
+ }
+
+ function closeModal() {
+ $('#modal-root').innerHTML = '';
+ S.picker = null;
+ }
+
+ /* -------------------------------------------------------- directory picker */
+
+ async function openPicker(mode) {
+ const start = (S.boot && S.boot.home) || '';
+ S.picker = {
+ mode,
+ path: start,
+ input: start,
+ error: '',
+ parent: null,
+ entries: [],
+ loading: true,
+ busy: false,
+ };
+ await loadDir(S.picker.path);
+ }
+
+ /** Accept what people actually paste: quotes, file://, trailing slash, spaces. */
+ function normalizePathInput(value) {
+ let text = String(value ?? '').trim();
+ text = text.replace(/^["'`]+/, '').replace(/["'`]+$/, '').trim();
+ text = text.replace(/^file:\/\/\/?/i, '');
+ text = text.replace(/[\\/]+$/, '');
+ if (/^[a-zA-Z]:$/.test(text)) text += '\\';
+ return text;
+ }
+
+ function isAbsolutePath(value) {
+ return /^[a-zA-Z]:[\\/]/.test(value) || /^\\\\/.test(value);
+ }
+
+ async function loadDir(target) {
+ const picker = S.picker;
+ if (!picker) return false;
+ const next = normalizePathInput(target);
+ picker.input = String(target ?? '');
+ if (!isAbsolutePath(next)) {
+ picker.error = '要填完整路径,例如 D:\\代码\\项目名';
+ picker.loading = false;
+ renderPicker();
+ return false;
+ }
+ picker.loading = true;
+ picker.error = '';
+ renderPicker();
+ try {
+ const data = await api(`/api/fs/list?path=${encodeURIComponent(next)}`);
+ picker.path = data.path;
+ picker.parent = data.parent;
+ picker.entries = data.entries;
+ picker.input = data.path;
+ picker.error = '';
+ return true;
+ } catch (error) {
+ // Keep the typed value so a bad paste never silently falls back to the
+ // previously browsed directory.
+ picker.input = String(target ?? '');
+ picker.error =
+ error.code === 'not_a_directory' || error.code === 'path_must_be_absolute'
+ ? '读不到这个目录:确认路径存在、且是一个文件夹'
+ : errorText(error);
+ return false;
+ } finally {
+ picker.loading = false;
+ renderPicker();
+ }
+ }
+
+ function renderPicker() {
+ const picker = S.picker;
+ if (!picker) return;
+ const isCreate = picker.mode === 'create';
+ const typed = normalizePathInput(picker.input || picker.path);
+ const body = `
+
+
+
+
+
+ ${picker.error ? `${esc(picker.error)}
` : ''}
+
+ ${
+ picker.loading
+ ? `
读取中…
`
+ : picker.entries.length
+ ? picker.entries
+ .map(
+ (entry) => `
`,
+ )
+ .join('')
+ : `
这个目录里没有子目录。
`
+ }
+
+ ${
+ isCreate
+ ? `
+
+ 将在
+ ${esc(
+ typed || '(还没选)',
+ )}
+
+
会在这里生成 MISSION.md、RESOURCES.md、GLOSSARY.md、lessons/、reference/、.workbench/ 等结构;已有同名文件不会覆盖。
+
主题、使命和规则不在这里填——创建工作台后会开一个配置会话,老师先问清楚再写,这一轮不产出课程和课纲。
+
`
+ : `选择已经用学习工作台创建过的目录(里面有 .workbench/workspace.json)。
`
+ }`;
+ const footer = isCreate
+ ? `
+ `
+ : `
+ `;
+ openModal({
+ title: isCreate ? '新建学习工作台' : '导入已有学习工作台',
+ body,
+ footer,
+ wide: true,
+ onMount: (root) => {
+ const pathInput = $('#pick-path', root);
+ if (!pathInput) return;
+ pathInput.addEventListener('input', () => {
+ picker.input = pathInput.value;
+ picker.error = '';
+ const line = root.querySelector('.stack .mono');
+ if (line) line.textContent = normalizePathInput(pathInput.value) || '(还没选)';
+ });
+ pathInput.addEventListener('keydown', (event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void loadDir(pathInput.value);
+ }
+ });
+ },
+ });
+ window.setTimeout(() => {
+ const input = $('#pick-path');
+ if (input && document.activeElement !== input) {
+ input.focus();
+ input.setSelectionRange(input.value.length, input.value.length);
+ }
+ }, 30);
+ }
+
+ /** Verify the typed path, then create — never reuse a stale browsed path. */
+ async function resolveTargetPath() {
+ const picker = S.picker;
+ if (!picker) return null;
+ const input = $('#pick-path');
+ const raw = input ? input.value : picker.input;
+ const target = normalizePathInput(raw);
+ if (!isAbsolutePath(target)) {
+ picker.input = String(raw ?? '');
+ picker.error = '要填完整路径,例如 D:\\代码\\项目名';
+ renderPicker();
+ return null;
+ }
+ picker.input = String(raw ?? '');
+ const listing = await api(`/api/fs/list?path=${encodeURIComponent(target)}`);
+ return listing.path;
+ }
+
+ async function submitCreate() {
+ const picker = S.picker;
+ if (!picker) return;
+ picker.busy = true;
+ renderPicker();
+ try {
+ const target = await resolveTargetPath();
+ if (!target) {
+ picker.busy = false;
+ renderPicker();
+ return;
+ }
+ picker.path = target;
+ picker.input = target;
+ const result = await api('/api/workspaces/create', {
+ method: 'POST',
+ body: { parentPath: target },
+ });
+ closeModal();
+ S.boot = await api('/api/bootstrap');
+ S.talkOpen = window.innerWidth > 1120;
+ await openWorkspace(result.workspace.id);
+ toast(result.existing ? '这个目录已经是学习工作台' : '工作台已创建,老师开始配置');
+ } catch (error) {
+ picker.busy = false;
+ picker.error = errorText(error);
+ renderPicker();
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function submitImport() {
+ const picker = S.picker;
+ if (!picker) return;
+ picker.busy = true;
+ renderPicker();
+ try {
+ const target = await resolveTargetPath();
+ if (!target) {
+ picker.busy = false;
+ renderPicker();
+ return;
+ }
+ picker.path = target;
+ picker.input = target;
+ const result = await api('/api/workspaces/import', {
+ method: 'POST',
+ body: { root: target },
+ });
+ closeModal();
+ S.boot = await api('/api/bootstrap');
+ S.talkOpen = window.innerWidth > 1120;
+ await openWorkspace(result.workspace.id);
+ toast('已导入');
+ } catch (error) {
+ picker.busy = false;
+ picker.error = errorText(error);
+ renderPicker();
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* -------------------------------------------------------------- manage */
+
+ const cleanList = () => (S.boot && Array.isArray(S.boot.cleanTargets) ? S.boot.cleanTargets : []);
+ const defaultCleanTargets = () =>
+ new Set(cleanList().filter((row) => row.default).map((row) => row.key));
+
+ function openManage(view, id) {
+ S.manage = {
+ view: view || 'list',
+ id: id || '',
+ targets: defaultCleanTargets(),
+ };
+ renderManage();
+ }
+
+ function renderManage() {
+ const manage = S.manage;
+ if (!manage) return;
+ const workspaces = (S.boot && S.boot.workspaces) || [];
+
+ if (manage.view === 'clean') {
+ const workspace = workspaces.find((item) => item.id === manage.id);
+ if (!workspace) {
+ openManage('list');
+ return;
+ }
+ const rows = cleanList();
+ openModal({
+ title: '清理产物',
+ wide: true,
+ body: `只删下面勾选的路径;目录里的其他文件(源码、docs、datasets 等)不会动。
+ ${esc(workspace.root)}
+
+ ${rows
+ .map(
+ (row) => ``,
+ )
+ .join('')}
+
`,
+ footer: `
+ `,
+ onMount: (root) => {
+ root.querySelectorAll('input[data-clean]').forEach((input) => {
+ input.addEventListener('change', () => {
+ if (input.checked) manage.targets.add(input.dataset.clean);
+ else manage.targets.delete(input.dataset.clean);
+ });
+ });
+ },
+ });
+ return;
+ }
+
+ openModal({
+ title: '工作台管理',
+ wide: true,
+ body: `新增、移除,或清理某个工作台按 teach 规约生成的文件。
+ ${
+ workspaces.length
+ ? workspaces
+ .map(
+ (workspace) => `
+
+
${esc(workspace.name)}${
+ workspace.id === S.wsId ? ' 当前' : ''
+ }
+
${esc(workspace.root)}
+
+ ${
+ workspace.id === S.wsId
+ ? ''
+ : `
`
+ }
+
+
+
`,
+ )
+ .join('')
+ : '还没有工作台。
'
+ }`,
+ footer: `
+
+ `,
+ });
+ }
+
+ async function confirmClean() {
+ const manage = S.manage;
+ if (!manage) return;
+ const targets = Array.from(manage.targets);
+ if (!targets.length) {
+ toast('先勾选要清理的内容');
+ return;
+ }
+ // The clean stops running turns before it deletes, so show the wait.
+ const button = $('[data-act="manage-clean-confirm"]');
+ const label = button ? button.textContent : '';
+ if (button) {
+ button.disabled = true;
+ button.textContent = '清理中…';
+ }
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(manage.id)}/clean`, {
+ method: 'POST',
+ body: { targets },
+ });
+ const wasCurrent = manage.id === S.wsId;
+ S.boot = await api('/api/bootstrap');
+ const count = result.removed ? result.removed.length : 0;
+ const effects = result.effects || {};
+ const notes = effects.notesPruned ? `,笔记索引移除 ${effects.notesPruned} 条` : '';
+ toast(`已清理 ${count} 项${notes}`);
+ if (result.workspaceGone) {
+ closeModal();
+ if (wasCurrent) {
+ const next = (S.boot.workspaces || [])[0];
+ if (next) {
+ await openWorkspace(next.id);
+ } else {
+ S.wsId = null;
+ setSnapshot(null);
+ renderLanding();
+ }
+ }
+ return;
+ }
+ if (wasCurrent) {
+ S.centerSig = '';
+ await refreshSnapshot();
+ }
+ openManage('list');
+ } catch (error) {
+ if (button) {
+ button.disabled = false;
+ button.textContent = label;
+ }
+ toast(errorText(error), 'error');
+ }
+ }
+
+ function confirmRemove(id) {
+ const workspace = ((S.boot && S.boot.workspaces) || []).find((item) => item.id === id);
+ if (!workspace) return;
+ openModal({
+ title: '移除工作台',
+ body: `把「${esc(workspace.name)}」从列表移除。磁盘上的文件不会删除,之后可以再导入。
+ ${esc(workspace.root)}
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function doRemove(id) {
+ try {
+ await api('/api/workspaces/forget', { method: 'POST', body: { id } });
+ closeModal();
+ S.boot = await api('/api/bootstrap');
+ if (id === S.wsId) {
+ const next = (S.boot.workspaces || [])[0];
+ if (next) {
+ await openWorkspace(next.id);
+ } else {
+ S.wsId = null;
+ setSnapshot(null);
+ renderLanding();
+ }
+ } else {
+ toast('已从列表移除');
+ }
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ------------------------------------------------------------- annotate */
+
+ function openAnnotate(options) {
+ const opts = options || {};
+ S.pendingQuote = opts.quote || '';
+ S.pendingAnnoId = opts.id || '';
+ const existing = opts.id ? S.snap.annotations.find((item) => item.id === opts.id) : null;
+ openModal({
+ title: existing ? '编辑批注' : '添加批注',
+ body: `
+ ${opts.quote ? `${esc(opts.quote)}
` : ''}
+
+ ${
+ opts.quote ? '批注会挂在这句话上,并在这节课里高亮。' : '整节批注会挂在这一课上。'
+ } 提炼笔记时会被一起带上。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function saveAnnotation() {
+ const input = $('#anno-note');
+ const note = input ? input.value.trim() : '';
+ if (!note) {
+ toast('写点什么再保存');
+ return;
+ }
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/annotations`, {
+ method: 'POST',
+ body: {
+ action: S.pendingAnnoId ? 'update' : 'create',
+ id: S.pendingAnnoId || undefined,
+ lessonId: S.lessonId,
+ quote: S.pendingQuote,
+ note,
+ },
+ });
+ closeModal();
+ await refreshSnapshot();
+ S.tab = 'anno';
+ S.centerSig = '';
+ updateCenter();
+ toast('已保存批注');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ async function deleteAnnotation(id) {
+ openModal({
+ title: '删除批注',
+ body: `删除后无法恢复。这节课的笔记如果已经生成,不受影响。
`,
+ footer: `
+ `,
+ });
+ }
+
+ async function confirmDeleteAnnotation(id) {
+ try {
+ await api(`/api/ws/${encodeURIComponent(S.wsId)}/annotations`, {
+ method: 'POST',
+ body: { action: 'delete', id },
+ });
+ closeModal();
+ await refreshSnapshot();
+ S.centerSig = '';
+ updateCenter();
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ---------------------------------------------------------------- notes */
+
+ function openNotesPicker() {
+ const lessons = lessonsOf().filter((lesson) => lessonHasFile(lesson));
+ if (!lessons.length) {
+ toast('还没有生成任何课程文件');
+ return;
+ }
+ const state = {
+ selected: new Set(lessons.map((lesson) => lesson.id)),
+ title: '',
+ titleTouched: false,
+ };
+ const render = () => {
+ const selectedLessons = lessons.filter((lesson) => state.selected.has(lesson.id));
+ const annotationCount = S.snap.annotations.filter((item) => state.selected.has(item.lessonId)).length;
+ if (!state.titleTouched) {
+ state.title = `${lessonNumberList(Array.from(state.selected))}笔记`;
+ }
+ const body = `
+ 范围
+ ${
+ S.snap.curriculum.modules
+ .map((module) => {
+ const rows = module.lessons.filter((lesson) => lessonHasFile(lesson));
+ if (!rows.length) return '';
+ return `
+
${esc(module.title)}
+ ${rows
+ .map((lesson) => {
+ const count = annotationsOf(lesson.id).length;
+ return `
`;
+ })
+ .join('')}
+
`;
+ })
+ .join('')
+ }
+ 笔记标题
+
+ 会带上你选中的 ${
+ selectedLessons.length
+ } 节课的课程内容与 ${annotationCount} 条批注,在独立会话里写成 notes/*.md。
`;
+ openModal({
+ title: '提炼笔记',
+ body,
+ footer: `
+ `,
+ wide: true,
+ onMount: (root) => {
+ root.querySelectorAll('input[data-lesson]').forEach((input) => {
+ input.addEventListener('change', () => {
+ if (input.checked) state.selected.add(input.dataset.lesson);
+ else state.selected.delete(input.dataset.lesson);
+ render();
+ });
+ });
+ const title = $('#note-title', root);
+ if (title) {
+ title.addEventListener('input', () => {
+ state.title = title.value;
+ state.titleTouched = true;
+ });
+ }
+ },
+ });
+ S.notePick = state;
+ };
+ render();
+ }
+
+ async function startNote() {
+ const state = S.notePick;
+ if (!state) return;
+ const lessonIds = Array.from(state.selected);
+ if (!lessonIds.length) return;
+ const title = (state.title || '').trim() || `${lessonNumberList(lessonIds)}笔记`;
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/notes`, {
+ method: 'POST',
+ body: { lessonIds, title },
+ });
+ closeModal();
+ S.center = 'notes';
+ S.centerSig = '';
+ S.talkOpen = true;
+ renderShell(false);
+ await refreshSnapshot();
+ if (result && result.sessionId) await openSession(result.sessionId);
+ toast('已开一个独立会话提炼笔记');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ---------------------------------------------------------------- rules */
+
+ async function showRules() {
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/rules`);
+ openModal({
+ title: '教学规则 · teach.md',
+ wide: true,
+ body: `${esc(result.path || '')}
+ ${esc(
+ result.text || '',
+ )}`,
+ footer: ``,
+ });
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ }
+
+ /* ---------------------------------------------------------------- events */
+
+ function handleEvent(event) {
+ let message = null;
+ try {
+ message = JSON.parse(event.data);
+ } catch {
+ return;
+ }
+ if (!message || (message.wsId && message.wsId !== S.wsId)) return;
+
+ if (message.t === 'delta') {
+ const sid = message.sessionId;
+ const next = (S.live.get(sid) || '') + (message.text || '');
+ S.live.set(sid, next);
+ if (sid === S.sessionId) {
+ const body = $('#talk-body');
+ const live = $('#live-text');
+ if (body && live) {
+ const stick = body.scrollHeight - body.scrollTop - body.clientHeight < 90;
+ live.innerHTML = md(next);
+ if (stick) body.scrollTop = body.scrollHeight;
+ } else {
+ updateTalk();
+ }
+ }
+ return;
+ }
+
+ if (message.t === 'session') {
+ const sid = message.sessionId;
+ const session = message.session;
+ if (!session) return;
+ if (!session.running) {
+ S.live.delete(sid);
+ }
+ const known = S.transcripts.get(sid);
+ if (known) {
+ known.running = session.running;
+ known.pending = session.pending;
+ known.permissions = session.permissions || [];
+ known.title = session.title;
+ }
+ if (sid === S.sessionId) {
+ void loadTranscript(sid).then(() => {
+ S.tools.delete(sid);
+ updateTalk();
+ });
+ } else if (session.messageCount > ((known && known.messages.length) || 0)) {
+ S.unread.add(sid);
+ updateRail();
+ }
+ return;
+ }
+
+ if (message.t === 'tool') {
+ if (message.phase !== 'end') return;
+ const sid = message.sessionId;
+ const list = S.tools.get(sid) || [];
+ list.push({ name: message.name, phase: message.phase, ok: message.ok });
+ S.tools.set(sid, list.slice(-6));
+ if (sid === S.sessionId) {
+ const body = $('#talk-body');
+ if (body) {
+ const stick = body.scrollHeight - body.scrollTop - body.clientHeight < 90;
+ renderTalkBody(body, S.transcripts.get(sid) || { id: sid, messages: [] });
+ if (stick) body.scrollTop = body.scrollHeight;
+ }
+ }
+ return;
+ }
+
+ if (message.t === 'state' || message.t === 'annotations') {
+ window.clearTimeout(handleEvent.timer);
+ handleEvent.timer = window.setTimeout(() => {
+ void refreshSnapshot();
+ }, 250);
+ }
+ }
+
+ let reconnectCount = 0;
+ function connectEvents() {
+ if (S.es) {
+ S.es.close();
+ S.es = null;
+ }
+ if (!S.wsId) return;
+ try {
+ const es = new EventSource('/api/events');
+ es.onmessage = handleEvent;
+ es.onopen = () => {
+ reconnectCount += 1;
+ if (reconnectCount > 1) void refreshSnapshot();
+ };
+ es.onerror = () => {
+ /* EventSource reconnects on its own */
+ };
+ S.es = es;
+ } catch {
+ /* ignore */
+ }
+ }
+
+ /* --------------------------------------------------------------- bridge */
+
+ /** Resolve a lesson link against the lesson's own path; '' when it leaves the workspace. */
+ function resolveDocRel(lessonRel, href) {
+ const raw = String(href || '').trim();
+ if (!raw || raw.startsWith('#') || raw.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(raw)) return '';
+ const clean = raw.split('#')[0].split('?')[0];
+ if (!clean) return '';
+ let decoded = clean;
+ try {
+ decoded = decodeURIComponent(clean);
+ } catch {
+ /* keep the raw value */
+ }
+ const out = [];
+ for (const part of String(lessonRel || '').split('/').slice(0, -1).concat(decoded.split('/'))) {
+ if (!part || part === '.') continue;
+ if (part === '..') {
+ if (!out.length) return '';
+ out.pop();
+ continue;
+ }
+ out.push(part);
+ }
+ return out.join('/');
+ }
+
+ /** "main.py:46–48" → {line:46,end:48}; ":1807" → {line:1807,end:1807}. */
+ function parseLineRef(text) {
+ const match = String(text || '').match(/:(\d+)(?:\s*[–—-]\s*(\d+))?/);
+ if (!match) return { line: 0, end: 0 };
+ const line = Number(match[1]) || 0;
+ const end = Number(match[2]) || line;
+ return { line, end: Math.max(line, end) };
+ }
+
+ function openWorkspacePage(rel) {
+ const frame = $('#lesson-frame');
+ if (!frame) return;
+ frame.src = `/w/${encodeURIComponent(S.wsId)}/${rel.split('/').map(encodeURIComponent).join('/')}`;
+ }
+
+ async function openCodePanel(data) {
+ const lessonRel = data.rel || (currentLesson() || {}).file || '';
+ const rel = resolveDocRel(lessonRel, data.href);
+ if (!rel) {
+ toast('这个链接不在工作台里,暂时打不开');
+ return;
+ }
+ // A link to another lesson or a reference page is page navigation, not a
+ // code view: switch lessons for a lesson page, otherwise load the page into
+ // the lesson frame.
+ const target = lessonByFile(rel);
+ if (target) {
+ await selectLesson(target.id, { seed: false });
+ return;
+ }
+ if ((S.snap.lessonFiles || []).includes(rel) || (S.snap.referenceFiles || []).includes(rel)) {
+ openWorkspacePage(rel);
+ return;
+ }
+ const range = parseLineRef(data.text);
+ let payload;
+ try {
+ payload = await api(`/api/ws/${encodeURIComponent(S.wsId)}/file?rel=${encodeURIComponent(rel)}`);
+ } catch (error) {
+ toast(errorText(error), 'error');
+ return;
+ }
+ const lines = String(payload.text || '').replace(/\r\n/g, '\n').split('\n');
+ const start = range.line ? Math.min(range.line, lines.length) : 0;
+ const end = start ? Math.min(range.end || start, lines.length) : 0;
+ const rows = lines
+ .map((code, index) => {
+ const no = index + 1;
+ const hit = start && no >= start && no <= end ? ' hit' : '';
+ return `${no}${esc(code) || ' '}
`;
+ })
+ .join('');
+ const label = start ? `${rel}:${start}${end > start ? `–${end}` : ''}` : rel;
+ openModal({
+ title: label,
+ wide: true,
+ body: `${rows}
`,
+ footer: `共 ${lines.length} 行
`,
+ onMount: (root) => {
+ const view = root.querySelector('.file-view');
+ const hit = view ? view.querySelector('.file-row.hit') : null;
+ if (view && hit) view.scrollTop = Math.max(0, hit.offsetTop - view.clientHeight / 3);
+ },
+ });
+ }
+
+ window.addEventListener('message', (event) => {
+ const frame = $('#lesson-frame');
+ if (!frame || event.source !== frame.contentWindow) return;
+ const data = event.data;
+ if (!data || data.source !== 'wb') return;
+ if (data.type === 'file' && data.href) {
+ void openCodePanel(data);
+ return;
+ }
+ if (data.type === 'annotate' && data.quote) {
+ openAnnotate({ quote: data.quote });
+ }
+ if (data.type === 'ask' && data.quote) {
+ const quote = String(data.quote).slice(0, 300);
+ const prefix = '关于「' + quote + '」:';
+ const apply = () => {
+ if (!S.sessionId) return;
+ S.talkOpen = true;
+ renderShell(false);
+ S.drafts.set(S.sessionId, prefix);
+ const input = $('#talk-input');
+ if (!input) return;
+ input.value = prefix;
+ input.focus();
+ input.setSelectionRange(prefix.length, prefix.length);
+ autoSize(input);
+ };
+ if (S.sessionId) {
+ apply();
+ return;
+ }
+ // Reading a lesson without its branch session open: open it, then prefill.
+ const lessonId = pickLesson();
+ if (!lessonId) return;
+ void selectLesson(lessonId, { seed: false }).then(apply).catch(() => {});
+ }
+ if (data.type === 'open' && data.id) {
+ S.tab = 'anno';
+ S.centerSig = '';
+ updateCenter();
+ window.setTimeout(() => {
+ const node = $(`#anno-${CSS.escape(data.id)}`);
+ if (node) {
+ node.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ node.classList.add('flash');
+ window.setTimeout(() => node.classList.remove('flash'), 1800);
+ }
+ }, 60);
+ }
+ if (data.type === 'ready') {
+ frame.contentWindow.postMessage(
+ {
+ source: 'host',
+ type: 'theme',
+ theme: document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light',
+ },
+ '*',
+ );
+ }
+ });
+
+ /* -------------------------------------------------------------- handlers */
+
+ const ACTIONS = {
+ 'close-modal': () => closeModal(),
+ 'modal-backdrop': (node, event) => {
+ if (event.target === node) closeModal();
+ },
+ 'open-picker': (node) => openPicker(node.dataset.mode || 'create'),
+ 'picker-up': () => {
+ if (S.picker && S.picker.parent) void loadDir(S.picker.parent);
+ },
+ 'picker-enter': (node) => {
+ if (node.dataset.path) void loadDir(node.dataset.path);
+ },
+ 'picker-go': () => {
+ const input = $('#pick-path');
+ void loadDir(input ? input.value : S.picker && S.picker.input);
+ },
+ 'create-ws': () => void submitCreate(),
+ 'import-ws': () => void submitImport(),
+ 'open-ws': (node) => void openWorkspace(node.dataset.id),
+ 'manage-ws': () => openManage('list'),
+ 'manage-open': (node) => {
+ closeModal();
+ S.talkOpen = window.innerWidth > 1120;
+ void openWorkspace(node.dataset.id);
+ },
+ 'manage-clean': (node) => {
+ S.manage.view = 'clean';
+ S.manage.id = node.dataset.id;
+ S.manage.targets = defaultCleanTargets();
+ renderManage();
+ },
+ 'manage-back': () => {
+ S.manage.view = 'list';
+ renderManage();
+ },
+ 'manage-clean-confirm': () => void confirmClean(),
+ 'manage-remove': (node) => confirmRemove(node.dataset.id),
+ 'manage-remove-confirm': (node) => void doRemove(node.dataset.id),
+ 'open-lesson': (node) => void selectLesson(node.dataset.id, { seed: true }),
+ 'renew-lesson': () => {
+ const lesson = currentLesson();
+ if (!lesson) return;
+ openModal({
+ title: '新开追问',
+ body: '会为「第 ' + lesson.no + ' 课」新建一个分支会话:带上这一课的上下文与上一轮的结论。旧会话记录保留,课件不会被改写。
',
+ footer: '' +
+ '',
+ });
+ },
+ 'renew-lesson-confirm': () => void renewLesson(),
+ 'regenerate-lesson': () => {
+ const lesson = currentLesson();
+ if (!lesson) return;
+ openModal({
+ title: '重新生成这一课',
+ body:
+ '会按课纲把「第 ' +
+ lesson.no +
+ ' 课」整节重写,覆盖 ' +
+ esc(lesson.file || '本课文件') +
+ '。课件内容会被替换,批注、笔记与学习记录保留。
',
+ footer:
+ '' +
+ '',
+ });
+ },
+ 'regenerate-lesson-confirm': () => void regenerateLesson(),
+ 'open-main': () => void openMain(),
+ 'open-setup': () => void openSetupSession(),
+ 'open-overview': () => {
+ S.center = 'overview';
+ S.centerSig = '';
+ updateTop();
+ updateCenter();
+ },
+ 'open-notes': () => {
+ S.center = 'notes';
+ S.noteId = null;
+ S.centerSig = '';
+ updateTop();
+ updateCenter();
+ },
+ 'open-note': (node) => void openNote(node.dataset.id),
+ tab: (node) => {
+ S.tab = node.dataset.tab === 'anno' ? 'anno' : 'lesson';
+ S.centerSig = '';
+ updateCenter();
+ },
+ 'toggle-talk': () => {
+ S.talkOpen = !S.talkOpen;
+ renderShell(false);
+ },
+ 'mark-lesson': (node) => void markLesson(node.dataset.status),
+ 'start-lesson': () => {
+ if (S.lessonId) void selectLesson(S.lessonId, { seed: true });
+ },
+ 'start-main': () => void openMain({ seed: true }),
+ 'generate-curriculum': () => void generateCurriculum(),
+ 'refresh-ws': () => {
+ void (async () => {
+ try {
+ const result = await api(`/api/ws/${encodeURIComponent(S.wsId)}/refresh`, {
+ method: 'POST',
+ body: {},
+ });
+ if (result && result.snapshot) setSnapshot(result.snapshot);
+ S.centerSig = '';
+ updateTop();
+ updateRail();
+ updateCenter();
+ toast(result && result.error ? `课纲解析失败:${result.error}` : '已重新读取');
+ } catch (error) {
+ toast(errorText(error), 'error');
+ }
+ })();
+ },
+ 'annotate-lesson': () => openAnnotate({ quote: '' }),
+ 'edit-anno': (node) => {
+ const item = S.snap.annotations.find((entry) => entry.id === node.dataset.id);
+ if (item) openAnnotate({ quote: item.quote, id: item.id });
+ },
+ 'delete-anno': (node) => void deleteAnnotation(node.dataset.id),
+ 'confirm-delete-anno': (node) => void confirmDeleteAnnotation(node.dataset.id),
+ 'save-anno': () => void saveAnnotation(),
+ 'permission-allow': (node) => void replyPermission(node.dataset.request, 'allowOnce'),
+ 'permission-deny': (node) => void replyPermission(node.dataset.request, 'deny'),
+ 'answer-question': () => void submitAnswers(false),
+ 'skip-question': () => void submitAnswers(true),
+ 'cancel-turn': () => void cancelTurn(),
+ 'open-notes-picker': () => openNotesPicker(),
+ 'start-note': () => void startNote(),
+ 'show-rules': () => void showRules(),
+ 'show-mission': () =>
+ openModal({
+ title: '使命 · MISSION.md',
+ wide: true,
+ body: `${md((S.snap && S.snap.mission) || '')}
`,
+ footer: ``,
+ }),
+ 'copy-path': () => {
+ const root = S.snap && S.snap.workspace.root;
+ if (!root) return;
+ navigator.clipboard
+ .writeText(root)
+ .then(() => toast('路径已复制'))
+ .catch(() => toast('复制失败', 'error'));
+ },
+ };
+
+ document.addEventListener('click', (event) => {
+ const node = event.target.closest ? event.target.closest('[data-act]') : null;
+ if (!node) return;
+ // The modal backdrop is an ancestor of everything in the dialog. Clicks on
+ // inputs, checkboxes and links inside it must keep their default behaviour.
+ if (node.dataset.act === 'modal-backdrop' && event.target !== node) return;
+ const action = ACTIONS[node.dataset.act];
+ if (!action) return;
+ event.preventDefault();
+ action(node, event);
+ });
+
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape' && $('#modal-root').children.length) closeModal();
+ });
+
+ /* ------------------------------------------------------------------ boot */
+
+ async function boot() {
+ initTheme();
+ try {
+ S.boot = await api('/api/bootstrap');
+ } catch (error) {
+ $('#app').innerHTML = `
+
无法连接学习工作台
+
${esc(errorText(error))}
+
+
`;
+ return;
+ }
+ // A path-vocabulary drift is a code problem: say it here instead of leaving
+ // the startup check in a log nobody reads.
+ const pathIssues = (S.boot && S.boot.diagnostics && S.boot.diagnostics.pathVocabulary) || [];
+ if (pathIssues.length) {
+ console.warn('[check-paths]', pathIssues);
+ toast(`路径检查发现 ${pathIssues.length} 处问题,详见控制台`, 'error');
+ }
+ S.talkOpen = window.innerWidth > 1120;
+ const list = S.boot.workspaces || [];
+ if (!list.length) {
+ renderLanding();
+ return;
+ }
+ const last = localStorage.getItem('wb.last');
+ const target = list.find((workspace) => workspace.id === last) || list[0];
+ await openWorkspace(target.id);
+ }
+
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') {
+ const input = $('#talk-input');
+ if (input && S.sessionId) S.drafts.set(S.sessionId, input.value);
+ }
+ if (document.visibilityState === 'visible' && S.wsId) {
+ void refreshSnapshot();
+ }
+ });
+
+ void boot();
+})();
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/index.html b/plugins/meisijiya/learn-workbench/miniapp/client/index.html
new file mode 100644
index 00000000..11baf5ad
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/index.html
@@ -0,0 +1,15 @@
+
+
+
+
+
+ 学习工作台
+
+
+
+
+
+
+
+
+
diff --git a/plugins/meisijiya/learn-workbench/miniapp/client/lesson-bridge.js b/plugins/meisijiya/learn-workbench/miniapp/client/lesson-bridge.js
new file mode 100644
index 00000000..6ab80893
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/client/lesson-bridge.js
@@ -0,0 +1,395 @@
+(function () {
+ 'use strict';
+
+ const cfg = window.__WB__ || { annotations: [] };
+ const source = 'wb';
+
+ /* ------------------------------------------------------------ highlight */
+
+ const style = document.createElement('style');
+ style.textContent = `
+ mark.wb-hl {
+ background: color-mix(in srgb, #f59e0b 26%, transparent);
+ border-bottom: 1px solid color-mix(in srgb, #f59e0b 70%, transparent);
+ border-radius: 2px;
+ padding: 0 1px;
+ cursor: pointer;
+ color: inherit;
+ }
+ mark.wb-hl:hover { background: color-mix(in srgb, #f59e0b 40%, transparent); }
+ `;
+ document.head.appendChild(style);
+
+ function normalize(value) {
+ return String(value || '').replace(/\s+/g, ' ').trim();
+ }
+
+ // Quotes may cross / inside one block, so highlight per block
+ // instead of per text node.
+ const BLOCK_SELECTOR =
+ 'p, li, h1, h2, h3, h4, h5, h6, blockquote, td, th, dd, dt, figcaption, caption, pre';
+
+ function textNodesIn(root) {
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
+ acceptNode(node) {
+ const parent = node.parentElement;
+ if (!parent) return NodeFilter.FILTER_REJECT;
+ const tag = parent.tagName;
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'MARK' || tag === 'NOSCRIPT') {
+ return NodeFilter.FILTER_REJECT;
+ }
+ if (!node.nodeValue || !node.nodeValue.trim()) return NodeFilter.FILTER_REJECT;
+ return NodeFilter.FILTER_ACCEPT;
+ },
+ });
+ const nodes = [];
+ let current = walker.nextNode();
+ while (current) {
+ nodes.push(current);
+ current = walker.nextNode();
+ }
+ return nodes;
+ }
+
+ /** Concatenate a block's text and remember where each character came from. */
+ function buildIndex(nodes) {
+ let text = '';
+ const map = [];
+ for (const node of nodes) {
+ const value = node.nodeValue;
+ for (let i = 0; i < value.length; i += 1) {
+ const char = value[i];
+ if (/\s/.test(char)) {
+ if (text.endsWith(' ')) continue;
+ map.push({ node, offset: i });
+ text += ' ';
+ } else {
+ map.push({ node, offset: i });
+ text += char;
+ }
+ }
+ }
+ return { text, map };
+ }
+
+ function markFor(annotation) {
+ const mark = document.createElement('mark');
+ mark.className = 'wb-hl';
+ mark.dataset.wb = annotation.id;
+ mark.title = annotation.note ? String(annotation.note).slice(0, 200) : '查看批注';
+ return mark;
+ }
+
+ function wrapNode(node, start, end, annotation) {
+ if (start >= end) return false;
+ try {
+ const range = document.createRange();
+ range.setStart(node, start);
+ range.setEnd(node, end);
+ range.surroundContents(markFor(annotation));
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ function locate(index, target) {
+ if (target.length < 2) return null;
+ let at = index.text.indexOf(target);
+ let length = target.length;
+ if (at < 0 && target.length > 12) {
+ const head = target.slice(0, 12);
+ at = index.text.indexOf(head);
+ length = head.length;
+ }
+ if (at < 0) return null;
+ const start = index.map[at];
+ const end = index.map[Math.min(index.map.length - 1, at + length - 1)];
+ if (!start || !end) return null;
+ return { start, end, at, length };
+ }
+
+ function highlightIn(block, quote, annotation) {
+ const nodes = textNodesIn(block);
+ if (!nodes.length) return false;
+ const found = locate(buildIndex(nodes), normalize(quote));
+ if (!found) return false;
+ const { start, end } = found;
+
+ const range = document.createRange();
+ range.setStart(start.node, start.offset);
+ range.setEnd(end.node, end.offset + 1);
+ try {
+ range.surroundContents(markFor(annotation));
+ return true;
+ } catch {
+ /* The range crosses element boundaries; wrap each covered text node. */
+ }
+
+ const from = nodes.indexOf(start.node);
+ const to = nodes.indexOf(end.node);
+ if (from < 0 || to < from) return false;
+ let touched = false;
+ for (let i = from; i <= to; i += 1) {
+ const node = nodes[i];
+ const startOffset = node === start.node ? start.offset : 0;
+ const endOffset = node === end.node ? end.offset + 1 : node.nodeValue.length;
+ touched = wrapNode(node, startOffset, endOffset, annotation) || touched;
+ }
+ return touched;
+ }
+
+ /** Plain text inside a block-less container: only wrap within one text node. */
+ function highlightSingleNode(quote, annotation) {
+ const target = normalize(quote);
+ if (target.length < 2) return false;
+ for (const node of textNodesIn(document.body)) {
+ const flat = normalize(node.nodeValue);
+ if (flat.length < target.length) continue;
+ let at = flat.indexOf(target);
+ let length = target.length;
+ if (at < 0 && target.length > 12) {
+ at = flat.indexOf(target.slice(0, 12));
+ length = Math.min(12, target.length);
+ }
+ if (at < 0) continue;
+ // Map the normalized index back onto this node's raw text.
+ let rawStart = -1;
+ let seen = 0;
+ let cursor = 0;
+ while (cursor < node.nodeValue.length) {
+ const char = node.nodeValue[cursor];
+ if (/\s/.test(char)) {
+ if (seen > 0) {
+ let lookahead = cursor;
+ while (lookahead < node.nodeValue.length && /\s/.test(node.nodeValue[lookahead])) lookahead += 1;
+ if (lookahead < node.nodeValue.length && seen === at) {
+ rawStart = lookahead;
+ break;
+ }
+ cursor = lookahead;
+ continue;
+ }
+ cursor += 1;
+ continue;
+ }
+ if (seen === at) {
+ rawStart = cursor;
+ break;
+ }
+ seen += 1;
+ cursor += 1;
+ }
+ if (rawStart < 0) return false;
+ let rawEnd = rawStart;
+ let counted = 0;
+ while (rawEnd < node.nodeValue.length && counted < length) {
+ const char = node.nodeValue[rawEnd];
+ if (!/\s/.test(char) || !/\s/.test(node.nodeValue[rawEnd - 1] || '')) counted += 1;
+ rawEnd += 1;
+ }
+ return wrapNode(node, rawStart, rawEnd, annotation);
+ }
+ return false;
+ }
+
+ function applyHighlights() {
+ for (const annotation of cfg.annotations || []) {
+ if (document.querySelector(`mark.wb-hl[data-wb="${annotation.id}"]`)) continue;
+ let done = false;
+ for (const block of document.body.querySelectorAll(BLOCK_SELECTOR)) {
+ if (highlightIn(block, annotation.quote, annotation)) {
+ done = true;
+ break;
+ }
+ }
+ if (!done) highlightSingleNode(annotation.quote, annotation);
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', applyHighlights, { once: true });
+ } else {
+ applyHighlights();
+ }
+
+ /* --------------------------------------------------------------- bubble */
+
+ const host = document.createElement('div');
+ host.style.cssText = 'position:fixed;z-index:2147483647;top:0;left:0;';
+ document.body.appendChild(host);
+ const shadow = host.attachShadow({ mode: 'open' });
+ shadow.innerHTML = `
+
+
+ 添加批注
+
+
+
+ `;
+ const bubble = shadow.querySelector('.bubble');
+ const bubbleText = shadow.querySelector('.txt');
+ let pendingQuote = '';
+
+ function hideBubble() {
+ bubble.classList.remove('show');
+ pendingQuote = '';
+ }
+
+ function showBubble(quote, rect) {
+ pendingQuote = quote;
+ bubbleText.textContent = quote.length > 18 ? `${quote.slice(0, 18)}…` : quote;
+ bubble.style.left = `${Math.max(80, Math.min(window.innerWidth - 80, rect.left + rect.width / 2))}px`;
+ bubble.style.top = `${Math.max(40, rect.top - 6)}px`;
+ bubble.classList.add('show');
+ }
+
+ shadow.querySelectorAll('button').forEach((button) => {
+ button.addEventListener('click', (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!pendingQuote) return;
+ const kind = button.dataset.act === 'ask' ? 'ask' : 'annotate';
+ parent.postMessage({ source, type: kind, quote: pendingQuote }, '*');
+ hideBubble();
+ const selection = window.getSelection();
+ if (selection) selection.removeAllRanges();
+ });
+ });
+
+ document.addEventListener('mouseup', (event) => {
+ if (event.target && event.target.closest && event.target.closest('mark.wb-hl')) return;
+ window.setTimeout(() => {
+ const selection = window.getSelection();
+ const quote = selection ? normalize(selection.toString()) : '';
+ if (!quote || quote.length < 2) {
+ hideBubble();
+ return;
+ }
+ const range = selection.getRangeAt(0);
+ const rect = range.getBoundingClientRect();
+ if (!rect || (!rect.width && !rect.height)) return;
+ showBubble(quote.slice(0, 400), rect);
+ }, 10);
+ });
+
+ document.addEventListener('mousedown', (event) => {
+ // The bubble lives in a shadow root, so event.target arrives retargeted to
+ // the host. composedPath() is the only reliable way to tell a click on the
+ // bubble from a click on the lesson text; getting this wrong clears the
+ // pending quote before the button's click handler reads it.
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
+ if (path.includes(bubble) || path.includes(host) || bubble.contains(event.target)) return;
+ hideBubble();
+ });
+
+ document.addEventListener('scroll', hideBubble, true);
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape') hideBubble();
+ });
+
+ document.addEventListener(
+ 'click',
+ (event) => {
+ const link = event.target && event.target.closest ? event.target.closest('a[href]') : null;
+ if (!link) return;
+ const href = link.getAttribute('href') || '';
+ if (!href || href.startsWith('#') || href.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(href)) return;
+ // The lesson page cannot reach the workspace API (connect-src 'none'); the
+ // host opens the file panel on the lesson's behalf.
+ event.preventDefault();
+ parent.postMessage(
+ { source, type: 'file', href, text: normalize(link.textContent || ''), rel: cfg.rel || '' },
+ '*',
+ );
+ },
+ true,
+ );
+
+ document.addEventListener('click', (event) => {
+ const mark = event.target && event.target.closest ? event.target.closest('mark.wb-hl') : null;
+ if (!mark) return;
+ event.preventDefault();
+ parent.postMessage({ source, type: 'open', id: mark.dataset.wb }, '*');
+ });
+
+ /* ------------------------------------------------------------- lifecycle */
+
+ parent.postMessage({ source, type: 'ready', rel: cfg.rel || '' }, '*');
+
+ /* ------------------------------------------------------------- theme sync */
+
+ const LIGHT_VARS =
+ ':root{--ink:#1c1b19;--muted:#6b6a66;--line:#0a0a0a14;--paper:#fbfaf7;--surface:#ffffff;' +
+ '--accent:#0b6bcb;--ok:#0f7a3d;--bad:#b42318;--warn:#b45309;--code:#f2f0eb}' +
+ 'html{background:#fbfaf7;color-scheme:light}';
+ const DARK_VARS =
+ ':root{--ink:#ece9e2;--muted:#a09d95;--line:#ffffff1f;--paper:#1e1d1b;--surface:#26251f;' +
+ '--accent:#7db4ff;--ok:#6ee7a8;--bad:#ff9a8f;--warn:#ffc46b;--code:#2b2a24}' +
+ 'html{background:#1e1d1b;color-scheme:dark}';
+
+ let themeStyle = null;
+ function applyHostTheme(theme) {
+ const systemDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ const wantDark = theme === 'dark';
+ const needsOverride = wantDark !== Boolean(systemDark);
+ if (!themeStyle) {
+ themeStyle = document.createElement('style');
+ themeStyle.id = 'wb-theme';
+ document.head.appendChild(themeStyle);
+ }
+ themeStyle.textContent = needsOverride ? (wantDark ? DARK_VARS : LIGHT_VARS) : '';
+ document.documentElement.dataset.wbTheme = wantDark ? 'dark' : 'light';
+ }
+
+ window.addEventListener('message', (event) => {
+ const data = event.data;
+ if (!data || data.source !== 'host') return;
+ if (data.type === 'theme') {
+ applyHostTheme(data.theme);
+ return;
+ }
+ if (data.type === 'focus') {
+ const mark = document.querySelector(`mark.wb-hl[data-wb="${data.id}"]`);
+ if (mark) {
+ mark.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ mark.style.outline = '2px solid #f59e0b';
+ window.setTimeout(() => {
+ mark.style.outline = '';
+ }, 1600);
+ }
+ }
+ });
+})();
diff --git a/plugins/meisijiya/learn-workbench/miniapp/miniapp.json b/plugins/meisijiya/learn-workbench/miniapp/miniapp.json
new file mode 100644
index 00000000..80efd86e
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/miniapp.json
@@ -0,0 +1,32 @@
+{
+ "schemaVersion": 1,
+ "artifacts": {
+ "client": [
+ "./miniapp/client"
+ ],
+ "node": [
+ "./miniapp/node"
+ ]
+ },
+ "runtime": {
+ "kind": "process",
+ "entry": "./miniapp/node/server.mjs",
+ "lifecycle": "on-demand"
+ },
+ "surface": {
+ "path": "/workbench",
+ "window": {
+ "width": 1320,
+ "height": 880,
+ "minWidth": 900,
+ "minHeight": 560,
+ "resizable": true,
+ "frame": true
+ }
+ },
+ "agentAccess": [
+ "session.run"
+ ],
+ "agentConcurrency": 4,
+ "mcpEndpoints": []
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/agent.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/agent.mjs
new file mode 100644
index 00000000..ac888aa1
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/agent.mjs
@@ -0,0 +1,1205 @@
+import { randomUUID } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { readFile, readdir, stat } from 'node:fs/promises';
+import path from 'node:path';
+
+import {
+ backupCurriculum,
+ cleanCursor,
+ cleanSince,
+ findLesson,
+ getSession,
+ importCurriculum,
+ loadSnapshot,
+ makeMessage,
+ mutateCurriculum,
+ mutateNotes,
+ nodeWriteCursor,
+ nodeWritesAfter,
+ readCurriculumBackup,
+ readMeta,
+ readMission,
+ reconcileWorkspaceFiles,
+ registerWorkspace,
+ saveSession,
+ sessionSummary,
+ writeContextFile,
+ writeMeta,
+} from './store.mjs';
+import { readText, resolveInside, writeText } from './fsx.mjs';
+import {
+ canWrite,
+ denyMessage,
+ protectedSpecs,
+ rulesPath as contractPath,
+ toPosixRel,
+ underAny,
+} from './policy.mjs';
+import {
+ buildContextPacket,
+ curriculumPrompt,
+ lessonFileName,
+ lessonRewritePrompt,
+ lessonSeedPrompt,
+ mainSeedPrompt,
+ noteFileName,
+ notePrompt,
+ setupPrompt,
+} from './prompts.mjs';
+
+const ASK_TIMEOUT_MS = 5 * 60 * 1000;
+/** How long a clean waits for an aborted turn to write its last word. */
+const CANCEL_WAIT_MS = 4000;
+
+/** Said once per turn while a ready mission has no readable title line. */
+const MISSION_TITLE_NOTE =
+ 'MISSION.md 的第一行不是「# Mission: 主题」格式,工作台名字没有更新。把它改成这个格式,再重新读取一次就会按标题命名。';
+
+const READ_TOOLS = new Set([
+ 'read',
+ 'read_file',
+ 'readfile',
+ 'view',
+ 'open_file',
+ 'glob',
+ 'grep',
+ 'rg',
+ 'ls',
+ 'list',
+ 'list_dir',
+ 'list_files',
+ 'listdirectory',
+ 'webfetch',
+ 'web_fetch',
+ 'fetch',
+ 'web_search',
+ 'websearch',
+ 'search',
+ 'todo_write',
+ 'todo',
+ 'todos',
+ 'skill',
+ 'update_plan',
+ 'think',
+]);
+const WRITE_TOOLS = new Set([
+ 'write',
+ 'write_file',
+ 'writefile',
+ 'edit',
+ 'edit_file',
+ 'editfile',
+ 'multiedit',
+ 'multi_edit',
+ 'apply_patch',
+ 'applypatch',
+ 'create_file',
+ 'str_replace_editor',
+ 'str_replace',
+ 'notebook_edit',
+ 'notebookedit',
+ 'patch',
+ 'delete_file',
+ 'mkdir',
+]);
+const SHELL_TOOLS = new Set(['bash', 'shell', 'powershell', 'run_command', 'exec', 'terminal']);
+const DELEGATE_TOOLS = new Set(['task', 'agent', 'spawn_agent', 'launch_agent']);
+
+function toolKey(name) {
+ const raw = String(name ?? '').toLowerCase();
+ const tail = raw.includes('__') ? raw.split('__').pop() : raw;
+ return tail.replace(/[^a-z_]/g, '') || raw;
+}
+
+function collectPaths(input, key = '', out = []) {
+ if (typeof input === 'string') {
+ if (/^(file_?path|path|paths?|target|target_file|filename|file|notebook_path)$/i.test(key)) {
+ out.push(input);
+ }
+ if (/patch|diff/i.test(key) || input.includes('*** Begin Patch')) {
+ for (const match of input.matchAll(/\*\*\* (?:Add|Update|Delete) File: (.+)/g)) {
+ out.push(match[1].trim());
+ }
+ for (const match of input.matchAll(/^\+\+\+ (?:b\/)?(.+)$/gm)) {
+ out.push(match[1].trim());
+ }
+ }
+ return out;
+ }
+ if (Array.isArray(input)) {
+ input.forEach((item) => collectPaths(item, key, out));
+ return out;
+ }
+ if (input && typeof input === 'object') {
+ for (const [childKey, value] of Object.entries(input)) collectPaths(value, childKey, out);
+ }
+ return out;
+}
+
+export function createAgentService({ context, emit, onCurriculumImported }) {
+ const runs = new Map();
+ const ensuring = new Map();
+
+ const keyOf = (wsId, sessionId) => `${wsId}:${sessionId}`;
+
+ const summary = sessionSummary;
+
+ function newRecord({ id, kind, targetId, title }) {
+ const now = Date.now();
+ return {
+ id,
+ kind,
+ targetId,
+ title,
+ createdAt: now,
+ updatedAt: now,
+ messages: [],
+ pending: null,
+ permissions: [],
+ running: null,
+ seeded: false,
+ model: null,
+ };
+ }
+
+ /**
+ * Snapshot every artifact this kind must not write, so a turn that writes one
+ * anyway can be corrected. The cursor lets the restore skip files node itself
+ * touched during the same turn (curriculum, indexes, the session store).
+ */
+ async function snapshotProtected(ws, session) {
+ const files = new Map();
+ const take = async (rel) => {
+ try {
+ const abs = resolveInside(ws.root, rel);
+ const info = await stat(abs);
+ if (!info.isFile() || info.size > 400_000) return;
+ files.set(toPosixRel(rel), await readFile(abs, 'utf8'));
+ } catch {
+ /* missing files are not part of the snapshot */
+ }
+ };
+
+ const specs = protectedSpecs(session.kind);
+ for (const rel of specs.files) await take(rel);
+ for (const entry of specs.dirs) {
+ const dir = path.join(ws.root, entry.dir);
+ const names = await readdir(dir).catch(() => []);
+ const own =
+ entry.own && session.kind === 'lesson' ? toPosixRel(session.targetFile || '').split('/').pop() : '';
+ for (const name of names) {
+ if (name === own) continue;
+ if (entry.exts && !entry.exts.some((ext) => name.toLowerCase().endsWith(ext))) continue;
+ await take(`${entry.dir}/${name}`);
+ }
+ }
+ return { files, cursor: nodeWriteCursor() };
+ }
+
+ async function restoreProtected(ws, snapshot, session, cleanedPaths = []) {
+ if (!snapshot || !snapshot.files || !snapshot.files.size) return [];
+ const touched = nodeWritesAfter(ws.root, snapshot.cursor);
+ const restored = [];
+ for (const [rel, text] of snapshot.files) {
+ if (touched.has(rel)) continue;
+ // Deleted by a clean that started mid-turn: the clean wins over the copy.
+ if (underAny(rel, cleanedPaths)) continue;
+ const abs = resolveInside(ws.root, rel);
+ const current = await readFile(abs, 'utf8').catch(() => null);
+ if (current === text) continue;
+ await writeText(abs, text);
+ restored.push(rel);
+ }
+ if (restored.length) {
+ const hint =
+ {
+ lesson: '这一课只能改自己的课程文件',
+ note: '提炼会话只能写笔记与速查文档',
+ setup: '配置会话只能改 MISSION / RESOURCES / GLOSSARY / NOTES',
+ main: '主会话不直接改课程文件与学习记录',
+ }[session.kind] ?? '这一轮只能改自己负责的文件';
+ session.messages.push(
+ makeMessage('system', `已还原越界修改:${restored.join('、')}。${hint}。`, {
+ kind: 'policy',
+ }),
+ );
+ }
+ return restored;
+ }
+
+ function makeEventHandlers({ ws, session, record }) {
+ return (event) => {
+ if (!event || typeof event !== 'object') return;
+ if (event.type === 'text.delta') {
+ emit(ws.id, { t: 'delta', sessionId: session.id, text: event.text ?? '' });
+ return;
+ }
+ if (event.type === 'tool.started' || event.type === 'tool.finished') {
+ emit(ws.id, {
+ t: 'tool',
+ sessionId: session.id,
+ phase: event.type === 'tool.started' ? 'start' : 'end',
+ name: event.name ?? '',
+ ok: event.ok !== false,
+ });
+ return;
+ }
+ if (event.type === 'permission.requested') {
+ void handlePermission({ ws, session, event, record });
+ return;
+ }
+ if (event.type === 'turn.started') {
+ // The Host is the source of truth for which model actually ran.
+ if (event.model) session.model = event.model;
+ emit(ws.id, { t: 'turn', sessionId: session.id, phase: 'started', model: event.model ?? '' });
+ }
+ };
+ }
+
+ async function createHostSession() {
+ const created = await context.agent.create({});
+ if (!created?.sessionId) {
+ const error = new Error('session_create_failed');
+ error.code = 'SESSION_CREATE_FAILED';
+ throw error;
+ }
+ return created.sessionId;
+ }
+
+ /* ------------------------------------------------------------- deciding */
+
+ function decidePermission(session, event) {
+ const tool = toolKey(event.toolName);
+ const kind = session.kind;
+
+ if (READ_TOOLS.has(tool)) return { decision: 'allowOnce' };
+ if (WRITE_TOOLS.has(tool)) {
+ const targets = collectPaths(event.toolInput ?? {});
+ if (!targets.length) {
+ return { decision: 'ask', reason: '无法判断这次写入的目标路径' };
+ }
+ const relative = targets.filter((target) => !path.isAbsolute(target));
+ if (relative.length) {
+ return {
+ decision: 'deny',
+ note: `已阻止相对路径写入(${relative[0]}):本工作台要求对工作区文件使用绝对路径。`,
+ };
+ }
+ for (const target of targets) {
+ const resolved = path.resolve(target);
+ const rel = path.relative(session.root, resolved);
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
+ return { decision: 'ask', reason: `写入工作区之外的文件:${target}` };
+ }
+ if (!canWrite(kind, rel, session)) {
+ return { decision: 'deny', note: denyMessage(kind, rel, session) };
+ }
+ }
+ return { decision: 'allowOnce' };
+ }
+ if (SHELL_TOOLS.has(tool) || DELEGATE_TOOLS.has(tool)) {
+ if (kind === 'main') return { decision: 'ask', reason: `主会话请求 ${tool}` };
+ return {
+ decision: 'deny',
+ note: `已阻止 ${tool}:${kind === 'lesson' ? '课程' : '提炼'}会话不执行 shell,也不委派子任务。`,
+ };
+ }
+ return { decision: 'ask', reason: `工具 ${event.toolName} 需要确认` };
+ }
+
+ async function replyPermission(session, event, decision) {
+ try {
+ await context.agent.reply({
+ sessionId: event.sessionId,
+ requestId: event.requestId,
+ decision,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ /* ---------------------------------------------------------------- turns */
+
+ /**
+ * The only entry that starts a turn. A fresh turn pushes the user message and
+ * calls run; a resume keeps the transcript, clears the questionnaire and calls
+ * answer. Everything else — busy check, running marker, snapshot, record,
+ * finalize — happens exactly once here.
+ */
+ async function runTurn({ ws, session, prompt, promptKind, resume }) {
+ // Read before anything is written: a clean that lands after this point owns
+ // the files, and this turn must not write them back when it finalizes.
+ const turnFrom = cleanCursor();
+ const key = keyOf(ws.id, session.id);
+ if (runs.has(key)) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+
+ // The merge after the turn needs the curriculum as it was before the agent
+ // rewrites it: lesson files, statuses and session bindings live there. A
+ // backup taken at generation time is too old to carry them between turns.
+ if (session.kind === 'main') await backupCurriculum(ws.root);
+
+ const requestId = randomUUID();
+ if (!resume) {
+ const isSeed = (session.messages?.length ?? 0) === 0;
+ const kind = isSeed ? 'seed' : promptKind || '';
+ session.messages.push(makeMessage('user', prompt, kind ? { kind } : {}));
+ }
+ session.running = { requestId, startedAt: Date.now() };
+ session.pending = null;
+ session.updatedAt = Date.now();
+ session.root = ws.root;
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+
+ const controller = new AbortController();
+ let settle = () => {};
+ const done = new Promise((resolve) => {
+ settle = resolve;
+ });
+ const record = {
+ controller,
+ startedAt: Date.now(),
+ permissionTimers: new Map(),
+ protected: null,
+ cleanCursor: turnFrom,
+ done,
+ };
+ // Visible to cancelAll from the start; a failed snapshot only means there is
+ // nothing to restore later.
+ runs.set(key, record);
+ record.protected = await snapshotProtected(ws, session).catch(() => null);
+
+ const onEvent = makeEventHandlers({ ws, session, record });
+
+ void (async () => {
+ let result = null;
+ let failure = null;
+ try {
+ if (resume) {
+ result = await context.agent.answer(
+ {
+ sessionId: session.id,
+ requestId: resume.requestId,
+ answers: resume.answers,
+ ...(session.model ? { model: session.model } : {}),
+ },
+ { signal: controller.signal, onEvent },
+ );
+ } else {
+ result = await context.agent.run(
+ { text: prompt, sessionId: session.id, ...(session.model ? { model: session.model } : {}) },
+ { signal: controller.signal, onEvent },
+ );
+ }
+ } catch (error) {
+ failure = error;
+ }
+ // A questionnaire that never reached the Host can be answered again.
+ const retryable =
+ failure && (failure.code === 'AGENT_UNAVAILABLE' || failure.code === 'REQUEST_CANCELLED');
+ try {
+ await finalizeTurn({
+ ws,
+ session,
+ result,
+ failure,
+ record,
+ preservedPending: resume && retryable ? resume.pending : null,
+ });
+ } finally {
+ // Stay in runs until the last write is done: cancelAll waits on done.
+ runs.delete(key);
+ settle();
+ }
+ })();
+
+ return { requestId };
+ }
+
+ async function handlePermission({ ws, session, event, record }) {
+ const decision = decidePermission(session, event);
+
+ if (decision.decision !== 'ask') {
+ const settled = await replyPermission(session, event, decision.decision);
+ if (!settled) {
+ // The automatic reply failed, so the run would wait forever. Surface
+ // the request as a manual card instead of dropping it.
+ const pending = {
+ requestId: event.requestId,
+ agentSessionId: event.sessionId,
+ toolName: event.toolName,
+ reason: '自动处理失败,请手动决定',
+ at: Date.now(),
+ };
+ session.permissions = [...(session.permissions || []), pending];
+ session.messages.push(
+ makeMessage('system', `自动授权失败:${event.toolName}。请在会话里手动允许或拒绝。`, {
+ kind: 'policy',
+ }),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ return;
+ }
+ if (decision.note) {
+ session.messages.push(makeMessage('system', decision.note, { kind: 'policy' }));
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ }
+ emit(ws.id, {
+ t: 'permission',
+ sessionId: session.id,
+ toolName: event.toolName,
+ auto: decision.decision,
+ note: decision.note ?? '',
+ });
+ return;
+ }
+
+ const pending = {
+ requestId: event.requestId,
+ agentSessionId: event.sessionId,
+ toolName: event.toolName,
+ reason: decision.reason ?? event.reason ?? '',
+ at: Date.now(),
+ };
+ // Several tools can ask at once; every request keeps its own card and timer.
+ session.permissions = [
+ ...(session.permissions || []).filter((item) => item.requestId !== event.requestId),
+ pending,
+ ];
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+
+ const timer = setTimeout(() => {
+ void (async () => {
+ const still = (session.permissions || []).find((item) => item.requestId === event.requestId);
+ if (!still) return;
+ await replyPermission(session, event, 'deny');
+ session.permissions = (session.permissions || []).filter(
+ (item) => item.requestId !== event.requestId,
+ );
+ session.messages.push(
+ makeMessage('system', '这次工具调用等待了 5 分钟无人处理,已自动拒绝。', { kind: 'policy' }),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ })();
+ }, ASK_TIMEOUT_MS);
+ if (timer.unref) timer.unref();
+ record.permissionTimers.set(event.requestId, timer);
+ }
+
+ async function finalizeTurn({ ws, session, result, failure, record, preservedPending }) {
+ const status = result?.status ?? (failure ? 'error' : 'finished');
+ const reply = result?.text ?? '';
+
+ for (const timer of record?.permissionTimers?.values?.() ?? []) clearTimeout(timer);
+ record?.permissionTimers?.clear?.();
+
+ // 「清理产物」 that started after this turn did owns the files. A deleted
+ // state directory must not be written back, and a deleted artifact must not
+ // be restored from the protected snapshot.
+ const cleans = cleanSince(ws.root, record?.cleanCursor ?? 0);
+ const cleanedPaths = cleans.flatMap((entry) => entry.paths);
+ if (cleans.some((entry) => entry.keys.includes('state'))) {
+ // The workspace's state is gone: saving the transcript would recreate it
+ // and bring the cleaned workspace back. An out-of-scope write is still
+ // reverted (that file is not under the cleaned paths), but nothing is
+ // persisted and no post-turn bookkeeping runs.
+ if (record?.protected) {
+ try {
+ await restoreProtected(ws, record.protected, session, cleanedPaths);
+ } catch {
+ /* A restore failure is reported, never fatal. */
+ }
+ }
+ return;
+ }
+
+ if (reply.trim()) {
+ session.messages.push(makeMessage('assistant', reply, { status }));
+ }
+ if (failure) {
+ const code = failure?.code ?? failure?.message ?? 'unknown';
+ session.messages.push(
+ makeMessage('system', `这一轮没有跑完(${code})。可以直接再问一次,或检查插件权限。`, {
+ kind: 'error',
+ }),
+ );
+ } else if (status === 'error') {
+ session.messages.push(
+ makeMessage('system', `这一轮以错误结束${result?.error ? `:${result.error}` : ''}。`, {
+ kind: 'error',
+ }),
+ );
+ } else if (status === 'aborted') {
+ session.messages.push(makeMessage('system', '这一轮已停止。', { kind: 'policy' }));
+ }
+
+ session.pending = result?.pendingQuestion
+ ? {
+ kind: 'question',
+ requestId: result.pendingQuestion.requestId,
+ request: result.pendingQuestion.request,
+ at: Date.now(),
+ }
+ : preservedPending ?? null;
+ if (preservedPending) {
+ session.messages.push(
+ makeMessage('system', '这次回答没有送达,可以重新提交一次。', { kind: 'policy' }),
+ );
+ }
+ session.permissions = [];
+ session.running = null;
+ session.updatedAt = Date.now();
+
+ if (record?.protected) {
+ try {
+ await restoreProtected(ws, record.protected, session, cleanedPaths);
+ } catch {
+ /* A restore failure is reported, never fatal. */
+ }
+ }
+
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+
+ try {
+ await afterTurn({
+ ws,
+ session,
+ result,
+ failure,
+ cleanedKeys: new Set(cleans.flatMap((entry) => entry.keys)),
+ });
+ } catch {
+ /* A refresh failure never invalidates the stored turn. */
+ }
+ emit(ws.id, { t: 'state' });
+ }
+
+ /**
+ * Keep the workspace name in step with the mission title. Setup and main are the
+ * two kinds that may rewrite MISSION.md. A ready mission without a readable
+ * title line is reported once instead of silently keeping the directory name.
+ */
+ async function syncWorkspaceName({ ws, session }) {
+ const mission = readMission(await readText(path.join(ws.root, 'MISSION.md'), ''));
+ if (!mission.ready) return;
+ if (mission.title) {
+ await registerWorkspace(ws.root, { name: mission.title, touch: false });
+ return;
+ }
+ const said = session.messages.some(
+ (message) => message.role === 'system' && message.text === MISSION_TITLE_NOTE,
+ );
+ if (said) return;
+ session.messages.push(makeMessage('system', MISSION_TITLE_NOTE, { kind: 'policy' }));
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ }
+
+ async function afterTurn({ ws, session, result, cleanedKeys = new Set() }) {
+ const meta = await readMeta(ws.root);
+ if (session.kind === 'setup') {
+ await syncWorkspaceName({ ws, session });
+ return;
+ }
+ if (session.kind === 'main') {
+ // The Agent rewrites curriculum.json from scratch; merge it onto the
+ // pre-turn snapshot so lesson sessions, files and status survive.
+ const backup = await readCurriculumBackup(ws.root);
+ const imported = await importCurriculum(ws.root, meta, backup ? { previous: backup } : {});
+ if (imported.curriculum.modules.length && onCurriculumImported) {
+ onCurriculumImported(ws);
+ }
+ // The merge carries lesson files over from the pre-turn backup; a clean
+ // that deleted them mid-turn must not get those paths back.
+ if (cleanedKeys.has('lessons')) {
+ await reconcileWorkspaceFiles(ws.root, { lessons: true });
+ }
+ await syncWorkspaceName({ ws, session });
+ return;
+ }
+ if (session.kind === 'lesson') {
+ const snap = await loadSnapshot(ws);
+ const lesson = findLesson(snap.curriculum, session.targetId);
+ if (!lesson) return;
+ // The target is fixed before the turn. A file under another name is not
+ // this lesson's result, so it is never adopted.
+ const target = session.targetFile || lesson.file;
+ if (!target || !existsSync(resolveInside(ws.root, target))) {
+ session.messages.push(
+ makeMessage(
+ 'system',
+ cleanedKeys.has('lessons')
+ ? '「清理产物」删除了课程 HTML,这一轮生成的内容没有保留。可以再问一次重新生成。'
+ : `这一轮没有写成本课文件${target ? `(期望 ${target})` : ''}。可以再问一次,或检查它是否写到了别的文件名。`,
+ { kind: 'policy' },
+ ),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ return;
+ }
+ await mutateCurriculum(ws.root, meta, (curriculum) => {
+ const current = findLesson(curriculum, session.targetId);
+ if (!current) return null;
+ current.file = target;
+ current.sessionId = session.id;
+ if (current.status === 'planned') current.status = 'active';
+ return curriculum;
+ });
+ return;
+ }
+ if (session.kind === 'note') {
+ const target = session.targetFile || '';
+ const found = Boolean(target && existsSync(resolveInside(ws.root, target)));
+ await mutateNotes(ws.root, (notes) => {
+ const item = notes.items.find((entry) => entry.id === session.targetId);
+ if (!item) return null;
+ item.status = found ? 'ready' : 'failed';
+ if (found) item.path = target;
+ item.updatedAt = Date.now();
+ return notes;
+ });
+ }
+ }
+
+ /* ------------------------------------------------------------- opening */
+
+ async function ensureMainSession(ws) {
+ const meta = await readMeta(ws.root);
+ if (meta?.mainSessionId) {
+ const existing = await getSession(ws.root, meta.mainSessionId);
+ if (existing) return { session: existing, meta };
+ }
+ const sessionKey = `main:${ws.id}`;
+ if (ensuring.has(sessionKey)) return ensuring.get(sessionKey);
+ const task = (async () => {
+ const sid = await createHostSession();
+ const session = newRecord({ id: sid, kind: 'main', targetId: '', title: '主会话' });
+ await saveSession(ws.root, session);
+ const freshMeta = (await readMeta(ws.root)) ?? {};
+ await writeMeta(ws.root, { ...freshMeta, id: ws.id, mainSessionId: sid });
+ return { session, meta: { ...freshMeta, mainSessionId: sid } };
+ })();
+ ensuring.set(sessionKey, task);
+ try {
+ return await task;
+ } finally {
+ ensuring.delete(sessionKey);
+ }
+ }
+
+ async function ensureSetupSession(ws) {
+ const meta = await readMeta(ws.root);
+ if (meta?.setupSessionId) {
+ const existing = await getSession(ws.root, meta.setupSessionId);
+ if (existing) return { session: existing, meta };
+ }
+ const sessionKey = `setup:${ws.id}`;
+ if (ensuring.has(sessionKey)) return ensuring.get(sessionKey);
+ const task = (async () => {
+ const sid = await createHostSession();
+ const session = newRecord({ id: sid, kind: 'setup', targetId: '', title: '配置 · 学习工作台' });
+ await saveSession(ws.root, session);
+ const freshMeta = (await readMeta(ws.root)) ?? {};
+ await writeMeta(ws.root, { ...freshMeta, id: ws.id, setupSessionId: sid });
+ return { session, meta: { ...freshMeta, setupSessionId: sid } };
+ })();
+ ensuring.set(sessionKey, task);
+ try {
+ return await task;
+ } finally {
+ ensuring.delete(sessionKey);
+ }
+ }
+
+ /** Start the front-matter configuration conversation (once). */
+ async function seedSetup(ws) {
+ const { session } = await ensureSetupSession(ws);
+ if (session.seeded || (session.messages?.length ?? 0) > 0) {
+ return { sessionId: session.id, started: false };
+ }
+ const rulesPath = contractPath(ws.root);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: setupPrompt({ workspace: { ...ws, name: ws.name || path.basename(ws.root) }, rulesPath }),
+ });
+ return { sessionId: session.id, started: true };
+ }
+
+ async function openSetup(ws) {
+ const result = await seedSetup(ws);
+ const session = await getSession(ws.root, result.sessionId);
+ return {
+ sessionId: result.sessionId,
+ started: Boolean(result.started),
+ session: session ? summary(session) : null,
+ };
+ }
+
+ async function ensureLessonSession(ws, lessonId) {
+ const sessionKey = `lesson:${ws.id}:${lessonId}`;
+ if (ensuring.has(sessionKey)) return ensuring.get(sessionKey);
+ const task = (async () => {
+ const snap = await loadSnapshot(ws);
+ const lesson = findLesson(snap.curriculum, lessonId);
+ if (!lesson) {
+ const error = new Error('lesson_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ if (lesson.sessionId) {
+ const existing = await getSession(ws.root, lesson.sessionId);
+ if (existing) return { session: existing, lesson };
+ }
+ const sid = await createHostSession();
+ const target = lesson.file || lessonFileName(lesson);
+ const session = newRecord({
+ id: sid,
+ kind: 'lesson',
+ targetId: lesson.id,
+ title: `第 ${lesson.no} 课 · ${lesson.title}`,
+ });
+ session.targetFile = target;
+ await saveSession(ws.root, session);
+ const meta = await readMeta(ws.root);
+ await mutateCurriculum(ws.root, meta, (curriculum) => {
+ const current = findLesson(curriculum, lessonId);
+ if (!current) return null;
+ current.sessionId = sid;
+ return curriculum;
+ });
+ return { session, lesson: { ...lesson, sessionId: sid } };
+ })();
+ ensuring.set(sessionKey, task);
+ try {
+ return await task;
+ } finally {
+ ensuring.delete(sessionKey);
+ }
+ }
+
+ async function seedMain(ws) {
+ const { session, meta } = await ensureMainSession(ws);
+ if (session.seeded || (session.messages?.length ?? 0) > 0) {
+ return { sessionId: session.id, started: false };
+ }
+ const snap = await loadSnapshot(ws);
+ const hasMission = Boolean(snap.workspace.configured);
+ const rulesPath = contractPath(ws.root);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: mainSeedPrompt({ workspace: { ...ws, root: ws.root }, rulesPath, hasMission }),
+ });
+ return { sessionId: session.id, started: true };
+ }
+
+ async function seedLesson(ws, lessonId) {
+ const { session, lesson } = await ensureLessonSession(ws, lessonId);
+ // A lesson whose file the curriculum already claims is read, not generated:
+ // 「重新生成」 owns that case. A missing file — cleaned, or deleted by hand —
+ // is the one state where the same session may be seeded again, so the button
+ // that starts a lesson keeps working after 「清理产物」.
+ if (lesson.file && existsSync(resolveInside(ws.root, lesson.file))) {
+ return { sessionId: session.id, started: false };
+ }
+ // No file yet, but the session is already busy or waiting for an answer:
+ // seeding would start a second turn and clear the questionnaire. Refuse it;
+ // the caller opens the session as it stands instead.
+ if (session.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ if (session.pending) {
+ const error = new Error('answer_pending');
+ error.code = 'ANSWER_PENDING';
+ throw error;
+ }
+ const snap = await loadSnapshot(ws);
+ const main = snap.workspace.mainSessionId ? await getSession(ws.root, snap.workspace.mainSessionId) : null;
+ const target = session.targetFile || lesson.file || lessonFileName(lesson);
+ const rulesPath = contractPath(ws.root);
+ const packet = buildContextPacket({
+ workspace: { name: ws.name, root: ws.root, mission: snap.mission },
+ curriculum: snap.curriculum,
+ lesson,
+ records: snap.records,
+ mainSession: main,
+ });
+ await writeContextFile(ws.root, `lesson-${String(lesson.no).padStart(4, '0')}`, packet);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: lessonSeedPrompt({
+ workspace: { ...ws, name: ws.name },
+ rulesPath,
+ lesson,
+ target,
+ contextPacket: packet,
+ }),
+ promptKind: 'seed',
+ });
+ return { sessionId: session.id, started: true };
+ }
+
+ async function openLesson(ws, lessonId, { seed = true } = {}) {
+ let sessionId = '';
+ let started = false;
+ if (seed) {
+ const result = await seedLesson(ws, lessonId);
+ sessionId = result.sessionId;
+ started = Boolean(result.started);
+ } else {
+ const result = await ensureLessonSession(ws, lessonId);
+ sessionId = result.session.id;
+ }
+ const session = await getSession(ws.root, sessionId);
+ return {
+ sessionId,
+ started,
+ session: session ? summary(session) : null,
+ };
+ }
+
+ /**
+ * Rewrite one lesson in place: the same branch session and the same target
+ * file. Unlike a follow-up this asks for the whole lesson, and unlike seeding
+ * it runs even when the session already has a transcript.
+ */
+ async function regenerateLesson(ws, lessonId) {
+ const { session, lesson } = await ensureLessonSession(ws, lessonId);
+ if (session.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ if (session.pending) {
+ const error = new Error('answer_pending');
+ error.code = 'ANSWER_PENDING';
+ throw error;
+ }
+ const snap = await loadSnapshot(ws);
+ const main = snap.workspace.mainSessionId ? await getSession(ws.root, snap.workspace.mainSessionId) : null;
+ const target = session.targetFile || lesson.file || lessonFileName(lesson);
+ session.targetFile = target;
+ const rulesPath = contractPath(ws.root);
+ const packet = buildContextPacket({
+ workspace: { name: ws.name, root: ws.root, mission: snap.mission },
+ curriculum: snap.curriculum,
+ lesson,
+ records: snap.records,
+ mainSession: main,
+ });
+ await writeContextFile(ws.root, `lesson-${String(lesson.no).padStart(4, '0')}`, packet);
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await runTurn({
+ ws,
+ session,
+ prompt: lessonRewritePrompt({
+ workspace: { ...ws, name: ws.name },
+ rulesPath,
+ lesson,
+ target,
+ contextPacket: packet,
+ }),
+ promptKind: 'rewrite',
+ });
+ return { sessionId: session.id, started: true, target };
+ }
+ /**
+ * Start a follow-up branch for a lesson with a fresh Host session.
+ * The old session record stays on disk; the lesson points at the new one, so a
+ * long chain of questions never runs on an unbounded context.
+ */
+ async function renewLesson(ws, lessonId) {
+ const snap = await loadSnapshot(ws);
+ const lesson = findLesson(snap.curriculum, lessonId);
+ if (!lesson) {
+ const error = new Error('lesson_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ const previous = lesson.sessionId ? await getSession(ws.root, lesson.sessionId) : null;
+ if (previous?.running) {
+ const error = new Error('session_busy');
+ error.code = 'BUSY';
+ throw error;
+ }
+ const previousTurns = (previous?.messages ?? []).filter((message) => message.role === 'assistant').length;
+ const lastReply =
+ (previous?.messages ?? []).filter((message) => message.role === 'assistant').slice(-1)[0]?.text ?? '';
+ const main = snap.workspace.mainSessionId ? await getSession(ws.root, snap.workspace.mainSessionId) : null;
+ const target = lesson.file || lessonFileName(lesson);
+ const packet = buildContextPacket({
+ workspace: { name: ws.name, root: ws.root, mission: snap.mission },
+ curriculum: snap.curriculum,
+ lesson,
+ records: snap.records,
+ mainSession: main,
+ });
+ const sessionId = await createHostSession();
+ const session = newRecord({
+ id: sessionId,
+ kind: 'lesson',
+ targetId: lessonId,
+ title: `第 ${lesson.no} 课 · 续 ${previousTurns + 1}`,
+ });
+ session.targetFile = target;
+ session.seeded = true;
+ session.model = previous?.model ?? null;
+ await saveSession(ws.root, session);
+ await mutateCurriculum(ws.root, {}, (curriculum) => {
+ const current = findLesson(curriculum, lessonId);
+ if (!current) return null;
+ current.sessionId = sessionId;
+ return curriculum;
+ });
+ const prompt = [
+ `你是第 ${lesson.no} 课的追问续接会话(${session.title})。`,
+ `工作台:${ws.root}`,
+ `规则(先读):${contractPath(ws.root)}`,
+ `本课文件:${path.join(ws.root, target)}(已存在,不要重写整节课,只回答追问。)`,
+ lastReply ? `上一次会话的结论摘要:\n${lastReply.slice(0, 1500)}` : '',
+ packet ? `— 本课上下文 —\n${packet}\n— 上下文结束 —` : '',
+ '用户即将继续追问这一课。先用一句话确认你已接手这一课的上下文(不超过 40 字),不要重复课程内容,也不要生成新课件。',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+ await runTurn({ ws, session, prompt });
+ return { sessionId, started: true, session: summary(session) };
+ }
+
+ /* ------------------------------------------------------------ messaging */
+
+ async function send(ws, sessionId, text) {
+ const session = await getSession(ws.root, sessionId);
+ if (!session) {
+ const error = new Error('session_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ session.root = ws.root;
+ return runTurn({ ws, session, prompt: String(text ?? '').trim() });
+ }
+
+ async function answer(ws, sessionId, requestId, answers) {
+ const session = await getSession(ws.root, sessionId);
+ if (!session) {
+ const error = new Error('session_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ const pending = session.pending;
+ if (!pending || pending.kind !== 'question' || (requestId && pending.requestId !== requestId)) {
+ const error = new Error('no_pending_question');
+ error.code = 'NO_QUESTION';
+ throw error;
+ }
+ await runTurn({
+ ws,
+ session,
+ resume: { requestId: pending.requestId, answers, pending },
+ });
+ return { started: true };
+ }
+
+ async function reply(ws, sessionId, requestId, decision) {
+ const session = await getSession(ws.root, sessionId);
+ const pending = (session?.permissions || []).find((item) => item.requestId === requestId);
+ if (!session || !pending) {
+ const error = new Error('no_pending_permission');
+ error.code = 'NO_PERMISSION';
+ throw error;
+ }
+ try {
+ await context.agent.reply({
+ sessionId: pending.agentSessionId ?? session.id,
+ requestId,
+ decision,
+ });
+ } catch (error) {
+ const failed = new Error(error?.code ?? 'reply_failed');
+ failed.code = error?.code ?? 'REPLY_FAILED';
+ throw failed;
+ }
+ const record = runs.get(keyOf(ws.id, session.id));
+ const timer = record?.permissionTimers?.get(requestId);
+ if (timer) {
+ clearTimeout(timer);
+ record.permissionTimers.delete(requestId);
+ }
+ session.permissions = (session.permissions || []).filter((item) => item.requestId !== requestId);
+ session.messages.push(
+ makeMessage('system', decision === 'allowOnce' ? '已允许这次工具调用。' : '已拒绝这次工具调用。', {
+ kind: 'policy',
+ }),
+ );
+ await saveSession(ws.root, session);
+ emit(ws.id, { t: 'session', sessionId: session.id, session: summary(session) });
+ return { ok: true };
+ }
+
+ function cancel(ws, sessionId) {
+ const record = runs.get(keyOf(ws.id, sessionId));
+ if (!record) return false;
+ record.controller.abort();
+ return true;
+ }
+
+ /**
+ * Stop every running turn of one workspace and wait for their finalize.
+ * A caller that deletes workspace files must await this before it touches disk.
+ */
+ async function cancelAll(ws) {
+ const prefix = `${ws.id}:`;
+ const records = [];
+ for (const [key, record] of runs) {
+ if (!key.startsWith(prefix)) continue;
+ records.push(record);
+ record.controller.abort();
+ }
+ if (!records.length) return 0;
+ // A host that ignores the abort must not block the clean forever; whatever
+ // lands late is caught by the finalize gate.
+ await Promise.race([
+ Promise.all(records.map((record) => record.done)),
+ new Promise((resolve) => {
+ const timer = setTimeout(resolve, CANCEL_WAIT_MS);
+ if (timer.unref) timer.unref();
+ }),
+ ]);
+ return records.length;
+ }
+
+ /* -------------------------------------------------------------- notes */
+
+ async function startNoteJob(ws, { lessonIds, title }) {
+ const snap = await loadSnapshot(ws);
+ const lessons = lessonIds
+ .map((id) => findLesson(snap.curriculum, id))
+ .filter((lesson) => lesson && lesson.file);
+ if (!lessons.length) {
+ const error = new Error('no_lessons_with_files');
+ error.code = 'NO_LESSONS';
+ throw error;
+ }
+ const scoped = snap.annotations.filter((item) => lessonIds.includes(item.lessonId));
+ const safeTitle = String(title ?? '').trim() || `第 ${lessons.map((l) => l.no).join('、')} 课笔记`;
+ // A running note has no file yet, so also avoid paths already claimed by a note record.
+ const taken = new Set((snap.notes || []).map((item) => item.path));
+ let target = noteFileName(safeTitle);
+ let suffix = 2;
+ while (taken.has(target) || existsSync(resolveInside(ws.root, target))) {
+ target = noteFileName(safeTitle).replace(/\.md$/, `-${suffix}.md`);
+ suffix += 1;
+ }
+ const noteId = `n_${randomUUID().slice(0, 8)}`;
+ const sid = await createHostSession();
+ const session = newRecord({
+ id: sid,
+ kind: 'note',
+ targetId: noteId,
+ title: `提炼 · ${safeTitle}`,
+ });
+ session.targetFile = target;
+ session.seeded = true;
+ await saveSession(ws.root, session);
+ await mutateNotes(ws.root, (notes) => {
+ notes.items.unshift({
+ id: noteId,
+ title: safeTitle,
+ path: target,
+ lessonIds: lessons.map((lesson) => lesson.id),
+ sessionId: sid,
+ status: 'running',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ });
+ return notes;
+ });
+ const rulesPath = contractPath(ws.root);
+ await runTurn({
+ ws,
+ session,
+ prompt: notePrompt({
+ workspace: ws,
+ rulesPath,
+ title: safeTitle,
+ target,
+ lessons,
+ annotations: scoped,
+ }),
+ });
+ return { noteId, sessionId: sid, path: target };
+ }
+
+ async function curriculumTurn(ws) {
+ const snap = await loadSnapshot(ws);
+ if (!snap.workspace.configured) {
+ const error = new Error('setup_required');
+ error.code = 'SETUP_REQUIRED';
+ throw error;
+ }
+ const { session } = await ensureMainSession(ws);
+ const rulesPath = contractPath(ws.root);
+ // runTurn backs the curriculum up before the rewrite; importCurriculum merges
+ // lesson state back from it after the turn.
+ await runTurn({
+ ws,
+ session,
+ prompt: curriculumPrompt({ workspace: ws, rulesPath }),
+ promptKind: 'task',
+ });
+ return { sessionId: session.id };
+ }
+
+ function abortAll() {
+ for (const record of runs.values()) {
+ for (const timer of record.permissionTimers?.values?.() ?? []) clearTimeout(timer);
+ record.permissionTimers?.clear?.();
+ try {
+ record.controller.abort();
+ } catch {
+ /* ignore */
+ }
+ }
+ runs.clear();
+ }
+
+ return {
+ openLesson,
+ regenerateLesson,
+ renewLesson,
+ openSetup,
+ seedMain,
+ ensureMainSession,
+ send,
+ answer,
+ reply,
+ cancel,
+ cancelAll,
+ startNoteJob,
+ curriculumTurn,
+ abortAll,
+ };
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/check-paths.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/check-paths.mjs
new file mode 100644
index 00000000..d2264581
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/check-paths.mjs
@@ -0,0 +1,60 @@
+/**
+ * Path vocabulary guard.
+ *
+ * node check-paths.mjs → the manual check, with an exit code
+ * import { checkPaths } → the runtime's startup self-check
+ *
+ * It fails when a module keeps its own copy of a workspace path, or when the
+ * declared layout no longer matches what the app builds. Importing this module
+ * has no side effect, so the server can run it without taking the app down.
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import { artifactPaths, rulesPath, workbenchPaths } from './policy.mjs';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const skip = new Set(['policy.mjs', 'check-paths.mjs']);
+const forbidden = [/\.workbench/, /lessons\//, /notes\//, /reference\//, /learning-records\//, /assets\//, /teach\.md/];
+
+export function checkPaths() {
+ const failures = [];
+ for (const file of fs.readdirSync(here).filter((name) => name.endsWith('.mjs') && !skip.has(name))) {
+ const lines = fs.readFileSync(path.join(here, file), 'utf8').split(/\r?\n/);
+ lines.forEach((line, index) => {
+ if (forbidden.some((pattern) => pattern.test(line))) {
+ failures.push(`${file}:${index + 1} ${line.trim()}`);
+ }
+ });
+ }
+
+ const expected = {
+ lesson: 'lessons',
+ notes: 'notes',
+ reference: 'reference',
+ records: 'learning-records',
+ assets: 'assets',
+ };
+ for (const [id, dir] of Object.entries(expected)) {
+ const actual = artifactPaths(id)[0];
+ if (actual !== dir) failures.push(`artifactPaths(${id}) = ${actual}, expected ${dir}`);
+ }
+
+ const root = path.resolve('/tmp/workspace-check');
+ const paths = workbenchPaths(root);
+ if (paths.rules !== rulesPath(root)) failures.push('rules path mismatch');
+ if (!paths.curriculum.endsWith('curriculum.json')) failures.push('curriculum path mismatch');
+
+ return { ok: failures.length === 0, failures };
+}
+
+const entry = process.argv[1] ? pathToFileURL(process.argv[1]).href : '';
+if (entry === import.meta.url) {
+ const { ok, failures } = checkPaths();
+ if (!ok) {
+ console.error(failures.join('\n'));
+ process.exit(1);
+ }
+ process.stderr.write('path vocabulary OK\n');
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/clean.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/clean.mjs
new file mode 100644
index 00000000..725623b3
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/clean.mjs
@@ -0,0 +1,97 @@
+import { existsSync } from 'node:fs';
+import { rm } from 'node:fs/promises';
+
+import { resolveInside } from './fsx.mjs';
+import { artifactPaths, WORKBENCH_DIR } from './policy.mjs';
+import { forgetWorkspace, markClean, reconcileWorkspaceFiles, workspaceId } from './store.mjs';
+
+/**
+ * What 「清理产物」 offers, and what each key deletes.
+ *
+ * Paths come from the artifact table — the clean view owns only the clean
+ * semantics: which artifacts form one key, which keys start selected, and which
+ * side effects follow a deletion. Callers (the route, the client, the tests)
+ * ask this module instead of keeping their own copy of the list.
+ */
+const dirLabel = (id) => artifactPaths(id)[0] + '/';
+
+const ROWS = [
+ { key: 'lessons', ids: ['lesson'], label: dirLabel('lesson'), hint: '课程 HTML', default: true },
+ { key: 'reference', ids: ['reference'], label: dirLabel('reference'), hint: '速查文档', default: true },
+ { key: 'records', ids: ['records'], label: dirLabel('records'), hint: '学习记录', default: true },
+ { key: 'notes', ids: ['notes'], label: dirLabel('notes'), hint: '提炼出的笔记', default: true },
+ { key: 'assets', ids: ['assets'], label: dirLabel('assets'), hint: '共享样式 course.css', default: true },
+ {
+ key: 'docs',
+ ids: ['mission', 'resources', 'glossary', 'preferences', 'curriculumDoc'],
+ label: 'MISSION / RESOURCES / GLOSSARY / NOTES / CURRICULUM',
+ hint: '前置文档',
+ default: false,
+ },
+ {
+ key: 'state',
+ ids: null,
+ label: WORKBENCH_DIR + '/',
+ hint: '会话、批注、课纲状态(清理后会从列表移除)',
+ default: false,
+ },
+];
+
+/** The list the client renders and the route validates against. */
+export function cleanTargets() {
+ return ROWS.map((row) => ({
+ key: row.key,
+ label: row.label,
+ hint: row.hint,
+ default: row.default,
+ paths: row.ids ? row.ids.flatMap((id) => artifactPaths(id)) : [WORKBENCH_DIR],
+ }));
+}
+
+/** Unknown keys are dropped, so a stale client cannot delete something else. */
+export function cleanKeys(value) {
+ const known = new Set(ROWS.map((row) => row.key));
+ return Array.isArray(value) ? value.filter((key) => known.has(key)) : [];
+}
+
+/**
+ * Delete the selected keys and repair what pointed at them.
+ * Removing the state directory also removes the workspace from the registry; the
+ * caller stops and awaits its running turns first.
+ */
+export async function cleanWorkspace(root, keys) {
+ const wanted = cleanKeys(keys);
+ const rows = cleanTargets().filter((item) => wanted.includes(item.key));
+ // Claim the paths before the first rm: a turn that is still winding down must
+ // not restore them or write the state directory back.
+ markClean(root, { keys: wanted, paths: rows.flatMap((row) => row.paths) });
+ const removed = [];
+ for (const row of rows) {
+ for (const rel of row.paths) {
+ const absolute = resolveInside(root, rel);
+ if (!existsSync(absolute)) continue;
+ await rm(absolute, { recursive: true, force: true });
+ removed.push(rel);
+ }
+ }
+
+ const workspaceGone = wanted.includes('state');
+ const effects = { notesPruned: 0, lessonsReset: 0 };
+
+ if (workspaceGone) {
+ await forgetWorkspace(workspaceId(root));
+ // Sweep once more: a turn that outlived the abort may have written the state
+ // directory back between the delete and the forget.
+ await rm(resolveInside(root, WORKBENCH_DIR), { recursive: true, force: true });
+ return { removed, workspaceGone, effects };
+ }
+
+ const reconciled = await reconcileWorkspaceFiles(root, {
+ lessons: wanted.includes('lessons'),
+ notes: wanted.includes('notes'),
+ });
+ effects.notesPruned = reconciled.notesPruned;
+ effects.lessonsReset = reconciled.lessonsReset;
+
+ return { removed, workspaceGone, effects };
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/fsx.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/fsx.mjs
new file mode 100644
index 00000000..9c36f55e
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/fsx.mjs
@@ -0,0 +1,166 @@
+import { mkdir, readFile, rename, readdir, stat, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { WORKBENCH_DIR } from './policy.mjs';
+
+/** Read JSON; `fallback` on missing or (unless strict) unparsable files. */
+export async function readJson(file, fallback, { strict = false } = {}) {
+ let raw;
+ try {
+ raw = await readFile(file, 'utf8');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return fallback;
+ throw error;
+ }
+ if (!raw.trim()) return fallback;
+ try {
+ return JSON.parse(raw);
+ } catch (error) {
+ if (strict) throw new Error(`invalid_json:${path.basename(file)}`);
+ return fallback;
+ }
+}
+
+/** Read JSON and report parse failure without throwing. */
+export async function readJsonChecked(file, fallback) {
+ let raw;
+ try {
+ raw = await readFile(file, 'utf8');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return { value: fallback, missing: true, error: null };
+ return { value: fallback, missing: false, error: 'read_failed' };
+ }
+ if (!raw.trim()) return { value: fallback, missing: false, error: null };
+ try {
+ return { value: JSON.parse(raw), missing: false, error: null };
+ } catch {
+ return { value: fallback, missing: false, error: 'invalid_json' };
+ }
+}
+
+export async function readText(file, fallback = '') {
+ try {
+ return await readFile(file, 'utf8');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return fallback;
+ throw error;
+ }
+}
+
+export async function writeText(file, text) {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, text, 'utf8');
+}
+
+/** Atomic JSON write: temp file in the same directory, then rename over the target. */
+export async function writeJsonAtomic(file, value) {
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
+ await rename(tmp, file);
+}
+
+/** Write a text file only when it does not exist yet. */
+export async function writeTextOnce(file, text) {
+ if (existsSync(file)) return false;
+ await writeText(file, text);
+ return true;
+}
+
+export function resolveInside(root, relative) {
+ const clean = String(relative ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
+ const target = path.resolve(root, clean);
+ const rel = path.relative(root, target);
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
+ const error = new Error('path_outside_workspace');
+ error.code = 'PATH_OUTSIDE';
+ throw error;
+ }
+ return target;
+}
+
+export function isInside(root, candidate) {
+ const rel = path.relative(path.resolve(root), path.resolve(candidate));
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+}
+
+export function toPosix(value) {
+ return String(value).replace(/\\/g, '/');
+}
+
+export async function listFiles(dir, { extensions = null, max = 400 } = {}) {
+ const out = [];
+ async function walk(current, prefix) {
+ if (out.length >= max) return;
+ let entries;
+ try {
+ entries = await readdir(current, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (out.length >= max) return;
+ if (entry.name.startsWith('.') && entry.name !== WORKBENCH_DIR) continue;
+ const abs = path.join(current, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules') continue;
+ await walk(abs, `${prefix}${entry.name}/`);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ if (extensions && !extensions.includes(path.extname(entry.name).toLowerCase())) continue;
+ out.push(`${prefix}${entry.name}`);
+ }
+ }
+ await walk(dir, '');
+ return out;
+}
+
+export async function fileMeta(root, relative) {
+ try {
+ const info = await stat(resolveInside(root, relative));
+ if (!info.isFile()) return null;
+ return { rel: toPosix(relative), size: info.size, mtime: info.mtimeMs };
+ } catch {
+ return null;
+ }
+}
+
+export function platformRoots() {
+ const roots = [];
+ if (process.platform === 'win32') {
+ for (let code = 65; code <= 90; code += 1) {
+ const drive = `${String.fromCharCode(code)}:\\`;
+ if (existsSync(drive)) roots.push(drive);
+ }
+ } else {
+ roots.push('/');
+ }
+ return roots;
+}
+
+export function homeDir() {
+ try {
+ return os.homedir();
+ } catch {
+ return process.platform === 'win32' ? 'C:\\' : '/';
+ }
+}
+
+export function parentOf(target) {
+ const parent = path.dirname(path.resolve(target));
+ if (parent === path.resolve(target)) return null;
+ return parent;
+}
+
+export function slugify(value, fallback = 'study') {
+ const stripped = String(value ?? '')
+ .normalize('NFKD')
+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .toLowerCase()
+ .slice(0, 48);
+ return stripped || fallback;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/policy.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/policy.mjs
new file mode 100644
index 00000000..938f9adb
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/policy.mjs
@@ -0,0 +1,198 @@
+/**
+ * One declaration of every workspace artifact and who may write it.
+ *
+ * This module is the single source for four things that used to drift apart:
+ * 1. which session kind may write a path (the seam decision),
+ * 2. the explanation shown when a write is refused,
+ * 3. the contract text in .workbench/rules/teach.md and the prompts,
+ * 4. which files a turn snapshots so an out-of-scope write can be restored.
+ *
+ * Pure on purpose: no fs access, no session state beyond the lesson's own
+ * target file. Every function here is a table lookup, so the whole policy is
+ * testable as a matrix of (kind, rel) pairs.
+ */
+
+import path from 'node:path';
+
+/** Every directory and file name a workspace uses, declared once. */
+export const WORKBENCH_DIR = '.workbench';
+export const RULES_DIR = `${WORKBENCH_DIR}/rules`;
+export const COURSE_CSS_REL = 'assets/course.css';
+
+/** Workspace-relative state paths. */
+export const STATE_RELS = {
+ meta: `${WORKBENCH_DIR}/workspace.json`,
+ sessions: `${WORKBENCH_DIR}/sessions.json`,
+ annotations: `${WORKBENCH_DIR}/annotations.json`,
+ notes: `${WORKBENCH_DIR}/notes.json`,
+ curriculum: `${WORKBENCH_DIR}/curriculum.json`,
+ curriculumBackup: `${WORKBENCH_DIR}/curriculum.backup.json`,
+ rules: `${RULES_DIR}/teach.md`,
+ context: `${WORKBENCH_DIR}/context`,
+};
+
+/** Absolute paths for one workspace root; the only builder callers use. */
+export function workbenchPaths(root) {
+ return {
+ base: path.join(root, WORKBENCH_DIR),
+ meta: path.join(root, STATE_RELS.meta),
+ curriculum: path.join(root, STATE_RELS.curriculum),
+ curriculumBackup: path.join(root, STATE_RELS.curriculumBackup),
+ annotations: path.join(root, STATE_RELS.annotations),
+ notes: path.join(root, STATE_RELS.notes),
+ sessions: path.join(root, STATE_RELS.sessions),
+ context: path.join(root, STATE_RELS.context),
+ rules: path.join(root, STATE_RELS.rules),
+ };
+}
+
+export function rulesPath(root) {
+ return path.join(root, STATE_RELS.rules);
+}
+
+export const SESSION_KINDS = ['main', 'setup', 'lesson', 'note'];
+
+export const KIND_LABEL = {
+ main: '主会话',
+ setup: '配置会话',
+ lesson: '课程分支会话',
+ note: '提炼会话',
+};
+
+/**
+ * Ordered: the first spec whose files/dirs match owns the path.
+ * "other" is the fallback for everything the workspace does not own.
+ */
+export const ARTIFACTS = [
+ { id: 'mission', label: '使命', mention: '`MISSION.md`', files: ['MISSION.md'], writers: ['main', 'setup'] },
+ { id: 'resources', label: '来源清单', mention: '`RESOURCES.md`', files: ['RESOURCES.md'], writers: ['main', 'setup'] },
+ { id: 'glossary', label: '术语表', mention: '`GLOSSARY.md`', files: ['GLOSSARY.md'], writers: ['main', 'setup'] },
+ { id: 'preferences', label: '教学偏好', mention: '`NOTES.md`', files: ['NOTES.md'], writers: ['main', 'setup'] },
+ { id: 'curriculumDoc', label: '课纲文档', mention: '`CURRICULUM.md`', files: ['CURRICULUM.md'], writers: ['main'] },
+ { id: 'curriculumState', label: '课纲状态', mention: '`.workbench/curriculum.json`', files: [STATE_RELS.curriculum], writers: ['main'] },
+ { id: 'contextPacket', label: '上下文包', mention: '`.workbench/context/`', dirs: [{ dir: STATE_RELS.context }], writers: ['main'] },
+ {
+ id: 'appState',
+ label: '应用状态',
+ mention: '`.workbench/` 下的会话、批注、笔记索引',
+ files: [
+ STATE_RELS.meta,
+ STATE_RELS.sessions,
+ STATE_RELS.annotations,
+ STATE_RELS.notes,
+ STATE_RELS.curriculumBackup,
+ ],
+ writers: [],
+ },
+ { id: 'lesson', label: '课程', mention: '`lessons/*.html`', dirs: [{ dir: 'lessons', exts: ['.html'], own: true }], writers: ['lesson'] },
+ { id: 'reference', label: '速查文档', mention: '`reference/`', dirs: [{ dir: 'reference' }], writers: ['main', 'lesson', 'note'] },
+ { id: 'records', label: '学习记录', mention: '`learning-records/`', dirs: [{ dir: 'learning-records' }], writers: ['lesson'] },
+ { id: 'notes', label: '提炼笔记', mention: '`notes/`', dirs: [{ dir: 'notes' }], writers: ['note'] },
+ { id: 'assets', label: '共享样式', mention: '`assets/`', dirs: [{ dir: 'assets' }], writers: ['main', 'lesson'] },
+ { id: 'other', label: '其他文件', mention: '工作区里的其他文件', writers: ['main'], neverProtect: true },
+];
+
+const OTHER = ARTIFACTS[ARTIFACTS.length - 1];
+
+export function toPosixRel(rel) {
+ return String(rel ?? '')
+ .replace(/\\/g, '/')
+ .replace(/^\.\//, '')
+ .replace(/^\/+/, '');
+}
+
+/**
+ * True when `rel` is one of `paths` or lives inside one of those directories.
+ * Cleaned roots are declared without a trailing slash (lessons), so a plain
+ * prefix test would also match a sibling such as lessons-old.
+ */
+export function underAny(rel, paths) {
+ const posix = toPosixRel(rel);
+ return (paths ?? []).some((item) => {
+ const root = toPosixRel(item);
+ return Boolean(root) && (posix === root || posix.startsWith(`${root}/`));
+ });
+}
+
+function matches(spec, posix) {
+ if (spec.files) return spec.files.includes(posix);
+ if (spec.dirs) {
+ return spec.dirs.some((entry) => posix === entry.dir || posix.startsWith(`${entry.dir}/`));
+ }
+ return false;
+}
+
+export function classify(rel) {
+ const posix = toPosixRel(rel);
+ return ARTIFACTS.find((spec) => matches(spec, posix)) ?? OTHER;
+}
+
+/** Relative paths that belong to one artifact: its files and directory roots. */
+export function artifactPaths(id) {
+ const spec = ARTIFACTS.find((item) => item.id === id);
+ if (!spec) return [];
+ const out = [];
+ if (spec.files) out.push(...spec.files);
+ if (spec.dirs) for (const entry of spec.dirs) out.push(entry.dir);
+ return out;
+}
+
+/** The one place that decides whether a session may write a path. */
+export function canWrite(kind, rel, session = {}) {
+ const posix = toPosixRel(rel);
+ const spec = classify(posix);
+ if (!spec.writers.includes(kind)) return false;
+ if (spec.id === 'lesson' && kind === 'lesson') return posix === toPosixRel(session.targetFile);
+ return true;
+}
+
+/** The one place that explains a refusal. */
+export function denyMessage(kind, rel, session = {}) {
+ const posix = toPosixRel(rel);
+ const spec = classify(posix);
+ const who = KIND_LABEL[kind] ?? '这个会话';
+ if (spec.id === 'lesson' && kind === 'lesson') {
+ return `已阻止修改其他课程(${posix}):课程会话只能写自己的 ${session.targetFile || '本课文件'}。`;
+ }
+ const owners = spec.writers.map((item) => KIND_LABEL[item]).join(' 或 ');
+ return owners
+ ? `已阻止${who}写 ${posix}:${spec.label}只能由${owners}维护。`
+ : `已阻止${who}写 ${posix}:${spec.label}由应用维护,会话不写。`;
+}
+
+/** Artifacts this kind must not write, so a turn snapshots them for restore. */
+export function protectedSpecs(kind) {
+ const files = [];
+ const dirs = [];
+ for (const spec of ARTIFACTS) {
+ if (spec.neverProtect) continue;
+ // A kind that owns one file inside a shared directory (the lesson's own
+ // HTML) still needs the rest of that directory snapshotted.
+ const ownsOne = Boolean(spec.dirs && spec.dirs.some((entry) => entry.own));
+ if (spec.writers.includes(kind) && !ownsOne) continue;
+ if (spec.files) files.push(...spec.files);
+ if (spec.dirs) for (const entry of spec.dirs) dirs.push({ ...entry });
+ }
+ return { files, dirs };
+}
+
+function mentionFor(kind, spec) {
+ if (spec.id === 'lesson' && kind === 'lesson') return '`lessons/<本课文件>`';
+ return spec.mention;
+}
+
+/** Hard-boundary bullets for .workbench/rules/teach.md. */
+export function boundaryLines() {
+ return SESSION_KINDS.map((kind) => {
+ const can = ARTIFACTS.filter((spec) => spec.writers.includes(kind)).map((spec) => mentionFor(kind, spec));
+ const cannot = ARTIFACTS.filter((spec) => !spec.writers.includes(kind)).map((spec) => spec.mention);
+ return `- **${KIND_LABEL[kind]}**:可写 ${can.join('、') || '无'};不可写 ${cannot.join('、')}。`;
+ }).join('\n');
+}
+
+/** Short scope lines for prompts: what this turn may touch, and what it may not. */
+export function scopeLines(kind) {
+ const can = ARTIFACTS.filter((spec) => spec.writers.includes(kind)).map((spec) => mentionFor(kind, spec));
+ const cannot = ARTIFACTS.filter((spec) => !spec.writers.includes(kind)).map((spec) => spec.mention);
+ return `可以写:${can.join('、') || '无'}。\n禁止改动:${cannot.join('、')}。`;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/prompts.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/prompts.mjs
new file mode 100644
index 00000000..e9b9fa16
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/prompts.mjs
@@ -0,0 +1,244 @@
+import { allLessons } from './store.mjs';
+import { artifactPaths, COURSE_CSS_REL, scopeLines, workbenchPaths } from './policy.mjs';
+
+function clip(value, max) {
+ const text = String(value ?? '').trim();
+ if (text.length <= max) return text;
+ return `${text.slice(0, max)}…`;
+}
+
+export function lessonFileName(lesson) {
+ const no = String(lesson.no).padStart(4, '0');
+ const slug =
+ String(lesson.title)
+ .normalize('NFKD')
+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .toLowerCase()
+ .slice(0, 50) || 'lesson';
+ const dir = artifactPaths('lesson')[0];
+ return `${dir}/${no}-${slug}.html`;
+}
+
+export function noteFileName(title, date = new Date()) {
+ const stamp = [
+ date.getFullYear(),
+ String(date.getMonth() + 1).padStart(2, '0'),
+ String(date.getDate()).padStart(2, '0'),
+ ].join('-');
+ const clock = `${String(date.getHours()).padStart(2, '0')}${String(date.getMinutes()).padStart(2, '0')}`;
+ const slug =
+ String(title)
+ .normalize('NFKD')
+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .toLowerCase()
+ .slice(0, 36) || 'note';
+ const dir = artifactPaths('notes')[0];
+ return `${dir}/${stamp}-${slug}-${clock}.md`;
+}
+
+export function buildContextPacket({ workspace, curriculum, lesson, records, mainSession }) {
+ const lessons = allLessons(curriculum);
+ const outline = curriculum.modules
+ .map((module) => {
+ const items = module.lessons
+ .map((item) => `${String(item.no).padStart(2, '0')} ${item.title}${item.status === 'done' ? '(已完成)' : item.status === 'active' ? '(进行中)' : ''}`)
+ .join(' · ');
+ return `${module.title}:${items}`;
+ })
+ .join('\n');
+
+ const doneRecords = records
+ .slice(0, 6)
+ .map((record) => {
+ const summary = clip(record.excerpt ?? '', 160).replace(/\s+/g, ' ');
+ return `- ${record.title}${summary ? `:${summary}` : ''}`;
+ })
+ .join('\n');
+
+ const decisions = (mainSession?.messages ?? [])
+ .filter((message) => message.role === 'assistant')
+ .slice(-2)
+ .map((message) => `- ${clip(message.text, 360).replace(/\s+/g, ' ')}`)
+ .join('\n');
+
+ const position = `第 ${lesson.no} 课 / 共 ${lessons.length} 课`;
+
+ return [
+ `【工作台】${workspace.name}(${workspace.root})`,
+ `【本课位置】${position}`,
+ `【使命】${clip(
+ (workspace.mission ?? '').replace(//g, '').replace(/^#.*$/gm, '').trim(),
+ 700,
+ )}`,
+ `【课纲】\n${clip(outline, 1200)}`,
+ doneRecords ? `【已完成课程的学习记录】\n${clip(doneRecords, 900)}` : '',
+ decisions ? `【主会话最近结论】\n${clip(decisions, 700)}` : '',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+}
+
+export function setupPrompt({ workspace, rulesPath }) {
+ return `你是这个学习工作台的配置会话。工作台目录:${workspace.root}
+
+这一步只搭前置环境:确定学习者是谁、想从这个目录里学到什么、有哪些约束。不要产出课程,也不要写课纲。
+
+先做三件事(都用绝对路径):
+1. 读 ${rulesPath};
+2. 读 ${workspace.root}\\MISSION.md(现在是模板);
+3. 看一眼这个目录:列出根目录,读 README、docs/ 里能说明它在做什么的文件,判断用户为什么把这个目录选来学习。
+
+然后用 ask_user 采访用户:一次问完,最多 3 个问题,围绕「你想从这个项目/目录里学到什么、为什么现在要学、时间与已有基础」。每题给 3–4 个具体选项,选项要基于你在目录里看到的东西来设计,不要问空泛的问题。
+
+拿到答案后:
+- 把 ${workspace.root}\\MISSION.md 写完整(严格按契约里的模板;首行是 # Mission: <一句话主题>)。
+- 更新 ${workspace.root}\\RESOURCES.md:挑 2–4 个可信来源,每条一句话说明用途。
+- 在 ${workspace.root}\\NOTES.md 记下用户的偏好,以及你在目录里看到、后面设计课程会用到的结构(比如已有的 tasks/、docs/)。
+
+边界(硬性):这一轮只做前置配置,不生成课纲,也不写任何课程文件。
+${scopeLines('setup')}
+
+完成标准:MISSION.md 的 Why 和 Success looks like 都写实了,不是模板占位。
+写完后回复不超过 100 字:一句话主题 + 你记下的关键约束 + 一句「前置环境已就绪,可以生成课纲」。
+停在这里,不要继续生成课纲或课程。`;
+}
+
+export function mainSeedPrompt({ workspace, rulesPath, hasMission }) {
+ return `你是这个学习工作台的主会话(teacher of record)。工作台根目录:${workspace.root}
+
+先读这两个文件,再动手(所有文件操作都用绝对路径):
+1. ${rulesPath} —— 教学契约,必须遵守
+2. ${workspace.root}\\MISSION.md —— 当前使命${hasMission ? '(已填写)' : '(还是模板)'}
+如果 \`mattpocock-skills:teach\` 这个 Skill 可用,也读一遍;它与上面的契约冲突时,以契约里的会话边界为准。
+
+你的职责:确定使命、维护 RESOURCES.md 与 GLOSSARY.md、生成和调整课纲、处理全局配置。
+你不写具体课程内容:课程文件由每节课的分支会话负责。
+
+流程:
+- 如果使命仍未确定,用 ask_user 采访用户:一次问完,最多 3 个问题,围绕「为什么学、想做成什么、时间与已有基础」。每题给 3–4 个具体选项,不要开放式空问。
+- 拿到答案后,把 ${workspace.root}\\MISSION.md 写完整(严格按契约里的模板),并在 NOTES.md 记下用户的偏好。
+- 然后回复不超过 120 字的小结:一句话使命 + 建议的模块数量 + 下一步。
+- 除非用户明确要求,这一轮不要生成课纲。`;
+}
+
+export function curriculumPrompt({ workspace, rulesPath }) {
+ return `任务:为这个学习工作台生成课纲。
+
+先读:${rulesPath}、${workspace.root}\\MISSION.md、${workspace.root}\\RESOURCES.md。
+
+要求:
+- 3–6 个模块,每模块 2–5 节课,总课数 6–18;顺序从用户当前水平推到使命终点(最近发展区)。
+- 每节课单点、预算 15–25 分钟、有可验证的产出,直接服务使命。
+- 每节课必须能单独阅读:不假设读者记得上一课;需要前置知识时,用课内回顾补上(在 objective 里点明),拆不开的两课合并成一课。
+- 课程标题用中文、动词开头(例:「用 clap 建立子命令」),不要用「第一讲」这类编号标题。
+- objective 用一句话说清这节课结束时用户能做什么(可观察)。
+- **保留已有课程的原标题**:工作台按标题把每节课绑到它自己的分支会话;改标题等于换一门课。
+- 这一轮只写课纲,不要创建课程文件,不要写 HTML。
+
+写入 ${workbenchPaths(workspace.root).curriculum},严格是下面这个结构(不要注释、不要多余字段):
+{"schemaVersion":1,"modules":[{"title":"模块名","goal":"这一模块解决什么","lessons":[{"title":"课程标题","objective":"结束时能做什么","minutes":20}]}]}
+
+同时把人类可读版写入 ${workspace.root}\\CURRICULUM.md:每个模块一节,列出课号、标题、目标。
+
+完成后只回复:模块数、课程数、一句「课纲已写入」。`;
+}
+
+const LESSON_WRITING_RULES = `写作要求:
+- 一个自包含 HTML:用 复用共享样式,必要时少量内联样式。
+- 只教一个点,用户 20 分钟内能读完并做完练习。
+- 自包含:不假设读者读过上一课;需要前置知识时,用 1–2 句回顾并链接到对应课程。
+- 先给知识(来源以 RESOURCES.md 为准,不够就用 web 搜索补,并保持可信),再给互动练习。
+- 至少 2 个检索练习:单选、四个选项长度尽量一致、点选后立即显示对错与原因(原生 JS 即可)。
+- 每个事实性论断附近给来源链接;结尾列「主要来源」。
+- 结尾提醒:可以在这个分支会话里继续追问。
+- 不要引用远程脚本或 CDN。`;
+
+export function lessonSeedPrompt({ workspace, rulesPath, lesson, target, contextPacket }) {
+ return `你是第 ${lesson.no} 课的课程分支会话。这节课的上下文已经由主会话打包给你,你只负责这一课。
+
+工作台:${workspace.root}
+规则(先读):${rulesPath}
+如果 \`mattpocock-skills:teach\` 这个 Skill 可用,也读一遍;与规则冲突时以规则里的会话边界为准。
+本课:${lesson.title}
+目标:${lesson.objective || '(课纲未写目标,按标题把握)'}
+预算:${lesson.minutes} 分钟
+本课文件(唯一要写的课程文件):${workspace.root}\\${target}
+
+本课文件是唯一要写的课程文件;越界写入会被拒绝或还原。
+${scopeLines('lesson')}
+
+— 继承的上下文 —
+${contextPacket}
+— 上下文结束 —
+
+${LESSON_WRITING_RULES}
+
+第一步(不要跳过):先读规则、MISSION.md 与共享样式,然后回复 3 句——本课要拿到的一个具体成果、你打算怎么讲、需要用户准备什么。之后再写文件。
+写完回复:文件路径 + 一句自检(是否包含练习与来源)。`;
+}
+
+export function lessonRewritePrompt({ workspace, rulesPath, lesson, target, contextPacket }) {
+ return `这是第 ${lesson.no} 课的整节重做:用户看过现有课程,要求把这一课重新写一遍。
+
+工作台:${workspace.root}
+规则(先读):${rulesPath}
+本课:${lesson.title}
+目标:${lesson.objective || '(课纲未写目标,按标题把握)'}
+预算:${lesson.minutes} 分钟
+本课文件(唯一要写的课程文件,整份覆盖):${workspace.root}\\${target}
+
+本课文件是唯一要写的课程文件;越界写入会被拒绝或还原。
+${scopeLines('lesson')}
+
+— 继承的上下文 —
+${contextPacket}
+— 上下文结束 —
+
+这是重做,不是追问:
+- 覆盖同一个文件,不要新建第二个课程文件,也不要改其他课程。
+- 先读本课现有文件与 MISSION.md:保留值得留的部分,改进讲法、练习与来源。
+- 标题、目标、预算以课纲为准,不要改课纲。
+- 不要先复述计划,直接写。
+
+${LESSON_WRITING_RULES}
+
+写完回复:文件路径 + 一句自检(哪里比上一版好,是否包含练习与来源)。`;
+}
+
+export function notePrompt({ workspace, rulesPath, title, target, lessons, annotations }) {
+ const lessonLines = lessons
+ .map((lesson) => `- 第 ${lesson.no} 课《${lesson.title}》:${workspace.root}\\${lesson.file}`)
+ .join('\n');
+ const annotationLines = annotations.length
+ ? annotations
+ .map((item) => {
+ const lesson = lessons.find((entry) => entry.id === item.lessonId);
+ const label = lesson ? `第 ${lesson.no} 课` : '相关课程';
+ const quote = item.quote ? `引用「${clip(item.quote, 120)}」→ ` : '';
+ return `- [${label}] ${quote}${clip(item.note, 300)}`;
+ })
+ .join('\n')
+ : '(这个范围内没有批注)';
+
+ return `笔记提炼任务(独立会话,只读课程与批注)。
+
+工作台:${workspace.root}
+规则:${rulesPath}(先读,尤其是文档格式与「不要编造」)
+笔记标题:${title}
+
+范围课程:
+${lessonLines}
+
+用户批注(用户自己的想法,必须被吸收,保留他们的用词):
+${annotationLines}
+
+要求:
+- 读上面列出的课程 HTML,提炼而不是照抄。
+- 写入 ${workspace.root}\\${target},结构:一句话主旨 / 核心模型或步骤 / 我的批注要点(标注课次,引用用户原话)/ 易错点 / 下一步练习 / 来源。
+- 课程与批注冲突时保留冲突并指出,不要自行调和。
+- 只写这一个笔记文件,不改课程、不改其他文件。
+
+完成后回复:文件路径 + 一句话摘要。`;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/scaffold.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/scaffold.mjs
new file mode 100644
index 00000000..a97ce301
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/scaffold.mjs
@@ -0,0 +1,381 @@
+import { mkdir } from 'node:fs/promises';
+import path from 'node:path';
+
+import { writeText, writeTextOnce } from './fsx.mjs';
+import { artifactPaths, boundaryLines, COURSE_CSS_REL, RULES_DIR, STATE_RELS, WORKBENCH_DIR } from './policy.mjs';
+
+export const TEACH_RULES = `# 教学契约(学习工作台)
+
+本工作区遵循 Matt Pocock 的 teach 方法(改编自 \`mattpocock-skills:teach\`)。任何在这个目录里工作的会话都必须遵守本文件。
+这是「为什么这样教」的唯一依据:课程结构、练习形式、文档格式都以它为准。
+
+## 目录约定
+
+- \`MISSION.md\`:使命。为什么学、学成什么样。所有教学决策都要能回溯到这里。
+- \`CURRICULUM.md\`:人类可读的课纲。机器可读版在 \`${STATE_RELS.curriculum}\`。
+- \`${artifactPaths('lesson')[0]}/0001-.html\`:课程。一课一个自包含 HTML 文件,编号递增。
+- \`${artifactPaths('assets')[0]}/\`:课程共享的组件与样式(\`course.css\` 是默认样式表)。复用优先,不要复制粘贴。
+- \`${artifactPaths('reference')[0]}/*.html\`:速查文档。可打印、排版干净,供反复查阅。
+- \`${artifactPaths('records')[0]}/0001-.md\`:学习记录。记录非显然的理解、先前知识、被纠正的误解。
+- \`GLOSSARY.md\`:术语表。只收录用户已经理解的术语。
+- \`RESOURCES.md\`:可信来源清单,分 Knowledge / Wisdom 两组,每条都要有用途说明。
+- \`NOTES.md\`:教学偏好与临时笔记。
+- \`${artifactPaths('notes')[0]}/*.md\`:从课程与批注提炼出的笔记(由提炼会话写入)。
+- \`${WORKBENCH_DIR}/\`:学习工作台的机器状态,由应用维护;会话的写权限见「会话职责」。
+
+## 会话职责(硬边界)
+
+${boundaryLines()}
+
+## 教学原则
+
+学习需要三样东西:知识(来自高质量来源)、技能(通过有反馈的练习获得)、智慧(真实世界的交流)。
+不要相信自己的记忆:所有事实性陈述都要能指向 RESOURCES.md 里的来源。
+
+- **区分流畅度与存储强度**。看懂了不等于记住了。设计课程时用检索练习、间隔、交错,制造「合意的困难」。
+- **最近发展区**。每节课只比用户当前水平难一点点;读学习记录判断当前水平。
+- **知识先行,技能随后**。先用最少的知识把概念讲清,然后立刻用互动练习把它变成技能。
+- **反馈回路要短**。练习要立即给出对错与原因,不要让用户自己猜。
+- **一课一个收获**。工作记忆很小;宁可少讲,也要让用户拿到一个可以马上用出去的东西。
+- **每节课自包含**。读者只读这一课也能听懂;不假设他记得上一课的讲解。需要前置知识时,课内用 1–2 句回顾并链接到那一课;拆不开的两课合并成一课,不要拆成必须连着读的两课。
+
+## 课程(lesson)要求
+
+1. 一个自包含 HTML 文件,直接打开就能读。默认引用 \`../${COURSE_CSS_REL}\` 获得排版,
+ 需要时再加少量内联样式。
+2. 15–25 分钟内可完成。开头用一句话说清「这节课结束时你能做什么」。
+3. 结构:知识(带来源链接)→ 示例/演示 → 检索练习(至少 2 个)→ 这一课的收获 → 可以继续追问。
+4. 检索练习题:单选,四个选项长度尽量一致(不要用格式泄露答案),点选后立即出现对错与原因。
+5. 每个事实性论断附近给出链接;结尾列出「主要来源」。
+6. 用原生 HTML/CSS/JS。不要引用远程脚本或 CDN。
+7. 课程之间用相对链接互链;首次出现的术语链接到 \`${artifactPaths('reference')[0]}/\` 或 \`GLOSSARY.md\`。
+8. 结尾必须有一句提醒:可以在这个工作台的分支会话里继续追问。
+9. 打印友好:\`@media print\` 下不要出现交互控件。
+10. 内容自包含:不依赖上一课的讲解才能看懂;需要前置知识时,用 1–2 句在课内回顾,并链接到对应课程。拆不开的内容合并成一课。
+
+## 文档格式
+
+### MISSION.md
+
+\`\`\`md
+# Mission: {Topic}
+
+## Why
+{1-3 sentences. The concrete real-world goal.}
+
+## Success looks like
+- {A specific, observable thing the user will be able to do}
+
+## Constraints
+- {Time, budget, prior commitments, learning preferences}
+
+## Out of scope
+- {Adjacent topics deliberately not chased now}
+\`\`\`
+
+保持一屏以内。使命需要变化时,先和用户确认,再更新这份文件,并补一条 learning-record 说明为什么变——
+不要自己悄悄改掉方向,也不要留一份过时的使命指挥后面的课。
+
+### RESOURCES.md
+
+\`\`\`md
+# {Topic} Resources
+
+## Knowledge
+
+- [Book: _Title_ by Author](https://example.com)
+ 一句话说明它覆盖什么、什么时候该查它。
+
+## Wisdom (Communities)
+
+- [r/example](https://example.com)
+ 高信噪比社区,用来:方案点评、瓶颈排错。
+
+## Gaps
+- {还没有找到好来源的方向}
+\`\`\`
+
+只收高可信来源;每条都要有用途说明;宁可五个锋利的来源,不要三十个平庸的。
+
+### ${artifactPaths('records')[0]}/0001-.md
+
+\`\`\`md
+# {Short title}
+
+{1-3 sentences: 学到了什么(或确认了什么先前知识),为什么它会影响后面的课。}
+\`\`\`
+
+只在有**证据**时写:用户演示了真正的理解、说明了已知、纠正了误解、或使命发生变化。
+单纯的「讲过」不算学习,不要写。
+
+### GLOSSARY.md
+
+\`\`\`md
+# {Topic} Glossary
+
+## Terms
+
+**术语**:
+一到两句话,定义它是什么(不是怎么用)。
+_Avoid_: 同义的模糊说法
+\`\`\`
+
+术语只有等用户能正确使用之后才收录。定义里优先使用表里已有的术语。
+`;
+
+const MISSION_TEMPLATE = (topic) => `# Mission: ${topic}
+
+## Why
+_待主会话与你确认:一句话说清为什么学、想做成什么。_
+
+## Success looks like
+- _待填写:一个具体、可观察的结果_
+
+## Constraints
+- _待填写:时间、预算、已有基础、学习偏好_
+
+## Out of scope
+- _待填写:这次明确不追的相邻主题_
+`;
+
+const RESOURCES_TEMPLATE = (topic) => `# ${topic} Resources
+
+## Knowledge
+
+- _待主会话补充:可信来源,每条一句话说明用途_
+
+## Wisdom (Communities)
+
+- _待补充:可以验证技能的真实社区_
+
+## Gaps
+- _还没有找到好来源的方向_
+`;
+
+const GLOSSARY_TEMPLATE = (topic) => `# ${topic} Glossary
+
+只在你能正确使用一个术语之后,它才应该出现在这里。
+
+## Terms
+
+`;
+
+const NOTES_TEMPLATE = `# 教学笔记
+
+这里记录教学偏好、临时想法、以及主会话需要注意的事。
+
+- 界面语言:中文
+`;
+
+const CURRICULUM_TEMPLATE = `# 课纲
+
+尚未生成。在学习工作台的「概览」里点「生成课纲」,主会话会按使命写出模块与课程。
+`;
+
+export const COURSE_CSS = `/* 学习工作台共享课程样式:所有课程页默认引用它。 */
+:root {
+ --ink: #1c1b19;
+ --muted: #6b6a66;
+ --line: #0a0a0a14;
+ --paper: #fbfaf7;
+ --surface: #ffffff;
+ --accent: #0b6bcb;
+ --ok: #0f7a3d;
+ --bad: #b42318;
+ --warn: #b45309;
+ --code: #f2f0eb;
+ color-scheme: light dark;
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --ink: #ece9e2;
+ --muted: #a09d95;
+ --line: #ffffff1f;
+ --paper: #1e1d1b;
+ --surface: #26251f;
+ --accent: #7db4ff;
+ --ok: #6ee7a8;
+ --bad: #ff9a8f;
+ --warn: #ffc46b;
+ --code: #2b2a24;
+ }
+}
+* { box-sizing: border-box; }
+html { -webkit-text-size-adjust: 100%; }
+body {
+ margin: 0;
+ background: var(--paper);
+ color: var(--ink);
+ font-family: ui-serif, Georgia, "Songti SC", "Source Han Serif SC", "Noto Serif CJK SC", serif;
+ font-size: 17.5px;
+ line-height: 1.85;
+}
+.lesson {
+ max-width: 680px;
+ margin: 0 auto;
+ padding: 48px 28px 96px;
+}
+.kicker {
+ font-family: ui-sans-serif, -apple-system, system-ui, "PingFang SC", sans-serif;
+ font-size: 11px;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--muted);
+ margin-bottom: 1.6em;
+}
+h1, h2, h3 {
+ font-family: ui-sans-serif, -apple-system, system-ui, "PingFang SC", sans-serif;
+ line-height: 1.35;
+ letter-spacing: -0.01em;
+}
+h1 { font-size: 30px; font-weight: 600; margin: 0 0 0.4em; }
+h2 { font-size: 18px; font-weight: 600; margin: 2em 0 0.3em; }
+h3 { font-size: 15px; font-weight: 600; margin: 1.4em 0 0.2em; }
+p { margin: 0 0 1em; }
+a { color: var(--accent); text-decoration: none; border-bottom: 1px solid currentColor; }
+a:hover { opacity: 0.8; }
+code {
+ font-family: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.85em;
+ background: var(--code);
+ border-radius: 4px;
+ padding: 0.1em 0.34em;
+}
+pre {
+ background: var(--code);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ padding: 14px 16px;
+ overflow: auto;
+ font-size: 13px;
+ line-height: 1.7;
+}
+pre code { background: none; padding: 0; font-size: inherit; }
+blockquote {
+ margin: 1.4em 0;
+ padding: 2px 0 2px 16px;
+ border-left: 2px solid var(--line);
+ color: var(--muted);
+ font-style: italic;
+}
+ul, ol { padding-left: 1.3em; margin: 0 0 1em; }
+li + li { margin-top: 0.3em; }
+mark { background: #b4530922; border-radius: 2px; padding: 0 2px; color: inherit; }
+.lede { font-size: 1.05em; color: var(--muted); }
+.note {
+ border: 1px solid var(--line);
+ border-left: 3px solid var(--warn);
+ border-radius: 8px;
+ background: var(--surface);
+ padding: 12px 14px;
+ margin: 1.4em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.7;
+}
+.quiz {
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: var(--surface);
+ padding: 16px 18px;
+ margin: 1.8em 0;
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 14px;
+ line-height: 1.65;
+}
+.quiz h3 { margin: 0 0 2px; font-size: 14px; }
+.quiz .prompt { margin: 0 0 12px; color: var(--muted); font-size: 13px; }
+.quiz button {
+ display: flex;
+ gap: 9px;
+ width: 100%;
+ text-align: left;
+ align-items: flex-start;
+ padding: 9px 11px;
+ margin-bottom: 6px;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+}
+.quiz button:hover { border-color: var(--muted); }
+.quiz button b { width: 18px; flex: none; color: var(--muted); font-weight: 500; }
+.quiz button.right { border-color: var(--ok); background: color-mix(in srgb, var(--ok) 10%, transparent); }
+.quiz button.wrong { border-color: var(--bad); background: color-mix(in srgb, var(--bad) 8%, transparent); }
+.quiz .feedback { color: var(--muted); font-size: 13px; margin-top: 8px; }
+.quiz .feedback[hidden] { display: none; }
+.takeaway {
+ border-top: 1px solid var(--line);
+ margin-top: 2.4em;
+ padding-top: 16px;
+}
+.takeaway h2 { margin-top: 0; }
+.sources {
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 13px;
+ color: var(--muted);
+ border-top: 1px solid var(--line);
+ margin-top: 2.4em;
+ padding-top: 12px;
+}
+.ask-teacher {
+ font-family: ui-sans-serif, system-ui, "PingFang SC", sans-serif;
+ font-size: 13px;
+ color: var(--muted);
+ background: var(--code);
+ border-radius: 8px;
+ padding: 10px 12px;
+ margin-top: 1.6em;
+}
+mark.wb-hl {
+ background: color-mix(in srgb, #f59e0b 26%, transparent);
+ border-bottom: 1px solid color-mix(in srgb, #f59e0b 70%, transparent);
+ cursor: pointer;
+}
+@media print {
+ body { background: #fff; color: #000; font-size: 12pt; }
+ .quiz button, .ask-teacher { display: none; }
+ a { color: #000; }
+}
+`;
+
+/**
+ * The contract text is generated from the write policy, so it is refreshed in
+ * place: a workspace created by an older build must not keep a stale boundary.
+ */
+export async function refreshRules(root) {
+ const rel = STATE_RELS.rules;
+ const abs = path.join(root, rel);
+ await mkdir(path.dirname(abs), { recursive: true });
+ await writeText(abs, TEACH_RULES);
+ return rel;
+}
+
+/** Create the teach workspace structure. Existing files are never overwritten. */
+export async function ensureScaffold(root, { topic }) {
+ const dirs = [
+ ...['lesson', 'reference', 'records', 'assets', 'notes'].map((id) => artifactPaths(id)[0]),
+ RULES_DIR,
+ STATE_RELS.context,
+ ];
+ for (const dir of dirs) {
+ await mkdir(path.join(root, dir), { recursive: true });
+ }
+
+ const files = [
+ ['MISSION.md', MISSION_TEMPLATE(topic)],
+ ['RESOURCES.md', RESOURCES_TEMPLATE(topic)],
+ ['GLOSSARY.md', GLOSSARY_TEMPLATE(topic)],
+ ['NOTES.md', NOTES_TEMPLATE],
+ ['CURRICULUM.md', CURRICULUM_TEMPLATE],
+ [COURSE_CSS_REL, COURSE_CSS],
+ [STATE_RELS.rules, TEACH_RULES],
+ ];
+ const created = [];
+ for (const [rel, text] of files) {
+ if (await writeTextOnce(path.join(root, rel), text)) created.push(rel);
+ }
+ return created;
+}
diff --git a/plugins/meisijiya/learn-workbench/miniapp/node/server.mjs b/plugins/meisijiya/learn-workbench/miniapp/node/server.mjs
new file mode 100644
index 00000000..3015279f
--- /dev/null
+++ b/plugins/meisijiya/learn-workbench/miniapp/node/server.mjs
@@ -0,0 +1,867 @@
+import { createReadStream, existsSync } from 'node:fs';
+import { access, readFile, readdir, stat } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import path from 'node:path';
+
+import { createAgentService } from './agent.mjs';
+import { checkPaths } from './check-paths.mjs';
+import { cleanKeys, cleanTargets, cleanWorkspace } from './clean.mjs';
+import { rulesPath, STATE_RELS, WORKBENCH_DIR } from './policy.mjs';
+import { refreshRules } from './scaffold.mjs';
+import {
+ createWorkspace,
+ findLesson,
+ forgetWorkspace,
+ getSession,
+ getWorkspace,
+ importCurriculum,
+ importWorkspace,
+ initStore,
+ listWorkspaces,
+ loadSnapshot,
+ mutateAnnotations,
+ mutateCurriculum,
+ readAnnotations,
+ readCurriculum,
+ readMeta,
+ readMission,
+ readRules,
+ registerWorkspace,
+ saveSession,
+ sessionSummary,
+} from './store.mjs';
+import {
+ homeDir,
+ parentOf,
+ platformRoots,
+ readText,
+ resolveInside,
+ toPosix,
+} from './fsx.mjs';
+
+const SURFACE = '/workbench';
+
+/** Accept only a selection the Host can dispatch: provider, model, optional variant, optional effort. */
+function normalizeModelSelection(value) {
+ if (!value || typeof value !== 'object') return null;
+ const providerId = typeof value.providerId === 'string' ? value.providerId.trim() : '';
+ const modelId = typeof value.modelId === 'string' ? value.modelId.trim() : '';
+ if (!providerId || !modelId) return null;
+ const selection = { providerId, modelId };
+ if (typeof value.variant === 'string') selection.variant = value.variant;
+ if (value.thinking && typeof value.thinking === 'object' && typeof value.thinking.effort === 'string') {
+ selection.thinking = { effort: value.thinking.effort };
+ }
+ return selection;
+}
+
+const MIME = {
+ '.html': 'text/html; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.mjs': 'text/javascript; charset=utf-8',
+ '.json': 'application/json; charset=utf-8',
+ '.md': 'text/plain; charset=utf-8',
+ '.txt': 'text/plain; charset=utf-8',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.ico': 'image/x-icon',
+ '.woff2': 'font/woff2',
+ '.woff': 'font/woff',
+ '.ttf': 'font/ttf',
+ '.otf': 'font/otf',
+ '.pdf': 'application/pdf',
+ '.mp4': 'video/mp4',
+ '.webm': 'video/webm',
+};
+
+const TEXT_EXT = new Set(['.html', '.css', '.js', '.mjs', '.json', '.md', '.txt', '.svg']);
+// What the lesson file panel may read: the workspace's own text files plus the
+// code a lesson links to. Serving over /w/ stays on TEXT_EXT above.
+const READABLE_EXT = new Set([
+ ...TEXT_EXT,
+ '.py', '.pyi', '.ts', '.tsx', '.jsx', '.java', '.kt', '.go', '.rs', '.rb', '.php',
+ '.c', '.h', '.cc', '.cpp', '.hpp', '.cs', '.swift', '.sh', '.bash', '.ps1',
+ '.yml', '.yaml', '.toml', '.ini', '.cfg', '.conf', '.sql', '.log',
+]);
+
+/**
+ * Lesson pages are generated from web research and run their own scripts, so
+ * they get a CSP that keeps rendering and quizzes working but forbids any
+ * network call back into this app's API (or anywhere else).
+ */
+const LESSON_CSP = [
+ "default-src 'none'",
+ "script-src 'self' 'unsafe-inline'",
+ "style-src 'self' 'unsafe-inline' https:",
+ "img-src 'self' data: https:",
+ "font-src 'self' data: https:",
+ "media-src 'self' data: https:",
+ "connect-src 'none'",
+ "form-action 'none'",
+ "base-uri 'none'",
+ "frame-ancestors 'self'",
+].join('; ');
+
+function json(response, status, body) {
+ const payload = JSON.stringify(body);
+ response.writeHead(status, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'content-length': Buffer.byteLength(payload),
+ });
+ response.end(payload);
+}
+
+function fail(response, status, code, message) {
+ json(response, status, { error: code, message: message ?? code });
+}
+
+function decodeParam(value) {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ const error = new Error('invalid_path');
+ error.code = 'INVALID_PATH';
+ throw error;
+ }
+}
+
+async function readBody(request, limit = 2_000_000) {
+ const chunks = [];
+ let size = 0;
+ for await (const chunk of request) {
+ size += chunk.length;
+ if (size > limit) {
+ const error = new Error('payload_too_large');
+ error.code = 'PAYLOAD_TOO_LARGE';
+ throw error;
+ }
+ chunks.push(chunk);
+ }
+ if (!chunks.length) return {};
+ try {
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ } catch {
+ const error = new Error('invalid_json');
+ error.code = 'INVALID_JSON';
+ throw error;
+ }
+}
+
+function errorStatus(error) {
+ switch (error?.code) {
+ case 'NOT_FOUND':
+ return 404;
+ case 'SETUP_REQUIRED':
+ case 'BUSY':
+ case 'ANSWER_PENDING':
+ case 'NO_QUESTION':
+ case 'NO_PERMISSION':
+ case 'TARGET_NOT_EMPTY':
+ return 409;
+ case 'PARENT_NOT_FOUND':
+ case 'NOT_A_WORKSPACE':
+ case 'TOPIC_REQUIRED':
+ case 'INVALID_JSON':
+ case 'HOME_NOT_ALLOWED':
+ case 'DRIVE_ROOT_NOT_ALLOWED':
+ case 'NO_LESSONS':
+ case 'PATH_OUTSIDE':
+ case 'INVALID_PATH':
+ case 'PAYLOAD_TOO_LARGE':
+ return 400;
+ case 'SESSION_CREATE_FAILED':
+ return 502;
+ default:
+ return 500;
+ }
+}
+
+export async function start(context) {
+ initStore(context.dataDir);
+ // The vocabulary guard runs on every start, so a module that grows its own
+ // copy of a workspace path does not wait for someone to remember the CLI.
+ let pathCheck = { ok: true, failures: [] };
+ try {
+ pathCheck = checkPaths();
+ } catch (error) {
+ pathCheck = { ok: false, failures: [`check-paths 无法运行:${error?.message ?? error}`] };
+ }
+ if (!pathCheck.ok) console.error(`[check-paths]\n${pathCheck.failures.join('\n')}`);
+ for (const workspace of await listWorkspaces()) {
+ await refreshRules(workspace.root).catch(() => {});
+ }
+ const clientRoot = path.join(context.pluginRoot, 'miniapp', 'client');
+ const surfaceHtml = await readFile(path.join(clientRoot, 'index.html'), 'utf8');
+
+ /** @type {Set} */
+ const clients = new Set();
+
+ const emit = (wsId, payload) => {
+ const frame = `data: ${JSON.stringify({ wsId, ...payload })}\n\n`;
+ for (const response of clients) {
+ try {
+ response.write(frame);
+ } catch {
+ clients.delete(response);
+ }
+ }
+ };
+
+ const warming = new Set();
+ let disposing = false;
+
+ const agent = createAgentService({
+ context,
+ emit,
+ onCurriculumImported: (ws) => {
+ void warmLessonSessions(ws);
+ },
+ });
+
+ async function warmLessonSessions(ws) {
+ const key = `warm:${ws.id}`;
+ if (warming.has(key) || disposing) return;
+ warming.add(key);
+ try {
+ const snap = await loadSnapshot(ws);
+ const pending = snap.curriculum.modules
+ .flatMap((module) => module.lessons)
+ .filter((lesson) => !lesson.sessionId);
+ for (let index = 0; index < pending.length; index += 3) {
+ if (disposing) break;
+ const batch = pending.slice(index, index + 3);
+ await Promise.all(
+ batch.map((lesson) =>
+ agent.openLesson(ws, lesson.id, { seed: false }).catch(() => undefined),
+ ),
+ );
+ }
+ if (!disposing) emit(ws.id, { t: 'state' });
+ } catch {
+ /* warming is best effort; a lesson session is created when it is opened */
+ } finally {
+ warming.delete(key);
+ }
+ }
+
+ async function requireWorkspace(id) {
+ const ws = await getWorkspace(id);
+ if (!ws) {
+ const error = new Error('workspace_not_found');
+ error.code = 'NOT_FOUND';
+ throw error;
+ }
+ return ws;
+ }
+
+ async function serveClient(response, pathname) {
+ if (pathname === SURFACE || pathname === '/' || pathname === '/index.html') {
+ response.writeHead(200, {
+ 'content-type': 'text/html; charset=utf-8',
+ 'cache-control': 'no-store',
+ });
+ response.end(surfaceHtml);
+ return true;
+ }
+ const name = pathname.slice(1);
+ if (!['app.css', 'app.js', 'lesson-bridge.js'].includes(name)) return false;
+ try {
+ const body = await readFile(path.join(clientRoot, name));
+ const type = MIME[path.extname(name)] ?? 'application/octet-stream';
+ response.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' });
+ response.end(body);
+ return true;
+ } catch {
+ fail(response, 404, 'client_asset_missing', name);
+ return true;
+ }
+ }
+
+ function injectBridge(html, { wsId, rel, lessonId, annotations }) {
+ const payload = JSON.stringify({
+ wsId,
+ rel,
+ lessonId,
+ annotations: annotations.map((item) => ({ id: item.id, quote: item.quote, note: item.note })),
+ }).replace(/window.__WB__=${payload};`;
+ if (/<\/body>/i.test(html)) return html.replace(/<\/body>/i, `${snippet}\n