diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 524ee84..5b04fa0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -14,11 +14,10 @@ concurrency:
cancel-in-progress: true
jobs:
- gates:
- name: 门禁 · ${{ matrix.os }}
+ build:
+ name: 类型与构建 · ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
- # Windows 是这个产品的主平台,不能只在 Linux 上验过就说能构建
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
@@ -31,95 +30,18 @@ jobs:
with:
python-version: '3.12'
- - name: 装 Python 依赖
- # G3 从 M1 起会真渲染一张图,matplotlib/numpy/seaborn 不能缺;
- # jsonschema 也在同一份 requirements 里。
- run: |
- python -m pip install --upgrade pip
- python -m pip install -r requirements.txt
-
- name: 准备 Node
uses: actions/setup-node@v4
with:
node-version: '22'
- # CI 不启动窗口,所以跳过 Electron 二进制下载(约 100 MB,纯浪费)。
- # 类型检查需要的 electron 类型仍随 npm 包一起装好。
- # lockfile 提交后这里换成 npm ci。
- name: 安装 JS 依赖
- run: npm install --no-audit --no-fund
+ run: npm ci --no-audit --no-fund
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: 1
- - name: G1 注册表一致性
- run: node scripts/check-registry.mjs
-
- - name: G1 反向覆盖(门禁必须能变红)
- run: node scripts/check-registry.negative.mjs
-
- - name: G8 技能规范(SKILL.md 仍是合法 Agent Skills 入口)
- run: node scripts/check-skills.mjs
-
- - name: G8 反向覆盖(6 种破坏必须被抓到)
- run: node scripts/check-skills.mjs --self
-
- - name: G6b 真启动核验器自测
- # 不需要真窗口:它自己造 10 份合成结果,验证「ok=true 但读数不对」「关键断言被删」都会红
- run: npm run verify:window:selftest
-
- - name: 装排版依赖(G4/G11 全链与 G10 都要真编 PDF,只在 ubuntu 跑)
- # 0.2.0 起通道/编排自检覆盖阶段五论文生成,需要 xelatex/pandoc;
- # 必须放在 G4 之前。Windows 的 gates job 不装 TeX(体积与时长不划算),
- # 下面的 G4/G11/G10 用 MMS_PAPER_SKIP=1 显式跳过排版断言并打印「未验证」。
- if: matrix.os == 'ubuntu-latest'
- run: |
- sudo apt-get update -q
- sudo apt-get install -yq pandoc texlive-xetex texlive-lang-chinese texlive-latex-extra
-
- - name: G4 通道自检(握手、鉴权、SSE、取消、续传)
- # 起真 Python 子进程和本地假 OpenAI 端点;不需要窗口、不联网、不需要 Key
- env:
- MMS_PAPER_SKIP: ${{ matrix.os == 'windows-latest' && '1' || '' }}
- run: python runtime/tests/selfcheck_channel.py
-
- - name: G4/G5 反向覆盖(坏事件、Key 泄漏、假 provider 关闭)
- run: python runtime/tests/selfcheck_channel.py --selftest
-
- - name: G2 契约校验与版本同源
- run: python scripts/validate-contracts.py
-
- - name: G3 CLI 退出码契约
- run: python runtime/tests/selfcheck.py
-
- - name: G11 编排状态机(起题、确认、换一批、选模、全链)
- env:
- MMS_PAPER_SKIP: ${{ matrix.os == 'windows-latest' && '1' || '' }}
- run: python runtime/tests/selfcheck_orchestrator.py
-
- - name: G11 反向覆盖(默认族写坏、关键词族清空必须变红)
- run: python runtime/tests/selfcheck_orchestrator.py --selftest
-
- - name: G12 长会话 harness(预算、压缩、摘要、锚点、50 轮)
- run: python runtime/tests/selfcheck_harness.py
-
- - name: G12 反向覆盖(拆掉压缩、关掉工具裁剪必须变红)
- run: python runtime/tests/selfcheck_harness.py --selftest
-
- - name: G13 附件 xlsx 读取(工作表、日期、上限与坏文件)
- run: npm run check:xlsx
-
- - name: G9 工作台(真渲两版、回滚、评分)
- run: python runtime/tests/selfcheck_workbench.py
-
- - name: G10 论文排版(xelatex → pandoc → 三道门禁)
- # Windows 的 gates job 不装 TeX/MiKTeX(体积与安装时长都不划算),显式跳过并在文档里记成未证;
- # 真启动冒烟的 job 在 ubuntu 上有 TeX,G7-9 会真编一遍。
- env:
- MMS_PAPER_SKIP: ${{ matrix.os == 'windows-latest' && '1' || '' }}
- run: python runtime/tests/selfcheck_paper.py
-
- - name: 运行时语法检查
- run: python -m compileall -q runtime
+ - name: 内核语法检查
+ run: python -m compileall -q modeling gateway
- name: 类型检查
run: npm run typecheck
@@ -127,85 +49,40 @@ jobs:
- name: 构建
run: npm run build
- - name: G6 产物冒烟
- run: node scripts/smoke-dist.mjs
-
- # M0 的判据是「照手册装完能起一个空窗」。这条 job 真下载 Electron、真启动、真截图并按像素断言,
- # 而不是停在「能构建」。gates 那条故意跳过二进制,所以这一段只能在这里补上。
window-smoke:
name: 真启动冒烟 · ubuntu
runs-on: ubuntu-latest
- needs: []
steps:
- uses: actions/checkout@v4
- name: 准备 Python
- # 主进程用 python3 拉起 runtime/cli.py serve;M4 工作台要真渲图,下面会装 requirements。
uses: actions/setup-python@v5
with:
python-version: '3.12'
- - name: 装图表依赖(工作台要真渲一张样例图)
- run: |
- python -m pip install --upgrade pip
- python -m pip install -r requirements.txt
-
- name: 准备 Node
uses: actions/setup-node@v4
with:
node-version: '22'
- name: 安装 JS 依赖(含 Electron 二进制)
- run: npm install --no-audit --no-fund
+ run: npm ci --no-audit --no-fund
- name: 构建
run: npm run build
- - name: 取回 Electron 二进制并打印实况
- # 上一轮 chmod 报 No such file or directory:npm install 之后 dist/ 里并没有二进制,
- # 它是等到首次 npx electron 才懒下载的(那一轮的日志里有 "Downloading Electron binary...")。
- # 所以先把二进制显式取回来,再把目录列出来——下次再挂就知道挂在哪儿,而不是猜。
- # 注意这一步不运行 electron:沙箱助手还没改权限,跑一次就会 FATAL 退出(上一轮就是这么挂的)。
- run: |
- # GitHub release 直链偶发 504(2026-11-08 连续多轮挂在同一 URL),重试三次再放弃。
- ok=0
- for attempt in 1 2 3; do
- if node node_modules/electron/install.js; then ok=1; break; fi
- echo "第 $attempt 次取回 Electron 失败,10 秒后重试"
- sleep 10
- done
- [ "$ok" = 1 ] || exit 1
- ls -l node_modules/electron/ | head -10
- ls -l node_modules/electron/dist/ | head -12
-
- name: 修好 Electron 的 SUID 沙箱助手
- # 不改就会 FATAL:setuid_sandbox_host(chrome-sandbox 需 root:4755)而进程在断言前就死。
- # 用 --no-sandbox 绕过也能跑,但那等于把生产窗口的 sandbox: true 排除在验证之外,
- # 所以这里选择把沙箱修好:preload 能在 sandbox 下工作,本身就是被 G7-3 的 IPC 断言验过的。
run: |
sudo chown root:root node_modules/electron/dist/chrome-sandbox
sudo chmod 4755 node_modules/electron/dist/chrome-sandbox
- ls -l node_modules/electron/dist/chrome-sandbox
npx electron --version
- - name: 准备 Xvfb、中文字体与排版工具
- # fonts-noto-cjk 不是可选装饰:runner 默认没有中文字体,整片界面会渲染成豆腐块,
- # 而「非白像素 ≥1%」这种断言照样能过。G7-5 现在会直接问字体在不在。
- # M5 起 G7-9 会真编一篇演示稿,所以 xelatex(texlive-xetex + 中文支持)与 pandoc 也要装。
- run: |
- sudo apt-get update -q
- sudo apt-get install -yq xvfb fonts-noto-cjk pandoc texlive-xetex texlive-lang-chinese texlive-latex-extra
-
- - name: G7 无头真启动与像素断言
- # 虚拟屏幕必须大于设计基准:屏幕正好 1440x900 时装不下带边框的窗口,
- # 内容区会被钳成 1439x899,于是 G7 的尺寸断言红在一件与产品无关的事上。
- run: xvfb-run -a --server-args="-screen 0 1600x1000x24" npx electron tests/window-smoke.cjs
-
- - name: G6b 独立核验真启动结果
- # 不靠上面那一步的退出码:上一轮就是 app.exit(1) 被生产入口的 app.quit() 顶掉,
- # 10/12 项通过却把 job 跑绿了。这里改读 screenshots/window-smoke.json 并复算读数。
- run: npm run verify:window
+ - name: 准备 Xvfb 与中文字体
+ run: sudo apt-get update -q && sudo apt-get install -yq xvfb fonts-noto-cjk
+
+ - name: 真启动与像素断言
+ run: xvfb-run -a --server-args="-screen 0 1600x1000x24" npx electron desktop/tests/window-smoke.cjs
- name: 上传截图与结果
if: always()
diff --git a/.gitignore b/.gitignore
index 217ad36..9c8fd36 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,7 +7,8 @@ release/
*.log
# Python
-runtime/.venv/
+modeling/.venv/
+gateway/.venv/
.venv/
__pycache__/
*.py[cod]
@@ -24,19 +25,9 @@ vendor/python/
vendor/pandoc/
vendor/*.zip
vendor/.downloads/
-# 冒烟产物由 CI 上传为 artifact;只挡这几个具体文件,
-# 免得将来要提交的界面截图(screenshots/*.png)被整目录规则一起吞掉
+# 冒烟产物由 CI 上传为 artifact
screenshots/window-smoke.png
screenshots/window-smoke.json
-screenshots/conversation.png
-screenshots/settings.png
-screenshots/decision.png
-screenshots/drawer.png
-screenshots/figure.png
-screenshots/score.png
-screenshots/dropzone.png
-screenshots/files.png
-screenshots/attachments.png
*.7z
*.dmg
*.exe
@@ -55,11 +46,8 @@ open-dev.lnk
.env.*
!.env.example
-# 建模工作区(阶段二产物,用户内容不入库)
-workspaces/
-第*题_*/
-# M3 会话状态(SQLite;不含 Key,但属于本机运行数据)
+# 无界面运行的默认输出目录(本机运行数据)
.mms/
# 编辑器与系统
@@ -68,4 +56,3 @@ workspaces/
.idea/
.DS_Store
Thumbs.db
-screenshots/paper.png
diff --git a/.npmrc b/.npmrc
index e3f5dd9..ec500cc 100644
--- a/.npmrc
+++ b/.npmrc
@@ -1,5 +1,5 @@
# Electron 与 electron-builder 的二进制从 npmmirror 取,避免 github.com/443 在大陆网络下随机翻转。
# 这两行只影响「下载哪个 zip」,不改变依赖解析来源;不在大陆的开发者可直接删掉。
-# 注意信任边界:镜像与官方同源同校验值,但下载通道换成了第三方,见 docs/env-setup.md。
+# 注意信任边界:镜像与官方同源同校验值,但下载通道换成了第三方;下载失败先换源再判死。
electron_mirror=https://npmmirror.com/mirrors/electron/
electron_builder_binaries_mirror=https://npmmirror.com/mirrors/electron-builder-binaries/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 180dada..994d492 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,25 @@
本项目遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 格式,版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
从 `0.1.0` 起,CLI 参数与退出码、注册表字段、产物路径为 Stable;`--json` 字段顺序与错误措辞仍为 Experimental。
+## Unreleased - 精简
+
+### 变更
+
+- **目录分层**:`modeling/`(数模领域)、`gateway/`(通用通道)与 `desktop/`(Electron 桌面端)分开,根目录只保留 npm workspace 入口、版本与法务文档;`server` 不再直接 import 流水线,改由入口注入 runner。
+- **技能包归位**:原 `skills/` 恢复到 `modeling/skills/`(core / methods / figure / diagram / paper / deai / score),作为领域资产保留;当前流水线尚未调用。
+- **前端重做(极简聊天式)**:左侧「工作区 → 对话」两级树(多工作区、多对话,本地持久化);首开中部欢迎文案与四步数模引导;中部对话流承载一次完整运行(进度、日志、求解图、PDF/Word)。核心流水线不变。
+- **一键流水线**:题面拆解 → 选模(自动采用推荐)→ 生成 `solution.py` → 运行与修复 ≤3 轮 → 论文生成与排版 ≤3 轮。删除七阶段人审卡、评分、雷达、门禁、会话恢复与工作台七页。
+- **单页界面**:一页三栏「赛题 / 进度 / 结果」,保留设置弹窗、离线模式、产物打开按钮;渲染层去掉 katex、pdfjs、markdown 依赖。
+- **运行时收敛**:删除技能包(`skills/`)、契约 schema、工作台图表/评分、长会话 harness、SQLite 会话库与七个自检;论文骨架与写作规范迁入 `modeling/src/mms_modeling/templates/`。
+- **依赖收敛**:Python 只留 `numpy`、`matplotlib`;Word 由 pandoc 直接转换,不再后处理 DOCX。
+- **通道与安全保留**:127.0.0.1 + Bearer token + Host/Origin 校验;Key 仍用 `safeStorage`,不落盘、不进事件。
+
+### 验证(本机 Windows,2026-11-23)
+
+- `npm run typecheck`、`npm run build` 通过;`npm run smoke:window` 12 项断言全绿(窗口、运行时握手、界面文本、墨迹占比)。
+- 离线全链:无界面 CLI 与桌面界面各跑一遍,5 阶段全通过,R²=0.997,PNG/PDF/SVG 与 paper.pdf/paper.docx 均生成,界面耗时 8.1s。
+- 未证:真实服务商 Key 的联网端到端;安装包未重新构建。
+
## 0.2.0 - 2026-11-15
数模模块真正跑通:七阶段全链由 LLM 驱动(配 Key 时),离线演示与失败回退保留;移除 DSH 双内核,工作台精简。
diff --git a/README.md b/README.md
index 60a86b0..7193981 100644
--- a/README.md
+++ b/README.md
@@ -1,204 +1,92 @@
-
MathModel Studio
+# MathModel Studio
-面向数学建模竞赛的本地桌面 Agent · 关键判断留给你
+桌面端数学建模工作台:输入赛题与数据,自动完成题面拆解、方法选择、求解代码生成与运行、论文排版。界面走极简聊天式:左侧「工作区 → 对话」树,中部对话流与首开欢迎引导,没有多级工作台与人工确认卡。
-
- 从赛题到论文,需要判断的地方都会停下来等你确认:
- 选模理由、方案解释、门禁结论和扣分明细都在界面上,可以追问,也可以回滚。
-
+## 工作流
-
-
-
-
-
-
-
-
-
+1. **题面拆解**:模型把赛题拆成子问题;模型不可用时按小节切分。
+2. **方法选择**:模型给出三条候选并标出推荐,直接采用推荐;失败时用内置方法族。
+3. **生成代码**:按题面、所选方法与数据画像生成 `solution.py`,契约固定为 `--data` / `--out`,须写出 `result.json` 与 `figure.png/pdf/svg`。
+4. **运行求解**:执行脚本;失败把 stderr 与上一版代码回喂模型,最多 3 轮。
+5. **论文排版**:按真实 `result.json` 与求解图写 `paper.tex`,xelatex 编译 PDF、pandoc 转 Word;编译失败回喂修复,最多 3 轮。
-
- 简体中文 · English
-
+所有论文数值只来自本次运行的 `result.json`。没有可用模型时进入离线模式:内置基线脚本 + 样例稿,事件与界面会标明兜底,不冒充按本题生成。
----
+## 运行方式
-
-
-
-
-通用模式:欢迎页与通用快捷提问,右侧只剩文件页图标
-
-> **设计原则**:能自动校验的交给门禁,需要判断的留给人,判断点做成界面。
->
-> 桌面程序内置一组技能(出版级图表、排版规范、AI 痕迹检查、结构自检与评分)。模型由使用者接入,数据不出本机。
-
-## 概览
-
-MathModel Studio 面向正在推进建模工作、准备交付的参赛者与研究者。它不替使用者做建模判断,但把阶段推进、选模、图表返工、论文排版和交付检查放在同一个工作台里,每一步都有记录。
-
-- **本地优先**:桌面端和 Python 运行时都在本机运行,模型 Key 用系统安全存储加密。
-- **人在环**:关键节点会停下来等确认;重启后仍停在原来的决策点。
-- **契约驱动**:技能由注册表、JSON Schema 和 CLI 退出码约束,界面按注册表生成,不写死技能清单。
-- **证据可复核**:每条门禁都有读数,并配反向用例。
-
-## 界面
-
-截图来自实际界面(1.5 倍像素密度):整行大图来自 1440×900 窗口,面板图裁自 1500×900 窗口。会话内容来自离线演示,没有真实赛题和密钥。
-
-
-
-K3 选模:三条候选附五维雷达(创新、解释、精度、速度、易做),越靠外越好,难度与耗时已反向
-
-| 过程总览与产物芯片 | 五维评分与扣分定位 |
-| --- | --- |
-| | |
-| 七阶段管线按状态着色,点芯片直达对应页 | 五维得分、扣分明细和正文定位 |
-
-
-
-论文:xelatex → pandoc → 三道交付门禁,pdf.js 页级预览
-
-
-
-对话:流式回复、折叠思考与工具卡在同一条时间线上
-
-## 当前状态
-
-**0.2.0(2026-11-15)**。数模模块真正跑通:配 Key 后七阶段全链由 LLM 驱动——K2 拆题面与核对数据角色、K3 按本题出选模候选(五维雷达对比,难度与耗时反向归一)、阶段四按题面与所选方法生成求解代码并经「代码确认卡」点运行才执行(失败回喂修复 ≤2 轮)、阶段五按真实结果写论文并过三道门禁、阶段六按 rubric 真实评分(总分 <85 回喂修复 ≤3 轮熔断,一票否决直接淘汰)。没有 Key 或模型不可用时回退确定性路径与演示样例,并在对话里明确标注兜底。默认进入通用对话,底部「通用 | 数模」分段切换;单 Python 内核(DSH 双内核已移除)。基础能力:多会话管理、五类模型入口(DeepSeek、通义千问、Kimi、智谱 GLM、OpenAI 格式端点)、200k / 400k / 1m 上下文预算、中 / 高 / 最大思维深度、附件读取与可收起的右侧工作台。
-
-论文页完成整条排版链路:xelatex 两遍 → pandoc 转 DOCX → Word 版式后处理 → 去 AI 措辞、结构指标和章节结构三道门禁;PDF 用 pdf.js 逐页预览。论文与评分按会话隔离,构建成功自动推进阶段五。
-
-打包已配置完成:electron-builder 把便携 Python 和 pandoc 一起装进安装包;0.2.0 的 NSIS x64 安装包尚未构建,干净机安装仍是未证项。
-
-里程碑见 [PLAN.md](docs/PLAN.md) §7;已验证结论与未证事项见 [docs/handoff.md](docs/handoff.md)。
-
-## 快速开始
-
-```bash
-# 安装依赖。大陆网络环境请先阅读 docs/env-setup.md:npm 直连与 github.com 均不稳定
-npm install
-python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
-
-# 启动桌面端。无 Key 时可加 MMS_FAKE_PROVIDER=1 使用离线演示
-MMS_FAKE_PROVIDER=1 npm run dev
-
-# 不接入模型也可验证运行时:列出 25 个模板并渲染一张图(PNG/PDF/SVG)
-npm run mms -- templates
-npm run mms -- invoke figure paired-raincloud
-
-# 运行全部本地门禁:注册表、技能规范、反向覆盖、类型检查、构建、产物冒烟、契约、CLI、通道、工作台与论文
-npm run gate
-```
-
-`npm run gate` 全部通过,表示本地门禁没有问题,且不依赖网络和显示器。论文自检需要本机安装 `xelatex` 和 `pandoc`(见「依赖」)。
-
-## 核心能力
-
-### 阶段编排与决策点
-
-阶段零到阶段六(环境预检、赛题分析、工作目录、算法选择、代码实现、论文输出、评分优化)排成一条状态轨道,当前卡在哪一步可以直接看到。关键节点用决策卡暂停:
-
-- **K2 赛题与附件确认**:拆出子问题,标明附件用途,逐问对应数据。
-- **K3 选模卡**:2–3 条候选路线,列出核心思路、创新度、可解释性、实现难度、预计耗时和精度预期,附五维雷达对比,可换一批。
-- **K4 就地解释**:打开解释抽屉,待选状态不丢。
-- **K5 图表返工**:换模板、换主题、重渲和回滚;重渲后只显示当前图,旧版本进入历史。
-- **K6 评分与优化轮次**:五维评分、扣分定位、三轮熔断和一票否决。
-
-数模模式的右侧工作台默认打开「过程总览」:七阶段管线按状态着色,每个阶段挂一条产物芯片(题面与附件、已选模型、图表版本、论文 PDF/DOCX、评分轮次),点芯片直达对应页;每次切入数模都回到这一页。
-
-### 会话与上下文
-
-左栏是会话列表:建模会话存在 SQLite,问答会话存在本地;可以新建、切换、单条删除和清空。切换时恢复消息、附件、阶段和待决卡。中栏顶部显示当前会话和上下文用量,按 200k / 400k / 1m 预算从最新消息往回装载。
-
-### 模型接入
-
-设置页按服务商列出五类入口,模型名可选预设或手动填写。Key 只经主进程 `safeStorage` 加密保存;未配置 Key 时可用离线演示。详见 [docs/providers.md](docs/providers.md)。
-
-### 图表与论文
-
-图表工作台调用真实渲染器输出 PNG/PDF/SVG,同时保留可复现的命令和运行日志。论文页完成 xelatex、pandoc、Word 版式后处理和三道交付门禁,PDF 用 pdf.js 逐页预览。
-
-### 文件与工作区
-
-「文件」页列出工作区内容,可以切换目录;工作区默认在桌面「赛题」,首次启动时创建。附件可以直接拖入中栏或粘贴,主进程负责抽取正文(PDF 用 pdfjs,文本和 CSV 直接读取并报告行列,xlsx 按工作表读成表格并识别日期,旧版 .xls 仍需另存)。
-
-## 架构
-
-
-
-
-桌面端和 Python 运行时通过本地回环通道(HTTP + SSE)通信,模型 Key 只由主进程加密保存。阶段在 K2–K6 决策点暂停,状态、待决卡和消息历史写入 SQLite,重启后可以恢复。
-
-## 技能矩阵
-
-技能清单以 [`skills/manifest.json`](skills/manifest.json) 为准;下表行数和徽章计数由 CI 校验,必须一致。
-
-| 技能 | 职责 | 状态 |
+| 方式 | 命令 | 说明 |
| --- | --- | --- |
-| [`mathmodel-core`](skills/mathmodel-core/) | 阶段零至阶段六编排与路由 | 内置 |
-| [`mathmodel-methods`](skills/mathmodel-methods/) | 建模方法库与选型:问题族索引、选型依据、验证方式 | 内置 |
-| [`mathmodel-paper`](skills/mathmodel-paper/) | 论文写作与排版:写作规范、LaTeX 骨架、Word 输出、参考文献 | 内置 |
-| [`mathmodel-figure`](skills/mathmodel-figure/) | 数据图表:matplotlib 模板库与 Nature 出图标准 | 内置 |
-| [`mathmodel-diagram`](skills/mathmodel-diagram/) | 学术示意图:JSON 驱动版式模板与高保真复刻 | 内置 |
-| [`mathmodel-deai`](skills/mathmodel-deai/) | 降 AI 与交付核查:词表级、结构级、字符级三道门禁 | 内置 |
-| [`mathmodel-score`](skills/mathmodel-score/) | 结构自检与评分:章节门槛与百分制五维评分卡 | 内置 |
+| 桌面开发 | `npm install` → `npm run dev` | 启动 Electron 与本地 Python 运行时 |
+| 无界面跑一遍 | `python modeling/cli.py run --problem-file 题面.txt [--data 数据.csv] [--out 目录]` | 事件按 JSON Lines 输出;默认离线模式 |
+| 类型检查 | `npm run typecheck` | 主进程、preload、渲染层全覆盖 |
+| 构建 | `npm run build` | 产物在 `desktop/out/` |
+| 真启动冒烟 | `npm run smoke:window` | 起生产入口,断言窗口、运行时与界面文本 |
+| 打包 | `npm run vendor:python`、`npm run vendor:pandoc` → `npm run dist:win` | 随包 Python 与 pandoc,输出 NSIS 安装包 |
-七个技能以源码随仓库分发(Apache-2.0),版本和引入记录见 [`skills/VENDOR.md`](skills/VENDOR.md)。运行时只通过 subprocess 调用技能脚本、按退出码判定,因此每个技能也能被 Claude Code 等宿主单独加载。
+## 环境要求
-## 质量门禁与证据
+- Node.js 22 及以上。
+- Python 3.12 及以上,并安装 `modeling/requirements.txt`(`numpy`、`matplotlib`)。
+- 生成 PDF 需要本机 `xelatex`;转 Word 需要 `pandoc`。缺失时求解结果仍保留,论文步骤会明确报缺。
+- 主平台为 Windows;macOS / Linux 可开发运行,未做安装包验证。
-每条门禁都配了反向用例:只会报通过的检查器不算证据。
+## 数据与隐私
-| 门禁 | 判据 | 反向覆盖 |
-| --- | --- | --- |
-| G1 注册表一致 | 注册表、技能目录、契约词表与两份 README 的技能表及徽章计数一致 | 8 种破坏逐项注入,必须变红(`npm run check:registry:negative`) |
-| G8 技能规范 | 每个技能的 `SKILL.md` 为合法 Agent Skills 入口:frontmatter 可解析、名称与目录一致、描述非空且在 1024 字内、无仓库私有字段 | 6 种基于真实文件的破坏必须变红(`npm run check:skills:negative`) |
-| G2 契约校验 | 注册表按 JSON Schema Draft 2020-12 校验;`jsonschema` 缺席时降级并说明 | 两份非法注册表必须被拒 |
-| G2b 版本同源 | `VERSION`、`package.json`、`pyproject.toml`、`mms/__init__.py` 四处一致 | 任一缺项或取值不同即失败 |
-| G3 CLI 契约 | 退出码 0/1/2 均可达;实际调用渲染器并核验 PNG/PDF/SVG 三件产物 | 词表外取值、非法 JSON、空 `MMS_HOME`、未知子命令/模板与渲染器假成功均被拦截(`runtime/tests/selfcheck.py`) |
-| G4 事件流 | 握手、Bearer token、回环 Host/Origin 白名单、九类 SSE 事件、续传与取消;覆盖 K2/K3 暂停恢复与进程重启后恢复、思维深度与上下文裁剪、代码确认卡与全链(论文+评分)事件契约(64 条) | 12 种坏事件必须被拒;无 token、错误 Host、无待决恢复均被拒(`python runtime/tests/selfcheck_channel.py --selftest`) |
-| G5 provider 离线契约 | 本地假端点覆盖 429 退避、`reasoning_content` 分离、分片 `tool_calls` 拼装、历史消息剥离和 Key 传递边界 | Key 哨兵不得进入事件流与 stderr;未开启离线模式时假 provider 被拒 |
-| G6 桌面骨架 | 类型检查、构建,并校验产物包含本项目中文文案与设计令牌 | 断言失败即退出 1(`scripts/smoke-dist.mjs`) |
-| G9 工作台 | 真实渲染两版图、版本历史与回滚,未知模板、主题或版本不会写入历史;三轮评分、扣分定位、章节样例和一票否决(19 条) | 未知模板/主题/版本均为反向控制(`runtime/tests/selfcheck_workbench.py`) |
-| G10 论文排版 | xelatex 两遍 → pandoc → Word 后处理:PDF/DOCX 文件头与体积、六个步骤、三道门禁、状态写入磁盘(12 条) | 缺件、坏稿、坏 TeX、缺稿件四条反向;`MMS_PAPER_SKIP=1` 才允许跳过并打印未验证 |
-| G11 编排状态机 | 起题、K2 确认、K3 换一批与选模、代码确认卡(未确认不执行、失败回喂)、阶段四五六全链(求解→论文 PDF/DOCX+三门禁→真实评分达标/否决);LLM 注入的坏 JSON 回喂与回退、选模落盘(34 条) | 默认方法族写成单元素元组、关键词族被清空两种破坏必须变红(`python runtime/tests/selfcheck_orchestrator.py --selftest`) |
-| G12 长会话 harness | 预算核算、工具结果先裁剪再结构化摘要、摘要本身有长度上限、二次压缩并入旧摘要、锚点每轮替换、溢出识别、单条超预算时从最早处丢;50 轮压到预算内且最近 6 条原文保留(14 条) | 拆掉压缩、关掉工具裁剪两种破坏必须变红(`python runtime/tests/selfcheck_harness.py --selftest`) |
-| G13 附件 xlsx | 解压工作簿读出全部工作表:共享字符串与富文本、稀疏列、布尔/错误值、公式缓存值、日期与时间格式(含 1904 日期系统);单表最多 300 行 × 60 列(10 条) | 非 ZIP 与缺工作簿两种坏文件必须报错;301 行的表必须截到 300 行(`npm run check:xlsx`) |
-| G7 真启动冒烟 | 以生产入口起窗,验证构建产物、1440×900、非白像素、IPC、中文真字形与 Key 不回显;覆盖 K2→K3→解释→选择→代码确认卡→运行、阶段四真跑与自动出图、图表重渲与回滚、评分、论文构建与预览、附件与 xlsx、工作区文件拖入与右键、多会话、五家预设、上下文与思维深度、通用/数模分段切换与按模式记住收合偏好、过程总览默认页与五维雷达、评分示例入口(116 条) | 空白截图、自建窗口、缺字(方框字形)和删除关键断言都会被拦截(`tests/window-smoke.cjs`) |
-| G6b 结果核验 | 读取冒烟 JSON 并复算读数:内容尺寸、非白像素、断言下限、关键断言与自述计数 | `--selftest` 用 12 份合成结果证明假通过会被拒(`scripts/check-window-smoke.mjs`) |
+- API Key 用系统安全存储(Electron `safeStorage`)加密保存,运行时按次传给本机进程;不落日志、不进事件、不写入运行目录。
+- 每次运行的代码、结果、论文都在用户数据目录的 `runs/<时间戳>/` 下,界面提供「打开 PDF」「打开 Word」「结果文件夹」。
+- 本地通道只绑定 `127.0.0.1`,每个请求校验随机 token 与 Host/Origin;主进程不把端口和 token 交给渲染层。
+- 服务商地址默认 https;自定义端点若用 http,只接受回环地址。
-## 验证状态
+## 配置服务商
-0.2.0 在本机(Windows)验证了类型检查、构建与完整 `npm run gate`(G4 64/64、G11 34/34、G12 14/14、G13 10/10、G9 19/19、G10 12/12):离线全链(fake provider)从题面 → 选模 → 代码确认 → 运行 → 论文 PDF/DOCX + 三门禁 → 评分达标,阶段 0–6 全 passed。G7 真启动本轮被本机环境阻塞(重启后 Electron 渲染进程挂起,疑似终端安全软件拦截),待环境恢复后复跑。
+设置弹窗内置 DeepSeek、通义千问、Kimi、智谱 GLM、OpenAI 格式端点与离线模式。预设模型与地址在 `gateway/src/mms_gateway/providers.json`,可自行增改。
-0.2.0 的 NSIS x64 安装包尚未构建;打包配置已把便携 Python 与 pandoc 接入。
+- 真实服务商需要填写模型名与 API Key。
+- 自定义端点填到 `/v1` 为止,公网必须 https。
+- 离线模式不需要 Key,用于先跑通整条链路。
-未覆盖范围:五家服务商的真实联网端到端(本仓库不包含 Key,需用户配 Key 后自跑)、G7 真启动(环境阻塞)、CI 的 Windows 真起窗、CSP 违规场景的主动探测、安装包在干净机器上的安装与运行。发布记录见 [CHANGELOG.md](CHANGELOG.md),发布格式见 [docs/release.md](docs/release.md)。
-
-## 依赖
-
-| 用途 | 依赖 | 说明 |
-| --- | --- | --- |
-| 桌面壳 | Electron、electron-vite、React、TypeScript | 见 `package.json` |
-| 运行时 | Python 3.12+ | 通道服务器、SSE 与 provider 客户端仅用标准库;`jsonschema>=4.20` 可选,缺席时契约校验降级 |
-| 模型接入 | DeepSeek、通义千问、Kimi、智谱 GLM 与任意 OpenAI 格式端点 | 见 [docs/providers.md](docs/providers.md);Key 经主进程 `safeStorage` 加密 |
-| 排版 | xelatex、pandoc、python-docx | xelatex 需本机安装(TeX Live 或 MiKTeX);pandoc 可随包提供,也可放进 PATH、设置 `MMS_PANDOC`,或安装到 `%LOCALAPPDATA%\mms-tools\pandoc.exe` |
-| 出图 | matplotlib、numpy、seaborn | 版本下限见 `requirements.txt`,安装使用镜像 |
-| 论文预览 | pdfjs-dist | 随 `npm install` 安装,worker 由 Vite 打包,运行时无需网络 |
+## 目录
-## 打包与分发
+根目录是 npm workspace,只做脚本转发;数模领域、通用通道与桌面端各自独立。
-打包已配置:内置便携 Python 运行时(python-build-standalone,放在 `vendor/python`,不入库),pandoc 以 `vendor/pandoc/pandoc.exe` 随包放进 `resources/pandoc`;xelatex 仍需本机安装,TeX 没有内置。NSIS x64 配置见 `electron-builder.yml`,随包工具链由 `scripts/prepare-vendor.mjs` 准备。应用、安装器与向导页头/侧栏图共用 `build/icon.svg` 生成的图标;安装包用自签名证书,证书根不受信任,SmartScreen 会提示未知发布者。
-
-## 参与贡献
-
-欢迎提交 Issue 与 Pull Request。报告问题请写清版本号、Windows 版本、复现步骤与相关日志;改代码或文档前建议先开 Issue 说明意图,避免重复劳动。提交前请在本机跑通 `npm run typecheck`、`npm run build` 与上文「质量门禁与证据」中对应的门禁,并在 PR 描述里写明改动动机与验证方式。本仓库以 AGPL-3.0-only 发布,提交 PR 即表示同意你的贡献按同一许可分发。
-
-## 合规声明
-
-本工具用于排版、出图、交付前自检和方法选型讨论,不代替建模判断,也不保证获奖。内置评分与结构自检默认采用国赛口径(对齐 2026 格式规范),美赛口径可通过参数切换;AI 痕迹检查仅清理模板腔与不可见字符,不将未完成的工作表述为已完成。伪造结果、编造文献与数据属于硬性红线。请遵守所在赛事对生成式工具的规定。
+```
+.
+├─ modeling/ 数模领域(不依赖 GUI)
+│ ├─ cli.py serve / run 入口,装配 modeling + gateway
+│ ├─ pyproject.toml
+│ ├─ requirements.txt
+│ ├─ skills/ 技能包:core / methods / figure / diagram / paper / deai / score
+│ └─ src/mms_modeling/
+│ ├─ pipeline.py 一键流水线
+│ ├─ baseline.py 数据画像、基线脚本、执行与产物收集
+│ ├─ paper_gen.py / paper_build.py 论文生成与排版
+│ └─ templates/ 论文骨架与写作规范
+│ (skills/ 是领域资产,当前一键流水线尚未调用)
+├─ gateway/ 通用通道(不依赖数模)
+│ ├─ pyproject.toml
+│ └─ src/mms_gateway/
+│ ├─ server.py 本机 HTTP + SSE 通道,runner 由外部注入
+│ ├─ provider.py OpenAI 兼容流式客户端
+│ ├─ llm.py JSON / 文本调用与重试
+│ └─ providers.json 预设服务商与模型
+├─ desktop/ Electron 桌面端
+│ ├─ src/
+│ │ ├─ main/ 通道、设置、文件选择、产物打开
+│ │ ├─ preload/ 窄 IPC 接口
+│ │ ├─ renderer/ 极简聊天式界面(工作区/对话树 + 欢迎引导 + 对话流)
+│ │ └─ shared/ 共享类型
+│ ├─ tests/window-smoke.cjs 真启动冒烟
+│ ├─ scripts/prepare-vendor.mjs 随包 Python / pandoc 准备
+│ ├─ build/ 图标与安装向导图
+│ ├─ electron.vite.config.ts
+│ ├─ electron-builder.yml
+│ ├─ package.json 桌面端依赖与脚本
+│ └─ tsconfig*.json
+├─ package.json npm workspace 入口
+├─ VERSION / LICENSE / THIRD_PARTY_NOTICES.md
+└─ vendor/ 随包 Python / pandoc(本机生成,不入库)
+```
## 许可
-[AGPL-3.0-only](LICENSE)。本仓库整体以 AGPL-3.0-only 发布;分发本软件或其修改版时,需按该许可提供对应源码。[`skills/`](skills/) 中的 Apache-2.0 文件保留原许可与版权声明,版本与出处记录见 [`skills/VENDOR.md`](skills/VENDOR.md)。
+AGPL-3.0-only。第三方组件与分发说明见 `THIRD_PARTY_NOTICES.md`。
diff --git a/README_EN.md b/README_EN.md
deleted file mode 100644
index d857d2e..0000000
--- a/README_EN.md
+++ /dev/null
@@ -1,200 +0,0 @@
-MathModel Studio
-
-A local desktop agent for mathematical modeling contests · a human-in-the-loop workbench
-
-
- From problem statement to paper, the judgement calls stay with the user:
- model rationale, explanations, gate verdicts and scoring details remain visible, queryable and reversible.
-
-
-
-
-
-
-
-
-
-
-
-
-
- 简体中文 · English
-
-
----
-
-
-
-
-
-General mode: welcome page with generic starters; the workspace pane is down to a files-only icon strip
-
-> **Design principle**: anything a machine can verify goes to a gate; anything that requires judgement stays with the user, with each decision point rendered as UI.
->
-> This tool integrates a contract-driven skill set (publication-grade figures, typesetting rules, AI-trace checks, structural audit and scoring) into a local desktop program: the model is provided by the user, data stays on the machine, and every step is auditable.
-
-## Overview
-
-MathModel Studio targets contestants and researchers who are already working through a modeling problem. It does not replace modeling judgement; it organizes phase progression, model selection, figure rework, paper typesetting and delivery checks into an auditable workflow.
-
-- **Local first**: the desktop shell and the Python runtime both execute on the local machine; model keys are encrypted with the system secure store.
-- **Human in the loop**: phase progression pauses at key decision points and waits for confirmation; pending state survives process restarts.
-- **Contract driven**: skills are constrained by a registry, JSON Schemas and CLI exit codes; the UI is generated from the registry rather than a hard-coded skill list.
-- **Reviewable evidence**: gates, scoring and CI assertions provide readings and negative coverage.
-
-## Interface
-
-Screenshots come from the real UI at 1.5× pixel density: full-row shots come from a 1440×900 window, panel crops come from a 1500×900 window. Conversation content comes from the offline demo and contains no real problem statement or key.
-
-
-
-K3 model choice: three candidates with a five-dimension radar (innovation, explainability, accuracy, speed, ease); difficulty and effort are inverted so the outer edge is always better
-
-| Process overview with artifact chips | Five-dimension score and deduction targets |
-| --- | --- |
-| | |
-| The seven-phase pipeline is colored by state; chips jump to the matching page | Five dimensions, deductions and in-text targets |
-
-
-
-Paper: xelatex → pandoc → three delivery gates, previewed page by page with pdf.js
-
-
-
-Conversation: streamed replies, collapsible thinking and tool cards on one timeline
-
-## Status
-
-**0.2.0 (2026-11-15)**. The modeling module now runs end to end: with an API key configured, the whole seven-phase track is LLM-driven — K2 parses the problem and checks data roles, K3 proposes model candidates for the actual problem (five-dimension radar comparison, difficulty and effort inverted so the outer edge is always better), phase four generates solver code from the problem and chosen method and only executes it after the user clicks Run on a code-confirmation card (failures are fed back for repair, up to 2 rounds), phase five writes the paper from the real results and passes three delivery gates, and phase six scores the paper against the rubric (total <85 feeds deductions back for revision, up to 3 rounds before the breaker; a veto disqualifies immediately). Without a key, or when the model is unavailable, the app falls back to deterministic paths and demo samples, clearly labelled as fallback in the conversation. The app opens in general chat with a "General | Modeling" switch; a single Python kernel remains (the DSH dual-kernel was removed). Core features remain: multi-conversation management, five provider entry types (DeepSeek, Qwen, Kimi, Zhipu GLM and OpenAI-format endpoints), 200k / 400k / 1m context budgets, medium / high / max thinking depth, attachment reading, and a collapsible right-hand workspace.
-
-The paper tab runs the full typesetting chain: xelatex twice → pandoc to DOCX → Word restyle → de-AI phrasing, structural metrics and chapter-structure gates; PDFs are previewed page by page with pdf.js. Paper and scoring are scoped per conversation, and a successful build advances phase five automatically.
-
-Packaging is wired up: electron-builder bundles a portable Python and pandoc; the 0.2.0 NSIS x64 installer has not been built yet, and clean-machine installation remains unverified.
-
-Milestones are listed in [PLAN.md](docs/PLAN.md) §7; verified claims and open items are recorded in [docs/handoff.md](docs/handoff.md).
-
-## Quick start
-
-```bash
-# Install. On mainland networks read docs/env-setup.md first: direct npm and github.com are both unreliable
-npm install
-python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
-
-# Launch the desktop app. Without a key, prefix MMS_FAKE_PROVIDER=1 for the offline demo
-MMS_FAKE_PROVIDER=1 npm run dev
-
-# Validate the runtime without a model: list 25 templates and render one figure (PNG/PDF/SVG)
-npm run mms -- templates
-npm run mms -- invoke figure paired-raincloud
-
-# Run every local gate: registry, skill spec, negative coverage, typecheck, build, dist smoke, contracts, CLI, channel, workbench and paper
-npm run gate
-```
-
-A passing `npm run gate` means the scaffold is self-consistent and needs neither network nor a display. The paper self-check requires `xelatex` and `pandoc` on the machine (see Dependencies).
-
-## Capabilities
-
-### Phase orchestration and decision points
-
-Phases zero to six (environment preflight, problem analysis, workspace layout, algorithm selection, implementation, paper output, scoring) are mapped onto a status track that shows where the agent is blocked. Key points pause as decision cards:
-
-- **K2 Problem and attachment confirmation**: subproblem decomposition, attachment and data roles, per-question data mapping.
-- **K3 Model-choice cards**: two to three candidates with core idea, novelty, explainability, implementation difficulty, estimated effort and accuracy expectations, plus a five-dimension radar comparison; reroll is supported.
-- **K4 In-place explanation**: opens an explanation drawer without clearing the pending choice.
-- **K5 Figure rework**: switch template or theme, re-render and roll back; after a re-render only the current version is shown and older versions move into history.
-- **K6 Scoring and optimization rounds**: five dimensions, deduction targets, a three-round circuit breaker and a veto example.
-
-In Modeling mode the workspace pane opens on the process overview by default: the seven-phase pipeline is colored by state, each phase carries an artifact chip (problem and attachments, chosen model, figure versions, paper PDF/DOCX, scoring rounds), and chips jump straight to the matching page; every entry into Modeling mode returns to this page.
-
-### Conversations and context
-
-The left rail is a conversation list: modeling sessions are read from SQLite and chat sessions are stored locally; sessions can be created, switched, deleted individually or cleared. Switching restores messages, attachments, phase and pending cards. The chat header shows the active conversation and context usage, loaded backwards from the latest message within a 200k / 400k / 1m budget.
-
-### Model access
-
-The settings page organizes five provider types in a list, with preset or manually entered model names. Keys are encrypted by the main process via `safeStorage`; the offline demo runs without a key. See [docs/providers.md](docs/providers.md).
-
-### Figures and papers
-
-The figure workbench calls the real renderer to produce PNG/PDF/SVG and keeps the reproducible command and run logs. The paper tab runs xelatex, pandoc, Word restyling and three delivery gates, with a pdf.js page preview.
-
-### Files and workspace
-
-The files tab lists the workspace and can switch directories; the default workspace is a `赛题` folder on the Desktop, created on first launch. Attachments can be dropped or pasted into the chat column; the main process extracts their text (pdfjs for PDFs, direct reads for text/CSV with row × column counts, and xlsx read sheet by sheet with date detection; legacy .xls still needs conversion).
-
-## Architecture
-
-
-
-
-The desktop shell and the Python runtime communicate over a loopback channel (HTTP + SSE); model keys are encrypted by the main process only. Phase progression pauses at K2–K6 decision points, and phase, pending cards and message history are persisted in SQLite so they survive process restarts.
-
-## Skills
-
-[`skills/manifest.json`](skills/manifest.json) is the single source of truth; the row count below and the badge count above are enforced equal by CI.
-
-| Skill | Responsibility | Status |
-| --- | --- | --- |
-| [`mathmodel-core`](skills/mathmodel-core/) | Orchestration and routing across phases 0–6 | built-in |
-| [`mathmodel-methods`](skills/mathmodel-methods/) | Method library and selection: problem-family index, rationale, verification | built-in |
-| [`mathmodel-paper`](skills/mathmodel-paper/) | Writing and typesetting: rules, LaTeX skeleton, Word output, references | built-in |
-| [`mathmodel-figure`](skills/mathmodel-figure/) | Data figures: matplotlib template library and Nature drawing standard | built-in |
-| [`mathmodel-diagram`](skills/mathmodel-diagram/) | Academic diagrams: JSON-driven layout templates and faithful replication | built-in |
-| [`mathmodel-deai`](skills/mathmodel-deai/) | De-AI and delivery checks: lexical, structural and character-level gates | built-in |
-| [`mathmodel-score`](skills/mathmodel-score/) | Structure audit and scoring: chapter gate and a 100-point five-dimension rubric | built-in |
-
-The seven skills ship as source with this repository (Apache-2.0); versions and import history are recorded in [`skills/VENDOR.md`](skills/VENDOR.md). The runtime only calls skill scripts via subprocess and reads their exit codes, so each skill remains independently loadable by hosts such as Claude Code.
-
-## Gates and evidence
-
-Every gate ships with negative coverage: a checker that only ever returns zero is not evidence.
-
-| Gate | Criterion | Negative control |
-| --- | --- | --- |
-| G1 registry consistency | registry, skill directories, contract vocabularies and both README skill tables and badge counts agree | eight seeded breakages, each must turn red (`npm run check:registry:negative`) |
-| G8 skill specification | every `SKILL.md` is a valid Agent Skills entry: parseable frontmatter, name matching the directory, non-empty description within 1024 characters, no repository-private fields | six breakages built from the real files must turn red (`npm run check:skills:negative`) |
-| G2 contract validation | registry validated against JSON Schema Draft 2020-12; degrades with a printed note when `jsonschema` is absent | two deliberately invalid registries must be rejected |
-| G2b version parity | `VERSION`, `package.json`, `pyproject.toml` and `mms/__init__.py` agree | any missing or differing value fails |
-| G3 CLI contract | exit codes 0/1/2 are reachable; the renderer is actually invoked and PNG/PDF/SVG artifacts are verified | out-of-vocabulary values, invalid JSON, empty `MMS_HOME`, unknown subcommands/templates and a renderer that fakes success are all rejected (`runtime/tests/selfcheck.py`) |
-| G4 event stream | handshake, Bearer token, loopback Host/Origin allow-list, nine SSE event types, replay and cancellation; covers K2/K3 pause-and-resume, cross-process recovery, thinking depth and context trimming, the code-confirmation card and full-chain (paper + scoring) event contracts (64 assertions) | twelve malformed events must be rejected; missing token, wrong Host and resuming without a pending decision are refused (`python runtime/tests/selfcheck_channel.py --selftest`) |
-| G5 provider offline contract | a local fake endpoint covers 429 backoff, `reasoning_content` separation, split `tool_calls` assembly, reasoning stripped from history and key transmission boundaries | key sentinels must never reach the event stream or stderr; the fake provider is refused when offline mode is off |
-| G6 desktop scaffold | typecheck and build, plus verification that the bundle contains this project's Chinese copy and design tokens | any failed assertion exits 1 (`scripts/smoke-dist.mjs`) |
-| G9 workbench | two real renders, version history and rollback, unknown template/theme/version rejected without adding a version; three scoring rounds, deduction targets, chapter sample and veto example (19 assertions) | unknown template/theme/version are negative controls (`runtime/tests/selfcheck_workbench.py`) |
-| G10 paper typesetting | xelatex twice → pandoc → Word restyle: PDF/DOCX magic and size, six steps, three gates and persisted state (12 assertions) | four negative controls (missing tools, bad paper, broken TeX, missing source); skipping requires `MMS_PAPER_SKIP=1` and prints that G10 was not verified |
-| G11 orchestration state machine | start, K2 confirmation, K3 reroll and choice, the code-confirmation card (no execution before confirmation, failure feedback), and the full phase 4/5/6 chain (solver → paper PDF/DOCX + three gates → real scoring pass/veto); LLM-injection bad-JSON retry and fallback, and persisting the chosen model (34 assertions) | two seeded breakages must turn red: the default family written as a one-element tuple, and the keyword families cleared (`python runtime/tests/selfcheck_orchestrator.py --selftest`) |
-| G12 long-session harness | budget accounting, tool-result pruning before a structured summary, a hard size cap on the summary itself, summaries merged across compactions, per-turn anchor replacement, overflow detection, and oldest-first dropping when a single message exceeds the budget; 50 rounds compacted under budget with the last six messages kept verbatim (14 assertions) | disabling compaction or tool pruning must turn red (`python runtime/tests/selfcheck_harness.py --selftest`) |
-| G13 attachment xlsx | unzips the workbook and reads every sheet: shared strings and rich text, sparse columns, booleans/errors, cached formula values, date and time formats (including the 1904 date system); at most 300 rows × 60 columns per sheet (10 assertions) | a non-ZIP file and a ZIP without a workbook must be rejected; a 301-row sheet must be cut to 300 rows (`npm run check:xlsx`) |
-| G7 real launch | launches the production entry and asserts built artifact, 1440×900, non-white pixels, IPC, real CJK glyphs and that keys are never echoed; covers K2→K3→explain→choose→code-confirmation→run, real phase four and automatic figure registration, figure re-render and rollback, scoring, paper build and preview, attachments and xlsx, workspace-file drag and context menu, multi-conversation, five provider presets, context and thinking depth, the General/Modeling segmented switch with per-mode collapse memory, the process-overview default page, the five-dimension radar and the score demo entry (116 assertions) | blank screenshots, self-built windows, tofu glyphs and deleted key assertions have all been caught (`tests/window-smoke.cjs`) |
-| G6b result audit | reads the smoke JSON and recomputes the readings: content size, non-white ratio, assertion floor, key assertions and self-reported counts | `--selftest` with 12 synthetic results proves that fake greens are rejected (`scripts/check-window-smoke.mjs`) |
-
-## Verification status
-
-Local verification for 0.2.0 (Windows) covers typecheck, build and the full `npm run gate` (G4 64/64, G11 34/34, G12 14/14, G13 10/10, G9 19/19, G10 12/12): the offline full chain (fake provider) runs problem → model choice → code confirmation → run → paper PDF/DOCX + three gates → scoring pass, with phases 0–6 all passed. The G7 real launch is blocked this round by a local environment issue (Electron renderer processes hang after a reboot; Edge works as a control), to be re-run once the environment is cleared.
-
-The 0.2.0 NSIS x64 installer has not been built yet; packaging bundles a portable Python and pandoc.
-
-Not covered: real networked end-to-end runs with any of the five providers (no key is included in this repository — configure your own key to run a real problem), the G7 real launch (environment-blocked), launching a window on Windows in CI, active probing of CSP violations, and installing/running the installer on a clean machine. Release records live in [CHANGELOG.md](CHANGELOG.md); the release format is specified in [docs/release.md](docs/release.md).
-
-## Dependencies
-
-| Purpose | Requirement | Note |
-| --- | --- | --- |
-| Desktop shell | Electron, electron-vite, React, TypeScript | see `package.json` |
-| Runtime | Python 3.12+ | the channel server, SSE and provider client are standard-library only; `jsonschema>=4.20` is optional and validation degrades without it |
-| Model access | DeepSeek, Qwen, Kimi, Zhipu GLM and any OpenAI-format endpoint | see [docs/providers.md](docs/providers.md); keys are encrypted by the main process via `safeStorage` |
-| Typesetting | xelatex, pandoc, python-docx | xelatex requires a local install (TeX Live or MiKTeX); pandoc may be bundled, placed on PATH, pointed to by `MMS_PANDOC`, or installed at `%LOCALAPPDATA%\mms-tools\pandoc.exe` |
-| Figures | matplotlib, numpy, seaborn | lower bounds are in `requirements.txt`; install via a mirror |
-| Paper preview | pdfjs-dist | installed by `npm install`; the worker is bundled by Vite and needs no network at runtime |
-
-## Packaging and distribution
-
-Packaging is decided and wired up: a portable Python runtime is bundled (python-build-standalone under `vendor/python`, not committed), and pandoc ships as `vendor/pandoc/pandoc.exe` under `resources/pandoc`; xelatex still requires a local install and TeX is not bundled. The NSIS x64 configuration lives in `electron-builder.yml`, and the bundled toolchain is prepared by `scripts/prepare-vendor.mjs`. The current installer is unsigned and uses the default Electron icon.
-
-## Compliance
-
-This tool assists modeling work that has already been done: typesetting, publication-grade figures, pre-delivery self-audit and method-selection discussion. It does not replace modeling judgement and does not promise an award. The bundled scoring and structure checks default to the Chinese national contest rubric (aligned to the 2026 format rules) and can be switched to MCM/ICM; AI-trace checks only remove template phrasing and invisible characters and never present unperformed work as performed. Fabricating results, references or data is a hard red line. Follow your own contest's rules on generative tools.
-
-## License
-
-[AGPL-3.0-only](LICENSE). This repository is released as a whole under AGPL-3.0-only; distributing the software or a modified version requires providing the corresponding source under that license. Files under [`skills/`](skills/) that are Apache-2.0 retain their original license and notices; versions and provenance are recorded in [`skills/VENDOR.md`](skills/VENDOR.md).
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index cb2d52e..02dca2e 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -4,7 +4,7 @@
## 本仓库许可
-本仓库整体以 AGPL-3.0-only 发布,全文见 `LICENSE`;分发本软件或其修改版时,需按 AGPL-3.0 提供对应源码。`skills/` 下的技能文件原以 Apache-2.0 发布,作为整体分发作品的一部分保留原许可与版权声明,出处见 `skills/VENDOR.md`。
+本仓库整体以 AGPL-3.0-only 发布,全文见 `LICENSE`;分发本软件或其修改版时,需按 AGPL-3.0 提供对应源码。
| 组件 | 用途 | 许可 | 来源 |
| --- | --- | --- | --- |
@@ -12,18 +12,13 @@
| Chromium | Electron 渲染引擎 | BSD-3-Clause 等 | https://www.chromium.org |
| Node.js | Electron 内置运行时 | MIT | https://nodejs.org |
| React / ReactDOM | 渲染层 | MIT | https://github.com/facebook/react |
-| pdfjs-dist | PDF 预览 | Apache-2.0 | https://github.com/mozilla/pdf.js |
| Python(python-build-standalone) | 内置解释器 | PSF-2.0 | https://github.com/astral-sh/python-build-standalone |
| pandoc | Word 转换 | GPL-2.0-or-later | https://github.com/jgm/pandoc |
| matplotlib | 图表渲染 | Matplotlib License(PSF 派生) | https://github.com/matplotlib/matplotlib |
| numpy | 数值计算 | BSD-3-Clause | https://github.com/numpy/numpy |
-| seaborn | 统计图样式 | BSD-3-Clause | https://github.com/mwaskom/seaborn |
-| python-docx | DOCX 后处理 | MIT | https://github.com/python-openxml/python-docx |
-| jsonschema | 契约校验 | MIT | https://github.com/python-jsonschema/jsonschema |
-| PyMuPDF(fitz) | PDF 文本抽取 | AGPL-3.0 或 Artifex 商业许可(双许可) | https://github.com/pymupdf/PyMuPDF |
## 分发说明
- **Electron / Chromium**:完整许可文本随安装包提供,位于安装目录的 `LICENSE.electron.txt` 与 `LICENSES.chromium.html`。
- **pandoc(GPL-2.0-or-later)**:安装包随附二进制,许可全文见 `licenses/pandoc-COPYING.md`,版权与贡献者信息见 `licenses/pandoc-COPYRIGHT`;对应源码可从上游仓库获取。GPL-2.0-or-later 与 AGPLv3 兼容,随 AGPL-3.0-only 作品分发时保留本许可文本与源码获取方式即可。
-- **PyMuPDF(AGPL-3.0 / 商业许可)**:PyMuPDF 以 AGPL-3.0 或 Artifex 商业许可双许可发布。本仓库整体采用 AGPL-3.0-only,分发安装包时按 AGPL-3.0 提供对应源码(公开仓库与构建脚本即满足该义务);如需在闭源或非 AGPL 条件下分发,应取得 Artifex 商业许可,或改用宽松许可的 PDF 实现。
+- **PDF 排版**:论文 PDF 由系统或随包安装的 xelatex 生成,不随包分发 TeX 发行版;使用环境需自行安装并遵守其许可。
diff --git a/build/icon.ico b/desktop/build/icon.ico
similarity index 100%
rename from build/icon.ico
rename to desktop/build/icon.ico
diff --git a/build/icon.png b/desktop/build/icon.png
similarity index 100%
rename from build/icon.png
rename to desktop/build/icon.png
diff --git a/build/icon.svg b/desktop/build/icon.svg
similarity index 100%
rename from build/icon.svg
rename to desktop/build/icon.svg
diff --git a/build/installer.nsh b/desktop/build/installer.nsh
similarity index 100%
rename from build/installer.nsh
rename to desktop/build/installer.nsh
diff --git a/build/installerHeader.bmp b/desktop/build/installerHeader.bmp
similarity index 100%
rename from build/installerHeader.bmp
rename to desktop/build/installerHeader.bmp
diff --git a/build/installerSidebar.bmp b/desktop/build/installerSidebar.bmp
similarity index 100%
rename from build/installerSidebar.bmp
rename to desktop/build/installerSidebar.bmp
diff --git a/electron-builder.yml b/desktop/electron-builder.yml
similarity index 57%
rename from electron-builder.yml
rename to desktop/electron-builder.yml
index 3d9a310..e722535 100644
--- a/electron-builder.yml
+++ b/desktop/electron-builder.yml
@@ -1,8 +1,8 @@
-# electron-builder 配置(M6)
+# electron-builder 配置(桌面端)
#
-# 资源布局:runtime/skills/schemas/VERSION/python/pandoc 都放在 resources/ 下,
-# 与 src/main/runtime-env.ts 的 APP_ROOT 对齐;app.asar 里只放 JS 产物。
-# vendor/python 与 vendor/pandoc 由 scripts/prepare-vendor.mjs 准备,不入库。
+# 资源布局:modeling/gateway/VERSION/python/pandoc 放在 resources/ 下,
+# 与 desktop/src/main/runtime-env.ts 的 APP_ROOT 对齐;app.asar 里只放 JS 产物。
+# vendor/python 与 vendor/pandoc 由 scripts/prepare-vendor.mjs 准备到仓库根 vendor/,不入库。
appId: cn.escap1ng.mathmodel-studio
productName: MathModel Studio
copyright: Copyright © 2026 Escap1ng
@@ -19,36 +19,33 @@ electronLanguages:
files:
- out/**/*
- package.json
- - node_modules/pdfjs-dist/**/*
extraResources:
- - from: runtime
- to: runtime
+ - from: ../modeling
+ to: modeling
filter:
- "**/*"
- "!**/__pycache__/**"
- "!**/*.pyc"
- - from: skills
- to: skills
- - from: schemas
- to: schemas
- - from: VERSION
+ - from: ../gateway
+ to: gateway
+ filter:
+ - "**/*"
+ - "!**/__pycache__/**"
+ - "!**/*.pyc"
+ - from: ../VERSION
to: VERSION
- - from: LICENSE
+ - from: ../LICENSE
to: LICENSE.txt
- - from: THIRD_PARTY_NOTICES.md
+ - from: ../THIRD_PARTY_NOTICES.md
to: THIRD_PARTY_NOTICES.md
- - from: licenses
+ - from: ../licenses
to: licenses
- - from: vendor/python
+ - from: ../vendor/python
to: python
- - from: vendor/pandoc/pandoc.exe
+ - from: ../vendor/pandoc/pandoc.exe
to: pandoc/pandoc.exe
-# 主进程用 createRequire 加载 pdfjs 的 legacy 构建,从 asar 里读 worker/字体不稳。
-asarUnpack:
- - node_modules/pdfjs-dist/**
-
win:
target:
- target: nsis
@@ -60,8 +57,7 @@ nsis:
# build/installer.nsh 自动被 include,负责把默认安装目录改成桌面的 MathModel Studio。
installerIcon: build/icon.ico
uninstallerIcon: build/icon.ico
- # 向导内两张图由 scripts/make-icon.mjs 从 build/icon.svg 生成;assisted 模式下
- # installerHeaderIcon 不生效(只在 oneClick 分支读取),页头图要靠 installerHeader。
+ # 页头/侧栏图已入库;assisted 模式只读 installerHeader/installerSidebar。
installerHeader: installerHeader.bmp
installerSidebar: installerSidebar.bmp
oneClick: false
diff --git a/electron.vite.config.ts b/desktop/electron.vite.config.ts
similarity index 100%
rename from electron.vite.config.ts
rename to desktop/electron.vite.config.ts
diff --git a/desktop/package.json b/desktop/package.json
new file mode 100644
index 0000000..e7ec1e0
--- /dev/null
+++ b/desktop/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "mathmodel-studio",
+ "version": "0.2.0",
+ "private": true,
+ "description": "数学建模桌面工作台:题面 → 选模 → 代码 → 论文",
+ "author": "Escap1ng",
+ "license": "AGPL-3.0-only",
+ "main": "out/main/index.js",
+ "scripts": {
+ "dev": "electron-vite dev",
+ "build": "electron-vite build",
+ "preview": "electron-vite preview",
+ "typecheck": "tsc -p tsconfig.node.json --noEmit && tsc -p tsconfig.web.json --noEmit",
+ "pack:win": "npm run build && electron-builder --win --dir",
+ "dist:win": "npm run build && electron-builder --win nsis",
+ "vendor:python": "node scripts/prepare-vendor.mjs python",
+ "vendor:pandoc": "node scripts/prepare-vendor.mjs pandoc"
+ },
+ "devDependencies": {
+ "@types/node": "^26.6.5",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "@vitejs/plugin-react": "^6.1.2",
+ "electron": "^44.8.0",
+ "electron-builder": "^26.18.0",
+ "electron-vite": "^6.0.0",
+ "react": "^19.3.1",
+ "react-dom": "^19.3.1",
+ "typescript": "^7.0.2",
+ "vite": "^8.3.4"
+ }
+}
diff --git a/scripts/prepare-vendor.mjs b/desktop/scripts/prepare-vendor.mjs
similarity index 95%
rename from scripts/prepare-vendor.mjs
rename to desktop/scripts/prepare-vendor.mjs
index e32e039..584d67e 100644
--- a/scripts/prepare-vendor.mjs
+++ b/desktop/scripts/prepare-vendor.mjs
@@ -6,9 +6,9 @@
* node scripts/prepare-vendor.mjs pandoc [--force]
*
* python: python-build-standalone 的解压版解释器(npmmirror 通道)解到 vendor/python,
- * 再按 requirements.txt 装依赖,最后逐个 import 自检。
+ * 再装 numpy 与 matplotlib,最后逐个 import 自检。
* pandoc: 把本机 pandoc.exe 复制到 vendor/pandoc。pandoc 是 GPL-2.0-or-later,
- * 随安装包分发时需要保留上游许可与源码指引(见 docs/env-setup.md)。
+ * 随安装包分发时需要保留上游许可与源码指引(见 THIRD_PARTY_NOTICES.md)。
*
* 下载地址与版本都在下面常量里,换版本时改这两行;失败先换通道再下结论。
*/
@@ -19,7 +19,8 @@ import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
-const VENDOR = join(ROOT, 'vendor')
+const REPO = resolve(ROOT, '..')
+const VENDOR = join(REPO, 'vendor')
const PBS_TAG = process.env['MMS_PBS_TAG'] || '20261026'
const PY_VERSION = process.env['MMS_PY_VERSION'] || '3.12.16'
@@ -35,7 +36,7 @@ const PY_DIR = join(VENDOR, 'python')
const PY_EXE = join(PY_DIR, 'python.exe')
const PANDOC_DIR = join(VENDOR, 'pandoc')
const PANDOC_EXE = join(PANDOC_DIR, 'pandoc.exe')
-const MODULES = ['matplotlib', 'numpy', 'seaborn', 'docx', 'fitz', 'jsonschema']
+const MODULES = ['matplotlib', 'numpy']
function log(message) {
console.log(`[vendor] ${message}`)
@@ -132,7 +133,7 @@ async function preparePython(force) {
const version = run(PY_EXE, ['-c', 'import sys; print(sys.version)'], { stdio: 'pipe' })
log(`解释器就绪:${String(version.stdout).trim().split('\n')[0]}`)
- log(`安装 requirements.txt(索引 ${PIP_INDEX})`)
+ log(`安装 modeling/requirements.txt(索引 ${PIP_INDEX})`)
run(PY_EXE, [
'-m',
'pip',
@@ -140,7 +141,7 @@ async function preparePython(force) {
'--disable-pip-version-check',
'--no-warn-script-location',
'-r',
- join(ROOT, 'requirements.txt'),
+ join(REPO, 'modeling', 'requirements.txt'),
'-i',
PIP_INDEX
])
diff --git a/desktop/src/main/channel.ts b/desktop/src/main/channel.ts
new file mode 100644
index 0000000..29ac5bd
--- /dev/null
+++ b/desktop/src/main/channel.ts
@@ -0,0 +1,243 @@
+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
+import { join } from 'node:path'
+import type { RunEvent, RuntimeStatus } from '../shared/api'
+
+// 与 gateway/src/mms_gateway/server.py 的握手契约。渲染层永远拿不到 port 与 token。
+export interface ChannelHandshake {
+ port: number
+ token: string
+ pid: number
+ fake: boolean
+ version: string
+}
+
+export interface RuntimeProvider {
+ id: string
+ display: string
+ models: string[]
+ model: string
+ base_url: string
+ requires_key: boolean
+ custom: boolean
+ note?: string
+}
+
+interface RunBody {
+ problem: string
+ dataPaths: string[]
+ provider: { id: string; model: string; baseUrl?: string; apiKey: string }
+}
+
+export class Channel {
+ private child: ChildProcessWithoutNullStreams | null = null
+ private handshake: ChannelHandshake | null = null
+ private status: RuntimeStatus = { state: 'starting' }
+ private readonly listeners = new Set<(s: RuntimeStatus) => void>()
+ private startPromise: Promise | null = null
+ private stopping = false
+
+ constructor(
+ private readonly root: string,
+ private readonly python: string,
+ private readonly dataDir?: string
+ ) {}
+
+ onStatus(cb: (s: RuntimeStatus) => void): () => void {
+ this.listeners.add(cb)
+ return () => this.listeners.delete(cb)
+ }
+
+ current(): RuntimeStatus {
+ return this.status
+ }
+
+ private setStatus(next: RuntimeStatus): void {
+ this.status = next
+ for (const cb of this.listeners) cb(next)
+ }
+
+ start(): Promise {
+ if (this.handshake) return Promise.resolve()
+ if (this.startPromise) return this.startPromise
+ this.stopping = false
+ this.startPromise = this.launch().finally(() => {
+ this.startPromise = null
+ })
+ return this.startPromise
+ }
+
+ async restart(): Promise {
+ this.stop()
+ await this.start()
+ }
+
+ private async launch(): Promise {
+ this.setStatus({ state: 'starting' })
+ const child = spawn(this.python, [join(this.root, 'modeling', 'cli.py'), 'serve', '--port', '0'], {
+ cwd: this.root,
+ windowsHide: true,
+ env: {
+ ...process.env,
+ MMS_HOME: this.root,
+ ...(this.dataDir ? { MMS_DATA_DIR: this.dataDir } : {}),
+ MMS_PYTHON: this.python,
+ ...(this.dataDir ? { PYTHONPYCACHEPREFIX: join(this.dataDir, 'pycache') } : {}),
+ PYTHONIOENCODING: 'utf-8',
+ PYTHONUTF8: '1'
+ }
+ })
+ this.child = child
+
+ try {
+ const handshake = await this.readHandshake(child)
+ if (this.child !== child) throw new Error('runtime 启动被新的启动请求取代')
+ this.handshake = handshake
+ this.setStatus({ state: 'ready', version: handshake.version })
+
+ child.stdout.on('data', (chunk: Buffer) => {
+ const text = chunk.toString('utf8').trim()
+ if (text) console.warn('[runtime stdout]', text.slice(0, 500))
+ })
+ child.stderr.on('data', (chunk: Buffer) => {
+ const text = chunk.toString('utf8').trim()
+ if (text) console.warn('[runtime]', text.slice(0, 500))
+ })
+ child.on('exit', (code) => {
+ if (this.child !== child) return
+ this.child = null
+ this.handshake = null
+ if (!this.stopping) {
+ this.setStatus({ state: 'error', message: `runtime 已退出(code ${code ?? '?'})` })
+ }
+ })
+ } catch (err) {
+ child.kill()
+ this.child = null
+ this.handshake = null
+ const message = err instanceof Error ? err.message : String(err)
+ if (!this.stopping) this.setStatus({ state: 'error', message })
+ throw err
+ }
+ }
+
+ private readHandshake(child: ChildProcessWithoutNullStreams): Promise {
+ return new Promise((resolve, reject) => {
+ let buffer = ''
+ const timer = setTimeout(() => {
+ cleanup()
+ reject(new Error('runtime 握手超时'))
+ }, 20_000)
+ const cleanup = (): void => {
+ clearTimeout(timer)
+ child.stdout.off('data', onData)
+ child.off('exit', onExit)
+ }
+ const onData = (chunk: Buffer): void => {
+ buffer += chunk.toString('utf8')
+ const index = buffer.indexOf('\n')
+ if (index < 0) return
+ const line = buffer.slice(0, index).trim()
+ cleanup()
+ try {
+ resolve(JSON.parse(line) as ChannelHandshake)
+ } catch {
+ reject(new Error('runtime 握手不是合法 JSON'))
+ }
+ }
+ const onExit = (code: number | null): void => {
+ cleanup()
+ reject(new Error(`runtime 启动即退出(code ${code ?? '?'})`))
+ }
+ child.stdout.on('data', onData)
+ child.on('exit', onExit)
+ })
+ }
+
+ private async request(method: string, path: string, body?: unknown): Promise {
+ await this.start()
+ const handshake = this.handshake
+ if (!handshake) throw new Error('runtime 未就绪')
+ const response = await fetch(`http://127.0.0.1:${handshake.port}${path}`, {
+ method,
+ headers: {
+ Authorization: `Bearer ${handshake.token}`,
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {})
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined
+ })
+ const text = await response.text()
+ let data: unknown
+ try {
+ data = JSON.parse(text)
+ } catch {
+ throw new Error(`runtime 返回非 JSON(HTTP ${response.status})`)
+ }
+ const payload = data as { ok?: boolean; error?: { message?: string } }
+ if (!response.ok || payload.ok === false) {
+ throw new Error(payload.error?.message || `HTTP ${response.status}`)
+ }
+ return data as T
+ }
+
+ async providers(): Promise<{ ok: true; providers: RuntimeProvider[] }> {
+ return this.request('GET', '/providers')
+ }
+
+ async startRun(body: RunBody): Promise<{ ok: true; runId: string }> {
+ return this.request('POST', '/runs', body)
+ }
+
+ async cancelRun(runId: string): Promise<{ ok: true }> {
+ return this.request('POST', `/runs/${encodeURIComponent(runId)}/cancel`)
+ }
+
+ async stream(runId: string, cb: (event: RunEvent) => void, signal: AbortSignal): Promise {
+ await this.start()
+ const handshake = this.handshake
+ if (!handshake) throw new Error('runtime 未就绪')
+ const response = await fetch(
+ `http://127.0.0.1:${handshake.port}/runs/${encodeURIComponent(runId)}/events`,
+ { headers: { Authorization: `Bearer ${handshake.token}` }, signal }
+ )
+ if (!response.ok || !response.body) throw new Error(`事件流打开失败(HTTP ${response.status})`)
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let buffer = ''
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+ buffer += decoder.decode(value, { stream: true })
+ let index: number
+ while ((index = buffer.indexOf('\n\n')) >= 0) {
+ const frame = buffer.slice(0, index)
+ buffer = buffer.slice(index + 2)
+ this.parseFrame(frame, runId, cb)
+ }
+ }
+ }
+
+ private parseFrame(frame: string, runId: string, cb: (event: RunEvent) => void): void {
+ let id = '0'
+ let event = 'message'
+ let data = ''
+ for (const line of frame.split('\n')) {
+ if (line.startsWith('id:')) id = line.slice(3).trim()
+ else if (line.startsWith('event:')) event = line.slice(6).trim()
+ else if (line.startsWith('data:')) data += line.slice(5).trim()
+ }
+ if (!data) return
+ try {
+ cb({ runId, id, event, data: JSON.parse(data) as Record })
+ } catch {
+ // 坏帧只跳过,不打断流
+ }
+ }
+
+ stop(): void {
+ this.stopping = true
+ const child = this.child
+ this.child = null
+ this.handshake = null
+ if (child) child.kill()
+ }
+}
diff --git a/desktop/src/main/files.ts b/desktop/src/main/files.ts
new file mode 100644
index 0000000..1215a06
--- /dev/null
+++ b/desktop/src/main/files.ts
@@ -0,0 +1,30 @@
+import { dialog, type BrowserWindow } from 'electron'
+import { readFileSync } from 'node:fs'
+import type { ProblemFile } from '../shared/api'
+
+const MAX_PROBLEM_CHARS = 200_000
+
+export async function pickProblemFile(win: BrowserWindow | null): Promise {
+ const options = {
+ title: '选择题面文件',
+ properties: ['openFile' as const],
+ filters: [{ name: '题面文本', extensions: ['txt', 'md', 'tex'] }]
+ }
+ const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options)
+ if (result.canceled || result.filePaths.length === 0) return null
+ const path = result.filePaths[0]
+ const text = readFileSync(path, 'utf8')
+ if (text.length > MAX_PROBLEM_CHARS) throw new Error('题面文件过大(超过 20 万字符)')
+ return { path, text }
+}
+
+export async function pickDataFiles(win: BrowserWindow | null): Promise {
+ const options = {
+ title: '选择数据文件',
+ properties: ['openFile' as const],
+ filters: [{ name: '表格数据', extensions: ['csv', 'tsv'] }]
+ }
+ const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options)
+ if (result.canceled) return []
+ return result.filePaths.slice(0, 1)
+}
diff --git a/desktop/src/main/index.ts b/desktop/src/main/index.ts
new file mode 100644
index 0000000..b493f77
--- /dev/null
+++ b/desktop/src/main/index.ts
@@ -0,0 +1,301 @@
+import { app, BrowserWindow, ipcMain, Menu, shell, type WebContents } from 'electron'
+import { readFileSync } from 'node:fs'
+import { join, relative, isAbsolute } from 'node:path'
+import { APP_ROOT, runtimePython } from './runtime-env'
+import { Channel, type RuntimeProvider } from './channel'
+import { pickDataFiles, pickProblemFile } from './files'
+import {
+ activeProviderId,
+ apiKeyFor,
+ clearProviderKey,
+ publicProviders,
+ saveProvider
+} from './settings'
+import type {
+ ProviderList,
+ ProviderView,
+ RunEvent,
+ RunInput,
+ RuntimeStatus,
+ SaveProviderInput
+} from '../shared/api'
+
+// 开发时 electron-vite 会注入 ELECTRON_RENDERER_URL;打包后走 out/renderer/index.html。
+const DEV_SERVER_URL = process.env['ELECTRON_RENDERER_URL']
+const RUNS_ROOT = join(app.getPath('userData'), 'runs')
+const channel = new Channel(APP_ROOT, runtimePython(), app.getPath('userData'))
+const activeStreams = new Map()
+
+channel.onStatus((status: RuntimeStatus) => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) win.webContents.send('runtime:status', status)
+ }
+})
+
+async function providerViews(): Promise {
+ const { providers } = await channel.providers()
+ const saved = publicProviders()
+ const views: ProviderView[] = providers.map((row: RuntimeProvider) => {
+ const stored = saved[row.id]
+ const models = row.models ?? []
+ return {
+ id: row.id,
+ display: row.display,
+ models,
+ model: stored?.model || row.model || models[0] || '',
+ baseUrl: stored?.baseUrl || row.base_url || '',
+ requiresKey: Boolean(row.requires_key),
+ custom: Boolean(row.custom),
+ configured: row.id === 'fake' || Boolean(stored?.configured),
+ note: row.note
+ }
+ })
+ const preferred = activeProviderId()
+ const active =
+ views.find((view) => view.id === preferred) ??
+ views.find((view) => view.configured) ??
+ views[0]
+ return { ok: true, providers: views, activeProvider: active?.id ?? '' }
+}
+
+function parseSaveInput(raw: unknown): SaveProviderInput {
+ if (!raw || typeof raw !== 'object') throw new Error('设置格式不对')
+ const obj = raw as Record
+ const id = typeof obj.id === 'string' ? obj.id.trim() : ''
+ const model = typeof obj.model === 'string' ? obj.model.trim() : ''
+ if (!id) throw new Error('缺少服务商')
+ if (!model) throw new Error('缺少模型名')
+ return {
+ id,
+ model,
+ apiKey: typeof obj.apiKey === 'string' ? obj.apiKey : undefined,
+ baseUrl: typeof obj.baseUrl === 'string' ? obj.baseUrl : undefined
+ }
+}
+
+function parseRunInput(raw: unknown): RunInput {
+ if (!raw || typeof raw !== 'object') throw new Error('运行请求格式不对')
+ const obj = raw as Record
+ const problem = typeof obj.problem === 'string' ? obj.problem.trim() : ''
+ const providerId = typeof obj.providerId === 'string' ? obj.providerId.trim() : ''
+ if (problem.length < 10) throw new Error('题面至少写一句完整的题目描述')
+ if (problem.length > 200_000) throw new Error('题面过长')
+ if (!providerId) throw new Error('没有选择服务商')
+ const dataPaths = Array.isArray(obj.dataPaths)
+ ? obj.dataPaths.filter((item): item is string => typeof item === 'string' && Boolean(item)).slice(0, 10)
+ : []
+ return {
+ problem,
+ dataPaths,
+ providerId,
+ model: typeof obj.model === 'string' ? obj.model.trim() : ''
+ }
+}
+
+function insideRuns(path: string): boolean {
+ if (!isAbsolute(path)) return false
+ const rel = relative(RUNS_ROOT, path)
+ return Boolean(rel) && !rel.startsWith('..') && !isAbsolute(rel)
+}
+
+function attachStream(runId: string, sender: WebContents): void {
+ const controller = new AbortController()
+ activeStreams.set(runId, controller)
+ void channel
+ .stream(
+ runId,
+ (event: RunEvent) => {
+ if (!sender.isDestroyed()) sender.send('run:event', event)
+ },
+ controller.signal
+ )
+ .catch((err: unknown) => {
+ if (controller.signal.aborted || sender.isDestroyed()) return
+ const message = err instanceof Error ? err.message : String(err)
+ sender.send('run:event', {
+ runId,
+ id: '0',
+ event: 'done',
+ data: { ok: false, error: message, outputs: {} }
+ })
+ })
+ .finally(() => activeStreams.delete(runId))
+}
+
+function appVersion(): string {
+ try {
+ return readFileSync(join(APP_ROOT, 'VERSION'), 'utf8').trim() || app.getVersion()
+ } catch {
+ return app.getVersion()
+ }
+}
+
+ipcMain.handle('app:meta', () => ({
+ version: appVersion(),
+ platform: process.platform,
+ electron: process.versions.electron,
+ chrome: process.versions.chrome
+}))
+
+ipcMain.handle('runtime:status', () => channel.current())
+
+ipcMain.handle('runtime:restart', async () => {
+ await channel.restart()
+ return providerViews()
+})
+
+ipcMain.handle('providers:list', () => providerViews())
+
+ipcMain.handle('providers:save', async (_event, raw: unknown) => {
+ saveProvider(parseSaveInput(raw))
+ return providerViews()
+})
+
+ipcMain.handle('providers:clear', async (_event, raw: unknown) => {
+ const id = typeof raw === 'string' ? raw : ''
+ if (!id) throw new Error('缺少服务商')
+ clearProviderKey(id)
+ return providerViews()
+})
+
+ipcMain.handle('files:pick-problem', (event) => pickProblemFile(BrowserWindow.fromWebContents(event.sender)))
+
+ipcMain.handle('files:pick-data', (event) => pickDataFiles(BrowserWindow.fromWebContents(event.sender)))
+
+ipcMain.handle('run:start', async (event, raw: unknown) => {
+ const input = parseRunInput(raw)
+ const list = await providerViews()
+ const view = list.providers.find((item) => item.id === input.providerId)
+ if (!view) throw new Error('未知服务商')
+ if (view.custom && !view.baseUrl) throw new Error('自定义端点还没填 base URL')
+ const apiKey = view.id === 'fake' ? '' : apiKeyFor(view.id) ?? ''
+ if (view.requiresKey && !apiKey) throw new Error('还没配置 API Key')
+ const result = await channel.startRun({
+ problem: input.problem,
+ dataPaths: input.dataPaths,
+ provider: {
+ id: view.id,
+ model: input.model || view.model,
+ baseUrl: view.custom ? view.baseUrl : undefined,
+ apiKey
+ }
+ })
+ attachStream(result.runId, event.sender)
+ return result
+})
+
+ipcMain.handle('run:cancel', async (_event, raw: unknown) => {
+ const runId = typeof raw === 'string' ? raw : ''
+ if (!runId) throw new Error('缺少运行 id')
+ await channel.cancelRun(runId)
+ // provider 正在等下一块数据时 cancel 只能等它醒来;2 秒后断开本地流兜底。
+ const controller = activeStreams.get(runId)
+ if (controller) setTimeout(() => controller.abort(), 2000)
+ return { ok: true }
+})
+
+ipcMain.handle('run:summary', (_event, raw: unknown) => {
+ const id = typeof raw === 'string' ? raw : ''
+ if (!id) return null
+ const path = join(RUNS_ROOT, id, 'summary.json')
+ if (!insideRuns(path)) return null
+ try {
+ return JSON.parse(readFileSync(path, 'utf8')) as unknown
+ } catch {
+ return null
+ }
+})
+
+ipcMain.handle('artifact:open', async (_event, raw: unknown) => {
+ const path = typeof raw === 'string' ? raw : ''
+ if (!insideRuns(path)) throw new Error('只能打开本次运行的产物')
+ const error = await shell.openPath(path)
+ if (error) throw new Error(error)
+ return { ok: true }
+})
+
+ipcMain.handle('artifact:reveal', (_event, raw: unknown) => {
+ const path = typeof raw === 'string' ? raw : ''
+ if (!insideRuns(path)) throw new Error('只能定位本次运行的产物')
+ shell.showItemInFolder(path)
+ return { ok: true }
+})
+
+ipcMain.handle('artifact:image', (_event, raw: unknown) => {
+ const path = typeof raw === 'string' ? raw : ''
+ if (!insideRuns(path)) return null
+ try {
+ const bytes = readFileSync(path)
+ if (!bytes.length || bytes.length > 12 * 1024 * 1024) return null
+ return `data:image/png;base64,${bytes.toString('base64')}`
+ } catch {
+ return null
+ }
+})
+
+function createWindow(): BrowserWindow {
+ const win = new BrowserWindow({
+ width: 1280,
+ height: 860,
+ useContentSize: true,
+ minWidth: 980,
+ minHeight: 640,
+ show: false,
+ backgroundColor: '#ffffff',
+ title: 'MathModel Studio',
+ webPreferences: {
+ preload: join(__dirname, '../preload/index.js'),
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ webSecurity: true
+ }
+ })
+
+ win.once('ready-to-show', () => {
+ win.setContentSize(1280, 860)
+ win.show()
+ })
+
+ if (DEV_SERVER_URL && !app.isPackaged) {
+ void win.loadURL(DEV_SERVER_URL)
+ } else {
+ void win.loadFile(join(__dirname, '../renderer/index.html'))
+ }
+
+ return win
+}
+
+// 渲染层拿不到 Node 能力,也不该拿到:外部链接一律走 shell.openExternal,且只放 https。
+app.on('web-contents-created', (_event, contents) => {
+ contents.setWindowOpenHandler(({ url }) => {
+ if (url.startsWith('https://')) void shell.openExternal(url)
+ return { action: 'deny' }
+ })
+ contents.on('will-navigate', (event, url) => {
+ const allowedOrigin = DEV_SERVER_URL ? new URL(DEV_SERVER_URL).origin : 'file:'
+ const origin = url.startsWith('file://') ? 'file:' : new URL(url).origin
+ if (origin !== allowedOrigin) event.preventDefault()
+ })
+})
+
+app.whenReady().then(() => {
+ if (process.platform !== 'darwin') Menu.setApplicationMenu(null)
+ void channel.start().catch((err: unknown) => {
+ console.error('[runtime] 启动失败:', err instanceof Error ? err.message : err)
+ })
+ createWindow()
+ app.on('activate', () => {
+ if (BrowserWindow.getAllWindows().length === 0) createWindow()
+ })
+})
+
+app.on('will-quit', () => {
+ for (const controller of activeStreams.values()) controller.abort()
+ activeStreams.clear()
+ channel.stop()
+})
+
+app.on('window-all-closed', () => {
+ if (process.platform !== 'darwin') app.quit()
+})
diff --git a/src/main/runtime-env.ts b/desktop/src/main/runtime-env.ts
similarity index 71%
rename from src/main/runtime-env.ts
rename to desktop/src/main/runtime-env.ts
index dea2d3e..3cd2623 100644
--- a/src/main/runtime-env.ts
+++ b/desktop/src/main/runtime-env.ts
@@ -1,10 +1,11 @@
import { app } from 'electron'
import { join } from 'node:path'
-// 开发时资源在仓库根;打包后 runtime/skills/schemas/python 放在 resources/ 下——
+// 开发时资源在仓库根(modeling/、gateway/、vendor/);打包后它们放在 resources/ 下——
// app.asar 里的文件 Python 读不到,所以 ROOT 必须指向 resourcesPath 而不是 __dirname 往上找。
export const APP_ROOT =
- process.env['MMS_HOME'] || (app.isPackaged ? process.resourcesPath : join(__dirname, '..', '..'))
+ process.env['MMS_HOME'] ||
+ (app.isPackaged ? process.resourcesPath : join(__dirname, '..', '..', '..'))
export function runtimePython(): string {
const override = process.env['MMS_PYTHON']
diff --git a/src/main/settings.ts b/desktop/src/main/settings.ts
similarity index 51%
rename from src/main/settings.ts
rename to desktop/src/main/settings.ts
index c58a98d..51b3a15 100644
--- a/src/main/settings.ts
+++ b/desktop/src/main/settings.ts
@@ -1,25 +1,18 @@
import { app, safeStorage } from 'electron'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
-import type { ThinkingDepth } from '../shared/api'
+import type { SaveProviderInput } from '../shared/api'
-// 磁盘上只有 safeStorage 的密文。safeStorage 不可用时**拒绝保存**,
-// 不退回明文——这条比"让用户先存上"重要。
+// 磁盘上只有 safeStorage 的密文。safeStorage 不可用时拒绝保存,不退回明文。
interface StoredProvider {
model?: string
baseUrl?: string
key?: string
- context?: number
- depth?: ThinkingDepth
- sendThinking?: boolean
}
interface SettingsFile {
version: 1
activeProvider?: string
- workspace?: string
- /** 按赛题分项目文件夹;缺省视为开启 */
- projectFolders?: boolean
providers: Record
}
@@ -33,7 +26,7 @@ function defaults(): SettingsFile {
return { version: 1, providers: {} }
}
-export function loadSettings(): SettingsFile {
+function loadSettings(): SettingsFile {
if (cache) return cache
const path = filePath()
if (!existsSync(path)) {
@@ -43,12 +36,12 @@ export function loadSettings(): SettingsFile {
try {
const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial
const providers =
- raw.providers && typeof raw.providers === 'object' ? (raw.providers as Record) : {}
+ raw.providers && typeof raw.providers === 'object'
+ ? (raw.providers as Record)
+ : {}
cache = {
version: 1,
activeProvider: typeof raw.activeProvider === 'string' ? raw.activeProvider : undefined,
- workspace: typeof raw.workspace === 'string' && raw.workspace ? raw.workspace : undefined,
- projectFolders: typeof raw.projectFolders === 'boolean' ? raw.projectFolders : undefined,
providers
}
} catch {
@@ -68,24 +61,13 @@ export interface PublicProvider {
configured: boolean
model?: string
baseUrl?: string
- context?: number
- depth?: ThinkingDepth
- sendThinking?: boolean
}
/** 只给渲染层展示用的合并视图,不含密文。 */
export function publicProviders(): Record {
- const file = loadSettings()
const out: Record = {}
- for (const [id, item] of Object.entries(file.providers)) {
- out[id] = {
- configured: Boolean(item.key),
- model: item.model,
- baseUrl: item.baseUrl,
- context: item.context,
- depth: item.depth,
- sendThinking: item.sendThinking
- }
+ for (const [id, item] of Object.entries(loadSettings().providers)) {
+ out[id] = { configured: Boolean(item.key), model: item.model, baseUrl: item.baseUrl }
}
return out
}
@@ -94,37 +76,14 @@ export function activeProviderId(): string | undefined {
return loadSettings().activeProvider
}
-export interface SaveProviderInput {
- id: string
- model: string
- apiKey?: string
- baseUrl?: string
- contextTokens?: number
- thinkingDepth?: ThinkingDepth
- sendThinking?: boolean
-}
-
-const CONTEXTS = new Set([200_000, 400_000, 1_000_000])
-const DEPTHS = new Set(['medium', 'high', 'max'])
-
export function saveProvider(input: SaveProviderInput): void {
const id = String(input.id || '').trim()
const model = String(input.model || '').trim()
if (!id) throw new Error('缺少服务商标识')
if (!model) throw new Error('缺少模型名')
- if (input.contextTokens !== undefined && !CONTEXTS.has(input.contextTokens)) {
- throw new Error('上下文预算只能是 200k / 400k / 1m')
- }
- if (input.thinkingDepth !== undefined && !DEPTHS.has(input.thinkingDepth)) {
- throw new Error('思维深度只能是中 / 高 / 最大')
- }
const file = loadSettings()
- const prev = file.providers[id] ?? {}
- const next: StoredProvider = { ...prev, model }
+ const next: StoredProvider = { ...file.providers[id], model }
if (typeof input.baseUrl === 'string') next.baseUrl = input.baseUrl.trim()
- if (input.contextTokens !== undefined) next.context = input.contextTokens
- if (input.thinkingDepth !== undefined) next.depth = input.thinkingDepth
- if (typeof input.sendThinking === 'boolean') next.sendThinking = input.sendThinking
const apiKey = String(input.apiKey || '').trim()
if (apiKey) {
if (!safeStorage.isEncryptionAvailable()) {
@@ -132,11 +91,7 @@ export function saveProvider(input: SaveProviderInput): void {
}
next.key = safeStorage.encryptString(apiKey).toString('base64')
}
- persist({
- ...file,
- activeProvider: id,
- providers: { ...file.providers, [id]: next }
- })
+ persist({ ...file, activeProvider: id, providers: { ...file.providers, [id]: next } })
}
export function clearProviderKey(id: string): void {
@@ -160,25 +115,3 @@ export function apiKeyFor(id: string): string | null {
return null
}
}
-
-/** 用户自选的工作区目录;未设置时用桌面的「赛题」。 */
-export function savedWorkspace(): string | undefined {
- return loadSettings().workspace
-}
-
-export function saveWorkspace(path: string | undefined): void {
- const file = loadSettings()
- const next: SettingsFile = { ...file }
- if (path) next.workspace = path
- else delete next.workspace
- persist(next)
-}
-
-/** 按赛题分项目文件夹的总开关;未写过时默认开启。 */
-export function projectFoldersEnabled(): boolean {
- return loadSettings().projectFolders !== false
-}
-
-export function setProjectFolders(enabled: boolean): void {
- persist({ ...loadSettings(), projectFolders: enabled })
-}
diff --git a/src/preload/index.d.ts b/desktop/src/preload/index.d.ts
similarity index 100%
rename from src/preload/index.d.ts
rename to desktop/src/preload/index.d.ts
diff --git a/desktop/src/preload/index.ts b/desktop/src/preload/index.ts
new file mode 100644
index 0000000..b5e25df
--- /dev/null
+++ b/desktop/src/preload/index.ts
@@ -0,0 +1,60 @@
+import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'
+import type {
+ ProblemFile,
+ ProviderList,
+ RunEvent,
+ RunInput,
+ RunStartResult,
+ RunSummary,
+ RuntimeStatus,
+ SaveProviderInput,
+ StudioMeta
+} from '../shared/api'
+
+// 渲染层只能看到这几条窄接口:主进程的 runtime 端口、token 与 API Key 都不经过这里。
+const studioApi = {
+ meta: (): Promise => ipcRenderer.invoke('app:meta'),
+
+ runtime: {
+ status: (): Promise => ipcRenderer.invoke('runtime:status'),
+ restart: (): Promise => ipcRenderer.invoke('runtime:restart'),
+ onStatus: (cb: (status: RuntimeStatus) => void): (() => void) => {
+ const handler = (_event: IpcRendererEvent, status: RuntimeStatus): void => cb(status)
+ ipcRenderer.on('runtime:status', handler)
+ return () => ipcRenderer.removeListener('runtime:status', handler)
+ }
+ },
+
+ providers: {
+ list: (): Promise => ipcRenderer.invoke('providers:list'),
+ save: (payload: SaveProviderInput): Promise =>
+ ipcRenderer.invoke('providers:save', payload),
+ clear: (id: string): Promise => ipcRenderer.invoke('providers:clear', id)
+ },
+
+ files: {
+ pickProblem: (): Promise => ipcRenderer.invoke('files:pick-problem'),
+ pickData: (): Promise => ipcRenderer.invoke('files:pick-data')
+ },
+
+ run: {
+ start: (input: RunInput): Promise => ipcRenderer.invoke('run:start', input),
+ cancel: (runId: string): Promise<{ ok: true }> => ipcRenderer.invoke('run:cancel', runId),
+ summary: (runId: string): Promise => ipcRenderer.invoke('run:summary', runId),
+ onEvent: (cb: (event: RunEvent) => void): (() => void) => {
+ const handler = (_event: IpcRendererEvent, payload: RunEvent): void => cb(payload)
+ ipcRenderer.on('run:event', handler)
+ return () => ipcRenderer.removeListener('run:event', handler)
+ }
+ },
+
+ artifacts: {
+ open: (path: string): Promise<{ ok: true }> => ipcRenderer.invoke('artifact:open', path),
+ reveal: (path: string): Promise<{ ok: true }> => ipcRenderer.invoke('artifact:reveal', path),
+ image: (path: string): Promise => ipcRenderer.invoke('artifact:image', path)
+ }
+}
+
+contextBridge.exposeInMainWorld('studio', studioApi)
+
+export type StudioApi = typeof studioApi
diff --git a/src/renderer/index.html b/desktop/src/renderer/index.html
similarity index 93%
rename from src/renderer/index.html
rename to desktop/src/renderer/index.html
index 02b30eb..a422ae7 100644
--- a/src/renderer/index.html
+++ b/desktop/src/renderer/index.html
@@ -7,7 +7,7 @@
content="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ws://127.0.0.1:* ws://localhost:*"
/>
- mathmodel-studio
+ MathModel Studio
diff --git a/desktop/src/renderer/src/App.tsx b/desktop/src/renderer/src/App.tsx
new file mode 100644
index 0000000..9e62911
--- /dev/null
+++ b/desktop/src/renderer/src/App.tsx
@@ -0,0 +1,288 @@
+import { useEffect, useRef, useState, type JSX } from 'react'
+import type {
+ DoneData,
+ LogData,
+ PhaseData,
+ ProviderList,
+ RunSummary,
+ RuntimeStatus
+} from '../../shared/api'
+import Conversation from './components/Conversation'
+import { initialPhases, type LiveRun } from './components/RunView'
+import SettingsDialog from './components/SettingsDialog'
+import Sidebar from './components/Sidebar'
+import Welcome from './components/Welcome'
+import {
+ conversationTitle,
+ loadUi,
+ saveUi,
+ uid,
+ type Conversation as Conv,
+ type UiState
+} from './lib/store'
+
+function errorText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err)
+}
+
+export default function App(): JSX.Element {
+ const [ui, setUi] = useState(loadUi)
+ const [runtime, setRuntime] = useState({ state: 'starting' })
+ const [providers, setProviders] = useState(null)
+ const [settingsOpen, setSettingsOpen] = useState(false)
+ const [live, setLive] = useState>({})
+ const uiRef = useRef(ui)
+ uiRef.current = ui
+
+ const activeWorkspace = ui.workspaces.find((item) => item.id === ui.activeWorkspaceId) ?? ui.workspaces[0]
+ const activeConversation =
+ activeWorkspace?.conversations.find((item) => item.id === ui.activeConversationId) ?? null
+ const activeProvider = providers?.providers.find((item) => item.id === providers.activeProvider) ?? null
+
+ useEffect(() => saveUi(ui), [ui])
+
+ useEffect(() => {
+ void window.studio.runtime.status().then(setRuntime)
+ return window.studio.runtime.onStatus(setRuntime)
+ }, [])
+
+ useEffect(() => {
+ if (runtime.state !== 'ready') return
+ void window.studio.providers.list().then(setProviders).catch(() => undefined)
+ }, [runtime.state])
+
+ function patchConversation(convId: string, patch: Partial): void {
+ setUi((prev) => ({
+ ...prev,
+ workspaces: prev.workspaces.map((workspace) => ({
+ ...workspace,
+ conversations: workspace.conversations.map((item) =>
+ item.id === convId ? { ...item, ...patch } : item
+ )
+ }))
+ }))
+ }
+
+ useEffect(() => {
+ return window.studio.run.onEvent((payload) => {
+ const runId = payload.runId
+ let convId: string | null = null
+ for (const workspace of uiRef.current.workspaces) {
+ const found = workspace.conversations.find((item) => item.runId === runId)
+ if (found) {
+ convId = found.id
+ break
+ }
+ }
+ if (!convId) return
+
+ if (payload.event === 'phase') {
+ const data = payload.data as unknown as PhaseData
+ setLive((prev) => {
+ const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null }
+ return {
+ ...prev,
+ [runId]: {
+ ...run,
+ phases: { ...run.phases, [data.id]: { label: data.label, status: data.status, detail: data.detail } }
+ }
+ }
+ })
+ } else if (payload.event === 'log') {
+ const data = payload.data as unknown as LogData
+ setLive((prev) => {
+ const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null }
+ return { ...prev, [runId]: { ...run, logs: [...run.logs.slice(-400), data] } }
+ })
+ } else if (payload.event === 'progress') {
+ const data = payload.data as unknown as { stage?: string; chars?: number }
+ if (!data.stage) return
+ setLive((prev) => {
+ const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null }
+ return { ...prev, [runId]: { ...run, progress: `${data.stage} · ${data.chars ?? 0} 字` } }
+ })
+ } else if (payload.event === 'done') {
+ const data = payload.data as unknown as DoneData
+ setLive((prev) => {
+ const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null }
+ return { ...prev, [runId]: { ...run, progress: '', done: data } }
+ })
+ patchConversation(convId, {
+ status: data.ok ? 'done' : 'error',
+ outputs: data.outputs,
+ picked: data.picked,
+ sources: data.sources,
+ seconds: data.seconds,
+ error: data.error
+ })
+ }
+ })
+ }, [])
+
+ useEffect(() => {
+ const conversation = activeConversation
+ if (!conversation?.runId || conversation.outputs) return
+ let alive = true
+ void window.studio.run.summary(conversation.runId).then((summary: RunSummary | null) => {
+ if (!alive || !summary) return
+ patchConversation(conversation.id, {
+ status: summary.ok ? 'done' : 'error',
+ outputs: summary.outputs,
+ picked: summary.picked?.name,
+ sources: summary.sources,
+ seconds: summary.seconds,
+ error: summary.error
+ })
+ })
+ return () => {
+ alive = false
+ }
+ }, [ui.activeConversationId])
+
+ function newConversation(workspaceId?: string, problem = ''): string {
+ const conversation: Conv = {
+ id: uid('c'),
+ title: problem ? conversationTitle(problem) : '新对话',
+ problem,
+ dataPaths: [],
+ status: 'idle',
+ createdAt: Date.now()
+ }
+ setUi((prev) => {
+ const target = workspaceId ?? prev.activeWorkspaceId
+ return {
+ ...prev,
+ activeWorkspaceId: target,
+ workspaces: prev.workspaces.map((workspace) =>
+ workspace.id === target
+ ? { ...workspace, conversations: [conversation, ...workspace.conversations] }
+ : workspace
+ ),
+ activeConversationId: conversation.id
+ }
+ })
+ return conversation.id
+ }
+
+ function selectConversation(id: string): void {
+ const owner = ui.workspaces.find((workspace) => workspace.conversations.some((item) => item.id === id))
+ setUi((prev) => ({
+ ...prev,
+ activeWorkspaceId: owner?.id ?? prev.activeWorkspaceId,
+ activeConversationId: id
+ }))
+ }
+
+ function newWorkspace(): void {
+ const workspace = { id: uid('w'), name: `工作区 ${ui.workspaces.length + 1}`, conversations: [] }
+ setUi((prev) => ({
+ ...prev,
+ workspaces: [...prev.workspaces, workspace],
+ activeWorkspaceId: workspace.id,
+ activeConversationId: null
+ }))
+ }
+
+ function selectWorkspace(id: string): void {
+ const workspace = ui.workspaces.find((item) => item.id === id)
+ setUi((prev) => ({
+ ...prev,
+ activeWorkspaceId: id,
+ activeConversationId: workspace?.conversations[0]?.id ?? null
+ }))
+ }
+
+ function deleteConversation(id: string): void {
+ setUi((prev) => ({
+ ...prev,
+ workspaces: prev.workspaces.map((workspace) => ({
+ ...workspace,
+ conversations: workspace.conversations.filter((item) => item.id !== id)
+ })),
+ activeConversationId: prev.activeConversationId === id ? null : prev.activeConversationId
+ }))
+ }
+
+ async function send(convId: string, problem: string, dataPaths: string[]): Promise {
+ if (!activeProvider) return
+ try {
+ const result = await window.studio.run.start({
+ problem,
+ dataPaths,
+ providerId: activeProvider.id,
+ model: activeProvider.model
+ })
+ patchConversation(convId, {
+ problem,
+ dataPaths,
+ title: conversationTitle(problem),
+ status: 'running',
+ runId: result.runId,
+ error: undefined
+ })
+ setLive((prev) => ({
+ ...prev,
+ [result.runId]: { phases: initialPhases(), logs: [], progress: '', done: null }
+ }))
+ } catch (err) {
+ patchConversation(convId, { status: 'idle', error: errorText(err) })
+ }
+ }
+
+ async function cancel(): Promise {
+ if (activeConversation?.runId) {
+ await window.studio.run.cancel(activeConversation.runId).catch(() => undefined)
+ }
+ }
+
+ async function openArtifact(path?: string): Promise {
+ if (path) await window.studio.artifacts.open(path).catch(() => undefined)
+ }
+
+ async function revealArtifact(path?: string): Promise {
+ if (path) await window.studio.artifacts.reveal(path).catch(() => undefined)
+ }
+
+ return (
+
+ newConversation(workspaceId)}
+ onDeleteConversation={deleteConversation}
+ onOpenSettings={() => setSettingsOpen(true)}
+ />
+
+ {activeConversation ? (
+ void send(activeConversation.id, problem, dataPaths)}
+ onCancel={() => void cancel()}
+ onOpen={(path) => void openArtifact(path)}
+ onReveal={(path) => void revealArtifact(path)}
+ onNewConversation={() => newConversation()}
+ />
+ ) : (
+ newConversation()}
+ onExample={(problem) => newConversation(undefined, problem)}
+ />
+ )}
+
+ setSettingsOpen(false)}
+ onChanged={setProviders}
+ />
+
+ )
+}
diff --git a/desktop/src/renderer/src/components/Conversation.tsx b/desktop/src/renderer/src/components/Conversation.tsx
new file mode 100644
index 0000000..e75b096
--- /dev/null
+++ b/desktop/src/renderer/src/components/Conversation.tsx
@@ -0,0 +1,132 @@
+import { useEffect, useState, type JSX } from 'react'
+import type { Conversation } from '../lib/store'
+import RunView, { type LiveRun } from './RunView'
+
+interface Props {
+ conversation: Conversation
+ live?: LiveRun
+ providerLabel: string
+ runtimeReady: boolean
+ onSend: (problem: string, dataPaths: string[]) => void
+ onCancel: () => void
+ onOpen: (path?: string) => void
+ onReveal: (path?: string) => void
+ onNewConversation: () => void
+}
+
+function baseName(path: string): string {
+ return path.split(/[\\/]/).pop() || path
+}
+
+export default function Conversation(props: Props): JSX.Element {
+ const { conversation } = props
+ const [problem, setProblem] = useState(conversation.problem)
+ const [dataPaths, setDataPaths] = useState(conversation.dataPaths)
+ const [error, setError] = useState('')
+
+ useEffect(() => {
+ setProblem(conversation.problem)
+ setDataPaths(conversation.dataPaths)
+ setError(conversation.error ?? '')
+ }, [conversation.id, conversation.error])
+
+ async function pickProblem(): Promise {
+ try {
+ const file = await window.studio.files.pickProblem()
+ if (file) setProblem(file.text)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err))
+ }
+ }
+
+ async function pickData(): Promise {
+ try {
+ const paths = await window.studio.files.pickData()
+ if (paths.length) setDataPaths(paths.slice(0, 1))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err))
+ }
+ }
+
+ function send(): void {
+ if (problem.trim().length < 10) {
+ setError('先把题目写完整(至少一句描述)。')
+ return
+ }
+ setError('')
+ props.onSend(problem.trim(), dataPaths)
+ }
+
+ const idle = conversation.status === 'idle'
+ const running = conversation.status === 'running'
+
+ return (
+
+
+ {conversation.problem && (
+
+
{conversation.problem}
+ {conversation.dataPaths.length > 0 && (
+
+ {conversation.dataPaths.map((path) => (
+ {baseName(path)}
+ ))}
+
+ )}
+
+ )}
+ {(conversation.runId || props.live || conversation.status !== 'idle') && (
+
+
+
+ )}
+ {idle && !conversation.problem && (
+
写下赛题开始一次建模;一个对话对应一次完整运行。
+ )}
+
+
+ {idle || running ? (
+
+ ) : (
+
+ 新对话
+
+ )}
+
+ )
+}
diff --git a/desktop/src/renderer/src/components/RunView.tsx b/desktop/src/renderer/src/components/RunView.tsx
new file mode 100644
index 0000000..b39ec5e
--- /dev/null
+++ b/desktop/src/renderer/src/components/RunView.tsx
@@ -0,0 +1,126 @@
+import { useEffect, useRef, useState, type JSX } from 'react'
+import type { DoneData, LogData } from '../../../shared/api'
+import type { Conversation } from '../lib/store'
+
+export interface PhaseView {
+ label: string
+ status: 'idle' | 'running' | 'ok' | 'error'
+ detail?: string
+}
+
+export interface LiveRun {
+ phases: Record
+ logs: LogData[]
+ progress: string
+ done: DoneData | null
+}
+
+export const PHASE_ROWS = [
+ { id: 1, label: '题面拆解' },
+ { id: 2, label: '方法选择' },
+ { id: 3, label: '生成代码' },
+ { id: 4, label: '运行求解' },
+ { id: 5, label: '论文排版' }
+]
+
+export function initialPhases(): Record {
+ return Object.fromEntries(PHASE_ROWS.map((row) => [row.id, { label: row.label, status: 'idle' as const }]))
+}
+
+const SOURCE_LABELS: Record = {
+ questions: '拆题',
+ method: '选模',
+ code: '代码',
+ paper: '论文'
+}
+
+interface Props {
+ live?: LiveRun
+ conversation: Conversation
+ onOpen: (path?: string) => void
+ onReveal: (path?: string) => void
+}
+
+export default function RunView({ live, conversation, onOpen, onReveal }: Props): JSX.Element {
+ const done = live?.done ?? null
+ const outputs = done?.outputs ?? conversation.outputs
+ const picked = done?.picked ?? conversation.picked
+ const sources = done?.sources ?? conversation.sources
+ const seconds = done?.seconds ?? conversation.seconds
+ const failed = done ? !done.ok : conversation.status === 'error'
+ const error = done?.error ?? conversation.error
+ const [image, setImage] = useState(null)
+ const logRef = useRef(null)
+
+ useEffect(() => {
+ const path = outputs?.png
+ if (!path) {
+ setImage(null)
+ return
+ }
+ let alive = true
+ void window.studio.artifacts.image(path).then((url) => {
+ if (alive) setImage(url)
+ })
+ return () => {
+ alive = false
+ }
+ }, [outputs?.png])
+
+ useEffect(() => {
+ const element = logRef.current
+ if (element) element.scrollTop = element.scrollHeight
+ }, [live?.logs, live?.progress])
+
+ return (
+
+ {live && (
+ <>
+
+ {PHASE_ROWS.map((row) => {
+ const view = live.phases[row.id] ?? { label: row.label, status: 'idle' as const }
+ return (
+
+
+ {view.label}
+ {view.detail ?? ''}
+
+ )
+ })}
+
+
+ {live.logs.map((line, index) => (
+
{line.text}
+ ))}
+ {live.progress &&
{live.progress}
}
+
+ >
+ )}
+
+ {(outputs || failed) && (
+
+
+ {conversation.status === 'running' && !done ? '运行中' : failed ? '运行失败' : '运行完成'}
+ {seconds ? {seconds}s : null}
+
+ {picked &&
方法:{picked}
}
+ {sources && (
+
+ {Object.entries(sources).map(([key, value]) => (
+ {SOURCE_LABELS[key] ?? key}:{value}
+ ))}
+
+ )}
+ {image &&
}
+ {outputs?.paperError &&
{outputs.paperError}
}
+ {failed && error &&
{error}
}
+
+ onOpen(outputs?.paperPdf)} disabled={!outputs?.paperPdf}>打开 PDF
+ onOpen(outputs?.paperDocx)} disabled={!outputs?.paperDocx}>打开 Word
+ onReveal(outputs?.dir)} disabled={!outputs?.dir}>结果文件夹
+
+
+ )}
+
+ )
+}
diff --git a/desktop/src/renderer/src/components/SettingsDialog.tsx b/desktop/src/renderer/src/components/SettingsDialog.tsx
new file mode 100644
index 0000000..1b06d41
--- /dev/null
+++ b/desktop/src/renderer/src/components/SettingsDialog.tsx
@@ -0,0 +1,169 @@
+import { useEffect, useState, type JSX } from 'react'
+import type { ProviderList, ProviderView } from '../../../shared/api'
+
+interface Props {
+ open: boolean
+ providers: ProviderList | null
+ onClose: () => void
+ onChanged: (list: ProviderList) => void
+}
+
+function errorText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err)
+}
+
+export default function SettingsDialog({ open, providers, onClose, onChanged }: Props): JSX.Element | null {
+ const [selected, setSelected] = useState('')
+ const [model, setModel] = useState('')
+ const [baseUrl, setBaseUrl] = useState('')
+ const [apiKey, setApiKey] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [note, setNote] = useState('')
+
+ useEffect(() => {
+ if (!open || !providers) return
+ const view = providers.providers.find((item) => item.id === providers.activeProvider) ?? providers.providers[0]
+ if (view) {
+ setSelected(view.id)
+ setModel(view.model)
+ setBaseUrl(view.baseUrl)
+ }
+ setApiKey('')
+ setError('')
+ setNote('')
+ }, [open, providers])
+
+ if (!open) return null
+
+ const view: ProviderView | undefined = providers?.providers.find((item) => item.id === selected)
+ const isFake = view?.id === 'fake'
+
+ function selectProvider(id: string): void {
+ const next = providers?.providers.find((item) => item.id === id)
+ setSelected(id)
+ if (next) {
+ setModel(next.model)
+ setBaseUrl(next.baseUrl)
+ }
+ setApiKey('')
+ setError('')
+ setNote('')
+ }
+
+ async function save(): Promise {
+ if (!view) return
+ setBusy(true)
+ setError('')
+ setNote('')
+ try {
+ const list = await window.studio.providers.save({
+ id: view.id,
+ model: model.trim(),
+ baseUrl: view.custom ? baseUrl.trim() : undefined,
+ apiKey: apiKey.trim() || undefined
+ })
+ onChanged(list)
+ setNote('已保存')
+ setApiKey('')
+ } catch (err) {
+ setError(errorText(err))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function clearKey(): Promise {
+ if (!view) return
+ setBusy(true)
+ setError('')
+ setNote('')
+ try {
+ const list = await window.studio.providers.clear(view.id)
+ onChanged(list)
+ setNote('已清除 Key')
+ } catch (err) {
+ setError(errorText(err))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+ event.target === event.currentTarget && onClose()}>
+
+
+
+
+ 服务商
+ selectProvider(event.target.value)}>
+ {providers?.providers.map((item) => (
+
+ {item.display}
+ {item.configured && item.id !== 'fake' ? '(已配置)' : ''}
+
+ ))}
+
+
+
+ {isFake ? (
+
离线模式不联网:用内置基线脚本与样例论文跑通链路,适合先看界面。
+ ) : (
+ <>
+
+ 模型
+ setModel(event.target.value)}
+ list={`models-${view?.id ?? 'none'}`}
+ placeholder={view?.models[0] || '模型名'}
+ />
+
+ {view?.models.map((item) => )}
+
+
+ {view?.custom && (
+
+ Base URL
+ setBaseUrl(event.target.value)}
+ placeholder="https://…/v1"
+ />
+
+ )}
+
+ API Key
+ setApiKey(event.target.value)}
+ placeholder={view?.configured ? '已保存(留空则不变)' : '粘贴 Key'}
+ autoComplete="off"
+ />
+
+
Key 用系统安全存储加密后保存,运行时按次传给本机进程,不写日志、不进事件。
+ >
+ )}
+
+ {view?.note &&
{view.note}
}
+ {error &&
{error}
}
+ {note &&
{note}
}
+
+
+ {!isFake && (
+
+ 清除 Key
+
+ )}
+
+ {busy ? '保存中…' : '保存'}
+
+
+
+
+ )
+}
diff --git a/desktop/src/renderer/src/components/Sidebar.tsx b/desktop/src/renderer/src/components/Sidebar.tsx
new file mode 100644
index 0000000..3215381
--- /dev/null
+++ b/desktop/src/renderer/src/components/Sidebar.tsx
@@ -0,0 +1,91 @@
+import { useEffect, useState, type JSX } from 'react'
+import type { RuntimeStatus } from '../../../shared/api'
+import type { Workspace } from '../lib/store'
+
+interface Props {
+ workspaces: Workspace[]
+ activeWorkspaceId: string
+ activeConversationId: string | null
+ runtime: RuntimeStatus
+ onSelectWorkspace: (id: string) => void
+ onNewWorkspace: () => void
+ onSelectConversation: (id: string) => void
+ onNewConversation: (workspaceId: string) => void
+ onDeleteConversation: (id: string) => void
+ onOpenSettings: () => void
+}
+
+function runtimeText(status: RuntimeStatus): string {
+ if (status.state === 'ready') return '就绪'
+ if (status.state === 'error') return '错误'
+ return '启动中'
+}
+
+export default function Sidebar(props: Props): JSX.Element {
+ const [expanded, setExpanded] = useState>({ [props.activeWorkspaceId]: true })
+
+ useEffect(() => {
+ setExpanded((prev) => ({ ...prev, [props.activeWorkspaceId]: true }))
+ }, [props.activeWorkspaceId])
+
+ function toggle(id: string): void {
+ setExpanded((prev) => ({ ...prev, [id]: !prev[id] }))
+ }
+
+ return (
+
+
+ MM
+ MathModel Studio
+
+
+
+
+ 工作区
+ +
+
+
+ {props.workspaces.map((workspace) => {
+ const open = Boolean(expanded[workspace.id])
+ return (
+
+
+ toggle(workspace.id)} title={open ? '收起' : '展开'}>
+ {open ? '▾' : '▸'}
+
+ props.onSelectWorkspace(workspace.id)}>
+ {workspace.name}
+
+ {workspace.conversations.length}
+ props.onNewConversation(workspace.id)}>+
+
+ {open && (
+
+ {workspace.conversations.length === 0 &&
暂无对话
}
+ {workspace.conversations.map((conversation) => (
+
+ props.onSelectConversation(conversation.id)}>
+
+ {conversation.title}
+
+ props.onDeleteConversation(conversation.id)}>×
+
+ ))}
+
+ )}
+
+ )
+ })}
+
+
+
+
+ 设置
+ {runtimeText(props.runtime)}
+
+
+ )
+}
diff --git a/desktop/src/renderer/src/components/Welcome.tsx b/desktop/src/renderer/src/components/Welcome.tsx
new file mode 100644
index 0000000..80ab1ec
--- /dev/null
+++ b/desktop/src/renderer/src/components/Welcome.tsx
@@ -0,0 +1,35 @@
+import type { JSX } from 'react'
+
+const EXAMPLE =
+ '某工厂有 120 条生产线,附件给出每条产线的温度、压力与产量记录。问题一:建立产量与温度、压力的关系模型并做预测;问题二:分析异常产线并给出改进建议;问题三:评估模型稳健性。'
+
+interface Props {
+ onNewConversation: () => void
+ onExample: (problem: string) => void
+}
+
+export default function Welcome({ onNewConversation, onExample }: Props): JSX.Element {
+ return (
+
+
+
把赛题变成可交付的论文
+
+ 本地一键流水线:拆题 → 选模 → 生成并运行求解代码 → 按真实结果写论文、排 PDF/Word。
+
+
+ 粘贴或导入赛题 支持 txt / md / tex,或直接在输入框写题目。
+ 附上数据(可选) CSV / TSV;不附数据时用内置样例跑通链路。
+ 开始建模 自动选模、写代码、运行与修复,全程进度可见。
+ 查看交付物 求解图、result.json、paper.pdf / paper.docx。
+
+
+ 离线模式可先跑通;在设置里配置 DeepSeek 等服务商 Key 后,按本题真实生成。
+
+
+ 新建对话
+ onExample(EXAMPLE)}>试用示例
+
+
+
+ )
+}
diff --git a/src/renderer/src/env.d.ts b/desktop/src/renderer/src/env.d.ts
similarity index 100%
rename from src/renderer/src/env.d.ts
rename to desktop/src/renderer/src/env.d.ts
diff --git a/desktop/src/renderer/src/lib/store.ts b/desktop/src/renderer/src/lib/store.ts
new file mode 100644
index 0000000..5bfc1af
--- /dev/null
+++ b/desktop/src/renderer/src/lib/store.ts
@@ -0,0 +1,78 @@
+import type { RunOutputs } from '../../../shared/api'
+
+export interface Conversation {
+ id: string
+ title: string
+ problem: string
+ dataPaths: string[]
+ runId?: string
+ status: 'idle' | 'running' | 'done' | 'error'
+ outputs?: RunOutputs
+ picked?: string
+ sources?: Record
+ seconds?: number
+ error?: string
+ createdAt: number
+}
+
+export interface Workspace {
+ id: string
+ name: string
+ conversations: Conversation[]
+}
+
+export interface UiState {
+ workspaces: Workspace[]
+ activeWorkspaceId: string
+ activeConversationId: string | null
+}
+
+const KEY = 'mms.ui.v1'
+
+export function uid(prefix: string): string {
+ return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`
+}
+
+export function defaultUi(): UiState {
+ const workspace: Workspace = { id: uid('w'), name: '默认工作区', conversations: [] }
+ return { workspaces: [workspace], activeWorkspaceId: workspace.id, activeConversationId: null }
+}
+
+export function loadUi(): UiState {
+ try {
+ const raw = window.localStorage.getItem(KEY)
+ if (!raw) return defaultUi()
+ const parsed = JSON.parse(raw) as Partial
+ if (!Array.isArray(parsed.workspaces) || parsed.workspaces.length === 0) return defaultUi()
+ const workspaces = parsed.workspaces.filter(
+ (item): item is Workspace => Boolean(item && typeof item.id === 'string' && Array.isArray(item.conversations))
+ )
+ if (workspaces.length === 0) return defaultUi()
+ const activeWorkspaceId =
+ typeof parsed.activeWorkspaceId === 'string' && workspaces.some((w) => w.id === parsed.activeWorkspaceId)
+ ? parsed.activeWorkspaceId
+ : workspaces[0].id
+ const active = workspaces.find((w) => w.id === activeWorkspaceId)
+ const activeConversationId =
+ typeof parsed.activeConversationId === 'string' &&
+ active?.conversations.some((c) => c.id === parsed.activeConversationId)
+ ? parsed.activeConversationId
+ : null
+ return { workspaces, activeWorkspaceId, activeConversationId }
+ } catch {
+ return defaultUi()
+ }
+}
+
+export function saveUi(state: UiState): void {
+ try {
+ window.localStorage.setItem(KEY, JSON.stringify(state))
+ } catch {
+ // 存储不可用时只影响会话列表持久化,不影响运行
+ }
+}
+
+export function conversationTitle(problem: string): string {
+ const first = problem.trim().split(/\r?\n/)[0] ?? ''
+ return first.slice(0, 24) || '新对话'
+}
diff --git a/src/renderer/src/main.tsx b/desktop/src/renderer/src/main.tsx
similarity index 100%
rename from src/renderer/src/main.tsx
rename to desktop/src/renderer/src/main.tsx
diff --git a/desktop/src/renderer/src/styles/index.css b/desktop/src/renderer/src/styles/index.css
new file mode 100644
index 0000000..95ce260
--- /dev/null
+++ b/desktop/src/renderer/src/styles/index.css
@@ -0,0 +1,387 @@
+:root {
+ --bg: #ffffff;
+ --side: #f7f8f8;
+ --panel: #f7f8f8;
+ --line: #e4e7e7;
+ --text: #1f2328;
+ --muted: #6b7370;
+ --accent: #16a36a;
+ --accent-soft: #e7f5ee;
+ --warn: #b45309;
+ --warn-soft: #fdf3e5;
+ --danger: #b42318;
+ --danger-soft: #fdeceb;
+ --radius: 12px;
+ --font-ui: "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
+ --font-text: "Noto Serif SC", "Source Han Serif SC", "Songti SC", "STSong", serif;
+}
+
+* { box-sizing: border-box; }
+
+html, body, #root { height: 100%; margin: 0; }
+
+body {
+ background: var(--bg);
+ color: var(--text);
+ font-family: var(--font-ui);
+ font-size: 15px;
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+}
+
+button, input, select, textarea { font: inherit; color: inherit; }
+button { cursor: pointer; }
+button:disabled { cursor: not-allowed; opacity: 0.45; }
+
+.app { display: flex; height: 100%; }
+
+/* ---------- sidebar ---------- */
+
+.sidebar {
+ width: 264px;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ background: var(--side);
+ border-right: 1px solid var(--line);
+}
+
+.sidebar-brand {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 16px 16px 12px;
+}
+
+.brand-mark {
+ display: grid;
+ place-items: center;
+ width: 30px;
+ height: 30px;
+ border-radius: 8px;
+ background: var(--accent);
+ color: #fff;
+ font-weight: 700;
+ font-size: 13px;
+}
+
+.brand-name { font-weight: 650; font-size: 15px; }
+
+.sidebar-section { padding: 4px 10px; }
+.sidebar-section.grow { flex: 1; min-height: 0; display: flex; flex-direction: column; }
+
+.sidebar-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 6px 6px 4px;
+ color: var(--muted);
+ font-size: 12.5px;
+}
+
+.sidebar-list { overflow: auto; display: flex; flex-direction: column; gap: 2px; }
+.sidebar-section.grow .sidebar-list { flex: 1; }
+
+.sidebar-empty { margin: 4px 6px; color: var(--muted); font-size: 13px; }
+
+.tree { gap: 4px; }
+.tree-ws { display: flex; flex-direction: column; gap: 2px; }
+
+.ws-row {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 6px 6px;
+ border-radius: 8px;
+}
+.ws-row:hover { background: #eef0f0; }
+.ws-row.active { background: var(--accent-soft); }
+.ws-row.active .ws-name { color: var(--accent); }
+
+.ws-toggle {
+ border: none;
+ background: transparent;
+ color: var(--muted);
+ width: 18px;
+ padding: 0;
+ font-size: 11px;
+ line-height: 1;
+}
+
+.ws-name {
+ flex: 1;
+ min-width: 0;
+ border: none;
+ background: transparent;
+ text-align: left;
+ font-size: 14px;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ padding: 0;
+}
+
+.tree-convs { display: flex; flex-direction: column; gap: 1px; padding-left: 20px; }
+.sidebar-empty.indent { margin: 2px 8px; }
+
+.conv-row { display: flex; align-items: center; border-radius: 8px; }
+.conv-row:hover { background: #eef0f0; }
+.conv-row.active { background: var(--accent-soft); }
+.conv-row.active .conv-main { color: var(--accent); }
+
+.conv-main {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ padding: 6px 8px;
+ border: none;
+ background: transparent;
+ text-align: left;
+ font-size: 13.5px;
+}
+
+.item-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.item-count { color: var(--muted); font-size: 12px; }
+
+.item-x {
+ border: none;
+ background: transparent;
+ color: var(--muted);
+ padding: 0 8px;
+ font-size: 15px;
+ opacity: 0;
+}
+.conv-row:hover .item-x { opacity: 1; }
+.item-x:hover { color: var(--danger); }
+
+.status-dot { width: 7px; height: 7px; border-radius: 50%; background: #cfd4d1; flex-shrink: 0; }
+.status-dot.running { background: var(--warn); }
+.status-dot.done { background: var(--accent); }
+.status-dot.error { background: var(--danger); }
+
+.sidebar-foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 12px 16px;
+ border-top: 1px solid var(--line);
+}
+
+button.icon {
+ border: none;
+ background: transparent;
+ color: var(--muted);
+ font-size: 17px;
+ line-height: 1;
+ padding: 2px 6px;
+ border-radius: 6px;
+}
+button.icon:hover { color: var(--text); background: #eef0f0; }
+
+.pill {
+ padding: 3px 9px;
+ border-radius: 999px;
+ background: #eef0f0;
+ color: var(--muted);
+ font-size: 12px;
+}
+.pill.ready { background: var(--accent-soft); color: var(--accent); }
+.pill.error { background: var(--danger-soft); color: var(--danger); }
+
+/* ---------- main / welcome ---------- */
+
+.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+
+.welcome { flex: 1; overflow: auto; display: grid; place-items: center; padding: 32px; }
+
+.welcome-card { max-width: 620px; }
+.welcome-card h1 { margin: 0 0 8px; font-size: 26px; font-weight: 650; }
+.welcome-sub { margin: 0 0 20px; color: var(--muted); font-size: 15px; }
+
+.welcome-steps { list-style: none; margin: 0 0 16px; padding: 0; display: flex; flex-direction: column; gap: 10px; }
+.welcome-steps li {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 12px 14px;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: var(--panel);
+}
+.welcome-steps b { font-size: 14.5px; }
+.welcome-steps span { color: var(--muted); font-size: 13px; }
+
+.welcome-note { margin: 0 0 18px; color: var(--muted); font-size: 13px; }
+.welcome-actions { display: flex; gap: 10px; }
+
+/* ---------- conversation ---------- */
+
+.conversation { flex: 1; min-height: 0; display: flex; flex-direction: column; }
+
+.thread {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ width: 100%;
+ max-width: 860px;
+ margin: 0 auto;
+ padding: 24px 28px;
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+}
+
+.thread-hint { color: var(--muted); font-size: 13.5px; }
+
+.msg.user {
+ align-self: flex-end;
+ max-width: 82%;
+ padding: 12px 14px;
+ border-radius: 12px;
+ background: var(--accent-soft);
+ font-family: var(--font-text);
+ font-size: 15.5px;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+
+.msg.assistant { align-self: stretch; }
+
+.composer {
+ width: 100%;
+ max-width: 860px;
+ margin: 0 auto;
+ padding: 12px 28px 16px;
+ border-top: 1px solid var(--line);
+}
+
+.composer-input {
+ width: 100%;
+ min-height: 84px;
+ resize: vertical;
+ padding: 10px 12px;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: #fff;
+ font-family: var(--font-text);
+ font-size: 16px;
+ line-height: 1.7;
+}
+.composer-input:focus { outline: 2px solid var(--accent-soft); border-color: var(--accent); }
+
+.composer-bar { display: flex; align-items: center; gap: 8px; margin-top: 8px; }
+.composer-provider { margin-left: auto; color: var(--muted); font-size: 12.5px; }
+.composer.done-bar { display: flex; justify-content: flex-end; }
+
+/* ---------- buttons / chips / banners ---------- */
+
+button.primary, button.ghost, button.danger {
+ border-radius: 999px;
+ padding: 9px 18px;
+ border: 1px solid transparent;
+}
+button.small { padding: 6px 14px; font-size: 13.5px; }
+button.primary { background: var(--accent); color: #fff; font-weight: 600; }
+button.primary:hover:not(:disabled) { background: #128a59; }
+button.ghost { background: #fff; border-color: var(--line); }
+button.ghost:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
+button.danger { background: var(--danger); color: #fff; }
+
+.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
+.chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 3px 6px 3px 10px;
+ border-radius: 999px;
+ background: #fff;
+ border: 1px solid var(--line);
+ font-size: 12.5px;
+}
+.chip-x { border: none; background: transparent; color: var(--muted); padding: 0 4px; line-height: 1; }
+.chip-x:hover { color: var(--danger); }
+
+.banner { margin: 8px 0 0; padding: 9px 12px; border-radius: 10px; font-size: 13.5px; overflow-wrap: anywhere; }
+.banner.error { background: var(--danger-soft); color: var(--danger); }
+.banner.ok { background: var(--accent-soft); color: var(--accent); }
+.hint { margin: 8px 0 0; color: var(--muted); font-size: 13px; }
+
+/* ---------- run view ---------- */
+
+.run { display: flex; flex-direction: column; gap: 12px; }
+
+.phases { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
+.phase {
+ display: grid;
+ grid-template-columns: 14px 1fr auto;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 4px;
+ border-radius: 8px;
+ font-size: 14px;
+}
+.phase-detail { color: var(--muted); font-size: 12.5px; max-width: 60%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.phase-dot { width: 8px; height: 8px; border-radius: 50%; background: #cfd4d1; justify-self: center; }
+.phase.running { background: var(--warn-soft); }
+.phase.running .phase-dot { background: var(--warn); animation: pulse 1.2s ease-in-out infinite; }
+.phase.ok .phase-dot { background: var(--accent); }
+.phase.error { background: var(--danger-soft); }
+.phase.error .phase-dot { background: var(--danger); }
+@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } }
+
+.log {
+ max-height: 220px;
+ overflow: auto;
+ padding: 8px 12px;
+ border-radius: 10px;
+ background: var(--panel);
+ border: 1px solid var(--line);
+ font-family: var(--font-text);
+ font-size: 13.5px;
+ line-height: 1.7;
+}
+.log-line { padding: 1px 0; overflow-wrap: anywhere; }
+.log-line.warn { color: var(--warn); }
+.log-line.error { color: var(--danger); }
+.log-progress { margin-top: 4px; color: var(--accent); font-family: var(--font-ui); font-size: 12.5px; }
+
+.result { display: flex; flex-direction: column; gap: 10px; }
+.result-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; font-size: 14px; }
+.result-head.ok strong { color: var(--accent); }
+.result-head.error strong { color: var(--danger); }
+.result-head span { color: var(--muted); font-size: 12.5px; }
+.result-method { margin: 0; font-size: 13.5px; }
+.sources { display: flex; flex-wrap: wrap; gap: 6px; }
+.sources span { padding: 3px 9px; border-radius: 999px; background: var(--panel); border: 1px solid var(--line); color: var(--muted); font-size: 12.5px; }
+.figure { width: 100%; border-radius: 10px; border: 1px solid var(--line); background: #fff; }
+.buttons { display: flex; flex-wrap: wrap; gap: 8px; }
+.buttons button { padding: 7px 14px; }
+
+/* ---------- settings modal ---------- */
+
+.modal-backdrop {
+ position: fixed;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ background: rgba(31, 35, 40, 0.32);
+ z-index: 20;
+}
+.modal { width: min(520px, 100%); max-height: 86vh; overflow: auto; padding: 24px; border-radius: 16px; background: #fff; }
+.modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
+.modal-head h2 { margin: 0; font-size: 18px; }
+.field { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; font-size: 13.5px; }
+.field > span { color: var(--muted); }
+.field input, .field select { padding: 9px 11px; border: 1px solid var(--line); border-radius: 9px; background: #fff; font-size: 14px; }
+.field input:focus, .field select:focus { outline: 2px solid var(--accent-soft); border-color: var(--accent); }
+.modal-foot { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--line); }
+
+@media (max-width: 860px) {
+ .sidebar { width: 210px; }
+ .thread, .composer { padding-left: 16px; padding-right: 16px; }
+}
diff --git a/desktop/src/shared/api.ts b/desktop/src/shared/api.ts
new file mode 100644
index 0000000..10aedc9
--- /dev/null
+++ b/desktop/src/shared/api.ts
@@ -0,0 +1,112 @@
+// 主进程与渲染层共享的 IPC 形状。这里只放纯类型,不 import electron。
+
+export interface StudioMeta {
+ version: string
+ platform: string
+ electron: string
+ chrome: string
+}
+
+export type RuntimeState = 'starting' | 'ready' | 'error'
+
+export interface RuntimeStatus {
+ state: RuntimeState
+ message?: string
+ version?: string
+}
+
+export interface ProviderView {
+ id: string
+ display: string
+ models: string[]
+ model: string
+ baseUrl: string
+ requiresKey: boolean
+ custom: boolean
+ configured: boolean
+ note?: string
+}
+
+export interface ProviderList {
+ ok: true
+ providers: ProviderView[]
+ activeProvider: string
+}
+
+export interface SaveProviderInput {
+ id: string
+ model: string
+ apiKey?: string
+ baseUrl?: string
+}
+
+export interface ProblemFile {
+ path: string
+ text: string
+}
+
+export interface RunInput {
+ problem: string
+ dataPaths: string[]
+ providerId: string
+ model: string
+}
+
+export interface RunStartResult {
+ ok: true
+ runId: string
+}
+
+export type PhaseStatus = 'running' | 'ok' | 'error'
+
+export interface PhaseData {
+ id: number
+ label: string
+ status: PhaseStatus
+ detail?: string
+}
+
+export interface LogData {
+ level: 'info' | 'warn' | 'error'
+ text: string
+}
+
+export interface RunOutputs {
+ dir?: string
+ code?: string
+ resultJson?: string
+ png?: string
+ pdf?: string
+ svg?: string
+ paperPdf?: string
+ paperDocx?: string
+ paperTex?: string
+ paperError?: string
+}
+
+export interface DoneData {
+ ok: boolean
+ cancelled?: boolean
+ error?: string
+ outputs: RunOutputs
+ picked?: string
+ sources?: Record
+ seconds?: number
+}
+
+export interface RunEvent {
+ runId: string
+ id: string
+ event: string
+ data: Record
+}
+
+export interface RunSummary {
+ ok: boolean
+ error: string
+ problem: string
+ picked?: { name?: string }
+ sources?: Record
+ outputs: RunOutputs
+ seconds?: number
+}
diff --git a/desktop/tests/window-smoke.cjs b/desktop/tests/window-smoke.cjs
new file mode 100644
index 0000000..83ffb36
--- /dev/null
+++ b/desktop/tests/window-smoke.cjs
@@ -0,0 +1,111 @@
+/**
+ * 最小真启动冒烟:require 生产入口,等窗口与 runtime 就绪,按 DOM 与像素断言。
+ *
+ * 不联网、不需要 API Key;runtime 由主进程按 MMS_PYTHON 拉起。
+ * 退出码:0 全部通过 / 1 断言失败 / 2 窗口或构建产物没起来。
+ */
+const { app, BrowserWindow } = require('electron')
+const { mkdirSync, mkdtempSync, writeFileSync } = require('node:fs')
+const { tmpdir } = require('node:os')
+const { join } = require('node:path')
+
+const OUT_DIR = process.env.SMOKE_OUT || 'screenshots'
+const MIN_INK_RATIO = 0.01
+const results = []
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
+
+app.setPath('userData', mkdtempSync(join(tmpdir(), 'mms-smoke-')))
+require('../out/main/index.js')
+
+function record(name, ok, detail) {
+ results.push({ name, ok: Boolean(ok), detail: String(detail ?? '') })
+}
+
+async function waitFor(check, timeoutMs, stepMs = 250) {
+ const end = Date.now() + timeoutMs
+ while (Date.now() < end) {
+ try {
+ const value = await check()
+ if (value) return value
+ } catch {
+ // 页面还没加载完,下一轮再试
+ }
+ await sleep(stepMs)
+ }
+ return null
+}
+
+function inkRatio(image) {
+ const { width, height } = image.getSize()
+ if (!width || !height) return 0
+ const bitmap = image.toBitmap()
+ let ink = 0
+ for (let index = 0; index + 3 < bitmap.length; index += 4) {
+ if (bitmap[index] < 245 || bitmap[index + 1] < 245 || bitmap[index + 2] < 245) ink += 1
+ }
+ return ink / (width * height)
+}
+
+function finish(code) {
+ mkdirSync(OUT_DIR, { recursive: true })
+ const payload = { ok: code === 0, at: new Date().toISOString(), results }
+ writeFileSync(join(OUT_DIR, 'window-smoke.json'), JSON.stringify(payload, null, 2))
+ process.exitCode = code
+ for (const win of BrowserWindow.getAllWindows()) win.destroy()
+ setTimeout(() => app.exit(code), 100)
+}
+
+async function main() {
+ const win = await waitFor(() => BrowserWindow.getAllWindows()[0], 20_000)
+ if (!win) {
+ record('窗口创建', false, '20 秒内没有窗口')
+ return finish(2)
+ }
+ record('窗口创建', true, win.getTitle())
+
+ const ready = await waitFor(
+ async () => {
+ const text = await win.webContents.executeJavaScript('document.body.innerText')
+ return text.includes('就绪') && !text.includes('启动中') ? text : null
+ },
+ 30_000,
+ 400
+ )
+ if (!ready) {
+ record('runtime 就绪', false, '30 秒内没有出现“运行时就绪”')
+ return finish(2)
+ }
+ record('runtime 就绪', true, '握手完成')
+
+ record('窗口标题', win.getTitle() === 'MathModel Studio', win.getTitle())
+ const [width, height] = win.getContentSize()
+ record('内容尺寸 1280x860', width === 1280 && height === 860, `${width}x${height}`)
+ record(
+ '加载构建产物',
+ win.webContents.getURL().includes('/out/renderer/index.html'),
+ win.webContents.getURL()
+ )
+ for (const text of ['MathModel Studio', '把赛题变成可交付的论文', '工作区', '对话', '新建对话', '设置']) {
+ record(`界面含「${text}」`, ready.includes(text), text)
+ }
+
+ const image = await win.webContents.capturePage()
+ const ratio = inkRatio(image)
+ record('画面非空白', ratio >= MIN_INK_RATIO, `墨迹占比 ${(ratio * 100).toFixed(1)}%`)
+ try {
+ mkdirSync(OUT_DIR, { recursive: true })
+ writeFileSync(join(OUT_DIR, 'window-smoke.png'), image.toPNG())
+ } catch (err) {
+ record('截图落盘', false, err instanceof Error ? err.message : String(err))
+ }
+
+ const failed = results.filter((item) => !item.ok)
+ return finish(failed.length ? 1 : 0)
+}
+
+app.whenReady().then(() => {
+ main().catch((err) => {
+ record('冒烟脚本', false, err instanceof Error ? err.stack || err.message : String(err))
+ finish(1)
+ })
+})
diff --git a/tsconfig.json b/desktop/tsconfig.json
similarity index 100%
rename from tsconfig.json
rename to desktop/tsconfig.json
diff --git a/tsconfig.node.json b/desktop/tsconfig.node.json
similarity index 100%
rename from tsconfig.node.json
rename to desktop/tsconfig.node.json
diff --git a/tsconfig.web.json b/desktop/tsconfig.web.json
similarity index 100%
rename from tsconfig.web.json
rename to desktop/tsconfig.web.json
diff --git a/docs/PLAN.md b/docs/PLAN.md
deleted file mode 100644
index 4b1219b..0000000
--- a/docs/PLAN.md
+++ /dev/null
@@ -1,257 +0,0 @@
-# mathmodel-studio · 前期调研与实施方案
-
-日期 2026-10-16 | 状态:待你定第 9 节三项,之后从 M0 开工
-
-## 0 已锁定的四个决策
-
-| 项 | 结论 |
-|---|---|
-| skills 内容来源 | vendor 一份进新仓库,保留出处(`mathmodel-kit` v2.0.1,同作者 Apache-2.0) |
-| Agent 运行时 | 自研 Python runtime,BYOK 任意模型(不绑 Claude Code) |
-| v1 边界 | 先做桌面 shell + 编排闭环(选模/解释/门禁/评分),完整排版编译放 M5 |
-| 打包形态 | 内置便携 Python 运行时(bundled `uv` + python-build-standalone) |
-
-一句话定位:**本地、可审计、人在环的数模工作台**。赛道里"全自动无需人工干预"已经有人占了(见第 2 节),我们反着打:每个关键判断都交给参赛者点一下,并且每个数字都能追到脚本产物。
-
----
-
-## 1 源项目能继承什么
-
-`Escap1ng/mathmodel-kit`(★6,pushed 2026-09-18,v2.0.1)拆开看是四层资产:
-
-| 层 | 现成资产 | 桌面端要做的事 |
-|---|---|---|
-| 编排 | `mathmodel-core/SKILL.md` 阶段零~六强制流程:环境预检 → 赛题分析 → 工作目录 → 算法选择 → 代码实现 → 论文输出 → 评分优化(S≥85、熔断 3 轮) | 阶段变成**可视轨道 + 可中断状态机**,不再只是一段提示词 |
-| 契约 | `skills/manifest.json` 单一事实源(kind: core/knowledge/tool、contribution: open/maintainer);CLI 退出码统一 `0 成功 / 1 校验或渲染失败 / 2 用法或环境错误`;接口稳定性分 Stable / Experimental / Internal 三档;JSON Schema Draft 2020-12 内容契约 | 注册表**扩展出 UI 元数据**(见 6.2),让界面从数据渲染而不硬编码 |
-| 内容 | 7 个技能、25 个模板(`mathmodel-figure` 20 个 matplotlib + `mathmodel-diagram` 5 个 JSON 驱动版式,按文件树实数)、6 项 Python 依赖、中英双语音料 | 原样 vendor,加 provenance 记录 |
-| 门禁 | `deai`:`check_phrasing.py`(词表)/`check_style.py`(结构)/`strip_invisible.py`(字符);`score`:`check_chapters.py`(章节门槛)/`score_card.py`(五维 30/20/20/15/15);CI 校验 manifest ↔ 目录 ↔ README 表 ↔ 徽章计数 | 门禁结果**从退出码升格成界面元素**(门禁条 + 可点击定位) |
-
-kit 的三个缺口,正是这个产品的全部工作量:**没有 UI**、**没有 provider 层**(模型由宿主 agent 决定)、**没有持久化状态**(中断即丢,谈不上"人在环")。
-
----
-
-## 2 同类项目对照
-
-星数与日期为 2026-10-16 `gh api` 实测。
-
-| 项目 | 规模 | 形态 | 技能机制 | 人在环 | 对我们的意义 |
-|---|---|---|---|---|---|
-| `jihe520/MathModelAgent` | ★6211,pushed 2026-10-03,主语言报 TeX | FastAPI + Vue3/Vite/reka-ui/marked/katex + Docker + **官方桌面版** | 11 个 skill:`1start`…`6verity` + `mathmodel-to-ei`/`doctor`/`typst-author`/`figure-templates`/`_references`;17 套 Typst 模板;9 步自动验收 | **明确写"无需人工干预"** | 头号对手。它的桌面版做法是**内置 Claude Code + 全套 skill,UI 只做壳**——所以我们自研 runtime 是差异点不是重复;它的 Vue 依赖清单(marked/katex/highlight.js/lucide/motion)是现成的渲染器 checklist |
-| `LKQ667/metamath-harness` | ★22,pushed 2026-09-24 | DeepSeek Harness 增强套件 | `.dsh/skills/` 下 `math-paper-cn`/`-en`/`-huashu`,step0–5 硬门禁直通 LaTeX/PDF | 手动 Skill 卡片 | 门禁强度可参照:它按**编译后 PDF 的实际页面坐标**核对"符号说明标题 → 符号表 → 问题一"阅读顺序,并拒绝复用过期编译产物。**教训**:桌宠插件 2026-09-20 下架,官方原因是"常驻动画渲染造成卡顿" |
-| `CherryHQ/cherry-studio` | ★52672,pushed 2026-10-16 | Electron 44 + electron-vite + React 19 | `resources/skills/*/` + builtin-agents;agent 模式 spawn Claude Code CLI | 选项卡式提问 | **便携 Python 的生产级实现**:`src/main/services/binaryManager/pythonRuntime.ts`(6047 B)钉 `DEFAULT_VERSION = '3.12.13'`,中国镜像走 `registry.npmmirror.com/-/binary/python-build-standalone`,注释第 77 行写"绝不收养系统解释器,只认自己的安装目录"。三栏 shell + 右栏命名预设 + `@cherrystudio/file-preview`(PDF/DOCX/SVG) + 本机 OpenAI 兼容网关。**避坑**:CVE-2025-61929,`cherrystudio://` 自定义协议一键装 MCP 导致 RCE |
-| `lobehub/lobehub`(原 lobe-chat 已改名) | ★83267,pushed 2026-10-16 | Electron 薄壳 over Next.js | `packages/builtin-skills/src/manifests.ts` → `BuiltinSkillManifest[]`,每个技能 `manifest.ts` + `content.ts` | artifact canvas | `native-deps.config.mjs`:为 Vite 自动 externalize `.node`、从 asar 解包、剔除非目标平台 prebuild —— Windows 打包直接抄这段 |
-| `Mintplex-Labs/anything-llm` | ★67180 | React+Vite + Node server:3001 + collector | workspace 隔离向量集 | 会话级 | **反面教材**:`CONTRIBUTING.md` 自述桌面壳是把核心代码复制进私有仓库维护 → 单仓不要拆 |
-| `janhq/jan` | ★44963,主语言 Rust | Tauri + Next.js | 引擎 Cortex/llama.cpp | — | 本机 `127.0.0.1:1337` OpenAI 兼容服务;`src-tauri/utils/src/http.rs` 白名单只放 loopback/RFC1918/link-local 字面量、拒公网地址(防 DNS rebinding)——我们绑端口时照抄这个校验 |
-| `open-webui/open-webui` | ★155958 | Svelte5 由 FastAPI 直供 | — | — | "一个 Python 进程同时供 UI 与 API"跑得动;但桌面故事靠第三方壳 |
-
-三条收敛结论:
-
-1. **栈**:可比项目约 8:2 收敛在 Electron + React + Vite + electron-builder,agent 作为子进程(stdio JSON-RPC 或 localhost HTTP+SSE),不是 Tauri。OpenCode 在 2026-04 从 Tauri 回退 Electron,理由是各平台 WebKit 渲染漂移、内置 CLI 启动延迟、Windows 启动不稳。**本机也验证过 Tauri 走不通**(第 3 节)。
-2. **交互词汇**已被验证:三栏布局、流式工具卡、`AskUserQuestion` 式可点选项卡、按 prompt 建 checkpoint 并可回滚(代码/对话/两者)。
-3. **空位**:所有开源数模 agent 的界面都停在"能用",商业桌面版(B 站那几个全自动论文生成器)界面是十年前的 Win32 味。**白底 + 精致 + 人在环**这一格没人占。
-
----
-
-## 3 本机实测(可行性的钉子)
-
-全部由本轮命令产出,不是推断。
-
-| 检查 | 结果 | 影响 |
-|---|---|---|
-| `node -v` / `npm -v` | v24.18.1 / 11.16.0 | Electron 可开发 |
-| `python -V` | 3.14.5;`numpy 2.4.4` `matplotlib 3.10.9` `seaborn 0.13.2` `pandas 2.3.3` `jsonschema 4.26.0` `PyMuPDF 1.28.0` `python-docx 1.2.0` 均可 import | kit 的 6 项依赖在本机已满足,工具层能立刻跑 |
-| `rustc` / `cargo` | 1.98.0 / 1.98.0,host `x86_64-pc-windows-msvc` | 看着能装 Tauri,实则 |
-| `where link.exe` | 命中 `D:\git\usr\bin\link.exe` → `link (GNU coreutils) 8.32`,**不是 MSVC 链接器** | 假阳性,必须辨认 |
-| VS / Windows SDK | `C:\Program Files\Microsoft Visual Studio` 不存在;`Windows Kits\10\Lib` 不存在;`cl.exe` 找不到 | **Tauri 在本机不可构建**,Electron 是唯一路 |
-| `xelatex` | MiKTeX-XeTeX 4.16(MiKTeX 25.12) | M5 排版可本地真跑 |
-| `pandoc` | 2026-10-16 未安装;2026-10-30 装好 3.13(`%LOCALAPPDATA%\mms-tools\pandoc.exe`) | M5 的 Word 链路已接通 |
-| `registry.npmjs.org` | `npm view electron` 25 s 超时 | 直连不可用 |
-| `registry.npmmirror.com` | 200,1.37 s;Electron 二进制镜像 HEAD → 302 | **镜像可用**,装依赖走 npmmirror |
-| `github.com:443` | `curl` 超时;同一时刻 `gh api` 全程正常 | api 通道 ≠ git 通道,push/release 需备代理,写进手册不自动执行 |
-| `pypi.tuna.tsinghua.edu.cn` | 本轮 20 s 超时 | Python 依赖走 npmmirror 的 python-build-standalone + pip 镜像,且失败要换手段重试 |
-| `gh auth status` | 已登录 `Escap1ng`,token 含 `repo` `delete_repo` `workflow` | 建仓与 Actions 可行 |
-
----
-
-## 4 产品形态与交互设计
-
-### 4.1 窗口(以 1440×900 为基准,最小 1100×700)
-
-```
-┌──────────┬───────────────────────────────┬──────────────────┐
-│ 左栏 240 │ 中栏 · 对话流(正文列宽 760) │ 右栏 400–480 │
-│ │ │ 可折叠成 48 图标条│
-│ 赛题会话 │ 用户消息 │ │
-│ 列表 │ Agent 流式回复 │ 标签页: │
-│ │ ▸ 工具卡(模板 id / 退出码 / │ 图表 · 论文 · │
-│ ──────── │ 耗时,可展开 stderr) │ 代码 · 评分 · │
-│ 阶段轨道 │ ▸ 选模卡(见 4.3 K3) │ 门禁 · 日志 │
-│ 零…六 │ ▸ 门禁失败条(可点定位) │ │
-│ 每阶段 │ │ 预览:pdf.js 渲染 │
-│ 状态点 + │ ┌──────────────────────────┐ │ paper.pdf、图片 │
-│ 产物计数 │ │ 输入区:模型选择器 · 阶段 │ │ 300DPI 图、 │
-│ │ │ 开关 · 附件拖放 · 停止 │ │ content JSON │
-└──────────┴───────────────────────────────┴──────────────────┘
-```
-
-### 4.2 七个阶段是一条可视轨道,不是一段提示词
-
-kit 的阶段零~六直接映射为状态机节点,每个节点显示:状态(待办/进行/阻塞等待你/已过/未过)、耗时、产物计数、绑定的门禁。阶段图标上挂"等待你"的呼吸点,让"agent 卡在哪一步"一眼可读——这是全自动产品最缺的透明度。
-
-### 4.3 人在环卡点清单(本产品的核心差别)
-
-每个卡点 = 一次 `interrupt()` + 一个 JSON payload + 一个 UI 组件 + 一条恢复语义。关窗再开仍停在原处(SqliteSaver 持久化)。
-
-| 卡点 | 触发 | 界面 | 契约出处 |
-|---|---|---|---|
-| **K1 环境预检** | 阶段零检出缺件 | 缺件表:项目 / 检测命令 / 期望 / 建议动作;能自动补的(pip)给"补装"按钮,系统级的(pandoc/MiKTeX)只给指引,不偷装 | core 阶段零 4 条清单 |
-| **K2 赛题与附件确认** | 题目解析完 | 子问题卡片 + 附件列表;逐问标注"数据表 X / 共用一套数据",并把**数据角色判定**摊开显示(训练集目标列非空数、预测集目标列为空、行数、时间范围)——kit 明令"靠文件名猜不算完成" | core 阶段一第 5、6 条;implementation-guide §3.5 |
-| **K3 选模卡**(旗舰) | 阶段三 | 2–3 张并排卡,字段照抄 kit 表格列:核心思路 / 创新度 / 可解释性 / 实现难度 / 预计耗时(按本题数据规模给量级)/ 精度与鲁棒性预期;推荐项带徽标 + 一句理由;每卡三钮 **[选它] [解释] [换一批]**;至少 1 项带明显创新性由契约强制 | core 阶段三 |
-| **K4 就地解释** | 点方法名 / 公式 / 图 / 扣分项 | 右栏抽屉打开:数学形式(KaTeX)、为何适配本题数据规模与约束、与未选方案的差异、验证方式、预计运行时间、对应规范条文链接。**打开抽屉不清除 K3 的待选状态**;正文里方法名/评分项渲染为细虚线下划线,hover 出摘要、点击进抽屉 | methods `selection-guide`;score `rubric` |
-| **K5 图表返工** | 任意图产物 | 换模板(按 20 模板注册表给候选)/ 换主题(`themes/*.theme.json`,改色不改码)/ 换数据列 / 改字号密度;新旧并排 diff,保留旧版可回滚;`--check` 容量超框直接标红而不产出 | figure/diagram CLI;`validate_theme.py` |
-| **K6 评分与优化轮次** | 阶段六 | 五维条形 + 总分 S 与 ≥85 判定;扣分明细可点进"改哪一句";每轮列出上一轮改了什么;轮次到 3 熔断并按 kit 原话标注"未达 85 分标准,需人工复核";一票否决项(身份信息/页眉)红色横条、不进循环 | score `rubric` / `chapter-checklist` / core 阶段六 |
-
-另外两条贯穿性交互:
-
-- **追溯链**:论文里每个数字都能点 → 产出它的脚本 → 那次运行的事件与 stdout。把 kit"论文数字能追溯到脚本产物"的口号做成一个真实可点的链条。
-- **回滚**:按 prompt 建 checkpoint,可只回代码、只回对话、或两者都回(Claude Code 的 rewind 语义)。**注意它不跟踪 Bash 副作用**,我们的产物目录走快照,否则"回滚"是假的。
-
-### 4.4 视觉方向(主色白,三案待选)
-
-| 案 | 强调色 | 语义色 | 性格 |
-|---|---|---|---|
-| A 松绿 | `#16A36A`,hover `#0E8A58` | 成功 `#2F7A55` 警示 `#A9631C` 失败 `#A63232` | 对话与工作台的主操作色 |
-| B 靛蓝 | `#2B4C7E`,hover `#1F3A63` | 同上 | 工具感、克制的"高级" |
-| C 朱砂 | 主 `#1A1D21` + 点缀 `#B03A2E` | 靠排版分层 | 最不像 AI 生成的,风险也最高 |
-
-统一基底:白色主体 `#FFFFFF`、侧栏/状态栏 chrome `#F4F5F6`、面板面 `#F3F4F5`、发丝线 `#E9EBED`、主文 `#1A1D21`、次文 `#5F666D`;阴影只用 `0 1px 2px rgba(16,24,40,.06)` 与 `0 8px 24px rgba(16,24,40,.08)` 两级。层次优先用色块与留白,细线只留给表单控件。中文正文 `16px/1.75`,数字一律 tabular-nums,等宽用 Maple Mono NF CN(自托管,不嵌 OS 字体)。**动效预算**:只做状态变化(120–200ms ease-out)与流式光标,**不做常驻动画**——metamath-harness 的桌宠因常驻渲染卡顿被下架,这条是花钱买的结论。
-
----
-
-## 5 技术架构
-
-### 5.1 三层
-
-```
-src/ Electron 壳:窗口、IPC、provider 密钥、更新、打包 ← 不写业务规则
-runtime/ Python:阶段状态机、provider 适配、工具调用、产物、事件 ← 唯一编排者
-skills/ vendor 自 kit:方法论 + 模板 + 检查器 + Schema ← 只读契约与脚本
-```
-
-runtime **subprocess 调用** skills 里的脚本并按退出码判定,不 import 其私有函数——这样 skills/ 仍可独立被 Claude Code 使用,符合"复制哪一个哪一个就能单独用"的原承诺。
-
-### 5.2 传输:localhost HTTP + SSE,stdio 只管生命周期
-
-主进程 `spawn` Python(`--port 0`),子进程在 stdout 打印一行 `{port, token}` 完成握手;此后全部走 HTTP。只绑 `127.0.0.1`,每个请求校验 `Origin`/`Host` 并按 Jan 的 loopback 白名单拒绝公网地址(防 DNS rebinding)。
-
-- 控制面 REST:`POST /runs`、`POST /runs/{id}/resume`、`POST /runs/{id}/cancel`、`GET /runs/{id}/events`
-- 事件面 SSE:`token` / `reasoning` / `tool_call` / `artifact` / `interrupt` / `gate` / `error` / `done`,带 `id:` 与 `Last-Event-ID` 续传,`: ping` 保活
-- 产物一律以 `/files/...` URL 传,支持 HTTP Range(pdf.js 需要);**不用 base64 塞大文件**,仅小图标内联
-- 理由:SSE 自带重连语义,省去自研帧协议;浏览器对单 host HTTP/1.1 有约 6 连接上限,所以保持"一条流 + 一条控制面"
-
-### 5.3 编排与持久化
-
-LangGraph `interrupt()` + `SqliteSaver`(`thread_id` = 赛题会话)。选它的唯一理由:它是主流框架里唯一给出**可跨进程重启存活**的暂停语义、且 payload 是 JSON 可直接渲染成选项卡的方案。OpenAI Agents SDK 的 `to_state()` 也能持久化但循环不由我们写;Claude Agent SDK 的 `canUseTool` 是活回调、不耐久且 Anthropic-only,直接排除(它的 AskUserQuestion payload 形状可以抄)。
-
-**硬约束**:`interrupt()` 所在节点会从顶部重新执行,因此任何非幂等副作用(编译、写文件、花 token)必须放在 interrupt 之后。这条会写进 runtime 的 AGENTS 约束并在契约测试里设防。
-
-### 5.4 provider 层("好用的 AI 接口"的对内一半)
-
-自研矩阵,不用 LiteLLM:官方 `openai` SDK 配 `base_url` + 一层薄 Anthropic 适配器 + **`providers.json` 能力注册表**。字段:`id / display / base_url / auth_style / models[] / tool_calling / streaming_tools / reasoning_field / thinking_extra_body / context_len / max_out`。预设 DeepSeek、Kimi、通义/DashScope、智谱 GLM、火山方舟、OpenRouter、Ollama、OpenAI、Anthropic,外加"自定义 OpenAI 兼容端点"。
-
-已知怪癖按数据登记而非散在代码里:Qwen 的 `enable_thinking` 需走 `extra_body` 且流式字段是 `reasoning_content`(重放历史前必须剥离);Anthropic 开 `thinking.budget_tokens` 会强制 `temperature=1`;OpenAI o 系列忽略 temperature;Ollama 的 `/v1` 兼容层滞后;vLLM/SGLang 不加 `--enable-auto-tool-choice --tool-call-parser` 会**静默**丢掉工具调用。归一化成 `content` 与 `reasoning` 两类事件。
-
-密钥:只进 Electron `safeStorage`(Windows 侧 DPAPI),**磁盘上任何 JSON 不落明文**;号池轮转 + 429 退避 + 每模型成本与额度计量。可按阶段分配模型(选模与摘要用强模型,批量代码与检查用便宜模型)。
-
-### 5.5 "好用的 AI 接口"的对外一半
-
-延续 kit 的接口开放承诺,三个出口:
-1. `mms skills --json` / `mms invoke --json` —— 能力可列举、可校验、可编排,退出码沿用 `0/1/2`
-2. 本机 OpenAI 兼容网关(Cherry 的 apiGateway / Jan 的 :1337 先例)—— 别家客户端能把我们的 agent 当模型用
-3. 可选 MCP server —— 让 Claude Code / Cursor 直接调 skills
-
-稳定性同样分档:命令行参数与退出码、注册表字段、产物路径 = **Stable**;`--lang`、事件字段顺序、错误措辞 = **Experimental**;内部几何常量与基元签名 = **Internal**。
-
-### 5.6 工作区目录沿用 kit 阶段二规范
-
-`第X题_赛题简称/answer/{code,figures/final,figures/tmp,paper}`,交付/打包前整体删 `tmp`;`figures/final` 语义命名 `fig{图号}_{题型}_{内容}.png/pdf`,≥300 DPI 且必须被 `paper.tex` 引用(这条做成门禁,不靠自觉)。
-
-### 5.7 便携 Python
-
-照 Cherry 的做法:bundled `uv` + python-build-standalone **3.12.13**(不是本机 3.14——科学计算 wheel 面在 3.12 最厚,且这是上游已验证的钉法),装进应用自有目录,npmmirror 优先再回落官方源,**绝不收养系统解释器**。体积代价预估安装包 300–400 MB(Electron ~100 + Python+whl ~200);早期实测为 264 MB,原估偏高。
-
-LaTeX 路线已在 2026-10-30 定为 **xelatex 优先**(接 kit 现状),Word 由 pandoc 转换;Tectonic/Typst 不作为 v1 路径。打包方式(要求本机装 / 内置)留到 M6。中文排版另有一条暗坑:`xeCJK` 依赖本机 SimHei/SimSun 存在,`plot_style.pick_cjk_font` 的字体回退要同样用于预览。
-
----
-
-## 6 仓库结构与 CI 门禁
-
-### 6.1 结构
-
-```
-Escap1ng/<仓库名>/
-├── README.md / README_EN.md / CHANGELOG.md / VERSION / LICENSE(AGPL-3.0-only)
-├── docs/ 架构、交互规格、provider 指南、环境手册、upgrade-plan(+_EN)
-├── skills/ vendor 自 kit v2.0.1,含 VENDOR.md 记录来源 commit 与差异
-├── runtime/ providers/ orchestrator/ tools/ artifacts/ server/ events/
-├── src/ Electron 壳:main/ preload/ renderer/(沿用 electron-vite 默认目录约定,
-│ 不另设 desktop/——少一批自定义路径,Windows 首运行更容易一次通过)
-├── schemas/ 技能注册表、事件流、选模 payload、评分卡、provider 矩阵
-├── tests/ 契约测试 + 门禁自检 fixture
-└── .github/workflows/ ci / gates / desktop-build / release
-```
-
-### 6.2 对 kit manifest.json 的唯一结构性增量
-
-给每个 skill 增加 `ui` 与 `hitl` 元数据(入口图标、产物类型、可渲染的 payload schema、是否阻塞等待)。**界面从注册表生成,不硬编码技能清单**——第三方加一个技能,UI 就多一个卡,这正是把 kit 的"契约开放"从命令行推进到图形界面。
-
-### 6.3 六道门禁,且每条都要证明它会失败
-
-| 门禁 | 内容 | 反向验证 |
-|---|---|---|
-| G1 注册表一致 | `skills/manifest.json` ↔ `skills/` 目录 ↔ README 技能表 ↔ 徽章计数 | 故意删一行注册表,CI 必须红(继承 kit 已验证的做法) |
-| G2 Schema 校验 | 所有契约文件按 Draft 2020-12 校验;skills frontmatter 过 `skills-ref validate`,保证仍可被 Claude Code 装载 | 喂一个非法 payload 必须非零退出 |
-| G3 工具层契约 | 每个 skill CLI 的 `--list --json` / `--check` / `validate_*` 输出结构与退出码 | 断言 `0/1/2` 三码各自可达 |
-| G4 事件流契约 | SSE 事件类型与字段顺序快照;`interrupt` payload 必须能渲染成选模卡 | 缺字段 → 渲染层抛错而不是白屏 |
-| G5 provider 离线 contract | 用本地假端点跑流式/工具调用/`reasoning_content` 剥离/429 退避 | 每个怪癖一条 fixture;**fixture 必须真跑过被测代码** |
-| G6 桌面构建 | TS 类型检查 + 打包 + 无窗口 smoke(起进程、握手、拿注册表、渲染 25 模板清单) | 已知风险:CI 里 Electron 需 xvfb;且**检查器要能失败**——把 smoke 的断言反过来跑一次确认非零 |
-
----
-
-## 7 里程碑
-
-| 阶段 | 交付 | 可运行判据 |
-|---|---|---|
-| **M0** 脚手架 | 仓库、双语 README 骨架、CI 空跑、**环境手册**(npmmirror/镜像钉法、pandoc/MiKTeX 只写指引不代跑) | 新人照手册能 `npm i` 起一个空窗 |
-| **M1** skills 落地 | vendor + VENDOR.md + G1/G2/G3;runtime 无 LLM 也能"列举 25 模板、渲染一张、跑一次门禁" | `mms invoke figure paired-raincloud` 出 PNG/PDF/SVG 且退出码正确 |
-| **M2** 通道与壳 | Python 子进程握手、SSE 事件、Electron 三栏空壳、流式渲染、provider 设置页 + safeStorage | 选 DeepSeek/Kimi 任一家,能在 UI 里流式对话并显示工具卡 |
-| **M3** 编排闭环 | 阶段状态机 + SqliteSaver + **K2/K3/K4** | 提交一道题 → 停在选模卡 → 关窗重开仍停在原处 → 点选后继续;"解释"打开抽屉且不清除待选 |
-| **M4** 工作台 | 右栏 pdf.js/图预览 + **K5** + 门禁条 + 评分卡 **K6** | 一张图能换主题重渲并回滚;一份稿子能出五维评分与扣分定位 |
-| **M5** 排版全链路 | xelatex/pandoc 接入、交付门禁、`tmp` 清理、一票否决红线 | 一题进、`paper.pdf`+`paper.docx` 出,deai/score 全绿 |
-| **M6** 发布 | 便携打包(NSIS + 可选全内置大包)、截图、示例赛题、Release | Windows 干净机装完填 key 即可跑通一道真题 |
-
-签名与公证不在 M6 默认项里:MathModelAgent 的 Windows 包至今未签名、README 里专门写了如何绕过 SmartScreen。打包起改用自签名证书,证书根不受信任,SmartScreen 的告警照旧;是否花钱买受信任的证书留给你决定(macOS 侧它是 Developer ID 签名 + 公证都做齐了)。
-
----
-
-## 8 风险登记
-
-| 风险 | 概率 | 处置 |
-|---|---|---|
-| `github.com:443` 与 pip 直连随时翻转(本轮已实测 npm/github 超时、`gh api` 正常) | 高 | 全部联网动作写成手册;镜像失败换手段(换端口/换协议/换通道)后再报失败 |
-| Electron 在 CI 无显示器 | 中 | headless + xvfb,或主进程逻辑抽到可单测的纯函数 |
-| LangGraph 拖入 langchain-core 语义 | 中 | 只用 `interrupt`/`SqliteSaver` 两点,把依赖面写死在 G6;不可控则自研 200 行状态机(已识别为可退让项) |
-| provider 工具调用漂移(尤其国产 + Ollama) | 高 | 能力矩阵按数据登记,UI 在缺 `tool_calling` 时降级为"建议式工具调用",不谎报 |
-| 中文 LaTeX 缺字体 / matplotlib 方框 | 中 | 阶段零把字体也当依赖检测;复用 `pick_cjk_font` |
-| 安装包体积与签名告警 | 中 | 早期实测 264 MB;自签名证书根不受信任,SmartScreen 仍告警,要消除得换受信任证书 |
-| 单人维护、面铺太宽 | 高 | v1 边界已收窄到 M3/M4;排版与 EI 改稿后置;每步有可运行判据 |
-
----
-
-## 9 需要你定的三件事
-
-1. **仓库名**。候选:`mathmodel-studio`(撞名 `yan315598-design/mathmodel-studio` ★47,但全名带你的命名空间仍唯一)/`mathmodel-desk`/`mathmodework`(都不撞)。
-2. **UI 依赖取向**:手写 CSS 令牌 + 只引 Radix 原语(无 Tailwind,视觉可控、少一层"AI 味")/Tailwind v4(快,但默认观感要额外压)。kit 和 VisualLaTeX 都是零依赖取向,我倾向前者,但它会让每个视觉细节都变成真代码。
-3. **排版引擎优先级**(2026-10-30 已定):xelatex 优先,pandoc 出 Word;Typst 不进入 v1。
-
-定完我从 M0 开工:先建仓、出双语 README 骨架和环境手册,再动代码。
diff --git a/docs/env-setup.md b/docs/env-setup.md
deleted file mode 100644
index 31ede5b..0000000
--- a/docs/env-setup.md
+++ /dev/null
@@ -1,138 +0,0 @@
-# 环境准备手册
-
-这份文档只做一件事:把**需要联网的动作**写清楚,让它在你的机器上可重复。
-本项目不会自动替你下载或安装任何东西——缺件时程序只报出该装什么、怎么装。
-
-实测数据来自 2026-10-16 一台 Windows 10 (26100) / x64 机器,命令与返回一并写出来,方便你判断是不是同一个症状。
-
-## 1 先看通道,再看版本
-
-网络通道会翻转,**任何一条失败先换通道重试再下结论**:
-
-| 目标 | 命令 | 实测结果 | 结论 |
-| --- | --- | --- | --- |
-| npm 官方源 | `npm view electron version` | 25 s 超时无输出 | 大陆直连不可用,走镜像 |
-| npmmirror | `curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" https://registry.npmmirror.com/electron` | `200 1.37s` | 可用,作为默认 |
-| Electron 二进制镜像 | `curl -sI https://npmmirror.com/mirrors/electron/v33.2.0/electron-v33.2.0-win32-x64.zip` | `HTTP/1.1 302` | 可用 |
-| github.com | `curl -s -o /dev/null -w "%{http_code}" https://github.com/...` | 超时 | git clone / release 下载不稳 |
-| api.github.com | `gh api repos/Escap1ng/mathmodel-kit --jq .full_name` | 正常返回 | **api 通道 ≠ git 通道**,能 `gh api` 不代表能 `git push` |
-| TUNA pypi | `curl -s -o /dev/null -w "%{http_code}" https://pypi.tuna.tsinghua.edu.cn/simple/` | 20 s 超时(本轮) | 镜像本身也会挂,别当成配置错了 |
-
-两个判读陷阱,都是踩过才知道的:
-
-- **别把慢当死锁**。`npm install` / `uv sync` 卡住时,如果你加了 `| tail`、`| grep` 之类的管道,输出被全缓冲,看起来像挂了,其实是 KB/s 级慢。先摘掉管道再看。
-- **管道之后的 `$?` 是管道的退出码**,不是被测命令的。要判死活就 `cmd; echo "exit=$?"` 或者 `set -o pipefail`。
-
-## 2 镜像配置
-
-仓库里的 [`.npmrc`](../.npmrc) 已经钉了 Electron 与 electron-builder 的二进制镜像,`npm install` 会直接生效:
-
-```ini
-electron_mirror=https://npmmirror.com/mirrors/electron/
-electron_builder_binaries_mirror=https://npmmirror.com/mirrors/electron-builder-binaries/
-```
-
-**信任边界说明**:这两行把下载通道从官方 CDN 换成了第三方镜像。包内容与校验值一致,但通道不同——不在大陆的开发者请删掉这两行。
-
-如果你的 `npm` 源本身也慢,再加一行 registry(这一行没进仓库,因为它会改变所有依赖的解析来源,CI 用官方源更合适):
-
-```ini
-registry=https://registry.npmmirror.com/
-```
-
-临时用一次,不想改文件:
-
-```bash
-npm install --registry=https://registry.npmmirror.com/
-```
-
-## 3 版本怎么来的(别照抄数字)
-
-`package.json` 里每个 JS 依赖的版本都是这么查出来的,不是猜的,也不是从旧文档抄的:
-
-```bash
-curl -s https://registry.npmmirror.com/electron | python -c "import sys,json;print(json.load(sys.stdin)['dist-tags'])"
-```
-
-`dist-tags.latest` 的实测值(2026-10-16):`electron 44.8.0`、`vite 8.3.4`、`electron-vite 6.0.0`、
-`react 19.3.1`、`typescript 7.0.2`、`@vitejs/plugin-react 6.1.2`。
-
-兼容性由 peer 依赖核对,不靠印象:`electron-vite` 6.0.0 对 `vite` 的要求是 `^6 || ^7 || ^8`,
-所以配 Vite 8 是上游支持组合,不是我们运气好。
-
-## 4 Python
-
-G1 与 CLI 的注册表部分**只用标准库**;M1 起 `runtime/tests/selfcheck.py` 会真渲染一张图,需要科学计算依赖。
-版本下限统一写在仓库根的 `requirements.txt`(与上游技能 v2.0.1 一致),安装走镜像:
-
-```bash
-python -m pip install -r requirements.txt -i https://registry.npmmirror.com/pypi/simple/
-```
-
-M2 起桌面端会自己拉起 `python runtime/cli.py serve`(Linux/macOS 用 `python3`),所以起窗口要求 Python 在 `PATH` 上;
-不在就用 `MMS_PYTHON` 指向解释器。通道服务器、SSE 与 provider 客户端只用标准库,不需要额外的 pip 包。
-没有 API Key 时用 `MMS_FAKE_PROVIDER=1` 走离线演示,细节见 [providers.md](providers.md)。
-
-`jsonschema` 也在其中;缺它时契约校验仍会降级并在输出里说明,但 CI 必须装齐。TUNA 镜像在本机实测会超时,
-npmmirror 可用——镜像本身也会挂,超时不等于配置错了。
-
-**为什么运行时钉 3.12 而不是本机已有的 3.14**:M5 要随包分发一个可安装 matplotlib / seaborn / PyMuPDF 的解释器,
-科学计算 wheel 在 3.12 这一档覆盖面最全。参考实现是 Cherry Studio 的
-`src/main/services/binaryManager/pythonRuntime.ts`——它钉 `3.12.13`,
-便携解释器走 `https://registry.npmmirror.com/-/binary/python-build-standalone`,
-并在注释里明确「绝不收养系统解释器,只认自己的安装目录」。我们照这套做法,理由相同:可复现优先于少下载。
-
-## 5 系统级依赖(程序不会替你装)
-
-| 依赖 | 用途 | 检测命令 | 本机实测 | 缺件时 |
-| --- | --- | --- | --- | --- |
-| Node.js | 桌面壳 | `node -v` | v24.18.1 | 装 LTS |
-| xelatex | 论文排版(M5) | `xelatex --version` | MiKTeX-XeTeX 4.16(MiKTeX 25.12) | 装 TeX Live 或 MiKTeX,系统级安装,pip 装不上;可用 `MMS_XELATEX` 指定路径 |
-| pandoc | LaTeX→Word,公式转 OMML | `pandoc --version` | pandoc 3.13,`%LOCALAPPDATA%\mms-tools\pandoc.exe`(2026-10-30) | Windows:官方 zip 解出 `pandoc.exe`(`winget install --id JohnMacFarlane.Pandoc` 也可) |
-| 中文字体 | CJK 排版与出图 | 见下 | 未单独核对 | `xeCJK` 需要 SimHei/SimSun 在场;matplotlib 缺字体会画成方框,上游 `plot_style.pick_cjk_font` 有回退 |
-| Electron 链接器 | 若改用 Tauri 才需要 | `where link.exe` + `link --version` | 命中的是 GNU coreutils 8.32,**不是 MSVC 链接器**;无 Visual Studio、无 `Windows Kits\10\Lib` | 本仓库选 Electron 正是因为这里没有可用链接器 |
-
-最后一条值得记住:`where link.exe` 有结果**不代表有链接器**。用它找工具链组件时,一律再跑一次 `--version` 认身份。
-
-**pandoc 的查找顺序**:`PATH` → `MMS_PANDOC` → `%LOCALAPPDATA%\mms-tools\pandoc.exe`。三处都没有时论文页列出缺件并禁用构建按钮,G10 退出 1;只有显式 `MMS_PAPER_SKIP=1` 才跳过,且会打印「未验证 G10」。
-
-本机 2026-10-30 的装法(github.com:443 被挡、api 通道可用):
-
-```bash
-gh release download 3.13 --repo jgm/pandoc --pattern "pandoc-3.13-windows-x86_64.zip" --dir /tmp/pandoc
-unzip /tmp/pandoc/pandoc-3.13-windows-x86_64.zip
-mkdir -p "$LOCALAPPDATA/mms-tools"
-cp /tmp/pandoc/pandoc-3.13/pandoc.exe "$LOCALAPPDATA/mms-tools/pandoc.exe"
-"$LOCALAPPDATA/mms-tools/pandoc.exe" --version
-```
-
-单文件 exe 约 239 MB,是静态链接的完整包;仓库不收录它,也不在运行时自动下载。
-
-TeX 侧需要的是 xelatex 与中文支持(ctex/xeCJK)。Linux CI 用 apt:
-
-```bash
-sudo apt-get install -y pandoc texlive-xetex texlive-lang-chinese texlive-latex-extra
-```
-
-Windows 上装 MiKTeX 后 `xelatex` 进入 PATH 即可,本机没有再设置 `MMS_XELATEX`。
-
-## 6 写脚本时的 Windows 坑
-
-- **PowerShell 5.1 按 GBK 解 `.ps1`**:含中文的安装/启动脚本会报语法错或静默吞语句。要么脚本全 ASCII,要么带 UTF-8 BOM。上游 metamath-harness 就因为漏了 BOM 导致旧终端下装机必炸。
-- **Python 在 GBK 控制台 print 中文会抛 `UnicodeEncodeError`**:本机是 GBK,Windows CI 的 stdout 更窄(cp1252)。`mms` CLI 与两个自检脚本都在入口把 stdout/stderr 重配成 UTF-8;你自己的脚本也要照做,否则本机乱码、CI 直接崩。
-- **别按进程名杀进程**(`taskkill /IM`),按 PID 杀;Git Bash 会把 `/PID` 当路径吃掉,需要 `MSYS_NO_PATHCONV=1`。
-
-## 7 装完之后
-
-```bash
-npm run gate
-```
-
-全绿即脚手架自洽。其中只有 `typecheck`、`build`、`smoke:dist` 需要 `npm install` 成功;
-`check:registry`、`check:registry:negative`、`check:contracts`、`check:channel` 只吃标准库(契约校验缺 `jsonschema` 时降级);
-`check:cli` 与 `check:workbench` 需要 `requirements.txt` 里的科学计算包;`check:paper` 还需要 xelatex 与 pandoc。这是刻意设计,方便你在任何机器上验证注册表与通道没漂。
-
-想看界面就两条路:`npm run dev` 起开发窗口;或先 `npm run build` 再 `npm run smoke:window`,
-它会 `require` 生产入口真起一次窗口、拉起 Python 通道、用离线 provider 走完 K2→K3→解释→换一批→选择,再重启 runtime 确认待选卡还在;接着真渲一张图、换主题重渲、并排 diff、回滚,再看评分五维/扣分定位/熔断与一票否决(53 条),
-截图写到 `screenshots/`(`decision.png`、`drawer.png` 是 M3 新增,`figure.png`、`score.png` 是 M4)。本机有显示器,不需要 xvfb;CI 那条 job 才需要,并且要先修好 Electron 的 SUID 沙箱助手(见 `ci.yml` 的注释)。
-会话状态默认写在 Electron `userData/sessions.db`,图表版本在 `userData/workbench/figure/`(开发期可用 `MMS_DATA_DIR` 指到别处),都不存 Key。
diff --git a/docs/handoff.md b/docs/handoff.md
deleted file mode 100644
index 7f5aafb..0000000
--- a/docs/handoff.md
+++ /dev/null
@@ -1,206 +0,0 @@
-# 交接 · 当前状态(0.2.0)
-
-给接手的人(或下一轮会话的我)。日期 2026-11-15。
-提交数与文件数不要信这里抄的数字,跑 `git rev-list --count HEAD` 和 `git ls-files | wc -l` 自己取;HEAD 以 `git log -1` 为准。
-
-## 0 一句话现状
-
-0.2.0 把数模模块真正跑通:七阶段全链由 LLM 驱动(配 Key 时)——K2 题面拆解、K3 选模、阶段四按题生成求解代码并经「代码确认卡」点运行才执行、阶段五按真实结果写论文并过三道门禁、阶段六按 rubric 真实评分(<85 回喂修复 ≤3 轮熔断)。没有 Key 或模型不可用时回退确定性路径/演示样例,并在对话里明确标注兜底。DSH 双内核已移除,只剩自研 Python 单内核;工作台日志页并入代码页(标签 8→7)。
-
-三句必须保留的限制:
-
-- **没有用真实 DeepSeek / 通义千问 / Kimi / 智谱 GLM Key 跑过联网端到端。** 已验证的是 OpenAI 兼容协议(本地假端点)与整条本机离线链路;各服务的当下行为不在证据里。真实链路需用户在设置页配 Key 后自跑一道真题。
-- **离线演示的论文与评分是兜底样例,不是对真实赛题的解答。** 配 Key 后才按本题生成;PDF/Word 一致性核对没有自动化。
-- **0.2.0 的安装包尚未构建;G7 真启动本轮被本机环境阻塞**(今晨重启后 Electron 渲染进程挂起,Edge 对照正常,疑似终端安全软件拦截),待环境恢复后复跑。
-
-## 1 怎么验(命令 → 期望)
-
-需要先装两侧依赖:`npm install`(可加 `ELECTRON_SKIP_BINARY_DOWNLOAD=1`,CI 不启动窗口时用)与
-`python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/`。
-
-论文自检还需要 **xelatex 与 pandoc**(见 `docs/env-setup.md`):xelatex 走 PATH 或 `MMS_XELATEX`;pandoc 走 PATH、`MMS_PANDOC`,最后回落到 `%LOCALAPPDATA%\mms-tools\pandoc.exe`。缺件时 G10 退出 1 并打印缺什么;只有显式 `MMS_PAPER_SKIP=1` 才跳过,且会打印「未验证 G10」。
-
-不需要网络、不需要显示器的部分:
-
-```bash
-node scripts/check-registry.mjs # 8/8 项通过,技能 7 个 → exit 0
-node scripts/check-registry.negative.mjs # 9/9 条破坏被门禁抓到(含基线自证)→ exit 0
-node scripts/check-skills.mjs # 6/6 项通过,技能 7 个 → exit 0
-node scripts/check-skills.mjs --self # 7/7 条自检通过(含基线自证) → exit 0
-node scripts/check-window-smoke.mjs --selftest # 12/12 条核验自测 → exit 0
-python scripts/validate-contracts.py # 9/9 项通过(jsonschema) → exit 0
-python runtime/tests/selfcheck.py # 13/13 条 CLI 断言,含真渲一张图 → exit 0
-python runtime/tests/selfcheck_channel.py # 64/64 条通道断言(含 C16–C18 全链)→ exit 0
-python runtime/tests/selfcheck_channel.py --selftest # 12/12 条坏事件被拒 → exit 0
-python runtime/tests/selfcheck_orchestrator.py # 34/34 条编排断言(含 L1–L14 LLM 注入)→ exit 0
-python runtime/tests/selfcheck_workbench.py # 19/19 条工作台断言(真渲两版) → exit 0
-python runtime/tests/selfcheck_paper.py # 12/12 条论文断言(真编 PDF/DOCX)→ exit 0
-```
-
-`selfcheck.py`、`selfcheck_orchestrator.py`、`selfcheck_workbench.py` 与 `selfcheck_paper.py` 会真调 matplotlib / xelatex / pandoc(编排全链含论文编译,约一两分钟)。
-
-需要显示器的部分:
-
-```bash
-npm run smoke:window # 真起窗口,116 条断言,写 screenshots/window-smoke.{png,json} 与各页截图
-npm run verify:window # 独立读 JSON 并复算读数
-```
-
-`smoke:window` 自己设置 `MMS_FAKE_PROVIDER=1`,并把 Electron `userData` 与 `MMS_WORKSPACE` 指到临时目录,所以不会用你已保存的真实 provider,也不会在真实桌面建「赛题」。G7-9 会真编一遍论文,跑 G7 的机器必须有 xelatex 与 pandoc。
-
-一把梭:`npm run gate`(顺序见 `package.json` 的 scripts;G7 不在 gate 里,因为它要显示器和 Electron 二进制)。
-
-**本机跑 G7 前去掉 `ELECTRON_RUN_AS_NODE`**:本会话 shell 里它是 `1`,会让 `electron` 退化成 Node 并报 `app.setPath` 不存在。
-
-**G7 环境阻塞(2026-11-15)**:本机今晨重启后 Electron 渲染进程一律挂起(连内联 data URL 都不加载),Edge 无头对照正常;已排除路径空格、沙箱、GPU、用户数据目录、残留进程,沙箱外运行同样复现。疑似终端安全软件(edrservice)拦截,需排查后复跑 G7。
-
-CI:。0.2.0 尚未在 CI 上复跑。
-
-## 2 已证 / 未证(别混)
-
-| 结论 | 证据来源 | 强度 |
-| --- | --- | --- |
-| 注册表、技能规范、契约与 CLI 自洽 | `npm run gate`(本机 Windows,2026-11-15) | 强(本机) |
-| 本机通道:握手、Bearer、Host/Origin、SSE 契约、续传、取消、思考深度与上下文截断 | `selfcheck_channel.py` 64/64 | 强(本机) |
-| LLM 注入:K2/K3 模型生成、坏 JSON 回喂重试与回退、选模落盘 | `selfcheck_orchestrator.py` L1–L8 | 强(本机,fake) |
-| 代码确认卡:未确认不执行、动作守卫、失败回喂 ≤2 轮 | 同上 L9–L10、C17 | 强(本机) |
-| 全链离线:题面→选模→代码→运行→论文 PDF/DOCX+三门禁→评分达标 | 同上 K3/L11–L12、C12/C18 | 强(本机,fake 兜底) |
-| 真实评分:评分卡校验、按会话落盘、一票否决淘汰 | 同上 L13–L14、C18 | 强(本机) |
-| 上下文选模卡:工具调用后推送 `interrupt`,候选与编排器同源 | C15 | 强(本机) |
-| 编排闭环跨进程恢复 | C13 | 强(本机) |
-| 图表工作台、评分卡、论文排版与三道门禁 | G9 19/19、G10 12/12 | 强(演示数据/演示稿) |
-| 门禁能抓住坏稿;缺工具 / 坏 TeX / 缺稿件 | G10 反向 P6–P9 | 强(反向) |
-| 真实厂商 Key 联网端到端 | 无 Key,未跑 | **未证** |
-| G7 真启动(0.2.0) | 本机环境阻塞,未跑 | **未证** |
-| 0.2.0 的 NSIS 安装包 | 未构建 | **未证** |
-| 0.2.0 在 CI 上的门禁与真启动 | 未复跑 | **未证** |
-| Windows CI 真起窗、干净机安装 | 无 | **未证** |
-| Linux 桌面 `safeStorage` 可用分支 | 只证了「不可用就拒绝保存」 | **未证** |
-
-## 3 待维护者定的项
-
-1. **TeX 与 pandoc 在安装包里怎么存在**:要求用户本机装 / 内置 Tectonic / 两者都支持并让环境检测决定。当前只做了检测与明确拒绝。
-2. **provider 列表的维护方式**:预设写死在 `runtime/src/mms/providers.json`,界面允许手填模型名与自定义端点。是否改成用户可增删的服务商列表,取决于「选模型」要多重。
-3. **Key 的 Linux 兜底**:当前规则是安全存储不可用就拒绝保存,不退回明文。保持拒绝还是允许「本次会话内存保存」,需要拍板。
-4. **双模式与双存储合并**:通用/数模双模式、问答会话 localStorage 与建模会话 SQLite 两套存储仍在(本轮稳妥简化未动)。合并为单一对话流 + 统一存储是下一版本的简化方向,需重写 G7 大面积断言。
-5. **论文分章生成**:当前一次生成整篇,实测输出被截断时再改分章。
-
-## 4 界面待判的观感问题(我只报,没改)
-
-`screenshots/` 下的截图均为 1440×900、本机 Windows 渲染(0.1.0 旧图,0.2.0 待 G7 恢复后重拍)。
-
-- 左栏 240px 装不下最长的阶段名时靠收紧占位解决;阶段圆点描边较淡。
-- 中栏空态文字偏上,下方到输入框之间空隙大。
-- 状态栏右侧色块与文字间距偏小。
-- 工具卡灰底与白底差别小;模型条最长 300px,长名字会被截断。
-- 设置页服务商是等宽胶囊,没有分组。
-- 评分页信息密度较高;论文页 A4 缩到约 370px 宽,正文可辨但字号很小。
-- 代码确认卡的代码预览块最高 320px 可滚动,长脚本需滚动查看。
-
-## 5 已做与仍欠
-
-已做(0.2.0):
-
-1. LLM 进编排:K2/K3 模型生成 + 回退;恢复决策带服务商上下文,Key 按次补齐不落盘。
-2. 代码确认卡(K4):模型生成求解代码,点运行才执行,失败回喂 ≤2 轮;所选模型落盘。
-3. 真实论文生成:骨架 + 规范 + 真实结果 → tex → 排版 + 三门禁,修复 ≤3 轮;阶段五推进(含手动构建)。
-4. 真实评分:rubric 评审 + score_card 校验 + 按会话落盘;<85 回喂修复 ≤3 轮熔断;一票否决淘汰。
-5. 移除 DSH 双内核(适配层/MCP/SDK/环境注入/自检全清);单 Python 内核。
-6. 工作台精简:日志并入代码页,标签 8→7。
-7. 门禁:G4 64、G11 34、G9 19、G10 12、G12 14、G13 10;版本 0.2.0 四处同源。
-
-仍欠:
-
-- 真实厂商 Key 联网端到端(需用户配 Key 自跑)。
-- G7 真启动复跑(本机环境阻塞)与截图重拍。
-- 0.2.0 安装包重建与干净机安装验证;CI 复跑。
-- 双模式合并、存储统一(下一版本)。
-- Linux 桌面 safeStorage 可用分支。
-
-## 6 踩过的坑(别再踩)
-
-**POST 处理器必须读请求体,否则 keep-alive 会中毒**:凡是 `do_POST` 分支,先读体再处理。
-
-**pdf.js 不要传 `data:` URL**:把 base64 解成 `Uint8Array` 传给 `getDocument({data})`;worker 由 Vite 打包,CSP 需要 `worker-src 'self' blob:`。
-
-**pandoc 不在 PATH 时要有回落,但覆盖变量指向不存在的路径必须判缺**:`MMS_PANDOC` 设了但文件不存在时直接判缺。
-
-**xelatex 能编模板不等于模板能过门禁**:`check_style.py` 的段落节奏要求相邻合格段落字数差 ≥20%;LaTeX 表格行也会被当成段落统计。`check_phrasing.py` 会扫注释。
-
-**G7 新增断言要同步三处**:`tests/window-smoke.cjs` 的断言、`scripts/check-window-smoke.mjs` 的 `MIN_ASSERTIONS` 与 `REQUIRED_ASSERTIONS`、以及文档里的条数。
-
-**默认模式改了要查恢复路径**:恢复待决会话时必须 `setMode('workflow')`,否则点确认走成聊天消息。
-
-**interrupt 节点幂等硬约束**:写文件/执行脚本/花 token 一律在 interrupt 之后。代码确认卡先落 pending 再 yield interrupt,`run` 动作才执行;阶段五/六的生成与编译都在 resume 链里,不在挂卡前。
-
-**LLM 输出先校验再改状态**:`llm.complete_json`/`complete_text` 剥围栏、坏输出回喂重试一次,仍坏抛 LlmError 由编排层回退;schema 校验先于状态变更。fake provider 按 system 消息的 `[mms-stage:...]` 标记路由,聊天两段脚本不受影响。
-
-**兜底必须标注**:fake/无模型时论文用样例稿、评分用演示卡,来源标 fallback 并在对话里写明「非按本题生成/评审」,不冒充真实结果。
-
-**工具卡片的通道**:选模卡/代码卡走 `interrupt` 事件,不是 `gate`;`gate` 是技能门禁的 `{skill, ok, exit}`。`artifact` 事件支持 `path`(单文件)与 `outputs`(多产物)两种形状。
-
-**窗口 resize 时的夹取要防抖**:等 180ms 稳定后再夹。
-
-**分隔条高亮用 CSS 变量定位**:`--grip-y` 由 pointermove 写入,不要固定 50%。
-
-**CI 的排版依赖是硬依赖**:gates 的 ubuntu job 与 window-smoke job 都要装 pandoc 与 TeX;Windows gates 没有 TeX,G10 用 `MMS_PAPER_SKIP=1` 显式跳过。
-
-**上一轮的坑仍然有效**:SSE 流要显式 `Connection: close`;事件可能比 `chat.start` 返回值先到;G7 的假 provider 必须在 `require` 生产入口之前设;`app.exit(1)` 会被 `window-all-closed` 顶掉,结论必须落 JSON 由 G6b 独立判;Windows 控制台 cp1252 会因中文崩溃,入口要 reconfigure UTF-8;本机 shell 可能带 `ELECTRON_RUN_AS_NODE=1`;safeStorage 的「不可用」是正常分支。
-
-**近期新增的坑**:
-
-- `capturePage()` 在窗口被遮挡时会抛 `UnknownVizError`,G7 的截图全部走 `capture(win)` 重试封装。
-- 会话列表有两套来源:`GET /sessions` 只返回建模会话摘要,问答会话在渲染层 `localStorage`。清空历史必须两边一起删。
-- 上下文估算在 TS(`lib/context.ts`)与 Python(`harness.estimate_tokens`)各有一份;改公式必须两边同步。
-- 左栏宽度 240px、`.tab` 7 个(0.2.0 日志并入代码后)是 G6b 点名项;右栏分组用 `.tabs__group`/`.tabs__label`。
-- 面板标题与门禁条已并入栏头/`.panel__bar`;门禁页 `[data-gate-row]` 仍必须 4 条。
-- 评分按会话隔离:`workbench_score.state(root, data_dir)` 优先读 `<会话>/workbench/score/round-N.json`,无则回落演示三轮;章节门禁优先查本会话 `paper.tex`。
-
-## 7 结构速查
-
-```
-skills/ 7 个 vendor 进来的技能(原样)+ manifest.json + VENDOR.md
-schemas/ skill-manifest.schema.json、chat-events.schema.json
-runtime/src/mms/
- server.py 本机通道:握手、鉴权、SSE、会话、workflow、工具与工作台端点(单 Python 内核)
- store.py SQLite:阶段、待决卡、消息、轮次、picked(所选模型)
- orchestrator.py K2/K3 状态机 + 代码确认卡 + 阶段四五六全链;chat 选模卡共用候选
- llm.py 编排器 LLM 注入层:阶段标记、JSON/文本补全、回喂重试
- paper_gen.py 阶段五论文生成:骨架 + 规范 + 真实结果 → tex
- score_gen.py 阶段六评分生成:rubric 评审 → 评分卡
- workbench_figure.py 图表渲染、主题、版本与回滚
- workbench_score.py 评分卡、扣分定位、按会话真实轮次、章节门禁与一票否决
- paper_build.py 论文流水线:xelatex、pandoc、Word 后处理、三道门禁
- baseline.py 数据画像、脚本校验、求解脚本执行框架
- provider.py OpenAI 兼容流式客户端 + 离线假 provider(按阶段路由)
- providers.json DeepSeek / 通义千问 / Kimi / 智谱 GLM / OpenAI 格式预设与思考参数映射
- cli.py serve / templates / invoke
-runtime/cli.py 开发期入口(npm run mms)
-runtime/tests/ 自检:CLI、通道、编排、harness、工作台、论文(G3–G13,含反向覆盖)
-src/main/
- index.ts 窗口、IPC、provider 合并视图、SSE 转发、resume(带 Key)、PDF data URL
- channel.ts Python 子进程生命周期、HTTP/SSE 客户端
- settings.ts safeStorage 密文、工作区与 provider 设置
-src/preload/index.ts window.studio 窄接口
-src/shared/api.ts 主进程与渲染层共享的纯类型
-src/shared/file-kinds.ts 扩展名 → 文件类别(主进程与渲染层共用)
-src/renderer/src/
- App.tsx 运行时状态、provider、对话事件归并、快照恢复、卡片决策分流
- components/chat/ 对话流、欢迎屏、决策卡(含代码确认卡)、解释抽屉、Markdown 与消息操作
- components/rail/ PhaseRail:会话列表与七阶段轨道
- components/workspace/ WorkspacePane 与图表/论文/评分/门禁/代码(含日志)/文件/过程总览面板
- components/settings/ SettingsDialog:服务商/模型/Key 设置
- components/common/ ContextMenu、SelectMenu、FileChips
- lib/chat.ts 事件折叠的纯函数
-scripts/ G1/G1 反向/G8/G8 反向/G6/G6b 与契约校验
-tests/window-smoke.cjs 真启动断言(116 条)+ 截图与 JSON 结论
-docs/release.md 发布格式规范
-.github/workflows/ci.yml gates(ubuntu+windows,含 G9/G10)与 window-smoke(ubuntu)
-```
-
-会话库位置:Electron `userData/sessions.db`;命令行直接起 runtime 时是 `/.mms/sessions.db`,可用 `MMS_DATA_DIR` 覆盖。库内只有阶段、待决卡、消息与所选模型,没有 Key。
-图表版本位置:`userData/sessions//workbench/figure/versions/`,`state.json` 记当前版与上一版;无合法 sid 时回落 `userData/workbench/`。
-论文工作区:`userData/sessions//workbench/paper/`,含 `paper.tex`、`paper.pdf`、`paper.docx`、`figures/final/`、`logs/` 与 `build.json`;受同样回落规则约束。
-评分轮次:`userData/sessions//workbench/score/round-N.json`。
-
-一处刻意的设计:`runtime` 只用 subprocess 调技能脚本、按退出码与产物双重判定,不 import 技能内部函数——这样 `skills/` 仍可被 Claude Code 等宿主单独装载。改这条要先想清楚代价。
\ No newline at end of file
diff --git a/docs/images/architecture-en.svg b/docs/images/architecture-en.svg
deleted file mode 100644
index b78615c..0000000
--- a/docs/images/architecture-en.svg
+++ /dev/null
@@ -1,81 +0,0 @@
-
-
-
- Runtime architecture
- Desktop, process boundaries and data flow
-
-
- Electron desktop
-
-
- Renderer · React
- conversations · phase rail · cards
- figures / paper / score / gates / files
- pdf.js page preview
- renderer process · sandbox
-
-
- Main process
- IPC · channel forwarding · SSE merge
- safeStorage-encrypted model keys
- attachment text (PDF / text / CSV)
- keys never enter the renderer or logs
-
-
- Local channel
- HTTP + SSE
- Bearer · loopback only
- replay · cancel
- 127.0.0.1
-
-
- Python runtime
-
-
- Orchestrator
- phases 0–6 · K2–K6 decision points
- pause & resume · context budget
- provider adapters · event stream
-
-
- Skill runner
- subprocess · exit codes 0 / 1 / 2
- figures · typesetting · de-AI · audit · score
- loadable by hosts such as Claude Code
-
-
- SQLite
- phase · pending cards · message history
- cross-process recovery
-
-
- Model APIs
- DeepSeek
- Qwen
- Kimi / GLM
- OpenAI-format
- BYOK
-
-
- Artifacts
- PNG / PDF / SVG
- PDF / DOCX
- logs & commands
- written to disk
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Model keys are encrypted by the main process; the runtime reads them through the loopback channel. Keys never reach the renderer, event stream or logs.
-
diff --git a/docs/images/architecture.svg b/docs/images/architecture.svg
deleted file mode 100644
index d3278ad..0000000
--- a/docs/images/architecture.svg
+++ /dev/null
@@ -1,81 +0,0 @@
-
-
-
- 运行时架构
- 桌面端、进程边界与数据流
-
-
- Electron 桌面端
-
-
- 渲染层 · React
- 会话列表 · 阶段轨道 · 决策卡
- 图表 / 论文 / 评分 / 门禁 / 文件
- pdf.js 页级预览
- 渲染进程 · sandbox
-
-
- 主进程
- IPC · 通道转发 · SSE 归并
- safeStorage 加密模型 Key
- 附件正文抽取(PDF / 文本 / CSV)
- Key 不进入渲染层与日志
-
-
- 本地通道
- HTTP + SSE
- Bearer · 仅回环
- 续传 · 取消
- 127.0.0.1
-
-
- Python 运行时
-
-
- 编排器
- 阶段零 – 六 · K2 – K6 决策点
- 暂停与恢复 · 上下文预算
- provider 适配 · 事件流
-
-
- 技能执行
- subprocess · 退出码 0 / 1 / 2
- 图表 · 排版 · 降 AI · 结构自检 · 评分
- 技能可被 Claude Code 等宿主单独装载
-
-
- SQLite
- 阶段 · 待决卡 · 消息历史
- 跨进程恢复
-
-
- 模型 API
- DeepSeek
- 通义千问
- Kimi / GLM
- OpenAI 格式
- BYOK
-
-
- 产物
- PNG / PDF / SVG
- PDF / DOCX
- 日志与命令
- 落盘
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 模型 Key 仅经主进程加密保存;运行时通过本地回环通道取用,不写入渲染层、事件流与日志。
-
diff --git a/docs/images/conversation.png b/docs/images/conversation.png
deleted file mode 100644
index 01cc094..0000000
Binary files a/docs/images/conversation.png and /dev/null differ
diff --git a/docs/images/decision.png b/docs/images/decision.png
deleted file mode 100644
index f558cd5..0000000
Binary files a/docs/images/decision.png and /dev/null differ
diff --git a/docs/images/paper.png b/docs/images/paper.png
deleted file mode 100644
index 46a3d10..0000000
Binary files a/docs/images/paper.png and /dev/null differ
diff --git a/docs/images/process.png b/docs/images/process.png
deleted file mode 100644
index 3092b12..0000000
Binary files a/docs/images/process.png and /dev/null differ
diff --git a/docs/images/score.png b/docs/images/score.png
deleted file mode 100644
index c77c301..0000000
Binary files a/docs/images/score.png and /dev/null differ
diff --git a/docs/images/workbench.png b/docs/images/workbench.png
deleted file mode 100644
index bb369ea..0000000
Binary files a/docs/images/workbench.png and /dev/null differ
diff --git a/docs/images/workflow-en.svg b/docs/images/workflow-en.svg
deleted file mode 100644
index e9e374c..0000000
--- a/docs/images/workflow-en.svg
+++ /dev/null
@@ -1,61 +0,0 @@
-
-
-
- Phase rail and decision points
- Each judgement point pauses the run until the user confirms
-
-
-
-
- Phase 0
- Environment
- Phase 1
- Problem
- Phase 2
- Workspace
- Phase 3
- Model choice
- Phase 4
- Implementation
- Phase 5
- Paper
- Phase 6
- Scoring
-
-
- 0
-
- 1
-
- 2
-
- 3
-
- 4
-
- 5
-
- 6
-
-
- K2 Problem check
-
-
- K3 Model cards
-
- K4 Explain
-
-
- K5 Figure rework
-
-
- K6 Scoring rounds
-
-
-
-
-
-
-
- Pause state, pending cards and message history live in SQLite; closing the window or restarting the process returns to the same point.
-
diff --git a/docs/images/workflow.svg b/docs/images/workflow.svg
deleted file mode 100644
index 17c7dc5..0000000
--- a/docs/images/workflow.svg
+++ /dev/null
@@ -1,61 +0,0 @@
-
-
-
- 阶段轨道与决策点
- 推进到判断节点即暂停,确认后继续
-
-
-
-
- 阶段零
- 环境预检
- 阶段一
- 赛题分析
- 阶段二
- 工作目录
- 阶段三
- 算法选择
- 阶段四
- 代码实现
- 阶段五
- 论文输出
- 阶段六
- 评分优化
-
-
- 0
-
- 1
-
- 2
-
- 3
-
- 4
-
- 5
-
- 6
-
-
- K2 赛题确认
-
-
- K3 选模卡
-
- K4 就地解释
-
-
- K5 图表返工
-
-
- K6 评分轮次
-
-
-
-
-
-
-
- 暂停状态、待决卡与消息历史写入 SQLite;关闭窗口或重启进程后仍停在原处。
-
diff --git a/docs/providers.md b/docs/providers.md
deleted file mode 100644
index e06c4f0..0000000
--- a/docs/providers.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# 模型接入与 Key 存储
-
-M2 起,桌面端可以把对话交给一个 OpenAI 兼容的流式端点。本文写清三件事:怎么配、Key 存在哪、哪些结论还没有被验证。
-
-## 1 内置的五个预设
-
-单一事实源是 [`runtime/src/mms/providers.json`](../runtime/src/mms/providers.json);界面只是把这份清单渲染成设置页。模型名按各家官网 2026-10 核对;它们仍是**预设**,不是白名单,设置页允许手填。
-
-| id | 显示名 | Base URL | 预设模型 | 思考参数 |
-| --- | --- | --- | --- | --- |
-| `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | `deepseek-flash`、`deepseek-v4-pro` | `reasoning_effort`:low / high / max |
-| `qwen` | 通义千问 | `https://dashscope.aliyuncs.com/compatible-mode/v1` | `qwen3.8-max`、`qwen3.7-plus`、`qwen3.8-flash` | `reasoning_effort`:medium / high / max |
-| `kimi` | Kimi | `https://api.moonshot.cn/v1` | `kimi-k3.1-pro`、`kimi-k3`、`kimi-k2.7-code`、`kimi-k2.6` | K3 系列用 `reasoning_effort`(low/high/max);K2.x 用 `thinking.type` |
-| `glm` | 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | `glm-5.3`、`glm-5.3-flash`、`glm-4.7` | GLM-5.3 用 `reasoning_effort`(low/high/max);4.x 用 `thinking.type` |
-| `custom` | OpenAI 格式 | 空,需自己填 | 空,需自己填 | 勾选「发送思考深度」后才带 `reasoning_effort` |
-
-五家都支持流式工具调用;工具调用是否真的可用取决于端点本身。模型改名后不必等本仓库发版,手填新的模型 ID 即可。
-
-## 2 在界面里配置
-
-1. 起窗口(`npm run dev`),点输入框下方的模型条,打开模型设置。
-2. 左侧选服务商,右侧点模型胶囊或手填模型 ID;OpenAI 格式还要填 Base URL。
-3. 粘贴 API Key,保存。已保存的 Key 不会再显示,输入框留空表示「不修改」,只能覆盖或清除。
-4. 保存后模型条立即变成「服务商 · 模型名」,发送按钮随即可用。
-
-Key 不会经渲染层回读。设置页只能看到「已保存」标记,拿不到明文,也没有「显示 Key」按钮。
-
-### 2.1 上下文预算与思维深度
-
-- **上下文预算 200k / 400k / 1m** 是**本地回放上限**,不是模型的硬上限。每次发送前按粗估 token(CJK 1 字 1 token,其余 3.5 字符 1 token)从最新消息往回装,装不下的旧历史不送给模型;中栏顶部显示「上下文约已用 / 上限」。runtime 会按同一预算再截一次,防止渲染层估算漏项。预设里 GLM-4.7 的上限是 200k,选中它时更大的档位会禁用。
-- **思维深度 中 / 高 / 最大** 按服务商映射到它认识的字段:「中 / 高 / 最大」在 DeepSeek、Kimi K3、GLM-5.3 上映射为 `low / high / max`,在 Qwen 上映射为 `medium / high / max`。Kimi K2.x 与 GLM-4.x 改成发送 `thinking: {type: "enabled"}`,不发送 `reasoning_effort`。
-- OpenAI 格式端点默认**不发送**思考参数;只有勾选「发送思考深度」才会带 `reasoning_effort`。本地推理服务不认这个字段时保持关闭。
-- 这些是请求参数,不是效果承诺:模型是否真的思考、思考多深,由各家服务决定。
-
-## 3 Key 存在哪、边界在哪
-
-- 磁盘位置:Electron 的 `userData/settings.json`(Windows 通常是 `%APPDATA%\mathmodel-studio\settings.json`,macOS 与 Linux 按 Electron 的默认规则)。
-- 文件里只有 `safeStorage.encryptString(key)` 的 base64 密文;渲染层拿到的是 `configured: true/false`,不是 Key。
-- **系统安全存储不可用时拒绝保存**,不会退回明文。Linux 上这通常意味着没有可用的 Secret Service(gnome-keyring / KWallet 等);无头环境与部分 CI 容器属于这一类。
-- 文件以 `0600` 写入。它保护的是「同机其他用户」,不是「拿到你账户的人」——这与所有桌面端 BYOK 的边界相同。
-- 运行时只在下一次 `chat:start` 时由主进程解密并放进 HTTP `Authorization: Bearer` 头。Key 不进渲染层、不进事件流、不进 stderr;G4/G5 自检用一个 Key 哨兵扫描了这三处。
-
-## 4 OpenAI 格式端点的规则
-
-- 公网地址必须是 `https`;`http` 只接受 `127.0.0.1`、`localhost`、`::1`。这条在运行时校验,不只在界面提示。
-- Base URL 填到 `/v1` 为止,运行时自己拼 `/chat/completions`。
-- 端点需要兼容 OpenAI 的 **流式 chat completions**:`data:` 帧、增量 `content`、可选 `reasoning_content`、可选分片 `tool_calls`。不支持流式工具调用也能聊天,只是不会出现工具卡。
-- 想发送思考深度时勾选「发送思考深度」,运行时会把中 / 高 / 最大映射为 `medium / high / max`;端点不认这个字段时会返回 400,此时关闭开关即可。
-- 429 与 5xx 会按 `Retry-After` 做有界重试(最多 3 次);401/403 直接把错误文本交给对话流,不重试。
-
-## 5 离线演示(不需要 Key)
-
-设置 `MMS_FAKE_PROVIDER=1` 后,runtime 会在服务商列表最前面插入一个「离线演示(不联网)」条目,不读 Key、不发任何网络请求。它的内容是写死的:先给一段 reasoning,发一个 `list_templates` 工具调用,再根据 25 个模板总结一句。用于验证通道、流式渲染与工具卡。
-
-```bash
-# Git Bash / macOS / Linux
-MMS_FAKE_PROVIDER=1 npm run dev
-```
-
-```powershell
-# PowerShell
-$env:MMS_FAKE_PROVIDER='1'; npm run dev
-```
-
-可选 `MMS_FAKE_DELAY_MS`(默认 20)控制每块文本之间的间隔,用来观察流式效果;它只影响假 provider。
-
-G7 真启动冒烟会在自己的进程里打开这个开关,并把 `userData` 指到临时目录,避免你本机已保存的 provider 改变默认选中项。因此 **G7 跑的是离线演示,不是真实模型**。
-
-## 6 已验证与未验证
-
-已验证(本机 + 自检脚本):
-
-- 握手、Bearer 鉴权、回环 Host/Origin 白名单、SSE 续传与取消(G4;55 条,含思考深度映射、关闭开关、上下文裁剪)。
-- OpenAI 兼容协议本身:429 退避、`reasoning_content` 与正文分离、分片 `tool_calls` 拼装、历史剥离 reasoning、Key 只出现在 Authorization(G5,用本地假端点,不联网)。
-- 界面端到端:设置页打开/关闭、五家预设与模型胶囊、上下文/深度选择器、不回显 Key、哨兵 Key 经 UI 保存后磁盘上只有密文(G7 共 97 条,本机 Windows 真启动)。
-- 离线 provider 的文字真的流进气泡,`list_templates` 工具卡从 running 走到 ok,结束后按钮回到「发送」(G7 同一轮)。
-- 安全存储不可用时明确拒绝且不落盘:CI run `40982728779`(M3)的 Linux runner 没有 Secret Service,G7 实得 `可用=false、文件存在=false、明确拒绝=true`。
-
-**未验证**:
-
-- 真实 DeepSeek / 通义千问 / Kimi / GLM 的联网对话。本仓库不内置任何 Key,CI 也不调用真实服务;这条只能由你填自己的 Key 验证。
-- 各家的 `reasoning_effort` 在**当前**模型上的实际效果(docs 只说明参数可传,不等于每档都有可观测差异)。
-- 自定义端点的兼容性差异(有的实现不发 `reasoning_content`,有的分片 `tool_calls` 字段不全,有的不认 `reasoning_effort`)。这些情况会以错误文本呈现,但尚未逐个建 fixture。
-- Linux 桌面上 Secret Service 可用时的加密保存;CI 只跑到不可用分支,桌面分支没有环境可验。
-
-## 7 故障排查
-
-| 现象 | 先查什么 |
-| --- | --- |
-| 状态栏「runtime 未连接」 | 终端里能否 `python --version`(Linux/macOS 为 `python3`);不能就用 `MMS_PYTHON` 指向解释器。点状态栏「重试」会重启子进程。 |
-| 发送按钮一直灰 | 该服务商未配置 Key,或自定义端点没填 Base URL;设置页有「已保存」标记才表示 Key 在。 |
-| 保存 Key 报「系统安全存储不可用」 | 当前系统没有可用的加密后端;本仓库不会以明文降级保存。 |
-| 429 / 5xx | 运行时已自动重试 3 次;仍失败时错误会出现在对话里。 |
-| 工具卡不出现 | 端点没有返回 `tool_calls`,或该端点不支持工具调用。M2 只有一个只读工具 `list_templates`。 |
diff --git a/docs/release.md b/docs/release.md
deleted file mode 100644
index 845c87f..0000000
--- a/docs/release.md
+++ /dev/null
@@ -1,74 +0,0 @@
-# 发布规范
-
-本文件规定 GitHub Release 的版本号、标题、正文与附件格式。以后每次发布按此执行,不再各自发挥。
-
-## 版本号
-
-- 使用 `X.Y.Z` 语义化版本,Git tag 为 `vX.Y.Z`(带 `v` 前缀)。
-- 当前版本为 `0.1.0`。
-- 版本号在四处同源,发布前必须一致:`VERSION`、`package.json`、`runtime/pyproject.toml`、`runtime/src/mms/__init__.py`。`npm run check:contracts` 的 C4 断言会拦截不一致。
-
-## 标题
-
-```
-vX.Y.Z · 一句话主题
-```
-
-示例:`v0.2.0 · 数模全链跑通与单内核`。主题只写这一版最主要的变化,不堆功能清单。
-
-## 正文结构
-
-固定五节,按此顺序;某节没有内容就写「无」,不要删节。
-
-```markdown
-## 变更
-- 面向用户可感知的新能力,一条一句,动词开头。
-
-## 修复
-- 修掉的缺陷,写清触发条件与修复后的行为。
-
-## 升级注意
-- 需要用户手动处理的事项(安装目录、配置迁移、旧会话兼容等)。
-
-## 校验
-- 安装包:`mathmodel-studio-X.Y.Z-setup.exe`,<字节数> 字节(约 MB)
-- SHA-256:``
-- 随包组件:Python <版本>、pandoc <版本>
-- 门禁:`npm run gate` 通过;窗口冒烟 /
-- 签名:<有/无自签名证书及信任状态>
-
-## 已知问题
-- 未验证或已知缺陷,写清影响面。
-```
-
-## 附件
-
-- 只附 `mathmodel-studio-X.Y.Z-setup.exe` 与对应的 `*.blockmap`。
-- 不手工上传源码压缩包;GitHub 自动生成的 Source code 条目保持默认。
-- 安装包必须从待发布 tag 对应的提交重新构建,不复用旧构建产物。
-
-## 发布前检查清单
-
-1. `VERSION`、`package.json`、`runtime/pyproject.toml`、`runtime/src/mms/__init__.py` 均为同一版本。
-2. `CHANGELOG.md` 有无对应版本条目。
-3. `npm run gate` 全绿;`npm run smoke:window` 全绿。
-4. 工作区干净,tag 指向的提交与构建来源一致;构建后核对安装包内的 `VERSION`。
-5. 在 Release 正文「校验」中写入安装包字节数、SHA-256 与构建来源提交。
-
-## 发布操作
-
-```bash
-git tag vX.Y.Z <提交>
-git push origin vX.Y.Z
-gh release create vX.Y.Z \
- "release/mathmodel-studio-X.Y.Z-setup.exe" \
- "release/mathmodel-studio-X.Y.Z-setup.exe.blockmap" \
- --title "vX.Y.Z · 一句话主题" \
- --notes-file <正文文件>
-```
-
-移除旧版本时,release 与 tag 一起删:
-
-```bash
-gh release delete vX.Y.Z --yes --cleanup-tag
-```
diff --git a/gateway/pyproject.toml b/gateway/pyproject.toml
new file mode 100644
index 0000000..73eb65b
--- /dev/null
+++ b/gateway/pyproject.toml
@@ -0,0 +1,15 @@
+[project]
+name = "mms-gateway"
+version = "0.2.0"
+description = "mathmodel-studio 通用通道:OpenAI 兼容流式调用与本机 HTTP + SSE 服务"
+requires-python = ">=3.12"
+license = { text = "AGPL-3.0-only" }
+authors = [{ name = "Escap1ng" }]
+dependencies = []
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/mms_gateway"]
diff --git a/gateway/src/mms_gateway/__init__.py b/gateway/src/mms_gateway/__init__.py
new file mode 100644
index 0000000..a709514
--- /dev/null
+++ b/gateway/src/mms_gateway/__init__.py
@@ -0,0 +1,6 @@
+"""通用通道:OpenAI 兼容调用、本机 HTTP + SSE 服务。
+
+不包含任何数模领域逻辑;数模流水线由 modeling/ 注入。
+"""
+
+__version__ = "0.2.0"
diff --git a/runtime/src/mms/common.py b/gateway/src/mms_gateway/common.py
similarity index 100%
rename from runtime/src/mms/common.py
rename to gateway/src/mms_gateway/common.py
diff --git a/runtime/src/mms/llm.py b/gateway/src/mms_gateway/llm.py
similarity index 72%
rename from runtime/src/mms/llm.py
rename to gateway/src/mms_gateway/llm.py
index e9f965e..b23f271 100644
--- a/runtime/src/mms/llm.py
+++ b/gateway/src/mms_gateway/llm.py
@@ -1,11 +1,9 @@
-"""编排器的 LLM 注入层:按阶段调一次模型,拿回校验过的 JSON。
+"""一次性的模型调用层:拿到校验过的 JSON 或文本。
约定:
-- 每次调用都是独立的 system+user 两条消息,不带历史;system 里带阶段标记,
- 离线假 provider 按标记路由脚本化响应。
+- 每次调用都是独立的 system+user 两条消息,不带历史;system 里带阶段标记,便于排查。
- Key 只从调用方按次传入,不落盘、不进事件、不进异常文本。
-- 解析失败重试一次(把坏输出回喂);仍失败抛 LlmError,由调用方回退确定性路径。
- 状态变更必须发生在拿到合法 JSON 之后(interrupt 幂等硬约束)。
+- 解析失败重试一次(把坏输出回喂);仍失败抛 LlmError,由流水线回退确定性路径。
"""
from __future__ import annotations
@@ -14,11 +12,9 @@
import re
from collections.abc import Callable
-from .provider import CancelledError, ProviderError, fake_completion, stream_completion
+from .provider import CancelledError, ProviderError, stream_completion
STAGE_PREFIX = "[mms-stage:"
-
-# 单次调用的输出预算提示:论文正文最长,其余阶段都是结构化短 JSON。
MAX_HINT_CHARS = 60_000
@@ -30,18 +26,6 @@ def stage_prompt(stage: str, instruction: str) -> str:
return f"{STAGE_PREFIX}{stage}] {instruction}"
-def stage_of(messages: list[dict]) -> str:
- """从 system 消息里认出阶段标记;聊天消息没有标记,返回空串。"""
- for message in messages:
- if message.get("role") != "system":
- continue
- content = str(message.get("content") or "")
- match = re.search(re.escape(STAGE_PREFIX) + r"([a-z0-9-]+)\]", content)
- if match:
- return match.group(1)
- return ""
-
-
def _strip_fence(text: str) -> str:
value = text.strip()
match = re.match(r"^```[a-zA-Z0-9_-]*\s*\n(.*?)\n?```$", value, re.DOTALL)
@@ -52,9 +36,8 @@ def _strip_fence(text: str) -> str:
def parse_json(text: str) -> dict:
"""剥掉 markdown 围栏后解析 JSON 对象;失败抛 ValueError。"""
- value = _strip_fence(text)
try:
- data = json.loads(value)
+ data = json.loads(_strip_fence(text))
except json.JSONDecodeError as exc:
raise ValueError(f"输出不是合法 JSON:{exc.msg}") from exc
if not isinstance(data, dict):
@@ -69,20 +52,13 @@ def complete(
messages: list[dict],
should_stop: Callable[[], bool] | None = None,
on_delta: Callable[[str, str], None] | None = None,
- depth: str = "",
) -> str:
- """跑一次补全,返回全文。fake provider 走本地脚本,不发网络请求。"""
if not provider:
raise LlmError("没有可用的服务商")
stop = should_stop or (lambda: False)
delta = on_delta or (lambda kind, text: None)
try:
- if provider.get("id") == "fake":
- completion = fake_completion(messages, delta, stop, delay=0.0)
- else:
- completion = stream_completion(
- provider, api_key, model, messages, None, delta, stop, depth=depth
- )
+ completion = stream_completion(provider, api_key, model, messages, delta, stop)
except CancelledError:
raise
except ProviderError as exc:
@@ -101,7 +77,6 @@ def _retry_loop(
retry_hint: str,
should_stop: Callable[[], bool] | None,
on_delta: Callable[[str, str], None] | None,
- depth: str,
):
messages = [
{"role": "system", "content": stage_prompt(stage, instruction)},
@@ -109,7 +84,7 @@ def _retry_loop(
]
last_error = ""
for attempt in range(2):
- content = complete(provider, api_key, model, messages, should_stop, on_delta, depth)
+ content = complete(provider, api_key, model, messages, should_stop, on_delta)
try:
return extract(content)
except ValueError as exc:
@@ -132,14 +107,13 @@ def complete_json(
validate: Callable[[dict], dict],
should_stop: Callable[[], bool] | None = None,
on_delta: Callable[[str, str], None] | None = None,
- depth: str = "",
) -> dict:
"""调模型并拿回校验过的 JSON。坏输出回喂重试一次,仍坏抛 LlmError。"""
return _retry_loop(
provider, api_key, model, stage, instruction, user_content,
lambda content: validate(parse_json(content)),
"请重新输出,只输出一个合法 JSON 对象,不要围栏、不要解释。",
- should_stop, on_delta, depth,
+ should_stop, on_delta,
)
@@ -153,7 +127,6 @@ def complete_text(
validate: Callable[[str], str],
should_stop: Callable[[], bool] | None = None,
on_delta: Callable[[str, str], None] | None = None,
- depth: str = "",
) -> str:
"""调模型并拿回校验过的文本(如 LaTeX 稿件)。剥围栏后校验,坏输出重试一次。"""
@@ -164,5 +137,5 @@ def extract(content: str) -> str:
provider, api_key, model, stage, instruction, user_content,
extract,
"请重新输出完整内容,不要围栏、不要解释。",
- should_stop, on_delta, depth,
- )
\ No newline at end of file
+ should_stop, on_delta,
+ )
diff --git a/gateway/src/mms_gateway/provider.py b/gateway/src/mms_gateway/provider.py
new file mode 100644
index 0000000..5359096
--- /dev/null
+++ b/gateway/src/mms_gateway/provider.py
@@ -0,0 +1,157 @@
+"""OpenAI 兼容 provider 的最小流式客户端。
+
+只做三件事:把 SSE chunk 归一成正文、对 429/5xx 做有界重试、校验端点地址。
+密钥只从调用方按次传入,不落盘、不写日志、不放进异常文本。
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from urllib import error, request
+from urllib.parse import urlparse
+
+RETRYABLE = (429, 500, 502, 503, 504)
+MAX_ATTEMPTS = 3
+TIMEOUT_SECONDS = 120
+LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1"}
+
+
+class ProviderError(RuntimeError):
+ """provider 调用失败。错误文本里不得出现 API Key。"""
+
+
+class CancelledError(RuntimeError):
+ """用户取消了这次运行。"""
+
+
+@dataclass
+class Completion:
+ content: str = ""
+ finish_reason: str = ""
+ usage: dict | None = None
+
+
+def load_providers() -> list[dict]:
+ path = Path(__file__).with_name("providers.json")
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return list(data.get("providers") or [])
+
+
+def find_provider(provider_id: str) -> dict | None:
+ for item in load_providers():
+ if item.get("id") == provider_id:
+ return dict(item)
+ return None
+
+
+def validate_base_url(url: str) -> str:
+ """公网只许 https;http 只许本机回环,防止把密钥送到明文公网。"""
+ value = (url or "").strip().rstrip("/")
+ if not value:
+ raise ProviderError("自定义端点缺少 base URL")
+ parsed = urlparse(value)
+ if parsed.scheme not in ("http", "https"):
+ raise ProviderError("base URL 只支持 http/https")
+ if parsed.username or parsed.password:
+ raise ProviderError("base URL 里不要带凭据")
+ if not parsed.hostname:
+ raise ProviderError("base URL 缺少主机名")
+ if parsed.scheme == "http" and parsed.hostname not in LOOPBACK_HOSTS:
+ raise ProviderError("公网 base URL 必须是 https;http 只接受 127.0.0.1 / localhost / ::1")
+ return value
+
+
+def chat_url(base_url: str) -> str:
+ base = validate_base_url(base_url)
+ if base.endswith("/chat/completions"):
+ return base
+ return base + "/chat/completions"
+
+
+def _retry_delay(exc: error.HTTPError, attempt: int) -> float:
+ raw = (exc.headers.get("Retry-After") or "").strip() if exc.headers else ""
+ try:
+ return max(0.0, min(10.0, float(raw)))
+ except ValueError:
+ return 1.0 * (attempt + 1)
+
+
+def _short(text: str, limit: int = 300) -> str:
+ text = " ".join((text or "").split())
+ return text if len(text) <= limit else text[:limit] + "…"
+
+
+def _post_stream(payload: dict, api_key: str, url: str):
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "text/event-stream",
+ "User-Agent": "mathmodel-studio/0.2",
+ }
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+ req = request.Request(url, data=body, headers=headers, method="POST")
+
+ for attempt in range(MAX_ATTEMPTS):
+ try:
+ return request.urlopen(req, timeout=TIMEOUT_SECONDS)
+ except error.HTTPError as exc:
+ detail = ""
+ try:
+ detail = _short(exc.read(4096).decode("utf-8", "replace"))
+ except OSError:
+ pass
+ if exc.code in RETRYABLE and attempt < MAX_ATTEMPTS - 1:
+ time.sleep(_retry_delay(exc, attempt))
+ continue
+ raise ProviderError(f"provider 返回 HTTP {exc.code}{(':' + detail) if detail else ''}") from exc
+ except error.URLError as exc:
+ if attempt < MAX_ATTEMPTS - 1:
+ time.sleep(1.0 * (attempt + 1))
+ continue
+ raise ProviderError(f"连不上 provider:{exc.reason}") from exc
+ raise ProviderError("服务商连续重试后仍失败")
+
+
+def stream_completion(
+ provider: dict,
+ api_key: str,
+ model: str,
+ messages: list[dict],
+ on_delta,
+ should_stop,
+) -> Completion:
+ """跑一次流式补全。on_delta("token", text) 会收到正文增量。"""
+ url = chat_url(provider.get("base_url") or "")
+ payload = {"model": model, "messages": messages, "stream": True}
+ completion = Completion()
+
+ resp = _post_stream(payload, api_key, url)
+ with resp:
+ for raw in resp:
+ if should_stop():
+ raise CancelledError()
+ line = raw.decode("utf-8", "replace").strip()
+ if not line or line.startswith(":") or not line.startswith("data:"):
+ continue
+ data = line[5:].strip()
+ if data == "[DONE]":
+ break
+ try:
+ chunk = json.loads(data)
+ except json.JSONDecodeError:
+ continue
+ if chunk.get("usage"):
+ completion.usage = chunk["usage"]
+ for choice in chunk.get("choices") or []:
+ delta = choice.get("delta") or {}
+ text = delta.get("content")
+ if text:
+ completion.content += text
+ on_delta("token", text)
+ if choice.get("finish_reason"):
+ completion.finish_reason = str(choice["finish_reason"])
+ return completion
diff --git a/runtime/src/mms/providers.json b/gateway/src/mms_gateway/providers.json
similarity index 100%
rename from runtime/src/mms/providers.json
rename to gateway/src/mms_gateway/providers.json
diff --git a/gateway/src/mms_gateway/server.py b/gateway/src/mms_gateway/server.py
new file mode 100644
index 0000000..c8a9758
--- /dev/null
+++ b/gateway/src/mms_gateway/server.py
@@ -0,0 +1,371 @@
+"""本机通道服务器:stdout 握手,此后只走 127.0.0.1 HTTP + SSE。
+
+安全边界:
+- 只绑 127.0.0.1,每个请求校验 Host 与 Origin(防 DNS rebinding)。
+- 每个请求校验 Bearer token(防同机其他进程顺手调用)。
+- API Key 按次传入,不落盘、不写日志、不放进任何事件。
+"""
+
+from __future__ import annotations
+
+import hmac
+import json
+import os
+import secrets
+import signal
+import sys
+import threading
+import time
+from datetime import datetime
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from . import __version__
+from .provider import ProviderError, find_provider, load_providers, validate_base_url
+
+MAX_BODY = 1 << 20
+MAX_PROBLEM = 200_000
+PING_SECONDS = 15
+DATA_SUFFIXES = (".csv", ".tsv")
+
+
+def data_root(root: Path) -> Path:
+ return Path(os.environ.get("MMS_DATA_DIR") or (root / ".mms")).resolve()
+
+
+def provider_rows() -> list[dict]:
+ rows = [
+ {
+ "id": "fake",
+ "display": "离线模式",
+ "models": ["offline"],
+ "model": "offline",
+ "base_url": "",
+ "requires_key": False,
+ "custom": False,
+ "note": "不联网:用内置基线与样例论文跑通链路。",
+ }
+ ]
+ for item in load_providers():
+ models = [str(m) for m in item.get("models") or []]
+ rows.append(
+ {
+ "id": item.get("id"),
+ "display": item.get("display"),
+ "models": models,
+ "model": models[0] if models else "",
+ "base_url": item.get("base_url") or "",
+ "requires_key": not item.get("custom"),
+ "custom": bool(item.get("custom")),
+ "note": item.get("note") or "",
+ }
+ )
+ return rows
+
+
+class RunJob:
+ def __init__(self, run_id: str) -> None:
+ self.id = run_id
+ self.events: list[dict] = []
+ self.cond = threading.Condition()
+ self.done = False
+ self.cancelled = False
+
+ def emit(self, event: str, data: dict) -> None:
+ with self.cond:
+ self.events.append({"id": str(len(self.events) + 1), "event": event, "data": data})
+ self.cond.notify_all()
+
+ def finish(self) -> None:
+ with self.cond:
+ self.done = True
+ self.cond.notify_all()
+
+ def cancel(self) -> None:
+ self.cancelled = True
+
+ def should_stop(self) -> bool:
+ return self.cancelled
+
+
+class ChannelServer(ThreadingHTTPServer):
+ daemon_threads = True
+ allow_reuse_address = True
+
+ def __init__(self, address, handler, token: str, root: Path, runner_factory=None):
+ super().__init__(address, handler)
+ self.token = token
+ self.root = root
+ self.runner_factory = runner_factory
+ self.data_root = data_root(root)
+ self.jobs: dict[str, RunJob] = {}
+ self.jobs_lock = threading.Lock()
+
+
+class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+ server: ChannelServer
+
+ def log_message(self, fmt: str, *args) -> None:
+ sys.stderr.write("[mms] %s\n" % (fmt % args))
+
+ def _json(self, status: int, payload: dict) -> None:
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json; charset=utf-8")
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Cache-Control", "no-store")
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _error(self, status: int, code: str, message: str) -> None:
+ self._json(status, {"ok": False, "error": {"code": code, "message": message}})
+
+ def _guard(self) -> bool:
+ port = self.server.server_address[1]
+ allowed_hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
+ host = (self.headers.get("Host") or "").strip()
+ if host not in allowed_hosts:
+ self._error(403, "host", "Host 不在回环白名单")
+ return False
+ origin = (self.headers.get("Origin") or "").strip()
+ if origin and origin not in {f"http://{h}" for h in allowed_hosts}:
+ self._error(403, "origin", "Origin 不在回环白名单")
+ return False
+ auth = (self.headers.get("Authorization") or "").strip()
+ if not hmac.compare_digest(auth, f"Bearer {self.server.token}"):
+ self._error(401, "auth", "缺少或错误的 token")
+ return False
+ return True
+
+ def _body(self) -> dict | None:
+ try:
+ length = int(self.headers.get("Content-Length") or "0")
+ except ValueError:
+ self._error(400, "body", "Content-Length 非法")
+ return None
+ if length <= 0 or length > MAX_BODY:
+ self._error(400, "body", "请求体为空或过大")
+ return None
+ try:
+ data = json.loads(self.rfile.read(length).decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ self._error(400, "body", "请求体不是合法 JSON")
+ return None
+ if not isinstance(data, dict):
+ self._error(400, "body", "请求体必须是对象")
+ return None
+ return data
+
+ def do_GET(self) -> None: # noqa: N802
+ if not self._guard():
+ return
+ parsed = urlparse(self.path)
+ if parsed.path == "/health":
+ self._json(200, {"ok": True, "version": __version__, "pid": os.getpid()})
+ return
+ if parsed.path == "/providers":
+ self._json(200, {"ok": True, "providers": provider_rows()})
+ return
+ if parsed.path.startswith("/runs/") and parsed.path.endswith("/events"):
+ run_id = parsed.path[len("/runs/") : -len("/events")].strip("/")
+ self._stream(run_id, parse_qs(parsed.query))
+ return
+ self._error(404, "not_found", "没有这个端点")
+
+ def do_POST(self) -> None: # noqa: N802
+ if not self._guard():
+ return
+ parsed = urlparse(self.path)
+ if parsed.path == "/runs":
+ self._start_run()
+ return
+ if parsed.path.startswith("/runs/") and parsed.path.endswith("/cancel"):
+ run_id = parsed.path[len("/runs/") : -len("/cancel")].strip("/")
+ with self.server.jobs_lock:
+ job = self.server.jobs.get(run_id)
+ if not job:
+ self._error(404, "run", "没有这个运行")
+ return
+ job.cancel()
+ self._json(200, {"ok": True, "runId": run_id})
+ return
+ self._error(404, "not_found", "没有这个端点")
+
+ def _start_run(self) -> None:
+ body = self._body()
+ if body is None:
+ return
+ problem = str(body.get("problem") or "").strip()
+ if len(problem) < 10:
+ self._error(400, "problem", "题面至少写一句完整的题目描述")
+ return
+ if len(problem) > MAX_PROBLEM:
+ self._error(400, "problem", "题面过长")
+ return
+
+ data_path: Path | None = None
+ raw_paths = body.get("dataPaths")
+ if isinstance(raw_paths, list):
+ for item in raw_paths[:10]:
+ if not isinstance(item, str) or not item:
+ continue
+ candidate = Path(item)
+ if candidate.is_file() and candidate.suffix.lower() in DATA_SUFFIXES:
+ data_path = candidate.resolve()
+ break
+ if data_path is None and raw_paths:
+ self._error(400, "data", "数据文件需为存在的 CSV/TSV")
+ return
+
+ ctx = body.get("provider") if isinstance(body.get("provider"), dict) else {}
+ provider_id = str(ctx.get("id") or "fake").strip()
+ api_key = str(ctx.get("apiKey") or "")
+ model = str(ctx.get("model") or "").strip()
+ provider: dict | None = None
+ if provider_id and provider_id != "fake":
+ provider = find_provider(provider_id)
+ if not provider:
+ self._error(400, "provider", "未知服务商")
+ return
+ if provider.get("custom"):
+ try:
+ provider["base_url"] = validate_base_url(str(ctx.get("baseUrl") or ""))
+ except ProviderError as exc:
+ self._error(400, "provider", str(exc))
+ return
+ if not api_key and not provider.get("custom"):
+ self._error(400, "provider", "还没配置 API Key")
+ return
+ if not model:
+ models = [str(m) for m in (provider or {}).get("models") or []]
+ model = models[0] if models else "offline"
+
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
+ run_id = f"{stamp}-{secrets.token_hex(3)}"
+ job_dir = self.server.data_root / "runs" / run_id
+ try:
+ job_dir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ self._error(500, "dir", f"运行目录创建失败:{exc}")
+ return
+
+ if self.server.runner_factory is None:
+ self._error(503, "runner", "服务端没有装配数模流水线")
+ return
+
+ job = RunJob(run_id)
+ with self.server.jobs_lock:
+ while len(self.server.jobs) >= 20:
+ oldest = next(iter(self.server.jobs))
+ self.server.jobs.pop(oldest, None)
+ self.server.jobs[run_id] = job
+
+ runner = self.server.runner_factory(
+ job_dir=job_dir,
+ problem=problem,
+ data_path=data_path,
+ provider=provider,
+ api_key=api_key,
+ model=model,
+ emit=job.emit,
+ should_stop=job.should_stop,
+ )
+
+ def _run() -> None:
+ try:
+ runner.run()
+ finally:
+ job.finish()
+
+ threading.Thread(target=_run, name=f"mms-run-{run_id}", daemon=True).start()
+ self._json(200, {"ok": True, "runId": run_id})
+
+ def _stream(self, run_id: str, query: dict) -> None:
+ with self.server.jobs_lock:
+ job = self.server.jobs.get(run_id)
+ if not job:
+ self._error(404, "run", "没有这个运行")
+ return
+
+ raw_last = (self.headers.get("Last-Event-ID") or (query.get("last_id") or [""])[0] or "0").strip()
+ try:
+ last_id = max(0, int(raw_last))
+ except ValueError:
+ last_id = 0
+
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream; charset=utf-8")
+ self.send_header("Cache-Control", "no-cache")
+ self.send_header("Connection", "close")
+ self.send_header("X-Accel-Buffering", "no")
+ self.end_headers()
+ self.close_connection = True
+ try:
+ self.wfile.write(b"retry: 1500\n\n")
+ self.wfile.flush()
+ index = min(last_id, len(job.events))
+ last_ping = time.monotonic()
+ while True:
+ with job.cond:
+ while index >= len(job.events) and not job.done:
+ job.cond.wait(timeout=PING_SECONDS)
+ if index >= len(job.events):
+ break
+ pending = job.events[index:]
+ done = job.done
+ if pending:
+ for ev in pending:
+ frame = (
+ f"id: {ev['id']}\nevent: {ev['event']}\n"
+ f"data: {json.dumps(ev['data'], ensure_ascii=False)}\n\n"
+ )
+ self.wfile.write(frame.encode("utf-8"))
+ index += len(pending)
+ self.wfile.flush()
+ last_ping = time.monotonic()
+ continue
+ if done:
+ return
+ if time.monotonic() - last_ping >= PING_SECONDS:
+ self.wfile.write(b": ping\n\n")
+ self.wfile.flush()
+ last_ping = time.monotonic()
+ except (BrokenPipeError, ConnectionResetError):
+ return
+
+
+def serve(port: int = 0, runner_factory=None) -> int:
+ token = secrets.token_hex(24)
+ root = Path(os.environ.get("MMS_HOME") or ".").resolve()
+ server = ChannelServer(("127.0.0.1", port), Handler, token, root, runner_factory)
+ print(
+ json.dumps(
+ {
+ "port": server.server_address[1],
+ "token": token,
+ "pid": os.getpid(),
+ "fake": True,
+ "version": __version__,
+ }
+ ),
+ flush=True,
+ )
+ stop = threading.Event()
+
+ def _request_stop(*_args) -> None:
+ stop.set()
+
+ for sig in (signal.SIGTERM, signal.SIGINT):
+ try:
+ signal.signal(sig, _request_stop)
+ except (ValueError, OSError):
+ pass
+
+ thread = threading.Thread(target=server.serve_forever, name="mms-http", daemon=True)
+ thread.start()
+ stop.wait()
+ server.shutdown()
+ server.server_close()
+ return 0
diff --git a/modeling/cli.py b/modeling/cli.py
new file mode 100644
index 0000000..08f6152
--- /dev/null
+++ b/modeling/cli.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python3
+"""数模内核入口:`python modeling/cli.py ...`(或 `npm run mms -- ...`)。
+
+把 `modeling/src` 与 `gateway/src` 加进 sys.path 后转调 `mms_modeling.cli`,
+这样在仓库根就能跑,不必先 pip install -e。
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent / "gateway" / "src"))
+sys.path.insert(0, str(HERE / "src"))
+
+from mms_modeling.cli import main # noqa: E402 (必须先设置 sys.path)
+
+raise SystemExit(main())
diff --git a/modeling/pyproject.toml b/modeling/pyproject.toml
new file mode 100644
index 0000000..685b4fd
--- /dev/null
+++ b/modeling/pyproject.toml
@@ -0,0 +1,18 @@
+[project]
+name = "mms-modeling"
+version = "0.2.0"
+description = "mathmodel-studio 数模内核:一键流水线(题面 → 选模 → 代码 → 论文)"
+requires-python = ">=3.12"
+license = { text = "AGPL-3.0-only" }
+authors = [{ name = "Escap1ng" }]
+dependencies = []
+
+[project.scripts]
+mms = "mms_modeling.cli:main"
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/mms_modeling"]
diff --git a/modeling/requirements.txt b/modeling/requirements.txt
new file mode 100644
index 0000000..56a7434
--- /dev/null
+++ b/modeling/requirements.txt
@@ -0,0 +1,6 @@
+# mathmodel-studio 的 Python 依赖(生成代码与图表)
+# 安装(大陆镜像):
+# python -m pip install -r modeling/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
+
+matplotlib>=3.7
+numpy>=1.24
diff --git a/skills/VENDOR.md b/modeling/skills/VENDOR.md
similarity index 100%
rename from skills/VENDOR.md
rename to modeling/skills/VENDOR.md
diff --git a/skills/manifest.json b/modeling/skills/manifest.json
similarity index 100%
rename from skills/manifest.json
rename to modeling/skills/manifest.json
diff --git a/skills/mathmodel-core/SKILL.md b/modeling/skills/mathmodel-core/SKILL.md
similarity index 100%
rename from skills/mathmodel-core/SKILL.md
rename to modeling/skills/mathmodel-core/SKILL.md
diff --git a/skills/mathmodel-deai/README.md b/modeling/skills/mathmodel-deai/README.md
similarity index 100%
rename from skills/mathmodel-deai/README.md
rename to modeling/skills/mathmodel-deai/README.md
diff --git a/skills/mathmodel-deai/SKILL.md b/modeling/skills/mathmodel-deai/SKILL.md
similarity index 100%
rename from skills/mathmodel-deai/SKILL.md
rename to modeling/skills/mathmodel-deai/SKILL.md
diff --git a/skills/mathmodel-deai/code/check_phrasing.py b/modeling/skills/mathmodel-deai/code/check_phrasing.py
similarity index 100%
rename from skills/mathmodel-deai/code/check_phrasing.py
rename to modeling/skills/mathmodel-deai/code/check_phrasing.py
diff --git a/skills/mathmodel-deai/code/check_style.py b/modeling/skills/mathmodel-deai/code/check_style.py
similarity index 100%
rename from skills/mathmodel-deai/code/check_style.py
rename to modeling/skills/mathmodel-deai/code/check_style.py
diff --git a/skills/mathmodel-deai/code/phrasing-blacklist.json b/modeling/skills/mathmodel-deai/code/phrasing-blacklist.json
similarity index 100%
rename from skills/mathmodel-deai/code/phrasing-blacklist.json
rename to modeling/skills/mathmodel-deai/code/phrasing-blacklist.json
diff --git a/skills/mathmodel-deai/code/strip_invisible.py b/modeling/skills/mathmodel-deai/code/strip_invisible.py
similarity index 100%
rename from skills/mathmodel-deai/code/strip_invisible.py
rename to modeling/skills/mathmodel-deai/code/strip_invisible.py
diff --git a/skills/mathmodel-deai/docs/deai-rules.md b/modeling/skills/mathmodel-deai/docs/deai-rules.md
similarity index 100%
rename from skills/mathmodel-deai/docs/deai-rules.md
rename to modeling/skills/mathmodel-deai/docs/deai-rules.md
diff --git a/skills/mathmodel-deai/docs/no-ai-slop-reference.md b/modeling/skills/mathmodel-deai/docs/no-ai-slop-reference.md
similarity index 100%
rename from skills/mathmodel-deai/docs/no-ai-slop-reference.md
rename to modeling/skills/mathmodel-deai/docs/no-ai-slop-reference.md
diff --git a/skills/mathmodel-deai/examples/clean-sample-en.md b/modeling/skills/mathmodel-deai/examples/clean-sample-en.md
similarity index 100%
rename from skills/mathmodel-deai/examples/clean-sample-en.md
rename to modeling/skills/mathmodel-deai/examples/clean-sample-en.md
diff --git a/skills/mathmodel-deai/examples/clean-sample.tex b/modeling/skills/mathmodel-deai/examples/clean-sample.tex
similarity index 100%
rename from skills/mathmodel-deai/examples/clean-sample.tex
rename to modeling/skills/mathmodel-deai/examples/clean-sample.tex
diff --git a/skills/mathmodel-deai/examples/slop-sample-en.md b/modeling/skills/mathmodel-deai/examples/slop-sample-en.md
similarity index 100%
rename from skills/mathmodel-deai/examples/slop-sample-en.md
rename to modeling/skills/mathmodel-deai/examples/slop-sample-en.md
diff --git a/skills/mathmodel-deai/examples/slop-sample.tex b/modeling/skills/mathmodel-deai/examples/slop-sample.tex
similarity index 100%
rename from skills/mathmodel-deai/examples/slop-sample.tex
rename to modeling/skills/mathmodel-deai/examples/slop-sample.tex
diff --git a/skills/mathmodel-deai/examples/style-slop-sample.tex b/modeling/skills/mathmodel-deai/examples/style-slop-sample.tex
similarity index 100%
rename from skills/mathmodel-deai/examples/style-slop-sample.tex
rename to modeling/skills/mathmodel-deai/examples/style-slop-sample.tex
diff --git a/skills/mathmodel-diagram/README.md b/modeling/skills/mathmodel-diagram/README.md
similarity index 100%
rename from skills/mathmodel-diagram/README.md
rename to modeling/skills/mathmodel-diagram/README.md
diff --git a/skills/mathmodel-diagram/SKILL.md b/modeling/skills/mathmodel-diagram/SKILL.md
similarity index 100%
rename from skills/mathmodel-diagram/SKILL.md
rename to modeling/skills/mathmodel-diagram/SKILL.md
diff --git a/skills/mathmodel-diagram/code/common.py b/modeling/skills/mathmodel-diagram/code/common.py
similarity index 100%
rename from skills/mathmodel-diagram/code/common.py
rename to modeling/skills/mathmodel-diagram/code/common.py
diff --git a/skills/mathmodel-diagram/code/templates/framework_3col.py b/modeling/skills/mathmodel-diagram/code/templates/framework_3col.py
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/framework_3col.py
rename to modeling/skills/mathmodel-diagram/code/templates/framework_3col.py
diff --git a/skills/mathmodel-diagram/code/templates/manifest.json b/modeling/skills/mathmodel-diagram/code/templates/manifest.json
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/manifest.json
rename to modeling/skills/mathmodel-diagram/code/templates/manifest.json
diff --git a/skills/mathmodel-diagram/code/templates/problem_flow.py b/modeling/skills/mathmodel-diagram/code/templates/problem_flow.py
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/problem_flow.py
rename to modeling/skills/mathmodel-diagram/code/templates/problem_flow.py
diff --git a/skills/mathmodel-diagram/code/templates/roadmap_5band.py b/modeling/skills/mathmodel-diagram/code/templates/roadmap_5band.py
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/roadmap_5band.py
rename to modeling/skills/mathmodel-diagram/code/templates/roadmap_5band.py
diff --git a/skills/mathmodel-diagram/code/templates/schema/framework-3col.schema.json b/modeling/skills/mathmodel-diagram/code/templates/schema/framework-3col.schema.json
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/schema/framework-3col.schema.json
rename to modeling/skills/mathmodel-diagram/code/templates/schema/framework-3col.schema.json
diff --git a/skills/mathmodel-diagram/code/templates/schema/problem-flow.schema.json b/modeling/skills/mathmodel-diagram/code/templates/schema/problem-flow.schema.json
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/schema/problem-flow.schema.json
rename to modeling/skills/mathmodel-diagram/code/templates/schema/problem-flow.schema.json
diff --git a/skills/mathmodel-diagram/code/templates/schema/roadmap-5band.schema.json b/modeling/skills/mathmodel-diagram/code/templates/schema/roadmap-5band.schema.json
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/schema/roadmap-5band.schema.json
rename to modeling/skills/mathmodel-diagram/code/templates/schema/roadmap-5band.schema.json
diff --git a/skills/mathmodel-diagram/code/templates/schema/stageflow-3col.schema.json b/modeling/skills/mathmodel-diagram/code/templates/schema/stageflow-3col.schema.json
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/schema/stageflow-3col.schema.json
rename to modeling/skills/mathmodel-diagram/code/templates/schema/stageflow-3col.schema.json
diff --git a/skills/mathmodel-diagram/code/templates/schema/taskflow-land.schema.json b/modeling/skills/mathmodel-diagram/code/templates/schema/taskflow-land.schema.json
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/schema/taskflow-land.schema.json
rename to modeling/skills/mathmodel-diagram/code/templates/schema/taskflow-land.schema.json
diff --git a/skills/mathmodel-diagram/code/templates/stageflow_3col.py b/modeling/skills/mathmodel-diagram/code/templates/stageflow_3col.py
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/stageflow_3col.py
rename to modeling/skills/mathmodel-diagram/code/templates/stageflow_3col.py
diff --git a/skills/mathmodel-diagram/code/templates/taskflow_land.py b/modeling/skills/mathmodel-diagram/code/templates/taskflow_land.py
similarity index 100%
rename from skills/mathmodel-diagram/code/templates/taskflow_land.py
rename to modeling/skills/mathmodel-diagram/code/templates/taskflow_land.py
diff --git a/skills/mathmodel-diagram/code/tools/render_template.py b/modeling/skills/mathmodel-diagram/code/tools/render_template.py
similarity index 100%
rename from skills/mathmodel-diagram/code/tools/render_template.py
rename to modeling/skills/mathmodel-diagram/code/tools/render_template.py
diff --git a/skills/mathmodel-diagram/code/tools/validate_content.py b/modeling/skills/mathmodel-diagram/code/tools/validate_content.py
similarity index 100%
rename from skills/mathmodel-diagram/code/tools/validate_content.py
rename to modeling/skills/mathmodel-diagram/code/tools/validate_content.py
diff --git a/skills/mathmodel-diagram/docs/guides/authoring.md b/modeling/skills/mathmodel-diagram/docs/guides/authoring.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/guides/authoring.md
rename to modeling/skills/mathmodel-diagram/docs/guides/authoring.md
diff --git a/skills/mathmodel-diagram/docs/guides/replication.md b/modeling/skills/mathmodel-diagram/docs/guides/replication.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/guides/replication.md
rename to modeling/skills/mathmodel-diagram/docs/guides/replication.md
diff --git a/skills/mathmodel-diagram/docs/guides/self-check.md b/modeling/skills/mathmodel-diagram/docs/guides/self-check.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/guides/self-check.md
rename to modeling/skills/mathmodel-diagram/docs/guides/self-check.md
diff --git a/skills/mathmodel-diagram/docs/templates/adding-templates.md b/modeling/skills/mathmodel-diagram/docs/templates/adding-templates.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/templates/adding-templates.md
rename to modeling/skills/mathmodel-diagram/docs/templates/adding-templates.md
diff --git a/skills/mathmodel-diagram/docs/templates/framework-3col.md b/modeling/skills/mathmodel-diagram/docs/templates/framework-3col.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/templates/framework-3col.md
rename to modeling/skills/mathmodel-diagram/docs/templates/framework-3col.md
diff --git a/skills/mathmodel-diagram/docs/templates/problem-flow.md b/modeling/skills/mathmodel-diagram/docs/templates/problem-flow.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/templates/problem-flow.md
rename to modeling/skills/mathmodel-diagram/docs/templates/problem-flow.md
diff --git a/skills/mathmodel-diagram/docs/templates/roadmap-5band.md b/modeling/skills/mathmodel-diagram/docs/templates/roadmap-5band.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/templates/roadmap-5band.md
rename to modeling/skills/mathmodel-diagram/docs/templates/roadmap-5band.md
diff --git a/skills/mathmodel-diagram/docs/templates/stageflow-3col.md b/modeling/skills/mathmodel-diagram/docs/templates/stageflow-3col.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/templates/stageflow-3col.md
rename to modeling/skills/mathmodel-diagram/docs/templates/stageflow-3col.md
diff --git a/skills/mathmodel-diagram/docs/templates/taskflow-land.md b/modeling/skills/mathmodel-diagram/docs/templates/taskflow-land.md
similarity index 100%
rename from skills/mathmodel-diagram/docs/templates/taskflow-land.md
rename to modeling/skills/mathmodel-diagram/docs/templates/taskflow-land.md
diff --git a/skills/mathmodel-diagram/examples/framework-3col/example.json b/modeling/skills/mathmodel-diagram/examples/framework-3col/example.json
similarity index 100%
rename from skills/mathmodel-diagram/examples/framework-3col/example.json
rename to modeling/skills/mathmodel-diagram/examples/framework-3col/example.json
diff --git a/skills/mathmodel-diagram/examples/framework-3col/preview.png b/modeling/skills/mathmodel-diagram/examples/framework-3col/preview.png
similarity index 100%
rename from skills/mathmodel-diagram/examples/framework-3col/preview.png
rename to modeling/skills/mathmodel-diagram/examples/framework-3col/preview.png
diff --git a/skills/mathmodel-diagram/examples/problem-flow/example.json b/modeling/skills/mathmodel-diagram/examples/problem-flow/example.json
similarity index 100%
rename from skills/mathmodel-diagram/examples/problem-flow/example.json
rename to modeling/skills/mathmodel-diagram/examples/problem-flow/example.json
diff --git a/skills/mathmodel-diagram/examples/problem-flow/preview.png b/modeling/skills/mathmodel-diagram/examples/problem-flow/preview.png
similarity index 100%
rename from skills/mathmodel-diagram/examples/problem-flow/preview.png
rename to modeling/skills/mathmodel-diagram/examples/problem-flow/preview.png
diff --git a/skills/mathmodel-diagram/examples/roadmap-5band/example.json b/modeling/skills/mathmodel-diagram/examples/roadmap-5band/example.json
similarity index 100%
rename from skills/mathmodel-diagram/examples/roadmap-5band/example.json
rename to modeling/skills/mathmodel-diagram/examples/roadmap-5band/example.json
diff --git a/skills/mathmodel-diagram/examples/roadmap-5band/preview.png b/modeling/skills/mathmodel-diagram/examples/roadmap-5band/preview.png
similarity index 100%
rename from skills/mathmodel-diagram/examples/roadmap-5band/preview.png
rename to modeling/skills/mathmodel-diagram/examples/roadmap-5band/preview.png
diff --git a/skills/mathmodel-diagram/examples/stageflow-3col/example.json b/modeling/skills/mathmodel-diagram/examples/stageflow-3col/example.json
similarity index 100%
rename from skills/mathmodel-diagram/examples/stageflow-3col/example.json
rename to modeling/skills/mathmodel-diagram/examples/stageflow-3col/example.json
diff --git a/skills/mathmodel-diagram/examples/stageflow-3col/preview.png b/modeling/skills/mathmodel-diagram/examples/stageflow-3col/preview.png
similarity index 100%
rename from skills/mathmodel-diagram/examples/stageflow-3col/preview.png
rename to modeling/skills/mathmodel-diagram/examples/stageflow-3col/preview.png
diff --git a/skills/mathmodel-diagram/examples/taskflow-land/example.json b/modeling/skills/mathmodel-diagram/examples/taskflow-land/example.json
similarity index 100%
rename from skills/mathmodel-diagram/examples/taskflow-land/example.json
rename to modeling/skills/mathmodel-diagram/examples/taskflow-land/example.json
diff --git a/skills/mathmodel-diagram/examples/taskflow-land/preview.png b/modeling/skills/mathmodel-diagram/examples/taskflow-land/preview.png
similarity index 100%
rename from skills/mathmodel-diagram/examples/taskflow-land/preview.png
rename to modeling/skills/mathmodel-diagram/examples/taskflow-land/preview.png
diff --git a/skills/mathmodel-figure/README.md b/modeling/skills/mathmodel-figure/README.md
similarity index 100%
rename from skills/mathmodel-figure/README.md
rename to modeling/skills/mathmodel-figure/README.md
diff --git a/skills/mathmodel-figure/SKILL.md b/modeling/skills/mathmodel-figure/SKILL.md
similarity index 100%
rename from skills/mathmodel-figure/SKILL.md
rename to modeling/skills/mathmodel-figure/SKILL.md
diff --git a/skills/mathmodel-figure/code/style/plot_style.py b/modeling/skills/mathmodel-figure/code/style/plot_style.py
similarity index 100%
rename from skills/mathmodel-figure/code/style/plot_style.py
rename to modeling/skills/mathmodel-figure/code/style/plot_style.py
diff --git a/skills/mathmodel-figure/code/templates/make_boxplot_jitter.py b/modeling/skills/mathmodel-figure/code/templates/make_boxplot_jitter.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_boxplot_jitter.py
rename to modeling/skills/mathmodel-figure/code/templates/make_boxplot_jitter.py
diff --git a/skills/mathmodel-figure/code/templates/make_convergence_curve.py b/modeling/skills/mathmodel-figure/code/templates/make_convergence_curve.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_convergence_curve.py
rename to modeling/skills/mathmodel-figure/code/templates/make_convergence_curve.py
diff --git a/skills/mathmodel-figure/code/templates/make_correlation_pairgrid.py b/modeling/skills/mathmodel-figure/code/templates/make_correlation_pairgrid.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_correlation_pairgrid.py
rename to modeling/skills/mathmodel-figure/code/templates/make_correlation_pairgrid.py
diff --git a/skills/mathmodel-figure/code/templates/make_cv_roc_ci.py b/modeling/skills/mathmodel-figure/code/templates/make_cv_roc_ci.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_cv_roc_ci.py
rename to modeling/skills/mathmodel-figure/code/templates/make_cv_roc_ci.py
diff --git a/skills/mathmodel-figure/code/templates/make_fit_confidence_residual.py b/modeling/skills/mathmodel-figure/code/templates/make_fit_confidence_residual.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_fit_confidence_residual.py
rename to modeling/skills/mathmodel-figure/code/templates/make_fit_confidence_residual.py
diff --git a/skills/mathmodel-figure/code/templates/make_grouped_bar.py b/modeling/skills/mathmodel-figure/code/templates/make_grouped_bar.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_grouped_bar.py
rename to modeling/skills/mathmodel-figure/code/templates/make_grouped_bar.py
diff --git a/skills/mathmodel-figure/code/templates/make_grouped_circular_heatmap.py b/modeling/skills/mathmodel-figure/code/templates/make_grouped_circular_heatmap.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_grouped_circular_heatmap.py
rename to modeling/skills/mathmodel-figure/code/templates/make_grouped_circular_heatmap.py
diff --git a/skills/mathmodel-figure/code/templates/make_grouped_corr_split_violin.py b/modeling/skills/mathmodel-figure/code/templates/make_grouped_corr_split_violin.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_grouped_corr_split_violin.py
rename to modeling/skills/mathmodel-figure/code/templates/make_grouped_corr_split_violin.py
diff --git a/skills/mathmodel-figure/code/templates/make_hbar_longlabel.py b/modeling/skills/mathmodel-figure/code/templates/make_hbar_longlabel.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_hbar_longlabel.py
rename to modeling/skills/mathmodel-figure/code/templates/make_hbar_longlabel.py
diff --git a/skills/mathmodel-figure/code/templates/make_heatmap_annotated.py b/modeling/skills/mathmodel-figure/code/templates/make_heatmap_annotated.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_heatmap_annotated.py
rename to modeling/skills/mathmodel-figure/code/templates/make_heatmap_annotated.py
diff --git a/skills/mathmodel-figure/code/templates/make_line_compare.py b/modeling/skills/mathmodel-figure/code/templates/make_line_compare.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_line_compare.py
rename to modeling/skills/mathmodel-figure/code/templates/make_line_compare.py
diff --git a/skills/mathmodel-figure/code/templates/make_multiclass_shap_combo.py b/modeling/skills/mathmodel-figure/code/templates/make_multiclass_shap_combo.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_multiclass_shap_combo.py
rename to modeling/skills/mathmodel-figure/code/templates/make_multiclass_shap_combo.py
diff --git a/skills/mathmodel-figure/code/templates/make_nature_chord_diagram.py b/modeling/skills/mathmodel-figure/code/templates/make_nature_chord_diagram.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_nature_chord_diagram.py
rename to modeling/skills/mathmodel-figure/code/templates/make_nature_chord_diagram.py
diff --git a/skills/mathmodel-figure/code/templates/make_paired_raincloud.py b/modeling/skills/mathmodel-figure/code/templates/make_paired_raincloud.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_paired_raincloud.py
rename to modeling/skills/mathmodel-figure/code/templates/make_paired_raincloud.py
diff --git a/skills/mathmodel-figure/code/templates/make_pareto_front.py b/modeling/skills/mathmodel-figure/code/templates/make_pareto_front.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_pareto_front.py
rename to modeling/skills/mathmodel-figure/code/templates/make_pareto_front.py
diff --git a/skills/mathmodel-figure/code/templates/make_pie_modules.py b/modeling/skills/mathmodel-figure/code/templates/make_pie_modules.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_pie_modules.py
rename to modeling/skills/mathmodel-figure/code/templates/make_pie_modules.py
diff --git a/skills/mathmodel-figure/code/templates/make_prediction_marginal_grid.py b/modeling/skills/mathmodel-figure/code/templates/make_prediction_marginal_grid.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_prediction_marginal_grid.py
rename to modeling/skills/mathmodel-figure/code/templates/make_prediction_marginal_grid.py
diff --git a/skills/mathmodel-figure/code/templates/make_rf_tpe_surface.py b/modeling/skills/mathmodel-figure/code/templates/make_rf_tpe_surface.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_rf_tpe_surface.py
rename to modeling/skills/mathmodel-figure/code/templates/make_rf_tpe_surface.py
diff --git a/skills/mathmodel-figure/code/templates/make_taylor_diagram.py b/modeling/skills/mathmodel-figure/code/templates/make_taylor_diagram.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_taylor_diagram.py
rename to modeling/skills/mathmodel-figure/code/templates/make_taylor_diagram.py
diff --git a/skills/mathmodel-figure/code/templates/make_urban_park_cooling_combo.py b/modeling/skills/mathmodel-figure/code/templates/make_urban_park_cooling_combo.py
similarity index 100%
rename from skills/mathmodel-figure/code/templates/make_urban_park_cooling_combo.py
rename to modeling/skills/mathmodel-figure/code/templates/make_urban_park_cooling_combo.py
diff --git a/skills/mathmodel-figure/code/tools/manifest.json b/modeling/skills/mathmodel-figure/code/tools/manifest.json
similarity index 100%
rename from skills/mathmodel-figure/code/tools/manifest.json
rename to modeling/skills/mathmodel-figure/code/tools/manifest.json
diff --git a/skills/mathmodel-figure/code/tools/render_template.py b/modeling/skills/mathmodel-figure/code/tools/render_template.py
similarity index 100%
rename from skills/mathmodel-figure/code/tools/render_template.py
rename to modeling/skills/mathmodel-figure/code/tools/render_template.py
diff --git a/skills/mathmodel-figure/code/tools/validate_theme.py b/modeling/skills/mathmodel-figure/code/tools/validate_theme.py
similarity index 100%
rename from skills/mathmodel-figure/code/tools/validate_theme.py
rename to modeling/skills/mathmodel-figure/code/tools/validate_theme.py
diff --git a/skills/mathmodel-figure/docs/guides/nature-standard.md b/modeling/skills/mathmodel-figure/docs/guides/nature-standard.md
similarity index 100%
rename from skills/mathmodel-figure/docs/guides/nature-standard.md
rename to modeling/skills/mathmodel-figure/docs/guides/nature-standard.md
diff --git a/skills/mathmodel-figure/docs/guides/plot-recipes.md b/modeling/skills/mathmodel-figure/docs/guides/plot-recipes.md
similarity index 100%
rename from skills/mathmodel-figure/docs/guides/plot-recipes.md
rename to modeling/skills/mathmodel-figure/docs/guides/plot-recipes.md
diff --git a/skills/mathmodel-figure/docs/guides/visualization-rules.md b/modeling/skills/mathmodel-figure/docs/guides/visualization-rules.md
similarity index 100%
rename from skills/mathmodel-figure/docs/guides/visualization-rules.md
rename to modeling/skills/mathmodel-figure/docs/guides/visualization-rules.md
diff --git a/skills/mathmodel-figure/docs/templates/figure-catalog.md b/modeling/skills/mathmodel-figure/docs/templates/figure-catalog.md
similarity index 100%
rename from skills/mathmodel-figure/docs/templates/figure-catalog.md
rename to modeling/skills/mathmodel-figure/docs/templates/figure-catalog.md
diff --git a/skills/mathmodel-figure/examples/previews/boxplot_jitter_replica.png b/modeling/skills/mathmodel-figure/examples/previews/boxplot_jitter_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/boxplot_jitter_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/boxplot_jitter_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/convergence_curve_replica.png b/modeling/skills/mathmodel-figure/examples/previews/convergence_curve_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/convergence_curve_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/convergence_curve_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/correlation_pairgrid_replica.png b/modeling/skills/mathmodel-figure/examples/previews/correlation_pairgrid_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/correlation_pairgrid_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/correlation_pairgrid_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/cv_roc_ci_replica.png b/modeling/skills/mathmodel-figure/examples/previews/cv_roc_ci_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/cv_roc_ci_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/cv_roc_ci_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/fit_confidence_residual_replica.png b/modeling/skills/mathmodel-figure/examples/previews/fit_confidence_residual_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/fit_confidence_residual_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/fit_confidence_residual_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/grouped_bar_replica.png b/modeling/skills/mathmodel-figure/examples/previews/grouped_bar_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/grouped_bar_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/grouped_bar_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/grouped_circular_heatmap_replica.png b/modeling/skills/mathmodel-figure/examples/previews/grouped_circular_heatmap_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/grouped_circular_heatmap_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/grouped_circular_heatmap_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/grouped_corr_split_violin_replica.png b/modeling/skills/mathmodel-figure/examples/previews/grouped_corr_split_violin_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/grouped_corr_split_violin_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/grouped_corr_split_violin_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/hbar_longlabel_replica.png b/modeling/skills/mathmodel-figure/examples/previews/hbar_longlabel_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/hbar_longlabel_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/hbar_longlabel_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/heatmap_annotated_replica.png b/modeling/skills/mathmodel-figure/examples/previews/heatmap_annotated_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/heatmap_annotated_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/heatmap_annotated_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/line_compare_replica.png b/modeling/skills/mathmodel-figure/examples/previews/line_compare_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/line_compare_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/line_compare_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/multiclass_shap_combo_replica.png b/modeling/skills/mathmodel-figure/examples/previews/multiclass_shap_combo_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/multiclass_shap_combo_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/multiclass_shap_combo_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/nature_chord_diagram_replica.png b/modeling/skills/mathmodel-figure/examples/previews/nature_chord_diagram_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/nature_chord_diagram_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/nature_chord_diagram_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/paired_raincloud_replica.png b/modeling/skills/mathmodel-figure/examples/previews/paired_raincloud_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/paired_raincloud_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/paired_raincloud_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/pareto_front_replica.png b/modeling/skills/mathmodel-figure/examples/previews/pareto_front_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/pareto_front_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/pareto_front_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/pie_modules_replica.png b/modeling/skills/mathmodel-figure/examples/previews/pie_modules_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/pie_modules_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/pie_modules_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/prediction_marginal_grid_replica.png b/modeling/skills/mathmodel-figure/examples/previews/prediction_marginal_grid_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/prediction_marginal_grid_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/prediction_marginal_grid_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/rf_tpe_surface_replica.png b/modeling/skills/mathmodel-figure/examples/previews/rf_tpe_surface_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/rf_tpe_surface_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/rf_tpe_surface_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/taylor_diagram_replica.png b/modeling/skills/mathmodel-figure/examples/previews/taylor_diagram_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/taylor_diagram_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/taylor_diagram_replica.png
diff --git a/skills/mathmodel-figure/examples/previews/urban_park_cooling_combo_replica.png b/modeling/skills/mathmodel-figure/examples/previews/urban_park_cooling_combo_replica.png
similarity index 100%
rename from skills/mathmodel-figure/examples/previews/urban_park_cooling_combo_replica.png
rename to modeling/skills/mathmodel-figure/examples/previews/urban_park_cooling_combo_replica.png
diff --git a/skills/mathmodel-figure/themes/README.md b/modeling/skills/mathmodel-figure/themes/README.md
similarity index 100%
rename from skills/mathmodel-figure/themes/README.md
rename to modeling/skills/mathmodel-figure/themes/README.md
diff --git a/skills/mathmodel-figure/themes/nature.theme.json b/modeling/skills/mathmodel-figure/themes/nature.theme.json
similarity index 100%
rename from skills/mathmodel-figure/themes/nature.theme.json
rename to modeling/skills/mathmodel-figure/themes/nature.theme.json
diff --git a/skills/mathmodel-figure/themes/theme.schema.json b/modeling/skills/mathmodel-figure/themes/theme.schema.json
similarity index 100%
rename from skills/mathmodel-figure/themes/theme.schema.json
rename to modeling/skills/mathmodel-figure/themes/theme.schema.json
diff --git a/skills/mathmodel-methods/README.md b/modeling/skills/mathmodel-methods/README.md
similarity index 100%
rename from skills/mathmodel-methods/README.md
rename to modeling/skills/mathmodel-methods/README.md
diff --git a/skills/mathmodel-methods/SKILL.md b/modeling/skills/mathmodel-methods/SKILL.md
similarity index 100%
rename from skills/mathmodel-methods/SKILL.md
rename to modeling/skills/mathmodel-methods/SKILL.md
diff --git a/skills/mathmodel-methods/docs/implementation-guide.md b/modeling/skills/mathmodel-methods/docs/implementation-guide.md
similarity index 100%
rename from skills/mathmodel-methods/docs/implementation-guide.md
rename to modeling/skills/mathmodel-methods/docs/implementation-guide.md
diff --git a/skills/mathmodel-methods/docs/method-library.md b/modeling/skills/mathmodel-methods/docs/method-library.md
similarity index 100%
rename from skills/mathmodel-methods/docs/method-library.md
rename to modeling/skills/mathmodel-methods/docs/method-library.md
diff --git a/skills/mathmodel-methods/docs/selection-guide.md b/modeling/skills/mathmodel-methods/docs/selection-guide.md
similarity index 100%
rename from skills/mathmodel-methods/docs/selection-guide.md
rename to modeling/skills/mathmodel-methods/docs/selection-guide.md
diff --git a/skills/mathmodel-paper/README.md b/modeling/skills/mathmodel-paper/README.md
similarity index 100%
rename from skills/mathmodel-paper/README.md
rename to modeling/skills/mathmodel-paper/README.md
diff --git a/skills/mathmodel-paper/SKILL.md b/modeling/skills/mathmodel-paper/SKILL.md
similarity index 100%
rename from skills/mathmodel-paper/SKILL.md
rename to modeling/skills/mathmodel-paper/SKILL.md
diff --git a/skills/mathmodel-paper/code/word_postprocess.py b/modeling/skills/mathmodel-paper/code/word_postprocess.py
similarity index 100%
rename from skills/mathmodel-paper/code/word_postprocess.py
rename to modeling/skills/mathmodel-paper/code/word_postprocess.py
diff --git a/skills/mathmodel-paper/docs/references.md b/modeling/skills/mathmodel-paper/docs/references.md
similarity index 100%
rename from skills/mathmodel-paper/docs/references.md
rename to modeling/skills/mathmodel-paper/docs/references.md
diff --git a/skills/mathmodel-paper/docs/typesetting-rules.md b/modeling/skills/mathmodel-paper/docs/typesetting-rules.md
similarity index 100%
rename from skills/mathmodel-paper/docs/typesetting-rules.md
rename to modeling/skills/mathmodel-paper/docs/typesetting-rules.md
diff --git a/skills/mathmodel-paper/docs/writing-rules.md b/modeling/skills/mathmodel-paper/docs/writing-rules.md
similarity index 100%
rename from skills/mathmodel-paper/docs/writing-rules.md
rename to modeling/skills/mathmodel-paper/docs/writing-rules.md
diff --git a/skills/mathmodel-paper/templates/abstract-template.md b/modeling/skills/mathmodel-paper/templates/abstract-template.md
similarity index 100%
rename from skills/mathmodel-paper/templates/abstract-template.md
rename to modeling/skills/mathmodel-paper/templates/abstract-template.md
diff --git a/skills/mathmodel-paper/templates/paper.tex b/modeling/skills/mathmodel-paper/templates/paper.tex
similarity index 100%
rename from skills/mathmodel-paper/templates/paper.tex
rename to modeling/skills/mathmodel-paper/templates/paper.tex
diff --git a/skills/mathmodel-score/README.md b/modeling/skills/mathmodel-score/README.md
similarity index 100%
rename from skills/mathmodel-score/README.md
rename to modeling/skills/mathmodel-score/README.md
diff --git a/skills/mathmodel-score/SKILL.md b/modeling/skills/mathmodel-score/SKILL.md
similarity index 100%
rename from skills/mathmodel-score/SKILL.md
rename to modeling/skills/mathmodel-score/SKILL.md
diff --git a/skills/mathmodel-score/code/chapter-checklist.json b/modeling/skills/mathmodel-score/code/chapter-checklist.json
similarity index 100%
rename from skills/mathmodel-score/code/chapter-checklist.json
rename to modeling/skills/mathmodel-score/code/chapter-checklist.json
diff --git a/skills/mathmodel-score/code/check_chapters.py b/modeling/skills/mathmodel-score/code/check_chapters.py
similarity index 100%
rename from skills/mathmodel-score/code/check_chapters.py
rename to modeling/skills/mathmodel-score/code/check_chapters.py
diff --git a/skills/mathmodel-score/code/score_card.py b/modeling/skills/mathmodel-score/code/score_card.py
similarity index 100%
rename from skills/mathmodel-score/code/score_card.py
rename to modeling/skills/mathmodel-score/code/score_card.py
diff --git a/skills/mathmodel-score/docs/chapter-checklist.md b/modeling/skills/mathmodel-score/docs/chapter-checklist.md
similarity index 100%
rename from skills/mathmodel-score/docs/chapter-checklist.md
rename to modeling/skills/mathmodel-score/docs/chapter-checklist.md
diff --git a/skills/mathmodel-score/docs/rubric.md b/modeling/skills/mathmodel-score/docs/rubric.md
similarity index 100%
rename from skills/mathmodel-score/docs/rubric.md
rename to modeling/skills/mathmodel-score/docs/rubric.md
diff --git a/skills/mathmodel-score/docs/self-check.md b/modeling/skills/mathmodel-score/docs/self-check.md
similarity index 100%
rename from skills/mathmodel-score/docs/self-check.md
rename to modeling/skills/mathmodel-score/docs/self-check.md
diff --git a/skills/mathmodel-score/examples/chapter-missing-sample.tex b/modeling/skills/mathmodel-score/examples/chapter-missing-sample.tex
similarity index 100%
rename from skills/mathmodel-score/examples/chapter-missing-sample.tex
rename to modeling/skills/mathmodel-score/examples/chapter-missing-sample.tex
diff --git a/skills/mathmodel-score/examples/chapter-sample.tex b/modeling/skills/mathmodel-score/examples/chapter-sample.tex
similarity index 100%
rename from skills/mathmodel-score/examples/chapter-sample.tex
rename to modeling/skills/mathmodel-score/examples/chapter-sample.tex
diff --git a/skills/mathmodel-score/examples/example-scorecard.json b/modeling/skills/mathmodel-score/examples/example-scorecard.json
similarity index 100%
rename from skills/mathmodel-score/examples/example-scorecard.json
rename to modeling/skills/mathmodel-score/examples/example-scorecard.json
diff --git a/modeling/src/mms_modeling/__init__.py b/modeling/src/mms_modeling/__init__.py
new file mode 100644
index 0000000..fe216f6
--- /dev/null
+++ b/modeling/src/mms_modeling/__init__.py
@@ -0,0 +1,6 @@
+"""mathmodel-studio 数模领域:一键流水线与论文交付。
+
+版本号与 VERSION、desktop/package.json 及两个 pyproject 同源,改一处要同步其余。
+"""
+
+__version__ = "0.2.0"
diff --git a/runtime/src/mms/baseline.py b/modeling/src/mms_modeling/baseline.py
similarity index 92%
rename from runtime/src/mms/baseline.py
rename to modeling/src/mms_modeling/baseline.py
index 508bcb0..229089c 100644
--- a/runtime/src/mms/baseline.py
+++ b/modeling/src/mms_modeling/baseline.py
@@ -14,7 +14,6 @@
import sys
from pathlib import Path
-DATA_SUFFIXES = (".csv", ".tsv")
SCRIPT_NAME = "solution.py"
SAMPLE_NAME = "sample.csv"
@@ -254,25 +253,6 @@ def validate_script(code: str) -> list[str]:
return problems
-def find_data(workspace: Path) -> Path | None:
- """工作区里最新的 CSV/TSV;附件副本在 附件/日期/ 下,所以递归找。"""
- if not workspace.is_dir():
- return None
- best: tuple[float, Path] | None = None
- for path in workspace.rglob("*"):
- if path.suffix.lower() not in DATA_SUFFIXES or not path.is_file():
- continue
- if any(part.startswith(".") for part in path.parts):
- continue
- try:
- mtime = path.stat().st_mtime
- except OSError:
- continue
- if best is None or mtime > best[0]:
- best = (mtime, path)
- return best[1] if best else None
-
-
def ensure_sample(code_dir: Path) -> Path:
"""工作区没有数据时用一份内置样例把链路跑通,文件名与内容都标明 sample。"""
path = code_dir / SAMPLE_NAME
@@ -291,13 +271,6 @@ def ensure_sample(code_dir: Path) -> Path:
return path
-def write_script(code_dir: Path) -> tuple[Path, int]:
- code_dir.mkdir(parents=True, exist_ok=True)
- path = code_dir / SCRIPT_NAME
- path.write_text(SCRIPT, encoding="utf-8")
- return path, len(SCRIPT.splitlines())
-
-
def run_baseline(
code_dir: Path, data_path: Path, out_dir: Path, timeout: int = 180
) -> dict:
diff --git a/modeling/src/mms_modeling/cli.py b/modeling/src/mms_modeling/cli.py
new file mode 100644
index 0000000..6839476
--- /dev/null
+++ b/modeling/src/mms_modeling/cli.py
@@ -0,0 +1,108 @@
+"""`mms` 命令行入口。
+
+serve:桌面壳拉起本机通道(stdout 先输出一行握手 JSON)。
+run:无界面跑一遍流水线,事件按 JSON Lines 打到 stdout,便于 CI 与排障。
+
+退出码:0 成功 / 1 流水线失败 / 2 用法或环境错误。
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+from mms_gateway.common import utf8_console
+from mms_gateway.provider import find_provider
+from mms_gateway.server import serve
+
+from . import __version__
+from .pipeline import Pipeline
+
+
+def cmd_serve(args: argparse.Namespace) -> int:
+ return serve(args.port, Pipeline)
+
+
+def _read_problem(args: argparse.Namespace) -> str:
+ if args.problem_file:
+ path = Path(args.problem_file)
+ if not path.is_file():
+ raise SystemExit(f"题面文件不存在:{path}")
+ return path.read_text(encoding="utf-8", errors="replace")
+ return args.problem or ""
+
+
+def cmd_run(args: argparse.Namespace) -> int:
+ problem = _read_problem(args).strip()
+ if len(problem) < 10:
+ print("题面太短:用 --problem 或 --problem-file 给一段完整题目。", file=sys.stderr)
+ return 2
+
+ data_path = Path(args.data).resolve() if args.data else None
+ if data_path is not None and (not data_path.is_file() or data_path.suffix.lower() not in (".csv", ".tsv")):
+ print(f"数据文件需为存在的 CSV/TSV:{data_path}", file=sys.stderr)
+ return 2
+
+ provider = None
+ if args.provider and args.provider != "fake":
+ provider = find_provider(args.provider)
+ if not provider:
+ print(f"未知服务商:{args.provider}", file=sys.stderr)
+ return 2
+ if not os.environ.get("MMS_API_KEY"):
+ print("真实服务商需要 MMS_API_KEY 环境变量(不会落盘)。", file=sys.stderr)
+ return 2
+
+ stamp = time.strftime("%Y%m%d-%H%M%S")
+ job_dir = Path(args.out).resolve() if args.out else (Path.cwd() / "runs" / stamp)
+ job_dir.mkdir(parents=True, exist_ok=True)
+
+ def emit(event: str, data: dict) -> None:
+ print(json.dumps({"event": event, "data": data}, ensure_ascii=False), flush=True)
+
+ pipeline = Pipeline(
+ job_dir=job_dir,
+ problem=problem,
+ data_path=data_path,
+ provider=provider,
+ api_key=os.environ.get("MMS_API_KEY", ""),
+ model=args.model or ((provider or {}).get("models") or ["offline"])[0],
+ emit=emit,
+ should_stop=lambda: False,
+ )
+ summary = pipeline.run()
+ print(f"输出目录:{job_dir}", file=sys.stderr)
+ return 0 if summary.get("ok") else 1
+
+
+def main(argv: list[str] | None = None) -> int:
+ utf8_console()
+ parser = argparse.ArgumentParser(prog="mms", description="mathmodel-studio 运行时")
+ parser.add_argument("--version", action="version", version=__version__)
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ p_serve = sub.add_parser("serve", help="启动本机通道服务器(桌面壳使用)")
+ p_serve.add_argument("--port", type=int, default=0)
+ p_serve.set_defaults(func=cmd_serve)
+
+ p_run = sub.add_parser("run", help="无界面跑一遍:题面 → 选模 → 代码 → 论文")
+ p_run.add_argument("--problem", "-p", help="题目文本")
+ p_run.add_argument("--problem-file", help="题目文本文件")
+ p_run.add_argument("--data", help="CSV/TSV 数据文件(省略则用内置样例)")
+ p_run.add_argument("--provider", default="fake", help="服务商 id(默认 fake 离线)")
+ p_run.add_argument("--model", help="模型名(省略取服务商第一个)")
+ p_run.add_argument("--out", help="输出目录(省略 runs/<时间戳>)")
+ p_run.set_defaults(func=cmd_run)
+
+ args = parser.parse_args(argv)
+ try:
+ return args.func(args)
+ except SystemExit:
+ raise
+ except Exception as exc: # noqa: BLE001 顶层兜底,错误要能落到退出码
+ print(f"失败:{exc}", file=sys.stderr)
+ return 1
diff --git a/modeling/src/mms_modeling/paper_build.py b/modeling/src/mms_modeling/paper_build.py
new file mode 100644
index 0000000..dfcf006
--- /dev/null
+++ b/modeling/src/mms_modeling/paper_build.py
@@ -0,0 +1,214 @@
+"""论文排版:xelatex 编译 PDF,pandoc 转 Word。
+
+排版工具不在仓库里:xelatex 走系统 PATH(或 MMS_XELATEX),pandoc 依次看
+MMS_PANDOC、随包的 /pandoc、PATH,最后回落到
+%LOCALAPPDATA%/mms-tools/pandoc.exe。缺件时明确报缺,不尝试自动安装。
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import time
+from pathlib import Path
+
+FIGURE_TARGET = Path("figures") / "final" / "fig1_residual.png"
+XELATEX_TIMEOUT = 300
+PANDOC_TIMEOUT = 180
+MAX_TAIL = 4000
+
+
+def _tail(text: str, limit: int = MAX_TAIL) -> str:
+ return (text or "").strip()[-limit:]
+
+
+def _which_pandoc() -> str | None:
+ override = os.environ.get("MMS_PANDOC")
+ if override:
+ return override if Path(override).is_file() else None
+ home = os.environ.get("MMS_HOME")
+ if home:
+ bundled = Path(home) / "pandoc" / ("pandoc.exe" if os.name == "nt" else "pandoc")
+ if bundled.is_file():
+ return str(bundled)
+ found = shutil.which("pandoc")
+ if found:
+ return found
+ local = os.environ.get("LOCALAPPDATA")
+ if local:
+ candidate = Path(local) / "mms-tools" / "pandoc.exe"
+ if candidate.is_file():
+ return str(candidate)
+ return None
+
+
+def _version(exe: str | None) -> str:
+ if not exe:
+ return ""
+ try:
+ proc = subprocess.run(
+ [exe, "--version"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=30,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+ lines = (proc.stdout or "").strip().splitlines()
+ return lines[0].strip() if lines else ""
+
+
+def env_status() -> dict:
+ override = os.environ.get("MMS_XELATEX")
+ xelatex = (override if Path(override).is_file() else None) if override else shutil.which("xelatex")
+ pandoc = _which_pandoc()
+ missing = []
+ if not xelatex:
+ missing.append("xelatex")
+ if not pandoc:
+ missing.append("pandoc")
+ return {
+ "ok": not missing,
+ "missing": missing,
+ "xelatex": {"found": bool(xelatex), "path": xelatex or "", "version": _version(xelatex)},
+ "pandoc": {"found": bool(pandoc), "path": pandoc or "", "version": _version(pandoc)},
+ }
+
+
+def _run(cmd: list[str], cwd: Path, timeout: int) -> subprocess.CompletedProcess:
+ env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}
+ try:
+ return subprocess.run(
+ cmd,
+ cwd=str(cwd),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ env=env,
+ timeout=timeout,
+ check=False,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise RuntimeError(f"命令超时({timeout}s):{cmd[0]}") from exc
+ except OSError as exc:
+ raise RuntimeError(f"无法执行 {cmd[0]}:{exc}") from exc
+
+
+def _check_artifact(path: Path, kind: str) -> tuple[bool, str]:
+ if not path.is_file():
+ return False, f"{kind} 未生成"
+ size = path.stat().st_size
+ if size <= 1000:
+ return False, f"{kind} 只有 {size} B"
+ head = path.open("rb").read(8)
+ if kind == "PDF" and not head.startswith(b"%PDF"):
+ return False, "PDF 文件头不对"
+ if kind == "DOCX" and not head.startswith(b"PK"):
+ return False, "DOCX 不是 zip 容器"
+ return True, f"{kind} {size // 1024} KB"
+
+
+def _first_error(log: str) -> str:
+ for line in (log or "").splitlines():
+ if line.startswith("!") or "error:" in line.lower():
+ return line.strip()[:200]
+ return ""
+
+
+def build(workdir: Path, source_tex: Path, figure_png: Path | None) -> tuple[bool, dict]:
+ """把稿件与配图放进 workdir,编译 PDF/DOCX。返回 (ok, payload)。"""
+ env = env_status()
+ if not env["ok"]:
+ return False, {
+ "ok": False,
+ "error": "缺少排版工具:" + "、".join(env["missing"]),
+ "env": env,
+ "steps": [],
+ "artifacts": {},
+ "logTail": "",
+ }
+
+ steps: list[dict] = []
+ log_tail = ""
+
+ def step(row_id: str, label: str, ok: bool, detail: str, started: float) -> None:
+ steps.append(
+ {"id": row_id, "label": label, "ok": ok, "detail": detail,
+ "ms": int((time.time() - started) * 1000)}
+ )
+
+ started = time.time()
+ try:
+ workdir.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source_tex, workdir / "paper.tex")
+ if figure_png is not None and figure_png.is_file():
+ target = workdir / FIGURE_TARGET
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(figure_png, target)
+ note = "稿件与求解配图已就位"
+ else:
+ note = "稿件已就位(缺配图)"
+ step("stage", "准备稿件", True, note, started)
+ except OSError as exc:
+ step("stage", "准备稿件", False, str(exc), started)
+ return False, _payload(env, steps, {}, str(exc), log_tail, workdir)
+
+ xelatex = env["xelatex"]["path"]
+ pandoc = env["pandoc"]["path"]
+
+ for index in (1, 2):
+ started = time.time()
+ try:
+ proc = _run(
+ [xelatex, "-interaction=nonstopmode", "-halt-on-error", "-no-shell-escape", "paper.tex"],
+ workdir,
+ XELATEX_TIMEOUT,
+ )
+ except RuntimeError as exc:
+ step(f"xelatex-{index}", f"xelatex 第 {index} 遍", False, str(exc), started)
+ return False, _payload(env, steps, {}, str(exc), log_tail, workdir)
+ log_tail = _tail(proc.stdout + "\n" + proc.stderr)
+ ok = proc.returncode == 0
+ detail = "编译通过" if ok else _first_error(proc.stdout) or f"xelatex 退出 {proc.returncode}"
+ step(f"xelatex-{index}", f"xelatex 第 {index} 遍", ok, detail, started)
+ if not ok:
+ return False, _payload(env, steps, {}, f"xelatex 第 {index} 遍失败:{detail}", log_tail, workdir)
+
+ pdf = workdir / "paper.pdf"
+ pdf_ok, pdf_detail = _check_artifact(pdf, "PDF")
+ step("pdf", "PDF 产物", pdf_ok, pdf_detail, time.time())
+ if not pdf_ok:
+ return False, _payload(env, steps, {}, pdf_detail, log_tail, workdir)
+
+ started = time.time()
+ try:
+ proc = _run([pandoc, "paper.tex", "-o", "paper.docx", "--resource-path=."], workdir, PANDOC_TIMEOUT)
+ except RuntimeError as exc:
+ step("pandoc", "pandoc 转 Word", False, str(exc), started)
+ return False, _payload(env, steps, {}, str(exc), log_tail, workdir)
+ docx = workdir / "paper.docx"
+ docx_ok, docx_detail = _check_artifact(docx, "DOCX")
+ step("pandoc", "pandoc 转 Word", docx_ok,
+ docx_detail if docx_ok else _tail(proc.stderr, 400) or docx_detail, started)
+ if not docx_ok:
+ return False, _payload(env, steps, {}, docx_detail, log_tail, workdir)
+
+ artifacts = {"pdf": str(pdf), "docx": str(docx), "tex": str(workdir / "paper.tex")}
+ return True, _payload(env, steps, artifacts, "", log_tail, workdir)
+
+
+def _payload(env: dict, steps: list[dict], artifacts: dict, error: str, log_tail: str, workdir: Path) -> dict:
+ return {
+ "ok": not error,
+ "error": error or None,
+ "env": env,
+ "steps": steps,
+ "artifacts": artifacts,
+ "logTail": log_tail,
+ "workdir": str(workdir),
+ }
diff --git a/runtime/src/mms/paper_gen.py b/modeling/src/mms_modeling/paper_gen.py
similarity index 65%
rename from runtime/src/mms/paper_gen.py
rename to modeling/src/mms_modeling/paper_gen.py
index 763d8d8..4376a07 100644
--- a/runtime/src/mms/paper_gen.py
+++ b/modeling/src/mms_modeling/paper_gen.py
@@ -1,10 +1,7 @@
-"""阶段五 · 论文正文生成:骨架 + 写作规范 + 真实求解结果 → 完整 paper.tex。
+"""论文正文生成:骨架 + 写作规范 + 真实求解结果 → 完整 paper.tex。
-一次生成起步:整篇 tex 由模型按骨架写出,门禁与编译失败回喂修复 ≤3 轮。
-实测输出被截断时再考虑分章生成(见 docs/PLAN.md 的取舍记录)。
-
-离线兜底:没有可用模型时返回演示样例稿,并在对话里标明是兜底,
-不冒充按本题生成的论文。
+一次生成起步:整篇 tex 由模型按骨架写出,编译失败回喂修复。
+离线兜底:没有可用模型时返回样例稿,并在事件里标明是兜底。
"""
from __future__ import annotations
@@ -13,8 +10,9 @@
from collections.abc import Callable
from pathlib import Path
-from . import llm
-from .registry import repo_root
+from mms_gateway import llm
+
+TEMPLATES = Path(__file__).resolve().parent / "templates"
P5_INSTRUCTION = (
"你是数学建模竞赛的论文写作助手。按题面、所选方法、数据画像与真实求解结果,"
@@ -28,7 +26,7 @@
"所有数值必须来自给定的 result.json,禁止编造没有运行过的结果;"
"图用 \\includegraphics[width=0.85\\textwidth]{figures/final/fig1_residual.png} 引用(文件已就位);"
"参考文献至少 3 条真实可查的文献;正文不出现作者身份与页眉。"
- "修复轮次会附上门禁命中项或编译错误与上一版稿件,请针对性修改后重新输出完整稿件。"
+ "修复轮次会附上编译错误与上一版稿件,请针对性修改后重新输出完整稿件。"
)
MAX_RESULT_CHARS = 6000
@@ -37,18 +35,16 @@
MAX_PREV_TEX_CHARS = 12000
-def _skeleton(root: Path) -> str:
- path = root / "skills" / "mathmodel-paper" / "templates" / "paper.tex"
+def _skeleton() -> str:
try:
- return path.read_text(encoding="utf-8")
+ return (TEMPLATES / "paper.tex").read_text(encoding="utf-8")
except OSError:
return ""
-def _writing_rules(root: Path) -> str:
- path = root / "skills" / "mathmodel-paper" / "docs" / "writing-rules.md"
+def _writing_rules() -> str:
try:
- return path.read_text(encoding="utf-8")[:MAX_RULES_CHARS]
+ return (TEMPLATES / "writing-rules.md").read_text(encoding="utf-8")[:MAX_RULES_CHARS]
except OSError:
return ""
@@ -58,11 +54,9 @@ def build_context(
picked: dict,
profile: dict,
result: dict,
- root: Path | None = None,
feedback: str = "",
prev_tex: str = "",
) -> str:
- root = root or repo_root()
explain = picked.get("explain") or {}
parts = [
f"题面:\n{problem}",
@@ -73,14 +67,12 @@ def build_context(
"数据画像:\n" + json.dumps(profile, ensure_ascii=False)[:2000],
"真实求解结果(result.json,论文数值只能来自这里):\n"
+ json.dumps(result, ensure_ascii=False)[:MAX_RESULT_CHARS],
- "LaTeX 骨架(导言区原样沿用,章节结构照此组织):\n" + _skeleton(root),
- "写作规范节选:\n" + _writing_rules(root),
+ "LaTeX 骨架(导言区原样沿用,章节结构照此组织):\n" + _skeleton(),
+ "写作规范节选:\n" + _writing_rules(),
"配图已就位:figures/final/fig1_residual.png(求解产物图),正文必须引用它。",
]
if feedback:
- parts.append(
- f"上一轮未通过,问题如下(请针对性修复):\n{feedback[:MAX_FEEDBACK_CHARS]}"
- )
+ parts.append(f"上一轮未通过,问题如下(请针对性修复):\n{feedback[:MAX_FEEDBACK_CHARS]}")
if prev_tex:
parts.append(f"上一版稿件:\n{prev_tex[:MAX_PREV_TEX_CHARS]}")
return "\n\n".join(parts)
@@ -108,28 +100,19 @@ def generate(
picked: dict,
profile: dict,
result: dict,
- root: Path | None = None,
feedback: str = "",
prev_tex: str = "",
should_stop: Callable[[], bool] | None = None,
on_delta: Callable[[str, str], None] | None = None,
-) -> tuple[str, str]:
- """调模型生成完整 tex,返回 (tex, 来源)。失败抛 LlmError,由编排层决定回退或终止。
-
- 来源为 llm(真实模型)或 fallback(离线演示的样例稿);调用方必须把
- fallback 标明给用户,不冒充按本题生成的论文。
- """
- context = build_context(problem, picked, profile, result, root, feedback, prev_tex)
- tex = llm.complete_text(
+) -> str:
+ context = build_context(problem, picked, profile, result, feedback, prev_tex)
+ return llm.complete_text(
provider, api_key, model, "p5-paper", P5_INSTRUCTION, context, _validate_tex,
should_stop=should_stop, on_delta=on_delta,
)
- source = "fallback" if (provider or {}).get("id") == "fake" else "llm"
- return tex, source
def sample_tex() -> str:
- """离线兜底:演示样例稿(三门禁全绿),调用方必须标明是兜底。"""
- from .paper_build import SAMPLE_TEX
-
- return SAMPLE_TEX.read_text(encoding="utf-8")
\ No newline at end of file
+ """离线兜底:样例稿,调用方必须标明是兜底。"""
+ path = Path(__file__).resolve().parent / "paper_sample" / "paper.tex"
+ return path.read_text(encoding="utf-8")
diff --git a/runtime/src/mms/paper_sample/paper.tex b/modeling/src/mms_modeling/paper_sample/paper.tex
similarity index 96%
rename from runtime/src/mms/paper_sample/paper.tex
rename to modeling/src/mms_modeling/paper_sample/paper.tex
index 789baa4..3dad071 100644
--- a/runtime/src/mms/paper_sample/paper.tex
+++ b/modeling/src/mms_modeling/paper_sample/paper.tex
@@ -1,4 +1,4 @@
-% M5 演示稿:完整走通 xelatex -> pandoc -> 门禁,不是对真实赛题的解答。
+% 样例稿:完整走通 xelatex -> pandoc,不是对真实赛题的解答。
\documentclass[12pt,a4paper]{article}
\usepackage{ctex}
@@ -69,7 +69,7 @@
本文研究单城市共享单车的早晚高峰调度问题。运营方在每个调度周期只能移动有限数量的车辆,站点容量与骑行需求共同决定车辆缺口。本文建立以缺口加权和最小为目标的整数规划模型,并用贪心算法给出可在分钟级求解的调度方案。
问题一估计各站点的净需求。本文用历史骑行记录构造半小时粒度的流入流出差,再按天气与工作日标记做分层修正。
问题二安排调度车辆。模型把每个调度员的路线切成若干段,每段只服务相邻站点,避免跨区空驶。
-在演示数据上,方案把加权缺口从 41.20 降到 12.35,调度里程减少 9.60\%。灵敏度分析显示,缺口权重在 $\pm 20\%$ 内变化时,方案结构保持稳定。
+在样例数据上,方案把加权缺口从 41.20 降到 12.35,调度里程减少 9.60\%。灵敏度分析显示,缺口权重在 $\pm 20\%$ 内变化时,方案结构保持稳定。
\end{abstract}
\vspace{0.2cm}
@@ -188,7 +188,7 @@ \subsection{模型改进}
\section{AI 使用声明}
-本文的演示稿由 mathmodel-studio 的样例流水线生成,用于验证排版与门禁链路。文字与数值均为演示数据,不对应真实赛事论文。
+本文的样例稿由 mathmodel-studio 的离线模式生成,用于验证排版链路。文字与数值均为样例数据,不对应真实赛事论文。
\newpage
\renewcommand{\refname}{参考文献}
diff --git a/modeling/src/mms_modeling/pipeline.py b/modeling/src/mms_modeling/pipeline.py
new file mode 100644
index 0000000..7322a65
--- /dev/null
+++ b/modeling/src/mms_modeling/pipeline.py
@@ -0,0 +1,525 @@
+"""一键流水线:题面 → 选模 → 生成代码 → 运行修复 → 写论文排版。
+
+没有人工确认卡:模型给出的推荐候选直接采用,失败自动回退确定性路径。
+每个阶段的进度通过 emit(event, data) 报给通道层,事件形状见 server.py。
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import time
+from collections.abc import Callable
+from pathlib import Path
+
+from mms_gateway import llm
+from mms_gateway.provider import CancelledError
+
+from . import baseline, paper_build, paper_gen
+
+PHASES = [
+ {"id": 1, "label": "题面拆解"},
+ {"id": 2, "label": "方法选择"},
+ {"id": 3, "label": "生成代码"},
+ {"id": 4, "label": "运行求解"},
+ {"id": 5, "label": "论文排版"},
+]
+
+K2_INSTRUCTION = (
+ "你是数学建模竞赛的题面分析助手。把用户给出的赛题拆成子问题,并核对附件的数据角色。"
+ "只输出一个 JSON 对象,不要围栏、不要解释,形状:"
+ '{"questions":[{"id":"q1","text":"子问题描述","data":"所需数据说明"}],'
+ '"dataRoles":[{"file":"文件名","role":"训练集/预测集/共用","note":"判断依据"}],'
+ '"warning":"数据缺口或风险提醒"}。'
+ "questions 最多 6 条,text 忠实于题面、不改写原意;数据没给就写「未附数据文件」。"
+)
+
+K3_INSTRUCTION = (
+ "你是数学建模竞赛的方法选型助手。针对题面给出恰好 3 条候选路线,"
+ "其中至少 1 条具备明显创新性,并标出恰好一条 recommended。"
+ "只输出一个 JSON 对象,不要围栏、不要解释,形状:"
+ '{"candidates":[{"name":"方法名","idea":"核心思路","innovation":"高/中/低",'
+ '"interpretability":"高/中/低","difficulty":"高/中/低","eta":"预计耗时",'
+ '"accuracy":"精度与鲁棒性预期","math":"数学形式","fit":"为何适配本题",'
+ '"diff":"与未选方案的差异","verify":"验证方式","recommended":true,"reason":"一句推荐理由"}]}。'
+)
+
+SELECTION_GUIDE = (
+ "选型原则:拟合性优先于高级性;能用初等方法解决的不用高等方法;"
+ "创新落点明确(建模/求解/结果/推广其一)。"
+ "问题特征参考:时序预测→ARIMA/Prophet/LSTM,小样本 GM(1,1);评价排序→熵权-TOPSIS/AHP;"
+ "0-1 变量→整数规划+遗传算法;机理演化→微分方程组+RK4+敏感性分析;"
+ "路径配送→TSP/VRP+GA/蚁群;插值补全→三次样条。"
+)
+
+P4_INSTRUCTION = (
+ "你是数学建模竞赛的求解代码生成助手。按题面、所选方法与数据画像,写一个完整可运行的 Python 脚本 solution.py。"
+ "只输出一个 JSON 对象,不要围栏、不要解释,形状:"
+ '{"rationale":"两三句实现思路","code":"完整 Python 源码"}。'
+ "脚本硬性契约:用 argparse 接受 --data(CSV/TSV 路径)与 --out(输出目录);"
+ "在 --out 写出 result.json(含 ok、rows、cols、target 与本题关键数值结果)"
+ "和 figure.png / figure.pdf / figure.svg 三件图(matplotlib 用 Agg 后端,dpi≥150);"
+ "只用标准库 + numpy + matplotlib,不依赖 pandas / scikit-learn;"
+ "数据编码按 utf-8-sig / gbk / utf-8 依次尝试;固定随机种子保证可复现;"
+ "不得联网、不得读写 --data/--out 之外的路径、不得执行系统命令。"
+ "修复轮次会附上上一版代码与失败输出,请针对性修改后重新输出完整脚本。"
+)
+
+P4_MAX_ROUNDS = 3
+P5_MAX_ROUNDS = 3
+
+DEFAULT_CANDIDATES = [
+ {
+ "name": "梯度提升回归",
+ "idea": "用滞后项、窗口统计与外部变量喂给树模型,直接拟合连续目标。",
+ "innovation": "中",
+ "interpretability": "中",
+ "difficulty": "中",
+ "eta": "2–4 小时",
+ "accuracy": "中高",
+ "math": "ŷ = Σ f_k(x),f_k 为逐步拟合残差的回归树;用早停与交叉验证选轮数。",
+ "fit": "样本量中等、特征以结构化数据为主时,先得到一个强基线,再谈复杂机制。",
+ "diff": "比时间序列模型更不依赖平稳性假设,但外推能力弱于机制模型。",
+ "verify": "按时间切分训练/验证,报告 RMSE 与残差自相关。",
+ "recommended": True,
+ "reason": "先跑通这条基线的代价最低,结果可直接对照后续模型。",
+ },
+ {
+ "name": "多元回归 + 正则化",
+ "idea": "用显式变量与约束项给出可解释的基线。",
+ "innovation": "低",
+ "interpretability": "高",
+ "difficulty": "低",
+ "eta": "1–2 小时",
+ "accuracy": "中",
+ "math": "min ‖y−Xβ‖² + λ‖β‖。",
+ "fit": "变量关系近似线性、需要逐项解释时优先。",
+ "diff": "比树模型透明,交互项需要手工构造。",
+ "verify": "残差诊断与系数稳定性检查。",
+ "recommended": False,
+ "reason": "作为透明的对照基线。",
+ },
+ {
+ "name": "机制模型 + 数据校准",
+ "idea": "先写守恒或平衡关系,再用数据校准少量参数。",
+ "innovation": "高",
+ "interpretability": "高",
+ "difficulty": "高",
+ "eta": "3–6 小时",
+ "accuracy": "中高",
+ "math": "由守恒关系给出 f(x,θ)=0,再最小化观测残差。",
+ "fit": "题面给了明确机制或约束时,比纯拟合更可信。",
+ "diff": "可外推、可解释,但建模与校准都更费时间。",
+ "verify": "参数敏感性分析与留出年份回测。",
+ "recommended": False,
+ "reason": "作为机制路线的创新对照。",
+ },
+]
+
+
+def split_questions(problem: str) -> list[str]:
+ text = problem.strip()
+ if not text:
+ return []
+ pattern = r"(?=(?:问题\s*[一二三四五六七八九十0-9]+|(\s*[0-9]+\s*)|\(\s*[0-9]+\s*\)))"
+ parts = [p.strip() for p in re.split(pattern, text) if p.strip()]
+ if len(parts) < 2:
+ parts = [line.strip() for line in text.splitlines() if line.strip()][:3] or [text]
+ return [p[:180] for p in parts[:6]]
+
+
+def _validate_problem(data: dict) -> dict:
+ raw = data.get("questions")
+ if not isinstance(raw, list) or not raw:
+ raise ValueError("questions 必须是非空数组")
+ rows: list[dict] = []
+ for index, item in enumerate(raw[:6]):
+ text = item.get("text") if isinstance(item, dict) else item
+ if not str(text or "").strip():
+ continue
+ rows.append({"id": f"q{index + 1}", "text": str(text).strip()[:300]})
+ if not rows:
+ raise ValueError("没有可用的子问题")
+ return {"questions": rows}
+
+
+def _normalize_candidate(item: dict, index: int) -> dict:
+ explain = item.get("explain") if isinstance(item.get("explain"), dict) else {}
+ row = {
+ "id": f"c{index + 1}",
+ "name": str(item.get("name") or "").strip()[:120],
+ "idea": str(item.get("idea") or "").strip()[:300],
+ "innovation": str(item.get("innovation") or "中").strip()[:20],
+ "interpretability": str(item.get("interpretability") or "中").strip()[:20],
+ "difficulty": str(item.get("difficulty") or "中").strip()[:20],
+ "eta": str(item.get("eta") or "未估").strip()[:60],
+ "accuracy": str(item.get("accuracy") or "").strip()[:120],
+ "recommended": item.get("recommended") is True,
+ "reason": str(item.get("reason") or "").strip()[:200],
+ "explain": {
+ "math": str(item.get("math") or explain.get("math") or "").strip()[:500],
+ "fit": str(item.get("fit") or explain.get("fit") or "").strip()[:500],
+ "diff": str(item.get("diff") or explain.get("diff") or "").strip()[:500],
+ "verify": str(item.get("verify") or explain.get("verify") or "").strip()[:500],
+ },
+ }
+ if not row["name"]:
+ raise ValueError("候选缺少 name")
+ return row
+
+
+def _validate_candidates(data: dict) -> dict:
+ raw = data.get("candidates")
+ if not isinstance(raw, list) or not raw or len(raw) > 5:
+ raise ValueError("candidates 必须是非空数组(最多 5 条)")
+ rows = [_normalize_candidate(item, index) for index, item in enumerate(raw) if isinstance(item, dict)]
+ if not rows:
+ raise ValueError("没有可用的候选")
+ if not any(row["recommended"] for row in rows):
+ rows[0]["recommended"] = True
+ return {"candidates": rows}
+
+
+def _validate_code(data: dict) -> dict:
+ code = data.get("code")
+ if not isinstance(code, str) or not code.strip():
+ raise ValueError("code 必须是非空字符串")
+ problems = baseline.validate_script(code)
+ if problems:
+ raise ValueError("脚本不满足契约:" + ";".join(problems))
+ return {"rationale": str(data.get("rationale") or "").strip()[:500], "code": code}
+
+
+class Pipeline:
+ def __init__(
+ self,
+ job_dir: Path,
+ problem: str,
+ data_path: Path | None,
+ provider: dict | None,
+ api_key: str,
+ model: str,
+ emit: Callable[[str, dict], None],
+ should_stop: Callable[[], bool],
+ ) -> None:
+ self.job_dir = job_dir
+ self.problem = problem.strip()
+ self.data_path = data_path
+ self.provider = provider
+ self.api_key = api_key
+ self.model = model
+ self.emit = emit
+ self.should_stop = should_stop
+ self.questions: list[dict] = []
+ self.picked: dict = {}
+ self.profile: dict = {}
+ self.sources: dict[str, str] = {}
+ self.outputs: dict[str, str] = {}
+ self.error = ""
+ self.started = time.time()
+
+ # ---------- 事件 ----------
+
+ def _log(self, text: str, level: str = "info") -> None:
+ self.emit("log", {"level": level, "text": text})
+
+ def _phase(self, phase_id: int, status: str, detail: str = "") -> None:
+ label = next((p["label"] for p in PHASES if p["id"] == phase_id), "")
+ data = {"id": phase_id, "label": label, "status": status}
+ if detail:
+ data["detail"] = detail
+ self.emit("phase", data)
+
+ def _progress_delta(self, stage: str) -> Callable[[str, str], None]:
+ counter = {"chars": 0, "sent": 0}
+
+ def on_delta(kind: str, text: str) -> None:
+ if kind != "token":
+ return
+ counter["chars"] += len(text)
+ if counter["chars"] - counter["sent"] >= 2000:
+ counter["sent"] = counter["chars"]
+ self.emit("progress", {"stage": stage, "chars": counter["chars"]})
+
+ return on_delta
+
+ # ---------- 主流程 ----------
+
+ def run(self) -> dict:
+ try:
+ self._step_problem()
+ self._step_method()
+ self._step_solve()
+ self._step_paper()
+ except CancelledError:
+ self.error = "已取消"
+ self._finish(False, cancelled=True)
+ return self.summary()
+ except Exception as exc: # noqa: BLE001 顶层兜底,错误要进事件
+ self.error = str(exc) or exc.__class__.__name__
+ self._log(self.error, "error")
+ self._finish(False)
+ return self.summary()
+ self._finish(True)
+ return self.summary()
+
+ def _step_problem(self) -> None:
+ self._phase(1, "running")
+ if len(self.problem) < 10:
+ raise RuntimeError("题面太短:至少写一句完整的题目描述")
+ questions = [
+ {"id": f"q{index + 1}", "text": text}
+ for index, text in enumerate(split_questions(self.problem))
+ ]
+ source = "按小节切分"
+ if self.provider:
+ user = f"题面:\n{self.problem}\n\n数据画像:\n{self._profile_json()}"
+ try:
+ parsed = llm.complete_json(
+ self.provider, self.api_key, self.model, "k2-problem",
+ K2_INSTRUCTION, user, _validate_problem,
+ should_stop=self.should_stop, on_delta=self._progress_delta("题面拆解"),
+ )
+ questions = parsed["questions"]
+ source = "模型拆解"
+ except llm.LlmError as exc:
+ self._log(f"模型拆题不可用({exc}),按小节切分。", "warn")
+ self.questions = questions
+ self.sources["questions"] = source
+ names = ";".join(q["text"][:40] for q in questions[:3])
+ self._log(f"{source}:{len(questions)} 个子问题。{names}")
+ self._phase(1, "ok", f"{len(questions)} 个子问题")
+
+ def _step_method(self) -> None:
+ self._phase(2, "running")
+ candidates: list[dict] = []
+ source = "内置方法族"
+ if self.provider:
+ user = (
+ f"题面:\n{self._problem_with_questions()}\n\n数据画像:\n{self._profile_json()}\n\n"
+ f"{SELECTION_GUIDE}"
+ )
+ try:
+ parsed = llm.complete_json(
+ self.provider, self.api_key, self.model, "k3-models",
+ K3_INSTRUCTION, user, _validate_candidates,
+ should_stop=self.should_stop, on_delta=self._progress_delta("方法选择"),
+ )
+ candidates = parsed["candidates"]
+ source = "模型推荐"
+ except llm.LlmError as exc:
+ self._log(f"模型选模不可用({exc}),使用内置方法族。", "warn")
+ if not candidates:
+ candidates = [_normalize_candidate(item, index) for index, item in enumerate(DEFAULT_CANDIDATES)]
+ picked = next((c for c in candidates if c.get("recommended")), candidates[0])
+ self.picked = picked
+ self.sources["method"] = source
+ self._log(f"{source}:采用「{picked['name']}」——{picked.get('reason') or picked.get('idea') or ''}")
+ self._phase(2, "ok", picked["name"])
+
+ def _step_solve(self) -> None:
+ code_dir = self.job_dir / "code"
+ out_dir = code_dir / "outputs"
+ code_dir.mkdir(parents=True, exist_ok=True)
+ data_path = self.data_path
+ sample = data_path is None
+ if data_path is None:
+ data_path = baseline.ensure_sample(code_dir)
+ self._log("没有选择数据文件,使用内置示例数据 sample.csv 跑通链路。", "warn")
+ self.data_path = data_path
+ self.profile = baseline.profile_data(data_path)
+ self._log(
+ f"数据:{data_path.name}({self.profile.get('rows', '?')} 行 × "
+ f"{self.profile.get('cols', '?')} 列{',示例数据' if sample else ''})"
+ )
+
+ self._phase(3, "running")
+ feedback = ""
+ code = ""
+ for round_no in range(1, P4_MAX_ROUNDS + 1):
+ if self.provider:
+ user = self._p4_user(feedback)
+ try:
+ parsed = llm.complete_json(
+ self.provider, self.api_key, self.model, "p4-code",
+ P4_INSTRUCTION, user, _validate_code,
+ should_stop=self.should_stop, on_delta=self._progress_delta("生成代码"),
+ )
+ code = parsed["code"]
+ self.sources["code"] = "模型生成"
+ except llm.LlmError as exc:
+ self._log(f"第 {round_no} 轮代码生成失败({exc})。", "warn")
+ code = ""
+ if not code:
+ code = baseline.SCRIPT
+ self.sources["code"] = "内置基线"
+ script = code_dir / baseline.SCRIPT_NAME
+ script.write_text(code, encoding="utf-8")
+ self._log(f"第 {round_no} 轮:solution.py 已写入({len(code.splitlines())} 行,{self.sources['code']})。")
+ self._phase(3, "ok", f"solution.py · {len(code.splitlines())} 行")
+
+ self._phase(4, "running")
+ run = baseline.run_baseline(code_dir, data_path, out_dir)
+ if run.get("ok"):
+ stats = run.get("result") or {}
+ self.outputs = {
+ "dir": str(self.job_dir),
+ "code": str(script),
+ "resultJson": str(out_dir / "result.json"),
+ **{kind: path for kind, path in (run.get("outputs") or {}).items()},
+ }
+ fit = ""
+ if isinstance(stats.get("r2"), (int, float)):
+ fit = f"R²={stats['r2']:.3f},RMSE={stats['rmse']:.3f}"
+ self._log(f"运行通过:{fit or '关键数值见 result.json'}")
+ self._phase(4, "ok", fit or "脚本运行通过")
+ return
+
+ error_text = (run.get("stderr") or run.get("stdout") or "").strip()
+ tail = " ".join(error_text.split())[-300:]
+ self._log(f"第 {round_no} 轮运行失败(退出 {run.get('exit')}):{tail}", "error")
+ if not self.provider or round_no >= P4_MAX_ROUNDS:
+ self._phase(4, "error", f"脚本失败(退出 {run.get('exit')})")
+ raise RuntimeError(
+ f"求解脚本运行失败(退出 {run.get('exit')})"
+ + (",已用尽修复轮次" if round_no >= P4_MAX_ROUNDS else "")
+ + (f":{tail}" if tail else "")
+ )
+ feedback = (
+ f"这是第 {round_no + 1} 轮修复。上一版代码运行失败,失败输出(尾部):\n{error_text[-1500:]}\n\n"
+ f"上一版代码:\n{code[:8000]}"
+ )
+
+ def _step_paper(self) -> None:
+ self._phase(5, "running")
+ env = paper_build.env_status()
+ if not env["ok"]:
+ self._phase(5, "error", "缺排版工具")
+ self._log("缺少排版工具(" + "、".join(env["missing"]) + "),求解结果已保留,论文未生成。", "error")
+ self.outputs["paperError"] = "缺少排版工具:" + "、".join(env["missing"])
+ raise RuntimeError("缺少排版工具:" + "、".join(env["missing"]))
+
+ workdir = self.job_dir / "paper"
+ source_tex = workdir / "draft.tex"
+ workdir.mkdir(parents=True, exist_ok=True)
+ figure = Path(self.outputs.get("png") or "") if self.outputs.get("png") else None
+ feedback = ""
+ prev_tex = ""
+ last_error = ""
+ for round_no in range(1, P5_MAX_ROUNDS + 1):
+ tex = ""
+ source = "模型撰写"
+ if self.provider:
+ try:
+ tex = paper_gen.generate(
+ self.provider, self.api_key, self.model,
+ self._problem_with_questions(), self.picked, self.profile,
+ self._result_json(), feedback=feedback, prev_tex=prev_tex,
+ should_stop=self.should_stop,
+ on_delta=self._progress_delta("论文排版"),
+ )
+ except llm.LlmError as exc:
+ self._log(f"第 {round_no} 轮论文生成失败({exc}),改用演示样例稿。", "warn")
+ if not tex:
+ tex = paper_gen.sample_tex()
+ source = "样例稿(兜底)"
+ self.sources["paper"] = source
+ source_tex.write_text(tex, encoding="utf-8")
+ self._log(f"第 {round_no} 轮:论文稿 {len(tex.splitlines())} 行({source}),开始排版。")
+
+ ok, payload = paper_build.build(workdir, source_tex, figure)
+ if ok:
+ artifacts = payload.get("artifacts") or {}
+ self.outputs.update(
+ {
+ "paperPdf": artifacts.get("pdf", ""),
+ "paperDocx": artifacts.get("docx", ""),
+ "paperTex": artifacts.get("tex", ""),
+ }
+ )
+ self._log("排版通过:paper.pdf / paper.docx 已生成。")
+ self._phase(5, "ok", "paper.pdf / paper.docx")
+ return
+
+ last_error = str(payload.get("error") or "排版未通过")
+ self._log(f"第 {round_no} 轮排版失败:{last_error}", "error")
+ if not self.provider or round_no >= P5_MAX_ROUNDS:
+ break
+ feedback = last_error + "\n" + str(payload.get("logTail") or "")
+ prev_tex = tex
+
+ self._phase(5, "error", last_error[:120])
+ raise RuntimeError(f"论文排版失败(已用尽 {P5_MAX_ROUNDS} 轮):{last_error}")
+
+ # ---------- 上下文 ----------
+
+ def _problem_with_questions(self) -> str:
+ if not self.questions:
+ return self.problem
+ lines = "\n".join(f"- {q['text']}" for q in self.questions)
+ return f"{self.problem}\n\n拆出的子问题:\n{lines}"
+
+ def _profile_json(self) -> str:
+ if not self.profile and self.data_path is not None:
+ self.profile = baseline.profile_data(self.data_path)
+ if not self.profile:
+ return "无(未选择数据文件)"
+ return json.dumps(self.profile, ensure_ascii=False)[:3000]
+
+ def _result_json(self) -> dict:
+ path = Path(self.outputs.get("resultJson") or "")
+ if not path.is_file():
+ return {}
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+
+ def _p4_user(self, feedback: str) -> str:
+ explain = self.picked.get("explain") or {}
+ parts = [
+ f"题面:\n{self._problem_with_questions()}",
+ (
+ f"所选方法:{self.picked.get('name')}\n核心思路:{self.picked.get('idea')}\n"
+ f"数学形式:{explain.get('math') or '无'}\n验证方式:{explain.get('verify') or '无'}"
+ ),
+ "数据画像:\n" + self._profile_json(),
+ ]
+ if feedback:
+ parts.append(feedback)
+ return "\n\n".join(parts)
+
+ # ---------- 收尾 ----------
+
+ def summary(self) -> dict:
+ return {
+ "ok": not self.error,
+ "error": self.error,
+ "problem": self.problem,
+ "questions": self.questions,
+ "picked": self.picked,
+ "data": str(self.data_path or ""),
+ "sources": self.sources,
+ "outputs": {key: value for key, value in self.outputs.items() if value},
+ "seconds": round(time.time() - self.started, 1),
+ }
+
+ def _finish(self, ok: bool, cancelled: bool = False) -> None:
+ summary = self.summary()
+ try:
+ (self.job_dir / "summary.json").write_text(
+ json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8"
+ )
+ except OSError:
+ pass
+ data = {
+ "ok": ok,
+ "outputs": summary["outputs"],
+ "error": self.error,
+ "picked": self.picked.get("name", ""),
+ "sources": self.sources,
+ "seconds": summary["seconds"],
+ }
+ if cancelled:
+ data["cancelled"] = True
+ self.emit("done", data)
diff --git a/modeling/src/mms_modeling/templates/paper.tex b/modeling/src/mms_modeling/templates/paper.tex
new file mode 100644
index 0000000..d228de4
--- /dev/null
+++ b/modeling/src/mms_modeling/templates/paper.tex
@@ -0,0 +1,138 @@
+% 论文骨架:占位示例保留,正文按本题内容替换。
+% 用法:生成 paper/paper.tex → xelatex 编译两遍 → pandoc paper.tex -o paper.docx
+\documentclass[12pt,a4paper]{article}
+
+% ========== 编码与中文支持 ==========
+\usepackage{ctex} % 中文支持(禁止inputenc)
+
+% ========== 宏包 ==========
+\usepackage{amsmath,amssymb,amsfonts}
+\usepackage{bm} % 矩阵/向量加粗
+\usepackage{geometry}
+\usepackage{graphicx}
+\usepackage{float}
+\usepackage{booktabs} % 三线表
+\usepackage{array} % m{}列类型(垂直居中)
+\usepackage{tabularx} % X列类型(自动宽度换行)
+\usepackage{multirow}
+\usepackage{caption}
+\usepackage{subcaption}
+\usepackage{hyperref}
+\usepackage{fancyhdr}
+\usepackage{titlesec}
+\usepackage{listings}
+\usepackage{xcolor}
+\usepackage{seqsplit} % 长单词断行
+
+% ========== 西文字体:优先 Times New Roman,缺失时回退度量兼容的 TeX Gyre Termes ==========
+% 竞赛交付环境(Windows/Word)使用 Times New Roman;TeX Live 等不含该商业字体的环境自动
+% 回退到度量兼容字体,因此 CI 不再需要替换字体,用户侧仍得到 Times New Roman。
+\IfFontExistsTF{Times New Roman}
+ {\setmainfont{Times New Roman}}
+ {\setmainfont{TeX Gyre Termes}}
+
+% ========== 页面设置(四边2.5cm) ==========
+\geometry{top=2.5cm, bottom=2.5cm, left=2.5cm, right=2.5cm}
+
+% ========== 标题格式(2026规范) ==========
+\renewcommand{\thesection}{\chinese{section}} % 一级标题使用中文数字
+\titleformat{\section}{\centering\heiti\fontsize{14}{18}\selectfont}{\thesection、}{1em}{} % 标题显示加顿号,交叉引用不受影响
+\titleformat{\subsection}{\heiti\fontsize{12}{16}\selectfont}{\arabic{section}.\arabic{subsection}}{1em}{}
+\titleformat{\subsubsection}{\heiti\fontsize{12}{16}\selectfont}{\arabic{section}.\arabic{subsection}.\arabic{subsubsection}}{1em}{}
+
+% ========== 正文格式 ==========
+\setlength{\parindent}{2em}
+\setlength{\parskip}{0pt}
+\renewcommand{\baselinestretch}{1} % 1倍行距
+
+% ========== 图表标题 ==========
+\captionsetup{font=small, labelsep=space, skip=6pt}
+\captionsetup[figure]{position=below}
+\captionsetup[table]{position=above}
+
+% ========== 页眉页脚:禁止页眉;页码从第一页(摘要页)起页尾居中 ==========
+\pagestyle{fancy}
+\fancyhf{} % 清空页眉页脚(页眉必须留空)
+\fancyfoot[C]{\thepage} % 页尾居中页码,从摘要页第1页开始
+\renewcommand{\headrulewidth}{0pt} % 禁止页眉横线(保证无页眉)
+
+% ========== 代码样式 ==========
+\lstset{
+ basicstyle=\small\ttfamily,
+ keywordstyle=\color{blue},
+ commentstyle=\color{green!60!black},
+ stringstyle=\color{red!70!black},
+ numbers=left,
+ numberstyle=\tiny\color{gray},
+ frame=single,
+ breaklines=true
+}
+
+\begin{document}
+
+% ========== 第一页:题目 + 摘要 + 关键词(必须同页,页码从本页开始) ==========
+\title{\heiti\fontsize{16}{20}\selectfont 论文题目}
+\author{}
+\date{}
+\maketitle
+\thispagestyle{fancy} % 覆盖 \maketitle 默认的 plain 样式,确保首页页脚与正文一致
+
+\vspace{0.3cm}
+
+% 摘要(与标题、关键词同一页,手动格式与正文一致)
+% 按五段式组织:① 钩子切入(背景中的具体矛盾/关键数字/决策困境,最多两句)② 方法链与一句话创新点
+% ③ 逐问结果(模型+算法+关键数值+对比)④ 稳健性/误差一句 ⑤ 结论的现实映射;
+% 禁止"随着…的发展""本文对…进行了深入研究""得到了较为理想的结果"等模板腔;详见 abstract-template.md
+\noindent{\heiti\fontsize{14}{18}\selectfont 摘要:}\par
+\setlength{\parindent}{2em}
+\normalsize
+[① 钩子:以背景中的具体矛盾或关键数字直入……② 方法链与创新点:本文以…为主线,建立…模型,并针对…设计…算法……③ 逐问结果:问题一…[关键数值],较…[对比];问题二以该基线为参照…;问题三进一步……④ 稳健性:敏感性分析显示…结论稳健……⑤ 映射:所得方案/结论可为[具体场景]提供决策依据]
+
+\vspace{0.2cm}
+
+\noindent{\heiti 关键词:}关键词1;关键词2;关键词3
+
+% ========== 关键词后换页,正文从第2页开始 ==========
+\newpage
+
+% ========== 正文内容 ==========
+% 一、问题背景与重述
+% 二、问题分析
+% 三、模型假设
+\section{模型假设}
+
+针对本题实际情况,在建模前提出如下假设,如表\ref{tab:assumptions}所示。
+
+\begin{table}[H]
+\centering
+\caption{模型假设}
+\label{tab:assumptions}
+\begin{tabularx}{\textwidth}{c X X}
+\toprule
+编号 & \multicolumn{1}{c}{假设内容} & \multicolumn{1}{c}{合理性说明} \\
+\midrule
+1 & 假设数据在采集过程中无系统性偏差 & 依据题目说明,数据经标准化预处理 \\
+2 & 假设各周期决策相互独立,无跨周期资源传递 & 题目未声明资源可累积,故按独立处理 \\
+3 & 假设模型参数在求解周期内保持恒定 & 短时间尺度内参数漂移可忽略\cite{ref1} \\
+4 & 假设随机扰动服从均值为零的正态分布 & 依据中心极限定理,多源扰动叠加趋近正态 \\
+\bottomrule
+\end{tabularx}
+\end{table}
+
+% 四、符号说明
+% 五、模型建立与求解(若所有问题共用一套数据,则先设"五、数据处理",本章顺延为第六章,后续章节类推)
+% 六、模型的评价、改进与推广
+
+% ========== 参考文献(另起一页,页码连续) ==========
+\newpage
+\begin{thebibliography}{99}
+\bibitem{ref1} ...
+\end{thebibliography}
+
+% ========== 附录/支撑材料(另起一页,页码连续) ==========
+\newpage
+\section*{附录}
+% 附录A 支撑材料清单
+% 附录B 核心代码
+
+\end{document}
diff --git a/modeling/src/mms_modeling/templates/writing-rules.md b/modeling/src/mms_modeling/templates/writing-rules.md
new file mode 100644
index 0000000..48196ff
--- /dev/null
+++ b/modeling/src/mms_modeling/templates/writing-rules.md
@@ -0,0 +1,51 @@
+# 论文写作规范(精简版)
+
+## 结构
+
+- 题目、摘要、关键词必须在同一页;关键词后用 `\newpage`。
+- 一级章节顺序:问题背景与重述 → 问题分析 → 模型假设 → 符号说明 → 数据处理(各问共用一套数据时设)→ 模型建立与求解 → 模型的评价、改进与推广。
+- 每个问题的求解用二级标题「问题X模型的建立与求解」。
+- 参考文献另起一页,附录另起一页。
+- 导言区沿用给定骨架,不增删宏包;正文不出现作者身份与页眉。
+
+## 标题
+
+推荐组合:方法名 + 研究对象 + 问题类型,20–30 字。
+示例:基于遗传算法的无人机投放策略优化研究;面向多源数据的产量预测与异常识别。
+
+## 摘要(800–1000 字,五段式)
+
+| 段 | 功能 | 写法 |
+| --- | --- | --- |
+| ① 钩子 | 具体矛盾、关键数字或决策困境 | 最多两句,直接切入 |
+| ② 方法链 | 方法组合与一句话创新点 | 创新点回答“解决了旧方法解决不了的什么问题” |
+| ③ 逐问结果 | 每问模型 + 算法 + 关键数值 + 对比 | 数值与正文表格同一小数位,问间递进显式写出 |
+| ④ 稳健性 | 敏感性/交叉验证核心结论 | 一句话说明扰动下结论是否稳定 |
+| ⑤ 映射 | 结果的现实意义与适用场景 | 落到具体场景,不写空泛意义 |
+
+摘要必须含具体数值与误差分析;方法名称与正文一致;关键词 3–5 个,分号分隔。
+
+## 模型假设与符号
+
+- 假设用三线表:编号 | 假设内容 | 合理性说明,4–6 条,表题在上方。
+- 符号用三线表:符号 | 含义 | 单位;正文首次出现时再次说明。
+
+## 图表与数值
+
+- 每张图、每张表都要有编号与标题,并在正文引用(如表X所示、由图X可见)。
+- 数值只能来自本次 `result.json`,禁止编造没有运行过的结果;保留 2–4 位小数,全文一致。
+- 求解图固定引用 `figures/final/fig1_residual.png`。
+- 表格用三线表,不使用竖线。
+
+## 表述
+
+- 避免模板腔:不用“随着…的快速发展”“本文对…进行了深入研究”“得到了较为理想的结果”“具有一定的实际意义”。
+- 改为具体写法:矛盾/数字直入;目标直述;给数值与对比;写明决策场景。
+- 至少 2–3 处客观自审:假设 → 失效情形 → 量化影响 → 适用边界。
+- 结论必须有数据或理论支撑;不确定结果明确标注范围。
+- 算法介绍结合本题数据结构,写清选择理由与关键参数依据,不堆砌模型。
+
+## 参考文献
+
+- GB/T 7714 格式,5–8 篇,至少 2 篇近五年、1 篇英文,真实可查。
+- 正文引用与文末条目一一对应。
diff --git a/open-dev.cmd b/open-dev.cmd
index 0f67220..a46bfce 100644
--- a/open-dev.cmd
+++ b/open-dev.cmd
@@ -1,10 +1,8 @@
@echo off
setlocal
cd /d "%~dp0"
-set MMS_FAKE_PROVIDER=1
-set MMS_FAKE_DELAY_MS=20
set ELECTRON_RUN_AS_NODE=
-echo Starting mathmodel-studio in offline demo mode...
+echo Starting MathModel Studio (offline provider by default)...
echo Close this window to stop the app.
call npm run dev
if errorlevel 1 pause
diff --git a/package-lock.json b/package-lock.json
index 3e76cc5..b3477b2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,21 +1,19 @@
{
- "name": "mathmodel-studio",
- "version": "0.1.0",
+ "name": "mathmodel-studio-workspace",
+ "version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
+ "name": "mathmodel-studio-workspace",
+ "workspaces": [
+ "desktop"
+ ]
+ },
+ "desktop": {
"name": "mathmodel-studio",
- "version": "0.1.0",
+ "version": "0.2.0",
"license": "AGPL-3.0-only",
- "dependencies": {
- "katex": "^0.19.1",
- "pdfjs-dist": "^6.4.299",
- "react-markdown": "^10.1.0",
- "rehype-katex": "^7.0.1",
- "remark-gfm": "^4.0.1",
- "remark-math": "^6.0.0"
- },
"devDependencies": {
"@types/node": "^26.6.5",
"@types/react": "^19.3.0",
@@ -738,271 +736,6 @@
"node": ">=10"
}
},
- "node_modules/@napi-rs/canvas": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas/-/canvas-1.1.0.tgz",
- "integrity": "sha512-k+ph/D8H9GS8ZZ48okvHrKeJynkqAA1kMUZRuzRWNlQUDHXngq7oRaWMZBdmSfd9ZhVy9bwNKei/7wMboI/uMg==",
- "license": "MIT",
- "optional": true,
- "workspaces": [
- "e2e/*"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- },
- "optionalDependencies": {
- "@napi-rs/canvas-android-arm64": "1.1.0",
- "@napi-rs/canvas-darwin-arm64": "1.1.0",
- "@napi-rs/canvas-darwin-x64": "1.1.0",
- "@napi-rs/canvas-linux-arm-gnueabihf": "1.1.0",
- "@napi-rs/canvas-linux-arm64-gnu": "1.1.0",
- "@napi-rs/canvas-linux-arm64-musl": "1.1.0",
- "@napi-rs/canvas-linux-riscv64-gnu": "1.1.0",
- "@napi-rs/canvas-linux-x64-gnu": "1.1.0",
- "@napi-rs/canvas-linux-x64-musl": "1.1.0",
- "@napi-rs/canvas-win32-arm64-msvc": "1.1.0",
- "@napi-rs/canvas-win32-x64-msvc": "1.1.0"
- }
- },
- "node_modules/@napi-rs/canvas-android-arm64": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.1.0.tgz",
- "integrity": "sha512-mKrSmRyhWK4q699Q1xthbZIZi7JBvLtsRNnOZAeFaLPOFT1yo8y82aRC2nNZbXTGJXU7fVDONgGQPr0vo3kerw==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-darwin-arm64": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.1.0.tgz",
- "integrity": "sha512-iqwST4g0oH+x8VCpBIYh+MYokv/mVvkM+v9oJGB0d9A3P2qBh42ogJlVyWq9SpPCrAjS7tplMb1D3OIfxl+utw==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-darwin-x64": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.1.0.tgz",
- "integrity": "sha512-jkeA8eVTxDum03LTvc32YJ28F6KB1U0gYwnWMfOAUQZvWWEh/kvONby4iWGJx3+Tw45UqMGMXjtw2GKNVZDhVg==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.1.0.tgz",
- "integrity": "sha512-Y4YkKG1ijoqkgUdTEEBNG4k+2BK5bR5jGL6S56YxCXYPwGfUd5nED8/74xyc7z+bpixPasCjSYoP3xYPOIGNxw==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-linux-arm64-gnu": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.1.0.tgz",
- "integrity": "sha512-dE/XthqYkiWcBVtKFlZbUXwAYfDuQGqDWixznipJNmevLGpprNnTVQZyftm1RZJudkIOn2EkzYZDMMETM08Row==",
- "cpu": [
- "arm64"
- ],
- "libc": [
- "glibc"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-linux-arm64-musl": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.1.0.tgz",
- "integrity": "sha512-DqZ/CMcHlhU56pPjv9AP0h3U7MFQ5LzC1HzMyRMotL+PFsJmZJA/ziApPYVyyz78DaVLhI8t3So3ztqtijbYpg==",
- "cpu": [
- "arm64"
- ],
- "libc": [
- "musl"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.1.0.tgz",
- "integrity": "sha512-kJ7m5n2VffxWXM5QGa5lfq8ZN4LdOJEoz3aAJAmIqYvKiZw1gRdXqpucnRXsF6D9nLYiiIlevaAtAclR7c5ilg==",
- "cpu": [
- "riscv64"
- ],
- "libc": [
- "glibc"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-linux-x64-gnu": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.1.0.tgz",
- "integrity": "sha512-uQ9JuJlRhQdHyttcMWOiwLkfIqkqaB0YFUVe835LUe12THt2b51HXkTItq0fxWT1jdhUPX2ylWZ1walkJyD6GQ==",
- "cpu": [
- "x64"
- ],
- "libc": [
- "glibc"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-linux-x64-musl": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.1.0.tgz",
- "integrity": "sha512-has4CPPAkkCac/LZ13VAw5p+MJLdaKVoyrhumN/A7uJd6960xYkJNDZgUebyxiha82AFzXx6RV+QJg5qGG079g==",
- "cpu": [
- "x64"
- ],
- "libc": [
- "musl"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-win32-arm64-msvc": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.1.0.tgz",
- "integrity": "sha512-MJnktLKNijmXqdjTughHDZ9TDLZ9uUm2hvFXqaOqn0+w7lphXFnft6bpSgQAc9U1exc20UGIBlzGu9+kiCj9Ag==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
- "node_modules/@napi-rs/canvas-win32-x64-msvc": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.1.0.tgz",
- "integrity": "sha512-08575bFk7iiadxap4h+JxgGut9xDCHAGum6wh0eInN53zEMImkmEHi5MushX2FOmNO7qRNX7BPiDC5ZYBwHeEg==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/Brooooooklyn"
- }
- },
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
@@ -1404,26 +1137,12 @@
"version": "4.1.13",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",
"integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/ms": "*"
}
},
- "node_modules/@types/estree": {
- "version": "1.0.10",
- "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.10.tgz",
- "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==",
- "license": "MIT"
- },
- "node_modules/@types/estree-jsx": {
- "version": "1.0.5",
- "resolved": "https://registry.npmmirror.com/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",
- "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",
- "license": "MIT",
- "dependencies": {
- "@types/estree": "*"
- }
- },
"node_modules/@types/fs-extra": {
"version": "9.0.13",
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-9.0.13.tgz",
@@ -1434,15 +1153,6 @@
"@types/node": "*"
}
},
- "node_modules/@types/hast": {
- "version": "3.0.5",
- "resolved": "https://registry.npmmirror.com/@types/hast/-/hast-3.0.5.tgz",
- "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "*"
- }
- },
"node_modules/@types/http-cache-semantics": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
@@ -1450,12 +1160,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/katex": {
- "version": "0.16.8",
- "resolved": "https://registry.npmmirror.com/@types/katex/-/katex-0.16.8.tgz",
- "integrity": "sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==",
- "license": "MIT"
- },
"node_modules/@types/keyv": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",
@@ -1466,19 +1170,11 @@
"@types/node": "*"
}
},
- "node_modules/@types/mdast": {
- "version": "4.0.4",
- "resolved": "https://registry.npmmirror.com/@types/mdast/-/mdast-4.0.4.tgz",
- "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "*"
- }
- },
"node_modules/@types/ms": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
@@ -1495,6 +1191,7 @@
"version": "19.3.0",
"resolved": "https://registry.npmmirror.com/@types/react/-/react-19.3.0.tgz",
"integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -1520,12 +1217,6 @@
"@types/node": "*"
}
},
- "node_modules/@types/unist": {
- "version": "3.0.3",
- "resolved": "https://registry.npmmirror.com/@types/unist/-/unist-3.0.3.tgz",
- "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
- "license": "MIT"
- },
"node_modules/@typescript/typescript-aix-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmmirror.com/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
@@ -1866,12 +1557,6 @@
"node": ">=16.20.0"
}
},
- "node_modules/@ungap/structured-clone": {
- "version": "1.4.0",
- "resolved": "https://registry.npmmirror.com/@ungap/structured-clone/-/structured-clone-1.4.0.tgz",
- "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==",
- "license": "ISC"
- },
"node_modules/@vitejs/plugin-react": {
"version": "6.1.2",
"resolved": "https://registry.npmmirror.com/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz",
@@ -2201,16 +1886,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/bail": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/bail/-/bail-2.0.2.tgz",
- "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
@@ -2449,16 +2124,6 @@
],
"license": "CC-BY-4.0"
},
- "node_modules/ccount": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/ccount/-/ccount-2.0.1.tgz",
- "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -2476,54 +2141,14 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
- "node_modules/character-entities": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/character-entities/-/character-entities-2.0.2.tgz",
- "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/character-entities-html4": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
- "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/character-entities-legacy": {
- "version": "3.0.0",
- "resolved": "https://registry.npmmirror.com/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
- "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/character-reference-invalid": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
- "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/chownr": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
- "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
- "dev": true,
- "license": "BlueOak-1.0.0",
- "engines": {
- "node": ">=18"
+ "node_modules/chownr": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
}
},
"node_modules/chromium-pickle-js": {
@@ -2610,16 +2235,6 @@
"node": ">= 0.8"
}
},
- "node_modules/comma-separated-tokens": {
- "version": "2.0.3",
- "resolved": "https://registry.npmmirror.com/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
- "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/commander": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
@@ -2712,12 +2327,14 @@
"version": "3.2.3",
"resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -2731,19 +2348,6 @@
}
}
},
- "node_modules/decode-named-character-reference": {
- "version": "1.3.0",
- "resolved": "https://registry.npmmirror.com/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
- "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",
- "license": "MIT",
- "dependencies": {
- "character-entities": "^2.0.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/decompress-response": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
@@ -2831,15 +2435,6 @@
"node": ">=0.4.0"
}
},
- "node_modules/dequal": {
- "version": "2.0.3",
- "resolved": "https://registry.npmmirror.com/dequal/-/dequal-2.0.3.tgz",
- "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -2858,19 +2453,6 @@
"license": "MIT",
"optional": true
},
- "node_modules/devlop": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/devlop/-/devlop-1.1.0.tgz",
- "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
- "license": "MIT",
- "dependencies": {
- "dequal": "^2.0.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/dir-compare": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",
@@ -3203,18 +2785,6 @@
"once": "^1.4.0"
}
},
- "node_modules/entities": {
- "version": "9.0.0",
- "resolved": "https://registry.npmmirror.com/entities/-/entities-9.0.0.tgz",
- "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==",
- "license": "BSD-2-Clause",
- "engines": {
- "node": ">=20.19.0"
- },
- "funding": {
- "url": "https://github.com/fb55/entities?sponsor=1"
- }
- },
"node_modules/env-paths": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/env-paths/-/env-paths-3.0.0.tgz",
@@ -3316,16 +2886,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/estree-util-is-identifier-name": {
- "version": "3.0.0",
- "resolved": "https://registry.npmmirror.com/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
- "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",
- "license": "MIT",
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
"node_modules/exponential-backoff": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
@@ -3333,12 +2893,6 @@
"dev": true,
"license": "Apache-2.0"
},
- "node_modules/extend": {
- "version": "3.0.2",
- "resolved": "https://registry.npmmirror.com/extend/-/extend-3.0.2.tgz",
- "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
- "license": "MIT"
- },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -3762,158 +3316,6 @@
"node": ">= 0.4"
}
},
- "node_modules/hast-util-from-dom": {
- "version": "5.0.1",
- "resolved": "https://registry.npmmirror.com/hast-util-from-dom/-/hast-util-from-dom-5.0.1.tgz",
- "integrity": "sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==",
- "license": "ISC",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "hastscript": "^9.0.0",
- "web-namespaces": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-from-html": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/hast-util-from-html/-/hast-util-from-html-2.1.0.tgz",
- "integrity": "sha512-873p9AuH93gBnATbH8rU3YvjTKxyrIeWd/M9tiLMzn3G82Os0xhQurctfnbYUSrDXoyjbJGpJ2qmTpefMw7ZaQ==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "devlop": "^1.1.0",
- "hast-util-from-parse5": "^8.0.0",
- "parse5": "^8.0.0",
- "vfile": "^6.0.0",
- "vfile-message": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-from-html-isomorphic": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/hast-util-from-html-isomorphic/-/hast-util-from-html-isomorphic-2.0.0.tgz",
- "integrity": "sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "hast-util-from-dom": "^5.0.0",
- "hast-util-from-html": "^2.0.0",
- "unist-util-remove-position": "^5.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-from-parse5": {
- "version": "8.0.4",
- "resolved": "https://registry.npmmirror.com/hast-util-from-parse5/-/hast-util-from-parse5-8.0.4.tgz",
- "integrity": "sha512-Yq7XlXor0Cpb71sI2E0zpv8QxQ5a6rfhDEETk4bcgrFX2SvJAY2PHocWwFtL6U9qyfiyByW3wZ6sZEfP2kW81g==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/unist": "^3.0.0",
- "devlop": "^1.0.0",
- "hastscript": "^9.0.0",
- "property-information": "^7.0.0",
- "vfile": "^6.0.0",
- "vfile-location": "^5.0.0",
- "web-namespaces": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-parse-selector": {
- "version": "4.0.0",
- "resolved": "https://registry.npmmirror.com/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz",
- "integrity": "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-to-jsx-runtime": {
- "version": "2.3.7",
- "resolved": "https://registry.npmmirror.com/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.7.tgz",
- "integrity": "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg==",
- "license": "MIT",
- "dependencies": {
- "@types/estree": "^1.0.0",
- "@types/hast": "^3.0.0",
- "@types/unist": "^3.0.0",
- "comma-separated-tokens": "^2.0.0",
- "devlop": "^1.0.0",
- "estree-util-is-identifier-name": "^3.0.0",
- "hast-util-whitespace": "^3.0.0",
- "mdast-util-mdx-expression": "^2.0.0",
- "mdast-util-mdx-jsx": "^3.0.0",
- "mdast-util-mdxjs-esm": "^2.0.0",
- "property-information": "^7.0.0",
- "space-separated-tokens": "^2.0.0",
- "style-to-object": "^2.0.0",
- "unist-util-position": "^5.0.0",
- "vfile-message": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-to-text": {
- "version": "4.0.3",
- "resolved": "https://registry.npmmirror.com/hast-util-to-text/-/hast-util-to-text-4.0.3.tgz",
- "integrity": "sha512-5yrlWOvGFs6CqHriUpSsNrjzT/Tdo+IOQudbznxOn8K5qblp18MJyzOg8IgDOKQ8MYgQcJA7SusuCjSpDr8mSA==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-whitespace": {
- "version": "3.0.0",
- "resolved": "https://registry.npmmirror.com/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
- "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hastscript": {
- "version": "9.0.3",
- "resolved": "https://registry.npmmirror.com/hastscript/-/hastscript-9.0.3.tgz",
- "integrity": "sha512-1ALZXSmCGmW3h8AMz4R4+QKSKFi7sNgXLVwmwB8FYVtl1CwQ3WDkSAEY/d5tp1g/vbQgq2s1WlHgfO3jbw1TsA==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "comma-separated-tokens": "^2.0.0",
- "hast-util-parse-selector": "^4.0.0",
- "property-information": "^7.0.0",
- "space-separated-tokens": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
"node_modules/hosted-git-info": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz",
@@ -3947,16 +3349,6 @@
"dev": true,
"license": "ISC"
},
- "node_modules/html-url-attributes": {
- "version": "3.0.1",
- "resolved": "https://registry.npmmirror.com/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
- "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",
- "license": "MIT",
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
"node_modules/http-cache-semantics": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz",
@@ -4025,46 +3417,6 @@
"dev": true,
"license": "ISC"
},
- "node_modules/inline-style-parser": {
- "version": "0.2.9",
- "resolved": "https://registry.npmmirror.com/inline-style-parser/-/inline-style-parser-0.2.9.tgz",
- "integrity": "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg==",
- "license": "MIT"
- },
- "node_modules/is-alphabetical": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
- "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/is-alphanumerical": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
- "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
- "license": "MIT",
- "dependencies": {
- "is-alphabetical": "^2.0.0",
- "is-decimal": "^2.0.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/is-decimal": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/is-decimal/-/is-decimal-2.0.1.tgz",
- "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
@@ -4075,28 +3427,6 @@
"node": ">=8"
}
},
- "node_modules/is-hexadecimal": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
- "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/is-plain-obj": {
- "version": "4.1.0",
- "resolved": "https://registry.npmmirror.com/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
- "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
@@ -4246,31 +3576,6 @@
"graceful-fs": "^4.1.6"
}
},
- "node_modules/katex": {
- "version": "0.19.1",
- "resolved": "https://registry.npmmirror.com/katex/-/katex-0.19.1.tgz",
- "integrity": "sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==",
- "funding": [
- "https://opencollective.com/katex",
- "https://github.com/sponsors/katex"
- ],
- "license": "MIT",
- "dependencies": {
- "commander": "^15.0.0"
- },
- "bin": {
- "katex": "cli.js"
- }
- },
- "node_modules/katex/node_modules/commander": {
- "version": "15.1.0",
- "resolved": "https://registry.npmmirror.com/commander/-/commander-15.1.0.tgz",
- "integrity": "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==",
- "license": "MIT",
- "engines": {
- "node": ">=22.12.0"
- }
- },
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -4568,16 +3873,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/longest-streak": {
- "version": "3.1.0",
- "resolved": "https://registry.npmmirror.com/longest-streak/-/longest-streak-3.1.0.tgz",
- "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/lowercase-keys": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
@@ -4608,16 +3903,6 @@
"@jridgewell/sourcemap-codec": "^1.6.0"
}
},
- "node_modules/markdown-table": {
- "version": "3.1.0",
- "resolved": "https://registry.npmmirror.com/markdown-table/-/markdown-table-3.1.0.tgz",
- "integrity": "sha512-xpeSCdM+B+6P3ncfgaB7FoDbtJ30xAe6Z18TGT7AgXJsHqCElCICZovQqdRMm7kHgpTyYv36EupqewoFFSB8vw==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/matcher": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",
@@ -4642,983 +3927,54 @@
"node": ">= 0.4"
}
},
- "node_modules/mdast-util-find-and-replace": {
- "version": "3.0.4",
- "resolved": "https://registry.npmmirror.com/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.4.tgz",
- "integrity": "sha512-z4B5c6jrnJ1ltOQemhWYPBSAo6y42Z8Gt2yEgfgNTMcLSU59B8bfj8Z8AnAlJrBGLnqkdAUZ7jdDEqQw3KuipQ==",
+ "node_modules/mathmodel-studio": {
+ "resolved": "desktop",
+ "link": true
+ },
+ "node_modules/mime": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",
+ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "escape-string-regexp": "^5.0.0",
- "unist-util-is": "^6.0.0",
- "unist-util-visit-parents": "^6.1.0"
+ "bin": {
+ "mime": "cli.js"
},
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
+ "engines": {
+ "node": ">=4.0.0"
}
},
- "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {
- "version": "5.0.0",
- "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",
- "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "dev": true,
"license": "MIT",
"engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/mdast-util-from-markdown": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz",
- "integrity": "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "@types/unist": "^3.0.0",
- "decode-named-character-reference": "^1.0.0",
- "devlop": "^1.0.0",
- "mdast-util-to-string": "^4.0.0",
- "micromark": "^4.0.0",
- "micromark-util-decode-numeric-character-reference": "^2.0.0",
- "micromark-util-decode-string": "^2.0.0",
- "micromark-util-normalize-identifier": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0",
- "unist-util-stringify-position": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
+ "node": ">= 0.6"
}
},
- "node_modules/mdast-util-gfm": {
- "version": "3.1.0",
- "resolved": "https://registry.npmmirror.com/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",
- "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "dev": true,
"license": "MIT",
"dependencies": {
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-gfm-autolink-literal": "^2.0.0",
- "mdast-util-gfm-footnote": "^2.0.0",
- "mdast-util-gfm-strikethrough": "^2.0.0",
- "mdast-util-gfm-table": "^2.0.0",
- "mdast-util-gfm-task-list-item": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0"
+ "mime-db": "1.52.0"
},
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
+ "engines": {
+ "node": ">= 0.6"
}
},
- "node_modules/mdast-util-gfm-autolink-literal": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.1.0.tgz",
- "integrity": "sha512-Jx6QSK8wDo558Bcf7q+1pe0v81g2PVs09Hlvu9xJHmCFRF3sAPW7vXFVIAwBncs3sde92WbsVqNxwdqViA2XnQ==",
+ "node_modules/mimic-response": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",
+ "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "ccount": "^2.0.0",
- "devlop": "^1.0.0",
- "mdast-util-find-and-replace": "^3.0.0",
- "micromark-util-character": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-gfm-footnote": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",
- "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "devlop": "^1.1.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0",
- "micromark-util-normalize-identifier": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-gfm-strikethrough": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.1.tgz",
- "integrity": "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-gfm-table": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.1.tgz",
- "integrity": "sha512-fiIjPrAy4kz68/eFbPHhsiWDGHhqUSVoU1XsfLM5DsEPXw7MxgiVVyulUggFRckVWeT1KXQXkg5vm3kv4oMSOA==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "devlop": "^1.0.0",
- "markdown-table": "^3.0.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0",
- "mdast-util-to-string": "^4.0.0",
- "unist-util-visit": "^5.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-gfm-task-list-item": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.1.tgz",
- "integrity": "sha512-jXVO1hvB2hs82g1esi7I9nIJDqiijbQLIyH2jDUb5s7jIAZMr/79h0VHSq7XHKTqpLARRm+DDNjduB7S9+6XZA==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "devlop": "^1.0.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-math": {
- "version": "3.0.0",
- "resolved": "https://registry.npmmirror.com/mdast-util-math/-/mdast-util-math-3.0.0.tgz",
- "integrity": "sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "devlop": "^1.0.0",
- "longest-streak": "^3.0.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.1.0",
- "unist-util-remove-position": "^5.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-mdx-expression": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",
- "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",
- "license": "MIT",
- "dependencies": {
- "@types/estree-jsx": "^1.0.0",
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "devlop": "^1.0.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-mdx-jsx": {
- "version": "3.2.1",
- "resolved": "https://registry.npmmirror.com/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.1.tgz",
- "integrity": "sha512-oXp1GIa+E9IwIs3a106+tr3Bz2MlTTBvlXjOZMoIat11kk7vjqgmBnksB9WHmWv+gZh7k3IUgpAHlwHB7DH4GQ==",
- "license": "MIT",
- "dependencies": {
- "@types/estree-jsx": "^1.0.0",
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "@types/unist": "^3.0.0",
- "ccount": "^2.0.0",
- "devlop": "^1.1.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0",
- "parse-entities": "^4.0.0",
- "stringify-entities": "^4.0.0",
- "unist-util-stringify-position": "^4.0.0",
- "vfile-message": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-mdxjs-esm": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",
- "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",
- "license": "MIT",
- "dependencies": {
- "@types/estree-jsx": "^1.0.0",
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "devlop": "^1.0.0",
- "mdast-util-from-markdown": "^2.0.0",
- "mdast-util-to-markdown": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-phrasing": {
- "version": "4.1.0",
- "resolved": "https://registry.npmmirror.com/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",
- "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "unist-util-is": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-to-hast": {
- "version": "13.2.1",
- "resolved": "https://registry.npmmirror.com/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
- "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "@ungap/structured-clone": "^1.0.0",
- "devlop": "^1.0.0",
- "micromark-util-sanitize-uri": "^2.0.0",
- "trim-lines": "^3.0.0",
- "unist-util-position": "^5.0.0",
- "unist-util-visit": "^5.0.0",
- "vfile": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-to-markdown": {
- "version": "2.2.3",
- "resolved": "https://registry.npmmirror.com/mdast-util-to-markdown/-/mdast-util-to-markdown-2.2.3.tgz",
- "integrity": "sha512-dImdB6VZRMRac1SwAW6o1c0ESk/7pFFAMCMuKM+9v7LpTSthMM5nzXpqKw4Mjo66aXVKhNkyrP4bMB9MurPyWg==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "@types/unist": "^3.0.0",
- "longest-streak": "^3.0.0",
- "mdast-util-phrasing": "^4.0.0",
- "mdast-util-to-string": "^4.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-classify-character": "^2.0.0",
- "micromark-util-decode-string": "^2.0.0",
- "micromark-util-html-tag-name": "^2.0.0",
- "unist-util-visit": "^5.0.0",
- "zwitch": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/mdast-util-to-string": {
- "version": "4.0.0",
- "resolved": "https://registry.npmmirror.com/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",
- "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark": {
- "version": "4.0.3",
- "resolved": "https://registry.npmmirror.com/micromark/-/micromark-4.0.3.tgz",
- "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "@types/debug": "^4.0.0",
- "debug": "^4.0.0",
- "decode-named-character-reference": "^1.0.0",
- "devlop": "^1.0.0",
- "micromark-core-commonmark": "^2.0.0",
- "micromark-factory-space": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-chunked": "^2.0.0",
- "micromark-util-combine-extensions": "^2.0.0",
- "micromark-util-decode-numeric-character-reference": "^2.0.0",
- "micromark-util-edit-map": "^1.0.0",
- "micromark-util-encode": "^2.0.0",
- "micromark-util-normalize-identifier": "^2.0.0",
- "micromark-util-resolve-all": "^2.0.0",
- "micromark-util-sanitize-uri": "^2.0.0",
- "micromark-util-subtokenize": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-core-commonmark": {
- "version": "2.0.4",
- "resolved": "https://registry.npmmirror.com/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz",
- "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "decode-named-character-reference": "^1.0.0",
- "devlop": "^1.0.0",
- "micromark-factory-destination": "^2.0.0",
- "micromark-factory-label": "^2.0.0",
- "micromark-factory-space": "^2.1.0",
- "micromark-factory-title": "^2.0.0",
- "micromark-factory-whitespace": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-chunked": "^2.0.0",
- "micromark-util-classify-character": "^2.0.0",
- "micromark-util-edit-map": "^1.0.0",
- "micromark-util-html-tag-name": "^2.0.0",
- "micromark-util-normalize-identifier": "^2.0.0",
- "micromark-util-resolve-all": "^2.0.0",
- "micromark-util-subtokenize": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.3"
- }
- },
- "node_modules/micromark-extension-gfm": {
- "version": "3.0.0",
- "resolved": "https://registry.npmmirror.com/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",
- "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",
- "license": "MIT",
- "dependencies": {
- "micromark-extension-gfm-autolink-literal": "^2.0.0",
- "micromark-extension-gfm-footnote": "^2.0.0",
- "micromark-extension-gfm-strikethrough": "^2.0.0",
- "micromark-extension-gfm-table": "^2.0.0",
- "micromark-extension-gfm-tagfilter": "^2.0.0",
- "micromark-extension-gfm-task-list-item": "^2.0.0",
- "micromark-util-combine-extensions": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-gfm-autolink-literal": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",
- "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",
- "license": "MIT",
- "dependencies": {
- "micromark-util-character": "^2.0.0",
- "micromark-util-sanitize-uri": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-gfm-footnote": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",
- "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",
- "license": "MIT",
- "dependencies": {
- "devlop": "^1.0.0",
- "micromark-core-commonmark": "^2.0.0",
- "micromark-factory-space": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-normalize-identifier": "^2.0.0",
- "micromark-util-sanitize-uri": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-gfm-strikethrough": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",
- "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",
- "license": "MIT",
- "dependencies": {
- "devlop": "^1.0.0",
- "micromark-util-chunked": "^2.0.0",
- "micromark-util-classify-character": "^2.0.0",
- "micromark-util-resolve-all": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-gfm-table": {
- "version": "2.1.2",
- "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.2.tgz",
- "integrity": "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA==",
- "license": "MIT",
- "dependencies": {
- "devlop": "^1.0.0",
- "micromark-factory-space": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-gfm-tagfilter": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",
- "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",
- "license": "MIT",
- "dependencies": {
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-gfm-task-list-item": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",
- "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",
- "license": "MIT",
- "dependencies": {
- "devlop": "^1.0.0",
- "micromark-factory-space": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-math": {
- "version": "3.1.0",
- "resolved": "https://registry.npmmirror.com/micromark-extension-math/-/micromark-extension-math-3.1.0.tgz",
- "integrity": "sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==",
- "license": "MIT",
- "dependencies": {
- "@types/katex": "^0.16.0",
- "devlop": "^1.0.0",
- "katex": "^0.16.0",
- "micromark-factory-space": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-extension-math/node_modules/commander": {
- "version": "8.3.0",
- "resolved": "https://registry.npmmirror.com/commander/-/commander-8.3.0.tgz",
- "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
- "license": "MIT",
- "engines": {
- "node": ">= 12"
- }
- },
- "node_modules/micromark-extension-math/node_modules/katex": {
- "version": "0.16.47",
- "resolved": "https://registry.npmmirror.com/katex/-/katex-0.16.47.tgz",
- "integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==",
- "funding": [
- "https://opencollective.com/katex",
- "https://github.com/sponsors/katex"
- ],
- "license": "MIT",
- "dependencies": {
- "commander": "^8.3.0"
- },
- "bin": {
- "katex": "cli.js"
- }
- },
- "node_modules/micromark-factory-destination": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",
- "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-factory-label": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",
- "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "devlop": "^1.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-factory-space": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz",
- "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-character": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-factory-title": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",
- "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-factory-space": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-factory-whitespace": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",
- "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-factory-space": "^2.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-character": {
- "version": "2.1.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
- "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-chunked": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",
- "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-symbol": "^2.0.0"
- }
- },
- "node_modules/micromark-util-classify-character": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",
- "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-character": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-combine-extensions": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",
- "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-chunked": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-decode-numeric-character-reference": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",
- "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-symbol": "^2.0.0"
- }
- },
- "node_modules/micromark-util-decode-string": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",
- "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "decode-named-character-reference": "^1.0.0",
- "micromark-util-character": "^2.0.0",
- "micromark-util-decode-numeric-character-reference": "^2.0.0",
- "micromark-util-symbol": "^2.0.0"
- }
- },
- "node_modules/micromark-util-edit-map": {
- "version": "1.0.0",
- "resolved": "https://registry.npmmirror.com/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz",
- "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-encode": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
- "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT"
- },
- "node_modules/micromark-util-html-tag-name": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",
- "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT"
- },
- "node_modules/micromark-util-normalize-identifier": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",
- "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-symbol": "^2.0.0"
- }
- },
- "node_modules/micromark-util-resolve-all": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",
- "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-sanitize-uri": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
- "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-character": "^2.0.0",
- "micromark-util-encode": "^2.0.0",
- "micromark-util-symbol": "^2.0.0"
- }
- },
- "node_modules/micromark-util-subtokenize": {
- "version": "2.1.0",
- "resolved": "https://registry.npmmirror.com/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",
- "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "devlop": "^1.0.0",
- "micromark-util-chunked": "^2.0.0",
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-symbol": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
- "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT"
- },
- "node_modules/micromark-util-types": {
- "version": "2.0.3",
- "resolved": "https://registry.npmmirror.com/micromark-util-types/-/micromark-util-types-2.0.3.tgz",
- "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT"
- },
- "node_modules/mime": {
- "version": "2.6.0",
- "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",
- "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",
- "dev": true,
- "license": "MIT",
- "bin": {
- "mime": "cli.js"
- },
- "engines": {
- "node": ">=4.0.0"
- }
- },
- "node_modules/mime-db": {
- "version": "1.52.0",
- "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
- "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/mime-types": {
- "version": "2.1.35",
- "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
- "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "mime-db": "1.52.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/mimic-response": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",
- "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=4"
+ "engines": {
+ "node": ">=4"
}
},
"node_modules/minimatch": {
@@ -5688,6 +4044,7 @@
"version": "2.1.3",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
"license": "MIT"
},
"node_modules/nanoid": {
@@ -5896,43 +4253,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/parse-entities": {
- "version": "4.0.2",
- "resolved": "https://registry.npmmirror.com/parse-entities/-/parse-entities-4.0.2.tgz",
- "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^2.0.0",
- "character-entities-legacy": "^3.0.0",
- "character-reference-invalid": "^2.0.0",
- "decode-named-character-reference": "^1.0.0",
- "is-alphanumerical": "^2.0.0",
- "is-decimal": "^2.0.0",
- "is-hexadecimal": "^2.0.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/parse-entities/node_modules/@types/unist": {
- "version": "2.0.11",
- "resolved": "https://registry.npmmirror.com/@types/unist/-/unist-2.0.11.tgz",
- "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
- "license": "MIT"
- },
- "node_modules/parse5": {
- "version": "8.1.1",
- "resolved": "https://registry.npmmirror.com/parse5/-/parse5-8.1.1.tgz",
- "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==",
- "license": "MIT",
- "dependencies": {
- "entities": "^9.0.0"
- },
- "funding": {
- "url": "https://github.com/inikulin/parse5?sponsor=1"
- }
- },
"node_modules/path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
@@ -5953,18 +4273,6 @@
"node": ">=8"
}
},
- "node_modules/pdfjs-dist": {
- "version": "6.4.299",
- "resolved": "https://registry.npmmirror.com/pdfjs-dist/-/pdfjs-dist-6.4.299.tgz",
- "integrity": "sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==",
- "license": "Apache-2.0",
- "engines": {
- "node": ">=22.13.0 || >=24"
- },
- "optionalDependencies": {
- "@napi-rs/canvas": "^1.0.10"
- }
- },
"node_modules/pe-library": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz",
@@ -6148,16 +4456,6 @@
"signal-exit": "^3.0.2"
}
},
- "node_modules/property-information": {
- "version": "7.2.0",
- "resolved": "https://registry.npmmirror.com/property-information/-/property-information-7.2.0.tgz",
- "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/pump": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
@@ -6206,6 +4504,7 @@
"version": "19.3.1",
"resolved": "https://registry.npmmirror.com/react/-/react-19.3.1.tgz",
"integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -6224,33 +4523,6 @@
"react": "^19.3.1"
}
},
- "node_modules/react-markdown": {
- "version": "10.1.0",
- "resolved": "https://registry.npmmirror.com/react-markdown/-/react-markdown-10.1.0.tgz",
- "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "devlop": "^1.0.0",
- "hast-util-to-jsx-runtime": "^2.0.0",
- "html-url-attributes": "^3.0.0",
- "mdast-util-to-hast": "^13.0.0",
- "remark-parse": "^11.0.0",
- "remark-rehype": "^11.0.0",
- "unified": "^11.0.0",
- "unist-util-visit": "^5.0.0",
- "vfile": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- },
- "peerDependencies": {
- "@types/react": ">=18",
- "react": ">=18"
- }
- },
"node_modules/read-binary-file-arch": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",
@@ -6280,132 +4552,6 @@
"util-deprecate": "~1.0.1"
}
},
- "node_modules/rehype-katex": {
- "version": "7.0.1",
- "resolved": "https://registry.npmmirror.com/rehype-katex/-/rehype-katex-7.0.1.tgz",
- "integrity": "sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/katex": "^0.16.0",
- "hast-util-from-html-isomorphic": "^2.0.0",
- "hast-util-to-text": "^4.0.0",
- "katex": "^0.16.0",
- "unist-util-visit-parents": "^6.0.0",
- "vfile": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/rehype-katex/node_modules/commander": {
- "version": "8.3.0",
- "resolved": "https://registry.npmmirror.com/commander/-/commander-8.3.0.tgz",
- "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
- "license": "MIT",
- "engines": {
- "node": ">= 12"
- }
- },
- "node_modules/rehype-katex/node_modules/katex": {
- "version": "0.16.47",
- "resolved": "https://registry.npmmirror.com/katex/-/katex-0.16.47.tgz",
- "integrity": "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==",
- "funding": [
- "https://opencollective.com/katex",
- "https://github.com/sponsors/katex"
- ],
- "license": "MIT",
- "dependencies": {
- "commander": "^8.3.0"
- },
- "bin": {
- "katex": "cli.js"
- }
- },
- "node_modules/remark-gfm": {
- "version": "4.0.1",
- "resolved": "https://registry.npmmirror.com/remark-gfm/-/remark-gfm-4.0.1.tgz",
- "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "mdast-util-gfm": "^3.0.0",
- "micromark-extension-gfm": "^3.0.0",
- "remark-parse": "^11.0.0",
- "remark-stringify": "^11.0.0",
- "unified": "^11.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/remark-math": {
- "version": "6.0.0",
- "resolved": "https://registry.npmmirror.com/remark-math/-/remark-math-6.0.0.tgz",
- "integrity": "sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "mdast-util-math": "^3.0.0",
- "micromark-extension-math": "^3.0.0",
- "unified": "^11.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/remark-parse": {
- "version": "11.0.0",
- "resolved": "https://registry.npmmirror.com/remark-parse/-/remark-parse-11.0.0.tgz",
- "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "mdast-util-from-markdown": "^2.0.0",
- "micromark-util-types": "^2.0.0",
- "unified": "^11.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/remark-rehype": {
- "version": "11.1.2",
- "resolved": "https://registry.npmmirror.com/remark-rehype/-/remark-rehype-11.1.2.tgz",
- "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "mdast-util-to-hast": "^13.0.0",
- "unified": "^11.0.0",
- "vfile": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/remark-stringify": {
- "version": "11.0.0",
- "resolved": "https://registry.npmmirror.com/remark-stringify/-/remark-stringify-11.0.0.tgz",
- "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",
- "license": "MIT",
- "dependencies": {
- "@types/mdast": "^4.0.0",
- "mdast-util-to-markdown": "^2.0.0",
- "unified": "^11.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -6688,16 +4834,6 @@
"source-map": "^0.6.0"
}
},
- "node_modules/space-separated-tokens": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
- "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/sprintf-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
@@ -6741,20 +4877,6 @@
"node": ">=8"
}
},
- "node_modules/stringify-entities": {
- "version": "4.0.4",
- "resolved": "https://registry.npmmirror.com/stringify-entities/-/stringify-entities-4.0.4.tgz",
- "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
- "license": "MIT",
- "dependencies": {
- "character-entities-html4": "^2.0.0",
- "character-entities-legacy": "^3.0.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -6768,15 +4890,6 @@
"node": ">=8"
}
},
- "node_modules/style-to-object": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/style-to-object/-/style-to-object-2.0.2.tgz",
- "integrity": "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA==",
- "license": "MIT",
- "dependencies": {
- "inline-style-parser": "0.2.9"
- }
- },
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmmirror.com/sumchecker/-/sumchecker-3.0.1.tgz",
@@ -6913,26 +5026,6 @@
"tmp": "^0.2.0"
}
},
- "node_modules/trim-lines": {
- "version": "3.0.1",
- "resolved": "https://registry.npmmirror.com/trim-lines/-/trim-lines-3.0.1.tgz",
- "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/trough": {
- "version": "2.2.0",
- "resolved": "https://registry.npmmirror.com/trough/-/trough-2.2.0.tgz",
- "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/truncate-utf8-bytes": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz",
@@ -7017,107 +5110,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/unified": {
- "version": "11.0.5",
- "resolved": "https://registry.npmmirror.com/unified/-/unified-11.0.5.tgz",
- "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "bail": "^2.0.0",
- "devlop": "^1.0.0",
- "extend": "^3.0.0",
- "is-plain-obj": "^4.0.0",
- "trough": "^2.0.0",
- "vfile": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-is": {
- "version": "6.0.1",
- "resolved": "https://registry.npmmirror.com/unist-util-is/-/unist-util-is-6.0.1.tgz",
- "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-position": {
- "version": "5.0.0",
- "resolved": "https://registry.npmmirror.com/unist-util-position/-/unist-util-position-5.0.0.tgz",
- "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-remove-position": {
- "version": "5.0.0",
- "resolved": "https://registry.npmmirror.com/unist-util-remove-position/-/unist-util-remove-position-5.0.0.tgz",
- "integrity": "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "unist-util-visit": "^5.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-stringify-position": {
- "version": "4.0.0",
- "resolved": "https://registry.npmmirror.com/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
- "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-visit": {
- "version": "5.2.0",
- "resolved": "https://registry.npmmirror.com/unist-util-visit/-/unist-util-visit-5.2.0.tgz",
- "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "unist-util-is": "^6.0.0",
- "unist-util-visit-parents": "^6.1.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-visit-parents": {
- "version": "6.1.0",
- "resolved": "https://registry.npmmirror.com/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz",
- "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "unist-util-is": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -7202,48 +5194,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/vfile": {
- "version": "6.0.3",
- "resolved": "https://registry.npmmirror.com/vfile/-/vfile-6.0.3.tgz",
- "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "vfile-message": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/vfile-location": {
- "version": "5.0.4",
- "resolved": "https://registry.npmmirror.com/vfile-location/-/vfile-location-5.0.4.tgz",
- "integrity": "sha512-vEvxatYZCIpNvzGk2UD+u4I/sZkSKoOsdRCbkOIsN73QpJbriJ1qvvBAL1PeI0y55Leoqf7pORbaSPpG/smmOg==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "vfile": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/vfile-message": {
- "version": "4.0.4",
- "resolved": "https://registry.npmmirror.com/vfile-message/-/vfile-message-4.0.4.tgz",
- "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "unist-util-stringify-position": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
"node_modules/vite": {
"version": "8.3.4",
"resolved": "https://registry.npmmirror.com/vite/-/vite-8.3.4.tgz",
@@ -7322,16 +5272,6 @@
}
}
},
- "node_modules/web-namespaces": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/web-namespaces/-/web-namespaces-2.0.1.tgz",
- "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/webcrypto-core": {
"version": "1.9.2",
"resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz",
@@ -7455,16 +5395,6 @@
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
- },
- "node_modules/zwitch": {
- "version": "2.0.4",
- "resolved": "https://registry.npmmirror.com/zwitch/-/zwitch-2.0.4.tgz",
- "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
}
}
}
diff --git a/package.json b/package.json
index 143c4b3..17fb433 100644
--- a/package.json
+++ b/package.json
@@ -1,61 +1,17 @@
{
- "name": "mathmodel-studio",
- "version": "0.2.0",
+ "name": "mathmodel-studio-workspace",
"private": true,
- "description": "数学建模竞赛桌面 Agent:白底三栏工作台,人在环的选模、解释、门禁与评分",
- "author": "Escap1ng",
- "license": "AGPL-3.0-only",
- "main": "out/main/index.js",
+ "workspaces": ["desktop"],
"scripts": {
- "dev": "electron-vite dev",
- "build": "electron-vite build",
- "preview": "electron-vite preview",
- "pack:win": "npm run build && electron-builder --win --dir",
- "dist:win": "npm run build && electron-builder --win nsis",
- "vendor:python": "node scripts/prepare-vendor.mjs python",
- "vendor:pandoc": "node scripts/prepare-vendor.mjs pandoc",
- "typecheck": "tsc -p tsconfig.node.json --noEmit && tsc -p tsconfig.web.json --noEmit",
- "check:registry": "node scripts/check-registry.mjs",
- "check:registry:negative": "node scripts/check-registry.negative.mjs",
- "check:skills": "node scripts/check-skills.mjs",
- "check:skills:negative": "node scripts/check-skills.mjs --self",
- "check:contracts": "python scripts/validate-contracts.py",
- "check:cli": "python runtime/tests/selfcheck.py",
- "check:channel": "python runtime/tests/selfcheck_channel.py",
- "check:channel:negative": "python runtime/tests/selfcheck_channel.py --selftest",
- "check:orchestrator": "python runtime/tests/selfcheck_orchestrator.py",
- "check:orchestrator:negative": "python runtime/tests/selfcheck_orchestrator.py --selftest",
- "check:harness": "python runtime/tests/selfcheck_harness.py",
- "check:harness:negative": "python runtime/tests/selfcheck_harness.py --selftest",
- "check:xlsx": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/check-xlsx.mjs",
- "mms": "python runtime/cli.py",
- "smoke:dist": "node scripts/smoke-dist.mjs",
- "smoke:window": "electron tests/window-smoke.cjs",
- "verify:window": "node scripts/check-window-smoke.mjs",
- "verify:window:selftest": "node scripts/check-window-smoke.mjs --selftest",
- "gate": "npm run check:registry && npm run check:registry:negative && npm run check:skills && npm run check:skills:negative && npm run verify:window:selftest && npm run typecheck && npm run build && npm run smoke:dist && npm run check:contracts && npm run check:cli && npm run check:channel && npm run check:channel:negative && npm run check:orchestrator && npm run check:orchestrator:negative && npm run check:harness && npm run check:harness:negative && npm run check:xlsx && npm run check:workbench && npm run check:paper",
- "check:workbench": "python runtime/tests/selfcheck_workbench.py",
- "check:paper": "python runtime/tests/selfcheck_paper.py"
- },
- "devDependencies": {
- "@types/node": "^26.6.5",
- "@types/react": "^19.3.0",
- "@types/react-dom": "^19.3.0",
- "@vitejs/plugin-react": "^6.1.2",
- "electron": "^44.8.0",
- "electron-builder": "^26.18.0",
- "electron-vite": "^6.0.0",
- "react": "^19.3.1",
- "react-dom": "^19.3.1",
- "typescript": "^7.0.2",
- "vite": "^8.3.4"
- },
- "dependencies": {
- "katex": "^0.19.1",
- "pdfjs-dist": "^6.4.299",
- "react-markdown": "^10.1.0",
- "rehype-katex": "^7.0.1",
- "remark-gfm": "^4.0.1",
- "remark-math": "^6.0.0"
+ "dev": "npm --workspace mathmodel-studio run dev",
+ "build": "npm --workspace mathmodel-studio run build",
+ "preview": "npm --workspace mathmodel-studio run preview",
+ "typecheck": "npm --workspace mathmodel-studio run typecheck",
+ "pack:win": "npm --workspace mathmodel-studio run pack:win",
+ "dist:win": "npm --workspace mathmodel-studio run dist:win",
+ "vendor:python": "npm --workspace mathmodel-studio run vendor:python",
+ "vendor:pandoc": "npm --workspace mathmodel-studio run vendor:pandoc",
+ "smoke:window": "electron desktop/tests/window-smoke.cjs",
+ "mms": "python modeling/cli.py"
}
}
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index ad14d48..0000000
--- a/requirements.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-# mathmodel-studio 的 Python 依赖
-#
-# 版本下限与上游技能 v2.0.1 的 requirements.txt 一致(见 skills/VENDOR.md),
-# 只给下限、不锁死;需要完全可复现的环境时在此基础上自行 pip freeze。
-# 安装(大陆镜像;npmmirror 的 PyPI 代理 2026-10-31 起 404):
-# python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
-
-matplotlib>=3.7 # 数据图表与学术示意图
-numpy>=1.24 # 同上
-seaborn>=0.12 # plot_style.py 与热图模板
-python-docx>=1.1 # mathmodel-paper:Word 版式微调
-# PyMuPDF 2.0 起强依赖 onnxruntime/networkx 等约 170MB 附加包;1.28 起 import fitz 会向
-# stdout 打印弃用警告(会混进技能的 --json 输出)。代码只用 fitz.open 等基础 API。
-PyMuPDF>=1.23,<1.28 # mathmodel-deai:PDF 不可见字符清理
-jsonschema>=4.20 # 契约校验;缺席时降级
diff --git a/runtime/cli.py b/runtime/cli.py
deleted file mode 100644
index a9cf0a8..0000000
--- a/runtime/cli.py
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/usr/bin/env python3
-"""开发期入口:`python runtime/cli.py ...`(或 `npm run mms -- ...`)。
-
-把 `runtime/src` 加进 sys.path 后转调 `mms.cli`,这样在仓库根就能跑,
-不必先 pip install -e,也不必在 Windows 与 bash 之间换 PYTHONPATH 写法。
-"""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-sys.path.insert(0, str(Path(__file__).resolve().parent / "src"))
-
-from mms.cli import main # noqa: E402 (必须先设置 sys.path)
-
-raise SystemExit(main())
diff --git a/runtime/pyproject.toml b/runtime/pyproject.toml
deleted file mode 100644
index 606b4c2..0000000
--- a/runtime/pyproject.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-[project]
-name = "mms-runtime"
-version = "0.2.0"
-description = "mathmodel-studio 的 Agent 运行时:技能注册表读取、阶段编排、provider 适配与产物登记"
-requires-python = ">=3.12"
-license = { text = "AGPL-3.0-only" }
-authors = [{ name = "Escap1ng" }]
-# runtime 本身只依赖标准库:注册表读取与校验在 jsonschema 缺席时降级为内置最小校验。
-# 技能脚本的依赖(matplotlib 等)不装进 runtime 包,统一写在仓库根 requirements.txt。
-dependencies = []
-
-[project.optional-dependencies]
-contracts = ["jsonschema>=4.20"]
-
-[project.scripts]
-mms = "mms.cli:main"
-
-[build-system]
-requires = ["hatchling"]
-build-backend = "hatchling.build"
-
-[tool.hatch.build.targets.wheel]
-packages = ["src/mms"]
-
-# 大陆网络下 pypi 官方直连可用 KB/s 量级,装依赖前先开镜像:
-# [[tool.uv.index]]
-# name = "npmmirror"
-# url = "https://registry.npmmirror.com/pypi/simple/"
-# default = true
-# 见 docs/env-setup.md;镜像可用性本身会翻转,失败先换源再判死。
diff --git a/runtime/src/mms/__init__.py b/runtime/src/mms/__init__.py
deleted file mode 100644
index c6ea7bb..0000000
--- a/runtime/src/mms/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-"""mathmodel-studio 运行时。
-
-版本号与仓库根 VERSION、package.json、pyproject.toml 三处同源,
-由 scripts/validate-contracts.py 在 CI 里钉一致,改一处不改其余就会红。
-"""
-
-__version__ = "0.2.0"
diff --git a/runtime/src/mms/cli.py b/runtime/src/mms/cli.py
deleted file mode 100644
index 67fa5b2..0000000
--- a/runtime/src/mms/cli.py
+++ /dev/null
@@ -1,169 +0,0 @@
-"""`mms` 命令行入口。
-
-退出码沿用上游技能集的 CLI 契约:0 成功 / 1 校验失败 / 2 用法或环境错误。
-三码各自可达由 runtime/tests/selfcheck.py 反向验证。
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from pathlib import Path
-
-from . import __version__
-from .common import utf8_console
-from .invoke import FIGURE_SKILL, invoke, list_templates
-from .registry import (
- EXIT_OK,
- EXIT_USAGE_OR_ENV,
- EXIT_VALIDATION_FAILED,
- EnvError,
- load_manifest,
- minimal_validate,
- repo_root,
- skills,
-)
-
-
-def _schema_problems(manifest: dict) -> tuple[list[str], str]:
- """优先用 jsonschema 校验契约;缺库则降级为内置最小校验。返回 (问题, 用到的方式)。"""
- try:
- import jsonschema # type: ignore
- except ImportError:
- return minimal_validate(manifest), "minimal"
- schema_path = repo_root() / "schemas" / "skill-manifest.schema.json"
- if not schema_path.is_file():
- raise EnvError(f"契约文件不存在: {schema_path}")
- schema = json.loads(schema_path.read_text(encoding="utf-8"))
- validator = jsonschema.Draft202012Validator(schema)
- problems = [
- f"{'/'.join(str(p) for p in e.absolute_path) or ''}: {e.message}"
- for e in sorted(validator.iter_errors(manifest), key=lambda e: list(e.absolute_path))
- ]
- return problems, "jsonschema"
-
-
-def cmd_skills(args: argparse.Namespace) -> int:
- manifest = load_manifest()
- entries = skills(manifest)
-
- if args.check:
- problems, how = _schema_problems(manifest)
- if args.json:
- print(json.dumps({"ok": not problems, "validator": how, "problems": problems}, ensure_ascii=False, indent=2))
- elif problems:
- print(f"注册表校验未通过({len(problems)} 项,判据来源 {how}):", file=sys.stderr)
- for p in problems:
- print(f" - {p}", file=sys.stderr)
- else:
- print(f"注册表校验通过(判据来源 {how},技能 {len(entries)} 个)")
- return EXIT_VALIDATION_FAILED if problems else EXIT_OK
-
- if args.json:
- print(json.dumps(manifest, ensure_ascii=False, indent=2))
- return EXIT_OK
-
- print(f"{manifest['title']} · {len(entries)} 个技能 · manifest {manifest['manifest_version']}")
- for s in entries:
- ui = s["ui"]
- print(
- f" {s['name']:<20} {s['kind']:<10} {s['status']:<9} "
- f"阶段 {','.join(str(p) for p in ui['phases']):<14} 卡点 {','.join(ui['hitl']) or '-'}"
- )
- return EXIT_OK
-
-
-def cmd_templates(args: argparse.Namespace) -> int:
- rows = list_templates()
- if args.json:
- print(json.dumps({"ok": True, "total": len(rows), "templates": rows}, ensure_ascii=False, indent=2))
- return EXIT_OK
- counts: dict[str, int] = {}
- for row in rows:
- counts[row["skill"]] = counts.get(row["skill"], 0) + 1
- summary = " + ".join(f"{name} {n}" for name, n in counts.items())
- print(f"模板 {len(rows)} 个({summary})")
- for row in rows:
- print(f" {row['skill']:<20} {row['id']:<28} {row['title']}")
- return EXIT_OK
-
-
-def cmd_invoke(args: argparse.Namespace) -> int:
- code, result = invoke(
- args.skill,
- args.template,
- Path(args.out) if args.out else None,
- args.theme,
- )
- if args.json:
- print(json.dumps(result, ensure_ascii=False, indent=2))
- return code
- if code == EXIT_OK:
- if result["stdout"].strip():
- print(result["stdout"].rstrip())
- print(f"\n产物目录: {result['out']}")
- for kind, path in result["outputs"].items():
- print(f" {kind.upper():<4} {path}")
- else:
- print(f"渲染失败: {result.get('error')}", file=sys.stderr)
- if result.get("stdout", "").strip():
- print(result["stdout"].rstrip(), file=sys.stderr)
- return code
-
-
-def cmd_serve(args: argparse.Namespace) -> int:
- # 内部命令:stdout 第一行是给父进程的握手 JSON,之后只走本机 HTTP。
- from .server import serve
-
- return serve(args.port)
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(prog="mms", description="mathmodel-studio 运行时入口")
- parser.add_argument("--version", action="version", version=f"mms {__version__}")
- sub = parser.add_subparsers(dest="command", required=True)
-
- p_skills = sub.add_parser("skills", help="列举、校验技能注册表")
- mode = p_skills.add_mutually_exclusive_group()
- mode.add_argument("--check", action="store_true", help="按契约校验注册表(退出码 0/1)")
- mode.add_argument("--json", action="store_true", help="输出整份注册表,供程序读取")
- p_skills.set_defaults(func=cmd_skills)
-
- p_templates = sub.add_parser("templates", help="列举技能内置模板(figure + diagram)")
- p_templates.add_argument("--json", action="store_true", help="输出机器可读清单")
- p_templates.set_defaults(func=cmd_templates)
-
- p_invoke = sub.add_parser("invoke", help="调用技能模板(subprocess,按退出码判定)")
- p_invoke.add_argument("skill", help=f"技能名,M1 支持 figure({FIGURE_SKILL})")
- p_invoke.add_argument("template", help="模板 id / 别名 / 中文图题片段")
- p_invoke.add_argument("--out", default=None, help="工作目录(默认系统临时目录下的 mms-invoke/)")
- p_invoke.add_argument("--theme", default=None, help="主题名或 .theme.json 路径")
- p_invoke.add_argument("--json", action="store_true", help="输出机器可读结果")
- p_invoke.set_defaults(func=cmd_invoke)
-
- p_serve = sub.add_parser("serve", help="启动本机通道服务器(供桌面壳握手,不面向日常使用)")
- p_serve.add_argument("--port", type=int, default=0, help="0 表示让系统分配;只绑 127.0.0.1")
- p_serve.set_defaults(func=cmd_serve)
- return parser
-
-
-def main(argv: list[str] | None = None) -> int:
- utf8_console()
- parser = build_parser()
- args = parser.parse_args(argv)
- try:
- return args.func(args)
- except EnvError as exc:
- print(f"环境或用法错误: {exc}", file=sys.stderr)
- return EXIT_USAGE_OR_ENV
- except FileNotFoundError as exc:
- print(f"环境或用法错误: {exc}", file=sys.stderr)
- return EXIT_USAGE_OR_ENV
- except json.JSONDecodeError as exc:
- print(f"校验失败: 注册表不是合法 JSON — {exc}", file=sys.stderr)
- return EXIT_VALIDATION_FAILED
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/runtime/src/mms/demo_scores.json b/runtime/src/mms/demo_scores.json
deleted file mode 100644
index 1afeeb6..0000000
--- a/runtime/src/mms/demo_scores.json
+++ /dev/null
@@ -1,152 +0,0 @@
-{
- "paper": "第X题_赛题简称",
- "rounds": [
- {
- "round": 1,
- "veto": false,
- "dimensions": [
- {
- "id": "abstract",
- "score": 24,
- "deductions": [
- {"item": "字数超出 800-1000 字范围", "penalty": 4, "note": "摘要约 1150 字", "target": "摘要第 2 段", "suggestion": "删去背景铺陈,把模型、方法、结论压进 800–1000 字。"},
- {"item": "缺少误差/不确定度分析", "penalty": 2, "note": "只有一句定性描述", "target": "摘要末句", "suggestion": "补上验证集误差区间或交叉验证结果。"}
- ]
- },
- {
- "id": "model",
- "score": 16,
- "deductions": [
- {"item": "参数设置无依据", "penalty": 3, "note": "学习率与树深未给来源", "target": "4.2 参数设置", "suggestion": "引用文献建议范围,或给出网格搜索区间与选择依据。"},
- {"item": "缺少灵敏度分析", "penalty": 1, "note": "只跑了单组参数", "target": "4.4 结果分析", "suggestion": "对 2–3 个关键参数做扰动,报告指标变化。"}
- ]
- },
- {
- "id": "innovation",
- "score": 13,
- "deductions": [
- {"item": "创新点缺乏理论支撑", "penalty": 4, "note": "改进算子没有收敛性讨论", "target": "5.1 模型改进", "suggestion": "补一段为什么该改动有效,或给出小规模实验证据。"},
- {"item": "未构建自定义指标", "penalty": 3, "note": "直接复用公开指标", "target": "5.2 评价指标", "suggestion": "结合本题约束新增一个可计算指标,并说明其含义。"}
- ]
- },
- {
- "id": "writing",
- "score": 12,
- "deductions": [
- {"item": "存在空泛表达", "penalty": 2, "note": "“效果较好” 2 处", "target": "6.1 结论", "suggestion": "把“较好”换成具体数值或比较对象。"},
- {"item": "无个性化痕迹", "penalty": 1, "note": "展望没有具体切入点", "target": "7 展望", "suggestion": "写清一个可继续做的具体实验。"}
- ]
- },
- {
- "id": "layout",
- "score": 13,
- "deductions": [
- {"item": "图表编号跳跃或缺失", "penalty": 1, "note": "图 3 缺失", "target": "图 2 与图 4 之间", "suggestion": "重排图号,确保正文引用与图片一致。"},
- {"item": "页眉信息不规范", "penalty": 1, "note": "缺少赛题编号", "target": "页眉", "suggestion": "按竞赛模板补齐页眉字段。"}
- ]
- }
- ]
- },
- {
- "round": 2,
- "veto": false,
- "dimensions": [
- {
- "id": "abstract",
- "score": 26,
- "deductions": [
- {"item": "字数超出 800-1000 字范围", "penalty": 3, "note": "摘要 1120 字", "target": "摘要第 2 段", "suggestion": "再压缩约 150 字。"},
- {"item": "缺少误差/不确定度分析", "penalty": 1, "note": "仅定性提了一句", "target": "摘要末句", "suggestion": "补上交叉验证的误差区间。"}
- ]
- },
- {
- "id": "model",
- "score": 18,
- "deductions": [
- {"item": "参数设置无依据(未引用文献建议范围)", "penalty": 2, "note": "学习率未给依据", "target": "4.2 参数设置", "suggestion": "补一行文献范围与最终取值理由。"}
- ]
- },
- {
- "id": "innovation",
- "score": 15,
- "deductions": [
- {"item": "创新点缺乏理论支撑", "penalty": 3, "note": "改进算子无收敛性讨论", "target": "5.1 模型改进", "suggestion": "补收敛性或小规模对比实验。"},
- {"item": "未构建自定义指标或改进算法", "penalty": 2, "note": "直接复用现有指标", "target": "5.2 评价指标", "suggestion": "新增一个与本题约束对应的指标。"}
- ]
- },
- {
- "id": "writing",
- "score": 13,
- "deductions": [
- {"item": "存在空泛表达(黑名单词)", "penalty": 1, "note": "“较好” 1 处", "target": "6.1 结论", "suggestion": "换成具体数值。"},
- {"item": "无个性化痕迹", "penalty": 1, "note": "展望无具体切入点", "target": "7 展望", "suggestion": "补一个可继续做的实验。"}
- ]
- },
- {
- "id": "layout",
- "score": 14,
- "deductions": [
- {"item": "图表编号跳跃或缺失", "penalty": 1, "note": "图 3 缺失", "target": "图 2 与图 4 之间", "suggestion": "重排图号并核对正文引用。"}
- ]
- }
- ]
- },
- {
- "round": 3,
- "veto": false,
- "dimensions": [
- {
- "id": "abstract",
- "score": 24,
- "deductions": [
- {"item": "字数超出 800-1000 字范围", "penalty": 3, "note": "摘要 1100 字", "target": "摘要第 2 段", "suggestion": "压缩到 1000 字以内。"},
- {"item": "缺少误差/不确定度分析", "penalty": 2, "note": "误差区间仍未给出", "target": "摘要末句", "suggestion": "补验证集误差区间。"},
- {"item": "结论不具体", "penalty": 1, "note": "结论只写“有效”", "target": "摘要末句", "suggestion": "写出提升幅度或适用边界。"}
- ]
- },
- {
- "id": "model",
- "score": 19,
- "deductions": [
- {"item": "参数设置无依据", "penalty": 1, "note": "仍有一处未引用", "target": "4.2 参数设置", "suggestion": "补齐最后一个参数的出处。"}
- ]
- },
- {
- "id": "innovation",
- "score": 14,
- "deductions": [
- {"item": "创新点缺乏理论支撑", "penalty": 3, "note": "收敛性讨论仍缺", "target": "5.1 模型改进", "suggestion": "补一段收敛性或实验证据。"},
- {"item": "未构建自定义指标", "penalty": 3, "note": "自定义指标只写在展望里", "target": "5.2 评价指标", "suggestion": "把指标真正算出来并用于结果表。"}
- ]
- },
- {
- "id": "writing",
- "score": 13,
- "deductions": [
- {"item": "存在空泛表达", "penalty": 1, "note": "“较好” 1 处", "target": "6.1 结论", "suggestion": "换成具体数值。"},
- {"item": "无个性化痕迹", "penalty": 1, "note": "展望仍较泛", "target": "7 展望", "suggestion": "补一个具体实验。"}
- ]
- },
- {
- "id": "layout",
- "score": 14,
- "deductions": [
- {"item": "图表编号跳跃或缺失", "penalty": 1, "note": "图 3 仍缺", "target": "图 2 与图 4 之间", "suggestion": "重排图号。"}
- ]
- }
- ]
- }
- ],
- "veto": {
- "round": 1,
- "veto": true,
- "paper": "第X题_赛题简称(含身份信息)",
- "dimensions": [
- {"id": "abstract", "score": 30, "deductions": []},
- {"id": "model", "score": 20, "deductions": []},
- {"id": "innovation", "score": 20, "deductions": []},
- {"id": "writing", "score": 15, "deductions": []},
- {"id": "layout", "score": 15, "deductions": []}
- ]
- }
-}
diff --git a/runtime/src/mms/harness.py b/runtime/src/mms/harness.py
deleted file mode 100644
index 4e99387..0000000
--- a/runtime/src/mms/harness.py
+++ /dev/null
@@ -1,223 +0,0 @@
-"""会话上下文策略:预算核算、工具结果裁剪、结构化摘要、目标锚点。
-
-参照 DeepSeek Harness 的分层:这些能力挂在 Agent Loop 之外,按需调用。
-压缩顺序是「先无模型裁剪工具结果 → 再把较早的轮次压成结构化摘要 → 最近几轮保留原文」,
-每次压缩都由 server 记成 compaction 事件交给界面显示,可回看。
-"""
-
-from __future__ import annotations
-
-import json
-from dataclasses import dataclass
-
-COMPACT_RATIO = 0.70 # 到预算的这个比例开始压缩
-OVERFLOW_RATIO = 0.45 # provider 报上下文溢出后,用更狠的预算重试一次
-KEEP_RECENT = 6 # 最近几条消息保留原文
-PRUNE_HEAD = 400
-PRUNE_TAIL = 200
-PRUNE_MARK = "\n…[工具结果已裁剪]…\n"
-SUMMARY_MARK = "【较早对话摘要】"
-ANCHOR_MARK = "【会话状态】"
-SUMMARY_ITEM = 120
-MAX_SUMMARY_ITEMS = 12
-MAX_SUMMARY_CHARS = 1600
-OVERFLOW_MARKERS = (
- "context length",
- "context_length",
- "maximum context",
- "too many tokens",
- "reduce the length",
- "context window",
- "input is too long",
- "prompt is too long",
-)
-
-
-def estimate_tokens(text: str) -> int:
- """粗估 token:CJK 按 1 字 1 token,其余按 3.5 字符 1 token。
-
- 只用于上下文预算与「已用」显示,不追求与任何分词器逐 token 对齐;
- 宁可高估,避免把超出窗口的历史送出去。
- """
- cjk = 0
- for ch in text:
- code = ord(ch)
- if 0x2E80 <= code <= 0x9FFF or 0x3000 <= code <= 0x303F or 0xFF00 <= code <= 0xFFEF:
- cjk += 1
- other = max(0, len(text) - cjk)
- return int(cjk + other / 3.5 + 0.999)
-
-
-def message_tokens(message: dict) -> int:
- cost = estimate_tokens(str(message.get("content") or ""))
- calls = message.get("tool_calls")
- if calls:
- cost += estimate_tokens(json.dumps(calls, ensure_ascii=False))
- return cost
-
-
-def usage(messages: list[dict]) -> int:
- return sum(message_tokens(message) for message in messages)
-
-
-def is_anchor(message: dict) -> bool:
- return message.get("role") == "system" and str(message.get("content") or "").startswith(ANCHOR_MARK)
-
-
-def anchor_text(goal: str, turn: int, extra: list[str] | None = None) -> str:
- """每轮重写的一行状态头:会话目标、轮次、工作区等,防止长会话跑偏。"""
- lines = [f"{ANCHOR_MARK}目标:{goal or '未命名'};已进行 {turn} 轮。"]
- for item in extra or []:
- text = str(item or "").strip()
- if text:
- lines.append(f"- {text}")
- return "\n".join(lines)
-
-
-def looks_like_overflow(text: str) -> bool:
- lowered = (text or "").lower()
- return any(marker in lowered for marker in OVERFLOW_MARKERS)
-
-
-@dataclass
-class Plan:
- messages: list[dict]
- before: int
- after: int
- pruned: int = 0
- summarized: int = 0
- dropped: int = 0
- reason: str = ""
- summary: str = ""
-
- def event(self) -> dict:
- return {
- "reason": self.reason,
- "before": self.before,
- "after": self.after,
- "pruned": self.pruned,
- "summarized": self.summarized,
- "dropped": self.dropped,
- "summary": self.summary,
- }
-
-
-def _prune_tool_results(messages: list[dict], protect_tail: int = 2) -> tuple[list[dict], int]:
- positions = [index for index, message in enumerate(messages) if message.get("role") == "tool"]
- protected = set(positions[-protect_tail:]) if protect_tail else set()
- out: list[dict] = []
- pruned = 0
- for index, message in enumerate(messages):
- if message.get("role") == "tool" and index not in protected:
- text = str(message.get("content") or "")
- if len(text) > PRUNE_HEAD + PRUNE_TAIL + len(PRUNE_MARK):
- message = {**message, "content": text[:PRUNE_HEAD] + PRUNE_MARK + text[-PRUNE_TAIL:]}
- pruned += 1
- out.append(message)
- return out, pruned
-
-
-def _summarize(items: list[dict]) -> str:
- """规则摘要:只留开头与最近的少数几条,总长度有上限。
-
- 摘要本身必须比原文小一个量级,否则「压完还超预算」会无限逼近窗口。
- 多轮压缩时旧摘要的条目会被并入,但同样受条数与字数限制。
- """
- header = f"{SUMMARY_MARK}({len(items)} 条较早消息已压缩)"
- chosen = items if len(items) <= MAX_SUMMARY_ITEMS else items[:2] + items[-8:]
- skipped = len(items) - len(chosen)
- lines: list[str] = []
- if skipped > 0:
- lines.append(f"- …中间 {skipped} 条已省略")
- for message in chosen:
- role = message.get("role")
- raw = str(message.get("content") or "")
- if raw.lstrip().startswith(SUMMARY_MARK):
- body = raw[raw.index(SUMMARY_MARK) + len(SUMMARY_MARK) :]
- merged = [line.strip() for line in body.splitlines() if line.strip().startswith("-")]
- lines.extend(merged[:6])
- continue
- content = " ".join(raw.split())
- if role == "tool":
- name = message.get("name") or "工具"
- lines.append(f"- {name}:{content[:SUMMARY_ITEM]}")
- continue
- if role in ("user", "assistant"):
- label = "用户" if role == "user" else "助手"
- if not content:
- calls = message.get("tool_calls") or []
- names = [str((call.get("function") or {}).get("name") or "") for call in calls]
- content = "调用工具:" + "、".join(name for name in names if name)
- lines.append(f"- {label}:{content[:SUMMARY_ITEM]}")
- text = header + "\n" + "\n".join(lines)
- if len(text) > MAX_SUMMARY_CHARS:
- text = text[: MAX_SUMMARY_CHARS - 20] + "\n…[摘要已截断]"
- return text
-
-
-def prepare(
- messages: list[dict],
- budget: int | None = None,
- *,
- anchor: str = "",
- ratio: float = COMPACT_RATIO,
- keep_recent: int = KEEP_RECENT,
- reason: str = "auto",
-) -> Plan:
- """按预算整理一次上下文;没到阈值时只替换锚点,不动历史。"""
- base = [message for message in messages if not is_anchor(message)]
- head = [base[0]] if base and base[0].get("role") == "system" else []
- body = base[len(head) :]
- before = usage(messages)
-
- def assemble(rows: list[dict]) -> list[dict]:
- anchor_rows = [{"role": "system", "content": anchor}] if anchor else []
- return head + anchor_rows + rows
-
- current = body
- pruned = summarized = dropped = 0
- summary_text = ""
- changed = ""
- if budget and budget > 0:
- limit = budget * ratio
- if usage(assemble(current)) > limit:
- current, pruned = _prune_tool_results(current)
- if pruned:
- changed = "tools"
- while usage(assemble(current)) > limit and len(current) > max(2, keep_recent):
- cut = max(1, len(current) - keep_recent)
- older, recent = current[:cut], current[cut:]
- summary_text = _summarize(older)
- merged = [{"role": "system", "content": summary_text}] + recent
- # 只剩摘要本身可压时长度不再变化,再循环也不会更短,直接收手。
- if len(merged) >= len(current):
- break
- current = merged
- summarized += cut
- changed = "summary"
- # 最后手段:摘要后仍超预算(历史很短但单条很大)就从最早处丢;
- # 开头不能是 assistant / tool,最后一条用户消息永远保留。
- while usage(assemble(current)) > limit and len(current) > 1:
- first = current.pop(0)
- dropped += 1
- if first.get("tool_calls"):
- while current and current[0].get("role") == "tool":
- current.pop(0)
- dropped += 1
- while len(current) > 1 and current[0].get("role") not in ("user", "system"):
- current.pop(0)
- dropped += 1
- if dropped:
- changed = "trim"
-
- result = assemble(current)
- return Plan(
- messages=result,
- before=before,
- after=usage(result),
- pruned=pruned,
- summarized=summarized,
- dropped=dropped,
- reason=changed if reason else changed,
- summary=summary_text,
- )
diff --git a/runtime/src/mms/invoke.py b/runtime/src/mms/invoke.py
deleted file mode 100644
index d2c81f1..0000000
--- a/runtime/src/mms/invoke.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""`mms templates` 与 `mms invoke` 的实现。
-
-契约边界:本模块**不 import 任何技能内部函数**,只把技能脚本当外部程序调用,
-按退出码判定,并在成功退出后独立核验产物是否真的落盘。这样上游升级不会
-把桌面端代码和技能实现绑死(见 skills/VENDOR.md 第 4 条)。
-"""
-
-from __future__ import annotations
-
-import importlib.util
-import json
-import os
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-from .registry import (
- EXIT_OK,
- EXIT_USAGE_OR_ENV,
- EXIT_VALIDATION_FAILED,
- EnvError,
- repo_root,
-)
-
-FIGURE_SKILL = "mathmodel-figure"
-FIGURE_DIR = Path("skills") / FIGURE_SKILL
-FIGURE_RENDERER = FIGURE_DIR / "code" / "tools" / "render_template.py"
-FIGURE_MANIFEST = FIGURE_DIR / "code" / "tools" / "manifest.json"
-DIAGRAM_MANIFEST = Path("skills") / "mathmodel-diagram" / "code" / "templates" / "manifest.json"
-
-FIGURE_DEPS = ("matplotlib", "numpy", "seaborn")
-
-# 命令行用短名(文档与验收口径写的是 `mms invoke figure ...`),注册表里是全名。
-SKILL_ALIASES = {"figure": FIGURE_SKILL, FIGURE_SKILL: FIGURE_SKILL}
-
-
-def _load_json(path: Path, label: str) -> dict:
- if not path.is_file():
- raise EnvError(f"{label}不存在: {path}(技能是否已 vendor?)")
- try:
- return json.loads(path.read_text(encoding="utf-8"))
- except json.JSONDecodeError as exc:
- raise EnvError(f"{label}不是合法 JSON: {path} — {exc}") from exc
-
-
-def list_templates(root: Path | None = None) -> list[dict]:
- """返回两个技能注册表里登记的全部模板(M1 时是 20 + 5)。"""
- root = root or repo_root()
- rows: list[dict] = []
- figure = _load_json(root / FIGURE_MANIFEST, "图表模板注册表")
- for entry in figure.get("templates", []):
- rows.append(
- {
- "skill": FIGURE_SKILL,
- "id": entry.get("id"),
- "title": entry.get("title"),
- "group": entry.get("group", "figure"),
- }
- )
- diagram = _load_json(root / DIAGRAM_MANIFEST, "示意图模板注册表")
- for entry in diagram.get("templates", []):
- rows.append(
- {
- "skill": "mathmodel-diagram",
- "id": entry.get("id"),
- "title": entry.get("title"),
- "group": "diagram",
- }
- )
- return rows
-
-
-def _missing_deps() -> list[str]:
- return [name for name in FIGURE_DEPS if importlib.util.find_spec(name) is None]
-
-
-def _default_out(skill: str, template: str) -> Path:
- return Path(tempfile.gettempdir()) / "mms-invoke" / f"{skill}-{template}"
-
-
-def _collect_artifacts(out_dir: Path) -> dict[str, str]:
- outputs = out_dir / "outputs"
- found: dict[str, str] = {}
- for suffix in (".png", ".pdf", ".svg"):
- candidates = sorted(p for p in outputs.glob(f"*{suffix}") if p.is_file() and p.stat().st_size > 0)
- if candidates:
- found[suffix.lstrip(".")] = str(candidates[0])
- return found
-
-
-def invoke(
- skill: str,
- template: str,
- out_dir: Path | None = None,
- theme: str | None = None,
- root: Path | None = None,
-) -> tuple[int, dict]:
- """调用一个技能模板。返回 (退出码, 机器可读结果)。"""
- root = root or repo_root()
- raw_skill = skill
- skill = SKILL_ALIASES.get(skill.strip().lower())
- if not skill:
- raise EnvError(f"M1 只接通了 figure({FIGURE_SKILL}),暂不支持: {raw_skill}")
-
- renderer = root / FIGURE_RENDERER
- if not renderer.is_file():
- raise EnvError(f"找不到上游渲染器: {renderer}(技能是否已 vendor?)")
-
- missing = _missing_deps()
- if missing:
- raise EnvError(
- "缺少 Python 依赖: "
- + ", ".join(missing)
- + ";先执行 python -m pip install -r requirements.txt(国内镜像见 docs/env-setup.md)"
- )
-
- out_dir = (out_dir or _default_out(skill, template)).expanduser().resolve()
- out_dir.mkdir(parents=True, exist_ok=True)
-
- cmd = [
- sys.executable,
- str(renderer),
- template,
- "--project",
- str(out_dir),
- "--overwrite",
- "--lang",
- "en",
- ]
- if theme:
- cmd += ["--theme", theme]
-
- env = dict(os.environ)
- env["PYTHONIOENCODING"] = "utf-8"
- env["PYTHONUTF8"] = "1"
- env.setdefault("MPLCONFIGDIR", str(out_dir / ".mplconfig"))
-
- try:
- proc = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- env=env,
- timeout=300,
- check=False,
- )
- except subprocess.TimeoutExpired as exc:
- raise EnvError(f"渲染超时(300s): {template}") from exc
-
- result: dict = {
- "ok": False,
- "skill": skill,
- "template": template,
- "out": str(out_dir),
- "exit": proc.returncode,
- "stdout": proc.stdout,
- "stderr": proc.stderr,
- "outputs": {},
- }
-
- if proc.returncode != 0:
- # 上游契约:1 = 校验或渲染失败,2 = 用法或环境错误,原样透传。
- result["error"] = proc.stderr.strip() or proc.stdout.strip() or f"渲染器退出 {proc.returncode}"
- return (EXIT_USAGE_OR_ENV if proc.returncode == 2 else EXIT_VALIDATION_FAILED), result
-
- artifacts = _collect_artifacts(out_dir)
- missing_kinds = [k for k in ("png", "pdf", "svg") if k not in artifacts]
- if missing_kinds:
- # 渲染器说成功但产物没落盘:按校验失败处理,而不是相信退出码。
- result["error"] = f"渲染器退出 0,但缺少产物: {', '.join(missing_kinds)}(目录 {out_dir / 'outputs'})"
- return EXIT_VALIDATION_FAILED, result
-
- result["ok"] = True
- result["outputs"] = artifacts
- return EXIT_OK, result
diff --git a/runtime/src/mms/orchestrator.py b/runtime/src/mms/orchestrator.py
deleted file mode 100644
index b1ff28d..0000000
--- a/runtime/src/mms/orchestrator.py
+++ /dev/null
@@ -1,1605 +0,0 @@
-"""编排状态机:起题 → K2 确认 → K3 选模 → 阶段四真跑一次基线。
-
-K2/K3 的内容生产优先走 LLM(llm.complete_json):题面拆解与候选路线由模型
-按本题给出;没有 Key、模型不可用或输出两次不合法时,回退确定性的正则切分与
-内置方法族,并在卡片上标明是离线兜底。阶段四定位工作区数据、生成脚本、
-真跑一遍并把图登记成图表版本,进度用工具卡逐条报到界面上。
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import re
-import shutil
-import time
-from collections.abc import Callable, Iterator
-from pathlib import Path
-
-from . import (
- baseline,
- llm,
- paper_build,
- paper_gen,
- project_export,
- score_gen,
- workbench_figure,
- workbench_score,
-)
-from .store import SessionStore, session_scope
-
-PHASE_INTRO = "已收到题目。先按小节把题面拆开;确认题面后再进入算法选择。"
-
-K2_INSTRUCTION = (
- "你是数学建模竞赛的题面分析助手。把用户给出的赛题拆成子问题,并核对附件的数据角色。"
- "只输出一个 JSON 对象,不要围栏、不要解释,形状:"
- '{"questions":[{"id":"q1","text":"子问题描述","data":"所需数据说明"}],'
- '"dataRoles":[{"file":"文件名","role":"训练集/预测集/共用","note":"判断依据"}],'
- '"warning":"数据缺口或风险提醒"}。'
- "questions 最多 6 条,text 忠实于题面、不改写原意;data 写明该问需要哪份数据,"
- "题面没给数据就写「未附数据文件」;dataRoles 只在附件正文足够判断时给出,"
- "判断依据看目标列是否为空、行数与时间范围,不靠文件名猜。"
-)
-
-K3_INSTRUCTION = (
- "你是数学建模竞赛的方法选型助手。针对题面给出恰好 3 条候选路线,其中至少 1 条具备明显创新性。"
- "只输出一个 JSON 对象,不要围栏、不要解释,形状:"
- '{"candidates":[{"name":"方法名","idea":"核心思路","innovation":"高/中/低",'
- '"interpretability":"高/中/低","difficulty":"高/中/低","eta":"预计耗时(按本题数据规模给量级)",'
- '"accuracy":"精度与鲁棒性预期","math":"数学形式","fit":"为何适配本题","diff":"与未选方案的差异",'
- '"verify":"验证方式","recommended":true,"reason":"一句推荐理由"}]}。'
- "恰好一条 recommended 为 true;评估基于本题的数据规模与约束,不夸大创新度、不低估难度;"
- "换一批时给出与上一批不同的路线。"
-)
-
-SELECTION_GUIDE_EXCERPT = (
- "选型原则(mathmodel-methods · selection-guide 节选):拟合性优先于高级性;"
- "能用初等方法解决的不用高等方法;创新落点明确(建模/求解/结果/推广其一),"
- "须回答解决了旧方法解决不了的什么问题;验证手段与问题类型匹配。"
- "问题特征参考:时序预测→ARIMA/Prophet/LSTM,小样本 GM(1,1);评价排序→熵权-TOPSIS/AHP;"
- "0-1 变量→整数规划+遗传算法;机理演化→微分方程组+RK4+敏感性分析;"
- "路径配送→TSP/VRP+GA/蚁群;插值补全→三次样条。"
-)
-
-_CANDIDATE_TEXT_FIELDS = ("name", "idea", "innovation", "interpretability", "difficulty", "eta", "accuracy")
-_CANDIDATE_EXPLAIN_FIELDS = ("math", "fit", "diff", "verify")
-
-FAMILIES = [
- (
- ("预测", "回归", "销量", "价格", "需求", "增长", "估计"),
- [
- {
- "name": "梯度提升回归",
- "idea": "用滞后项、窗口统计与外部变量喂给树模型,直接拟合连续目标。",
- "innovation": "中",
- "interpretability": "中",
- "difficulty": "中",
- "eta": "2–4 小时",
- "accuracy": "中高",
- "math": "ŷ = Σ f_k(x),f_k 为逐步拟合残差的回归树;用早停与交叉验证选轮数。",
- "fit": "样本量中等、特征以结构化数据为主时,先得到一个强基线,再谈复杂机制。",
- "diff": "比 SARIMAX 更不依赖平稳性假设,但外推能力弱于机制模型。",
- "verify": "按时间切分训练/验证,报告 RMSE 与残差自相关。",
- },
- {
- "name": "SARIMAX 时间序列",
- "idea": "把趋势、季节项与外生变量放进同一个线性状态结构。",
- "innovation": "低",
- "interpretability": "高",
- "difficulty": "中",
- "eta": "1–3 小时",
- "accuracy": "中",
- "math": "φ(B)(1−B)^d y_t = θ(B) ε_t + β x_t,B 为滞后算子。",
- "fit": "目标按固定频率采样、样本跨度足够长时,系数可直接解释。",
- "diff": "可解释性高于树模型,但对缺失值与结构突变敏感。",
- "verify": "ADF 检验平稳性,Ljung-Box 检查残差白噪声。",
- },
- {
- "name": "高斯过程回归",
- "idea": "用核函数描述样本间相关性,同时给出预测区间。",
- "innovation": "高",
- "interpretability": "中",
- "difficulty": "高",
- "eta": "3–5 小时",
- "accuracy": "中高",
- "math": "f ~ GP(m(x), k(x,x')),后验均值与方差由核矩阵闭式给出。",
- "fit": "小样本、需要不确定性区间时最合适;样本上万后核矩阵代价明显。",
- "diff": "比树模型多给方差,但调核与数值稳定性更费时间。",
- "verify": "留出集覆盖率检查预测区间是否兑现。",
- },
- ],
- ),
- (
- ("分类", "识别", "判别", "检测", "标签"),
- [
- {
- "name": "LightGBM 分类",
- "idea": "直方图分裂的梯度提升树,处理混合类型特征与类别不平衡。",
- "innovation": "中",
- "interpretability": "中",
- "difficulty": "中",
- "eta": "1–3 小时",
- "accuracy": "高",
- "math": "在每轮拟合负梯度,按叶节点输出类概率;用 scale_pos_weight 处理不平衡。",
- "fit": "结构化特征、样本量从几千到几十万都稳,先看特征重要度。",
- "diff": "精度通常高于线性基线,代价是系数不可直接解释。",
- "verify": "分层交叉验证,报告 AUC、召回与混淆矩阵。",
- },
- {
- "name": "正则化逻辑回归",
- "idea": "在线性决策边界上加 L1/L2 约束,给出可读的系数方向。",
- "innovation": "低",
- "interpretability": "高",
- "difficulty": "低",
- "eta": "0.5–1.5 小时",
- "accuracy": "中",
- "math": "P(y=1|x)=σ(wᵀx+b),最小化对数损失 + λ‖w‖。",
- "fit": "特征维度可控、需要解释每个变量方向时优先。",
- "diff": "比树模型透明,但漏掉交互项时精度会明显落后。",
- "verify": "检查 VIF 与系数稳定性,报告校准曲线。",
- },
- {
- "name": "半监督标签传播",
- "idea": "用少量标注样本与大量未标注样本的相似图扩散标签。",
- "innovation": "高",
- "interpretability": "低",
- "difficulty": "高",
- "eta": "3–6 小时",
- "accuracy": "中",
- "math": "在相似度图上最小化 Σ w_ij‖f_i−f_j‖²,固定已标注点求解。",
- "fit": "标注稀缺但未标注样本充足时值得试,否则不如监督模型。",
- "diff": "能利用未标注数据,但图构建与阈值选择会显著影响结果。",
- "verify": "只用标注集做最终评估,另设人工抽查未标注伪标签。",
- },
- ],
- ),
- (
- ("优化", "调度", "分配", "路径", "选址", "排班", "规划"),
- [
- {
- "name": "混合整数线性规划",
- "idea": "把决策写成 0-1 与连续变量,目标与约束全部线性化。",
- "innovation": "中",
- "interpretability": "高",
- "difficulty": "中",
- "eta": "2–5 小时",
- "accuracy": "高",
- "math": "min cᵀx s.t. Ax ≤ b, x_i∈{0,1}(部分分量)。",
- "fit": "约束能写成线性、规模在求解器可承受范围时,给出可证明的最优界。",
- "diff": "比启发式慢,但结果可复核;非线性约束需要先线性化。",
- "verify": "检查求解状态与对偶界,扰动关键参数做敏感性分析。",
- },
- {
- "name": "遗传算法",
- "idea": "用编码、交叉与变异在非凸空间里搜索可行解。",
- "innovation": "中",
- "interpretability": "低",
- "difficulty": "中",
- "eta": "2–4 小时",
- "accuracy": "中",
- "math": "每代保留适应度高的个体,按选择概率重组并变异。",
- "fit": "目标非凸、约束难线性化时可用;需要固定随机种子才能复现。",
- "diff": "比 MILP 灵活,但没有最优性保证,调参成本高。",
- "verify": "多次独立运行看解的方差,并与贪心基线比较。",
- },
- {
- "name": "鲁棒优化",
- "idea": "把参数的不确定集写进约束,求最坏情况下的可行方案。",
- "innovation": "高",
- "interpretability": "中",
- "difficulty": "高",
- "eta": "4–6 小时",
- "accuracy": "中高",
- "math": "min cᵀx s.t. a(ξ)ᵀx ≤ b ∀ξ∈U,U 为盒式或椭球不确定集。",
- "fit": "需求或价格波动明显、方案不能事后补救时最有价值。",
- "diff": "比确定性模型保守,但能回答「参数偏多少会失效」。",
- "verify": "在不确定集边界采样,检查约束违反率与目标退化幅度。",
- },
- ],
- ),
- (
- ("评价", "指标", "权重", "排名", "综合", "评分"),
- [
- {
- "name": "熵权-TOPSIS",
- "idea": "用样本离散度定权,再按与理想解的距离排序。",
- "innovation": "中",
- "interpretability": "高",
- "difficulty": "低",
- "eta": "1–2 小时",
- "accuracy": "中",
- "math": "熵权 w_j ∝ 1−e_j;贴近度 C_i = d_i⁻/(d_i⁺+d_i⁻)。",
- "fit": "指标方向一致、样本量足够形成分布时,权重完全由数据决定。",
- "diff": "比 AHP 少主观性,但样本太少时熵权不稳定。",
- "verify": "对指标做正负向归一化,换权重方案检查排序是否翻转。",
- },
- {
- "name": "AHP-模糊综合评价",
- "idea": "用成对比较矩阵取权重,再用隶属度合成评价等级。",
- "innovation": "低",
- "interpretability": "高",
- "difficulty": "中",
- "eta": "1.5–3 小时",
- "accuracy": "中",
- "math": "判断矩阵最大特征向量作权重;B = W∘R 合成隶属度。",
- "fit": "指标难以量化、需要专家判断时可用,但要报告一致性比率。",
- "diff": "比熵权更能纳入领域知识,主观性也更高。",
- "verify": "CR < 0.1;更换专家矩阵做敏感性分析。",
- },
- {
- "name": "可解释加权评分",
- "idea": "把分项得分与权重写成显式公式,逐项可追溯。",
- "innovation": "高",
- "interpretability": "高",
- "difficulty": "低",
- "eta": "1–2 小时",
- "accuracy": "中",
- "math": "S = Σ w_j · s_j,s_j 为归一化分项,w_j 由约束或专家给定。",
- "fit": "评审需要看懂每一分从哪来时,比黑箱排序更合适。",
- "diff": "透明但依赖权重设定;可与熵权结果交叉验证。",
- "verify": "逐项回算总分,检查权重和为 1 与极端样本。",
- },
- ],
- ),
- (
- ("传播", "扩散", "动力学", "微分", "传染病", "演化"),
- [
- {
- "name": "常微分方程参数反演",
- "idea": "先写机制方程,再用观测数据拟合关键速率参数。",
- "innovation": "中",
- "interpretability": "高",
- "difficulty": "中",
- "eta": "3–5 小时",
- "accuracy": "中高",
- "math": "dx/dt = f(x,θ),最小化 Σ‖x(t_i;θ)−y_i‖²。",
- "fit": "变量少、机制清楚时最稳;参数不可辨识要先做结构分析。",
- "diff": "比纯数据驱动更能外推,但模型设定错会系统性偏差。",
- "verify": "多初值拟合,检查参数置信区间与残差结构。",
- },
- {
- "name": "元胞自动机",
- "idea": "把空间划成网格,用局部更新规则模拟扩散与聚集。",
- "innovation": "中",
- "interpretability": "中",
- "difficulty": "中",
- "eta": "2–4 小时",
- "accuracy": "中",
- "math": "x_i(t+1)=F(x_i(t), N(i)),N(i) 为邻域状态。",
- "fit": "空间异质性与局部交互明显、连续方程难写时可用。",
- "diff": "比 ODE 灵活,但规则与网格尺度会改变结论,需要做收敛检查。",
- "verify": "缩小网格与时间步,确认宏观指标收敛。",
- },
- {
- "name": "贝叶斯层次模型",
- "idea": "给参数加先验并共享组间信息,输出后验区间。",
- "innovation": "高",
- "interpretability": "中",
- "difficulty": "高",
- "eta": "4–7 小时",
- "accuracy": "中高",
- "math": "θ_g ~ p(θ|φ),y_g ~ p(y|θ_g),对 φ 与 θ_g 联合求后验。",
- "fit": "分组样本量不均、需要量化不确定性时最有价值。",
- "diff": "比点估计多给区间,但采样诊断与先验选择成本高。",
- "verify": "检查 R̂ 与有效样本量,做先验敏感性分析。",
- },
- ],
- ),
-]
-
-DEFAULT_FAMILY = [
- {
- "name": "梯度提升树",
- "idea": "先用结构化特征建立非线性基线,量化可提升空间。",
- "innovation": "低",
- "interpretability": "中",
- "difficulty": "低",
- "eta": "1–2 小时",
- "accuracy": "中高",
- "math": "ŷ = Σ f_k(x),逐轮拟合残差。",
- "fit": "题面尚未暴露明确机制时,先拿到可复现的基线。",
- "diff": "比机制模型省时,但外推与解释较弱。",
- "verify": "交叉验证并报告特征重要度。",
- },
- {
- "name": "多元回归 + 正则化",
- "idea": "用显式变量与约束项给出可解释的基线。",
- "innovation": "低",
- "interpretability": "高",
- "difficulty": "低",
- "eta": "1–2 小时",
- "accuracy": "中",
- "math": "min ‖y−Xβ‖² + λ‖β‖。",
- "fit": "变量关系近似线性、需要逐项解释时优先。",
- "diff": "比树模型透明,交互项需要手工构造。",
- "verify": "残差诊断与系数稳定性检查。",
- },
- {
- "name": "机制模型 + 数据校准",
- "idea": "先写守恒或平衡关系,再用数据校准少量参数。",
- "innovation": "高",
- "interpretability": "高",
- "difficulty": "高",
- "eta": "3–6 小时",
- "accuracy": "中高",
- "math": "由守恒关系给出 f(x,θ)=0,再最小化观测残差。",
- "fit": "题面给了明确机制或约束时,比纯拟合更可信。",
- "diff": "可外推、可解释,但建模与校准都更费时间。",
- "verify": "参数敏感性分析与留出年份回测。",
- },
-]
-
-
-def _family_for(problem: str):
- for keywords, pool in FAMILIES:
- if any(k in problem for k in keywords):
- return pool
- return DEFAULT_FAMILY
-
-
-def split_questions(problem: str) -> list[str]:
- text = problem.strip()
- if not text:
- return []
- pattern = r"(?=(?:问题\s*[一二三四五六七八九十0-9]+|(\s*[0-9]+\s*)|\(\s*[0-9]+\s*\)))"
- parts = [p.strip() for p in re.split(pattern, text) if p.strip()]
- if len(parts) < 2:
- parts = [line.strip() for line in text.splitlines() if line.strip()][:3] or [text]
- return [p[:180] for p in parts[:6]]
-
-
-# 渲染层把附件正文包在这对标记里送进来;题目切分只用标记外的手打文字。
-ATTACH_START = "--- 附件(本机文件)---"
-ATTACH_END = "--- 附件结束 ---"
-
-
-def _attachment_region(problem: str) -> str:
- start = problem.find(ATTACH_START)
- if start < 0:
- return ""
- end = problem.find(ATTACH_END, start + len(ATTACH_START))
- begin = start + len(ATTACH_START)
- return problem[begin:] if end < 0 else problem[begin:end]
-
-
-def attachment_names(problem: str) -> list[str]:
- names: list[str] = []
- for line in _attachment_region(problem).splitlines():
- line = line.strip()
- if not line.startswith("### "):
- continue
- name = line[4:].split(" · ", 1)[0].strip()
- if name and name not in names:
- names.append(name)
- return names
-
-
-def strip_attachments(problem: str) -> str:
- start = problem.find(ATTACH_START)
- if start < 0:
- return problem.strip()
- end = problem.find(ATTACH_END, start + len(ATTACH_START))
- head = problem[:start].strip()
- tail = "" if end < 0 else problem[end + len(ATTACH_END):].strip()
- return (head + ("\n" + tail if tail else "")).strip()
-
-
-def question_source(problem: str) -> str:
- # 只拖了文件、没手打题面时,题面就在附件正文里;此时用正文切子问题。
- typed = strip_attachments(problem)
- if typed:
- return typed
- body = _attachment_region(problem)
- return "\n".join(line for line in body.splitlines() if not line.strip().startswith("### ")).strip()
-
-
-def phase_event(num: int, status: str, note: str = "") -> dict:
- data = {"phase": num, "status": status}
- if note:
- data["note"] = note
- return {"event": "phase", "data": data}
-
-
-def set_phase(record: dict, num: int, status: str) -> None:
- for row in record["phases"]:
- if row["phase"] == num:
- row["status"] = status
-
-
-def _last_assistant(record: dict) -> dict | None:
- for message in reversed(record["messages"]):
- if message.get("role") == "assistant":
- return message
- return None
-
-
-def _resolve_interrupt(record: dict, label: str) -> None:
- message = _last_assistant(record)
- if message and message.get("interrupt"):
- message["interrupt"]["resolved"] = label
-
-
-def _problem_payload(problem: str) -> dict:
- names = attachment_names(problem)
- questions = split_questions(question_source(problem))
- intro = (
- f"按题面切出 {len(questions)} 个子问题,收到 {len(names)} 个附件;附件正文已并入题面。"
- if names
- else f"按题面切出 {len(questions)} 个子问题。附件核对需要真实文件,这一步先标出缺口。"
- )
- return {
- "title": "赛题与附件确认",
- "intro": intro,
- "questions": [
- {"id": f"q{i + 1}", "text": text, "data": "未附数据文件"}
- for i, text in enumerate(questions)
- ],
- "attachments": [{"id": f"a{i + 1}", "name": name} for i, name in enumerate(names)],
- "dataRoles": [],
- "warning": (
- "附件正文已随题面送入;数据角色核对(目标列是否为空、行数、时间范围)尚未接入。"
- if names
- else "未附数据文件:数据角色核对需要真实表格。确认后按文字题面继续。"
- ),
- }
-
-
-def _candidates(problem: str, batch: int) -> list[dict]:
- pool = _family_for(problem)
- start = (batch - 1) % len(pool)
- picked = [pool[(start + i) % len(pool)] for i in range(3)]
- out = []
- for index, base in enumerate(picked):
- item = dict(base)
- item["id"] = f"c{index + 1}"
- item["recommended"] = index == 0
- item["reason"] = (
- "先跑通这条基线的代价最低,结果可直接对照后续模型。"
- if index == 0
- else "作为对照,用来检验推荐方案的优势是否真实存在。"
- )
- item["explain"] = {
- "math": item.pop("math"),
- "fit": item.pop("fit"),
- "diff": item.pop("diff"),
- "verify": item.pop("verify"),
- "eta": item["eta"],
- "source": "mathmodel-methods · selection-guide(M3 内置节选)",
- }
- out.append(item)
- return out
-
-
-def _model_payload(problem: str, batch: int) -> dict:
- return {
- "title": "算法选择",
- "intro": "以下是同题的三条路线。先看差异,再选一条进入代码实现。",
- "batch": batch,
- "candidates": _candidates(problem, batch),
- }
-
-
-def model_candidates(problem: str, batch: int = 1) -> list[dict]:
- """对话式选模卡与全流程编排共用同一份候选,避免两套口径。"""
- return _candidates(problem, batch)
-
-
-def _validate_problem(data: dict) -> dict:
- questions = data.get("questions")
- if not isinstance(questions, list) or not questions:
- raise ValueError("questions 必须是非空数组")
- rows: list[dict] = []
- for index, item in enumerate(questions[:6]):
- if not isinstance(item, dict) or not str(item.get("text") or "").strip():
- raise ValueError("每个子问题必须有 text")
- rows.append(
- {
- "id": str(item.get("id") or f"q{index + 1}"),
- "text": str(item["text"]).strip()[:300],
- "data": str(item.get("data") or "未附数据文件").strip()[:120],
- }
- )
- roles: list[dict] = []
- for item in data.get("dataRoles") or []:
- if isinstance(item, dict) and str(item.get("file") or "").strip():
- roles.append(
- {
- "file": str(item["file"]).strip()[:120],
- "role": str(item.get("role") or "").strip()[:40],
- "note": str(item.get("note") or "").strip()[:200],
- }
- )
- return {
- "questions": rows,
- "dataRoles": roles,
- "warning": str(data.get("warning") or "").strip()[:300],
- }
-
-
-def _problem_payload_llm(
- problem: str,
- provider: dict | None,
- api_key: str,
- model: str,
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> dict:
- """K2:LLM 拆子问题并核对数据角色;失败回退正则切分并标明兜底。"""
- base = _problem_payload(problem)
- if not provider:
- return base
- user = (
- f"题面:\n{question_source(problem)}\n\n"
- f"附件清单:{'、'.join(attachment_names(problem)) or '无'}\n\n"
- f"附件正文(节选):\n{_attachment_region(problem)[:6000] or '无'}"
- )
- try:
- parsed = llm.complete_json(
- provider, api_key, model, "k2-problem", K2_INSTRUCTION, user, _validate_problem,
- should_stop=should_stop, on_delta=on_delta,
- )
- except llm.LlmError:
- base["warning"] = (base["warning"] + "(模型不可用,已回退按小节切分)").strip()
- return base
- names = attachment_names(problem)
- count = len(parsed["questions"])
- intro = (
- f"模型拆出 {count} 个子问题,收到 {len(names)} 个附件;请核对数据角色后确认。"
- if names
- else f"模型拆出 {count} 个子问题。未附数据文件,确认后按文字题面继续。"
- )
- return {
- "title": "赛题与附件确认",
- "intro": intro,
- "questions": parsed["questions"],
- "attachments": base["attachments"],
- "dataRoles": parsed["dataRoles"],
- "warning": parsed["warning"] or base["warning"],
- }
-
-
-def _validate_candidates(data: dict) -> dict:
- candidates = data.get("candidates")
- if not isinstance(candidates, list) or len(candidates) != 3:
- raise ValueError("candidates 必须恰好 3 条")
- rows: list[dict] = []
- recommended_count = 0
- for index, item in enumerate(candidates):
- if not isinstance(item, dict):
- raise ValueError("候选必须是对象")
- row: dict = {"id": f"c{index + 1}"}
- for field in _CANDIDATE_TEXT_FIELDS:
- value = str(item.get(field) or "").strip()
- if not value:
- raise ValueError(f"候选缺少字段 {field}")
- row[field] = value[:300]
- explain: dict = {}
- for field in _CANDIDATE_EXPLAIN_FIELDS:
- value = str(item.get(field) or "").strip()
- if not value:
- raise ValueError(f"候选缺少解释字段 {field}")
- explain[field] = value[:500]
- explain["eta"] = row["eta"]
- explain["source"] = "模型判断(参考 mathmodel-methods · selection-guide)"
- row["explain"] = explain
- row["recommended"] = item.get("recommended") is True
- recommended_count += int(row["recommended"])
- row["reason"] = str(item.get("reason") or "").strip()[:200]
- rows.append(row)
- if recommended_count != 1:
- raise ValueError("必须恰好一条推荐候选")
- if not any(row["innovation"] == "高" for row in rows):
- raise ValueError("至少一条候选的创新度必须为高")
- return {"candidates": rows}
-
-
-def _model_payload_llm(
- problem: str,
- batch: int,
- provider: dict | None,
- api_key: str,
- model: str,
- previous: list[str] | None = None,
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> dict:
- """K3:LLM 按题出候选;失败回退内置方法族并标明兜底。"""
- if not provider:
- return _model_payload(problem, batch)
- user = (
- f"题面:\n{question_source(problem)}\n\n"
- f"附件清单:{'、'.join(attachment_names(problem)) or '无'}\n\n"
- f"{SELECTION_GUIDE_EXCERPT}"
- )
- if previous:
- user += f"\n\n上一批候选(换一批时不要重复):{'、'.join(previous)}"
- try:
- parsed = llm.complete_json(
- provider, api_key, model, "k3-models", K3_INSTRUCTION, user, _validate_candidates,
- should_stop=should_stop, on_delta=on_delta,
- )
- except llm.LlmError:
- payload = _model_payload(problem, batch)
- payload["intro"] = "模型不可用,以下候选来自内置方法族(离线兜底)。先看差异,再选一条。"
- return payload
- return {
- "title": "算法选择",
- "intro": "以下是模型按本题给出的三条路线。先看差异,再选一条进入代码实现。",
- "batch": batch,
- "candidates": parsed["candidates"],
- }
-
-
-def start(
- store: SessionStore,
- record: dict,
- provider: dict | None = None,
- api_key: str = "",
- model: str = "",
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> list[dict]:
- payload = _problem_payload_llm(
- record["problem"], provider, api_key, model or record.get("model") or "",
- should_stop=should_stop, on_delta=on_delta,
- )
- set_phase(record, 0, "passed")
- set_phase(record, 1, "waiting")
- record["messages"].append({"role": "user", "content": record["problem"]})
- record["messages"].append(
- {
- "role": "assistant",
- "content": PHASE_INTRO,
- "interrupt": {"card": "problem-confirm", "payload": payload},
- }
- )
- record["pending"] = {"card": "problem-confirm", "payload": payload}
- store.put(record)
- return [
- phase_event(0, "passed", "runtime 环境就绪(xelatex/pandoc 等外部依赖未检)"),
- phase_event(1, "running"),
- {"event": "token", "data": {"text": PHASE_INTRO}},
- phase_event(1, "waiting"),
- {"event": "interrupt", "data": record["pending"]},
- ]
-
-
-def resume(
- store: SessionStore,
- record: dict,
- action: str,
- choice: str,
- workspace: str = "",
- provider: dict | None = None,
- api_key: str = "",
- model: str = "",
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> list[dict]:
- return list(
- resume_iter(
- store, record, action, choice, workspace,
- provider=provider, api_key=api_key, model=model,
- should_stop=should_stop, on_delta=on_delta,
- )
- )
-
-
-def resume_iter(
- store: SessionStore,
- record: dict,
- action: str,
- choice: str,
- workspace: str = "",
- provider: dict | None = None,
- api_key: str = "",
- model: str = "",
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> Iterator[dict]:
- pending = record["pending"]
- if not pending:
- raise ValueError("这个会话没有等待中的决策")
- card = pending.get("card")
- model = model or record.get("model") or ""
-
- if action == "confirm":
- if card != "problem-confirm":
- raise ValueError("当前不是在确认赛题")
- _resolve_interrupt(record, "已确认")
- set_phase(record, 1, "passed")
- set_phase(record, 2, "passed")
- set_phase(record, 3, "waiting")
- payload = _model_payload_llm(
- record["problem"], record["batch"], provider, api_key, model,
- should_stop=should_stop, on_delta=on_delta,
- )
- text = "题面已确认。会话数据已落盘,下面是三条候选路线。"
- record["messages"].append(
- {
- "role": "assistant",
- "content": text,
- "interrupt": {"card": "model-choice", "payload": payload},
- }
- )
- record["pending"] = {"card": "model-choice", "payload": payload}
- store.put(record)
- yield phase_event(1, "passed")
- yield phase_event(2, "passed", "会话数据目录已创建")
- yield phase_event(3, "running")
- yield {"event": "token", "data": {"text": text}}
- yield phase_event(3, "waiting")
- yield {"event": "interrupt", "data": record["pending"]}
- return
-
- if action == "reroll":
- if card != "model-choice":
- raise ValueError("当前不是在选模")
- _resolve_interrupt(record, "已换一批")
- previous = [
- str(item.get("name") or "")
- for item in (pending.get("payload") or {}).get("candidates") or []
- ]
- record["batch"] += 1
- payload = _model_payload_llm(
- record["problem"], record["batch"], provider, api_key, model,
- previous=previous, should_stop=should_stop, on_delta=on_delta,
- )
- text = f"换一批(第 {record['batch']} 组):仍然只看路线差异,不改变待选状态。"
- record["messages"].append(
- {
- "role": "assistant",
- "content": text,
- "interrupt": {"card": "model-choice", "payload": payload},
- }
- )
- record["pending"] = {"card": "model-choice", "payload": payload}
- set_phase(record, 3, "waiting")
- store.put(record)
- yield {"event": "token", "data": {"text": text}}
- yield {"event": "interrupt", "data": record["pending"]}
- return
-
- if action == "choose":
- if card != "model-choice":
- raise ValueError("当前不是在选模")
- candidates = pending.get("payload", {}).get("candidates", [])
- picked = next((c for c in candidates if c.get("id") == choice), None)
- if picked is None:
- raise ValueError("选择的候选不存在")
- _resolve_interrupt(record, f"已选:{picked['name']}")
- # 所选模型落盘:阶段四按它生成代码,选模不再是装饰。
- record["picked"] = picked
- set_phase(record, 3, "passed")
- set_phase(record, 4, "running")
- text = f"已选择「{picked['name']}」。阶段三已过,开始阶段四:真跑一次基线。"
- record["messages"].append({"role": "assistant", "content": text})
- record["pending"] = None
- store.put(record)
- yield phase_event(3, "passed")
- yield phase_event(4, "running")
- yield {"event": "token", "data": {"text": text}}
- yield from _phase4_prepare(
- store, record, picked, workspace,
- provider=provider, api_key=api_key, model=model,
- should_stop=should_stop, on_delta=on_delta,
- )
- return
-
- if action == "run":
- if card != "code-confirm":
- raise ValueError("当前不是在确认求解代码")
- yield from _run_code(
- store, record, workspace,
- {
- "provider": provider, "api_key": api_key, "model": model,
- "should_stop": should_stop, "on_delta": on_delta,
- },
- )
- return
-
- raise ValueError(f"未知动作: {action}")
-
-
-def _workflow_delay() -> float:
- try:
- return max(0.0, float(os.environ.get("MMS_WORKFLOW_DELAY_MS") or "180") / 1000)
- except ValueError:
- return 0.18
-
-
-def _tool(
- call_id: str,
- name: str,
- status: str,
- *,
- args=None,
- result=None,
- duration_ms: int | None = None,
- delay: float = 0.0,
-) -> dict:
- data: dict = {"id": call_id, "name": name, "status": status}
- if args is not None:
- data["args"] = args
- if result is not None:
- data["result"] = result
- if duration_ms is not None:
- data["duration_ms"] = duration_ms
- row: dict = {"event": "tool_call", "data": data}
- if delay:
- row["delay"] = delay
- return row
-
-
-def _text_event(text: str, delay: float = 0.0) -> dict:
- row: dict = {"event": "token", "data": {"text": text}}
- if delay:
- row["delay"] = delay
- return row
-
-
-def _close_phase4(store: SessionStore, record: dict, text: str) -> None:
- record["messages"].append({"role": "assistant", "content": text})
- record["pending"] = None
- store.put(record)
-
-
-P4_INSTRUCTION = (
- "你是数学建模竞赛的求解代码生成助手。按题面、所选方法与数据画像,写一个完整可运行的 Python 脚本 solution.py。"
- "只输出一个 JSON 对象,不要围栏、不要解释,形状:"
- '{"rationale":"两三句实现思路","code":"完整 Python 源码"}。'
- "脚本硬性契约:用 argparse 接受 --data(CSV/TSV 路径)与 --out(输出目录);"
- "在 --out 写出 result.json(含 ok、rows、cols、target 与本题关键数值结果)"
- "和 figure.png / figure.pdf / figure.svg 三件图(matplotlib 用 Agg 后端,dpi≥150);"
- "只用标准库 + numpy + matplotlib,不依赖 pandas / scikit-learn;"
- "数据编码按 utf-8-sig / gbk / utf-8 依次尝试;固定随机种子保证可复现;"
- "不得联网、不得读写 --data/--out 之外的路径、不得执行系统命令。"
- "修复轮次会附上上一版代码与失败输出,请针对性修改后重新输出完整脚本。"
-)
-
-P4_MAX_ROUNDS = 3
-
-
-def _validate_code(data: dict) -> dict:
- code = data.get("code")
- if not isinstance(code, str) or not code.strip():
- raise ValueError("code 必须是非空字符串")
- problems = baseline.validate_script(code)
- if problems:
- raise ValueError("脚本不满足契约:" + ";".join(problems))
- return {"rationale": str(data.get("rationale") or "").strip()[:500], "code": code}
-
-
-def _p4_user_content(record: dict, picked: dict, profile: dict, feedback: str = "") -> str:
- explain = picked.get("explain") or {}
- parts = [
- f"题面:\n{question_source(record['problem'])}",
- (
- f"所选方法:{picked.get('name')}\n核心思路:{picked.get('idea')}\n"
- f"数学形式:{explain.get('math') or '无'}\n验证方式:{explain.get('verify') or '无'}"
- ),
- "数据画像:\n" + json.dumps(profile, ensure_ascii=False)[:4000],
- ]
- if feedback:
- parts.append(feedback)
- return "\n\n".join(parts)
-
-
-def _p4_feedback(round_no: int, prev_code: str, error_text: str) -> str:
- return (
- f"这是第 {round_no} 轮修复。上一版代码运行失败,失败输出(尾部):\n{error_text[-1500:]}\n\n"
- f"上一版代码:\n{prev_code[:8000]}"
- )
-
-
-def _code_card(
- store: SessionStore,
- record: dict,
- code: str,
- rationale: str,
- script_path: Path,
- data_path: Path,
- round_no: int,
- sample: bool,
- source: str,
-) -> Iterator[dict]:
- """先落 pending 再 yield interrupt:执行严格发生在用户点「运行」之后。"""
- text = (
- f"求解脚本已生成(第 {round_no} 轮,{source})。请检查代码,点「运行」才执行;"
- "脚本只读数据文件、只写输出目录。\n\n"
- )
- payload = {
- "title": "求解代码确认",
- "intro": rationale or "检查代码后运行。",
- "code": code,
- "scriptPath": str(script_path),
- "dataPath": str(data_path),
- "round": round_no,
- "rationale": rationale,
- "sample": sample,
- }
- record["messages"].append(
- {"role": "assistant", "content": text, "interrupt": {"card": "code-confirm", "payload": payload}}
- )
- record["pending"] = {"card": "code-confirm", "payload": payload}
- store.put(record)
- yield _text_event(text, _workflow_delay())
- yield {"event": "interrupt", "data": record["pending"]}
-
-
-def _phase4_prepare(
- store: SessionStore,
- record: dict,
- picked: dict,
- workspace: str,
- provider: dict | None = None,
- api_key: str = "",
- model: str = "",
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> Iterator[dict]:
- """阶段四前半:目录 → 数据画像 → LLM 生成代码 → 挂确认卡。不执行任何脚本。"""
- delay = _workflow_delay()
- name = str(picked.get("name") or "方案")
- data_root = session_scope(store.path.parent, record.get("id"))
- code_dir = data_root / "workbench" / "code"
-
- yield _text_event(
- f"按「{name}」进入阶段四:准备目录 → 定位数据 → 生成求解代码,等你确认后运行。\n\n",
- delay,
- )
-
- yield _tool("p4-prepare", "准备目录", "running", args={"dir": str(code_dir)})
- started = time.monotonic()
- try:
- code_dir.mkdir(parents=True, exist_ok=True)
- prep_error = ""
- except OSError as exc:
- prep_error = str(exc)
- yield _tool(
- "p4-prepare",
- "准备目录",
- "ok" if not prep_error else "error",
- args={"dir": str(code_dir)},
- result={"ok": not prep_error, "dir": str(code_dir), "error": prep_error},
- duration_ms=int((time.monotonic() - started) * 1000),
- delay=delay,
- )
- if prep_error:
- text = f"阶段四没开始:工作目录创建失败({prep_error})。"
- set_phase(record, 4, "failed")
- _close_phase4(store, record, text)
- yield phase_event(4, "failed", prep_error)
- yield _text_event(text, delay)
- return
-
- yield _tool("p4-data", "定位数据", "running", args={"workspace": workspace or "(未设置)"})
- started = time.monotonic()
- data_path = baseline.find_data(Path(workspace)) if workspace else None
- sample = data_path is None
- if sample:
- data_path = baseline.ensure_sample(code_dir)
- try:
- size_kb = round(data_path.stat().st_size / 1024, 1)
- except OSError:
- size_kb = 0.0
- yield _tool(
- "p4-data",
- "定位数据",
- "ok",
- args={"workspace": workspace or "(未设置)"},
- result={
- "file": data_path.name,
- "path": str(data_path),
- "size_kb": size_kb,
- "sample": sample,
- },
- duration_ms=int((time.monotonic() - started) * 1000),
- delay=delay,
- )
- if sample:
- yield _text_event("工作区里没有 CSV/TSV,先用内置示例数据 sample.csv 把链路跑通。\n", delay)
-
- profile = baseline.profile_data(data_path)
- yield from _p4_generate(
- store, record, picked, code_dir, data_path, profile, sample, round_no=1,
- provider=provider, api_key=api_key, model=model,
- should_stop=should_stop, on_delta=on_delta,
- )
-
-
-def _p4_generate(
- store: SessionStore,
- record: dict,
- picked: dict,
- code_dir: Path,
- data_path: Path,
- profile: dict,
- sample: bool,
- round_no: int,
- feedback: str = "",
- provider: dict | None = None,
- api_key: str = "",
- model: str = "",
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> Iterator[dict]:
- """生成脚本(LLM 优先,失败回退内置基线),写盘后挂 code-confirm 卡。"""
- delay = _workflow_delay()
- yield _tool("p4-code", "生成脚本", "running", args={"file": baseline.SCRIPT_NAME, "round": round_no})
- started = time.monotonic()
- code, rationale, source = baseline.SCRIPT, "内置基线脚本(离线兜底)", "fallback"
- if provider:
- try:
- parsed = llm.complete_json(
- provider, api_key, model or record.get("model") or "",
- "p4-code", P4_INSTRUCTION,
- _p4_user_content(record, picked, profile, feedback),
- _validate_code,
- should_stop=should_stop, on_delta=on_delta,
- )
- code, rationale, source = parsed["code"], parsed["rationale"], "llm"
- except llm.LlmError as exc:
- rationale = f"模型不可用({exc}),回退内置基线脚本。"
- script_path = code_dir / baseline.SCRIPT_NAME
- try:
- script_path.write_text(code, encoding="utf-8")
- write_error = ""
- except OSError as exc:
- write_error = str(exc)
- yield _tool(
- "p4-code",
- "生成脚本",
- "ok" if not write_error else "error",
- args={"file": baseline.SCRIPT_NAME, "round": round_no},
- result={
- "ok": not write_error,
- "file": str(script_path),
- "lines": len(code.splitlines()),
- "source": source,
- "error": write_error,
- },
- duration_ms=int((time.monotonic() - started) * 1000),
- delay=delay,
- )
- if write_error:
- text = f"阶段四失败:脚本写入失败({write_error})。"
- set_phase(record, 4, "failed")
- _close_phase4(store, record, text)
- yield phase_event(4, "failed", write_error)
- yield _text_event(text, delay)
- return
- yield from _code_card(store, record, code, rationale, script_path, data_path, round_no, sample, source)
-
-
-def _run_code(store: SessionStore, record: dict, workspace: str, ctx: dict) -> Iterator[dict]:
- """阶段四后半:用户点「运行」后才执行;失败回喂修复 ≤2 轮,成功登记产物。"""
- delay = _workflow_delay()
- pending = record.get("pending") or {}
- payload = pending.get("payload") or {}
- picked = record.get("picked") or {}
- name = str(picked.get("name") or "方案")
- data_root = session_scope(store.path.parent, record.get("id"))
- code_dir = data_root / "workbench" / "code"
- out_dir = code_dir / "outputs"
- data_path = Path(str(payload.get("dataPath") or ""))
- round_no = int(payload.get("round") or 1)
- sample = bool(payload.get("sample"))
- code = str(payload.get("code") or "")
-
- _resolve_interrupt(record, "已运行")
- record["pending"] = None
- store.put(record)
- yield _text_event(f"开始运行求解脚本(第 {round_no} 轮)。\n", delay)
-
- if not data_path.is_file():
- text = "阶段四失败:数据文件不存在,请重新选择题面数据。"
- set_phase(record, 4, "failed")
- _close_phase4(store, record, text)
- yield phase_event(4, "failed", "数据文件缺失")
- yield _text_event(text, delay)
- return
-
- yield _tool("p4-run", "运行脚本", "running", args={"data": str(data_path), "out": str(out_dir)})
- started = time.monotonic()
- run = baseline.run_baseline(code_dir, data_path, out_dir)
- stats = run.get("result") or {}
- seconds = round(time.monotonic() - started, 1)
- yield _tool(
- "p4-run",
- "运行脚本",
- "ok" if run.get("ok") else "error",
- args={"data": str(data_path), "out": str(out_dir)},
- result={
- "ok": run.get("ok"),
- "exit": run.get("exit"),
- "seconds": seconds,
- "rows": stats.get("rows"),
- "cols": stats.get("cols"),
- "target": stats.get("target"),
- "r2": stats.get("r2"),
- "rmse": stats.get("rmse"),
- "stderr": (run.get("stderr") or "")[-400:],
- },
- duration_ms=int(seconds * 1000),
- delay=delay,
- )
-
- if not run.get("ok"):
- error_text = (run.get("stderr") or run.get("stdout") or "").strip()
- if round_no < P4_MAX_ROUNDS and ctx.get("provider"):
- text = f"第 {round_no} 轮运行失败(退出 {run.get('exit')}),把失败输出回喂模型修复。\n"
- record["messages"].append({"role": "assistant", "content": text})
- store.put(record)
- yield _text_event(text, delay)
- profile = baseline.profile_data(data_path)
- yield from _p4_generate(
- store, record, picked, code_dir, data_path, profile, sample,
- round_no=round_no + 1,
- feedback=_p4_feedback(round_no + 1, code, error_text),
- provider=ctx.get("provider"), api_key=ctx.get("api_key") or "",
- model=ctx.get("model") or "", should_stop=ctx.get("should_stop"),
- on_delta=ctx.get("on_delta"),
- )
- return
- tail = " ".join(error_text.split())[-200:]
- text = (
- f"阶段四失败:脚本退出 {run.get('exit')}"
- f"{',已用尽修复轮次' if round_no >= P4_MAX_ROUNDS else ',且没有可用模型做修复'}。"
- f"{('输出:' + tail) if tail else ''}"
- )
- set_phase(record, 4, "failed")
- _close_phase4(store, record, text)
- yield phase_event(4, "failed", "求解脚本失败")
- yield _text_event(text, delay)
- return
-
- yield _tool("p4-collect", "登记产物", "running", args={"outputs": sorted(run["outputs"])})
- started = time.monotonic()
- version = workbench_figure.register(
- data_dir=data_root,
- sources=run["outputs"],
- template="solution",
- template_title=f"阶段四 · 求解({name})",
- theme="studio-ink",
- theme_title="Studio Ink",
- command=run.get("command") or "",
- stdout=run.get("stdout") or "",
- stderr=run.get("stderr") or "",
- label="求解",
- )
- # 用户文件夹里的「图表」放最新的可读副本;写不进去只记日志,不影响阶段推进。
- project_export.copy_outputs(workspace, "图表", version["outputs"])
- yield _tool(
- "p4-collect",
- "登记产物",
- "ok",
- args={"outputs": sorted(run["outputs"])},
- result={"version": version["id"], "outputs": version["outputs"]},
- duration_ms=int((time.monotonic() - started) * 1000),
- delay=delay,
- )
- yield {
- "event": "artifact",
- "data": {"kind": "figure", "version": version["id"], "outputs": version["outputs"]},
- }
-
- r2 = stats.get("r2")
- rmse = stats.get("rmse")
- if isinstance(r2, (int, float)) and isinstance(rmse, (int, float)):
- fit = f"R²={r2:.3f},RMSE={rmse:.3f}"
- else:
- fit = "关键数值结果见 result.json"
- source = "内置示例数据" if sample else "工作区数据"
- text = (
- f"阶段四完成({name})。\n"
- f"- 数据:{data_path.name}({source},{stats.get('rows')} 行 × {stats.get('cols')} 列,"
- f"目标列 {stats.get('target')})\n"
- f"- 结果:{fit}\n"
- f"- 产物:PNG/PDF/SVG 三件,已登记为图表版本 {version['id']}\n"
- "进入阶段五:按真实结果写论文并排版。"
- )
- set_phase(record, 4, "passed")
- record["messages"].append({"role": "assistant", "content": text})
- record["pending"] = None
- store.put(record)
- yield phase_event(4, "passed", "求解脚本已跑通,图表版本已登记")
- yield _text_event(text, delay)
- yield from _phase5_paper(store, record, workspace, ctx, run.get("result") or {}, version)
-
-
-P5_MAX_ROUNDS = 3
-
-
-def _p5_feedback(result: dict) -> str:
- parts: list[str] = []
- if result.get("error"):
- parts.append(str(result["error"]))
- for gate in result.get("gates") or []:
- if not gate.get("ok"):
- parts.append(f"{gate.get('label')}:{gate.get('detail')}")
- if result.get("logTail"):
- parts.append("编译日志尾部:\n" + str(result["logTail"])[-1500:])
- return "\n".join(parts) or "构建未通过"
-
-
-def _build_paper_once(
- store: SessionStore,
- record: dict,
- ctx: dict,
- data_root: Path,
- profile: dict,
- result_json: dict,
- version: dict,
- round_no: int,
- feedback: str,
- prev_tex: str,
- prefix: str,
-) -> Iterator[dict]:
- """写一轮论文并排版:yield 工具卡/门禁事件,最后 yield 一个 outcome 事件。
-
- outcome.data = {ok, tex, source, error}。阶段五首轮与阶段六优化轮共用。
- """
- delay = _workflow_delay()
- paper_dir = paper_build.workspace(data_root)
- picked = record.get("picked") or {}
- provider = ctx.get("provider")
- yield _tool(
- f"{prefix}-write", "撰写论文", "running",
- args={"round": round_no, "source": "llm" if provider else "fallback"},
- )
- started = time.monotonic()
- source = "llm"
- try:
- if provider:
- tex, source = paper_gen.generate(
- provider, ctx.get("api_key") or "", ctx.get("model") or record.get("model") or "",
- question_source(record["problem"]), picked, profile, result_json,
- feedback=feedback, prev_tex=prev_tex,
- should_stop=ctx.get("should_stop"), on_delta=ctx.get("on_delta"),
- )
- else:
- tex = paper_gen.sample_tex()
- source = "fallback"
- write_error = ""
- except llm.LlmError as exc:
- tex, write_error = "", str(exc)
- draft = paper_dir / "draft.tex"
- if not write_error:
- try:
- paper_dir.mkdir(parents=True, exist_ok=True)
- draft.write_text(tex, encoding="utf-8")
- # 真实求解图放进论文工作区;骨架引用 figures/final/fig1_residual.png。
- figure_src = Path((version.get("outputs") or {}).get("png") or "")
- if figure_src.is_file():
- figure_dst = paper_dir / paper_build.FIGURE_TARGET
- figure_dst.parent.mkdir(parents=True, exist_ok=True)
- shutil.copyfile(figure_src, figure_dst)
- except OSError as exc:
- write_error = str(exc)
- yield _tool(
- f"{prefix}-write", "撰写论文", "ok" if not write_error else "error",
- args={"round": round_no, "source": source},
- result={
- "ok": not write_error,
- "round": round_no,
- "source": source,
- "lines": len(tex.splitlines()),
- "error": write_error,
- },
- duration_ms=int((time.monotonic() - started) * 1000),
- delay=delay,
- )
- if write_error:
- yield {"event": "outcome", "data": {"ok": False, "tex": "", "source": source, "error": write_error}}
- return
- if source == "fallback":
- note = "没有可用模型,论文暂用演示样例稿兜底(非按本题生成);配置 Key 后可在论文页重新构建。\n"
- record["messages"].append({"role": "assistant", "content": note})
- store.put(record)
- yield _text_event(note, delay)
-
- yield _tool(f"{prefix}-build", "排版与门禁", "running", args={"round": round_no})
- started = time.monotonic()
- code, result = paper_build.build(data_root, source=draft)
- seconds = round(time.monotonic() - started, 1)
- gates = result.get("gates") or []
- yield _tool(
- f"{prefix}-build", "排版与门禁", "ok" if code == 0 else "error",
- args={"round": round_no},
- result={
- "ok": code == 0,
- "exit": code,
- "seconds": seconds,
- "gates": [{"id": g.get("id"), "ok": g.get("ok"), "detail": g.get("detail")} for g in gates],
- "error": result.get("error"),
- },
- duration_ms=int(seconds * 1000),
- delay=delay,
- )
- for gate in gates:
- yield {
- "event": "gate",
- "data": {
- "skill": str(gate.get("id") or ""),
- "ok": bool(gate.get("ok")),
- "exit": 0 if gate.get("ok") else 1,
- "summary": str(gate.get("detail") or ""),
- },
- }
- yield {
- "event": "outcome",
- "data": {"ok": code == 0, "tex": tex, "source": source, "error": result.get("error") or ""},
- }
-
-
-def _p5_profile(data_root: Path, workspace: str) -> dict:
- code_dir = data_root / "workbench" / "code"
- located = baseline.find_data(Path(workspace)) if workspace else None
- if located is None and (code_dir / baseline.SAMPLE_NAME).is_file():
- located = code_dir / baseline.SAMPLE_NAME
- return baseline.profile_data(located) if located else {}
-
-
-def _phase5_paper(
- store: SessionStore,
- record: dict,
- workspace: str,
- ctx: dict,
- result_json: dict,
- version: dict,
-) -> Iterator[dict]:
- """阶段五:LLM 按真实结果写论文 → 排版 → 门禁;失败回喂修复 ≤3 轮。
-
- 没有可用模型时回退演示样例稿并标明兜底;缺排版工具时阶段五判 failed。
- 成功后链入阶段六真实评分。
- """
- delay = _workflow_delay()
- data_root = session_scope(store.path.parent, record.get("id"))
- paper_dir = paper_build.workspace(data_root)
- provider = ctx.get("provider")
- set_phase(record, 5, "running")
- store.put(record)
- yield phase_event(5, "running")
-
- env = paper_build.env_status()
- if not env["ok"]:
- text = "阶段五失败:缺少排版工具(" + "、".join(env["missing"]) + ")。装好后在工作台论文页重试构建。"
- set_phase(record, 5, "failed")
- _close_phase4(store, record, text)
- yield phase_event(5, "failed", "缺排版工具")
- yield _text_event(text, delay)
- return
-
- profile = _p5_profile(data_root, workspace)
- prev_tex = ""
- feedback = ""
- outcome: dict = {}
- for round_no in range(1, P5_MAX_ROUNDS + 1):
- for ev in _build_paper_once(
- store, record, ctx, data_root, profile, result_json, version,
- round_no, feedback, prev_tex, "p5",
- ):
- if ev["event"] == "outcome":
- outcome = ev["data"]
- else:
- yield ev
- if outcome.get("ok"):
- break
- if not outcome.get("tex"):
- text = f"阶段五失败:论文生成不可用({outcome.get('error')})。"
- set_phase(record, 5, "failed")
- _close_phase4(store, record, text)
- yield phase_event(5, "failed", "论文生成失败")
- yield _text_event(text, delay)
- return
- prev_tex = outcome["tex"]
- feedback = str(outcome.get("error") or "构建未通过")
- if round_no < P5_MAX_ROUNDS and provider:
- note = f"第 {round_no} 轮未过门禁/编译,把问题回喂模型修复。\n"
- record["messages"].append({"role": "assistant", "content": note})
- store.put(record)
- yield _text_event(note, delay)
- continue
- break
-
- if outcome.get("ok"):
- artifacts = paper_build.state(data_root).get("artifacts") or {}
- deliverables = {
- kind: str((artifacts.get(kind) or {}).get("path") or "")
- for kind in ("pdf", "docx")
- if artifacts.get(kind)
- }
- project_export.copy_outputs(workspace, "论文", deliverables)
- headline = (
- "阶段五完成:论文已按真实求解结果生成并排版。"
- if outcome.get("source") == "llm"
- else "阶段五完成:论文已排版(离线兜底样例稿,非按本题生成)。"
- )
- text = (
- f"{headline}\n"
- f"- 产物:paper.pdf / paper.docx({paper_dir})\n"
- "- 三道交付门禁全绿(去 AI 措辞 / 结构指标 / 章节结构)\n"
- "进入阶段六:按评分口径评审论文。"
- )
- set_phase(record, 5, "passed")
- record["messages"].append({"role": "assistant", "content": text})
- record["pending"] = None
- store.put(record)
- yield phase_event(5, "passed", "论文 PDF/DOCX 已产出,门禁全绿")
- yield {"event": "artifact", "data": {"kind": "paper", "outputs": deliverables}}
- yield _text_event(text, delay)
- yield from _phase6_score(store, record, workspace, ctx, result_json, version, profile)
- return
-
- error = str(outcome.get("error") or "构建失败")
- text = (
- f"阶段五失败(已用尽 {P5_MAX_ROUNDS} 轮修复):{error}\n"
- "可在论文页查看日志并手动重试构建。"
- )
- set_phase(record, 5, "failed")
- _close_phase4(store, record, text)
- yield phase_event(5, "failed", error[:120])
- yield _text_event(text, delay)
-
-
-P6_MAX_ROUNDS = 3
-
-
-def _score_feedback(card: dict) -> str:
- lines: list[str] = []
- for dim in card.get("dimensions") or []:
- for item in dim.get("deductions") or []:
- lines.append(
- f"[{dim.get('id')}] {item.get('item')}(-{item.get('penalty')})"
- f"位置:{item.get('target') or '未标注'};改法:{item.get('suggestion') or '无'}"
- )
- return "\n".join(lines) or "无扣分明细"
-
-
-def _phase6_score(
- store: SessionStore,
- record: dict,
- workspace: str,
- ctx: dict,
- result_json: dict,
- version: dict,
- profile: dict,
-) -> Iterator[dict]:
- """阶段六:LLM 按 rubric 评审真实论文;S<85 回喂扣分修复,≤3 轮熔断。
-
- 一票否决直接淘汰、不进优化循环;没有可用模型时用演示评分卡并标明兜底。
- """
- delay = _workflow_delay()
- data_root = session_scope(store.path.parent, record.get("id"))
- paper_dir = paper_build.workspace(data_root)
- provider = ctx.get("provider")
- set_phase(record, 6, "running")
- store.put(record)
- yield phase_event(6, "running")
-
- prev_card: dict | None = None
- last_data: dict = {}
- for round_no in range(1, P6_MAX_ROUNDS + 1):
- tex_path = paper_dir / "paper.tex"
- try:
- tex = tex_path.read_text(encoding="utf-8")
- except OSError as exc:
- text = f"阶段六失败:读不到论文稿件({exc})。"
- set_phase(record, 6, "failed")
- _close_phase4(store, record, text)
- yield phase_event(6, "failed", "稿件缺失")
- yield _text_event(text, delay)
- return
-
- yield _tool("p6-score", "评分", "running", args={"round": round_no})
- started = time.monotonic()
- source = "llm"
- try:
- if provider:
- card, source = score_gen.generate(
- provider, ctx.get("api_key") or "", ctx.get("model") or record.get("model") or "",
- tex, round_no, prev_card=prev_card,
- should_stop=ctx.get("should_stop"), on_delta=ctx.get("on_delta"),
- )
- else:
- card = score_gen.demo_card(round_no)
- source = "fallback"
- score_error = ""
- except llm.LlmError as exc:
- card, score_error = {}, str(exc)
- if not score_error:
- try:
- workbench_score.save_card(data_root, card)
- state = workbench_score.state(data_dir=data_root)
- last_data = next(
- (r for r in state.get("rounds", []) if r.get("round") == round_no), {}
- )
- except (RuntimeError, OSError, ValueError) as exc:
- score_error = str(exc)
- seconds = round(time.monotonic() - started, 1)
- yield _tool(
- "p6-score", "评分", "ok" if not score_error else "error",
- args={"round": round_no},
- result={
- "ok": not score_error,
- "round": round_no,
- "source": source,
- "total": last_data.get("total"),
- "pass": last_data.get("pass"),
- "veto": last_data.get("veto"),
- "error": score_error,
- },
- duration_ms=int(seconds * 1000),
- delay=delay,
- )
- if score_error:
- text = f"阶段六失败:评分不可用({score_error})。"
- set_phase(record, 6, "failed")
- _close_phase4(store, record, text)
- yield phase_event(6, "failed", "评分失败")
- yield _text_event(text, delay)
- return
- if source == "fallback":
- note = "没有可用模型,评分暂用演示评分卡兜底(非按本论文评审);配置 Key 后可重新评分。\n"
- record["messages"].append({"role": "assistant", "content": note})
- store.put(record)
- yield _text_event(note, delay)
-
- total = last_data.get("total")
- passed = bool(last_data.get("pass"))
- veto = bool(last_data.get("veto"))
- if passed or veto:
- break
- prev_card = card
- if round_no < P6_MAX_ROUNDS and provider:
- note = f"第 {round_no} 轮总分 {total} < 85,把扣分明细回喂模型修改论文。\n"
- record["messages"].append({"role": "assistant", "content": note})
- store.put(record)
- yield _text_event(note, delay)
- feedback = "评分未达标,请按以下扣分明细逐条修改论文:\n" + _score_feedback(card)
- outcome: dict = {}
- for ev in _build_paper_once(
- store, record, ctx, data_root, profile, result_json, version,
- round_no, feedback, tex, "p6-fix",
- ):
- if ev["event"] == "outcome":
- outcome = ev["data"]
- else:
- yield ev
- if not outcome.get("ok"):
- text = f"阶段六中断:第 {round_no} 轮修改后排版未通过({outcome.get('error')})。"
- set_phase(record, 6, "failed")
- _close_phase4(store, record, text)
- yield phase_event(6, "failed", "优化轮排版失败")
- yield _text_event(text, delay)
- return
- continue
- break
-
- total = last_data.get("total")
- passed = bool(last_data.get("pass"))
- veto = bool(last_data.get("veto"))
- breaker = bool(last_data.get("breaker"))
- if veto:
- text = (
- "阶段六结束:触发一票否决(身份信息/页眉等红线),直接淘汰、不计分。\n"
- "请删除红线内容后重新构建论文并评分。"
- )
- set_phase(record, 6, "failed")
- elif passed:
- text = f"阶段六完成:总分 {total} ≥ 85,达标。全流程跑通。"
- set_phase(record, 6, "passed")
- elif breaker:
- text = (
- f"阶段六熔断:{P6_MAX_ROUNDS} 轮优化后总分 {total} 仍 < 85,"
- "未达 85 分标准,需人工复核。扣分明细见评分页。"
- )
- set_phase(record, 6, "failed")
- else:
- text = f"阶段六结束:总分 {total} < 85,需针对性优化后重新评分。"
- set_phase(record, 6, "failed")
- _close_phase4(store, record, text)
- yield phase_event(6, "passed" if passed else "failed", f"总分 {total}")
- yield {"event": "artifact", "data": {"kind": "score", "outputs": {"round": str(last_data.get("round") or 1)}}}
- yield _text_event(text, delay)
diff --git a/runtime/src/mms/paper_build.py b/runtime/src/mms/paper_build.py
deleted file mode 100644
index fc9ba21..0000000
--- a/runtime/src/mms/paper_build.py
+++ /dev/null
@@ -1,358 +0,0 @@
-"""M5 论文排版:xelatex 编译、pandoc 转 Word、去 AI 与章节门禁。
-
-排版工具不在仓库里:xelatex 走系统 PATH(或 MMS_XELATEX),pandoc 依次看
-MMS_PANDOC、随包的 /pandoc、PATH,最后回落到
-%LOCALAPPDATA%/mms-tools/pandoc.exe。缺件时明确报缺,不尝试自动安装。
-"""
-
-from __future__ import annotations
-
-import importlib.util
-import json
-import os
-import shutil
-import subprocess
-import sys
-import time
-from datetime import datetime, timezone
-from pathlib import Path
-
-from .registry import EXIT_OK, EXIT_USAGE_OR_ENV, EXIT_VALIDATION_FAILED, EnvError, repo_root
-
-SAMPLE_DIR = Path(__file__).resolve().parent / "paper_sample"
-SAMPLE_TEX = SAMPLE_DIR / "paper.tex"
-SAMPLE_FIGURE = Path("skills") / "mathmodel-figure" / "examples" / "previews" / "fit_confidence_residual_replica.png"
-FIGURE_TARGET = Path("figures") / "final" / "fig1_residual.png"
-XELATEX_TIMEOUT = 300
-PANDOC_TIMEOUT = 180
-MAX_TAIL = 4000
-
-
-def _tail(text: str, limit: int = MAX_TAIL) -> str:
- text = (text or "").strip()
- return text[-limit:]
-
-
-def _which_pandoc() -> str | None:
- override = os.environ.get("MMS_PANDOC")
- if override:
- return override if Path(override).is_file() else None
- home = os.environ.get("MMS_HOME")
- if home:
- bundled = Path(home) / "pandoc" / ("pandoc.exe" if os.name == "nt" else "pandoc")
- if bundled.is_file():
- return str(bundled)
- found = shutil.which("pandoc")
- if found:
- return found
- local = os.environ.get("LOCALAPPDATA")
- if local:
- candidate = Path(local) / "mms-tools" / "pandoc.exe"
- if candidate.is_file():
- return str(candidate)
- return None
-
-
-def _version(exe: str | None) -> str:
- if not exe:
- return ""
- try:
- proc = subprocess.run(
- [exe, "--version"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=30,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired):
- return ""
- line = (proc.stdout or "").strip().splitlines()
- return line[0].strip() if line else ""
-
-
-def env_status() -> dict:
- override = os.environ.get("MMS_XELATEX")
- xelatex = (override if Path(override).is_file() else None) if override else shutil.which("xelatex")
- pandoc = _which_pandoc()
- python_docx = importlib.util.find_spec("docx") is not None
- missing = []
- if not xelatex:
- missing.append("xelatex")
- if not pandoc:
- missing.append("pandoc")
- if not python_docx:
- missing.append("python-docx")
- return {
- "ok": not missing,
- "missing": missing,
- "xelatex": {"found": bool(xelatex), "path": xelatex or "", "version": _version(xelatex)},
- "pandoc": {"found": bool(pandoc), "path": pandoc or "", "version": _version(pandoc)},
- "python_docx": python_docx,
- }
-
-
-def _state_path(data_dir: Path) -> Path:
- return data_dir / "workbench" / "paper" / "build.json"
-
-
-def workspace(data_dir: Path) -> Path:
- return data_dir / "workbench" / "paper"
-
-
-def _read_state(data_dir: Path) -> dict:
- try:
- data = json.loads(_state_path(data_dir).read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- return {}
- return data if isinstance(data, dict) else {}
-
-
-def _save_state(data_dir: Path, state: dict) -> None:
- path = _state_path(data_dir)
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(".tmp")
- tmp.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
- tmp.replace(path)
-
-
-def _run(cmd: list[str], cwd: Path, timeout: int) -> subprocess.CompletedProcess:
- env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}
- try:
- return subprocess.run(
- cmd,
- cwd=str(cwd),
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- env=env,
- timeout=timeout,
- check=False,
- )
- except subprocess.TimeoutExpired as exc:
- raise EnvError(f"命令超时({timeout}s):{' '.join(cmd[:2])}") from exc
- except OSError as exc:
- raise EnvError(f"无法执行 {cmd[0]}:{exc}") from exc
-
-
-def _run_json(script: Path, args: list[str], cwd: Path, timeout: int = 120) -> tuple[int, dict | None]:
- proc = _run([sys.executable, str(script), *args], cwd, timeout)
- try:
- data = json.loads(proc.stdout)
- except json.JSONDecodeError:
- return proc.returncode, None
- return proc.returncode, data
-
-
-def _stage(workspace_dir: Path, root: Path, source: Path | None) -> list[str]:
- """把稿件与配图放进工作区,返回做了什么。"""
- notes = []
- workspace_dir.mkdir(parents=True, exist_ok=True)
- tex = workspace_dir / "paper.tex"
- if source is not None:
- if not source.is_file():
- raise EnvError(f"找不到稿件:{source}")
- shutil.copyfile(source, tex)
- notes.append(f"稿件来自 {source}")
- elif not tex.is_file():
- shutil.copyfile(SAMPLE_TEX, tex)
- notes.append("稿件来自演示样例")
-
- figure_src = root / SAMPLE_FIGURE
- figure_dst = workspace_dir / FIGURE_TARGET
- if not figure_dst.is_file():
- if not figure_src.is_file():
- raise EnvError(f"找不到演示配图:{figure_src}(技能是否已 vendor?)")
- figure_dst.parent.mkdir(parents=True, exist_ok=True)
- shutil.copyfile(figure_src, figure_dst)
- notes.append("配图来自 mathmodel-figure 的预览")
- return notes
-
-
-def _check_artifact(path: Path, kind: str) -> tuple[bool, str]:
- if not path.is_file():
- return False, f"{kind} 未生成"
- size = path.stat().st_size
- if size <= 1000:
- return False, f"{kind} 只有 {size} B"
- head = path.open("rb").read(8)
- if kind == "PDF" and not head.startswith(b"%PDF"):
- return False, "PDF 文件头不对"
- if kind == "DOCX" and not head.startswith(b"PK"):
- return False, "DOCX 不是 zip 容器"
- return True, f"{kind} {size // 1024} KB"
-
-
-def _gate_phrasing(root: Path, cwd: Path, tex: str) -> dict:
- script = root / "skills" / "mathmodel-deai" / "code" / "check_phrasing.py"
- code, data = _run_json(script, ["--json", tex], cwd)
- hits = len((data or {}).get("hits") or [])
- ok = code == 0
- return {
- "id": "phrasing",
- "label": "去 AI 措辞",
- "ok": ok,
- "detail": "0 处命中" if ok else f"命中 {hits} 处" if data else f"检查器退出 {code}",
- }
-
-
-def _gate_style(root: Path, cwd: Path, tex: str) -> dict:
- script = root / "skills" / "mathmodel-deai" / "code" / "check_style.py"
- code, data = _run_json(script, ["--json", tex], cwd)
- hits = (data or {}).get("hits") or []
- ok = code == 0
- detail = "0 处命中" if ok else f"命中 {len(hits)} 处" if data else f"检查器退出 {code}"
- return {"id": "style", "label": "结构指标", "ok": ok, "detail": detail}
-
-
-def _gate_chapters(root: Path, cwd: Path, tex: str) -> dict:
- script = root / "skills" / "mathmodel-score" / "code" / "check_chapters.py"
- code, data = _run_json(script, ["--json", "--rules", "cumcm", tex], cwd)
- if data is None:
- return {"id": "chapters", "label": "章节结构", "ok": False, "detail": f"检查器退出 {code}"}
- counts = ((data.get("files") or [{}])[0]).get("counts", {})
- hard = int(data.get("hard_failed", counts.get("hard", 0)))
- soft = int(data.get("soft_failed", counts.get("soft", 0)))
- manual = int(counts.get("manual", 0))
- return {
- "id": "chapters",
- "label": "章节结构",
- "ok": hard == 0,
- "detail": f"hard {hard} · soft {soft} · 人工 {manual}",
- }
-
-
-def state(data_dir: Path, root: Path | None = None) -> dict:
- root = root or repo_root()
- state = _read_state(data_dir)
- workdir = workspace(data_dir)
- artifacts = {}
- for kind, name in (("pdf", "paper.pdf"), ("docx", "paper.docx"), ("tex", "paper.tex")):
- path = workdir / name
- if path.is_file():
- artifacts[kind] = {"path": str(path), "size": path.stat().st_size}
- return {
- "ok": bool(state.get("ok")),
- "env": env_status(),
- "artifacts": artifacts,
- "builtAt": state.get("builtAt"),
- "steps": state.get("steps", []),
- "gates": state.get("gates", []),
- "error": state.get("error"),
- "logTail": state.get("logTail", ""),
- "workspace": str(workdir),
- }
-
-
-def build(data_dir: Path, root: Path | None = None, source: Path | None = None) -> tuple[int, dict]:
- root = root or repo_root()
- env = env_status()
- if not env["ok"]:
- return EXIT_USAGE_OR_ENV, {
- "ok": False,
- "error": "缺少排版工具:" + "、".join(env["missing"]),
- "env": env,
- "steps": [],
- "gates": [],
- }
-
- workdir = workspace(data_dir)
- steps: list[dict] = []
- log_tail = ""
-
- def step(row_id: str, label: str, ok: bool, detail: str, started: float) -> None:
- steps.append(
- {
- "id": row_id,
- "label": label,
- "ok": ok,
- "detail": detail,
- "ms": int((time.time() - started) * 1000),
- }
- )
-
- started = time.time()
- try:
- notes = _stage(workdir, root, source)
- step("stage", "准备稿件", True, ";".join(notes) or "沿用现有稿件", started)
- except EnvError as exc:
- step("stage", "准备稿件", False, str(exc), started)
- code, payload = _finish(data_dir, env, steps, [], str(exc), "")
- return EXIT_USAGE_OR_ENV, payload
-
- xelatex = env["xelatex"]["path"]
- pandoc = env["pandoc"]["path"]
- tex = "paper.tex"
-
- for index in (1, 2):
- started = time.time()
- proc = _run(
- [xelatex, "-interaction=nonstopmode", "-halt-on-error", "-no-shell-escape", tex],
- workdir,
- XELATEX_TIMEOUT,
- )
- log_tail = _tail(proc.stdout + "\n" + proc.stderr)
- ok = proc.returncode == 0
- detail = "编译通过" if ok else _first_error(proc.stdout) or f"xelatex 退出 {proc.returncode}"
- step(f"xelatex-{index}", f"xelatex 第 {index} 遍", ok, detail, started)
- if not ok:
- return _finish(data_dir, env, steps, [], f"xelatex 第 {index} 遍失败:{detail}", log_tail)
-
- (workdir / "logs").mkdir(exist_ok=True)
- if (workdir / "paper.log").is_file():
- shutil.copyfile(workdir / "paper.log", workdir / "logs" / "paper.log")
- pdf = workdir / "paper.pdf"
- pdf_ok, pdf_detail = _check_artifact(pdf, "PDF")
- started = time.time()
- step("pdf", "PDF 产物", pdf_ok, pdf_detail, started)
- if not pdf_ok:
- return _finish(data_dir, env, steps, [], pdf_detail, log_tail)
-
- started = time.time()
- proc = _run([pandoc, tex, "-o", "paper.docx", "--resource-path=."], workdir, PANDOC_TIMEOUT)
- docx = workdir / "paper.docx"
- docx_ok, docx_detail = _check_artifact(docx, "DOCX")
- step("pandoc", "pandoc 转 Word", docx_ok, docx_detail if docx_ok else _tail(proc.stderr, 400) or docx_detail, started)
- if not docx_ok:
- return _finish(data_dir, env, steps, [], docx_detail, log_tail)
-
- started = time.time()
- post = root / "skills" / "mathmodel-paper" / "code" / "word_postprocess.py"
- proc = _run([sys.executable, str(post), "paper.docx"], workdir, PANDOC_TIMEOUT)
- ok = proc.returncode == 0 and _check_artifact(docx, "DOCX")[0]
- step("docx", "Word 版式微调", ok, "版式微调完成" if ok else _tail(proc.stderr, 400) or f"后处理退出 {proc.returncode}", started)
-
- gates = [
- _gate_phrasing(root, workdir, tex),
- _gate_style(root, workdir, tex),
- _gate_chapters(root, workdir, tex),
- ]
- all_ok = ok and all(g["ok"] for g in gates)
- error = "" if all_ok else ";".join(g["label"] + ":" + g["detail"] for g in gates if not g["ok"])
- return _finish(data_dir, env, steps, gates, error, log_tail)
-
-
-def _first_error(log: str) -> str:
- for line in (log or "").splitlines():
- if line.startswith("!") or "error:" in line.lower():
- return line.strip()[:200]
- return ""
-
-
-def _finish(
- data_dir: Path, env: dict, steps: list[dict], gates: list[dict], error: str, log_tail: str
-) -> tuple[int, dict]:
- ok = not error and bool(steps) and all(s["ok"] for s in steps) and all(g["ok"] for g in gates)
- state = {
- "ok": ok,
- "builtAt": datetime.now(timezone.utc).isoformat(timespec="seconds"),
- "steps": steps,
- "gates": gates,
- "error": error or None,
- "logTail": log_tail,
- }
- _save_state(data_dir, state)
- payload = state | {"env": env, "workspace": str(workspace(data_dir))}
- return (EXIT_OK if ok else EXIT_VALIDATION_FAILED), payload
diff --git a/runtime/src/mms/project_export.py b/runtime/src/mms/project_export.py
deleted file mode 100644
index 98616ac..0000000
--- a/runtime/src/mms/project_export.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""把会话产物复制到用户看得见的赛题文件夹(图表/论文)。
-
-复制是附带动作:目标目录不可写或文件被占用时只记一行日志,不阻断渲染与构建。
-"""
-
-from __future__ import annotations
-
-import shutil
-import sys
-from pathlib import Path
-
-
-def copy_outputs(workspace: str, folder: str, sources: dict[str, str]) -> None:
- if not workspace:
- return
- target = Path(workspace) / folder
- try:
- target.mkdir(parents=True, exist_ok=True)
- except OSError as exc:
- print(f"[mms] 创建 {target} 失败:{exc}", file=sys.stderr)
- return
- for source in sources.values():
- path = Path(source)
- if not path.is_file():
- continue
- try:
- shutil.copy2(path, target / path.name)
- except OSError as exc:
- print(f"[mms] 复制 {path.name} 失败:{exc}", file=sys.stderr)
diff --git a/runtime/src/mms/provider.py b/runtime/src/mms/provider.py
deleted file mode 100644
index 53ffe78..0000000
--- a/runtime/src/mms/provider.py
+++ /dev/null
@@ -1,336 +0,0 @@
-"""OpenAI 兼容 provider 的流式客户端。
-
-只做三件事:把 SSE chunk 归一成 content / reasoning / tool_calls;
-把历史里的 reasoning 字段剥掉再回放;对 429 与 5xx 做**有界**重试。
-
-密钥只从调用方按次传入,不落盘、不写日志、不放进异常文本。
-"""
-
-from __future__ import annotations
-
-import json
-import time
-from dataclasses import dataclass, field
-from pathlib import Path
-from urllib import error, request
-from urllib.parse import urlparse
-
-RETRYABLE = (429, 500, 502, 503, 504)
-MAX_ATTEMPTS = 3
-TIMEOUT_SECONDS = 120
-LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1"}
-
-# 回放历史时只允许这些键。reasoning / reasoning_content 一律不带回去:
-# 部分 provider 在重放 reasoning 时会报错或重复计费。
-HISTORY_KEYS = {"role", "content", "tool_calls", "tool_call_id", "name"}
-
-
-class ProviderError(RuntimeError):
- """provider 调用失败。错误文本里不得出现 API Key。"""
-
-
-class CancelledError(RuntimeError):
- """用户取消了这次对话。"""
-
-
-@dataclass
-class Completion:
- content: str = ""
- reasoning: str = ""
- tool_calls: list[dict] = field(default_factory=list)
- finish_reason: str = ""
- usage: dict | None = None
-
-
-def load_providers() -> list[dict]:
- path = Path(__file__).with_name("providers.json")
- data = json.loads(path.read_text(encoding="utf-8"))
- return list(data.get("providers") or [])
-
-
-def find_provider(provider_id: str) -> dict | None:
- for item in load_providers():
- if item.get("id") == provider_id:
- return dict(item)
- return None
-
-
-def validate_base_url(url: str) -> str:
- """公网只许 https;http 只许本机回环,防止把密钥送到明文公网。"""
- value = (url or "").strip().rstrip("/")
- if not value:
- raise ProviderError("自定义端点缺少 base URL")
- parsed = urlparse(value)
- if parsed.scheme not in ("http", "https"):
- raise ProviderError("base URL 只支持 http/https")
- if parsed.username or parsed.password:
- raise ProviderError("base URL 里不要带凭据")
- if not parsed.hostname:
- raise ProviderError("base URL 缺少主机名")
- if parsed.scheme == "http" and parsed.hostname not in LOOPBACK_HOSTS:
- raise ProviderError("公网 base URL 必须是 https;http 只接受 127.0.0.1 / localhost / ::1")
- return value
-
-
-def strip_reasoning(messages: list[dict]) -> list[dict]:
- return [{k: v for k, v in m.items() if k in HISTORY_KEYS} for m in messages]
-
-
-def apply_reasoning(payload: dict, provider: dict, model: str, depth: str) -> dict:
- """把界面的「中/高/最大」翻成各服务商认识的思考参数。
-
- 预设里写清楚哪一档映射到什么值;不认识的模型名走 fallback(例如 Kimi K2.x
- 只认 thinking.type)。自定义端点由调用方决定是否发送,避免给不支持的端点塞参数。
- """
- spec = provider.get("reasoning") or {}
- if not depth or not spec:
- return payload
- patterns = [str(p) for p in (spec.get("models") or [])]
- if patterns and not any(model.startswith(p) for p in patterns):
- fallback = spec.get("fallback") or {}
- if isinstance(fallback, dict):
- payload.update(fallback)
- return payload
- value = (spec.get("map") or {}).get(depth)
- if value:
- payload[str(spec.get("param") or "reasoning_effort")] = value
- return payload
-
-
-def chat_url(base_url: str) -> str:
- base = validate_base_url(base_url)
- if base.endswith("/chat/completions"):
- return base
- return base + "/chat/completions"
-
-
-def _retry_delay(exc: error.HTTPError, attempt: int) -> float:
- raw = (exc.headers.get("Retry-After") or "").strip() if exc.headers else ""
- try:
- return max(0.0, min(10.0, float(raw)))
- except ValueError:
- return 1.0 * (attempt + 1)
-
-
-def _short(text: str, limit: int = 300) -> str:
- text = " ".join((text or "").split())
- return text if len(text) <= limit else text[:limit] + "…"
-
-
-def _post_stream(payload: dict, api_key: str, url: str):
- body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
- headers = {
- "Content-Type": "application/json",
- "Accept": "text/event-stream",
- "User-Agent": "mathmodel-studio/0.2",
- }
- if api_key:
- headers["Authorization"] = f"Bearer {api_key}"
- req = request.Request(url, data=body, headers=headers, method="POST")
-
- for attempt in range(MAX_ATTEMPTS):
- try:
- return request.urlopen(req, timeout=TIMEOUT_SECONDS)
- except error.HTTPError as exc:
- detail = ""
- try:
- detail = _short(exc.read(4096).decode("utf-8", "replace"))
- except OSError:
- pass
- if exc.code in RETRYABLE and attempt < MAX_ATTEMPTS - 1:
- time.sleep(_retry_delay(exc, attempt))
- continue
- raise ProviderError(f"provider 返回 HTTP {exc.code}{(':' + detail) if detail else ''}") from exc
- except error.URLError as exc:
- if attempt < MAX_ATTEMPTS - 1:
- time.sleep(1.0 * (attempt + 1))
- continue
- raise ProviderError(f"连不上 provider:{exc.reason}") from exc
- raise ProviderError("服务商连续重试后仍失败")
-
-
-def stream_completion(
- provider: dict,
- api_key: str,
- model: str,
- messages: list[dict],
- tools: list[dict] | None,
- on_delta,
- should_stop,
- depth: str = "",
-) -> Completion:
- """跑一次流式补全。on_delta(kind, text) 会收到 token 或 reasoning。"""
- base = provider.get("base_url") or ""
- url = chat_url(base)
- payload: dict = {
- "model": model,
- "messages": strip_reasoning(messages),
- "stream": True,
- }
- if tools:
- payload["tools"] = tools
- apply_reasoning(payload, provider, model, depth)
-
- completion = Completion()
- tool_slots: dict[int, dict] = {}
- reasoning_field = provider.get("reasoning_field") or "reasoning_content"
-
- resp = _post_stream(payload, api_key, url)
- with resp:
- for raw in resp:
- if should_stop():
- raise CancelledError()
- line = raw.decode("utf-8", "replace").strip()
- if not line or line.startswith(":"):
- continue
- if not line.startswith("data:"):
- continue
- data = line[5:].strip()
- if data == "[DONE]":
- break
- try:
- chunk = json.loads(data)
- except json.JSONDecodeError:
- continue
- if chunk.get("usage"):
- completion.usage = chunk["usage"]
- for choice in chunk.get("choices") or []:
- delta = choice.get("delta") or {}
- text = delta.get("content")
- if text:
- completion.content += text
- on_delta("token", text)
- thought = delta.get(reasoning_field) or delta.get("reasoning_content") or delta.get("reasoning")
- if thought:
- completion.reasoning += thought
- on_delta("reasoning", thought)
- for call in delta.get("tool_calls") or []:
- idx = int(call.get("index") or 0)
- slot = tool_slots.setdefault(
- idx,
- {"id": "", "type": "function", "function": {"name": "", "arguments": ""}},
- )
- if call.get("id"):
- slot["id"] = call["id"]
- fn = call.get("function") or {}
- if fn.get("name"):
- slot["function"]["name"] = fn["name"]
- args = fn.get("arguments")
- if args:
- if isinstance(args, str):
- slot["function"]["arguments"] += args
- else:
- slot["function"]["arguments"] += json.dumps(args, ensure_ascii=False)
- if choice.get("finish_reason"):
- completion.finish_reason = str(choice["finish_reason"])
- completion.tool_calls = [tool_slots[i] for i in sorted(tool_slots) if tool_slots[i]["function"]["name"]]
- return completion
-
-
-def _sleep_checked(seconds: float, should_stop) -> None:
- end = time.monotonic() + seconds
- while time.monotonic() < end:
- if should_stop():
- raise CancelledError()
- time.sleep(min(0.02, max(0.0, end - time.monotonic())))
-
-
-def _fake_stage_text(stage: str, messages: list[dict]) -> str | None:
- """编排阶段的脚本化响应:内容与确定性路径同源,离线演示不冒充模型判断。"""
- from . import baseline, orchestrator # 局部 import:避免模块级循环依赖
-
- if stage == "k2-problem":
- user = next((str(m.get("content") or "") for m in messages if m.get("role") == "user"), "")
- # 提示词模板形如「题面:\n…\n\n附件清单:…」;只取题面段,别把标签当题目。
- problem = user.split("\n\n附件清单:", 1)[0]
- if problem.startswith("题面:\n"):
- problem = problem[len("题面:\n"):]
- questions = orchestrator.split_questions(orchestrator.question_source(problem))
- names = orchestrator.attachment_names(problem)
- return json.dumps(
- {
- "questions": [
- {"id": f"q{i + 1}", "text": text, "data": "未附数据文件"}
- for i, text in enumerate(questions)
- ],
- "dataRoles": [],
- "warning": (
- "离线演示:数据角色核对未接入,附件正文已并入题面。"
- if names
- else "离线演示:未附数据文件,确认后按文字题面继续。"
- ),
- },
- ensure_ascii=False,
- )
- if stage == "k3-models":
- user = next((str(m.get("content") or "") for m in messages if m.get("role") == "user"), "")
- problem = user.split("\n\n附件清单:", 1)[0]
- if problem.startswith("题面:\n"):
- problem = problem[len("题面:\n"):]
- return json.dumps({"candidates": orchestrator.model_candidates(problem)}, ensure_ascii=False)
- if stage == "p4-code":
- return json.dumps(
- {"rationale": "离线演示:使用内置基线脚本,接真实模型后这里会按题生成代码。", "code": baseline.SCRIPT},
- ensure_ascii=False,
- )
- if stage == "p5-paper":
- # 离线兜底:演示样例稿(三门禁全绿)。编排层会在对话里标明是兜底。
- sample = Path(__file__).with_name("paper_sample") / "paper.tex"
- try:
- return sample.read_text(encoding="utf-8")
- except OSError:
- return None
- if stage == "p6-score":
- import re
-
- from . import score_gen
-
- user = next((str(m.get("content") or "") for m in messages if m.get("role") == "user"), "")
- match = re.search(r"第\s*(\d+)\s*轮", user)
- round_no = int(match.group(1)) if match else 1
- return json.dumps(score_gen.demo_card(round_no), ensure_ascii=False)
- return None
-
-
-def fake_completion(messages: list[dict], on_delta, should_stop, delay: float = 0.02) -> Completion:
- """仅测试与离线演示:不发任何网络请求。由 MMS_FAKE_PROVIDER=1 显式启用。"""
- from .llm import stage_of
-
- stage = stage_of(messages)
- if stage:
- text = _fake_stage_text(stage, messages)
- if text is not None:
- for i in range(0, len(text), 512):
- _sleep_checked(delay, should_stop)
- on_delta("token", text[i : i + 512])
- return Completion(content=text, finish_reason="stop")
-
- if any(m.get("role") == "tool" for m in messages):
- final = (
- "离线演示:共 25 个模板,20 张图表(matplotlib)+ 5 张示意图(JSON 驱动)。"
- "这条回复来自本地假 provider,用来验证流式通道与工具卡;接真实模型后这里会换成模型自己的话。"
- )
- for i in range(0, len(final), 6):
- _sleep_checked(delay, should_stop)
- piece = final[i : i + 6]
- on_delta("token", piece)
- return Completion(content=final, finish_reason="stop")
-
- for piece in ("先确认一下本机能列出哪些模板。", "这一步只读注册表,不联网。"):
- _sleep_checked(delay, should_stop)
- on_delta("reasoning", piece)
- intro = "我先查一下模板清单。"
- for i in range(0, len(intro), 4):
- _sleep_checked(delay, should_stop)
- on_delta("token", intro[i : i + 4])
- return Completion(
- content=intro,
- finish_reason="tool_calls",
- tool_calls=[
- {
- "id": "call_fake_templates",
- "type": "function",
- "function": {"name": "list_templates", "arguments": "{}"},
- }
- ],
- )
diff --git a/runtime/src/mms/registry.py b/runtime/src/mms/registry.py
deleted file mode 100644
index 73ac34d..0000000
--- a/runtime/src/mms/registry.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""技能注册表与仓库根定位。
-
-单一事实源是 skills/manifest.json。运行时的安装形态(pip install -e、便携包、
-打包后的只读资源目录)会让「向上找 VERSION」不可靠,所以显式支持 MMS_HOME 覆盖。
-"""
-
-from __future__ import annotations
-
-import json
-import os
-from pathlib import Path
-
-MANIFEST_RELPATH = Path("skills") / "manifest.json"
-
-EXIT_OK = 0
-EXIT_VALIDATION_FAILED = 1
-EXIT_USAGE_OR_ENV = 2
-
-
-def repo_root() -> Path:
- override = os.environ.get("MMS_HOME")
- if override:
- root = Path(override).expanduser()
- if not (root / MANIFEST_RELPATH).is_file():
- raise EnvError(f"MMS_HOME 指向的目录下没有 {MANIFEST_RELPATH.as_posix()}: {root}")
- return root
- here = Path(__file__).resolve()
- for candidate in here.parents:
- if (candidate / MANIFEST_RELPATH).is_file():
- return candidate
- raise EnvError(f"从 {here} 向上没找到含 {MANIFEST_RELPATH.as_posix()} 的仓库根")
-
-
-class EnvError(RuntimeError):
- """环境或用法错误:对应退出码 2,与校验失败(1)严格区分。"""
-
-
-def load_manifest(root: Path | None = None) -> dict:
- path = (root or repo_root()) / MANIFEST_RELPATH
- with path.open(encoding="utf-8") as fh:
- return json.load(fh)
-
-
-def skills(manifest: dict) -> list[dict]:
- return list(manifest.get("skills") or [])
-
-
-def minimal_validate(manifest: dict) -> list[str]:
- """无 jsonschema 时的最小结构校验;返回问题列表,空列表即通过。
-
- 与 kit 的降级口径一致:缺库不装死,但会说明只跑了最小校验。
- """
- problems: list[str] = []
- required_top = (
- "manifest_version",
- "schema_version",
- "title",
- "description",
- "kinds",
- "status",
- "contribution",
- "cli_contract",
- "phases",
- "skills",
- )
- for key in required_top:
- if key not in manifest:
- problems.append(f"缺顶层字段: {key}")
- entries = manifest.get("skills")
- if not isinstance(entries, list) or not entries:
- problems.append("skills 必须是非空数组")
- return problems
- allowed_phases = set(manifest.get("phases") or [])
- allowed_artifacts = set((manifest.get("artifact_kinds") or {}).keys())
- allowed_hitl = set((manifest.get("hitl_card_kinds") or {}).keys())
- seen: set[str] = set()
- for s in entries:
- name = s.get("name", "")
- if not name:
- problems.append("有技能缺 name")
- continue
- if name in seen:
- problems.append(f"技能名重复: {name}")
- seen.add(name)
- for key in ("kind", "role", "entry", "contribution", "status", "ui"):
- if key not in s:
- problems.append(f"{name}: 缺 {key}")
- # 枚举必须在降级路径上同样把住:C3 反向覆盖实测出这里曾经放过非法 kind
- if s.get("kind") not in ("core", "knowledge", "tool"):
- problems.append(f"{name}: kind 非法 {s.get('kind')!r}")
- if s.get("contribution") not in ("open", "maintainer"):
- problems.append(f"{name}: contribution 非法 {s.get('contribution')!r}")
- if s.get("status") not in ("planned", "vendored"):
- problems.append(f"{name}: status 非法 {s.get('status')!r}")
- if not s.get("entry"):
- problems.append(f"{name}: 缺 entry")
- ui = s.get("ui") or {}
- phases = ui.get("phases") or []
- if not phases:
- problems.append(f"{name}: ui.phases 为空")
- bad = [p for p in phases if p not in allowed_phases]
- if bad:
- problems.append(f"{name}: 阶段越界 {bad}")
- bad_art = [a for a in (ui.get("artifacts") or []) if a not in allowed_artifacts]
- if bad_art:
- problems.append(f"{name}: 产物类型不在词表 {bad_art}")
- bad_hitl = [h for h in (ui.get("hitl") or []) if h not in allowed_hitl]
- if bad_hitl:
- problems.append(f"{name}: 卡点不在词表 {bad_hitl}")
- return problems
diff --git a/runtime/src/mms/score_gen.py b/runtime/src/mms/score_gen.py
deleted file mode 100644
index 48f2be4..0000000
--- a/runtime/src/mms/score_gen.py
+++ /dev/null
@@ -1,151 +0,0 @@
-"""阶段六 · 真实评分:LLM 按 rubric 评审论文 → score_card.py 校验渲染。
-
-评分卡是数据:维度固定五项(摘要 30 / 模型 20 / 创新 20 / 写作 15 / 排版 15),
-扣分必须带正文定位与改法。总分 ≥85 且无一票否决才算达标;
-一票否决(身份信息/页眉等红线)直接淘汰、不进优化循环。
-
-离线兜底:没有可用模型时用演示评分卡,调用方必须标明是兜底。
-"""
-
-from __future__ import annotations
-
-import json
-from collections.abc import Callable
-from pathlib import Path
-
-from . import llm
-from .registry import repo_root
-
-P6_INSTRUCTION = (
- "你是数学建模竞赛的论文评审专家。按评分口径对给定论文逐项评分,"
- "只输出一个 JSON 对象,不要围栏、不要解释,形状:"
- '{"paper":"论文题目","round":1,"veto":false,"dimensions":['
- '{"id":"abstract","score":24,"deductions":[{"item":"扣分项","penalty":4,"note":"依据",'
- '"target":"正文位置(如 摘要第2段 / 4.2 参数设置)","suggestion":"具体改法"}]},'
- '{"id":"model","score":16,"deductions":[]},{"id":"innovation","score":13,"deductions":[]},'
- '{"id":"writing","score":12,"deductions":[]},{"id":"layout","score":13,"deductions":[]}]}。'
- "五个维度缺一不可:abstract 满分 30、model 满分 20、innovation 满分 20、writing 满分 15、layout 满分 15;"
- "score 为 0 到满分之间的数值,各维度扣分合计应等于满分减得分;"
- "每条扣分必须给 target(论文中的具体位置)与 suggestion(可执行的改法),禁止空泛评语。"
- "发现身份信息、页眉违规等红线时 veto 置 true。"
- "评分必须基于论文实际内容,禁止编造论文里没有的问题;修复轮会附上上一轮扣分与修改后的论文,请重新评审。"
-)
-
-DIMENSIONS = {
- "abstract": 30,
- "model": 20,
- "innovation": 20,
- "writing": 15,
- "layout": 15,
-}
-MAX_TEX_CHARS = 24000
-
-
-def _rubric(root: Path) -> str:
- path = root / "skills" / "mathmodel-score" / "docs" / "rubric.md"
- try:
- return path.read_text(encoding="utf-8")[:4000]
- except OSError:
- return ""
-
-
-def build_context(tex: str, round_no: int, root: Path | None = None, prev_card: dict | None = None) -> str:
- root = root or repo_root()
- parts = [
- f"评分口径(rubric 节选):\n{_rubric(root)}",
- f"待评审论文(第 {round_no} 轮):\n{tex[:MAX_TEX_CHARS]}",
- ]
- if prev_card:
- parts.append(
- "上一轮评分卡(论文已按扣分修改,请重新评审并给出本轮分数):\n"
- + json.dumps(prev_card, ensure_ascii=False)[:4000]
- )
- return "\n\n".join(parts)
-
-
-def _validate_card(data: dict) -> dict:
- dims = data.get("dimensions")
- if not isinstance(dims, list):
- raise ValueError("dimensions 必须是数组")
- seen: dict[str, dict] = {}
- for entry in dims:
- if not isinstance(entry, dict):
- raise ValueError("维度必须是对象")
- did = entry.get("id")
- if did not in DIMENSIONS:
- raise ValueError(f"未知维度: {did}")
- if did in seen:
- raise ValueError(f"维度重复: {did}")
- score = entry.get("score")
- if not isinstance(score, (int, float)) or isinstance(score, bool):
- raise ValueError(f"维度 {did} 的 score 必须是数值")
- if not 0 <= score <= DIMENSIONS[did]:
- raise ValueError(f"维度 {did} 的 score 超出 0–{DIMENSIONS[did]}")
- deductions = entry.get("deductions") or []
- if not isinstance(deductions, list):
- raise ValueError(f"维度 {did} 的 deductions 必须是数组")
- clean = []
- for item in deductions:
- if not isinstance(item, dict) or not str(item.get("item") or "").strip():
- raise ValueError(f"维度 {did} 的扣分项缺少 item")
- penalty = item.get("penalty")
- if not isinstance(penalty, (int, float)) or isinstance(penalty, bool) or penalty < 0:
- raise ValueError(f"维度 {did} 的扣分 penalty 必须是非负数值")
- clean.append(
- {
- "item": str(item["item"]).strip()[:200],
- "penalty": float(penalty),
- "note": str(item.get("note") or "").strip()[:300],
- "target": str(item.get("target") or "").strip()[:120],
- "suggestion": str(item.get("suggestion") or "").strip()[:300],
- }
- )
- seen[did] = {"id": did, "score": float(score), "deductions": clean}
- missing = set(DIMENSIONS) - set(seen)
- if missing:
- raise ValueError(f"缺少维度: {sorted(missing)}")
- return {
- "paper": str(data.get("paper") or "赛题论文").strip()[:120],
- "round": int(data.get("round") or 1),
- "veto": data.get("veto") is True,
- "dimensions": [seen[did] for did in DIMENSIONS],
- }
-
-
-def generate(
- provider: dict | None,
- api_key: str,
- model: str,
- tex: str,
- round_no: int,
- root: Path | None = None,
- prev_card: dict | None = None,
- should_stop: Callable[[], bool] | None = None,
- on_delta: Callable[[str, str], None] | None = None,
-) -> tuple[dict, str]:
- """调模型评审,返回 (评分卡, 来源)。失败抛 LlmError。"""
- context = build_context(tex, round_no, root, prev_card)
- card = llm.complete_json(
- provider, api_key, model, "p6-score", P6_INSTRUCTION, context, _validate_card,
- should_stop=should_stop, on_delta=on_delta,
- )
- card["round"] = round_no
- source = "fallback" if (provider or {}).get("id") == "fake" else "llm"
- return card, source
-
-
-def demo_card(round_no: int = 1) -> dict:
- """离线兜底:演示评分卡(标注兜底,不冒充真实评审)。
-
- 优先取演示里的达标轮,让离线链路能走完;真实评审才产生逐轮分数。
- """
- from .workbench_score import DEMO_SCORES
-
- demo = json.loads(DEMO_SCORES.read_text(encoding="utf-8"))
- rounds = demo.get("rounds") or []
- passing = [c for c in rounds if sum(d.get("score", 0) for d in c.get("dimensions", [])) >= 85]
- pool = passing or rounds
- card = next((c for c in pool if c.get("round") == round_no), pool[0] if pool else {})
- card = json.loads(json.dumps(card))
- card["round"] = round_no
- return card
\ No newline at end of file
diff --git a/runtime/src/mms/server.py b/runtime/src/mms/server.py
deleted file mode 100644
index dd2d00a..0000000
--- a/runtime/src/mms/server.py
+++ /dev/null
@@ -1,1040 +0,0 @@
-"""本机通道服务器:stdout 握手,此后只走 127.0.0.1 HTTP + SSE。
-
-为什么不是 stdio JSON-RPC:SSE 自带事件 id 与断线续传语义,主进程只需转发;
-端口与 token 由子进程生成并只交给父进程,渲染层既拿不到端口也拿不到 token。
-
-安全边界:
-- 只绑 127.0.0.1,每个请求校验 Host 与 Origin(防 DNS rebinding)。
-- 每个请求校验 Bearer token(防同机其他进程顺手调用)。
-- API Key 按次传入,不落盘、不写日志、不放进任何事件。
-"""
-
-from __future__ import annotations
-
-import hmac
-import json
-import os
-import secrets
-import signal
-import sys
-import threading
-import time
-import traceback
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from pathlib import Path
-from urllib.parse import parse_qs, urlparse
-
-from . import __version__, harness, orchestrator
-from .invoke import list_templates
-from .store import SessionStore, data_dir, session_scope, snapshot
-from . import paper_build, project_export, workbench_figure, workbench_score
-from .provider import (
- CancelledError,
- ProviderError,
- fake_completion,
- find_provider,
- load_providers,
- stream_completion,
- validate_base_url,
-)
-from .registry import EnvError
-
-MAX_BODY = 16 << 20
-MAX_MESSAGES = 200
-MAX_TOTAL_CHARS = 1_600_000
-MAX_TOOL_RESULT_CHARS = 8_000
-TOOL_ROUNDS = 8
-PING_SECONDS = 15
-DEPTHS = ("medium", "high", "max")
-
-SYSTEM_PROMPT = (
- "你是 mathmodel-studio 的数学建模助手。工具返回的数据以工具结果为准,不要编造没有运行过的结果;"
- "回答简洁,关键判断留给使用者确认。"
-)
-
-TOOLS = [
- {
- "type": "function",
- "function": {
- "name": "list_templates",
- "description": "列出本机技能内置的图表与示意图模板(只读注册表,不渲染)。",
- "parameters": {"type": "object", "properties": {}, "additionalProperties": False},
- },
- },
- {
- "type": "function",
- "function": {
- "name": "suggest_models",
- "description": (
- "用户讨论该用什么模型/方法时调用:向界面推送三张可选模型卡,由用户自己点选。"
- "用户要求换一批时,把 batch 加 1 再调用;不要替用户做选择,也不要编造用户已选。"
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "question": {
- "type": "string",
- "description": "要建模的子问题或用户原话;省略时用最近一条用户消息。",
- },
- "batch": {
- "type": "integer",
- "minimum": 1,
- "maximum": 9,
- "description": "第几批候选,默认 1;换一批时递增。",
- },
- },
- "additionalProperties": False,
- },
- },
- },
-]
-
-
-def fake_enabled() -> bool:
- return os.environ.get("MMS_FAKE_PROVIDER") == "1"
-
-
-def core_name() -> str:
- """对话内核:0.2.0 起只有自研 Python 内核(DSH 双内核已移除)。"""
- return "python"
-
-
-def provider_rows(fake: bool | None = None) -> list[dict]:
- rows = [dict(p) for p in load_providers()]
- for row in rows:
- row.setdefault("requires_key", True)
- if fake is None:
- fake = fake_enabled()
- if fake:
- rows.insert(
- 0,
- {
- "id": "fake",
- "display": "离线演示(不联网)",
- "base_url": "",
- "auth_style": "none",
- "models": ["fake-stream"],
- "tool_calling": True,
- "streaming_tools": True,
- "context_len": 4096,
- "max_out": 1024,
- "requires_key": False,
- "custom": False,
- "note": "只在 MMS_FAKE_PROVIDER=1 时出现,用于验证通道与工具卡。",
- },
- )
- return rows
-
-
-def run_tool(name: str, args: dict | None, context: str = "") -> tuple[dict, bool]:
- if name == "list_templates":
- try:
- rows = list_templates()
- except (EnvError, OSError, json.JSONDecodeError) as exc:
- return {"ok": False, "error": str(exc)}, False
- counts: dict[str, int] = {}
- for row in rows:
- counts[row["skill"]] = counts.get(row["skill"], 0) + 1
- return {"ok": True, "total": len(rows), "by_skill": counts, "templates": rows}, True
- if name == "suggest_models":
- args = args or {}
- question = str(args.get("question") or context or "").strip()
- if not question:
- return {"ok": False, "error": "没有可用的建模问题文本"}, False
- try:
- batch = int(args.get("batch") or 1)
- except (TypeError, ValueError):
- batch = 1
- batch = min(max(batch, 1), 9)
- candidates = orchestrator.model_candidates(question, batch)
- return {"ok": True, "batch": batch, "candidates": candidates}, True
- return {"ok": False, "error": f"未知工具: {name}"}, False
-
-
-def normalize_messages(raw) -> list[dict]:
- if not isinstance(raw, list) or not raw:
- raise ValueError("消息必须是非空数组")
- if len(raw) > MAX_MESSAGES:
- raise ValueError(f"消息超过 {MAX_MESSAGES} 条")
- out: list[dict] = []
- total = 0
- for item in raw:
- if not isinstance(item, dict):
- raise ValueError("消息每一项必须是对象")
- role = item.get("role")
- content = item.get("content")
- if role not in ("user", "assistant", "system"):
- raise ValueError(f"不支持的消息角色: {role!r}")
- if not isinstance(content, str):
- raise ValueError("消息 content 必须是字符串")
- total += len(content)
- if total > MAX_TOTAL_CHARS:
- raise ValueError("消息总长度超过上限")
- out.append({"role": role, "content": content})
- if not any(m["role"] == "user" for m in out):
- raise ValueError("至少需要一条 user 消息")
- if out[0]["role"] != "system":
- out.insert(0, {"role": "system", "content": SYSTEM_PROMPT})
- return out
-
-
-def estimate_tokens(text: str) -> int:
- """兼容旧调用点;真正的实现在 harness 里。"""
- return harness.estimate_tokens(text)
-
-
-class ChatSession:
- """一次对话:后台线程写事件,SSE 订阅者按 id 续读。"""
-
- def __init__(
- self,
- chat_id: str,
- provider: dict,
- api_key: str,
- model: str,
- messages: list[dict],
- depth: str = "",
- context_tokens: int | None = None,
- send_thinking: bool = True,
- goal: str = "",
- workspace: str = "",
- ):
- self.id = chat_id
- self.provider = provider
- self.api_key = api_key
- self.model = model
- self.messages = messages
- self.depth = depth if send_thinking else ""
- self.context_tokens = context_tokens
- self.goal = goal
- self.workspace = workspace
- self.events: list[dict] = []
- self.cond = threading.Condition()
- self.done = False
- self.cancelled = False
- self.reason = ""
- self.usage: dict | None = None
- self.thread = threading.Thread(target=self._run, name=f"chat-{chat_id}", daemon=True)
-
- def start(self) -> None:
- self.thread.start()
-
- def should_stop(self) -> bool:
- return self.cancelled
-
- def append(self, event: str, data: dict) -> None:
- with self.cond:
- if self.done:
- return
- eid = len(self.events) + 1
- self.events.append({"id": str(eid), "event": event, "data": data})
- self.cond.notify_all()
-
- def finish(self, reason: str, usage: dict | None = None) -> None:
- with self.cond:
- if self.done:
- return
- self.done = True
- self.reason = reason
- self.usage = usage
- payload = {"reason": reason}
- if usage:
- payload["usage"] = usage
- eid = len(self.events) + 1
- self.events.append({"id": str(eid), "event": "done", "data": payload})
- self.cond.notify_all()
-
- def cancel(self) -> None:
- with self.cond:
- if self.done:
- return
- self.cancelled = True
- self.cond.notify_all()
- # 不在这里 finish:worker 可能在一次工具调用中间,由它收尾,
- # 这样 done 一定排在最后一个真实事件之后。
-
- def _pause(self, seconds: float) -> None:
- end = time.monotonic() + max(0.0, seconds)
- while time.monotonic() < end:
- if self.cancelled:
- raise CancelledError()
- time.sleep(min(0.02, max(0.0, end - time.monotonic())))
-
- def _context_plan(
- self, ratio: float = harness.COMPACT_RATIO, reason: str = "auto"
- ) -> harness.Plan:
- turn = sum(1 for message in self.messages if message.get("role") == "user")
- extra = [f"工作区:{self.workspace}"] if self.workspace else []
- anchor = harness.anchor_text(self.goal, turn, extra)
- return harness.prepare(
- self.messages, self.context_tokens, anchor=anchor, ratio=ratio, reason=reason
- )
-
- def _apply_plan(self, plan: harness.Plan) -> None:
- self.messages = plan.messages
- if plan.reason:
- self.append("compaction", plan.event())
-
- def _complete(self, tools, deltas):
- recovered = False
- while True:
- if self.cancelled:
- raise CancelledError()
- try:
- if self.provider.get("id") == "fake":
- try:
- delay = max(0.0, float(os.environ.get("MMS_FAKE_DELAY_MS") or "20") / 1000)
- except ValueError:
- delay = 0.02
- return fake_completion(self.messages, deltas, self.should_stop, delay)
- return stream_completion(
- self.provider,
- self.api_key,
- self.model,
- self.messages,
- tools,
- deltas,
- self.should_stop,
- depth=self.depth,
- )
- except ProviderError as exc:
- if recovered or not harness.looks_like_overflow(str(exc)):
- raise
- # provider 报上下文溢出:压得更狠再试一次,别把错误直接甩给用户。
- recovered = True
- self._apply_plan(
- self._context_plan(ratio=harness.OVERFLOW_RATIO, reason="overflow")
- )
-
- def _tool_context(self) -> str:
- for message in reversed(self.messages):
- if message.get("role") == "user" and isinstance(message.get("content"), str):
- return message["content"]
- return ""
-
- def _run(self) -> None:
- tools = TOOLS if self.provider.get("tool_calling") else None
- self._apply_plan(self._context_plan())
- seen: dict[str, dict] = {}
- try:
- for _round in range(TOOL_ROUNDS):
- if self.cancelled:
- raise CancelledError()
- deltas = lambda kind, text: self.append(kind, {"text": text})
- completion = self._complete(tools, deltas)
- if not completion.tool_calls:
- self.finish("stop", completion.usage)
- return
- self.messages.append(
- {
- "role": "assistant",
- "content": completion.content or None,
- "tool_calls": completion.tool_calls,
- }
- )
- for call in completion.tool_calls:
- if self.cancelled:
- raise CancelledError()
- call_id = call.get("id") or f"call_{secrets.token_hex(4)}"
- fn = call.get("function") or {}
- name = fn.get("name") or ""
- raw_args = fn.get("arguments") or "{}"
- try:
- args = json.loads(raw_args) if raw_args.strip() else {}
- except json.JSONDecodeError:
- args = None
- shown = args if args is not None else raw_args
- self.append("tool_call", {"id": call_id, "name": name, "status": "running", "args": shown})
- started = time.monotonic()
- if args is None:
- result, ok = {"ok": False, "error": "工具参数不是合法 JSON"}, False
- else:
- key = f"{name}:{json.dumps(args, sort_keys=True, ensure_ascii=False)}"
- if key in seen:
- result = {**seen[key], "note": "重复调用,返回上次结果"}
- ok = bool(seen[key].get("ok"))
- else:
- result, ok = run_tool(name, args, self._tool_context())
- seen[key] = result
- duration = int((time.monotonic() - started) * 1000)
- self.append(
- "tool_call",
- {
- "id": call_id,
- "name": name,
- "status": "ok" if ok else "error",
- "args": shown,
- "result": result,
- "duration_ms": duration,
- },
- )
- if name == "suggest_models" and ok:
- # 卡片是给界面的插层,工具结果仍照常回给模型。
- self.append(
- "interrupt",
- {
- "card": "model-choice",
- "payload": {
- "title": "算法选择",
- "intro": "这三条路线来自本机方法库;点一张卡就按它继续,也可以再换一批。",
- "batch": result.get("batch", 1),
- "candidates": result.get("candidates", []),
- },
- },
- )
- content = json.dumps(result, ensure_ascii=False)
- if len(content) > MAX_TOOL_RESULT_CHARS:
- content = content[:MAX_TOOL_RESULT_CHARS] + "…[工具结果已截断]"
- self.messages.append(
- {
- "role": "tool",
- "tool_call_id": call_id,
- "name": name,
- "content": content,
- }
- )
- # 工具结果可能把上下文推过阈值:下一轮之前再压一次。
- if self.context_tokens:
- self._apply_plan(self._context_plan())
- self.finish("max_tool_rounds")
- except CancelledError:
- self.finish("cancelled")
- except ProviderError as exc:
- self.append("error", {"message": str(exc)})
- self.finish("error")
- except Exception:
- # 堆栈只进 stderr;事件里不回显请求体或密钥。
- traceback.print_exc(file=sys.stderr)
- self.append("error", {"message": "运行时内部错误,详情见 stderr"})
- self.finish("error")
-
-
-class WorkflowSession(ChatSession):
- """编排会话:复用事件缓冲与 SSE 语义,内容由状态机产生。
-
- provider/api_key/model 按次传入:K2/K3 由 LLM 生产内容,
- 没有 Key 时状态机回退确定性路径。Key 不进 store、不进事件。
- """
-
- def __init__(
- self,
- chat_id: str,
- store: SessionStore,
- record: dict,
- action: str,
- choice: str,
- workspace: str = "",
- provider: dict | None = None,
- api_key: str = "",
- model: str = "",
- depth: str = "",
- ):
- super().__init__(chat_id, provider or {}, api_key, model, [], workspace=workspace)
- self.store = store
- self.record = record
- self.action = action
- self.choice = choice
- self.depth = depth
-
- def _run(self) -> None:
- try:
- deltas = lambda kind, text: self.append(kind, {"text": text})
- provider = self.provider if self.provider.get("id") else None
- if self.action == "start":
- events = orchestrator.start(
- self.store, self.record,
- provider=provider, api_key=self.api_key, model=self.model,
- should_stop=self.should_stop, on_delta=deltas,
- )
- else:
- events = orchestrator.resume_iter(
- self.store, self.record, self.action, self.choice, self.workspace,
- provider=provider, api_key=self.api_key, model=self.model,
- should_stop=self.should_stop, on_delta=deltas,
- )
- for ev in events:
- if self.cancelled:
- raise CancelledError()
- delay = ev.get("delay")
- if delay:
- self._pause(float(delay))
- self.append(ev["event"], ev["data"])
- # 状态机跑完后仍挂着待决卡(K2/K3/代码确认)就是等待用户,不是结束。
- self.finish("waiting" if self.record.get("pending") else "stop")
- except CancelledError:
- self.finish("cancelled")
- except ValueError as exc:
- self.append("error", {"message": str(exc)})
- self.finish("error")
- except Exception:
- traceback.print_exc(file=sys.stderr)
- self.append("error", {"message": "编排状态机内部错误,详情见 stderr"})
- self.finish("error")
-
-
-class ChannelServer(ThreadingHTTPServer):
- daemon_threads = True
- allow_reuse_address = True
-
- def __init__(self, address, handler, token: str, fake: bool, store: SessionStore, root: Path):
- super().__init__(address, handler)
- self.token = token
- self.fake = fake
- self.store = store
- self.root = root
- self.sessions: dict[str, ChatSession] = {}
- self.sessions_lock = threading.Lock()
-
-
-class Handler(BaseHTTPRequestHandler):
- protocol_version = "HTTP/1.1"
- server: ChannelServer
-
- def log_message(self, fmt: str, *args) -> None:
- # 只记方法/路径/状态;不记 header 与 body,密钥没有机会进日志。
- sys.stderr.write("[mms] %s\n" % (fmt % args))
-
- def _json(self, status: int, payload: dict) -> None:
- body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
- self.send_response(status)
- self.send_header("Content-Type", "application/json; charset=utf-8")
- self.send_header("Content-Length", str(len(body)))
- self.send_header("Cache-Control", "no-store")
- self.end_headers()
- self.wfile.write(body)
-
- def _error(self, status: int, code: str, message: str) -> None:
- self._json(status, {"ok": False, "error": {"code": code, "message": message}})
-
- def _guard(self) -> bool:
- port = self.server.server_address[1]
- allowed_hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
- host = (self.headers.get("Host") or "").strip()
- if host not in allowed_hosts:
- self._error(403, "host", "Host 不在回环白名单")
- return False
- origin = (self.headers.get("Origin") or "").strip()
- if origin and origin not in {f"http://{h}" for h in allowed_hosts}:
- self._error(403, "origin", "Origin 不在回环白名单")
- return False
- auth = (self.headers.get("Authorization") or "").strip()
- expected = f"Bearer {self.server.token}"
- if not hmac.compare_digest(auth, expected):
- self._error(401, "auth", "缺少或错误的 token")
- return False
- return True
-
- def _body(self) -> dict | None:
- try:
- length = int(self.headers.get("Content-Length") or "0")
- except ValueError:
- self._error(400, "body", "Content-Length 非法")
- return None
- if length <= 0 or length > MAX_BODY:
- self._error(400, "body", "请求体为空或过大")
- return None
- raw = self.rfile.read(length)
- try:
- data = json.loads(raw.decode("utf-8"))
- except (UnicodeDecodeError, json.JSONDecodeError):
- self._error(400, "body", "请求体不是合法 JSON")
- return None
- if not isinstance(data, dict):
- self._error(400, "body", "请求体必须是对象")
- return None
- return data
-
- def do_GET(self) -> None: # noqa: N802
- if not self._guard():
- return
- parsed = urlparse(self.path)
- if parsed.path == "/health":
- self._json(
- 200,
- {
- "ok": True,
- "version": __version__,
- "fake": self.server.fake,
- "core": core_name(),
- "pid": os.getpid(),
- },
- )
- return
- if parsed.path == "/providers":
- self._json(200, {"ok": True, "fake": self.server.fake, "providers": provider_rows(self.server.fake)})
- return
- if parsed.path == "/sessions/latest":
- self._json(200, {"ok": True, "session": snapshot(self.server.store.latest())})
- return
- if parsed.path == "/sessions":
- self._json(200, {"ok": True, "sessions": self.server.store.list_summaries()})
- return
- if parsed.path == "/workbench/state":
- raw_session = parse_qs(parsed.query).get("session", [""])[0]
- self._json(200, self._workbench(self._scope_session(raw_session)))
- return
- if parsed.path.startswith("/sessions/") and parsed.path.count("/") == 2:
- session_id = parsed.path[len("/sessions/") :]
- record = self.server.store.get(session_id)
- if not record:
- self._error(404, "session", "没有这个会话")
- return
- self._json(200, {"ok": True, "session": snapshot(record)})
- return
- if parsed.path.startswith("/chats/") and parsed.path.endswith("/events"):
- chat_id = parsed.path[len("/chats/") : -len("/events")].strip("/")
- self._stream(chat_id, parse_qs(parsed.query))
- return
- self._error(404, "not_found", "没有这个端点")
-
- def do_POST(self) -> None: # noqa: N802
- if not self._guard():
- return
- parsed = urlparse(self.path)
- if parsed.path == "/chats":
- self._start_chat()
- return
- if parsed.path.startswith("/sessions/") and parsed.path.endswith("/resume"):
- session_id = parsed.path[len("/sessions/") : -len("/resume")].strip("/")
- self._resume_session(session_id)
- return
- if parsed.path == "/workbench/render":
- self._render_figure()
- return
- if parsed.path == "/workbench/rollback":
- self._rollback_figure()
- return
- if parsed.path == "/workbench/paper/build":
- self._build_paper()
- return
- if parsed.path.startswith("/chats/") and parsed.path.endswith("/cancel"):
- chat_id = parsed.path[len("/chats/") : -len("/cancel")].strip("/")
- with self.server.sessions_lock:
- session = self.server.sessions.get(chat_id)
- if not session:
- self._error(404, "chat", "没有这个对话")
- return
- session.cancel()
- self._json(200, {"ok": True, "chatId": chat_id})
- return
- self._error(404, "not_found", "没有这个端点")
-
- def do_DELETE(self) -> None: # noqa: N802
- if not self._guard():
- return
- parsed = urlparse(self.path)
- if parsed.path == "/sessions":
- removed = self.server.store.clear()
- self._json(200, {"ok": True, "removed": removed})
- return
- if parsed.path.startswith("/sessions/") and parsed.path.count("/") == 2:
- session_id = parsed.path[len("/sessions/") :]
- if not self.server.store.delete(session_id):
- self._error(404, "session", "没有这个会话")
- return
- self._json(200, {"ok": True, "id": session_id})
- return
- self._error(404, "not_found", "没有这个端点")
-
- def _scope_session(self, raw: object) -> str:
- """工作台请求定位会话产物目录:显式 sid 优先,缺省最近会话,非法 sid 回落全局。"""
- sid = str(raw or "").strip()
- if sid:
- return sid
- record = self.server.store.latest()
- return str(record["id"]) if record else ""
-
- def _scoped_dir(self, session_id: str) -> Path:
- base = self.server.store.path.parent
- return session_scope(base, session_id) if session_id else base
-
- def _workbench(self, session_id: str = "") -> dict:
- data_root = self._scoped_dir(session_id)
- figure = workbench_figure.state_payload(self.server.root, data_root)
- try:
- # 评分优先读本会话真实轮次;没有时回落演示数据。章节门禁同样优先查本会话论文。
- score = workbench_score.state(self.server.root, data_dir=data_root)
- score["is_demo"] = not workbench_score._real_cards(data_root)
- demo_rounds, demo_veto = workbench_score.demo_rounds(self.server.root)
- score["demo"] = {"rounds": demo_rounds, "veto": demo_veto}
- chapter = score.get("chapter", {})
- round_row = next(
- (r for r in score.get("rounds", []) if r.get("round") == score.get("defaultRound")),
- None,
- )
- score_ok = bool(round_row and round_row.get("pass"))
- score_detail = (
- f"第 {round_row['round']} 轮 {round_row['total']} / 100"
- if round_row
- else (score.get("error") or "无法评分")
- )
- except Exception as exc: # 评分脚本坏掉时工作台仍能打开
- score = {"ok": False, "error": str(exc), "rounds": []}
- chapter = {"ok": False, "error": str(exc)}
- score_ok = False
- score_detail = str(exc)
- active = next(
- (v for v in figure.get("versions", []) if v.get("id") == figure.get("active")),
- None,
- )
- outputs = (active or {}).get("outputs", {})
- figure_ok = bool(active) and all(
- kind in outputs and Path(outputs[kind]).is_file() and Path(outputs[kind]).stat().st_size > 0
- for kind in ("png", "pdf", "svg")
- )
- gate = [
- {
- "id": "figure",
- "label": "图表产物",
- "ok": figure_ok,
- "detail": "PNG / PDF / SVG 齐全" if figure_ok else "尚未渲染出三件产物",
- },
- {"id": "score", "label": "评分", "ok": score_ok, "detail": score_detail},
- {
- "id": "chapter",
- "label": "章节结构",
- "ok": bool(chapter.get("pass")),
- "detail": (
- f"hard {chapter.get('hard_failed', 0)} · soft {chapter.get('soft_failed', 0)} · 人工 {chapter.get('manual', 0)}"
- if chapter.get("ok")
- else chapter.get("error", "章节自检未运行")
- ),
- },
- ]
- paper = paper_build.state(data_root, self.server.root)
- artifacts = paper.get("artifacts") or {}
- paper_ok = bool(paper.get("ok")) and {"pdf", "docx"} <= set(artifacts)
- if paper_ok:
- paper_detail = f"PDF {artifacts['pdf']['size'] // 1024} KB · DOCX {artifacts['docx']['size'] // 1024} KB"
- elif paper.get("builtAt"):
- paper_detail = paper.get("error") or "上次构建未全绿"
- else:
- paper_detail = "尚未构建论文"
- gate.append({"id": "paper", "label": "论文排版", "ok": paper_ok, "detail": paper_detail})
- return {
- "ok": True,
- "figure": figure,
- "score": score,
- "chapter": chapter,
- "paper": paper,
- "gate": gate,
- }
-
- def _workspace_for(self, session_id: str) -> str:
- record = self.server.store.get(session_id) if session_id else None
- return str((record or {}).get("workspace") or "")
-
- def _render_figure(self) -> None:
- body = self._body()
- if body is None:
- return
- template = str(body.get("template") or "")
- theme = str(body.get("theme") or "")
- session_id = self._scope_session(body.get("sessionId"))
- data_root = self._scoped_dir(session_id)
- code, result = workbench_figure.render(
- template, theme, self.server.root, data_root
- )
- if code != 0:
- self._error(400, "figure", str(result.get("error") or "渲染失败"))
- return
- outputs = (result.get("version") or {}).get("outputs") or {}
- project_export.copy_outputs(self._workspace_for(session_id), "图表", outputs)
- self._json(200, {"ok": True, "version": result.get("version"), "state": self._workbench(session_id)})
-
- def _rollback_figure(self) -> None:
- body = self._body()
- if body is None:
- return
- version = str(body.get("version") or "")
- session_id = self._scope_session(body.get("sessionId"))
- code, result = workbench_figure.rollback(
- version, self.server.root, self._scoped_dir(session_id)
- )
- if code != 0:
- self._error(404, "figure", str(result.get("error") or "没有这个版本"))
- return
- self._json(200, {"ok": True, "state": self._workbench(session_id)})
-
- def _build_paper(self) -> None:
- body = self._body()
- if body is None:
- return
- session_id = self._scope_session(body.get("sessionId"))
- code, result = paper_build.build(
- self._scoped_dir(session_id), self.server.root
- )
- # 手动构建成功也推进阶段五:阶段轨道与工作台状态保持一致。
- if code == 0 and session_id:
- record = self.server.store.get(session_id)
- if record:
- changed = False
- for row in record["phases"]:
- if row["phase"] == 5 and row["status"] != "passed":
- row["status"] = "passed"
- changed = True
- if row["phase"] == 6 and row["status"] == "idle" and changed:
- row["status"] = "idle"
- if changed:
- self.server.store.put(record)
- state = self._workbench(session_id)
- deliverables = {
- kind: str((row or {}).get("path") or "")
- for kind, row in (state["paper"]["artifacts"] or {}).items()
- if kind in ("pdf", "docx")
- }
- project_export.copy_outputs(self._workspace_for(session_id), "论文", deliverables)
- self._json(
- 200,
- {
- "ok": bool(result.get("ok")),
- "code": code,
- "paper": result,
- "state": state,
- },
- )
-
- def _start_chat(self) -> None:
- body = self._body()
- if body is None:
- return
- provider_id = str(body.get("providerId") or "")
- try:
- messages = normalize_messages(body.get("messages"))
- except ValueError as exc:
- self._error(400, "messages", str(exc))
- return
- model = str(body.get("model") or "").strip()
- api_key = str(body.get("apiKey") or "")
- depth = str(body.get("thinking") or "")
- if depth and depth not in DEPTHS:
- self._error(400, "thinking", f"未知思维深度: {depth}")
- return
- context_tokens: int | None = None
- raw_context = body.get("contextTokens")
- if isinstance(raw_context, (int, float)) and not isinstance(raw_context, bool):
- context_tokens = int(raw_context)
- if context_tokens < 50_000 or context_tokens > 2_000_000:
- self._error(400, "context", "上下文预算必须在 50k–2M 之间")
- return
- send_thinking = body.get("sendThinking") is not False
-
- if provider_id == "fake":
- if not self.server.fake:
- self._error(400, "provider", "离线演示未启用")
- return
- provider = {
- "id": "fake",
- "display": "离线演示",
- "tool_calling": True,
- "base_url": "",
- }
- api_key = ""
- model = model or "fake-stream"
- else:
- provider = find_provider(provider_id)
- if not provider:
- self._error(400, "provider", f"未知服务商: {provider_id}")
- return
- if provider.get("custom"):
- provider["base_url"] = str(body.get("baseUrl") or "")
- try:
- validate_base_url(provider.get("base_url") or "")
- except ProviderError as exc:
- self._error(400, "base_url", str(exc))
- return
- if not api_key:
- self._error(400, "key", "缺少 API Key(在模型设置里填写)")
- return
- if not model:
- self._error(400, "model", "缺少模型名")
- return
-
- chat_id = secrets.token_hex(8)
- mode = str(body.get("mode") or "chat")
- if mode not in ("chat", "workflow"):
- self._error(400, "mode", f"未知对话模式: {mode}")
- return
- workspace = str(body.get("workspace") or "")
- raw_goal = next((m["content"] for m in messages if m["role"] == "user"), "")
- goal = " ".join(str(raw_goal).split())[:80]
- if mode == "workflow":
- problem = next(m["content"] for m in reversed(messages) if m["role"] == "user")
- record = self.server.store.create(chat_id, provider_id, model, problem, workspace)
- session: ChatSession = WorkflowSession(
- chat_id, self.server.store, record, "start", "", workspace=workspace,
- provider=provider, api_key=api_key, model=model,
- depth=depth if send_thinking else "",
- )
- else:
- session = ChatSession(
- chat_id,
- provider,
- api_key,
- model,
- messages,
- depth=depth,
- context_tokens=context_tokens,
- send_thinking=send_thinking,
- goal=goal,
- workspace=workspace,
- )
- with self.server.sessions_lock:
- self.server.sessions[chat_id] = session
- session.start()
- self._json(200, {"ok": True, "chatId": chat_id, "mode": mode})
-
- def _resume_session(self, session_id: str) -> None:
- body = self._body()
- if body is None:
- return
- action = str(body.get("action") or "")
- choice = str(body.get("choice") or "")
- if action not in ("confirm", "reroll", "choose", "run"):
- self._error(400, "action", f"未知动作: {action}")
- return
- if action == "choose" and not choice:
- self._error(400, "choice", "选择候选时必须给出 choice")
- return
- record = self.server.store.get(session_id)
- if not record:
- self._error(404, "session", "没有这个会话")
- return
- if not record.get("pending"):
- self._error(409, "pending", "这个会话没有等待中的决策")
- return
- # Key 按次传入:恢复时没带 Key(旧客户端或离线演示)不报错,
- # 状态机回退确定性路径,卡片上会标明兜底。
- provider: dict | None = None
- api_key = str(body.get("apiKey") or "")
- provider_id = str(body.get("providerId") or record.get("provider") or "")
- model = str(body.get("model") or record.get("model") or "")
- depth = str(body.get("thinking") or "")
- if depth and depth not in DEPTHS:
- self._error(400, "thinking", f"未知思维深度: {depth}")
- return
- if provider_id == "fake":
- if self.server.fake:
- provider = {"id": "fake", "display": "离线演示", "tool_calling": True, "base_url": ""}
- model = model or "fake-stream"
- elif provider_id:
- candidate = find_provider(provider_id)
- if candidate:
- if candidate.get("custom"):
- candidate["base_url"] = str(body.get("baseUrl") or "")
- try:
- validate_base_url(candidate.get("base_url") or "")
- except ProviderError as exc:
- self._error(400, "base_url", str(exc))
- return
- if api_key:
- provider = candidate
- session = WorkflowSession(
- session_id,
- self.server.store,
- record,
- action,
- choice,
- workspace=str(body.get("workspace") or ""),
- provider=provider,
- api_key=api_key if provider else "",
- model=model,
- depth=depth if body.get("sendThinking") is not False else "",
- )
- with self.server.sessions_lock:
- self.server.sessions[session_id] = session
- session.start()
- self._json(200, {"ok": True, "chatId": session_id})
-
- def _stream(self, chat_id: str, query: dict) -> None:
- with self.server.sessions_lock:
- session = self.server.sessions.get(chat_id)
- if not session:
- self._error(404, "chat", "没有这个对话")
- return
-
- raw_last = (self.headers.get("Last-Event-ID") or (query.get("last_id") or [""])[0] or "0").strip()
- try:
- last_id = max(0, int(raw_last))
- except ValueError:
- last_id = 0
-
- self.send_response(200)
- self.send_header("Content-Type", "text/event-stream; charset=utf-8")
- self.send_header("Cache-Control", "no-cache")
- # 流结束后必须由服务端关连接:客户端是 urllib/fetch,不是 EventSource,
- # 只认 EOF(或 chunked 结束),keep-alive 会让它一直等下去。
- self.send_header("Connection", "close")
- self.send_header("X-Accel-Buffering", "no")
- self.end_headers()
- self.close_connection = True
- try:
- self.wfile.write(b"retry: 1500\n\n")
- self.wfile.flush()
- index = min(last_id, len(session.events))
- last_ping = time.monotonic()
- while True:
- with session.cond:
- while index >= len(session.events) and not session.done:
- session.cond.wait(timeout=PING_SECONDS)
- if index >= len(session.events):
- break
- pending = session.events[index:]
- done = session.done
- if pending:
- for ev in pending:
- frame = (
- f"id: {ev['id']}\nevent: {ev['event']}\n"
- f"data: {json.dumps(ev['data'], ensure_ascii=False)}\n\n"
- )
- self.wfile.write(frame.encode("utf-8"))
- index += len(pending)
- self.wfile.flush()
- last_ping = time.monotonic()
- continue
- if done:
- return
- if time.monotonic() - last_ping >= PING_SECONDS:
- self.wfile.write(b": ping\n\n")
- self.wfile.flush()
- last_ping = time.monotonic()
- except (BrokenPipeError, ConnectionResetError):
- return
-
-
-def serve(port: int = 0) -> int:
- token = secrets.token_hex(24)
- fake = fake_enabled()
- root = Path(os.environ.get("MMS_HOME") or ".").resolve()
- store = SessionStore(data_dir(root) / "sessions.db")
- server = ChannelServer(("127.0.0.1", port), Handler, token, fake, store, root)
- # 握手行是 stdout 的唯一内容;之后所有诊断都走 stderr。
- print(
- json.dumps(
- {
- "port": server.server_address[1],
- "token": token,
- "pid": os.getpid(),
- "fake": fake,
- "version": __version__,
- }
- ),
- flush=True,
- )
- stop = threading.Event()
-
- def _request_stop(*_args) -> None:
- stop.set()
-
- for sig in (signal.SIGTERM, signal.SIGINT):
- try:
- signal.signal(sig, _request_stop)
- except (ValueError, OSError):
- pass
-
- thread = threading.Thread(target=server.serve_forever, name="mms-http", daemon=True)
- thread.start()
- stop.wait()
- server.shutdown()
- server.server_close()
- return 0
diff --git a/runtime/src/mms/store.py b/runtime/src/mms/store.py
deleted file mode 100644
index aa6aa47..0000000
--- a/runtime/src/mms/store.py
+++ /dev/null
@@ -1,223 +0,0 @@
-"""M3 会话存储:用标准库 sqlite3 持久化阶段、待决卡与消息。
-
-没有引入 LangGraph:这里需要的只有「暂停 + 跨进程恢复」两点,
-显式状态机加一张表就够,依赖面更小(PLAN §8 已把自研列为可退让项)。
-API Key 不进这张表,provider 只存 id 与模型名。
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import sqlite3
-import threading
-import time
-from pathlib import Path
-
-from .common import dump_json
-
-PHASE_COUNT = 7
-PHASE_NAMES = [
- "环境预检",
- "赛题分析与背景调研",
- "工作目录创建",
- "算法选择",
- "代码实现",
- "论文输出",
- "评分与优化",
-]
-
-SCHEMA = """
-CREATE TABLE IF NOT EXISTS sessions (
- id TEXT PRIMARY KEY,
- created REAL NOT NULL,
- updated REAL NOT NULL,
- provider TEXT NOT NULL,
- model TEXT NOT NULL,
- problem TEXT NOT NULL,
- phases TEXT NOT NULL,
- pending TEXT,
- messages TEXT NOT NULL,
- batch INTEGER NOT NULL DEFAULT 1,
- workspace TEXT
-);
-CREATE INDEX IF NOT EXISTS sessions_updated ON sessions(updated DESC);
-"""
-
-
-def data_dir(root: Path) -> Path:
- override = os.environ.get("MMS_DATA_DIR")
- return Path(override) if override else root / ".mms"
-
-
-def session_scope(base: Path, session_id: object) -> Path:
- """会话产物的隔离目录: /sessions/。
-
- sid 只接受十六进制:任何带 ../ 或分隔符的输入一律回落到旧全局目录,
- 宁可与旧数据共用,也不让路径穿出 base。
- """
- sid = str(session_id or "").strip()
- if sid and all(ch in "0123456789abcdef" for ch in sid) and 8 <= len(sid) <= 64:
- return base / "sessions" / sid
- return base
-
-
-def initial_phases() -> list[dict]:
- return [{"phase": i, "status": "idle", "name": PHASE_NAMES[i]} for i in range(PHASE_COUNT)]
-
-
-class SessionStore:
- def __init__(self, path: Path):
- self.path = path
- self.path.parent.mkdir(parents=True, exist_ok=True)
- self.lock = threading.Lock()
- with self._connect() as conn:
- conn.executescript(SCHEMA)
- # 旧库没有 workspace 列:补一列,历史会话保持空值(回落全局工作区)。
- columns = {row["name"] for row in conn.execute("PRAGMA table_info(sessions)")}
- if "workspace" not in columns:
- conn.execute("ALTER TABLE sessions ADD COLUMN workspace TEXT")
- # 旧库没有 picked 列:选模结果落盘,阶段四按它生成代码。
- if "picked" not in columns:
- conn.execute("ALTER TABLE sessions ADD COLUMN picked TEXT")
-
- def _connect(self) -> sqlite3.Connection:
- conn = sqlite3.connect(self.path, timeout=10)
- conn.row_factory = sqlite3.Row
- conn.execute("PRAGMA journal_mode=WAL")
- return conn
-
- @staticmethod
- def _row(row: sqlite3.Row | None) -> dict | None:
- if row is None:
- return None
- keys = row.keys()
- return {
- "id": row["id"],
- "created": row["created"],
- "updated": row["updated"],
- "provider": row["provider"],
- "model": row["model"],
- "problem": row["problem"],
- "phases": json.loads(row["phases"]),
- "pending": json.loads(row["pending"]) if row["pending"] else None,
- "messages": json.loads(row["messages"]),
- "batch": row["batch"],
- "workspace": row["workspace"] if "workspace" in keys else None,
- "picked": json.loads(row["picked"]) if "picked" in keys and row["picked"] else None,
- }
-
- def create(
- self, session_id: str, provider: str, model: str, problem: str, workspace: str = ""
- ) -> dict:
- now = time.time()
- record = {
- "id": session_id,
- "created": now,
- "updated": now,
- "provider": provider,
- "model": model,
- "problem": problem,
- "phases": initial_phases(),
- "pending": None,
- "messages": [],
- "batch": 1,
- "workspace": workspace,
- "picked": None,
- }
- with self.lock, self._connect() as conn:
- conn.execute(
- "INSERT INTO sessions (id, created, updated, provider, model, problem, phases, pending, messages, batch, workspace)"
- " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
- (
- session_id,
- now,
- now,
- provider,
- model,
- problem,
- dump_json(record["phases"]),
- None,
- "[]",
- 1,
- workspace,
- ),
- )
- return record
-
- def get(self, session_id: str) -> dict | None:
- with self.lock, self._connect() as conn:
- row = conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone()
- return self._row(row)
-
- def latest(self) -> dict | None:
- with self.lock, self._connect() as conn:
- row = conn.execute("SELECT * FROM sessions ORDER BY updated DESC LIMIT 1").fetchone()
- return self._row(row)
-
- def list_summaries(self, limit: int = 100) -> list[dict]:
- """左栏会话列表只需要标题、时间与待决状态,不把 messages 整包搬出来。"""
- with self.lock, self._connect() as conn:
- rows = conn.execute(
- "SELECT id, created, updated, provider, model, problem, phases, pending"
- " FROM sessions ORDER BY updated DESC LIMIT ?",
- (max(1, min(500, limit)),),
- ).fetchall()
- out: list[dict] = []
- for row in rows:
- out.append(
- {
- "id": row["id"],
- "created": row["created"],
- "updatedAt": row["updated"],
- "provider": row["provider"],
- "model": row["model"],
- "problem": row["problem"],
- "phases": json.loads(row["phases"]),
- "pending": bool(row["pending"]),
- }
- )
- return out
-
- def delete(self, session_id: str) -> bool:
- with self.lock, self._connect() as conn:
- cur = conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))
- return cur.rowcount > 0
-
- def clear(self) -> int:
- with self.lock, self._connect() as conn:
- cur = conn.execute("DELETE FROM sessions")
- return max(0, cur.rowcount)
-
- def put(self, record: dict) -> None:
- record["updated"] = time.time()
- with self.lock, self._connect() as conn:
- conn.execute(
- "UPDATE sessions SET updated = ?, phases = ?, pending = ?, messages = ?, batch = ?, picked = ? WHERE id = ?",
- (
- record["updated"],
- dump_json(record["phases"]),
- dump_json(record["pending"]) if record["pending"] is not None else None,
- dump_json(record["messages"]),
- record["batch"],
- dump_json(record["picked"]) if record.get("picked") is not None else None,
- record["id"],
- ),
- )
-
-
-def snapshot(record: dict | None) -> dict | None:
- if record is None:
- return None
- return {
- "id": record["id"],
- "provider": record["provider"],
- "model": record["model"],
- "problem": record["problem"],
- "updatedAt": record["updated"],
- "phases": record["phases"],
- "pending": record["pending"],
- "messages": record["messages"],
- "batch": record["batch"],
- "picked": record.get("picked"),
- }
diff --git a/runtime/src/mms/themes/studio-amber.theme.json b/runtime/src/mms/themes/studio-amber.theme.json
deleted file mode 100644
index 285ebf7..0000000
--- a/runtime/src/mms/themes/studio-amber.theme.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "schema_version": "1.0",
- "name": "studio-amber",
- "title": "工作台 · 琥珀",
- "description": "低饱和琥珀主色,适合暖色系论文版式;只换颜色,不改模板代码。",
- "author": "mathmodel-studio",
- "roles": {
- "identity": {
- "main": "#A9641C",
- "main_light": "#C98D4A",
- "main_pale": "#F0DDC4",
- "accents": ["#17494D", "#7B5FD6", "#33B5A5", "#D9544D", "#B89BD9"]
- },
- "baseline": {
- "base": "#6E6A63",
- "dark": "#45413B"
- },
- "signal": {
- "positive": "#2E9E44",
- "negative": "#D6453F"
- },
- "neutral": {
- "bg": "#FAF8F4",
- "light": "#E6E0D6",
- "mid": "#B5AA99",
- "dark": "#6B6255",
- "ink": "#332E27"
- }
- },
- "cmaps": {
- "divergent": ["#A9641C", "#FAF8F4", "#17494D"],
- "sequential": ["#FBF5EC", "#A9641C"]
- }
-}
diff --git a/runtime/src/mms/themes/studio-ink.theme.json b/runtime/src/mms/themes/studio-ink.theme.json
deleted file mode 100644
index f1dc540..0000000
--- a/runtime/src/mms/themes/studio-ink.theme.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "schema_version": "1.0",
- "name": "studio-ink",
- "title": "工作台 · 墨青",
- "description": "与界面默认强调色一致的墨青主题;只换颜色,不改模板代码。",
- "author": "mathmodel-studio",
- "roles": {
- "identity": {
- "main": "#17494D",
- "main_light": "#4C7C80",
- "main_pale": "#CFE0E1",
- "accents": ["#E28E2C", "#7B5FD6", "#33B5A5", "#D9544D", "#8FA6A8"]
- },
- "baseline": {
- "base": "#6B6B6B",
- "dark": "#3F3F3F"
- },
- "signal": {
- "positive": "#2E9E44",
- "negative": "#E53935"
- },
- "neutral": {
- "bg": "#F7F8F8",
- "light": "#DDE3E4",
- "mid": "#A5B0B2",
- "dark": "#5D6A6C",
- "ink": "#243033"
- }
- },
- "cmaps": {
- "divergent": ["#17494D", "#F5F7F7", "#D9544D"],
- "sequential": ["#F2F7F7", "#17494D"]
- }
-}
diff --git a/runtime/src/mms/workbench_figure.py b/runtime/src/mms/workbench_figure.py
deleted file mode 100644
index f2be628..0000000
--- a/runtime/src/mms/workbench_figure.py
+++ /dev/null
@@ -1,224 +0,0 @@
-"""M4 图表工作台:渲染、主题切换与版本回滚。
-
-渲染仍然走 mathmodel-figure 的 render_template.py(subprocess),
-这里只负责把产物放进版本目录、记录当前版与上一版。
-"""
-
-from __future__ import annotations
-
-import json
-import shutil
-import threading
-import time
-from pathlib import Path
-
-from .common import read_json
-from .invoke import invoke, list_templates
-from .registry import repo_root
-
-LOCK = threading.Lock()
-MAX_VERSIONS = 8
-CUSTOM_THEMES = Path(__file__).resolve().parent / "themes"
-
-
-def themes(root: Path | None = None) -> list[dict]:
- root = root or repo_root()
- rows = []
- bundled = root / "skills" / "mathmodel-figure" / "themes" / "nature.theme.json"
- for path, builtin in [(bundled, True)] + [
- (p, False) for p in sorted(CUSTOM_THEMES.glob("*.theme.json"))
- ]:
- data = read_json(path, {})
- name = data.get("name") or path.name.removesuffix(".theme.json")
- rows.append(
- {
- "id": name,
- "title": data.get("title") or name,
- "path": str(path),
- "builtin": builtin,
- }
- )
- return rows
-
-
-def templates(root: Path | None = None) -> list[dict]:
- return [row for row in list_templates(root) if row.get("skill") == "mathmodel-figure"]
-
-
-def _state_path(data_dir: Path) -> Path:
- return data_dir / "workbench" / "figure" / "state.json"
-
-
-def _load_state(data_dir: Path) -> dict:
- state = read_json(_state_path(data_dir), {})
- if not isinstance(state, dict):
- state = {}
- state.setdefault("counter", 0)
- state.setdefault("active", None)
- state.setdefault("versions", [])
- return state
-
-
-def _save_state(data_dir: Path, state: dict) -> None:
- path = _state_path(data_dir)
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(".tmp")
- tmp.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
- tmp.replace(path)
-
-
-def _find(state: dict, version_id: str | None) -> dict | None:
- if not version_id:
- return None
- return next((v for v in state["versions"] if v.get("id") == version_id), None)
-
-
-def state_payload(root: Path | None = None, data_dir: Path | None = None) -> dict:
- root = root or repo_root()
- data_dir = data_dir or Path(".")
- state = _load_state(data_dir)
- versions = state["versions"]
- active = _find(state, state.get("active")) or (versions[-1] if versions else None)
- if active and active.get("id") != state.get("active"):
- state["active"] = active["id"]
- _save_state(data_dir, state)
- previous = None
- if active:
- index = versions.index(active)
- if index > 0:
- previous = versions[index - 1]
- return {
- "ok": True,
- "templates": templates(root),
- "themes": [{k: v for k, v in row.items() if k != "path"} for row in themes(root)],
- "versions": versions,
- "active": active["id"] if active else None,
- "active_png": (active or {}).get("outputs", {}).get("png"),
- "previous": previous["id"] if previous else None,
- "previous_png": (previous or {}).get("outputs", {}).get("png"),
- }
-
-
-def _prune(data_dir: Path, state: dict) -> None:
- versions = state["versions"]
- if len(versions) <= MAX_VERSIONS:
- return
- drop = versions[:-MAX_VERSIONS]
- for version in drop:
- if version.get("id") == state.get("active"):
- continue
- path = data_dir / "workbench" / "figure" / "versions" / str(version.get("id"))
- shutil.rmtree(path, ignore_errors=True)
- state["versions"] = [v for v in versions if v not in drop]
-
-
-def render(
- template: str, theme: str, root: Path | None = None, data_dir: Path | None = None
-) -> tuple[int, dict]:
- root = root or repo_root()
- data_dir = data_dir or Path(".")
- template_row = next((row for row in templates(root) if row.get("id") == template), None)
- theme_row = next((row for row in themes(root) if row.get("id") == theme), None)
- if template_row is None:
- return 2, {"ok": False, "error": f"未知模板: {template}"}
- if theme_row is None:
- return 2, {"ok": False, "error": f"未知主题: {theme}"}
-
- with LOCK:
- state = _load_state(data_dir)
- state["counter"] += 1
- version_id = f"v{state['counter']}"
- out_dir = data_dir / "workbench" / "figure" / "versions" / version_id
- out_dir.mkdir(parents=True, exist_ok=True)
- code, result = invoke(
- "figure", template, out_dir=out_dir, theme=theme_row["path"], root=root
- )
- if code != 0:
- shutil.rmtree(out_dir, ignore_errors=True)
- return code, {"ok": False, "error": result.get("error", "渲染失败"), "result": result}
-
- version = {
- "id": version_id,
- "label": version_id,
- "template": template,
- "template_title": template_row.get("title", template),
- "theme": theme,
- "theme_title": theme_row.get("title", theme),
- "created": time.time(),
- "outputs": result["outputs"],
- "command": (
- f"python skills/mathmodel-figure/code/tools/render_template.py {template} "
- f"--project {out_dir} --theme {theme_row['path']} --overwrite --lang en"
- ),
- "stdout": (result.get("stdout") or "")[-4000:],
- "stderr": (result.get("stderr") or "")[-4000:],
- }
- state["versions"].append(version)
- state["active"] = version_id
- _prune(data_dir, state)
- _save_state(data_dir, state)
- return 0, {"ok": True, "version": version}
-
-
-def rollback(version_id: str, root: Path | None = None, data_dir: Path | None = None) -> tuple[int, dict]:
- data_dir = data_dir or Path(".")
- with LOCK:
- state = _load_state(data_dir)
- version = _find(state, version_id)
- if version is None:
- return 2, {"ok": False, "error": f"没有这个版本: {version_id}"}
- state["active"] = version_id
- _save_state(data_dir, state)
- return 0, {"ok": True, "version": version}
-
-
-def register(
- *,
- data_dir: Path,
- sources: dict[str, str],
- template: str,
- template_title: str,
- theme: str,
- theme_title: str,
- command: str,
- stdout: str = "",
- stderr: str = "",
- label: str | None = None,
-) -> dict:
- """把外部渲染的产物登记成一个版本(阶段四的基线图走这条路)。
-
- 和 render() 共用同一份版本状态:登记后图表页、代码页与日志页都只看这一处,
- 回滚、上限裁剪也沿用原有规则。
- """
- with LOCK:
- state = _load_state(data_dir)
- state["counter"] += 1
- version_id = f"v{state['counter']}"
- out_dir = data_dir / "workbench" / "figure" / "versions" / version_id
- out_dir.mkdir(parents=True, exist_ok=True)
- outputs: dict[str, str] = {}
- for kind, source in sources.items():
- src = Path(source)
- if not src.is_file():
- continue
- dest = out_dir / f"figure.{kind}"
- shutil.copyfile(src, dest)
- outputs[kind] = str(dest)
- version = {
- "id": version_id,
- "label": label or version_id,
- "template": template,
- "template_title": template_title,
- "theme": theme,
- "theme_title": theme_title,
- "created": time.time(),
- "outputs": outputs,
- "command": command,
- "stdout": (stdout or "")[-4000:],
- "stderr": (stderr or "")[-4000:],
- }
- state["versions"].append(version)
- state["active"] = version_id
- _prune(data_dir, state)
- _save_state(data_dir, state)
- return version
diff --git a/runtime/src/mms/workbench_score.py b/runtime/src/mms/workbench_score.py
deleted file mode 100644
index a16be42..0000000
--- a/runtime/src/mms/workbench_score.py
+++ /dev/null
@@ -1,180 +0,0 @@
-"""M4 评分与章节门禁:把 mathmodel-score 的脚本结果整理成界面可渲染的数据。"""
-
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-from .registry import repo_root
-
-MAX_ROUNDS = 3
-DEMO_SCORES = Path(__file__).resolve().parent / "demo_scores.json"
-
-
-def _run_script(script: Path, args: list[str], cwd: Path) -> tuple[int, str, str]:
- env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}
- proc = subprocess.run(
- [sys.executable, str(script), *args],
- cwd=str(cwd),
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- env=env,
- timeout=120,
- check=False,
- )
- return proc.returncode, proc.stdout, proc.stderr
-
-
-def _run_card(root: Path, card: dict, workdir: Path) -> dict:
- script = root / "skills" / "mathmodel-score" / "code" / "score_card.py"
- path = workdir / f"round-{card.get('round', 0)}.json"
- path.write_text(json.dumps(card, ensure_ascii=False), encoding="utf-8")
- code, stdout, stderr = _run_script(script, [str(path), "--json"], root)
- if code not in (0, 1):
- raise RuntimeError(stderr.strip() or f"评分脚本退出 {code}")
- data = json.loads(stdout)
-
- by_dim = {d["id"]: d for d in card.get("dimensions", [])}
- for deduction in data.get("deductions", []):
- source = by_dim.get(deduction.get("dim_id"), {})
- match = next(
- (
- item
- for item in source.get("deductions", [])
- if item.get("item") == deduction.get("item")
- and float(item.get("penalty", 0) or 0) == float(deduction.get("penalty", 0) or 0)
- ),
- {},
- )
- deduction["target"] = match.get("target", "尚未标注正文位置")
- deduction["suggestion"] = match.get("suggestion", "按评分项要求补充内容。")
- data["round"] = card.get("round", data.get("round"))
- data["veto"] = bool(card.get("veto"))
- data["changes"] = []
- data["breaker"] = bool(
- isinstance(data["round"], int) and data["round"] >= MAX_ROUNDS and not data.get("pass")
- )
- return data
-
-
-def _changes(current: dict, previous: dict | None) -> list[dict]:
- if not previous:
- return []
- old = {d["id"]: d["score"] for d in previous.get("dimensions", [])}
- out = []
- for dim in current.get("dimensions", []):
- before = old.get(dim["id"])
- if before is None:
- continue
- delta = dim["score"] - before
- if delta:
- out.append(
- {
- "dim": dim["label"],
- "from": before,
- "to": dim["score"],
- "delta": delta,
- }
- )
- return out
-
-
-def score_dir(data_dir: Path) -> Path:
- return data_dir / "workbench" / "score"
-
-
-def demo_rounds(root: Path | None = None) -> tuple[list[dict], dict | None]:
- """演示三轮与否决示例:供评分页「示例」入口展示口径,不与真实会话数据混放。"""
- root = root or repo_root()
- demo = json.loads(DEMO_SCORES.read_text(encoding="utf-8"))
- rounds = []
- with tempfile.TemporaryDirectory(prefix="mms-score-demo-") as temp:
- workdir = Path(temp)
- previous = None
- for card in demo.get("rounds", []):
- result = _run_card(root, card, workdir)
- result["changes"] = _changes(result, previous)
- rounds.append(result)
- previous = result
- veto = _run_card(root, demo.get("veto", {}), workdir) if demo.get("veto") else None
- return rounds, veto
-
-
-def save_card(data_dir: Path, card: dict) -> Path:
- """真实评分轮落盘:<会话>/workbench/score/round-N.json。"""
- target = score_dir(data_dir)
- target.mkdir(parents=True, exist_ok=True)
- path = target / f"round-{int(card.get('round', 0))}.json"
- path.write_text(json.dumps(card, ensure_ascii=False, indent=2), encoding="utf-8")
- return path
-
-
-def _real_cards(data_dir: Path | None) -> list[dict]:
- if data_dir is None:
- return []
- target = score_dir(data_dir)
- if not target.is_dir():
- return []
- cards: list[tuple[int, dict]] = []
- for path in target.glob("round-*.json"):
- try:
- card = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- continue
- if isinstance(card, dict) and isinstance(card.get("round"), int):
- cards.append((card["round"], card))
- return [card for _, card in sorted(cards)]
-
-
-def state(root: Path | None = None, data_dir: Path | None = None) -> dict:
- root = root or repo_root()
- real = _real_cards(data_dir)
- if real:
- cards = real
- veto_card = None
- else:
- demo = json.loads(DEMO_SCORES.read_text(encoding="utf-8"))
- cards = demo.get("rounds", [])
- veto_card = demo.get("veto")
- rounds = []
- with tempfile.TemporaryDirectory(prefix="mms-score-") as temp:
- workdir = Path(temp)
- previous = None
- for card in cards:
- result = _run_card(root, card, workdir)
- result["changes"] = _changes(result, previous)
- rounds.append(result)
- previous = result
- veto = _run_card(root, veto_card, workdir) if veto_card else None
-
- chapter_script = root / "skills" / "mathmodel-score" / "code" / "check_chapters.py"
- # 章节门禁优先查本会话真实论文;没有论文时回落内置样例。
- sample = root / "skills" / "mathmodel-score" / "examples" / "chapter-sample.tex"
- if data_dir is not None:
- paper_tex = data_dir / "workbench" / "paper" / "paper.tex"
- if paper_tex.is_file():
- sample = paper_tex
- code, stdout, stderr = _run_script(
- chapter_script, [str(sample), "--json"], root
- )
- chapter = {"ok": False, "error": stderr.strip() or f"章节自检退出 {code}"}
- if code in (0, 1):
- report = json.loads(stdout)
- counts = (report.get("files") or [{}])[0].get("counts", {})
- chapter = {
- "ok": True,
- "pass": bool(report.get("pass")),
- "hard_failed": int(report.get("hard_failed", 0)),
- "soft_failed": int(report.get("soft_failed", 0)),
- "manual": int(counts.get("manual", 0)),
- "pass_count": int(counts.get("pass", 0)),
- }
-
- default_round = next((r["round"] for r in rounds if r.get("pass")), rounds[-1]["round"] if rounds else 0)
- return {"ok": True, "rounds": rounds, "veto": veto, "defaultRound": default_round, "chapter": chapter}
diff --git a/runtime/tests/checklib.py b/runtime/tests/checklib.py
deleted file mode 100644
index a4d0b6c..0000000
--- a/runtime/tests/checklib.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""自检公共脚手架:UTF-8 控制台、仓库根与包路径注入、断言收集与汇总。
-
-六个 selfcheck 都以脚本方式运行(python runtime/tests/selfcheck_*.py),
-脚本目录自然在 sys.path[0],直接 ``from checklib import ...`` 即可。
-"""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[2]
-
-# CI 的 Windows 控制台是 cp1252,不重配会在打印中文时崩。
-for _stream in (sys.stdout, sys.stderr):
- if hasattr(_stream, "reconfigure"):
- try:
- _stream.reconfigure(encoding="utf-8", errors="replace")
- except (OSError, ValueError):
- pass
-
-sys.path.insert(0, str(ROOT / "runtime" / "src"))
-
-rows: list[tuple[str, bool, str]] = []
-
-
-def check(name: str, ok: bool, detail: str = "") -> None:
- rows.append((name, bool(ok), detail))
-
-
-def report(title: str) -> int:
- """打印断言与「通过数/总数 条 」,返回退出码(0 全绿 / 1 有失败)。"""
- failed = [row for row in rows if not row[1]]
- for name, ok, detail in rows:
- print(f"{'PASS' if ok else 'FAIL'} {name}\n {detail}")
- print(f"\n{len(rows) - len(failed)}/{len(rows)} 条 {title}")
- return 1 if failed else 0
diff --git a/runtime/tests/selfcheck.py b/runtime/tests/selfcheck.py
deleted file mode 100644
index 01ef525..0000000
--- a/runtime/tests/selfcheck.py
+++ /dev/null
@@ -1,211 +0,0 @@
-#!/usr/bin/env python3
-"""G3 · CLI 契约自检:把 mms 的 0/1/2 三个退出码各自跑到可达。
-
-除注册表命令外,也真调一次上游图表模板(subprocess)并核验三件产物;
-S13 是反向覆盖——渲染器假成功时必须判 1,而不是相信退出码。
-
-一个只会返回 0 的检查器没有价值,所以这里既跑「正常应当 0」,
-也跑「坏了必须 1」和「环境缺失必须 2」,并与注册表实数对照。
-
-本脚本只依赖标准库;jsonschema 在场时走完整契约校验,缺席时走降级校验,
-两种路径都必须退出 0(真实判据打印在输出里)。
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import shutil
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-from checklib import ROOT, check, report
-
-PKG_SRC = ROOT / "runtime" / "src"
-MANIFEST_PATH = ROOT / "skills" / "manifest.json"
-SCHEMA_PATH = ROOT / "schemas" / "skill-manifest.schema.json"
-
-
-def run(
- args: list[str], env_extra: dict[str, str] | None = None, timeout: float | None = None
-) -> subprocess.CompletedProcess:
- env = dict(os.environ)
- env["PYTHONPATH"] = str(PKG_SRC) + os.pathsep + env.get("PYTHONPATH", "")
- env.pop("MMS_HOME", None)
- if env_extra:
- env.update(env_extra)
- # cwd 故意设成临时目录,验证「从安装位置向上找仓库根」这条路径而不是依赖 cwd
- with tempfile.TemporaryDirectory() as td:
- return subprocess.run(
- [sys.executable, "-m", "mms.cli", *args],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- cwd=td,
- env=env,
- timeout=timeout,
- )
-
-
-def fixture_home(mutate) -> str:
- """复制一份真实注册表到临时仓库根,按 mutate 改坏,返回该根目录。"""
- home = tempfile.mkdtemp(prefix="mms-selfcheck-")
- (Path(home) / "skills").mkdir(parents=True, exist_ok=True)
- (Path(home) / "schemas").mkdir(parents=True, exist_ok=True)
- shutil.copy(MANIFEST_PATH, Path(home) / "skills" / "manifest.json")
- shutil.copy(SCHEMA_PATH, Path(home) / "schemas" / "skill-manifest.schema.json")
- mutate(Path(home))
- return home
-
-
-declared = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
-skill_count = len(declared["skills"])
-
-# S1 版本
-r = run(["--version"])
-check("S1 --version 退出 0", r.returncode == 0 and r.stdout.startswith("mms "), f"exit {r.returncode} · {r.stdout.strip()!r}")
-
-# S2 人读列举
-r = run(["skills"])
-listed = [ln for ln in r.stdout.splitlines() if ln.strip()]
-check(
- "S2 skills 列举数与注册表一致",
- r.returncode == 0 and len(listed) - 1 == skill_count,
- f"exit {r.returncode} · 列出 {len(listed) - 1} 行 / 注册表 {skill_count} 个",
-)
-
-# S3 机器可读
-r = run(["skills", "--json"])
-try:
- parsed = json.loads(r.stdout)
- ok3 = r.returncode == 0 and len(parsed["skills"]) == skill_count
- detail3 = f"exit {r.returncode} · JSON skills {len(parsed['skills'])} 个"
-except json.JSONDecodeError as exc:
- ok3, detail3 = False, f"exit {r.returncode} · JSON 解析失败 {exc}"
-check("S3 skills --json 可被程序读取", ok3, detail3)
-
-# S4 真注册表应当通过
-r = run(["skills", "--check"])
-how = "jsonschema" if "jsonschema" in r.stdout else ("minimal" if "minimal" in r.stdout else "?")
-check("S4 skills --check 对真注册表退出 0", r.returncode == 0, f"exit {r.returncode} · 判据来源 {how} · {r.stdout.strip()}")
-
-# S5 契约外取值必须 1
-def break_enum(home: Path) -> None:
- data = json.loads((home / "skills" / "manifest.json").read_text(encoding="utf-8"))
- data["skills"][0]["ui"]["artifacts"] = ["hologram"]
- (home / "skills" / "manifest.json").write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
-
-
-home5 = fixture_home(break_enum)
-try:
- r = run(["skills", "--check"], {"MMS_HOME": home5})
- check("S5 词表外取值退出 1", r.returncode == 1, f"exit {r.returncode} · {r.stderr.strip().splitlines()[-1] if r.stderr.strip() else r.stdout.strip()}")
-finally:
- shutil.rmtree(home5, ignore_errors=True)
-
-# S6 非 JSON 必须 1(而不是崩在读取阶段)
-def break_json(home: Path) -> None:
- (home / "skills" / "manifest.json").write_text('{"skills": [', encoding="utf-8")
-
-
-home6 = fixture_home(break_json)
-try:
- r = run(["skills", "--check"], {"MMS_HOME": home6})
- check("S6 非法 JSON 退出 1 且不抛栈", r.returncode == 1 and "Traceback" not in r.stderr, f"exit {r.returncode}")
-finally:
- shutil.rmtree(home6, ignore_errors=True)
-
-# S7 MMS_HOME 指向空目录必须 2
-empty = tempfile.mkdtemp(prefix="mms-selfcheck-empty-")
-try:
- r = run(["skills"], {"MMS_HOME": empty})
- check("S7 MMS_HOME 无注册表退出 2", r.returncode == 2, f"exit {r.returncode}")
-finally:
- shutil.rmtree(empty, ignore_errors=True)
-
-# S8 未知子命令必须 2
-r = run(["nope"])
-check("S8 未知子命令退出 2", r.returncode == 2, f"exit {r.returncode}")
-
-# S9 模板清单:20 张图 + 5 张示意图。上游增删模板时这条要跟着改(re-sync 记录里留痕)。
-r = run(["templates", "--json"])
-try:
- listing = json.loads(r.stdout)
- counts: dict[str, int] = {}
- for item in listing["templates"]:
- counts[item["skill"]] = counts.get(item["skill"], 0) + 1
- ok9 = (
- r.returncode == 0
- and listing["total"] == 25
- and counts.get("mathmodel-figure") == 20
- and counts.get("mathmodel-diagram") == 5
- )
- detail9 = (
- f"exit {r.returncode} · {listing['total']} 个"
- f"(figure {counts.get('mathmodel-figure')} / diagram {counts.get('mathmodel-diagram')})"
- )
-except (json.JSONDecodeError, KeyError) as exc:
- ok9, detail9 = False, f"exit {r.returncode} · JSON 解析失败 {exc}"
-check("S9 templates --json 列出 20 图 + 5 示意图", ok9, detail9)
-
-# S10 真渲染一张:退出 0 且 PNG/PDF/SVG 三件产物都非空
-render_out = tempfile.mkdtemp(prefix="mms-render-")
-try:
- r = run(
- ["invoke", "figure", "paired-raincloud", "--out", render_out, "--json"],
- timeout=300,
- )
- try:
- rendered = json.loads(r.stdout)
- outs = rendered.get("outputs") or {}
- sizes = {k: Path(v).stat().st_size for k, v in outs.items() if Path(v).is_file()}
- ok10 = (
- r.returncode == 0
- and rendered.get("ok") is True
- and set(sizes) == {"png", "pdf", "svg"}
- and all(s > 0 for s in sizes.values())
- )
- detail10 = f"exit {r.returncode} · 产物 {sizes}"
- except (json.JSONDecodeError, OSError) as exc:
- ok10, detail10 = False, f"exit {r.returncode} · 结果解析失败 {exc} · {r.stderr.strip()[:200]}"
-finally:
- shutil.rmtree(render_out, ignore_errors=True)
-check("S10 invoke figure 真出 PNG/PDF/SVG", ok10, detail10)
-
-# S11 未接通的技能必须 2(用法错误,不是渲染失败)
-r = run(["invoke", "paper", "x"])
-check("S11 invoke 未接通技能退出 2", r.returncode == 2, f"exit {r.returncode} · {r.stderr.strip()[:120]}")
-
-# S12 不存在的模板由上游渲染器报用法错误 2,我们原样透传
-bad_out = tempfile.mkdtemp(prefix="mms-render-bad-")
-try:
- r = run(["invoke", "figure", "no-such-template", "--out", bad_out], timeout=120)
-finally:
- shutil.rmtree(bad_out, ignore_errors=True)
-check("S12 未知模板退出 2", r.returncode == 2, f"exit {r.returncode}")
-
-# S13 反向覆盖:渲染器退出 0 但没写产物,必须判 1(不信退出码)
-def fake_renderer(home: Path) -> None:
- tool = home / "skills" / "mathmodel-figure" / "code" / "tools"
- tool.mkdir(parents=True, exist_ok=True)
- (tool / "render_template.py").write_text("import sys\nsys.exit(0)\n", encoding="utf-8")
-
-
-home13 = fixture_home(fake_renderer)
-empty_out = tempfile.mkdtemp(prefix="mms-render-empty-")
-try:
- r = run(
- ["invoke", "figure", "paired-raincloud", "--out", empty_out],
- {"MMS_HOME": home13},
- )
- ok13 = r.returncode == 1 and "缺少产物" in r.stderr
- detail13 = f"exit {r.returncode} · {r.stderr.strip().splitlines()[-1] if r.stderr.strip() else ''}"
-finally:
- shutil.rmtree(home13, ignore_errors=True)
- shutil.rmtree(empty_out, ignore_errors=True)
-check("S13 渲染器假成功(退出 0 无产物)被判 1", ok13, detail13)
-
-sys.exit(report("CLI 契约断言通过(0/1/2 三码各自可达)"))
diff --git a/runtime/tests/selfcheck_channel.py b/runtime/tests/selfcheck_channel.py
deleted file mode 100644
index 2169d9f..0000000
--- a/runtime/tests/selfcheck_channel.py
+++ /dev/null
@@ -1,1016 +0,0 @@
-"""G4/G5 · 本机通道与 provider 流式契约自检。
-
-不需要真实 API Key、不访问公网:通道用 MMS_FAKE_PROVIDER=1 的本地假 provider,
-provider 路径用 127.0.0.1 上的假 OpenAI 端点(含 429 重试、reasoning_content 剥离、
-tool_calls 增量拼装)。
-
-每条断言都能失败;--selftest 用多份坏事件证明事件判据本身会拒绝它们。
-退出码:0 全部通过 / 1 有断言失败 / 2 用法错误
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import shutil
-import subprocess
-import sys
-import tempfile
-import threading
-import time
-import http.client
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from pathlib import Path
-
-from checklib import ROOT, check, report
-
-SCHEMA_PATH = ROOT / "schemas" / "chat-events.schema.json"
-SENTINEL = "sk-test-SENTINEL-DO-NOT-LEAK"
-EVENT_TYPES = {"token", "reasoning", "tool_call", "compaction", "artifact", "interrupt", "gate", "phase", "error", "done"}
-from mms.provider import apply_reasoning, find_provider # noqa: E402
-from mms import paper_build # noqa: E402
-
-# 与 G10 同一约定:没有 TeX 的环境显式 MMS_PAPER_SKIP=1 跳过排版断言,
-# 跳过打印「未验证」,不当成通过。ubuntu gates 装齐 TeX 后走全链。
-PAPER_SKIP = os.environ.get("MMS_PAPER_SKIP") == "1"
-PAPER_OK = paper_build.env_status()["ok"]
-FULL_CHAIN = PAPER_OK and not PAPER_SKIP
-
-
-def lint_event(ev) -> list[str]:
- """不依赖 jsonschema 的形状判据;--selftest 证明它会拒绝坏事件。"""
- problems: list[str] = []
- if not isinstance(ev, dict):
- return ["事件不是对象"]
- eid = ev.get("id")
- if not isinstance(eid, str) or not eid.isdigit() or int(eid) < 1:
- problems.append("id 必须是正整数形式的字符串")
- event = ev.get("event")
- if event not in EVENT_TYPES:
- problems.append(f"未知事件类型: {event!r}")
- data = ev.get("data")
- if not isinstance(data, dict):
- problems.append("data 必须是对象")
- return problems
- if event in ("token", "reasoning"):
- if not isinstance(data.get("text"), str) or not data.get("text"):
- problems.append(f"{event} 缺非空 text")
- elif event == "tool_call":
- if not isinstance(data.get("id"), str) or not data.get("id"):
- problems.append("tool_call 缺 id")
- if not isinstance(data.get("name"), str) or not data.get("name"):
- problems.append("tool_call 缺 name")
- if data.get("status") not in ("running", "ok", "error"):
- problems.append("tool_call.status 非法")
- if "duration_ms" in data and not isinstance(data["duration_ms"], int):
- problems.append("tool_call.duration_ms 必须是整数")
- elif event == "compaction":
- for key in ("before", "after", "pruned", "summarized", "dropped"):
- if not isinstance(data.get(key), int) or data.get(key) < 0:
- problems.append(f"compaction.{key} 必须是非负整数")
- if not isinstance(data.get("reason"), str) or not data.get("reason"):
- problems.append("compaction 缺 reason")
- if "summary" in data and not isinstance(data["summary"], str):
- problems.append("compaction.summary 必须是字符串")
- elif event == "phase":
- if not isinstance(data.get("phase"), int) or not 0 <= data["phase"] <= 6:
- problems.append("phase 必须是 0..6 的整数")
- if data.get("status") not in ("idle", "running", "waiting", "passed", "failed"):
- problems.append("phase.status 非法")
- elif event == "error":
- if not isinstance(data.get("message"), str) or not data.get("message"):
- problems.append("error 缺 message")
- elif event == "done":
- if data.get("reason") not in ("stop", "error", "cancelled", "max_tool_rounds", "waiting"):
- problems.append("done.reason 非法")
- return problems
-
-
-def schema_validate(events: list[dict]) -> tuple[list[str], str]:
- """优先按 Draft 2020-12 契约校验;缺 jsonschema 时退回 lint_event。"""
- try:
- import jsonschema # type: ignore
- except ImportError:
- problems: list[str] = []
- for ev in events:
- problems.extend(lint_event(ev))
- return problems, "minimal"
- schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
- validator = jsonschema.Draft202012Validator(schema)
- problems = []
- for ev in events:
- for err in validator.iter_errors(ev):
- problems.append(f"事件 {ev.get('id')}: {err.message}")
- for ev in events:
- problems.extend(lint_event(ev))
- return problems, "jsonschema+shape"
-
-
-def parse_sse(raw: str) -> list[dict]:
- frames: list[dict] = []
- cur: dict = {}
- for line in raw.splitlines():
- if not line.strip() or line.startswith(":"):
- if cur.get("event") and cur.get("data") is not None:
- frames.append({"id": cur.get("id", ""), "event": cur["event"], "data": cur["data"]})
- cur = {}
- continue
- if line.startswith("retry:"):
- continue
- key, _, value = line.partition(":")
- value = value[1:] if value.startswith(" ") else value
- if key == "id":
- cur["id"] = value
- elif key == "event":
- cur["event"] = value
- elif key == "data":
- try:
- cur["data"] = json.loads(value)
- except json.JSONDecodeError:
- cur["data"] = {"__raw__": value}
- if cur.get("event") and cur.get("data") is not None:
- frames.append({"id": cur.get("id", ""), "event": cur["event"], "data": cur["data"]})
- return frames
-
-
-def read_frame(resp) -> dict | None:
- cur: dict = {}
- while True:
- line = resp.readline()
- if not line:
- if cur.get("event") and cur.get("data") is not None:
- return {"id": cur.get("id", ""), "event": cur["event"], "data": cur["data"]}
- return None
- text = line.decode("utf-8", "replace").rstrip("\r\n")
- if not text:
- if cur.get("event") and cur.get("data") is not None:
- return {"id": cur.get("id", ""), "event": cur["event"], "data": cur["data"]}
- continue
- if text.startswith(":"):
- continue
- key, _, value = text.partition(":")
- value = value[1:] if value.startswith(" ") else value
- if key == "id":
- cur["id"] = value
- elif key == "event":
- cur["event"] = value
- elif key == "data":
- cur["data"] = json.loads(value)
-
-
-class Channel:
- def __init__(self, fake: bool = True, env_extra: dict | None = None):
- env = {**os.environ}
- env.pop("MMS_FAKE_PROVIDER", None)
- env.pop("MMS_FAKE_DELAY_MS", None)
- if fake:
- env["MMS_FAKE_PROVIDER"] = "1"
- env.update(env_extra or {})
- self.proc = subprocess.Popen(
- [sys.executable, str(ROOT / "runtime" / "cli.py"), "serve", "--port", "0"],
- cwd=str(ROOT),
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- encoding="utf-8",
- errors="replace",
- bufsize=1,
- env=env,
- )
- timer = threading.Timer(20, self.proc.kill)
- timer.start()
- try:
- line = self.proc.stdout.readline() if self.proc.stdout else ""
- finally:
- timer.cancel()
- if not line:
- err = self.proc.stderr.read() if self.proc.stderr else ""
- raise RuntimeError(f"服务器没有打印握手行;stderr: {err[-800:]}")
- self.handshake = json.loads(line)
- self.port = int(self.handshake["port"])
- self.token = str(self.handshake["token"])
- self.extra_stdout = ""
- self.stderr = ""
-
- def header(self, extra: dict | None = None) -> dict:
- head = {"Authorization": f"Bearer {self.token}"}
- head.update(extra or {})
- return head
-
- def request(self, method: str, path: str, body=None, headers=None) -> tuple[int, bytes]:
- conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
- data = None
- head = self.header(headers)
- if body is not None:
- data = json.dumps(body, ensure_ascii=False).encode("utf-8")
- head["Content-Type"] = "application/json"
- conn.request(method, path, body=data, headers=head)
- resp = conn.getresponse()
- raw = resp.read()
- conn.close()
- return resp.status, raw
-
- def json(self, method: str, path: str, body=None, headers=None) -> tuple[int, dict]:
- status, raw = self.request(method, path, body, headers)
- try:
- return status, json.loads(raw.decode("utf-8"))
- except (UnicodeDecodeError, json.JSONDecodeError):
- return status, {"__raw__": raw.decode("utf-8", "replace")}
-
- def start_chat(self, body: dict) -> tuple[int, dict]:
- return self.json("POST", "/chats", body)
-
- def events(self, chat_id: str, last_id: str | None = None) -> tuple[list[dict], str]:
- headers = self.header({"Last-Event-ID": last_id} if last_id else None)
- conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
- conn.request("GET", f"/chats/{chat_id}/events", headers=headers)
- resp = conn.getresponse()
- raw = resp.read().decode("utf-8", "replace")
- conn.close()
- return parse_sse(raw), raw
-
- def open_events(self, chat_id: str, last_id: str | None = None):
- headers = self.header({"Last-Event-ID": last_id} if last_id else None)
- conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
- conn.request("GET", f"/chats/{chat_id}/events", headers=headers)
- return conn, conn.getresponse()
-
- def stop(self) -> None:
- if self.proc.poll() is None:
- self.proc.terminate()
- try:
- self.proc.wait(timeout=5)
- except subprocess.TimeoutExpired:
- self.proc.kill()
- self.proc.wait(timeout=5)
- self.extra_stdout = self.proc.stdout.read() if self.proc.stdout else ""
- self.stderr = self.proc.stderr.read() if self.proc.stderr else ""
-
-
-class FakeOpenAI(BaseHTTPRequestHandler):
- protocol_version = "HTTP/1.0"
-
- def log_message(self, fmt, *args):
- pass
-
- def do_POST(self): # noqa: N802
- length = int(self.headers.get("Content-Length") or "0")
- body = json.loads(self.rfile.read(length).decode("utf-8"))
- self.server.records.append(
- {"auth": self.headers.get("Authorization"), "body": body}
- )
- if getattr(self.server, "rate_limit", True) and len(self.server.records) == 1:
- self.send_response(429)
- self.send_header("Retry-After", "0")
- self.end_headers()
- self.wfile.write(b'{"error":"rate limited"}')
- return
-
- self.send_response(200)
- self.send_header("Content-Type", "text/event-stream")
- self.send_header("Connection", "close")
- self.end_headers()
- messages = body.get("messages") or []
- tool_name = getattr(self.server, "tool_name", "list_templates")
- tool_args = getattr(self.server, "tool_args", '{"unused": true}')
- has_tool_result = any(m.get("role") == "tool" for m in messages)
- if tool_name and not has_tool_result:
- chunks = [
- {"choices": [{"delta": {"reasoning_content": "想一想。"}, "finish_reason": None}]},
- {"choices": [{"delta": {"content": "查模板。"}, "finish_reason": None}]},
- {
- "choices": [
- {
- "delta": {
- "tool_calls": [
- {
- "index": 0,
- "id": "call_live_1",
- "type": "function",
- "function": {"name": tool_name, "arguments": ""},
- }
- ]
- },
- "finish_reason": None,
- }
- ]
- },
- {
- "choices": [
- {
- "delta": {
- "tool_calls": [
- {"index": 0, "function": {"arguments": tool_args}}
- ]
- },
- "finish_reason": "tool_calls",
- }
- ]
- },
- ]
- else:
- chunks = [
- {"choices": [{"delta": {"reasoning_content": "想一想。"}, "finish_reason": None}]},
- {"choices": [{"delta": {"content": "第一段"}, "finish_reason": None}]},
- {"choices": [{"delta": {"content": "第二段"}, "finish_reason": None}]},
- {"choices": [{"delta": {}, "finish_reason": "stop"}]},
- ]
- delay = float(getattr(self.server, "delay", 0.0) or 0.0)
- for chunk in chunks:
- self.wfile.write(("data: " + json.dumps(chunk, ensure_ascii=False) + "\n\n").encode("utf-8"))
- self.wfile.flush()
- if delay:
- time.sleep(delay)
- self.wfile.write(b"data: [DONE]\n\n")
- self.wfile.flush()
-
-
-def fake_openai(tool_name="list_templates", delay: float = 0.0, rate_limit: bool = True) -> ThreadingHTTPServer:
- server = ThreadingHTTPServer(("127.0.0.1", 0), FakeOpenAI)
- server.daemon_threads = True
- server.records = [] # type: ignore[attr-defined]
- server.tool_name = tool_name # type: ignore[attr-defined]
- server.tool_args = '{"unused": true}' # type: ignore[attr-defined]
- server.delay = delay # type: ignore[attr-defined]
- server.rate_limit = rate_limit # type: ignore[attr-defined]
- threading.Thread(target=server.serve_forever, daemon=True).start()
- return server
-
-
-def run_fake_chat(channel: Channel, api_key: str = "") -> tuple[list[dict], str, dict]:
- status, started = channel.start_chat(
- {
- "providerId": "fake",
- "model": "fake-stream",
- "apiKey": api_key,
- "messages": [{"role": "user", "content": "列一下模板"}],
- }
- )
- check("C5 假 provider 能开一次对话", status == 200 and started.get("ok") is True, f"HTTP {status} {started}")
- chat_id = started.get("chatId", "")
- events, raw = channel.events(chat_id)
- return events, raw, started
-
-
-def finish() -> None:
- raise SystemExit(report("通道契约断言通过"))
-
-
-def tests() -> None:
- channel = Channel(fake=True)
- try:
- hs = channel.handshake
- check(
- "C1 握手行含 port/token/pid",
- isinstance(hs.get("port"), int)
- and hs["port"] > 0
- and isinstance(hs.get("token"), str)
- and len(hs["token"]) >= 32
- and isinstance(hs.get("pid"), int),
- f"port={hs.get('port')} token_len={len(str(hs.get('token','')))} pid={hs.get('pid')}",
- )
- status, health = channel.json("GET", "/health")
- check("C1 /health 可用且报告 fake", status == 200 and health.get("ok") is True and health.get("fake") is True, f"HTTP {status} {health}")
-
- status, _ = channel.request("GET", "/health", headers={"Authorization": "Bearer wrong"})
- check("C2 错误 token 被拒", status == 401, f"HTTP {status}")
- conn = http.client.HTTPConnection("127.0.0.1", channel.port, timeout=10)
- conn.request("GET", "/health", headers={"Host": "evil.example"})
- resp = conn.getresponse()
- resp.read()
- conn.close()
- check("C2 非回环 Host 被拒(防 DNS rebinding)", resp.status == 403, f"HTTP {resp.status}")
-
- status, providers = channel.json("GET", "/providers")
- ids = [p.get("id") for p in providers.get("providers", [])]
- check("C3 provider 清单含 fake/deepseek/kimi/custom", status == 200 and {"fake", "deepseek", "kimi", "custom"} <= set(ids), f"HTTP {status} ids={ids}")
- blob = json.dumps(providers, ensure_ascii=False)
- check("C3 provider 清单不含密钥字段", "apiKey" not in blob and "api_key" not in blob and "key" not in providers.get("providers", [{}])[0], "只返回展示信息")
-
- events, raw, started = run_fake_chat(channel, api_key=SENTINEL)
- problems, how = schema_validate(events)
- check("C4 事件全部符合契约", not problems, f"判据 {how};{problems[:3]}")
- ids_seq = [int(e["id"]) for e in events]
- check("C4 事件 id 从 1 连续递增", ids_seq == list(range(1, len(events) + 1)), f"{ids_seq[:5]}…{ids_seq[-2:]}")
- kinds = [e["event"] for e in events]
- check("C4 同时出现 reasoning/token/tool_call/done", {"reasoning", "token", "tool_call", "done"} <= set(kinds), f"{kinds[:8]}…")
- running = [e for e in events if e["event"] == "tool_call" and e["data"].get("status") == "running"]
- finished = [e for e in events if e["event"] == "tool_call" and e["data"].get("status") == "ok"]
- check(
- "C4 工具卡先 running 后 ok,结果含 25 个模板",
- bool(running)
- and bool(finished)
- and finished[0]["data"].get("result", {}).get("total") == 25,
- f"running={len(running)} ok={len(finished)} total={finished[0]['data'].get('result', {}).get('total') if finished else None}",
- )
- check("C4 done 原因 = stop", events and events[-1]["event"] == "done" and events[-1]["data"].get("reason") == "stop", str(events[-1] if events else None))
- check("C4 密钥不出现在事件流", SENTINEL not in raw, "已扫描整条 SSE")
-
- # 续传:先读 3 条就断开,再用 Last-Event-ID 接上
- status, started2 = channel.start_chat(
- {
- "providerId": "fake",
- "model": "fake-stream",
- "messages": [{"role": "user", "content": "再列一次"}],
- }
- )
- chat2 = started2.get("chatId", "")
- conn, resp = channel.open_events(chat2)
- first = [read_frame(resp) for _ in range(3)]
- conn.close()
- last_id = first[-1]["id"] if all(first) else "0"
- rest, _ = channel.events(chat2, last_id=last_id)
- resumed = rest[0]["event"] if rest else None
- check(
- "C6 Last-Event-ID 续传不重不漏",
- bool(rest) and int(rest[0]["id"]) == int(last_id) + 1 and rest[-1]["event"] == "done",
- f"断在 {last_id},续得首条 id={rest[0]['id'] if rest else None} event={resumed}",
- )
-
- # 取消:慢一点的假 provider,确保取消发生在流中途
- slow = Channel(fake=True, env_extra={"MMS_FAKE_DELAY_MS": "120"})
- try:
- status, started3 = slow.start_chat(
- {
- "providerId": "fake",
- "model": "fake-stream",
- "messages": [{"role": "user", "content": "慢速演示"}],
- }
- )
- chat3 = started3.get("chatId", "")
- time.sleep(0.2)
- status_cancel, _ = slow.json("POST", f"/chats/{chat3}/cancel")
- events3, _ = slow.events(chat3)
- check("C7 取消请求被接受", status_cancel == 200, f"HTTP {status_cancel}")
- check(
- "C7 取消后 done.reason=cancelled 且 done 在最后",
- bool(events3)
- and events3[-1]["event"] == "done"
- and events3[-1]["data"].get("reason") == "cancelled",
- f"最后事件 {events3[-1] if events3 else None}",
- )
- finally:
- slow.stop()
-
- status, bad = channel.json("POST", "/chats", {"providerId": "nope", "messages": [{"role": "user", "content": "x"}]})
- check("C8 未知 provider 返回 400", status == 400, f"HTTP {status} {bad}")
- status, bad = channel.json(
- "POST",
- "/chats",
- {"providerId": "deepseek", "model": "deepseek-chat", "messages": [{"role": "user", "content": "x"}]},
- )
- check("C8 缺 API Key 返回 400", status == 400, f"HTTP {status} {bad}")
- status, bad = channel.json(
- "POST",
- "/chats",
- {
- "providerId": "custom",
- "model": "x",
- "apiKey": SENTINEL,
- "baseUrl": "http://example.com/v1",
- "messages": [{"role": "user", "content": "x"}],
- },
- )
- check("C8 公网 http 端点被拒", status == 400, f"HTTP {status} {bad}")
-
- channel.stop()
- check("C9 stdout 只有握手一行", channel.extra_stdout.strip() == "", f"多余输出: {channel.extra_stdout[-120:]!r}")
- check("C9 stderr 不出现密钥", SENTINEL not in channel.stderr, "已扫描服务器 stderr")
- finally:
- channel.stop()
-
- bare = Channel(fake=False)
- try:
- status, providers = bare.json("GET", "/providers")
- ids = [p.get("id") for p in providers.get("providers", [])]
- check("C10 未显式启用时不出现 fake", status == 200 and "fake" not in ids, f"ids={ids}")
- status, out = bare.json(
- "POST",
- "/chats",
- {"providerId": "fake", "model": "fake-stream", "messages": [{"role": "user", "content": "x"}]},
- )
- check("C10 未启用时 fake 对话被拒", status == 400, f"HTTP {status} {out}")
- finally:
- bare.stop()
-
- # 真实 provider 路径:本地假 OpenAI 端点,先 429 再流式
- upstream = fake_openai()
- try:
- base = f"http://127.0.0.1:{upstream.server_address[1]}/v1"
- channel2 = Channel(fake=False)
- try:
- status, started = channel2.start_chat(
- {
- "providerId": "custom",
- "model": "test-model",
- "apiKey": SENTINEL,
- "baseUrl": base,
- "messages": [{"role": "user", "content": "列模板"}],
- }
- )
- check("C11 自定义端点能开对话", status == 200 and started.get("ok") is True, f"HTTP {status} {started}")
- events, raw = channel2.events(started.get("chatId", ""))
- kinds = [e["event"] for e in events]
- check(
- "C11 429 后重试成功,聊天跑完",
- bool(events) and events[-1]["event"] == "done" and events[-1]["data"].get("reason") == "stop",
- f"最后事件 {events[-1] if events else None}",
- )
- check(
- "C11 reasoning 与 content 分开归一",
- any(e["event"] == "reasoning" and "想一想" in e["data"].get("text", "") for e in events)
- and any(e["event"] == "token" and "查模板" in e["data"].get("text", "") for e in events),
- f"事件 {kinds[:6]}",
- )
- tools_ok = [e for e in events if e["event"] == "tool_call" and e["data"].get("status") == "ok"]
- check("C11 分片 tool_call 被拼装并执行", bool(tools_ok) and tools_ok[0]["data"].get("result", {}).get("total") == 25, str(tools_ok[:1])[:200])
- check("C11 密钥不出现在事件流", SENTINEL not in raw, "已扫描整条 SSE")
- records = upstream.records # type: ignore[attr-defined]
- check("C11 provider 收到 3 次请求(1 次 429 + 两轮对话)", len(records) == 3, f"实得 {len(records)} 次")
- if len(records) >= 3:
- replay = records[2]["body"].get("messages") or []
- replayed = json.dumps(replay, ensure_ascii=False)
- check(
- "C11 回放历史已剥离 reasoning,且带 tool 结果",
- "reasoning_content" not in replayed
- and "reasoning" not in replayed
- and any(m.get("role") == "tool" for m in replay)
- and any(m.get("role") == "assistant" and m.get("tool_calls") for m in replay),
- f"第 3 次请求角色 {[m.get('role') for m in replay]}",
- )
- check("C11 密钥只出现在 Authorization 头", records[2].get("auth") == f"Bearer {SENTINEL}", "头部存在,正文不含")
-
- # C14 思考深度与上下文预算真的进入请求体
- before = len(records)
- status, started = channel2.start_chat(
- {
- "providerId": "custom",
- "model": "test-model",
- "apiKey": SENTINEL,
- "baseUrl": base,
- "thinking": "max",
- "contextTokens": 50000,
- "messages": [
- {"role": "user", "content": "数" * 30000 + "甲"},
- {"role": "assistant", "content": "数" * 30000 + "乙"},
- {"role": "user", "content": "最新问题"},
- ],
- }
- )
- events14, _ = channel2.events(started.get("chatId", ""))
- first_body = records[before]["body"] if len(records) > before else {}
- sent = first_body.get("messages") or []
- check(
- "C14 思维深度映射为 reasoning_effort",
- status == 200 and first_body.get("reasoning_effort") == "max",
- f"HTTP {status} effort={first_body.get('reasoning_effort')!r}",
- )
- check(
- "C14 上下文预算裁剪最早历史,保留锚点与最新一问",
- len(sent) == 3
- and sent[0].get("role") == "system"
- and str(sent[1].get("content") or "").startswith("【会话状态】")
- and sent[-1].get("content") == "最新问题"
- and all("数" * 100 not in str(m.get("content") or "") for m in sent),
- f"请求消息 {[(m.get('role'), str(m.get('content'))[:12]) for m in sent]}",
- )
- check(
- "C14 截断后对话仍能跑完",
- bool(events14) and events14[-1]["event"] == "done",
- f"最后事件 {events14[-1] if events14 else None}",
- )
-
- before = len(records)
- status, started = channel2.start_chat(
- {
- "providerId": "custom",
- "model": "test-model",
- "apiKey": SENTINEL,
- "baseUrl": base,
- "thinking": "max",
- "sendThinking": False,
- "messages": [{"role": "user", "content": "不发送深度"}],
- }
- )
- events15, _ = channel2.events(started.get("chatId", ""))
- off_body = records[before]["body"] if len(records) > before else {}
- check(
- "C14 关闭开关时不带 reasoning_effort",
- status == 200 and "reasoning_effort" not in off_body,
- f"字段={sorted(off_body.keys())[:8]}",
- )
-
- def mapped(provider_id: str, model_name: str, depth: str) -> dict:
- payload: dict = {}
- apply_reasoning(payload, find_provider(provider_id) or {}, model_name, depth)
- return payload
-
- deep = mapped("deepseek", "deepseek-flash", "medium")
- kimi = mapped("kimi", "kimi-k2.6", "max")
- qwen = mapped("qwen", "qwen3.8-max", "medium")
- check(
- "C14 预设深度的参数映射",
- deep.get("reasoning_effort") == "low"
- and kimi.get("thinking", {}).get("type") == "enabled"
- and qwen.get("reasoning_effort") == "medium",
- f"deepseek={deep} kimi-k2.6={kimi} qwen={qwen}",
- )
-
- # C15 上下文卡片:用户在对话里问该用什么模型,工具推送选模卡
- upstream.tool_name = "suggest_models"
- upstream.tool_args = '{"batch": 1, "question": "预测未来三个月的销量"}'
- status, started_card = channel2.start_chat(
- {
- "providerId": "custom",
- "model": "test-model",
- "apiKey": SENTINEL,
- "baseUrl": base,
- "messages": [{"role": "user", "content": "这道销量预测题该用什么模型?"}],
- }
- )
- card_events, card_raw = channel2.events(started_card.get("chatId", ""))
- card_problems, card_how = schema_validate(card_events)
- interrupts = [e for e in card_events if e["event"] == "interrupt"]
- payload = interrupts[0]["data"].get("payload", {}) if interrupts else {}
- cards = payload.get("candidates") or []
- from mms import orchestrator as _orch
-
- expected = _orch.model_candidates("预测未来三个月的销量", 1)
- check(
- "C15 选模卡通过 interrupt 事件推送",
- status == 200
- and bool(interrupts)
- and interrupts[0]["data"].get("card") == "model-choice"
- and len(cards) == 3
- and not card_problems,
- f"HTTP {status} interrupts={len(interrupts)} cards={len(cards)} 判据={card_how} {card_problems[:2]}",
- )
- check(
- "C15 卡片候选与编排器同源",
- [c.get("name") for c in cards] == [c.get("name") for c in expected],
- f"cards={[c.get('name') for c in cards]} expected={[c.get('name') for c in expected]}",
- )
- check("C15 卡片事件不含密钥", SENTINEL not in card_raw, "已扫描 SSE")
- upstream.tool_name = "list_templates"
- upstream.tool_args = '{"unused": true}'
- channel2.stop()
- check("C11 密钥不出现在服务器 stderr", SENTINEL not in channel2.stderr, "已扫描 stderr")
- finally:
- channel2.stop()
- finally:
- upstream.shutdown()
- upstream.server_close()
-
- # M3 编排闭环:暂停、恢复、换一批、选择,以及跨进程恢复
- workdir = tempfile.mkdtemp(prefix="mms-workflow-")
- try:
- wf = Channel(fake=True, env_extra={"MMS_DATA_DIR": workdir})
- try:
- problem = (
- "问题1 预测未来三个月的销量。\n问题2 给出补货建议。\n\n"
- "--- 附件(本机文件)---\n\n"
- "### sales.csv · 12 KB(120 行 × 3 列)\n"
- "month,region,sales\n2026-01,华东,120\n2026-02,华南,138\n\n"
- "--- 附件结束 ---"
- )
- status, started = wf.start_chat(
- {
- "providerId": "fake",
- "model": "fake-stream",
- "mode": "workflow",
- "messages": [{"role": "user", "content": problem}],
- }
- )
- sid = started.get("chatId", "")
- events, raw = wf.events(sid)
- problems, how = schema_validate(events)
- statuses = {e["data"]["phase"]: e["data"]["status"] for e in events if e["event"] == "phase"}
- card = next((e["data"] for e in events if e["event"] == "interrupt"), {})
- questions = card.get("payload", {}).get("questions", [])
- check(
- "C12 新赛题停在 K2,事件符合契约",
- status == 200 and not problems and events[-1]["data"].get("reason") == "waiting",
- f"HTTP {status};{problems[:2]};最后事件 {events[-1]['event'] if events else None}",
- )
- check(
- "C12 阶段 0 已过、阶段 1 等你确认",
- statuses.get(0) == "passed" and statuses.get(1) == "waiting",
- f"阶段状态 {statuses}",
- )
- attachments = card.get("payload", {}).get("attachments", [])
- check(
- "C12 K2 卡带子问题与附件清单",
- card.get("card") == "problem-confirm"
- and len(questions) >= 2
- and len(attachments) == 1
- and attachments[0].get("name") == "sales.csv"
- and bool(card.get("payload", {}).get("warning")),
- f"card={card.get('card')} questions={len(questions)} attachments={attachments}",
- )
- check(
- "C12 附件正文不参与子问题切分",
- all("month,region" not in str(q.get("text", "")) for q in questions),
- f"子问题 {[q.get('text', '')[:24] for q in questions]}",
- )
- check("C12 K2 的 SSE 不含密钥", SENTINEL not in raw, "已扫描整条 SSE")
-
- status, latest = wf.json("GET", "/sessions/latest")
- check(
- "C12 /sessions/latest 能读出待决卡",
- status == 200 and latest.get("session", {}).get("pending", {}).get("card") == "problem-confirm",
- f"HTTP {status} pending={(latest.get('session') or {}).get('pending', {}).get('card')}",
- )
-
- status, _ = wf.json("POST", f"/sessions/{sid}/resume", {"action": "confirm"})
- k3, _ = wf.events(sid)
- k3_card = next((e["data"] for e in k3 if e["event"] == "interrupt"), {})
- candidates = k3_card.get("payload", {}).get("candidates", [])
- k3_statuses = {e["data"]["phase"]: e["data"]["status"] for e in k3 if e["event"] == "phase"}
- check(
- "C12 确认后到 K3,三张候选且至少一项创新性高",
- status == 200
- and k3[-1]["data"].get("reason") == "waiting"
- and k3_card.get("card") == "model-choice"
- and len(candidates) == 3
- and any(c.get("innovation") == "高" for c in candidates),
- f"HTTP {status} candidates={len(candidates)} innovations={[c.get('innovation') for c in candidates]}",
- )
- check("C12 阶段 3 停在等你选", k3_statuses.get(3) == "waiting", f"阶段状态 {k3_statuses}")
-
- status, _ = wf.json("POST", f"/sessions/{sid}/resume", {"action": "reroll"})
- k3b, _ = wf.events(sid)
- card_b = next((e["data"] for e in k3b if e["event"] == "interrupt"), {})
- candidates_b = card_b.get("payload", {}).get("candidates", [])
- check(
- "C12 换一批返回新候选,待选不消失",
- status == 200
- and card_b.get("payload", {}).get("batch") == 2
- and candidates_b
- and candidates_b[0].get("name") != candidates[0].get("name")
- and k3b[-1]["data"].get("reason") == "waiting",
- f"batch={card_b.get('payload', {}).get('batch')} 首项 {candidates_b[0].get('name') if candidates_b else None}",
- )
-
- pick = candidates_b[0]["id"]
- status, _ = wf.json("POST", f"/sessions/{sid}/resume", {"action": "choose", "choice": pick})
- chosen, _ = wf.events(sid)
- chosen_statuses = {e["data"]["phase"]: e["data"]["status"] for e in chosen if e["event"] == "phase"}
- code_card = next((e["data"] for e in chosen if e["event"] == "interrupt"), {})
- status, latest = wf.json("GET", "/sessions/latest")
- session = latest.get("session") or {}
- check(
- "C12 选择后阶段 3 过、挂出代码确认卡,脚本未执行",
- status == 200
- and chosen_statuses.get(3) == "passed"
- and chosen_statuses.get(4) == "running"
- and code_card.get("card") == "code-confirm"
- and bool(code_card.get("payload", {}).get("code"))
- and session.get("pending", {}).get("card") == "code-confirm"
- and chosen[-1]["data"].get("reason") == "waiting",
- f"状态 {chosen_statuses} card={code_card.get('card')} reason={chosen[-1]['data'].get('reason')}",
- )
- status, _ = wf.json("POST", f"/sessions/{sid}/resume", {"action": "run"})
- ran, _ = wf.events(sid)
- ran_statuses = {e["data"]["phase"]: e["data"]["status"] for e in ran if e["event"] == "phase"}
- status, latest = wf.json("GET", "/sessions/latest")
- session = latest.get("session") or {}
- last_text = session.get("messages", [{}])[-1].get("content", "") if session.get("messages") else ""
- if FULL_CHAIN:
- check(
- "C12 点运行后阶段 4/5/6 全链完成,待决清空",
- status == 200
- and ran_statuses.get(4) == "passed"
- and ran_statuses.get(5) == "passed"
- and ran_statuses.get(6) == "passed"
- and session.get("pending") is None
- and ran[-1]["data"].get("reason") == "stop"
- and "阶段六完成" in last_text,
- f"状态 {ran_statuses} pending={session.get('pending')} 文本={last_text[:60]}",
- )
- else:
- print("SKIP 缺少排版工具或 MMS_PAPER_SKIP=1:C12/C18 只验到阶段四(未验证阶段五六)")
- check(
- "C12 点运行后阶段 4 完成(排版跳过,未验证阶段五六)",
- status == 200
- and ran_statuses.get(4) == "passed"
- and session.get("pending") is None,
- f"状态 {ran_statuses} pending={session.get('pending')}",
- )
- check(
- "C12 K3 的历史消息标了已选,K2 标了已确认",
- [m for m in session.get("messages", []) if m.get("interrupt") and m["interrupt"].get("resolved")]
- and all(
- m["interrupt"].get("resolved")
- for m in session.get("messages", [])
- if m.get("interrupt")
- ),
- f"resolved={[m.get('interrupt', {}).get('resolved') for m in session.get('messages', []) if m.get('interrupt')]}",
- )
- status, out = wf.json("POST", f"/sessions/{sid}/resume", {"action": "confirm"})
- check("C12 没有待决时恢复被拒", status == 409, f"HTTP {status} {out}")
- finally:
- wf.stop()
-
- # 跨进程:换一个服务器进程,仍然读得到上一次的待选
- wf2 = Channel(fake=True, env_extra={"MMS_DATA_DIR": workdir})
- try:
- status, started = wf2.start_chat(
- {
- "providerId": "fake",
- "model": "fake-stream",
- "mode": "workflow",
- "messages": [{"role": "user", "content": "问题1 给某城市做公交调度优化。"}],
- }
- )
- sid2 = started.get("chatId", "")
- wf2.events(sid2)
- finally:
- wf2.stop()
-
- wf3 = Channel(fake=True, env_extra={"MMS_DATA_DIR": workdir})
- try:
- status, latest = wf3.json("GET", "/sessions/latest")
- session = latest.get("session") or {}
- check(
- "C13 服务器重启后仍停在原来的 K2",
- status == 200
- and session.get("id") == sid2
- and session.get("pending", {}).get("card") == "problem-confirm",
- f"id={session.get('id')} pending={(session.get('pending') or {}).get('card')}",
- )
- check(
- "C13 会话表里没有哨兵密钥",
- SENTINEL not in json.dumps(session, ensure_ascii=False),
- "已扫描快照",
- )
- status, _ = wf3.json("POST", f"/sessions/{sid2}/resume", {"action": "confirm"})
- after, _ = wf3.events(sid2)
- check(
- "C13 重启后仍能确认并进入 K3",
- status == 200
- and any(e["event"] == "interrupt" and e["data"].get("card") == "model-choice" for e in after),
- f"HTTP {status} 事件 {[e['event'] for e in after][:6]}",
- )
- finally:
- wf3.stop()
-
- # C16 工作流 LLM 管道:fake 按阶段脚本出内容;resume 带 Key 时密钥不落盘不进事件
- wf4 = Channel(fake=True, env_extra={"MMS_DATA_DIR": workdir})
- try:
- status, started = wf4.start_chat(
- {
- "providerId": "fake",
- "model": "fake-stream",
- "mode": "workflow",
- "messages": [{"role": "user", "content": "问题1 预测销量。问题2 给出建议。"}],
- }
- )
- sid4 = started.get("chatId", "")
- events4, raw4 = wf4.events(sid4)
- card4 = next((e["data"] for e in events4 if e["event"] == "interrupt"), {})
- warning4 = str(card4.get("payload", {}).get("warning") or "")
- check(
- "C16 fake 工作流起题走阶段脚本,K2 卡标明离线演示",
- status == 200
- and card4.get("card") == "problem-confirm"
- and "离线演示" in warning4,
- f"HTTP {status} card={card4.get('card')} warning={warning4[:40]!r}",
- )
- status, _ = wf4.json(
- "POST",
- f"/sessions/{sid4}/resume",
- {"action": "confirm", "providerId": "fake", "model": "fake-stream", "apiKey": SENTINEL},
- )
- k34, raw34 = wf4.events(sid4)
- problems4, how4 = schema_validate(k34)
- status, latest4 = wf4.json("GET", "/sessions/latest")
- session4 = latest4.get("session") or {}
- check(
- "C16 带 Key 恢复仍走通 K3,事件符合契约且不含密钥",
- status == 200
- and not problems4
- and any(e["event"] == "interrupt" and e["data"].get("card") == "model-choice" for e in k34)
- and SENTINEL not in raw34
- and SENTINEL not in json.dumps(session4, ensure_ascii=False),
- f"HTTP {status} 判据={how4} {problems4[:2]}",
- )
- check(
- "C16 fake 恢复不带 Key 也走通(旧客户端兼容)",
- wf4.json("POST", f"/sessions/{sid4}/resume", {"action": "reroll"})[0] == 200,
- "reroll 无 Key",
- )
-
- # C17 代码确认卡走通道:事件符合契约,动作守卫有效,运行后阶段四过
- status, _ = wf4.json("POST", f"/sessions/{sid4}/resume", {"action": "choose", "choice": "c1"})
- code_events, code_raw = wf4.events(sid4)
- code_problems, code_how = schema_validate(code_events)
- code_card = next((e["data"] for e in code_events if e["event"] == "interrupt"), {})
- check(
- "C17 代码确认卡事件符合契约且带代码",
- status == 200
- and not code_problems
- and code_card.get("card") == "code-confirm"
- and bool(code_card.get("payload", {}).get("code"))
- and code_events[-1]["data"].get("reason") == "waiting",
- f"HTTP {status} 判据={code_how} {code_problems[:2]} card={code_card.get('card')}",
- )
- status, _ = wf4.json("POST", f"/sessions/{sid4}/resume", {"action": "confirm"})
- guard_events, _ = wf4.events(sid4)
- guard_error = next((e["data"].get("message", "") for e in guard_events if e["event"] == "error"), "")
- check(
- "C17 代码卡上点确认被拒(动作守卫)",
- status == 200 and "确认赛题" in guard_error,
- f"HTTP {status} error={guard_error[:60]!r}",
- )
- status, _ = wf4.json("POST", f"/sessions/{sid4}/resume", {"action": "run"})
- run_events, run_raw = wf4.events(sid4)
- run_problems, run_how = schema_validate(run_events)
- run_statuses = {e["data"]["phase"]: e["data"]["status"] for e in run_events if e["event"] == "phase"}
- check(
- "C17 通道点运行后阶段四通过",
- status == 200 and run_statuses.get(4) == "passed",
- f"HTTP {status} 状态 {run_statuses}",
- )
- if FULL_CHAIN:
- p5_gates = [e for e in run_events if e["event"] == "gate"]
- gate_ids = {e["data"].get("skill") for e in p5_gates}
- p5_paper = [e for e in run_events if e["event"] == "artifact" and e["data"].get("kind") == "paper"]
- p6_score = [e for e in run_events if e["event"] == "artifact" and e["data"].get("kind") == "score"]
- check(
- "C18 全链事件符合契约:三类门禁、论文与评分产物、阶段五六通过",
- not run_problems
- and run_statuses.get(5) == "passed"
- and run_statuses.get(6) == "passed"
- and gate_ids == {"phrasing", "style", "chapters"}
- and len(p5_paper) == 1
- and len(p6_score) == 1,
- f"判据={run_how} {run_problems[:2]} gates={sorted(gate_ids)} paper={len(p5_paper)} score={len(p6_score)} 状态={run_statuses}",
- )
- status, wb = wf4.json("GET", f"/workbench/state?session={sid4}")
- wb_rounds = (wb.get("score") or {}).get("rounds") or []
- wb_last = wb_rounds[-1] if wb_rounds else {}
- check(
- "C18 工作台按会话读到真实评分轮次(非演示三轮)",
- status == 200
- and 1 <= len(wb_rounds) < 3
- and wb_last.get("total") == 86
- and bool(wb_last.get("pass")),
- f"HTTP {status} rounds={len(wb_rounds)} total={wb_last.get('total')}",
- )
- finally:
- wf4.stop()
- finally:
- shutil.rmtree(workdir, ignore_errors=True)
-
- finish()
-
-
-def selftest() -> None:
- good = {"id": "1", "event": "token", "data": {"text": "好"}}
- cases = [
- ("合法事件应通过", good, True),
- ("缺 id", {"event": "token", "data": {"text": "x"}}, False),
- ("id 为 0", {"id": "0", "event": "token", "data": {"text": "x"}}, False),
- ("未知事件类型", {"id": "1", "event": "chunk", "data": {"text": "x"}}, False),
- ("token 缺 text", {"id": "1", "event": "token", "data": {}}, False),
- ("tool_call 状态非法", {"id": "1", "event": "tool_call", "data": {"id": "c", "name": "n", "status": "done"}}, False),
- ("done 原因非法", {"id": "1", "event": "done", "data": {"reason": "ok"}}, False),
- ("phase 状态非法", {"id": "1", "event": "phase", "data": {"phase": 3, "status": "done"}}, False),
- ("phase 越界", {"id": "1", "event": "phase", "data": {"phase": 7, "status": "running"}}, False),
- ("done.waiting 合法", {"id": "1", "event": "done", "data": {"reason": "waiting"}}, True),
- (
- "compaction 合法",
- {"id": "1", "event": "compaction", "data": {"reason": "auto", "before": 10, "after": 5, "pruned": 1, "summarized": 0, "dropped": 0}},
- True,
- ),
- (
- "compaction 缺字段",
- {"id": "1", "event": "compaction", "data": {"reason": "auto", "before": 10}},
- False,
- ),
- ]
- rows = []
- for label, ev, want_pass in cases:
- problems = lint_event(ev)
- rows.append({"label": label, "pass": (not problems) if want_pass else bool(problems), "detail": problems or "通过"})
- bad = [r for r in rows if not r["pass"]]
- for row in rows:
- print(f"{'PASS' if row['pass'] else 'FAIL'} {row['label']}\n {row['detail']}")
- print(f"\n{len(rows) - len(bad)}/{len(rows)} 条事件判据自测通过")
- raise SystemExit(0 if not bad else 1)
-
-
-def main(argv: list[str] | None = None) -> int:
- args = list(argv if argv is not None else sys.argv[1:])
- if "--selftest" in args:
- selftest()
- unknown = [value for value in args if value != "--selftest"]
- if unknown:
- print(f"用法错误: 未知参数 {unknown}", file=sys.stderr)
- return 2
- tests()
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/runtime/tests/selfcheck_harness.py b/runtime/tests/selfcheck_harness.py
deleted file mode 100644
index 9ee751c..0000000
--- a/runtime/tests/selfcheck_harness.py
+++ /dev/null
@@ -1,214 +0,0 @@
-"""G12 · 长会话 harness 自检:预算、压缩、摘要、锚点、溢出识别。
-
-纯逻辑,不联网、不启动窗口;50 轮会话用滚动调用 prepare 模拟。
-`--selftest` 把压缩拆掉,确认这些断言真的会红。
-"""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-from checklib import ROOT, check, report
-
-from mms import harness # noqa: E402
-
-
-def session_messages(turns: int, size: int = 400) -> list[dict]:
- rows = [{"role": "system", "content": "你是 mathmodel-studio 的建模助手。"}]
- for index in range(turns):
- rows.append({"role": "user", "content": f"第 {index + 1} 问:" + "数" * size})
- rows.append({"role": "assistant", "content": f"第 {index + 1} 答:" + "据" * size})
- return rows
-
-
-def tool_messages(count: int, size: int = 5000) -> list[dict]:
- rows = [{"role": "system", "content": "系统提示"}]
- rows.append({"role": "user", "content": "跑一遍模板清单"})
- rows.append(
- {
- "role": "assistant",
- "content": None,
- "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "list_templates", "arguments": "{}"}}],
- }
- )
- for index in range(count):
- rows.append(
- {
- "role": "tool",
- "tool_call_id": f"c{index}",
- "name": f"tool_{index}",
- "content": "结果" + "x" * size,
- }
- )
- return rows
-
-
-def run_checks() -> None:
- base = session_messages(3, size=20)
- plan = harness.prepare(base, None)
- check(
- "H1 没有预算时不动历史,只按需插锚点",
- [m["content"] for m in plan.messages] == [m["content"] for m in base] and plan.reason == "",
- f"messages={len(plan.messages)} reason={plan.reason}",
- )
-
- rows = tool_messages(6)
- plan = harness.prepare(rows, 12_000)
- tool_lens = [len(str(m.get("content") or "")) for m in plan.messages if m.get("role") == "tool"]
- check(
- "H2 超预算时先裁剪旧工具结果(保留头尾,最近两条不动)",
- plan.pruned >= 1 and any(harness.PRUNE_MARK.strip() in str(m.get("content")) for m in plan.messages),
- f"pruned={plan.pruned} tool_lens={tool_lens} after={plan.after}",
- )
- check(
- "H2 裁剪后仍然不超过预算比例",
- plan.after <= 12_000 * harness.COMPACT_RATIO,
- f"after={plan.after} limit={int(12_000 * harness.COMPACT_RATIO)}",
- )
-
- rows = session_messages(6, size=600)
- plan = harness.prepare(rows, 8_000)
- summary = plan.summary
- check(
- "H3 仍然超预算时把较早轮次压成结构化摘要",
- plan.summarized > 0 and summary.startswith(harness.SUMMARY_MARK),
- f"summarized={plan.summarized} summary={summary[:80]!r}",
- )
- check(
- "H3 摘要里保留用户与助手要点",
- "用户:" in summary and "助手:" in summary,
- summary[:160],
- )
-
- older = harness.prepare(session_messages(6, size=600), 8_000).messages
- again = harness.prepare(older, 4_000)
- check(
- "H3 二次压缩把旧摘要整段并入,不层层变薄",
- again.summary.count(harness.SUMMARY_MARK) == 1 and "第 1 问" in again.summary,
- f"summary={again.summary[:120]!r}",
- )
-
- anchored = harness.prepare(base, None, anchor=harness.anchor_text("预测销量", 2, ["工作区:D:/题"]))
- anchors = [m for m in anchored.messages if harness.is_anchor(m)]
- check(
- "H4 锚点插在系统提示之后,且只有一条",
- len(anchors) == 1 and harness.is_anchor(anchored.messages[1]) and "预测销量" in anchors[0]["content"],
- f"at={0 if harness.is_anchor(anchored.messages[0]) else 1} count={len(anchors)}",
- )
- replaced = harness.prepare(anchored.messages, None, anchor=harness.anchor_text("识别故障", 9))
- anchors = [m for m in replaced.messages if harness.is_anchor(m)]
- check(
- "H4 下一轮锚点被替换而不是累加",
- len(anchors) == 1 and "识别故障" in anchors[0]["content"] and "预测销量" not in anchors[0]["content"],
- f"count={len(anchors)} text={anchors[0]['content'][:60]!r}",
- )
-
- check(
- "H5 能认出常见的上下文溢出报错",
- harness.looks_like_overflow("Error code: 400 - context_length_exceeded")
- and harness.looks_like_overflow("This model's maximum context length is 65536 tokens")
- and not harness.looks_like_overflow("429 rate limit"),
- "markers",
- )
-
- huge = [
- {"role": "system", "content": "你是 mathmodel-studio 的建模助手。"},
- {"role": "user", "content": "数" * 8000 + "甲"},
- {"role": "assistant", "content": "数" * 8000 + "乙"},
- {"role": "user", "content": "最新问题"},
- ]
- plan = harness.prepare(huge, 5_000, anchor=harness.anchor_text("大消息", 3))
- check(
- "H8 单条就超预算时从最早处丢,锚点与最新一问保留",
- plan.dropped >= 1
- and plan.messages[-1]["content"] == "最新问题"
- and harness.is_anchor(plan.messages[1])
- and all(len(str(m.get("content") or "")) < 8_000 for m in plan.messages),
- f"dropped={plan.dropped} after={plan.after} roles={[m['role'] for m in plan.messages]}",
- )
-
- rows = session_messages(50, size=400)
- plan = harness.prepare(rows, 20_000)
- tail = [str(m.get("content") or "") for m in plan.messages[-6:]]
- expected_tail = [str(m.get("content") or "") for m in rows[-6:]]
- check(
- "H6 50 轮压到预算内,最近 6 条原文保留",
- plan.after <= 20_000 * harness.COMPACT_RATIO and tail == expected_tail,
- f"after={plan.after} kept={len(plan.messages)}",
- )
- check(
- "H6 压缩后第一条仍是系统提示",
- plan.messages[0].get("role") == "system" and plan.messages[0]["content"].startswith("你是"),
- plan.messages[0].get("content", "")[:40],
- )
-
- rolling = [{"role": "system", "content": "你是 mathmodel-studio 的建模助手。"}]
- peak = 0
- for index in range(50):
- rolling.append({"role": "user", "content": f"第 {index + 1} 问:" + "数" * 400})
- rolling = harness.prepare(
- rolling, 30_000, anchor=harness.anchor_text("一道 50 轮的题", index + 1)
- ).messages
- rolling.append({"role": "assistant", "content": f"第 {index + 1} 答:" + "据" * 400})
- peak = max(peak, harness.usage(rolling))
- anchors = [m for m in rolling if harness.is_anchor(m)]
- check(
- "H7 滚动 50 轮始终不超预算,消息数有界",
- peak <= 30_000 and len(rolling) <= 30,
- f"peak={peak} messages={len(rolling)}",
- )
- check(
- "H7 长会话里锚点仍只有一条且指向当前轮",
- len(anchors) == 1 and "已进行 50 轮" in anchors[0]["content"],
- anchors[0]["content"][:60] if anchors else "(没有锚点)",
- )
-
-
-def run_self_test() -> int:
- negative: list[tuple[str, bool, str]] = []
-
- original_prepare = harness.prepare
- harness.prepare = lambda messages, budget=None, **kwargs: harness.Plan(
- messages=list(messages),
- before=harness.usage(messages),
- after=harness.usage(messages),
- )
- try:
- rows = session_messages(50, size=400)
- plan = harness.prepare(rows, 20_000)
- caught = plan.after > 20_000 * harness.COMPACT_RATIO
- detail = f"after={plan.after} limit={int(20_000 * harness.COMPACT_RATIO)}"
- finally:
- harness.prepare = original_prepare
- negative.append(("N1 压缩被拆掉时,H6 的预算断言真的会红", caught, detail))
-
- original_prune = harness._prune_tool_results
- harness._prune_tool_results = lambda messages, protect_tail=2: (list(messages), 0)
- try:
- rows = tool_messages(6)
- plan = harness.prepare(rows, 12_000)
- caught = plan.pruned == 0 or not any(
- harness.PRUNE_MARK.strip() in str(m.get("content")) for m in plan.messages
- )
- detail = f"pruned={plan.pruned}"
- finally:
- harness._prune_tool_results = original_prune
- negative.append(("N2 工具结果裁剪被关掉时,H2 真的会红", caught, detail))
-
- failed = [row for row in negative if not row[1]]
- for name, ok, detail in negative:
- print(f"{'PASS' if ok else 'FAIL'} {name}\n {detail}")
- print(f"\n{len(negative) - len(failed)}/{len(negative)} 条反向覆盖通过")
- return 0 if not failed else 1
-
-
-def main(argv: list[str]) -> int:
- if "--selftest" in argv:
- return run_self_test()
- run_checks()
- return report("harness 断言通过")
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv[1:]))
diff --git a/runtime/tests/selfcheck_orchestrator.py b/runtime/tests/selfcheck_orchestrator.py
deleted file mode 100644
index c172ab0..0000000
--- a/runtime/tests/selfcheck_orchestrator.py
+++ /dev/null
@@ -1,647 +0,0 @@
-"""G11 · 编排状态机自检:起题 → K2 确认 → K3 选模 → 进入阶段四。
-
-不依赖窗口、不联网、不读真实 Key;只用临时目录里的 SQLite。
-回归点:英文题面不含中文关键词时走默认方法族,`DEFAULT_FAMILY` 曾写成单元素元组,
-`_candidates` 拿到的是一串候选 dict,`dict()` 抛 ValueError 被界面原样显示。
-`--selftest` 把同样的坏形状塞回去,确认这些断言真的会红。
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import shutil
-import sys
-import tempfile
-from pathlib import Path
-
-from checklib import ROOT, check, report
-
-from mms import llm, orchestrator, paper_build, workbench_figure # noqa: E402
-from mms.store import SessionStore # noqa: E402
-
-# 阶段四的节奏停顿只影响观感,自检里关掉。
-os.environ.setdefault("MMS_WORKFLOW_DELAY_MS", "0")
-
-# 与 G10 同一约定:没有 TeX 的环境显式 MMS_PAPER_SKIP=1 跳过阶段五六断言,
-# 跳过打印「未验证」,不当成通过。
-PAPER_SKIP = os.environ.get("MMS_PAPER_SKIP") == "1"
-FULL_CHAIN = paper_build.env_status()["ok"] and not PAPER_SKIP
-
-# 不匹配任何关键词族:APMCM 那道英文机器人题面的形态。
-ENGLISH_PROBLEM = (
- "Optimization of Robot's Performance. The safety of the robot motor is the core of "
- "operation, and the stability of its power output directly affects the safety."
-)
-KEYWORD_PROBLEM = "预测某城市未来五年的用电需求,并给出区间估计。"
-PLAIN_PROBLEM = "一道没有任何关键词的题,只有场景描述。"
-PREDICTION_FAMILY = {"梯度提升回归", "SARIMAX 时间序列", "高斯过程回归"}
-
-def interrupt_card(events: list[dict]) -> dict:
- for event in events:
- if event["event"] == "interrupt":
- return event["data"] or {}
- return {}
-
-
-def candidate_names(events: list[dict]) -> list[str]:
- payload = interrupt_card(events).get("payload") or {}
- return [str(item.get("name")) for item in payload.get("candidates") or []]
-
-
-def phase_status(record: dict) -> dict[int, str]:
- return {int(row["phase"]): str(row["status"]) for row in record["phases"]}
-
-
-def confirm_flow(store: SessionStore, problem: str) -> tuple[dict, list[dict]]:
- record = store.create("chat-1", "deepseek", "deepseek-flash", problem)
- orchestrator.start(store, record)
- return record, orchestrator.resume(store, record, "confirm", "")
-
-
-def run_checks(workdir: Path) -> None:
- store = SessionStore(workdir / "en.db")
- record = store.create("chat-1", "deepseek", "deepseek-flash", ENGLISH_PROBLEM)
- started = orchestrator.start(store, record)
- status = phase_status(record)
- card = interrupt_card(started)
- check(
- "K1 起题:阶段一等你确认,挂出赛题确认卡,消息落盘两条",
- status.get(0) == "passed"
- and status.get(1) == "waiting"
- and card.get("card") == "problem-confirm"
- and len(record["messages"]) == 2,
- f"phases={status} card={card.get('card')} messages={len(record['messages'])}",
- )
-
- confirmed = orchestrator.resume(store, record, "confirm", "")
- names = candidate_names(confirmed)
- check(
- "K2 英文题面(无中文关键词)确认后给出 3 条不同候选(回归)",
- len(names) == 3 and len(set(names)) == 3,
- f"names={names}",
- )
-
- status = phase_status(record)
- check(
- "K2 阶段二三通过、阶段四等你确认,待决卡换成选模",
- status.get(2) == "passed"
- and status.get(3) == "waiting"
- and (record["pending"] or {}).get("card") == "model-choice",
- f"phases={status} pending={(record['pending'] or {}).get('card')}",
- )
-
- rerolled = orchestrator.resume(store, record, "reroll", "")
- reroll_names = candidate_names(rerolled)
- check(
- "K3 换一批:batch 递增,仍给 3 条不同候选",
- record["batch"] == 2 and len(reroll_names) == 3 and len(set(reroll_names)) == 3,
- f"batch={record['batch']} names={reroll_names}",
- )
-
- chosen = orchestrator.resume(store, record, "choose", "c1")
- status = phase_status(record)
- check(
- "K3 选模后挂出代码确认卡,脚本未执行(执行严格在确认之后)",
- status.get(3) == "passed"
- and status.get(4) == "running"
- and (record["pending"] or {}).get("card") == "code-confirm",
- f"phases={status} pending={(record['pending'] or {}).get('card')} events={[e['event'] for e in chosen]}",
- )
- chosen = orchestrator.resume(store, record, "run", "")
- status = phase_status(record)
- if FULL_CHAIN:
- check(
- "K3 点运行后阶段四五六全链跑完(离线兜底)、待决清空",
- status.get(4) == "passed"
- and status.get(5) == "passed"
- and status.get(6) == "passed"
- and record["pending"] is None,
- f"phases={status} pending={record['pending']} events={[e['event'] for e in chosen]}",
- )
- else:
- print("SKIP 缺少排版工具或 MMS_PAPER_SKIP=1:K3/K7/L9–L14 只验到阶段四(未验证阶段五六)")
- check(
- "K3 点运行后阶段四跑完、待决清空(排版跳过,未验证阶段五六)",
- status.get(4) == "passed" and record["pending"] is None,
- f"phases={status} pending={record['pending']}",
- )
-
- reloaded = SessionStore(workdir / "en.db").get("chat-1")
- check(
- "K3 选择结果已落盘,换个连接读回一致",
- reloaded is not None
- and len(reloaded["messages"]) == len(record["messages"])
- and reloaded["batch"] == 2,
- f"messages={len(reloaded['messages']) if reloaded else None}",
- )
-
- keyword_store = SessionStore(workdir / "keyword.db")
- _, keyword_events = confirm_flow(keyword_store, KEYWORD_PROBLEM)
- keyword_names = candidate_names(keyword_events)
- check(
- "K4 含关键词的题面走预测方法族",
- set(keyword_names) == PREDICTION_FAMILY,
- f"names={keyword_names}",
- )
-
- plain_store = SessionStore(workdir / "plain.db")
- _, plain_events = confirm_flow(plain_store, PLAIN_PROBLEM)
- plain_names = candidate_names(plain_events)
- check(
- "K5 无关键词题面回落到默认族,3 条互不相同",
- len(plain_names) == 3 and len(set(plain_names)) == 3,
- f"names={plain_names}",
- )
-
- pending = plain_store.get("chat-1")
- try:
- orchestrator.resume(plain_store, pending, "confirm", "")
- except ValueError as exc:
- rejected, detail = "当前不是在确认赛题" in str(exc), str(exc)
- else:
- rejected, detail = False, "没有抛错"
- check("K6 卡类型不对的动作被拒绝,不静默通过", rejected, detail)
-
- workspace = workdir / "workspace"
- attach = workspace / "附件" / "2026-11-01"
- attach.mkdir(parents=True)
- rows = ["x1,x2,y"] + [
- f"{index},{round(index * 0.5, 2)},{round(2.4 * index + 1.2 * index * 0.5 + (index % 3) * 0.1, 3)}"
- for index in range(1, 41)
- ]
- (attach / "sales.csv").write_text("\n".join(rows) + "\n", encoding="utf-8")
-
- phase_store = SessionStore(workdir / "phase.db")
- phase_record = phase_store.create("chat-phase", "deepseek", "deepseek-flash", ENGLISH_PROBLEM)
- orchestrator.start(phase_store, phase_record)
- orchestrator.resume(phase_store, phase_record, "confirm", "")
- choose_events = orchestrator.resume(phase_store, phase_record, "choose", "c1", str(workspace))
- run_events = orchestrator.resume(phase_store, phase_record, "run", "", str(workspace))
- phase_events = choose_events + run_events
- # 阶段五/六的工具卡以 p5-/p6- 开头;这里只统计阶段四的五个步骤。
- finished = [
- event
- for event in phase_events
- if event["event"] == "tool_call"
- and event["data"].get("status") != "running"
- and not str(event["data"].get("id") or "").startswith(("p5-", "p6-"))
- ]
- artifact = [
- event
- for event in phase_events
- if event["event"] == "artifact" and event["data"].get("kind") == "figure"
- ]
- figure = workbench_figure.state_payload(data_dir=phase_store.path.parent)
- outputs = (figure.get("versions") or [{}])[-1].get("outputs") or {}
- code_dir = phase_store.path.parent / "workbench" / "code"
- status = phase_status(phase_record)
- summary = "\n".join(str(m.get("content") or "") for m in phase_record["messages"])
- check(
- "K7 阶段四:五个工具步骤全部落地,工作区的 CSV 被真读进去",
- len(finished) == 5
- and all(event["data"].get("status") == "ok" for event in finished)
- and "sales.csv" in summary
- and "40 行" in summary,
- f"steps={[(e['data']['name'], e['data'].get('status')) for e in finished]} summary={summary[:80]!r}",
- )
- check(
- "K7 阶段四:PNG/PDF/SVG 三件产物登记成图表版本",
- len(artifact) == 1
- and {"png", "pdf", "svg"} <= set(outputs)
- and all(Path(outputs[kind]).is_file() and Path(outputs[kind]).stat().st_size > 0 for kind in outputs),
- f"artifact={bool(artifact)} outputs={sorted(outputs)}",
- )
- check(
- "K7 阶段四:代码与结果落盘,阶段四通过" + ("、五六全链完成" if FULL_CHAIN else "(排版跳过)"),
- (code_dir / "solution.py").is_file()
- and (code_dir / "outputs" / "result.json").is_file()
- and status.get(4) == "passed"
- and (status.get(5) == "passed" and status.get(6) == "passed" if FULL_CHAIN else True)
- and phase_record["pending"] is None,
- f"phases={status} pending={phase_record['pending']}",
- )
-
- empty = workdir / "empty-workspace"
- empty.mkdir()
- sample_store = SessionStore(workdir / "sample.db")
- sample_record = sample_store.create("chat-sample", "deepseek", "deepseek-flash", PLAIN_PROBLEM)
- orchestrator.start(sample_store, sample_record)
- orchestrator.resume(sample_store, sample_record, "confirm", "")
- sample_choose = orchestrator.resume(sample_store, sample_record, "choose", "c1", str(empty))
- sample_events = sample_choose + orchestrator.resume(sample_store, sample_record, "run", "", str(empty))
- sample_figure = workbench_figure.state_payload(data_dir=sample_store.path.parent)
- sample_tools = {
- event["data"]["name"]: event["data"].get("result")
- for event in sample_events
- if event["event"] == "tool_call" and event["data"].get("status") == "ok"
- }
- sample_text = "\n".join(str(m.get("content") or "") for m in sample_record["messages"])
- check(
- "K8 工作区没有数据时用内置示例把链路跑通,并在对话里说明",
- bool((sample_tools.get("定位数据") or {}).get("sample"))
- and bool(sample_figure.get("versions"))
- and "示例数据" in sample_text,
- f"locate={sample_tools.get('定位数据')} versions={len(sample_figure.get('versions') or [])}",
- )
-
-
-def run_llm_checks(workdir: Path) -> None:
- """LLM 注入层:fake 按阶段路由、坏输出重试与回退、选模落盘。"""
- fake = {"id": "fake", "base_url": "", "tool_calling": True}
-
- store = SessionStore(workdir / "llm.db")
- record = store.create("aabbccdd11", "fake", "fake-stream", KEYWORD_PROBLEM)
- orchestrator.start(store, record, provider=fake)
- card = (record["pending"] or {}).get("payload") or {}
- check(
- "L1 fake 起题:K2 卡由阶段脚本生成,子问题非空且标明离线演示",
- bool(card.get("questions")) and "离线演示" in str(card.get("warning") or ""),
- f"questions={len(card.get('questions') or [])} warning={str(card.get('warning'))[:40]!r}",
- )
-
- events = orchestrator.resume(store, record, "confirm", "", provider=fake)
- names = candidate_names(events)
- check(
- "L2 fake 确认后 K3 候选与确定性方法族同源(离线不冒充模型判断)",
- set(names) == PREDICTION_FAMILY,
- f"names={names}",
- )
-
- orchestrator.resume(store, record, "choose", "c1", provider=fake)
- orchestrator.resume(store, record, "run", "", provider=fake)
- reloaded = SessionStore(workdir / "llm.db").get("aabbccdd11")
- check(
- "L3 选模结果落盘:picked 列跨连接可读,阶段四按所选继续",
- reloaded is not None
- and (reloaded.get("picked") or {}).get("name") == names[0]
- and phase_status(reloaded).get(4) == "passed",
- f"picked={(reloaded or {}).get('picked')}",
- )
-
- # 坏 JSON:第一次回喂重试,第二次合法 → 成功
- calls = {"n": 0}
-
- def flaky_complete(provider, api_key, model, messages, should_stop=None, on_delta=None, depth=""):
- calls["n"] += 1
- if calls["n"] == 1:
- return "这不是 JSON"
- return json.dumps(
- {
- "questions": [{"id": "q1", "text": "子问题一", "data": "未附数据文件"}],
- "dataRoles": [],
- "warning": "测试提醒",
- },
- ensure_ascii=False,
- )
-
- original_complete = llm.complete
- llm.complete = flaky_complete
- try:
- payload = orchestrator._problem_payload_llm("题面", fake, "", "m")
- check(
- "L4 坏 JSON 回喂重试一次后成功,重试真的发生",
- calls["n"] == 2 and payload["questions"][0]["text"] == "子问题一",
- f"calls={calls['n']} payload={str(payload)[:60]}",
- )
-
- calls["n"] = 0
-
- def always_bad(provider, api_key, model, messages, should_stop=None, on_delta=None, depth=""):
- calls["n"] += 1
- return "还是坏输出"
-
- llm.complete = always_bad
- payload = orchestrator._problem_payload_llm("题面", fake, "", "m")
- check(
- "L5 两次都坏时回退确定性切分,并在警告里标明兜底",
- calls["n"] == 2
- and bool(payload.get("questions"))
- and "回退" in str(payload.get("warning") or ""),
- f"calls={calls['n']} warning={str(payload.get('warning'))[:60]!r}",
- )
-
- candidates_payload = orchestrator._model_payload_llm("预测销量", 1, fake, "", "m")
- check(
- "L6 K3 模型不可用时回退内置方法族并标明兜底",
- len(candidates_payload.get("candidates") or []) == 3
- and "兜底" in str(candidates_payload.get("intro") or ""),
- f"intro={str(candidates_payload.get('intro'))[:40]!r}",
- )
- finally:
- llm.complete = original_complete
-
- # 校验器:缺推荐、缺创新高项、数量不对都必须拒绝
- def candidate(**over):
- base = {
- "name": "方法", "idea": "思路", "innovation": "中", "interpretability": "中",
- "difficulty": "中", "eta": "1–2 小时", "accuracy": "中",
- "math": "公式", "fit": "适配", "diff": "差异", "verify": "验证",
- "recommended": False, "reason": "",
- }
- base.update(over)
- return base
-
- good = [candidate(recommended=True), candidate(), candidate(innovation="高")]
- try:
- orchestrator._validate_candidates({"candidates": good})
- ok_good = True
- except ValueError:
- ok_good = False
- rejected = 0
- for bad in (
- {"candidates": good[:2]},
- {"candidates": [candidate(), candidate(), candidate(innovation="高")]},
- {"candidates": [candidate(recommended=True), candidate(recommended=True), candidate(innovation="高")]},
- ):
- try:
- orchestrator._validate_candidates(bad)
- except ValueError:
- rejected += 1
- check(
- "L7 候选校验:合法形状通过;缺项/无推荐/无高创新都被拒",
- ok_good and rejected == 3,
- f"ok_good={ok_good} rejected={rejected}/3",
- )
-
- check(
- "L8 阶段标记识别与围栏剥离",
- llm.stage_of([{"role": "system", "content": llm.stage_prompt("k2-problem", "指令")}]) == "k2-problem"
- and llm.stage_of([{"role": "system", "content": "普通聊天"}]) == ""
- and llm.parse_json('```json\n{"a": 1}\n```') == {"a": 1},
- "stage_of / parse_json",
- )
-
- # L9 代码确认卡:choose 后脚本未执行;run 动作只在 code-confirm 上有效
- cstore = SessionStore(workdir / "code.db")
- crecord = cstore.create("ccddeeff22", "fake", "fake-stream", PLAIN_PROBLEM)
- orchestrator.start(cstore, crecord)
- orchestrator.resume(cstore, crecord, "confirm", "")
- choose_events = orchestrator.resume(cstore, crecord, "choose", "c1")
- cpayload = (crecord["pending"] or {}).get("payload") or {}
- crun_called = {"n": 0}
- original_run = orchestrator.baseline.run_baseline
-
- def counting_run(*args, **kwargs):
- crun_called["n"] += 1
- return original_run(*args, **kwargs)
-
- orchestrator.baseline.run_baseline = counting_run
- try:
- check(
- "L9 代码卡带代码与轮次,choose 全程没有执行脚本",
- (crecord["pending"] or {}).get("card") == "code-confirm"
- and bool(cpayload.get("code"))
- and cpayload.get("round") == 1
- and crun_called["n"] == 0
- and any(e["event"] == "interrupt" for e in choose_events),
- f"card={(crecord['pending'] or {}).get('card')} round={cpayload.get('round')} runs={crun_called['n']}",
- )
- try:
- orchestrator.resume(cstore, crecord, "confirm", "")
- guard_ok = False
- except ValueError as exc:
- guard_ok = "确认赛题" in str(exc)
- check("L9 代码卡上点确认被拒绝,不静默通过", guard_ok, "action guard")
- orchestrator.resume(cstore, crecord, "run", "")
- check(
- "L9 点运行才执行,产物登记、阶段四通过" + ("、全链完成" if FULL_CHAIN else "(排版跳过)"),
- crun_called["n"] == 1
- and phase_status(crecord).get(4) == "passed"
- and (phase_status(crecord).get(5) == "passed" and phase_status(crecord).get(6) == "passed" if FULL_CHAIN else True)
- and crecord["pending"] is None,
- f"runs={crun_called['n']} phases={phase_status(crecord)}",
- )
- finally:
- orchestrator.baseline.run_baseline = original_run
-
- # L10 运行失败 → 回喂修复:第二轮真跑成功;无模型时直接失败
- BAD_CODE = (
- "import argparse\n"
- "parser = argparse.ArgumentParser()\n"
- "parser.add_argument('--data')\n"
- "parser.add_argument('--out')\n"
- "args = parser.parse_args()\n"
- "raise RuntimeError('故意失败:测试修复环')\n"
- "# result.json figure.png\n"
- )
- fstore = SessionStore(workdir / "fix.db")
- frecord = fstore.create("ddeeff3344", "fake", "fake-stream", PLAIN_PROBLEM)
- orchestrator.start(fstore, frecord)
- orchestrator.resume(fstore, frecord, "confirm", "")
- orchestrator.resume(fstore, frecord, "choose", "c1")
- fcard = frecord["pending"]["payload"]
- fcard["code"] = BAD_CODE
- Path(fcard["scriptPath"]).write_text(BAD_CODE, encoding="utf-8")
- fstore.put(frecord)
- fix_events = orchestrator.resume(fstore, frecord, "run", "", provider=fake)
- fix_card = (frecord["pending"] or {}).get("payload") or {}
- check(
- "L10 第一轮失败后回喂模型,第二轮代码卡出现且未自动执行",
- (frecord["pending"] or {}).get("card") == "code-confirm"
- and fix_card.get("round") == 2
- and phase_status(frecord).get(4) == "running",
- f"round={fix_card.get('round')} phases={phase_status(frecord)}",
- )
- orchestrator.resume(fstore, frecord, "run", "", provider=fake)
- check(
- "L10 第二轮(fake 返回基线脚本)运行成功" + (",全链完成" if FULL_CHAIN else "(排版跳过)"),
- phase_status(frecord).get(4) == "passed"
- and (phase_status(frecord).get(5) == "passed" and phase_status(frecord).get(6) == "passed" if FULL_CHAIN else True)
- and frecord["pending"] is None,
- f"phases={phase_status(frecord)}",
- )
-
- nstore = SessionStore(workdir / "nofix.db")
- nrecord = nstore.create("eeff445566", "fake", "fake-stream", PLAIN_PROBLEM)
- orchestrator.start(nstore, nrecord)
- orchestrator.resume(nstore, nrecord, "confirm", "")
- orchestrator.resume(nstore, nrecord, "choose", "c1")
- ncard = nrecord["pending"]["payload"]
- ncard["code"] = BAD_CODE
- Path(ncard["scriptPath"]).write_text(BAD_CODE, encoding="utf-8")
- nstore.put(nrecord)
- orchestrator.resume(nstore, nrecord, "run", "")
- ntext = str(nrecord["messages"][-1].get("content") or "")
- check(
- "L10 没有可用模型时运行失败直接终止,不假装修复",
- phase_status(nrecord).get(4) == "failed"
- and nrecord["pending"] is None
- and "没有可用模型" in ntext,
- f"phases={phase_status(nrecord)} text={ntext[:60]!r}",
- )
-
-def run_paper_checks(workdir: Path) -> None:
- """L11–L14:阶段五六全链(论文真排版、真实评分、否决)。需要 TeX,仅在排版可用时跑。"""
- fake = {"id": "fake", "base_url": "", "tool_calling": True}
- # L11 阶段五:fake 兜底样例稿真排版,产物落盘、门禁事件齐全、兜底有标注
- pstore = SessionStore(workdir / "paper.db")
- precord = pstore.create("ff5566778899", "fake", "fake-stream", PLAIN_PROBLEM)
- orchestrator.start(pstore, precord, provider=fake)
- orchestrator.resume(pstore, precord, "confirm", "", provider=fake)
- orchestrator.resume(pstore, precord, "choose", "c1", provider=fake)
- p5_events = orchestrator.resume(pstore, precord, "run", "", provider=fake)
- p5_status = phase_status(precord)
- paper_dir = pstore.path.parent / "sessions" / "ff5566778899" / "workbench" / "paper"
- gate_events = [e for e in p5_events if e["event"] == "gate"]
- paper_artifact = [e for e in p5_events if e["event"] == "artifact" and e["data"].get("kind") == "paper"]
- all_text = "\n".join(str(m.get("content") or "") for m in precord["messages"])
- gate_ids = {e["data"].get("skill") for e in gate_events}
- check(
- "L11 阶段五自动完成:PDF/DOCX 落盘、三类门禁全绿、paper 产物事件",
- p5_status.get(5) == "passed"
- and (paper_dir / "paper.pdf").is_file()
- and (paper_dir / "paper.docx").is_file()
- and gate_ids == {"phrasing", "style", "chapters"}
- and all(e["data"].get("ok") for e in gate_events)
- and len(paper_artifact) == 1,
- f"phases={p5_status} gates={sorted(gate_ids)} artifact={len(paper_artifact)}",
- )
- check(
- "L11 离线兜底论文明确标注,不冒充按本题生成",
- "兜底" in all_text and "样例稿" in all_text,
- f"text={all_text[-120:]!r}",
- )
-
- # L12 阶段六:评分卡落盘、按会话读真实轮次、达标判定
- from mms import score_gen, workbench_score
-
- p6_status = phase_status(precord)
- score_file = pstore.path.parent / "sessions" / "ff5566778899" / "workbench" / "score" / "round-1.json"
- real_state = workbench_score.state(data_dir=pstore.path.parent / "sessions" / "ff5566778899")
- real_rounds = real_state.get("rounds") or []
- p6_text = "\n".join(str(m.get("content") or "") for m in precord["messages"])
- last_round = real_rounds[-1] if real_rounds else {}
- check(
- "L12 阶段六完成:评分卡落盘、工作台读到真实轮次、末轮达标",
- p6_status.get(6) == "passed"
- and score_file.is_file()
- and len(real_rounds) >= 1
- and last_round.get("total") == 86
- and bool(last_round.get("pass"))
- and "86" in p6_text,
- f"phases={p6_status} rounds={len(real_rounds)} total={last_round.get('total')}",
- )
- check(
- "L12 离线兜底评分明确标注,不冒充真实评审",
- "评分暂用演示评分卡兜底" in p6_text,
- f"text={p6_text[-100:]!r}",
- )
-
- # L13 评分校验器:合法卡通过;缺维度/超分/重复都被拒
- good_card = score_gen.demo_card(1)
- try:
- score_gen._validate_card(good_card)
- ok_card = True
- except ValueError:
- ok_card = False
- rejected = 0
- bad_cards = [
- {"dimensions": good_card["dimensions"][:4]},
- {"dimensions": [dict(d, score=999) if d["id"] == "abstract" else d for d in good_card["dimensions"]]},
- {"dimensions": good_card["dimensions"] + [good_card["dimensions"][0]]},
- ]
- for bad in bad_cards:
- try:
- score_gen._validate_card(bad)
- except ValueError:
- rejected += 1
- check(
- "L13 评分卡校验:合法通过;缺维度/超分/重复都拒",
- ok_card and rejected == 3,
- f"ok={ok_card} rejected={rejected}/3",
- )
-
- # L14 一票否决:veto 卡直接淘汰,阶段六判 failed,不进优化循环
- vstore = SessionStore(workdir / "veto.db")
- vrecord = vstore.create("aa9988776655", "fake", "fake-stream", PLAIN_PROBLEM)
- orchestrator.start(vstore, vrecord, provider=fake)
- orchestrator.resume(vstore, vrecord, "confirm", "", provider=fake)
- orchestrator.resume(vstore, vrecord, "choose", "c1", provider=fake)
- original_demo = score_gen.demo_card
-
- def veto_card(round_no=1):
- card = original_demo(round_no)
- card["veto"] = True
- return card
-
- score_gen.demo_card = veto_card
- try:
- orchestrator.resume(vstore, vrecord, "run", "", provider=fake)
- finally:
- score_gen.demo_card = original_demo
- vstatus = phase_status(vrecord)
- vtext = "\n".join(str(m.get("content") or "") for m in vrecord["messages"])
- check(
- "L14 一票否决直接淘汰:阶段六 failed、不进优化循环",
- vstatus.get(6) == "failed"
- and "一票否决" in vtext
- and vstatus.get(5) == "passed",
- f"phases={vstatus} text={vtext[-80:]!r}",
- )
-
-
-def run_self_test() -> int:
- negative: list[tuple[str, bool, str]] = []
-
- original_family = orchestrator.DEFAULT_FAMILY
- orchestrator.DEFAULT_FAMILY = (original_family,) # 复现旧 bug:单元素元组
- caught = False
- detail = ""
- workdir = Path(tempfile.mkdtemp(prefix="mms-orchestrator-neg-"))
- try:
- store = SessionStore(workdir / "neg.db")
- record = store.create("chat-neg", "deepseek", "deepseek-flash", ENGLISH_PROBLEM)
- orchestrator.start(store, record)
- orchestrator.resume(store, record, "confirm", "")
- except ValueError as exc:
- caught = "dictionary update sequence element" in str(exc)
- detail = str(exc)
- else:
- detail = "没有抛错"
- finally:
- orchestrator.DEFAULT_FAMILY = original_family
- shutil.rmtree(workdir, ignore_errors=True)
- negative.append(("N1 默认族写成单元素元组时,K2 真的会红", caught, detail))
-
- original_families = list(orchestrator.FAMILIES)
- orchestrator.FAMILIES[:] = [] # 关键词族被清空后,关键词题面会落到默认族
- caught = False
- detail = ""
- workdir = Path(tempfile.mkdtemp(prefix="mms-orchestrator-neg2-"))
- try:
- store = SessionStore(workdir / "neg.db")
- _, events = confirm_flow(store, KEYWORD_PROBLEM)
- names = candidate_names(events)
- caught = set(names) != PREDICTION_FAMILY
- detail = f"names={names}"
- finally:
- orchestrator.FAMILIES[:] = original_families
- shutil.rmtree(workdir, ignore_errors=True)
- negative.append(("N2 关键词族被清空时,K4 真的会红", caught, detail))
-
- failed = [row for row in negative if not row[1]]
- for name, ok, detail in negative:
- print(f"{'PASS' if ok else 'FAIL'} {name}\n {detail}")
- print(f"\n{len(negative) - len(failed)}/{len(negative)} 条反向覆盖通过")
- return 0 if not failed else 1
-
-
-def main(argv: list[str]) -> int:
- if "--selftest" in argv:
- return run_self_test()
-
- workdir = Path(tempfile.mkdtemp(prefix="mms-orchestrator-"))
- try:
- run_checks(workdir)
- run_llm_checks(workdir)
- if FULL_CHAIN:
- run_paper_checks(workdir)
- finally:
- shutil.rmtree(workdir, ignore_errors=True)
-
- return report("编排断言通过")
-
-
-if __name__ == "__main__":
- raise SystemExit(main(sys.argv[1:]))
diff --git a/runtime/tests/selfcheck_paper.py b/runtime/tests/selfcheck_paper.py
deleted file mode 100644
index 93ec9ea..0000000
--- a/runtime/tests/selfcheck_paper.py
+++ /dev/null
@@ -1,165 +0,0 @@
-"""G10 · 论文排版自检:真跑 xelatex、pandoc 与三道门禁。
-
-需要 xelatex、pandoc 与 python-docx。CI 的 ubuntu gates job 负责装齐;
-没有 TeX 的环境显式跳过(MMS_PAPER_SKIP=1),跳过不会被当成通过。
-"""
-
-from __future__ import annotations
-
-import os
-import shutil
-import tempfile
-from pathlib import Path
-
-from checklib import ROOT, check, report
-
-from mms import paper_build, project_export # noqa: E402
-from mms.store import session_scope # noqa: E402
-
-
-def artifact(data: Path, name: str) -> Path:
- return paper_build.workspace(data) / name
-
-
-def main() -> int:
- workdir = Path(tempfile.mkdtemp(prefix="mms-paper-check-"))
- data = workdir / "data"
- data_bad = workdir / "data-bad"
- try:
- env = paper_build.env_status()
- check(
- "P1 排版工具齐全",
- env["ok"],
- f"missing={env['missing']} xelatex={env['xelatex']['version']} pandoc={env['pandoc']['version']}",
- )
- if not env["ok"]:
- if os.environ.get("MMS_PAPER_SKIP") == "1":
- print(f"SKIP 缺少排版工具:{env['missing']}(MMS_PAPER_SKIP=1,未验证 G10)")
- return 0
- print(f"FAIL 缺少排版工具:{env['missing']};装齐后再跑,或显式设 MMS_PAPER_SKIP=1 跳过")
- return 1
-
- code, first = paper_build.build(data, ROOT)
- pdf = artifact(data, "paper.pdf")
- docx = artifact(data, "paper.docx")
- steps = {row["id"]: row for row in first["steps"]}
- gates = {row["id"]: row for row in first["gates"]}
- check(
- "P2 首次构建通过",
- code == 0 and first["ok"] and pdf.is_file() and docx.is_file(),
- f"exit={code} steps={len(steps)} pdf={pdf.exists()} docx={docx.exists()}",
- )
- check(
- "P2 PDF 与 DOCX 文件头正确",
- pdf.open("rb").read(4) == b"%PDF" and docx.open("rb").read(2) == b"PK",
- f"pdf={pdf.stat().st_size if pdf.exists() else 0}B docx={docx.stat().st_size if docx.exists() else 0}B",
- )
- check(
- "P3 六个构建步骤全部完成",
- set(steps) == {"stage", "xelatex-1", "xelatex-2", "pdf", "pandoc", "docx"}
- and all(row["ok"] for row in steps.values()),
- ",".join(f"{k}={v['ok']}" for k, v in steps.items()),
- )
- check(
- "P4 三道门禁全绿",
- set(gates) == {"phrasing", "style", "chapters"} and all(row["ok"] for row in gates.values()),
- ";".join(f"{k}: {v['detail']}" for k, v in gates.items()),
- )
-
- saved = paper_build.state(data, ROOT)
- check(
- "P5 构建状态落盘并可复读",
- saved["ok"] and saved["builtAt"] and Path(saved["artifacts"]["pdf"]["path"]).is_file(),
- f"builtAt={saved['builtAt']} artifacts={sorted(saved['artifacts'])}",
- )
-
- deliverables = {"pdf": str(pdf), "docx": str(docx)}
- for name in ("ws-a", "ws-b"):
- project_export.copy_outputs(str(workdir / name), "论文", deliverables)
- copied = {name: sorted(item.name for item in (workdir / name / "论文").iterdir()) for name in ("ws-a", "ws-b")}
- check(
- "P11 论文 PDF/DOCX 复制到各自赛题文件夹",
- all(names == ["paper.docx", "paper.pdf"] for names in copied.values()),
- str(copied),
- )
-
- old = os.environ.get("MMS_PANDOC")
- os.environ["MMS_PANDOC"] = str(workdir / "no-such-pandoc.exe")
- try:
- missing_code, missing = paper_build.build(data_bad, ROOT)
- finally:
- if old is None:
- os.environ.pop("MMS_PANDOC", None)
- else:
- os.environ["MMS_PANDOC"] = old
- check(
- "P6 缺 pandoc 时明确拒绝且不产出",
- missing_code == 2
- and "pandoc" in (missing.get("error") or "")
- and not artifact(data_bad, "paper.pdf").exists(),
- f"exit={missing_code} error={missing.get('error')}",
- )
-
- bad_source = workdir / "banned.tex"
- sample = (paper_build.SAMPLE_TEX).read_text(encoding="utf-8")
- # transition-abuse 的 max_per_document 是 1,注入两次才会超限。
- bad_source.write_text(
- sample.replace(
- "共享单车系统在早高峰呈现单向潮汐。",
- "综上所述,共享单车系统在早高峰呈现单向潮汐。",
- ).replace(
- "模型规模可控,贪心算法在普通笔记本上 3 分钟内收敛。",
- "综上所述,模型规模可控,贪心算法在普通笔记本上 3 分钟内收敛。",
- ),
- encoding="utf-8",
- )
- gate_code, gate_state = paper_build.build(workdir / "data-gate", ROOT, source=bad_source)
- gate_rows = {row["id"]: row for row in gate_state["gates"]}
- check(
- "P7 门禁能抓住坏稿(排版仍出产物,但整体判失败)",
- gate_code == 1
- and not gate_state["ok"]
- and gate_rows.get("phrasing", {}).get("ok") is False
- and artifact(workdir / "data-gate", "paper.pdf").is_file(),
- f"exit={gate_code} phrasing={gate_rows.get('phrasing')}",
- )
-
- broken = workdir / "broken.tex"
- broken.write_text(
- "\\documentclass{article}\\begin{document}\\nosuchcommand\\end{document}\n",
- encoding="utf-8",
- )
- broken_code, broken_state = paper_build.build(workdir / "data-broken", ROOT, source=broken)
- check(
- "P8 编译失败给出错误位置与退出码 1",
- broken_code == 1
- and not broken_state["ok"]
- and not artifact(workdir / "data-broken", "paper.pdf").exists(),
- f"exit={broken_code} error={broken_state.get('error')}",
- )
-
- missing_code, missing_state = paper_build.build(
- workdir / "data-missing", ROOT, source=workdir / "no-such.tex"
- )
- check(
- "P9 稿件不存在按用法错误退出 2",
- missing_code == 2 and not missing_state["ok"],
- f"exit={missing_code} error={missing_state.get('error')}",
- )
-
- sid_dir = session_scope(data, "a1b2c3d4e5f60718")
- check(
- "P10 论文目录按会话隔离,非法 sid 回落全局",
- paper_build.workspace(sid_dir)
- == data / "sessions" / "a1b2c3d4e5f60718" / "workbench" / "paper"
- and paper_build.workspace(session_scope(data, "../x")) == paper_build.workspace(data),
- str(paper_build.workspace(sid_dir)),
- )
- finally:
- shutil.rmtree(workdir, ignore_errors=True)
-
- return report("论文断言通过")
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/runtime/tests/selfcheck_workbench.py b/runtime/tests/selfcheck_workbench.py
deleted file mode 100644
index bf580c0..0000000
--- a/runtime/tests/selfcheck_workbench.py
+++ /dev/null
@@ -1,203 +0,0 @@
-"""G9 · 工作台自检:真渲两版、换主题、回滚、评分与门禁。
-
-需要 matplotlib/numpy/seaborn(与 G3 相同),运行于 gates job;
-不依赖窗口、不联网、不读真实 Key。
-"""
-
-from __future__ import annotations
-
-import contextlib
-import hashlib
-import io
-import shutil
-import sqlite3
-import tempfile
-from pathlib import Path
-
-from checklib import ROOT, check, report
-
-from mms import project_export, workbench_figure, workbench_score # noqa: E402
-from mms.store import SessionStore, session_scope # noqa: E402
-
-
-def digest(path: str | None) -> str:
- if not path or not Path(path).is_file():
- return ""
- return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:16]
-
-
-def main() -> int:
- workdir = Path(tempfile.mkdtemp(prefix="mms-workbench-"))
- data = workdir / "data"
- try:
- initial = workbench_figure.state_payload(ROOT, data)
- check(
- "W1 初始工作台有 20 个图表模板与 3 套主题",
- len(initial["templates"]) == 20
- and {t["id"] for t in initial["themes"]} == {"nature", "studio-ink", "studio-amber"},
- f"templates={len(initial['templates'])} themes={[t['id'] for t in initial['themes']]}",
- )
- check("W1 初始没有版本", initial["versions"] == [] and initial["active"] is None, str(initial["versions"]))
-
- code, first = workbench_figure.render("line-compare", "nature", ROOT, data)
- outputs = (first.get("version") or {}).get("outputs", {})
- check(
- "W2 第一次渲染产出 PNG/PDF/SVG",
- code == 0 and all(Path(outputs.get(k, "")).is_file() and Path(outputs[k]).stat().st_size > 0 for k in ("png", "pdf", "svg")),
- f"exit={code} outputs={sorted(outputs)}",
- )
-
- code2, second = workbench_figure.render("line-compare", "studio-ink", ROOT, data)
- after = workbench_figure.state_payload(ROOT, data)
- first_png = (first.get("version") or {}).get("outputs", {}).get("png")
- second_png = (second.get("version") or {}).get("outputs", {}).get("png")
- check(
- "W3 换主题生成第二版,当前与上一版并存",
- code2 == 0
- and len(after["versions"]) == 2
- and after["active"] == second["version"]["id"]
- and after["previous"] == first["version"]["id"]
- and digest(first_png) != digest(second_png),
- f"active={after['active']} previous={after['previous']} hash {digest(first_png)}/{digest(second_png)}",
- )
-
- code3, _ = workbench_figure.rollback(first["version"]["id"], ROOT, data)
- rolled = workbench_figure.state_payload(ROOT, data)
- check(
- "W4 回滚到第一版",
- code3 == 0 and rolled["active"] == first["version"]["id"] and Path(rolled["active_png"]).is_file(),
- f"exit={code3} active={rolled['active']}",
- )
-
- before_count = len(rolled["versions"])
- bad_code, bad = workbench_figure.render("not-a-template", "nature", ROOT, data)
- bad_theme_code, bad_theme = workbench_figure.render("line-compare", "not-a-theme", ROOT, data)
- after_bad = workbench_figure.state_payload(ROOT, data)
- check(
- "W5 未知模板/主题被拒且不新增版本",
- bad_code == 2 and bad_theme_code == 2 and len(after_bad["versions"]) == before_count,
- f"template={bad_code} theme={bad_theme_code} versions={len(after_bad['versions'])}",
- )
- check(
- "W5 未知版本回滚被拒",
- workbench_figure.rollback("v999", ROOT, data)[0] == 2,
- "v999",
- )
-
- # S7b:产物目录按会话隔离;非法 sid 一律回落全局目录。
- scoped = session_scope(data, "a1b2c3d4")
- check(
- "W8 十六进制 sid 映射到 sessions/",
- scoped == data / "sessions" / "a1b2c3d4",
- str(scoped),
- )
- bad_sids = ("../evil", "a1/b2", "A1B2C3D4", "a1", "", None, "a1b2c3d4/../../x")
- check(
- "W8 非法 sid 回落全局目录(路径穿越被拒)",
- all(session_scope(data, bad) == data for bad in bad_sids),
- ",".join(str(session_scope(data, bad)) for bad in bad_sids),
- )
- scoped_code, _ = workbench_figure.render("line-compare", "nature", ROOT, scoped)
- scoped_state = workbench_figure.state_payload(ROOT, scoped)
- global_state = workbench_figure.state_payload(ROOT, data)
- check(
- "W8 会话产物的版本不混入全局目录",
- scoped_code == 0
- and len(scoped_state["versions"]) == 1
- and len(global_state["versions"]) == before_count
- and Path(scoped_state["active_png"]).is_file()
- # Windows runner 的临时目录带 8.3 短名(RUNNER~1),产物路径却是长名,先 resolve 再比。
- and Path(scoped_state["active_png"]).resolve().is_relative_to(scoped.resolve()),
- f"scoped={len(scoped_state['versions'])} global={len(global_state['versions'])} active={scoped_state['active_png']}",
- )
-
- old_db = workdir / "old" / "sessions.db"
- old_db.parent.mkdir(parents=True)
- with sqlite3.connect(old_db) as conn:
- conn.executescript(
- "CREATE TABLE sessions (id TEXT PRIMARY KEY, created REAL NOT NULL, updated REAL NOT NULL,"
- " provider TEXT NOT NULL, model TEXT NOT NULL, problem TEXT NOT NULL, phases TEXT NOT NULL,"
- " pending TEXT, messages TEXT NOT NULL, batch INTEGER NOT NULL DEFAULT 1);"
- )
- conn.execute(
- "INSERT INTO sessions VALUES"
- " ('a1b2c3d4e5f60718', 0, 0, 'fake', 'm', 'p', '[]', NULL, '[]', 1)"
- )
- migrated = SessionStore(old_db)
- old_row = migrated.get("a1b2c3d4e5f60718")
- migrated.create("0011223344556677", "fake", "m", "p", str(workdir))
- new_row = migrated.get("0011223344556677")
- check(
- "W8 旧库补 workspace 列,新会话可写入归属目录",
- old_row is not None
- and old_row["workspace"] is None
- and new_row is not None
- and new_row["workspace"] == str(workdir),
- f"old={(old_row or {}).get('workspace')} new={(new_row or {}).get('workspace')}",
- )
-
- # S7c:图表副本落进用户赛题文件夹;目标不可写只记日志、不抛错。
- user_ws = workdir / "user-workspace"
- scoped_outputs = scoped_state["versions"][-1]["outputs"]
- project_export.copy_outputs(str(user_ws), "图表", scoped_outputs)
- copied = sorted(item.name for item in (user_ws / "图表").iterdir())
- check(
- "W9 图表三件套复制到赛题文件夹",
- set(copied) == {Path(path).name for path in scoped_outputs.values()},
- f"copied={copied}",
- )
- blocked = workdir / "blocked-target"
- blocked.write_text("x", encoding="utf-8")
- quiet = io.StringIO()
- with contextlib.redirect_stderr(quiet):
- project_export.copy_outputs(str(blocked), "论文", scoped_outputs)
- check(
- "W9 目标不可写时静默跳过",
- blocked.is_file() and "[mms]" in quiet.getvalue(),
- quiet.getvalue().strip()[:80],
- )
-
- score = workbench_score.state(ROOT)
- rounds = score["rounds"]
- check(
- "W6 三轮评分与默认轮次",
- [r["total"] for r in rounds] == [78, 86, 84]
- and score["defaultRound"] == 2
- and all(len(r["dimensions"]) == 5 for r in rounds),
- f"totals={[r['total'] for r in rounds]} default={score['defaultRound']}",
- )
- check(
- "W6 第 3 轮低于 85 触发熔断",
- rounds[2]["breaker"] is True and rounds[1]["pass"] is True,
- f"round3 breaker={rounds[2]['breaker']} round2 pass={rounds[1]['pass']}",
- )
- targets = [d.get("target") for r in rounds for d in r["deductions"] if d.get("target")]
- check(
- "W6 扣分项带正文定位与改法",
- len(targets) >= 8 and any("摘要" in (t or "") for t in targets),
- f"targets={len(targets)} sample={targets[:2]}",
- )
- check(
- "W6 一票否决示例",
- score["veto"] is not None and score["veto"]["verdict"] == "veto" and not score["veto"]["pass"],
- f"verdict={(score['veto'] or {}).get('verdict')}",
- )
- check(
- "W7 章节样例 hard/soft 均为 0",
- score["chapter"].get("ok") and score["chapter"].get("hard_failed") == 0
- and score["chapter"].get("soft_failed") == 0,
- str(score["chapter"]),
- )
- check(
- "W7 默认轮次总分达标",
- next(r for r in rounds if r["round"] == score["defaultRound"])["pass"] is True,
- f"total={next(r['total'] for r in rounds if r['round'] == score['defaultRound'])}",
- )
- finally:
- shutil.rmtree(workdir, ignore_errors=True)
-
- return report("工作台断言通过")
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/schemas/chat-events.schema.json b/schemas/chat-events.schema.json
deleted file mode 100644
index 0e286bb..0000000
--- a/schemas/chat-events.schema.json
+++ /dev/null
@@ -1,192 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://mathmodel-studio.local/schemas/chat-events.schema.json",
- "title": "mms channel chat event",
- "description": "Python 通道发往 Electron 的 SSE 事件信封。id 单调递增,按 Last-Event-ID 续传。",
- "type": "object",
- "required": ["id", "event", "data"],
- "additionalProperties": false,
- "properties": {
- "id": { "type": "string", "pattern": "^[1-9][0-9]*$" },
- "event": {
- "enum": ["token", "reasoning", "tool_call", "compaction", "artifact", "interrupt", "gate", "phase", "error", "done"]
- },
- "data": { "type": "object" }
- },
- "allOf": [
- {
- "if": { "properties": { "event": { "const": "token" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["text"],
- "additionalProperties": false,
- "properties": { "text": { "type": "string" } }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "reasoning" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["text"],
- "additionalProperties": false,
- "properties": { "text": { "type": "string" } }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "tool_call" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["id", "name", "status"],
- "additionalProperties": false,
- "properties": {
- "id": { "type": "string", "minLength": 1 },
- "name": { "type": "string", "minLength": 1 },
- "status": { "enum": ["running", "ok", "error"] },
- "args": { "type": ["object", "string", "null"] },
- "result": { "type": "object" },
- "error": { "type": "string" },
- "duration_ms": { "type": "integer", "minimum": 0 }
- }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "compaction" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["reason", "before", "after", "pruned", "summarized", "dropped"],
- "additionalProperties": false,
- "properties": {
- "reason": { "type": "string" },
- "before": { "type": "integer", "minimum": 0 },
- "after": { "type": "integer", "minimum": 0 },
- "pruned": { "type": "integer", "minimum": 0 },
- "summarized": { "type": "integer", "minimum": 0 },
- "dropped": { "type": "integer", "minimum": 0 },
- "summary": { "type": "string" }
- }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "artifact" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["kind"],
- "anyOf": [
- { "required": ["path"] },
- { "required": ["outputs"] }
- ],
- "additionalProperties": false,
- "properties": {
- "kind": { "type": "string" },
- "path": { "type": "string" },
- "url": { "type": "string" },
- "version": { "type": "string" },
- "outputs": {
- "type": "object",
- "additionalProperties": { "type": "string" }
- }
- }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "interrupt" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["card", "payload"],
- "additionalProperties": false,
- "properties": {
- "card": { "type": "string" },
- "payload": { "type": "object" }
- }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "gate" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["skill", "ok", "exit"],
- "additionalProperties": false,
- "properties": {
- "skill": { "type": "string" },
- "ok": { "type": "boolean" },
- "exit": { "type": "integer" },
- "summary": { "type": "string" }
- }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "phase" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["phase", "status"],
- "additionalProperties": false,
- "properties": {
- "phase": { "type": "integer", "minimum": 0, "maximum": 6 },
- "status": { "enum": ["idle", "running", "waiting", "passed", "failed"] },
- "note": { "type": "string" }
- }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "error" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["message"],
- "additionalProperties": false,
- "properties": { "message": { "type": "string" } }
- }
- }
- }
- },
- {
- "if": { "properties": { "event": { "const": "done" } }, "required": ["event"] },
- "then": {
- "properties": {
- "data": {
- "type": "object",
- "required": ["reason"],
- "additionalProperties": false,
- "properties": {
- "reason": { "enum": ["stop", "error", "cancelled", "max_tool_rounds", "waiting"] },
- "usage": { "type": "object" }
- }
- }
- }
- }
- }
- ]
-}
diff --git a/schemas/skill-manifest.schema.json b/schemas/skill-manifest.schema.json
deleted file mode 100644
index 5cd0d63..0000000
--- a/schemas/skill-manifest.schema.json
+++ /dev/null
@@ -1,146 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://github.com/Escap1ng/mathmodel-studio/schemas/skill-manifest.schema.json",
- "title": "技能注册表契约",
- "description": "skills/manifest.json 的结构契约。枚举值与 manifest 内的词表(kinds/status/contribution/hitl_card_kinds/artifact_kinds)由 check-registry.mjs 交叉校验,两处不一致即门禁失败。",
- "type": "object",
- "additionalProperties": false,
- "required": [
- "manifest_version",
- "schema_version",
- "title",
- "description",
- "kinds",
- "status",
- "contribution",
- "cli_contract",
- "phases",
- "skills"
- ],
- "properties": {
- "manifest_version": { "type": "string", "pattern": "^\\d+\\.\\d+$" },
- "schema_version": { "type": "string", "pattern": "^\\d+\\.\\d+$" },
- "title": { "type": "string", "minLength": 1 },
- "description": { "type": "string", "minLength": 1 },
- "upstream": {
- "type": "object",
- "additionalProperties": false,
- "required": ["source", "version", "license", "note"],
- "properties": {
- "source": { "type": "string", "pattern": "^[\\w.-]+/[\\w.-]+$" },
- "version": { "type": "string", "minLength": 1 },
- "license": { "type": "string", "minLength": 1 },
- "note": { "type": "string", "minLength": 1 }
- }
- },
- "kinds": {
- "type": "object",
- "required": ["core", "knowledge", "tool"],
- "additionalProperties": { "type": "string", "minLength": 1 }
- },
- "status": {
- "type": "object",
- "required": ["planned", "vendored"],
- "additionalProperties": { "type": "string", "minLength": 1 }
- },
- "contribution": {
- "type": "object",
- "required": ["open", "maintainer"],
- "additionalProperties": { "type": "string", "minLength": 1 }
- },
- "cli_contract": {
- "type": "object",
- "additionalProperties": false,
- "required": ["exit_codes", "stability"],
- "properties": {
- "exit_codes": { "type": "string", "minLength": 1 },
- "stability": { "type": "string", "minLength": 1 }
- }
- },
- "hitl_card_kinds": {
- "type": "object",
- "additionalProperties": { "type": "string", "minLength": 1 }
- },
- "artifact_kinds": {
- "type": "object",
- "additionalProperties": { "type": "string", "minLength": 1 }
- },
- "phases": {
- "type": "array",
- "items": { "type": "integer", "minimum": 0, "maximum": 6 },
- "uniqueItems": true,
- "minItems": 1
- },
- "skills": {
- "type": "array",
- "minItems": 1,
- "items": { "$ref": "#/$defs/skill" }
- }
- },
- "$defs": {
- "skill": {
- "type": "object",
- "additionalProperties": false,
- "required": ["name", "kind", "role", "entry", "contribution", "status", "ui"],
- "properties": {
- "name": { "type": "string", "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" },
- "kind": { "enum": ["core", "knowledge", "tool"] },
- "role": { "type": "string", "minLength": 1 },
- "entry": { "type": "string", "minLength": 1 },
- "contribution": { "enum": ["open", "maintainer"] },
- "status": { "enum": ["planned", "vendored"] },
- "docs": {
- "type": "array",
- "items": { "type": "string", "minLength": 1 },
- "uniqueItems": true
- },
- "ui": { "$ref": "#/$defs/ui" }
- }
- },
- "ui": {
- "type": "object",
- "additionalProperties": false,
- "required": ["phases", "artifacts", "hitl"],
- "properties": {
- "phases": {
- "type": "array",
- "items": { "type": "integer", "minimum": 0, "maximum": 6 },
- "uniqueItems": true,
- "minItems": 1
- },
- "artifacts": {
- "type": "array",
- "items": {
- "enum": [
- "workspace",
- "table",
- "png",
- "pdf",
- "svg",
- "docx",
- "tex",
- "json",
- "report"
- ]
- },
- "uniqueItems": true,
- "minItems": 1
- },
- "hitl": {
- "type": "array",
- "items": {
- "enum": [
- "env-preflight",
- "problem-confirm",
- "model-choice",
- "explain",
- "figure-rework",
- "score-round"
- ]
- },
- "uniqueItems": true
- }
- }
- }
- }
-}
diff --git a/scripts/check-registry.mjs b/scripts/check-registry.mjs
deleted file mode 100644
index 4c3d53b..0000000
--- a/scripts/check-registry.mjs
+++ /dev/null
@@ -1,270 +0,0 @@
-#!/usr/bin/env node
-/**
- * G1 · 注册表一致性门禁
- *
- * 单一事实源是 skills/manifest.json。本脚本把四处东西钉在一起:
- * 注册表 ↔ skills/ 目录 ↔ schemas/skill-manifest.schema.json 的词表
- * ↔ README.md 技能表与徽章 ↔ README_EN.md 技能表
- * 任何一处不一致就非零退出,不允许靠人工同步。
- *
- * 退出码沿用上游 CLI 契约:0 通过 / 1 校验失败 / 2 用法或环境错误。
- * 反向覆盖见 scripts/check-registry.negative.mjs。
- */
-import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs'
-import { dirname, join, resolve } from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
-
-const USAGE = `用法: node scripts/check-registry.mjs [选项]
- --manifest 注册表文件(默认 skills/manifest.json)
- --skills-dir 技能目录(默认 skills/)
- --schema 契约文件(默认 schemas/skill-manifest.schema.json)
- --readme 中文 README(默认 README.md)
- --readme-en 英文 README(默认 README_EN.md)
- --json 机器可读输出
- -h, --help 看这个`
-
-const FLAG_KEYS = {
- manifest: 'manifest',
- 'skills-dir': 'skillsDir',
- schema: 'schema',
- readme: 'readme',
- 'readme-en': 'readmeEn'
-}
-
-function parseArgs(argv) {
- const opts = {
- manifest: join(ROOT, 'skills/manifest.json'),
- skillsDir: join(ROOT, 'skills'),
- schema: join(ROOT, 'schemas/skill-manifest.schema.json'),
- readme: join(ROOT, 'README.md'),
- readmeEn: join(ROOT, 'README_EN.md'),
- json: false
- }
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i]
- if (a === '--json') opts.json = true
- else if (a === '-h' || a === '--help') {
- process.stdout.write(USAGE + '\n')
- process.exit(0)
- } else if (a.startsWith('--')) {
- const key = FLAG_KEYS[a.slice(2)]
- if (!key) failUsage(`未知选项: ${a}`)
- const val = argv[++i]
- if (val === undefined || val.startsWith('--')) failUsage(`${a} 缺参数值`)
- opts[key] = resolve(val)
- } else failUsage(`多余参数: ${a}`)
- }
- return opts
-}
-
-function failUsage(msg) {
- process.stderr.write(`用法或环境错误: ${msg}\n${USAGE}\n`)
- process.exit(2)
-}
-
-function readText(path, label) {
- if (!existsSync(path)) failUsage(`${label} 不存在: ${path}`)
- return readFileSync(path, 'utf8')
-}
-
-function readJson(path, label) {
- const raw = readText(path, label)
- try {
- return JSON.parse(raw)
- } catch (e) {
- process.stderr.write(`校验失败: ${label} 不是合法 JSON — ${e.message}\n`)
- process.exit(1)
- }
-}
-
-const results = []
-function check(id, ok, detail) {
- results.push({ id, ok, detail })
-}
-
-const opts = parseArgs(process.argv.slice(2))
-const manifest = readJson(opts.manifest, '注册表')
-const schema = readJson(opts.schema, '契约')
-const readmeCn = readText(opts.readme, 'README')
-const readmeEn = readText(opts.readmeEn, 'README_EN')
-
-// —— R1 顶层字段
-const REQUIRED_TOP = [
- 'manifest_version',
- 'schema_version',
- 'title',
- 'description',
- 'kinds',
- 'status',
- 'contribution',
- 'cli_contract',
- 'phases',
- 'skills'
-]
-const missingTop = REQUIRED_TOP.filter((k) => manifest[k] === undefined)
-check('R1', missingTop.length === 0, missingTop.length ? `缺字段: ${missingTop.join(', ')}` : '顶层字段齐')
-
-const skills = Array.isArray(manifest.skills) ? manifest.skills : []
-
-// —— R2 名字唯一且合式
-const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/
-const badNames = skills.filter((s) => typeof s.name !== 'string' || !NAME_RE.test(s.name)).map((s) => String(s.name))
-const dupNames = skills.map((s) => s.name).filter((n, i, all) => all.indexOf(n) !== i)
-check(
- 'R2',
- badNames.length === 0 && dupNames.length === 0,
- badNames.length || dupNames.length
- ? `合式: ${badNames.join(', ') || 'ok'} / 重复: ${dupNames.join(', ') || 'ok'}`
- : `${skills.length} 个技能名唯一且合式`
-)
-
-// —— R3 注册表 ↔ 目录 双向
-const dirsOnDisk = existsSync(opts.skillsDir)
- ? readdirSync(opts.skillsDir).filter((d) => {
- const p = join(opts.skillsDir, d)
- return statSync(p).isDirectory()
- })
- : []
-const declared = new Set(skills.map((s) => s.name))
-const missingDirs = [...declared].filter((n) => !dirsOnDisk.includes(n))
-const undeclaredDirs = dirsOnDisk.filter((d) => !declared.has(d))
-check(
- 'R3',
- missingDirs.length === 0 && undeclaredDirs.length === 0,
- missingDirs.length || undeclaredDirs.length
- ? `登记了但没目录: ${missingDirs.join(', ') || '-'} / 有目录没登记: ${undeclaredDirs.join(', ') || '-'}`
- : `目录与注册表一一对应(${dirsOnDisk.length} 个目录)`
-)
-
-// —— R4 status 语义
-const statusProblems = []
-for (const s of skills) {
- const dir = join(opts.skillsDir, s.name)
- if (!existsSync(dir)) continue // R3 已经报过
- const entryPath = join(dir, s.entry ?? '')
- const hasEntry = s.entry ? existsSync(entryPath) : false
- const hasSkillMd = existsSync(join(dir, 'SKILL.md'))
- if (s.status === 'planned' && hasSkillMd) {
- statusProblems.push(`${s.name}: status=planned 却已有 SKILL.md(半 vendor)`)
- }
- if (s.status === 'vendored' && !hasEntry) {
- statusProblems.push(`${s.name}: status=vendored 但入口 ${s.entry} 不存在`)
- }
-}
-check('R4', statusProblems.length === 0, statusProblems.length ? statusProblems.join(' | ') : 'planned/vendored 语义一致')
-
-// —— R5/R6 UI 契约取值
-const allowedPhases = Array.isArray(manifest.phases) ? new Set(manifest.phases) : new Set()
-const allowedArtifacts = new Set(Object.keys(manifest.artifact_kinds ?? {}))
-const allowedHitl = new Set(Object.keys(manifest.hitl_card_kinds ?? {}))
-const uiProblems = []
-for (const s of skills) {
- const ui = s.ui
- if (!ui || !Array.isArray(ui.phases) || ui.phases.length === 0) {
- uiProblems.push(`${s.name}: 缺 ui.phases`)
- continue
- }
- const badPhases = ui.phases.filter((p) => !allowedPhases.has(p))
- if (badPhases.length) uiProblems.push(`${s.name}: 阶段越界 ${badPhases.join(',')}`)
- const badArt = (ui.artifacts ?? []).filter((a) => !allowedArtifacts.has(a))
- if (badArt.length) uiProblems.push(`${s.name}: 产物类型不在词表 ${badArt.join(',')}`)
- if (!Array.isArray(ui.artifacts) || ui.artifacts.length === 0) uiProblems.push(`${s.name}: 缺 ui.artifacts`)
- const badHitl = (ui.hitl ?? []).filter((h) => !allowedHitl.has(h))
- if (badHitl.length) uiProblems.push(`${s.name}: 卡点不在词表 ${badHitl.join(',')}`)
-}
-check('R5+R6', uiProblems.length === 0, uiProblems.length ? uiProblems.join(' | ') : 'UI 契约取值都在声明的词表内')
-
-// —— R7 schema 词表 ↔ manifest 词表
-const skillUi = schema?.$defs?.ui?.properties ?? {}
-const schemaArtifacts = skillUi?.artifacts?.items?.enum ?? null
-const schemaHitl = skillUi?.hitl?.items?.enum ?? null
-const vocabProblems = []
-if (!Array.isArray(schemaArtifacts)) vocabProblems.push('契约里缺 ui.artifacts 枚举')
-else {
- const a = new Set(schemaArtifacts)
- const onlySchema = [...a].filter((x) => !allowedArtifacts.has(x))
- const onlyManifest = [...allowedArtifacts].filter((x) => !a.has(x))
- if (onlySchema.length || onlyManifest.length) {
- vocabProblems.push(`产物词表不一致 契约独有:${onlySchema.join(',') || '-'} 注册表独有:${onlyManifest.join(',') || '-'}`)
- }
-}
-if (!Array.isArray(schemaHitl)) vocabProblems.push('契约里缺 ui.hitl 枚举')
-else {
- const h = new Set(schemaHitl)
- const onlySchema = [...h].filter((x) => !allowedHitl.has(x))
- const onlyManifest = [...allowedHitl].filter((x) => !h.has(x))
- if (onlySchema.length || onlyManifest.length) {
- vocabProblems.push(`卡点词表不一致 契约独有:${onlySchema.join(',') || '-'} 注册表独有:${onlyManifest.join(',') || '-'}`)
- }
-}
-check('R7', vocabProblems.length === 0, vocabProblems.length ? vocabProblems.join(' | ') : '契约枚举与注册表词表一致')
-
-// —— R8 README 技能表
-const ROW_RE = /^\|\s*\[`([a-z0-9-]+)`\]\(skills\/[^)]+\)\s*\|/gm
-function tableNames(text) {
- return [...text.matchAll(ROW_RE)].map((m) => m[1])
-}
-const cnNames = tableNames(readmeCn)
-const enNames = tableNames(readmeEn)
-const tableProblems = []
-for (const [label, names] of [
- ['README', cnNames],
- ['README_EN', enNames]
-]) {
- const missing = [...declared].filter((n) => !names.includes(n))
- const extra = names.filter((n) => !declared.has(n))
- if (missing.length) tableProblems.push(`${label} 表缺行: ${missing.join(',')}`)
- if (extra.length) tableProblems.push(`${label} 表多行: ${extra.join(',')}`)
-}
-check(
- 'R8',
- tableProblems.length === 0,
- tableProblems.length
- ? tableProblems.join(' | ')
- : `两份 README 技能表各 ${cnNames.length}/${enNames.length} 行,与注册表 ${skills.length} 个技能名单一致`
-)
-
-// —— R9 徽章计数
-function badgeCount(text, labelText) {
- const badgeRe = /img\.shields\.io\/badge\/([A-Za-z0-9%_.+~-]+?)-(\d+)-([0-9A-Fa-f]{3,8})/g
- for (const m of text.matchAll(badgeRe)) {
- let label = m[1]
- try {
- label = decodeURIComponent(label)
- } catch {
- /* 未编码的 label 原样比较 */
- }
- if (label === labelText) return Number(m[2])
- }
- return null
-}
-const cnBadge = badgeCount(readmeCn, '技能')
-const enBadge = badgeCount(readmeEn, 'skills')
-check(
- 'R9',
- cnBadge === skills.length && enBadge === skills.length,
- `中文徽章 技能=${cnBadge ?? '缺失'} / 英文徽章 skills=${enBadge ?? '缺失'} / 实际 ${skills.length}`
-)
-
-const failed = results.filter((r) => !r.ok)
-if (opts.json) {
- process.stdout.write(
- JSON.stringify(
- {
- ok: failed.length === 0,
- skills: skills.length,
- checks: results
- },
- null,
- 2
- ) + '\n'
- )
-} else {
- for (const r of results) {
- process.stdout.write(`${r.ok ? 'PASS' : 'FAIL'} ${r.id.padEnd(7)} ${r.detail}\n`)
- }
- process.stdout.write(`\n${results.length - failed.length}/${results.length} 项通过,技能 ${skills.length} 个\n`)
-}
-process.exit(failed.length === 0 ? 0 : 1)
diff --git a/scripts/check-registry.negative.mjs b/scripts/check-registry.negative.mjs
deleted file mode 100644
index 41628c2..0000000
--- a/scripts/check-registry.negative.mjs
+++ /dev/null
@@ -1,218 +0,0 @@
-#!/usr/bin/env node
-/**
- * G1 门禁的反向覆盖
- *
- * check-registry.mjs 报 PASS 本身不构成证据:一个永远返回 0 的检查器最危险。
- * 本脚本把真实注册表拷进临时目录,先证明**未改动的夹具退出 0**(夹具真的跑得通被测脚本),
- * 再逐个植入 8 种破坏,每种都必须让对应的检查项变红。
- *
- * 断言方式是「预期失败的检查项 ∈ 实际失败集合」而非「只有一项失败」:
- * 有些破坏天然会级联(删一个技能会同时让目录、表格、徽章三处不一致),
- * 级联清单会整行打印出来供人看,不隐藏。
- *
- * 退出码:0 = 门禁确实能失败且约定正确 / 1 = 有一条破坏没被抓到 / 2 = 夹具或环境自身出错
- */
-import { spawnSync } from 'node:child_process'
-import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { dirname, join, resolve } from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
-const CHECKER = join(ROOT, 'scripts/check-registry.mjs')
-const SKILL_DIRS = [
- 'mathmodel-core',
- 'mathmodel-methods',
- 'mathmodel-paper',
- 'mathmodel-figure',
- 'mathmodel-diagram',
- 'mathmodel-deai',
- 'mathmodel-score'
-]
-
-if (!existsSync(CHECKER)) {
- process.stderr.write(`环境错误: 找不到被测脚本 ${CHECKER}\n`)
- process.exit(2)
-}
-
-const base = mkdtempSync(join(tmpdir(), 'mms-registry-negative-'))
-
-function buildFixture() {
- const fx = {
- root: base,
- skills: join(base, 'skills'),
- manifest: join(base, 'skills/manifest.json'),
- schema: join(base, 'schemas/skill-manifest.schema.json'),
- readme: join(base, 'README.md'),
- readmeEn: join(base, 'README_EN.md')
- }
- mkdirSync(join(base, 'schemas'), { recursive: true })
- cpSync(join(ROOT, 'skills/manifest.json'), fx.manifest)
- cpSync(join(ROOT, 'schemas/skill-manifest.schema.json'), fx.schema)
- cpSync(join(ROOT, 'README.md'), fx.readme)
- cpSync(join(ROOT, 'README_EN.md'), fx.readmeEn)
- for (const d of SKILL_DIRS) {
- // 夹具只复制入口文件:R4 判的就是「vendored 时 entry 是否存在」。
- // 整目录复制会让 9 个用例各拷 16MB,且与判据无关。
- const src = join(ROOT, `skills/${d}/SKILL.md`)
- if (!existsSync(src)) {
- process.stderr.write(`夹具错误: ${src} 不存在——技能未 vendor 或目录已改名\n`)
- process.exit(2)
- }
- mkdirSync(join(fx.skills, d), { recursive: true })
- cpSync(src, join(fx.skills, d, 'SKILL.md'))
- }
- return fx
-}
-
-function run(fx, extraArgs = []) {
- const args = [
- CHECKER,
- '--manifest',
- fx.manifest,
- '--skills-dir',
- fx.skills,
- '--schema',
- fx.schema,
- '--readme',
- fx.readme,
- '--readme-en',
- fx.readmeEn,
- '--json',
- ...extraArgs
- ]
- const r = spawnSync(process.execPath, args, { encoding: 'utf8' })
- let parsed = null
- try {
- parsed = JSON.parse(r.stdout)
- } catch {
- /* 非零退出时输出可能不是 JSON,交给下面的 code 断言处理 */
- }
- return { code: r.status, parsed, stderr: r.stderr, stdout: r.stdout }
-}
-
-const failedIds = (out) => (out.parsed?.checks ?? []).filter((c) => !c.ok).map((c) => c.id)
-
-function patchJson(path, mutate) {
- const data = JSON.parse(readFileSync(path, 'utf8'))
- mutate(data)
- writeFileSync(path, JSON.stringify(data, null, 2) + '\n', 'utf8')
-}
-
-function patchText(path, from, to) {
- const text = readFileSync(path, 'utf8')
- if (!text.includes(from)) {
- process.stderr.write(`夹具错误: ${path} 里找不到锚点「${from}」——夹具已与仓库脱节\n`)
- process.exit(2)
- }
- writeFileSync(path, text.replace(from, to), 'utf8')
-}
-
-const cases = [
- {
- id: 'M1',
- expect: 'R3',
- label: '从注册表删掉一个技能 → 目录与清单不再一一对应',
- apply: (fx) => patchJson(fx.manifest, (m) => (m.skills = m.skills.slice(1)))
- },
- {
- id: 'M2',
- expect: 'R4',
- label: '把 vendored 技能的入口指向不存在的文件 → 入口缺失被拦下',
- apply: (fx) => patchJson(fx.manifest, (m) => (m.skills[3].entry = 'MISSING.md'))
- },
- {
- id: 'M3',
- expect: 'R5+R6',
- label: '给技能塞一个词表外的产物类型 → UI 契约取值被拦下',
- apply: (fx) => patchJson(fx.manifest, (m) => m.skills[0].ui.artifacts.push('hologram'))
- },
- {
- id: 'M4',
- expect: 'R7',
- label: '只改契约、让枚举少一项 → 两处词表漂移被拦下',
- apply: (fx) =>
- patchJson(fx.schema, (s) => {
- const enumList = s.$defs.ui.properties.artifacts.items.enum
- const i = enumList.indexOf('svg')
- enumList.splice(i, 1)
- })
- },
- {
- id: 'M5',
- expect: 'R8',
- label: '删掉中文 README 技能表一行 → 文档与注册表不一致被拦下',
- apply: (fx) => {
- const text = readFileSync(fx.readme, 'utf8')
- const line = text.split('\n').find((l) => l.startsWith('| [`mathmodel-deai`]('))
- if (!line) {
- process.stderr.write('夹具错误: README 里找不到 | [`mathmodel-deai`]( 开头的那一行\n')
- process.exit(2)
- }
- writeFileSync(fx.readme, text.replace(line + '\n', ''), 'utf8')
- }
- },
- {
- id: 'M6',
- expect: 'R9',
- label: '把徽章计数从 7 改成 6 → 徽章说谎被拦下',
- apply: (fx) => patchText(fx.readme, '%E6%8A%80%E8%83%BD-7-', '%E6%8A%80%E8%83%BD-6-')
- },
- {
- id: 'M7',
- expect: 'PARSE',
- label: '注册表写成非法 JSON → 退出 1 而不是崩在读取阶段',
- apply: (fx) => writeFileSync(fx.manifest, '{ "skills": [', 'utf8')
- },
- {
- id: 'M8',
- expect: 'ENV',
- label: '注册表路径不存在 → 退出 2(用法/环境错误),不与校验失败混淆',
- apply: (fx) => rmSync(fx.manifest, { force: true })
- }
-]
-
-const rows = []
-let baseline = run(buildFixture())
-if (baseline.code !== 0 || baseline.parsed?.ok !== true) {
- process.stderr.write(
- `夹具基线就没通过(退出 ${baseline.code}):\n${baseline.stdout}\n${baseline.stderr}\n夹具不可信,拒绝继续。\n`
- )
- rmSync(base, { recursive: true, force: true })
- process.exit(2)
-}
-rows.push({ id: 'M0', label: `未改动的夹具退出 0(${baseline.parsed.skills} 个技能,${baseline.parsed.checks.length} 项检查全绿)`, expect: '-', actual: 'exit 0', pass: true })
-
-for (const c of cases) {
- const fx = buildFixture()
- c.apply(fx)
- const out = run(fx)
- let pass
- let actual
- if (c.expect === 'PARSE') {
- pass = out.code === 1
- actual = `exit ${out.code}`
- } else if (c.expect === 'ENV') {
- pass = out.code === 2
- actual = `exit ${out.code}`
- } else {
- const ids = failedIds(out)
- pass = out.code === 1 && ids.includes(c.expect)
- actual = `exit ${out.code},失败项: ${ids.join(',') || '无'}`
- }
- rows.push({ id: c.id, label: c.label, expect: c.expect, actual, pass })
-}
-
-rmSync(base, { recursive: true, force: true })
-
-for (const r of rows) {
- process.stdout.write(`${r.pass ? 'PASS' : 'FAIL'} ${r.id.padEnd(3)} ${r.label}\n`)
- process.stdout.write(` 期望 ${r.expect} / 实得 ${r.actual}\n`)
-}
-const bad = rows.filter((r) => !r.pass)
-process.stdout.write(`\n${rows.length - bad.length}/${rows.length} 条破坏被门禁抓到(含 1 条夹具基线自证)\n`)
-if (bad.length) {
- process.stderr.write('门禁存在假绿:有破坏没被抓到\n')
- process.exit(1)
-}
-process.exit(0)
diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs
deleted file mode 100644
index dacaeb3..0000000
--- a/scripts/check-skills.mjs
+++ /dev/null
@@ -1,331 +0,0 @@
-#!/usr/bin/env node
-/**
- * G8 · 技能规范门禁
- *
- * 上游技能被原样 vendor 进本仓库,但桌面端只允许把 UI 契约写在 manifest.json。
- * 本脚本守住另一半:SKILL.md 必须仍然是合法的 Agent Skills 入口,且目录里没有
- * 本仓库的私有字段、占位文件或超出上游层级的结构。
- *
- * 退出码:0 通过 / 1 校验失败 / 2 用法或环境错误。
- * `--self` 是负向对照:用真实 SKILL.md 造 6 种破坏,每一种都必须让对应检查变红。
- */
-import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { dirname, join, relative, resolve, sep } from 'node:path'
-import { spawnSync } from 'node:child_process'
-import { fileURLToPath } from 'node:url'
-
-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
-
-const USAGE = `用法: node scripts/check-skills.mjs [选项]
- --manifest 注册表(默认 skills/manifest.json)
- --skills-dir 技能目录(默认 skills/)
- --json 机器可读输出
- --self 负向对照:6 种破坏都必须被抓到
- -h, --help 看这个`
-
-const FLAG_KEYS = { manifest: 'manifest', 'skills-dir': 'skillsDir' }
-
-function parseArgs(argv) {
- const opts = {
- manifest: join(ROOT, 'skills/manifest.json'),
- skillsDir: join(ROOT, 'skills'),
- json: false,
- self: false
- }
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i]
- if (a === '--json') opts.json = true
- else if (a === '--self') opts.self = true
- else if (a === '-h' || a === '--help') {
- process.stdout.write(USAGE + '\n')
- process.exit(0)
- } else if (a.startsWith('--')) {
- const key = FLAG_KEYS[a.slice(2)]
- if (!key) failUsage(`未知选项: ${a}`)
- const val = argv[++i]
- if (val === undefined || val.startsWith('--')) failUsage(`${a} 缺参数值`)
- opts[key] = resolve(val)
- } else failUsage(`多余参数: ${a}`)
- }
- return opts
-}
-
-function failUsage(msg) {
- process.stderr.write(`用法或环境错误: ${msg}\n${USAGE}\n`)
- process.exit(2)
-}
-
-function readText(path, label) {
- if (!existsSync(path)) failUsage(`${label} 不存在: ${path}`)
- const raw = readFileSync(path, 'utf8').replace(/^\uFEFF/, '')
- return raw.replace(/\r\n/g, '\n')
-}
-
-const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/
-const ALLOWED_KEYS = new Set(['name', 'description', 'license', 'compatibility', 'metadata', 'allowed-tools'])
-const PRIVATE_KEYS = new Set(['ui', 'phases', 'hitl', 'artifacts', 'status', 'kind', 'entry'])
-const MAX_DEPTH = 3
-
-/**
- * 只解析 Agent Skills frontmatter 需要的那一小撮 YAML:
- * 顶层 `key: value`、块标量 `key: |` / `key: >`,以及 `metadata:` 下的缩进行。
- * 不追求完整 YAML——遇到超出这一小撮的写法时宁可报错,也不静默猜。
- */
-function parseFrontmatter(text, problems, label) {
- const lines = text.split('\n')
- if (lines[0].trim() !== '---') {
- problems.push(`${label}: 第 1 行不是 ---,没有 frontmatter`)
- return null
- }
- let end = -1
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim() === '---') {
- end = i
- break
- }
- }
- if (end < 0) {
- problems.push(`${label}: frontmatter 没有闭合的 ---`)
- return null
- }
-
- const data = {}
- for (let i = 1; i < end; i++) {
- const line = lines[i]
- if (!line.trim() || line.trimStart().startsWith('#')) continue
- const m = line.match(/^([A-Za-z][A-Za-z0-9_-]*):(?:\s*(.*))?$/)
- if (!m) {
- // 缩进行只有在刚开了一个块标量/映射时才合法;这里交给键值归属判断。
- if (/^\s+\S/.test(line)) continue
- problems.push(`${label}: 第 ${i + 1} 行不是受支持的 YAML 写法: ${line.trim()}`)
- return null
- }
- const [, key, rawValue = ''] = m
- if (key === 'metadata') {
- data.metadata = ''
- continue
- }
- let value = rawValue.trim()
- if (value === '|' || value === '>' || value === '|-' || value === '>-' || value === '') {
- const parts = []
- let j = i + 1
- for (; j < end && (/^\s+\S/.test(lines[j]) || !lines[j].trim()); j++) {
- if (lines[j].trim()) parts.push(lines[j].trim())
- }
- value = parts.join(value.startsWith('>') ? ' ' : '\n')
- i = j - 1
- }
- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
- value = value.slice(1, -1)
- }
- data[key] = value
- }
- return data
-}
-
-function walkFiles(dir) {
- const out = []
- for (const name of readdirSync(dir)) {
- const p = join(dir, name)
- if (statSync(p).isDirectory()) out.push(...walkFiles(p))
- else out.push(p)
- }
- return out
-}
-
-function check(opts) {
- const manifest = JSON.parse(readText(opts.manifest, '注册表'))
- const skills = Array.isArray(manifest.skills) ? manifest.skills : []
- const problems = { S1: [], S2: [], S3: [], S4: [], S5: [], S6: [] }
- const details = {}
-
- for (const s of skills) {
- const dir = join(opts.skillsDir, s.name)
- const label = s.name
- if (!existsSync(dir) || !statSync(dir).isDirectory()) {
- problems.S1.push(`${label}: 技能目录不存在`)
- continue
- }
- const entryPath = join(dir, s.entry ?? 'SKILL.md')
- if (!existsSync(entryPath)) {
- problems.S1.push(`${label}: 入口 ${s.entry ?? 'SKILL.md'} 不存在`)
- continue
- }
- const fm = parseFrontmatter(readText(entryPath, `${label} 入口`), problems.S1, label)
- if (!fm) continue
-
- if (typeof fm.name !== 'string' || fm.name !== s.name || !NAME_RE.test(fm.name)) {
- problems.S2.push(`${label}: frontmatter name=${JSON.stringify(fm.name ?? null)},应与目录同名且合式`)
- }
- if (typeof fm.description !== 'string' || fm.description.trim() === '') {
- problems.S3.push(`${label}: description 为空或缺失`)
- } else if ([...fm.description].length > 1024) {
- problems.S3.push(`${label}: description 超过 1024 字符(${[...fm.description].length})`)
- }
- for (const key of Object.keys(fm)) {
- if (PRIVATE_KEYS.has(key)) problems.S4.push(`${label}: SKILL.md 出现本仓库私有字段 ${key}`)
- else if (!ALLOWED_KEYS.has(key)) problems.S4.push(`${label}: Agent Skills 规范外的字段 ${key}`)
- }
-
- const files = walkFiles(dir)
- for (const f of files) {
- if (f.endsWith('PLACEHOLDER.md')) problems.S5.push(`${label}: 残留占位文件 ${relative(dir, f)}`)
- const depth = relative(dir, f).split(sep).length - 1
- if (depth > MAX_DEPTH) problems.S6.push(`${label}: ${relative(dir, f)} 有 ${depth} 层目录,超过上游的 ${MAX_DEPTH} 层`)
- }
- details[label] = { files: files.length, descriptionChars: [...(fm.description ?? '')].length }
- }
-
- const checks = Object.entries(problems).map(([id, list]) => ({
- id,
- ok: list.length === 0,
- detail: list.length ? list.join(' | ') : 'ok'
- }))
- return { ok: checks.every((c) => c.ok), skills: skills.length, checks, details }
-}
-
-function printReport(report, json) {
- if (json) {
- process.stdout.write(JSON.stringify(report, null, 2) + '\n')
- return
- }
- for (const c of report.checks) {
- process.stdout.write(`${c.ok ? 'PASS' : 'FAIL'} ${c.id} ${c.detail}\n`)
- }
- const failed = report.checks.filter((c) => !c.ok).length
- process.stdout.write(`\n${report.checks.length - failed}/${report.checks.length} 项通过,技能 ${report.skills} 个\n`)
-}
-
-function buildSelfFixture(base) {
- const manifest = JSON.parse(readFileSync(join(ROOT, 'skills/manifest.json'), 'utf8'))
- const skillsDir = join(base, 'skills')
- for (const s of manifest.skills) {
- const src = join(ROOT, 'skills', s.name, s.entry ?? 'SKILL.md')
- if (!existsSync(src)) {
- process.stderr.write(`自检夹具错误: ${src} 不存在\n`)
- process.exit(2)
- }
- mkdirSync(join(skillsDir, s.name), { recursive: true })
- cpSync(src, join(skillsDir, s.name, 'SKILL.md'))
- }
- writeFileSync(join(base, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8')
- return { manifest: join(base, 'manifest.json'), skillsDir }
-}
-
-function runChild(fx) {
- const r = spawnSync(
- process.execPath,
- [fileURLToPath(import.meta.url), '--manifest', fx.manifest, '--skills-dir', fx.skillsDir, '--json'],
- { encoding: 'utf8' }
- )
- let parsed = null
- try {
- parsed = JSON.parse(r.stdout)
- } catch {
- /* 交给 code 断言 */
- }
- return { code: r.status, parsed, stderr: r.stderr }
-}
-
-function selfCheck() {
- const base = mkdtempSync(join(tmpdir(), 'mms-skills-self-'))
- const rows = []
- try {
- const baseline = runChild(buildSelfFixture(join(base, 'baseline')))
- rows.push({ id: 'S0', expect: '-', actual: `exit ${baseline.code}`, pass: baseline.code === 0 })
- if (baseline.code !== 0) {
- process.stderr.write(`自检基线失败,夹具不可信:\n${baseline.stderr}\n`)
- return 2
- }
-
- const first = JSON.parse(readFileSync(join(base, 'baseline/manifest.json'), 'utf8')).skills[0].name
- const mutations = [
- {
- id: 'M1',
- expect: 'S1',
- label: '删掉 SKILL.md',
- apply: (fx) => rmSync(join(fx.skillsDir, first, 'SKILL.md'))
- },
- {
- id: 'M2',
- expect: 'S2',
- label: 'frontmatter name 与目录不同名',
- apply: (fx) => {
- const p = join(fx.skillsDir, first, 'SKILL.md')
- writeFileSync(p, readFileSync(p, 'utf8').replace(/^name: .*$/m, 'name: wrong-name'), 'utf8')
- }
- },
- {
- id: 'M3',
- expect: 'S3',
- label: 'description 置空',
- apply: (fx) => {
- const p = join(fx.skillsDir, first, 'SKILL.md')
- writeFileSync(p, readFileSync(p, 'utf8').replace(/^description: .*$/m, 'description: ""'), 'utf8')
- }
- },
- {
- id: 'M4',
- expect: 'S4',
- label: '把 UI 契约塞进 SKILL.md',
- apply: (fx) => {
- const p = join(fx.skillsDir, first, 'SKILL.md')
- const text = readFileSync(p, 'utf8').replace(/\r\n/g, '\n')
- const close = text.indexOf('\n---\n', 3)
- if (close < 0) {
- process.stderr.write('自检夹具错误: 找不到 frontmatter 的闭合 ---\n')
- process.exit(2)
- }
- writeFileSync(p, text.slice(0, close) + '\nui:\n phases: [4]' + text.slice(close), 'utf8')
- }
- },
- {
- id: 'M5',
- expect: 'S5',
- label: '残留 PLACEHOLDER.md',
- apply: (fx) => writeFileSync(join(fx.skillsDir, first, 'PLACEHOLDER.md'), 'x\n', 'utf8')
- },
- {
- id: 'M6',
- expect: 'S6',
- label: '目录深到第 4 层',
- apply: (fx) => {
- const deep = join(fx.skillsDir, first, 'a/b/c/d')
- mkdirSync(deep, { recursive: true })
- writeFileSync(join(deep, 'x.txt'), 'x\n', 'utf8')
- }
- }
- ]
-
- for (const m of mutations) {
- const root = join(base, m.id)
- const fx = buildSelfFixture(root)
- m.apply(fx)
- const out = runChild(fx)
- const ids = (out.parsed?.checks ?? []).filter((c) => !c.ok).map((c) => c.id)
- const pass = out.code === 1 && ids.includes(m.expect)
- rows.push({ id: m.id, label: m.label, expect: m.expect, actual: `exit ${out.code},失败项: ${ids.join(',') || '无'}`, pass })
- }
- } finally {
- rmSync(base, { recursive: true, force: true })
- }
-
- for (const r of rows) {
- process.stdout.write(`${r.pass ? 'PASS' : 'FAIL'} ${r.id.padEnd(3)} ${r.label ?? '未改动的夹具退出 0'}\n`)
- process.stdout.write(` 期望 ${r.expect} / 实得 ${r.actual}\n`)
- }
- const bad = rows.filter((r) => !r.pass)
- process.stdout.write(`\n${rows.length - bad.length}/${rows.length} 条自检通过(含 1 条基线自证)\n`)
- if (bad.length) {
- process.stderr.write('技能规范检查器存在假绿\n')
- return 1
- }
- return 0
-}
-
-const opts = parseArgs(process.argv.slice(2))
-if (opts.self) process.exit(selfCheck())
-const report = check(opts)
-printReport(report, opts.json)
-process.exit(report.ok ? 0 : 1)
diff --git a/scripts/check-window-smoke.mjs b/scripts/check-window-smoke.mjs
deleted file mode 100644
index b5bdecc..0000000
--- a/scripts/check-window-smoke.mjs
+++ /dev/null
@@ -1,295 +0,0 @@
-#!/usr/bin/env node
-/**
- * G6b · 真启动结果的独立核验
- *
- * 为什么需要第二个脚本判一遍:上一轮 CI 里冒烟打印了「10/12 项通过」,
- * 但 job 却是绿的——app.exit(1) 被生产入口的 window-all-closed → app.quit() 抢先顶掉了。
- * 「通过与否」不能吊在 Electron 的退出码管道上,所以结果落成 JSON,由本脚本独立判定,
- * 并且**复算读数**而不是只看 ok 标志:ok:true 但内容尺寸 1439x899 一样判失败。
- *
- * 本脚本自带 --selftest,不需要真起窗口就能证明它会失败(本机即可跑)。
- * 退出码:0 通过 / 1 判据不满足或没有证据 / 2 用法错误
- */
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join, resolve } from 'node:path'
-import { dirname } from 'node:path'
-import { fileURLToPath } from 'node:url'
-import { spawnSync } from 'node:child_process'
-
-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
-const DEFAULT_FILE = join(ROOT, 'screenshots/window-smoke.json')
-// 新增断言时同步抬高这里:它的作用是「断言集合被删空」也会判失败
-const MIN_ASSERTIONS = 116
-const MIN_THRESHOLD_FLOOR = 0.01
-const EXPECT_SIZE = '1440x900'
-// 只认条数不够:把关键断言整条删掉、再拿凑数的 A 行补齐,条数照样够。
-// 这里点名 M2 闭环最关键的几条,少一条就判失败。
-const REQUIRED_ASSERTIONS = [
- 'G7-3 runtime 通过握手就绪',
- 'G7-4 空状态大框与加号居中',
- 'G7-4 拖入文件时大框高亮',
- 'G7-4 问答默认收起仅文件图标',
- 'G7-4 文件图标展开为文件面板',
- 'G7-4 附件正文抽取(PDF/CSV)',
- 'G7-4 只读取工作区里的文件',
- 'G7-4 附件暂存到工作区',
- 'G7-4 真拖放走完暂存与移除',
- 'G7-4 文件页列出工作区文件',
- 'G7-4 默认工作区在桌面「赛题」',
- 'G7-4 移除只删暂存副本',
- 'G7-4 粘贴截图进输入区并落盘',
- 'G7-4 输入区不常驻附件按钮',
- 'G7-4 工作区文件可拖进对话',
- 'G7-4 文件条目右键菜单可控制',
- 'G7-4 工作区原件移除后不删',
- 'G7-5 中文按真字形渲染(不是空心方框)',
- 'G7-5 工具卡完成并给出结构化结果',
- 'G7-5 回复文本含模板总数',
- 'G7-6 设置对话框打开并列出服务商',
- 'G7-6 设置页含四家预设与 OpenAI 格式',
- 'G7-6 四家预设模型名来自官方文档',
- 'G7-6 OpenAI 格式可填端点与开关',
- 'G7-6 预设模型与上下文/深度选择器',
- 'G7-7 选模卡含五维雷达',
- 'G7-13 过程总览为建模默认页',
- 'G7-6 上下文与深度可切换',
- 'G7-6 上下文与深度随设置落盘',
- 'G7-6 Key 落盘只有密文或明确拒绝',
- 'G7-7 K2 卡切出两个子问题',
- 'G7-7 解释抽屉打开不清除待选',
- 'G7-7 附件随消息送给模型',
- 'G7-7 重开后附件还原且不铺正文',
- 'G7-7 runtime 重启后仍停在 K3',
- 'G7-7 选模后挂出代码确认卡且未执行',
- 'G7-7 点运行后阶段 4 完成且待决清空',
- 'G7-7 问答会话进入历史列表',
- 'G7-7 新对话清空当前消息',
- 'G7-7 切换历史会话恢复消息',
- 'G7-7 删除历史会话',
- 'G7-7 清空历史后列表与阶段复位',
- 'G7-8 工作台渲染出首版图表',
- 'G7-8 换主题重渲出第二版,只显示当前图',
- 'G7-8 回滚到第一版',
- 'G7-8 评分卡五维、总分 86 且达标',
- 'G7-8 扣分项能定位到正文',
- 'G7-8 第三轮低于 85 显示熔断提示',
- 'G7-8 门禁条四项全绿',
- 'G7-8 门禁摘要并入栏头',
- 'G7-9 论文页打开且构建按钮可用',
- 'G7-9 论文构建出 PDF 与 DOCX',
- 'G7-9 去 AI 与章节门禁全绿',
- 'G7-9 论文 PDF 预览渲染且截图非空',
- 'G7-10 宽屏右栏按比例放宽',
- 'G7-10 宽屏论文页两栏且预览限宽',
- 'G7-10 宽屏评分页两栏',
- 'G7-10 握把高亮跟随指针',
- 'G7-10 左栏固定不可拖拽',
- 'G7-10 中/右分隔条可拖拽',
- 'G7-10 离开分隔条后握把保持在指针处',
- 'G7-10 输入框上沿可拖拽',
- 'G7-10 输入框上沿空心长条居中骑在框线',
- 'G7-10 按钮行在输入框卡片外且同宽',
- 'G7-10 按钮行不随输入框拉伸移动',
- 'G7-10 右栏可收起为图标条',
- 'G7-10 点图标展开并切到对应页',
- 'G7-12 问答手动收起写 chat 偏好',
- 'G7-12 切建模有列宽过渡',
- 'G7-12 进入建模自动展开大工作台',
- 'G7-12 建模态阶段轨道整块展开',
- 'G7-12 退出建模恢复问答收起偏好',
- 'G7-12 阶段区隐藏但仍在 DOM',
- 'G7-14 建模会话建出赛题文件夹',
- 'G7-14 暂存附件收进项目附件目录'
-]
-
-const problems = []
-const fail = (msg) => problems.push(msg)
-
-function parseArgs(argv) {
- const opts = { file: DEFAULT_FILE, selftest: false }
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i]
- if (a === '--selftest') opts.selftest = true
- else if (a === '-h' || a === '--help') {
- process.stdout.write('用法: node scripts/check-window-smoke.mjs [--file ] [--selftest]\n')
- process.exit(0)
- } else if (a === '--file') {
- const v = argv[++i]
- if (!v) usage('--file 缺参数值')
- opts.file = resolve(v)
- } else usage(`未知选项: ${a}`)
- }
- return opts
-}
-
-function usage(msg) {
- process.stderr.write(`用法错误: ${msg}\n`)
- process.exit(2)
-}
-
-/** 对一份结果对象做判据;返回问题列表,空即通过。 */
-export function judge(data) {
- const errs = []
- if (!data || typeof data !== 'object') return ['结果不是对象']
- if (typeof data.ok !== 'boolean') errs.push('缺布尔字段 ok')
- if (!Number.isInteger(data.total) || data.total < MIN_ASSERTIONS) {
- errs.push(`断言条数 ${data.total} 少于下限 ${MIN_ASSERTIONS}(断言集合被删空也是失败)`)
- }
- if (data.failed !== 0) errs.push(`failed=${data.failed},必须为 0`)
- if (data.ok !== true) errs.push('ok 不为 true')
- if (data.contentSize !== EXPECT_SIZE) errs.push(`内容尺寸实读 ${data.contentSize},应为 ${EXPECT_SIZE}`)
- if (typeof data.minInkRatio !== 'number' || data.minInkRatio < MIN_THRESHOLD_FLOOR) {
- errs.push(`非白像素阈值被调到 ${data.minInkRatio},不得低于 ${MIN_THRESHOLD_FLOOR}(把阈值调成 0 来「过」是假的通过)`)
- }
- if (typeof data.inkRatio !== 'number' || !(data.inkRatio >= (data.minInkRatio ?? 0))) {
- errs.push(`inkRatio=${data.inkRatio} 未达阈值 ${data.minInkRatio}`)
- }
- if (!Array.isArray(data.results)) errs.push('results 不是数组')
- else {
- const badShape = data.results.filter((r) => !r || typeof r.name !== 'string' || typeof r.ok !== 'boolean' || typeof r.detail !== 'string')
- if (badShape.length) errs.push(`${badShape.length} 条结果缺 name/ok/detail`)
- const countedFail = data.results.filter((r) => r && r.ok === false).length
- if (countedFail !== data.failed) errs.push(`自述 failed=${data.failed} 与明细里的 ${countedFail} 条 FAIL 不一致`)
- const selfTotal = data.results.length
- if (selfTotal !== data.total) errs.push(`自述 total=${data.total} 与明细 ${selfTotal} 条不一致`)
- const names = data.results.map((r) => (r && typeof r.name === 'string' ? r.name : ''))
- const missing = REQUIRED_ASSERTIONS.filter((name) => !names.includes(name))
- if (missing.length) errs.push(`缺少关键断言: ${missing.join(';')}`)
- const dupes = [...new Set(names.filter((name, i) => name && names.indexOf(name) !== i))]
- if (dupes.length) errs.push(`断言名重复: ${dupes.join(';')}(重复行可以凑条数)`)
- const ready = data.results.find((r) => r && r.name === 'G7-3 runtime 通过握手就绪')
- if (ready && !String(ready.detail).includes('离线演示')) {
- errs.push('runtime 就绪那条没有证明是离线演示 provider 在跑')
- }
- }
- return errs
-}
-
-function runJudge(file) {
- if (!existsSync(file)) {
- // 没有证据就是没过:上一轮的假绿正是「脚本没真跑成但也报了绿」的同类问题
- return ['没有结果文件 ' + file]
- }
- let data
- try {
- data = JSON.parse(readFileSync(file, 'utf8'))
- } catch (e) {
- return [`结果文件不是合法 JSON: ${e.message}`]
- }
- return judge(data)
-}
-
-function selftest() {
- const dir = mkdtempSync(join(tmpdir(), 'mms-wsmoke-'))
- const requiredRows = REQUIRED_ASSERTIONS.map((name) => ({
- name,
- ok: true,
- detail: name === 'G7-3 runtime 通过握手就绪' ? '状态栏: 运行时已连接 · 离线演示' : 'ok'
- }))
- const filler = Array.from(
- { length: Math.max(0, MIN_ASSERTIONS - requiredRows.length) },
- (_, i) => ({ name: `A${i}`, ok: true, detail: 'ok' })
- )
- const good = {
- ok: true,
- total: MIN_ASSERTIONS,
- failed: 0,
- contentSize: EXPECT_SIZE,
- inkRatio: 0.0211,
- minInkRatio: MIN_THRESHOLD_FLOOR,
- url: 'file:///abs/out/renderer/index.html',
- results: [...requiredRows, ...filler]
- }
- const cases = [
- { name: '全绿夹具应通过', mutate: () => good, wantPass: true },
- { name: '有一条 FAIL 必须判失败', mutate: (d) => ((d.failed = 1), (d.results[0].ok = false), (d.ok = false)), wantPass: false },
- { name: 'ok=true 但尺寸读数不对', mutate: (d) => (d.contentSize = '1439x899'), wantPass: false },
- { name: 'ok=true 但非白像素低于阈值', mutate: (d) => (d.inkRatio = 0.0002), wantPass: false },
- { name: 'ok=true 但阈值被调成 0', mutate: (d) => ((d.minInkRatio = 0), (d.inkRatio = 0)), wantPass: false },
- { name: '断言条数被删到下限以下', mutate: (d) => ((d.total = 3), (d.results = d.results.slice(0, 3))), wantPass: false },
- { name: '自述 failed 与明细不一致', mutate: (d) => (d.failed = 2), wantPass: false },
- {
- name: '删掉关键断言、用凑数行补满条数',
- mutate: (d) => {
- const idx = d.results.findIndex((r) => r.name === 'G7-5 工具卡完成并给出结构化结果')
- d.results[idx] = { name: 'A-extra', ok: true, detail: 'ok' }
- },
- wantPass: false
- },
- {
- name: '删掉 M3 的持久化断言、补一条 A 行',
- mutate: (d) => {
- const idx = d.results.findIndex((r) => r.name === 'G7-7 runtime 重启后仍停在 K3')
- d.results[idx] = { name: 'A-m3', ok: true, detail: 'ok' }
- },
- wantPass: false
- },
- {
- name: '关键断言的 detail 不再证明离线演示',
- mutate: (d) => {
- const row = d.results.find((r) => r.name === 'G7-3 runtime 通过握手就绪')
- row.detail = '状态栏: runtime 已连接'
- },
- wantPass: false
- },
- { name: '结果文件不存在', mutate: null, wantPass: false }
- ]
-
- const rows = []
- for (const [i, c] of cases.entries()) {
- const label = `${String(i + 1).padStart(2, '0')} ${c.name}`
- if (c.mutate === null) {
- const errs = runJudge(join(dir, 'nope.json'))
- rows.push({ label, pass: c.wantPass ? errs.length === 0 : errs.length > 0, detail: errs.join(' / ') || '居然放过了' })
- continue
- }
- const data = structuredClone(good)
- c.mutate(data)
- const file = join(dir, `case-${i}.json`)
- writeFileSync(file, JSON.stringify(data, null, 2))
- const errs = runJudge(file)
- rows.push({
- label,
- pass: c.wantPass ? errs.length === 0 : errs.length > 0,
- detail: errs.join(' / ') || '判为通过'
- })
- }
-
- // 再验一次「本脚本自己的退出码约定」:真把自己 spawn 起来跑一次坏结果
- const badFile = join(dir, 'spawn-bad.json')
- const bad = structuredClone(good)
- bad.failed = 1
- bad.ok = false
- bad.results[0].ok = false
- writeFileSync(badFile, JSON.stringify(bad, null, 2))
- const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--file', badFile], { encoding: 'utf8' })
- rows.push({
- label: '99 作为 CLI 对被污染结果必须非零退出',
- pass: r.status === 1,
- detail: `exit ${r.status}`
- })
-
- rmSync(dir, { recursive: true, force: true })
- for (const row of rows) {
- process.stdout.write(`${row.pass ? 'PASS' : 'FAIL'} ${row.label}\n ${row.detail}\n`)
- }
- const bad2 = rows.filter((x) => !x.pass)
- process.stdout.write(`\n${rows.length - bad2.length}/${rows.length} 条核验自测通过\n`)
- process.exit(bad2.length === 0 ? 0 : 1)
-}
-
-const opts = parseArgs(process.argv.slice(2))
-if (opts.selftest) selftest()
-
-const errs = runJudge(opts.file)
-if (errs.length === 0) {
- const data = JSON.parse(readFileSync(opts.file, 'utf8'))
- process.stdout.write(
- `PASS 真启动结果核验:${data.total} 条断言全过,内容尺寸 ${data.contentSize},非白像素 ${(data.inkRatio * 100).toFixed(2)}%(阈值 ${(data.minInkRatio * 100).toFixed(2)}%)\n`
- )
- process.exit(0)
-}
-process.stderr.write(`FAIL 真启动结果核验(${opts.file}):\n`)
-for (const e of errs) process.stderr.write(` - ${e}\n`)
-process.exit(1)
diff --git a/scripts/check-xlsx.mjs b/scripts/check-xlsx.mjs
deleted file mode 100644
index 0dc5a47..0000000
--- a/scripts/check-xlsx.mjs
+++ /dev/null
@@ -1,276 +0,0 @@
-#!/usr/bin/env node
-/**
- * xlsx 读取自检:用内存里拼出的最小工作簿跑 src/main/xlsx.ts。
- *
- * 覆盖共享字符串与富文本、拼音剔除、内联字符串、稀疏列、布尔/错误/公式缓存值、
- * 日期与时间格式、1904 日期系统、行列表数上限,以及两种坏文件必须报错。
- * 退出码:0 通过 / 1 断言失败 / 2 环境错误。
- */
-import { crc32, deflateRawSync } from 'node:zlib'
-
-const USAGE = '用法: node scripts/check-xlsx.mjs [-h]'
-
-function failUsage(message) {
- process.stderr.write(`用法或环境错误: ${message}\n${USAGE}\n`)
- process.exit(2)
-}
-
-for (const arg of process.argv.slice(2)) {
- if (arg === '-h' || arg === '--help') {
- process.stdout.write(USAGE + '\n')
- process.exit(0)
- }
- failUsage(`未知参数: ${arg}`)
-}
-
-function zip(parts) {
- const locals = []
- const centrals = []
- let offset = 0
- for (const [name, content] of Object.entries(parts)) {
- const nameBytes = Buffer.from(name, 'utf8')
- const data = Buffer.from(content, 'utf8')
- const compressed = deflateRawSync(data)
- const checksum = crc32(data)
-
- const local = Buffer.alloc(30)
- local.writeUInt32LE(0x04034b50, 0)
- local.writeUInt16LE(20, 4)
- local.writeUInt16LE(0x0800, 6)
- local.writeUInt16LE(8, 8)
- local.writeUInt32LE(checksum, 14)
- local.writeUInt32LE(compressed.length, 18)
- local.writeUInt32LE(data.length, 22)
- local.writeUInt16LE(nameBytes.length, 26)
- locals.push(local, nameBytes, compressed)
-
- const central = Buffer.alloc(46)
- central.writeUInt32LE(0x02014b50, 0)
- central.writeUInt16LE(20, 4)
- central.writeUInt16LE(20, 6)
- central.writeUInt16LE(0x0800, 8)
- central.writeUInt16LE(8, 10)
- central.writeUInt32LE(checksum, 16)
- central.writeUInt32LE(compressed.length, 20)
- central.writeUInt32LE(data.length, 24)
- central.writeUInt16LE(nameBytes.length, 28)
- central.writeUInt32LE(offset, 42)
- centrals.push(central, nameBytes)
-
- offset += 30 + nameBytes.length + compressed.length
- }
-
- const directory = Buffer.concat(centrals)
- const end = Buffer.alloc(22)
- end.writeUInt32LE(0x06054b50, 0)
- end.writeUInt16LE(Object.keys(parts).length, 8)
- end.writeUInt16LE(Object.keys(parts).length, 10)
- end.writeUInt32LE(directory.length, 12)
- end.writeUInt32LE(offset, 16)
- return Buffer.concat([...locals, directory, end])
-}
-
-const XML_HEAD = '\n'
-
-function workbook({ date1904 = false, sheets, shared, styles }) {
- const sheetTags = sheets
- .map((sheet, index) => ` `)
- .join('')
- const rels = sheets
- .map(
- (sheet, index) =>
- ` `
- )
- .join('')
- return zip({
- 'xl/workbook.xml': `${XML_HEAD}${sheetTags} `,
- 'xl/_rels/workbook.xml.rels': `${XML_HEAD}${rels} `,
- 'xl/sharedStrings.xml': shared,
- 'xl/styles.xml': styles,
- ...Object.fromEntries(sheets.map((sheet) => [sheet.path, sheet.xml]))
- })
-}
-
-const STYLES = `${XML_HEAD} `
-
-const SHARED = `${XML_HEAD}地区 华东 & 华南 销量 合计 带 PHONETIC `
-
-const SHEET1 = `${XML_HEAD}0 2 备注 |
1 12.5 45999 1 |
45999.5 0.75 SUM(B2) 行合计 #DIV/0! |
999 |
7 3 9 |
`
-
-const SHEET2 = `${XML_HEAD} `
-
-const MAIN_TEXT = [
- '[工作表 数据&表] 4 行 × 5 列',
- '地区\t销量合计\t\t备注',
- '华东 & 华南\t12.5\t2025-12-08\tTRUE',
- '2025-12-08 12:00:00\t18:00:00\t行合计\t#DIV/0!',
- '7\t\t带\t\t9',
- '',
- '[工作表 第二页] 空表'
-].join('\n')
-
-const expected = {
- text: MAIN_TEXT,
- note: '2 个工作表;数据&表 4 行 × 5 列、第二页 空表'
-}
-
-const checks = []
-function check(name, run) {
- try {
- const detail = run()
- checks.push({ name, ok: true, detail })
- } catch (err) {
- checks.push({ name, ok: false, detail: err instanceof Error ? err.message : String(err) })
- }
-}
-
-function equal(actual, want, label) {
- if (actual !== want) {
- throw new Error(`${label}\n 实际: ${JSON.stringify(actual)}\n 期望: ${JSON.stringify(want)}`)
- }
-}
-
-function includes(haystack, needle, label) {
- if (!haystack.includes(needle)) throw new Error(`${label}:找不到 ${JSON.stringify(needle)}`)
-}
-
-let extractXlsx
-try {
- ;({ extractXlsx } = await import('../src/main/xlsx.ts'))
-} catch (err) {
- failUsage(`加载 src/main/xlsx.ts 失败(需要 Node 22.18+): ${err.message}`)
-}
-if (typeof extractXlsx !== 'function') failUsage('src/main/xlsx.ts 没有导出 extractXlsx')
-
-const main = workbook({
- sheets: [
- { name: '数据&表', target: 'worksheets/sheet1.xml', path: 'xl/worksheets/sheet1.xml', xml: SHEET1 },
- { name: '第二页', target: '/xl/worksheets/sheet2.xml', path: 'xl/worksheets/sheet2.xml', xml: SHEET2 }
- ],
- shared: SHARED,
- styles: STYLES
-})
-
-check('主工作表:文本与表头', () => {
- const out = extractXlsx(main)
- equal(out.text, expected.text, '正文不一致')
- return '两表文本一致'
-})
-
-check('主工作表:说明含行×列', () => {
- const out = extractXlsx(main)
- equal(out.note, expected.note, '说明不一致')
- return out.note
-})
-
-check('共享字符串:实体、富文本拼合、拼音剔除', () => {
- const out = extractXlsx(main)
- includes(out.text, '华东 & 华南', 'XML 实体')
- includes(out.text, '销量合计', '富文本')
- if (out.text.includes('PHONETIC')) throw new Error('拼音行没有剔除')
- return '实体/富文本/拼音均正确'
-})
-
-check('稀疏列与日期时间', () => {
- const out = extractXlsx(main)
- includes(out.text, '2025-12-08\tTRUE', '日期列')
- includes(out.text, '2025-12-08 12:00:00\t18:00:00', '自定义日期与时间格式')
- includes(out.text, '7\t\t带\t\t9', '空列补齐')
- return '日期/时间/空列正确'
-})
-
-const longSheet = `${XML_HEAD}${Array.from(
- { length: 305 },
- (_, index) => `${index + 1}
`
-).join('')} `
-
-check('行数上限:只读 300 行并写入说明', () => {
- const out = extractXlsx(
- workbook({
- sheets: [{ name: '长表', target: 'worksheets/sheet1.xml', path: 'xl/worksheets/sheet1.xml', xml: longSheet }],
- shared: SHARED,
- styles: STYLES
- })
- )
- const lines = out.text.split('\n')
- equal(lines.length, 301, '正文行数')
- if (lines[300] !== '300') throw new Error(`第 300 行不是 300:${JSON.stringify(lines[300])}`)
- if (lines.includes('301')) throw new Error('第 301 行不该读入')
- includes(out.note, '每个工作表最多 300 行', '截断说明')
- return out.note
-})
-
-check('日期格式不带时间:小数部分不显示', () => {
- const xml = `${XML_HEAD}45999.5 |
`
- const out = extractXlsx(
- workbook({
- sheets: [{ name: '日期', target: 'worksheets/sheet1.xml', path: 'xl/worksheets/sheet1.xml', xml }],
- shared: SHARED,
- styles: STYLES
- })
- )
- includes(out.text, '2025-12-08', '日期')
- if (out.text.includes('12:00:00')) throw new Error('日期格式不该带出时间')
- return '2025-12-08'
-})
-
-check('1904 日期系统', () => {
- const xml = `${XML_HEAD}1 |
`
- const out = extractXlsx(
- workbook({
- date1904: true,
- sheets: [{ name: '日期', target: 'worksheets/sheet1.xml', path: 'xl/worksheets/sheet1.xml', xml }],
- shared: SHARED,
- styles: STYLES
- })
- )
- includes(out.text, '1904-01-02', '序列号 1')
- return '1904-01-02'
-})
-
-check('图表页不当作空表', () => {
- const wb = zip({
- 'xl/workbook.xml': `${XML_HEAD} `,
- 'xl/_rels/workbook.xml.rels': `${XML_HEAD} `,
- 'xl/sharedStrings.xml': SHARED,
- 'xl/styles.xml': STYLES,
- 'xl/worksheets/sheet1.xml': SHEET2,
- 'xl/chartsheets/sheet1.xml': `${XML_HEAD} `
- })
- const out = extractXlsx(wb)
- equal(out.note, '1 个工作表;数据 空表', '说明')
- if (out.text.includes('图表')) throw new Error('图表页不该出现在正文里')
- return out.note
-})
-
-check('坏文件:不是 ZIP', () => {
- let message = ''
- try {
- extractXlsx(Buffer.from('not a zip at all'))
- } catch (err) {
- message = err instanceof Error ? err.message : String(err)
- }
- includes(message, '缺少压缩目录', '错误说明')
- return message
-})
-
-check('坏文件:ZIP 里没有工作簿', () => {
- let message = ''
- try {
- extractXlsx(zip({ 'xl/worksheets/sheet1.xml': SHEET1 }))
- } catch (err) {
- message = err instanceof Error ? err.message : String(err)
- }
- includes(message, '缺少工作簿', '错误说明')
- return message
-})
-
-const failed = checks.filter((item) => !item.ok)
-for (const item of checks) {
- process.stdout.write(`${item.ok ? 'PASS' : 'FAIL'} ${item.name}${item.detail ? ` — ${item.detail}` : ''}\n`)
-}
-if (failed.length > 0) {
- process.stderr.write(`\n${failed.length}/${checks.length} 条未通过\n`)
- process.exit(1)
-}
-process.stdout.write(`\nOK ${checks.length}/${checks.length}\n`)
diff --git a/scripts/docshots.cjs b/scripts/docshots.cjs
deleted file mode 100644
index dd59404..0000000
--- a/scripts/docshots.cjs
+++ /dev/null
@@ -1,220 +0,0 @@
-/**
- * 文档截图采集:离线演示驱动真实流程,1.5 倍密率重拍 docs/images。
- * 运行:npm run build 后 `npx electron --force-device-scale-factor=1.5 scripts/docshots.cjs`
- * 产出:workbench.png(通用欢迎,整行)、conversation.png(对话,整行)、
- * decision.png(五维雷达,整行)、process.png(过程总览,整行)、
- * score.png / paper.png(评分与论文,窄窗面板裁切,README 双列)。
- */
-const { app, BrowserWindow } = require('electron')
-const { join } = require('node:path')
-const { mkdtempSync, mkdirSync, writeFileSync, copyFileSync, rmSync, existsSync } = require('node:fs')
-const { tmpdir } = require('node:os')
-
-const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
-
-process.env.MMS_FAKE_PROVIDER = '1'
-process.env.MMS_FAKE_DELAY_MS = '20'
-const userDataDir = mkdtempSync(join(tmpdir(), 'mms-docshots-'))
-app.setPath('userData', userDataDir)
-process.env.MMS_WORKSPACE = join(userDataDir, 'workspace')
-
-app.commandLine.appendSwitch('disable-dev-shm-usage')
-app.commandLine.appendSwitch('force-device-scale-factor', '1.5')
-app.disableHardwareAcceleration()
-
-const ROOT = join(__dirname, '..')
-const IMG_DIR = join(ROOT, 'docs', 'images')
-const BACKUP_DIR = join(tmpdir(), 'mms-docshots-backup')
-const SHOTS = ['workbench.png', 'conversation.png', 'decision.png', 'score.png', 'paper.png']
-// process.png 是新增文件;其余五张先备份,采完不满意可回退。
-if (!existsSync(BACKUP_DIR)) {
- mkdirSync(BACKUP_DIR, { recursive: true })
- for (const name of SHOTS) {
- const src = join(IMG_DIR, name)
- if (existsSync(src)) copyFileSync(src, join(BACKUP_DIR, name))
- }
-}
-
-async function firstWindow(ms) {
- const t0 = Date.now()
- while (Date.now() - t0 < ms) {
- const win = BrowserWindow.getAllWindows()[0]
- if (win) return win
- await sleep(100)
- }
- throw new Error('没有等到窗口')
-}
-
-async function waitLoaded(win, ms) {
- const t0 = Date.now()
- while (Date.now() - t0 < ms) {
- const url = win.webContents.getURL()
- if (url && !url.startsWith('about:')) return url
- await sleep(100)
- }
- throw new Error('页面没有加载完成')
-}
-
-async function waitFor(win, expression, ms) {
- const t0 = Date.now()
- while (Date.now() - t0 < ms) {
- try {
- if (await win.webContents.executeJavaScript(expression)) return true
- } catch {
- /* 还在加载 */
- }
- await sleep(150)
- }
- throw new Error(`等待超时:${expression.slice(0, 80)}`)
-}
-
-async function settle(win) {
- win.show()
- win.focus()
- win.webContents.invalidate()
- await sleep(250)
- await win.webContents.capturePage()
- await sleep(350)
-}
-
-async function shotFull(win, name) {
- await settle(win)
- const img = await win.webContents.capturePage()
- const size = img.getSize()
- if (size.width < 2000) throw new Error(`${name} 密率不对:${size.width}x${size.height},应约 2160x1352`)
- writeFileSync(join(IMG_DIR, name), img.toPNG())
- console.log(`${name}: ${size.width}x${size.height}`)
-}
-
-async function shotRect(win, name, selector, minWidth) {
- win.show()
- win.focus()
- win.webContents.invalidate()
- await sleep(250)
- await win.webContents.capturePage()
- await sleep(350)
- const rect = await win.webContents.executeJavaScript(`(() => {
- const b = document.querySelector('${selector}').getBoundingClientRect()
- return { x: Math.max(0, Math.round(b.left)), y: Math.max(0, Math.round(b.top)), width: Math.round(b.width), height: Math.round(b.height) }
- })()`)
- let img = null
- for (let i = 0; i < 4; i++) {
- try {
- img = await win.webContents.capturePage(rect)
- break
- } catch {
- await sleep(400)
- }
- }
- if (!img) throw new Error(`${name} 截取失败`)
- const size = img.getSize()
- if (size.width < minWidth) throw new Error(`${name} 裁切异常:${size.width}x${size.height}`)
- writeFileSync(join(IMG_DIR, name), img.toPNG())
- console.log(`${name}: ${size.width}x${size.height}(面板 ${rect.width}x${rect.height} @ (${rect.x},${rect.y}))`)
-}
-
-async function typeAndSend(win, text, mode) {
- const sent = await win.webContents.executeJavaScript(`(() => {
- const input = document.querySelector('.composer__input')
- const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set
- setter.call(input, ${JSON.stringify(text)})
- input.dispatchEvent(new Event('input', { bubbles: true }))
- return true
- })()`)
- if (!sent) throw new Error('输入框不存在')
- await sleep(200)
- const clicked = await win.webContents.executeJavaScript(`document.querySelector('.pill--send[data-mode="${mode}"]')?.click() ?? true`)
- if (!clicked) throw new Error('发送按钮不可用')
-}
-
-async function main() {
- require(join(__dirname, '..', 'out', 'main', 'index.js'))
- const win = await firstWindow(20000)
- await waitLoaded(win, 20000)
- await sleep(700)
-
- await waitFor(win, `(document.querySelector('.statusbar')?.textContent || '').includes('运行时已连接')`, 25000)
- await waitFor(win, `(document.querySelector('.pill--model')?.textContent || '').includes('离线演示')`, 20000)
- await sleep(600)
- await shotFull(win, 'workbench.png')
-
- // 对话:离线演示走 list_templates 工具卡,等回复与工具卡都落定再拍
- await typeAndSend(win, '模板清单怎么用', 'chat')
- await waitFor(win, `[...document.querySelectorAll('.msg--assistant .msg__text')].some((n) => n.textContent.includes('25 个模板'))`, 30000)
- await waitFor(win, `!!document.querySelector('.tool-card[data-tool="list_templates"][data-status="ok"]')`, 20000)
- await waitFor(win, `!document.querySelector('.pill--stop')`, 20000)
- await sleep(900)
- await shotFull(win, 'conversation.png')
-
- // 数模:切模式 → 发题 → K2 → 确认 → K3(三张候选带雷达)
- await win.webContents.executeJavaScript(`document.querySelector('.mode-switch__btn[data-mode="workflow"]')?.click()`)
- await sleep(1100)
- await typeAndSend(win, '问题1 预测未来三个月的销量。\n问题2 给出补货建议。', 'workflow')
- await waitFor(win, `!!document.querySelector('.decision[data-card="problem-confirm"]')`, 20000)
- await sleep(500)
- await win.webContents.executeJavaScript(`document.querySelector('[data-action="confirm"]')?.click()`)
- const k3 = await waitFor(
- win,
- `[...document.querySelectorAll('.decision[data-card="model-choice"]')].some((c) => !c.querySelector('.decision__resolved') && c.querySelectorAll('.candidate__radar svg').length === 3)`,
- 20000
- )
- if (!k3) throw new Error('K3 卡没有带出三张雷达')
- await win.webContents.executeJavaScript(
- `[...document.querySelectorAll('.decision[data-card="model-choice"]')].find((c) => !c.querySelector('.decision__resolved'))?.scrollIntoView({ block: 'start' })`
- )
- await sleep(900)
- await shotFull(win, 'decision.png')
- // 面板裁切换 1500 宽窗:面板 ≈570 CSS → 裁切 855 物理px,README 双列显示时字号比例与旧图一致
- win.setContentSize(1500, 900)
- await sleep(600)
- await shotRect(win, 'process.png', '.workspace', 700)
-
- // 选第一张候选,等阶段四真跑出图,再拍评分
- await win.webContents.executeJavaScript(
- `[...document.querySelectorAll('.decision[data-card="model-choice"]')].find((c) => !c.querySelector('.decision__resolved'))?.querySelector('[data-action="choose"]')?.click()`
- )
- await waitFor(win, `document.querySelector('.rail .phase[data-phase="4"]')?.dataset.state === 'running'`, 20000)
- await waitFor(
- win,
- `(async () => { const s = await window.studio.workbench.state(); return !document.querySelector('.pill--stop') && s.figure.versions.length >= 1 })()`,
- 180000
- )
- await win.webContents.executeJavaScript(`document.querySelector('.tab[data-tab="score"]')?.click()`)
- await waitFor(win, `document.querySelectorAll('[data-panel="score"] .score-row').length === 5 && (document.querySelector('[data-role="score-total"]')?.textContent || '').includes('86')`, 20000)
- await sleep(700)
- await shotRect(win, 'score.png', '.workspace', 700)
-
- await win.webContents.executeJavaScript(`document.querySelector('.tab[data-tab="paper"]')?.click()`)
- await waitFor(win, `!!document.querySelector('.panel[data-panel="paper"]') && document.querySelector('[data-action="build-paper"]')?.disabled === false`, 20000)
- await win.webContents.executeJavaScript(`document.querySelector('[data-action="build-paper"]')?.click()`)
- await waitFor(
- win,
- `document.querySelectorAll('[data-role="paper-steps"] li').length >= 6 && document.querySelectorAll('[data-role="paper-gates"] .paper-gate').length === 3`,
- 240000
- )
- await waitFor(
- win,
- `(() => { const c = document.querySelector('[data-role="paper-preview"] canvas'); return !!c && c.width > 200 && c.height > 200 })()`,
- 30000
- )
- await sleep(900)
- await shotRect(win, 'paper.png', '.workspace', 700)
-
- console.log('DOC_SHOTS_OK')
- try {
- rmSync(userDataDir, { recursive: true, force: true })
- } catch (cleanupErr) {
- console.log(`[残留] ${userDataDir} 未删净: ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`)
- }
- app.quit()
-}
-
-main().catch((err) => {
- console.error('DOC_SHOTS_FAIL', err instanceof Error ? err.stack : String(err))
- try {
- rmSync(userDataDir, { recursive: true, force: true })
- } catch {
- /* 运行时还占着,稍后手动清 */
- }
- app.exit(1)
-})
diff --git a/scripts/make-icon.mjs b/scripts/make-icon.mjs
deleted file mode 100644
index d03ab0c..0000000
--- a/scripts/make-icon.mjs
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/env node
-/**
- * 由 build/icon.svg 生成 build/icon.png(1024)、build/icon.ico(16–256 多尺寸),
- * 以及 NSIS 向导用的 installerSidebar.bmp(164×314)与 installerHeader.bmp(150×57)。
- *
- * 栅格化用 PyMuPDF(requirements.txt 已含),ico 用 Vista+ 的 PNG 条目手工封装,
- * NSIS 图交 MUI 只吃 24 位 BMP——不引第三方图标库,也保证 exe/任务栏/安装包拿到同一份图形。
- *
- * node scripts/make-icon.mjs
- */
-import { spawnSync } from 'node:child_process'
-import { readFile, rm, writeFile } from 'node:fs/promises'
-import { dirname, join, resolve } from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
-const BUILD = join(ROOT, 'build')
-const SIZES = [16, 24, 32, 48, 64, 128, 256]
-
-const RASTER = `
-import struct
-import numpy as np
-import fitz
-
-page = fitz.open(${JSON.stringify(join(BUILD, 'icon.svg'))})[0]
-for size in ${JSON.stringify(SIZES)}:
- page.get_pixmap(matrix=fitz.Matrix(size / 1024.0, size / 1024.0), alpha=True).save(
- ${JSON.stringify(BUILD)} + '/icon-%d.png' % size)
-page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=True).save(${JSON.stringify(join(BUILD, 'icon.png'))})
-
-def art(size):
- pix = page.get_pixmap(matrix=fitz.Matrix(size / 1024.0, size / 1024.0), alpha=True)
- raw = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, 4).astype(float)
- # MuPDF 的 alpha pixmap 是预乘的
- comp = raw[..., :3] + 255.0 * (1 - raw[..., 3:4] / 255.0)
- return np.clip(np.rint(comp), 0, 255).astype(np.uint8)
-
-def bmp(path, canvas_w, canvas_h, icon_size):
- small = art(icon_size)
- canvas = np.full((canvas_h, canvas_w, 3), 255, np.uint8)
- x = (canvas_w - icon_size) // 2
- y = (canvas_h - icon_size) // 2
- canvas[y:y + icon_size, x:x + icon_size] = small
- row = (canvas_w * 3 + 3) // 4 * 4
- pad = row - canvas_w * 3
- body = bytearray()
- for line in canvas[::-1]:
- bgr = line[:, ::-1].tobytes()
- body += bgr + b'\\x00' * pad
- header = struct.pack('<2sIHHI', b'BM', 14 + 40 + len(body), 0, 0, 14 + 40)
- info = struct.pack(' {
- const base = index * 16
- directory.writeUInt8(size === 256 ? 0 : size, base)
- directory.writeUInt8(size === 256 ? 0 : size, base + 1)
- directory.writeUInt8(0, base + 2)
- directory.writeUInt8(0, base + 3)
- directory.writeUInt16LE(1, base + 4)
- directory.writeUInt16LE(32, base + 6)
- directory.writeUInt32LE(buffer.length, base + 8)
- directory.writeUInt32LE(offset, base + 12)
- offset += buffer.length
-})
-
-await writeFile(join(BUILD, 'icon.ico'), Buffer.concat([header, directory, ...images.map((i) => i.buffer)]))
-for (const size of SIZES) await rm(join(BUILD, `icon-${size}.png`))
-
-console.log(
- `[icon] build/icon.png 1024x1024,build/icon.ico ${images.map((i) => i.size).join('/')},` +
- 'build/installerSidebar.bmp 164x314,build/installerHeader.bmp 150x57',
-)
diff --git a/scripts/smoke-dist.mjs b/scripts/smoke-dist.mjs
deleted file mode 100644
index 4647247..0000000
--- a/scripts/smoke-dist.mjs
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env node
-/**
- * G6 · 构建产物冒烟
- *
- * 只断言三件事:产物存在、HTML 真的挂上了 JS/CSS、bundle 里确实含有本项目的文案与配色令牌。
- * 最后一条是关键——「构建成功」不等于「打进去了我们的代码」,
- * 空模板目录也能构建出一个绿色的 dist。
- *
- * 退出码:0 通过 / 1 断言失败 / 2 环境错误(没跑过 build)
- */
-import { existsSync, readFileSync, readdirSync } from 'node:fs'
-import { dirname, join, resolve } from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
-const DIST = join(ROOT, 'out')
-const RENDERER = join(DIST, 'renderer')
-
-if (!existsSync(DIST)) {
- process.stderr.write('环境错误: 没有 out/ 目录,先跑 npm run build\n')
- process.exit(2)
-}
-
-const rows = []
-const record = (name, ok, detail) => rows.push({ name, ok, detail })
-
-// D1 三个入口都在
-for (const [label, p] of [
- ['out/main/index.js', join(DIST, 'main/index.js')],
- ['out/preload/index.js', join(DIST, 'preload/index.js')],
- ['out/renderer/index.html', join(RENDERER, 'index.html')]
-]) {
- record(`D1 存在 ${label}`, existsSync(p), existsSync(p) ? `${(readFileSync(p).length / 1024).toFixed(1)} KB` : '缺失')
-}
-
-const htmlPath = join(RENDERER, 'index.html')
-const html = existsSync(htmlPath) ? readFileSync(htmlPath, 'utf8') : ''
-
-// D2 挂载点与资源引用真的能落到磁盘上的文件
-const rootMount = /id=["']root["']/.test(html)
-const scriptSrc = html.match(/