question-workbench-mcp 0.2.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,115 +1,81 @@
1
1
  # question-workbench-mcp
2
2
 
3
- 给**非 DeepSeek Harness** 客户端用的题目工作台插件。它是标准 **MCP(Model Context Protocol)服务器**,不依赖 DSH,可被 Codex、WorkBuddy 以及其他支持 MCP 的代理客户端调用。
3
+ 题目工作台,**一个包,两种安装方式**:
4
4
 
5
- 已发布到 npm:`question-workbench-mcp`(需要 Node.js 18+)。
6
-
7
- ## 它提供什么
8
-
9
- | 工具 | 作用 |
10
- |---|---|
11
- | `question_prompt` | 生成题目处理提示:`recognition`(识图三段式)、`analysis`(思路)、`solution`(完整解题)、`summary`(总结)、`full`(全流程) |
12
- | `build_worksheet` | 生成 A4 讲义 HTML:题目、可选解答、**自动嵌入聊天里贴的图片**;默认**跳过【待确认】段**;返回文件路径,浏览器 Ctrl+P 打印 |
13
-
14
- 识图由客户端自己的多模态模型完成——MCP 服务器不本地 OCR。
15
-
16
- ## 直接贴图(0.2.0 起)
17
-
18
- 在 WorkBuddy 里直接把题目图片粘贴到聊天框,`build_worksheet` 会自动读取它保存的最近图片,**不需要再提供文件路径**:
5
+ | 装法 | 适用 | 得到什么 |
6
+ |---|---|---|
7
+ | DSH 插件 | DeepSeek Harness(Desktop / Web) | 输入框上方「题目工作台」面板 + 两个 Agent 工具 |
8
+ | MCP 服务器 | Codex、WorkBuddy 及其他 MCP 客户端 | `question_workbench_prompt` / `question_workbench_worksheet` 两个工具 |
19
9
 
20
- ```text
21
- 调用 build_worksheet,text=【题目】核对后的全文,outputPath=D:\讲义.html
22
- ```
10
+ 功能一致:题目图片识别提示 → 人工核对 → 思路/解题/总结 → A4 讲义 HTML 打印。识图由客户端多模态模型完成,本包不做本地 OCR。
23
11
 
24
- 默认规则:取 `~/.workbuddy/clipboard-images/` 中最近 **30 分钟**内的图片,最多 **3 张**。
12
+ ## 一、DSH 安装(0.3.0 起)
25
13
 
26
- 可用参数调整:
14
+ 在插件管理器里安装 `question-workbench-mcp@0.3.0` 即可(这个包同时带 bundle patch、Web 客户端和 Host 工具)。装完刷新页面:
27
15
 
28
- | 参数 | 默认 | 说明 |
29
- |---|---|---|
30
- | `useClipboard` | `true` | `false` 时不读贴图 |
31
- | `maxAgeMinutes` | `30` | 超过多久的贴图不再采用;`0` 表示不限 |
32
- | `imageLimit` | `3` | 最多嵌入几张 |
33
- | `clipboardDir` | WorkBuddy 目录 | 其他客户端可显式指定贴图目录 |
34
- | `images` | 无 | 显式传本地路径数组,优先于贴图 |
35
- | `skipChecks` | `true` | 生成讲义时去掉【待确认】/【待核实】整段;`false` 保留 |
16
+ - 输入框上方出现「▧ 题目工作台」
17
+ - 工具列表出现 `question_workbench_prompt`、`question_workbench_worksheet`
36
18
 
37
- 注意:贴图要**先粘进聊天再调用工具**;如果图片是很久以前贴的,把 `maxAgeMinutes` 调大或显式传 `images`。
19
+ ### 面板三步
38
20
 
39
- ## 跳过待确认
21
+ 1. **① 加图片**:在面板内直接 **Ctrl+V 粘贴截图**(也可点「选择题目图片」)→「提交识题」,图片随提示发到当前会话。
22
+ 2. **② 核对题目**:把回复粘贴进来修改;「已核对」勾选框为**可选**,不再拦下一步。
23
+ 3. **③ 分析解题**:思路分析 / 完整解题 / 知识总结 / 一键全流程;「预览」「导出讲义」「打印」。
40
24
 
41
- 默认生成讲义时直接跳过【待确认】段,不再要求先人工核对。代价是:如果识别里有错字,讲义也会带着错。需要保留时传 `skipChecks: false`。
25
+ 生成讲义时**默认跳过【待确认】段**;需要保留时对工具传 `skipChecks: false`。
42
26
 
43
- ## 快速启动(stdio)
27
+ ## 二、MCP 安装
44
28
 
45
29
  ```powershell
46
- npx -y question-workbench-mcp
30
+ npx -y question-workbench-mcp@0.3.0
47
31
  ```
48
32
 
49
- 本地源码方式:
33
+ ### Codex(`~/.codex/config.toml`)
50
34
 
51
- ```powershell
52
- node <本目录绝对路径>\server.js
53
- ```
35
+ ```toml
36
+ # Windows
37
+ [mcp_servers.question-workbench]
38
+ command = "cmd"
39
+ args = ["/c", "npx", "-y", "question-workbench-mcp@0.3.0"]
54
40
 
55
- ## WorkBuddy 配置
41
+ # macOS / Linux
42
+ # [mcp_servers.question-workbench]
43
+ # command = "npx"
44
+ # args = ["-y", "question-workbench-mcp@0.3.0"]
45
+ ```
56
46
 
57
- 配置文件:`C:\Users\<user>\.workbuddy\.mcp.json`(界面「MCP 服务管理」编辑器顶部显示的路径)。
47
+ ### WorkBuddy
58
48
 
59
- 把下面这一条**合并**进已有的 `mcpServers`,不要用整段替换整个文件——否则会删掉 `chrome-devtools`、`connector-proxy` 等其他服务器:
49
+ 配置文件 `C:\Users\<user>\.workbuddy\.mcp.json`,把下面一条**合并**进已有 `mcpServers`(不要整段替换):
60
50
 
61
51
  ```json
62
52
  "question-workbench": {
63
53
  "type": "stdio",
64
54
  "command": "npx",
65
- "args": ["-y", "question-workbench-mcp@0.2.0"]
55
+ "args": ["-y", "question-workbench-mcp@0.3.0"]
66
56
  }
67
57
  ```
68
58
 
69
- 也可以点界面「+ 添加 MCP」直接把上面的条目粘贴进去,让它自己写入。
70
-
71
- **生效方式**:一般**不需要重启 WorkBuddy**。改完配置后打开 `Renderer` 的新会话或重开「MCP 服务管理」面板,WorkBuddy 会重新解析并拉起 MCP(日志中会出现 `custom-mcp:question-workbench` 的 `stdio-connected`)。首次连接可能等 10 秒左右,因为 `npx` 要下载包;之后会走缓存。只有当面板里始终看不到、或工具列表里没有 `question_prompt` / `build_worksheet` 时,才需要完全退出 WorkBuddy 再启动。
59
+ 改完重开 MCP 面板或新会话即可生效,一般不需要重启;文件必须无 BOM 的 UTF-8。示例见 [workbuddy-mcp.example.json](workbuddy-mcp.example.json)。
72
60
 
73
- **编码注意**:文件必须是无 BOM 的 UTF-8;带 BOM 时 WorkBuddy 可能解析失败、只显示旧列表。
61
+ ## 三、两个工具的参数
74
62
 
75
- 示例文件:[workbuddy-mcp.example.json](workbuddy-mcp.example.json)。
63
+ `question_workbench_prompt`:`mode`(`recognition` / `analysis` / `solution` / `summary` / `full`)、`text`(除 recognition 外必填)、`language`。
76
64
 
77
- ## Codex CLI 配置
65
+ `question_workbench_worksheet`:`text`(必填)、`notes`、`title`、`grade`、`images`(本地图片路径数组)、`outputPath`(默认当前目录)、`skipChecks`(默认 true)、`language`。
78
66
 
79
- `~/.codex/config.toml`:
67
+ MCP 版额外支持 WorkBuddy 贴图目录自动取图:`useClipboard`(默认 true)、`maxAgeMinutes`(默认 30)、`imageLimit`(默认 3)、`clipboardDir`。
80
68
 
81
- ```toml
82
- # Windows
83
- [mcp_servers.question-workbench]
84
- command = "cmd"
85
- args = ["/c", "npx", "-y", "question-workbench-mcp@0.2.0"]
86
-
87
- # macOS / Linux
88
- # [mcp_servers.question-workbench]
89
- # command = "npx"
90
- # args = ["-y", "question-workbench-mcp@0.2.0"]
69
+ ```text
70
+ 调用 question_workbench_worksheet,text=题目,notes=解答,outputPath=D:\下载\讲义.html
91
71
  ```
92
72
 
93
- ## 在代理里的推荐流程
94
-
95
- 1. 用户在聊天里**贴题目图片**;
96
- 2. 调用 `question_prompt(mode="recognition")`,把三段结果给用户;
97
- 3. 用户确认/改正后,把文本传给 `question_prompt` 的 `analysis` / `solution` / `summary` / `full`;
98
- 4. 调用 `build_worksheet(text=题目, notes=解答)` —— 贴图自动带入、待确认段自动去掉;
99
- 5. 打开返回的 `.html`,Ctrl+P 预览并打印。
100
-
101
- ## 参数说明
102
-
103
- `question_prompt`:`mode`(必填)、`text`(除 recognition 外必填)、`language`(`zh` 默认 / `en`)。
104
-
105
- `build_worksheet`:`text`(必填)、`title`、`grade`、`notes`、`images`、`useClipboard`、`maxAgeMinutes`、`imageLimit`、`clipboardDir`、`skipChecks`、`outputPath`(默认写到当前工作目录)、`language`。
106
-
107
- ## 已知限制
73
+ ## 四、已知限制
108
74
 
109
- - 不做本地 OCR,也不做照片增强(去阴影/裁剪属于 DSH 版插件的浏览器端能力);
110
- - 贴图自动读取目前面向 WorkBuddy 的目录约定;其他客户端请显式传 `images` 或 `clipboardDir`;
111
- - 讲义中 `[待核实:原因]` / `[verify: reason]` 会以红色标出(`skipChecks` 只删除整段,不处理行内标记);
112
- - MCP 服务器不保存状态,草稿由客户端或用户自行保存。
75
+ - 不做本地 OCR;识别质量取决于客户端模型与图片清晰度。
76
+ - DSH 面板的原图增强(去阴影/裁剪/对比度)是浏览器 Canvas 实现;MCP 版没有该能力。
77
+ - 讲义中 `[待核实:原因]` 会标红;`skipChecks` 只删除整段,不处理行内标记。
78
+ - 0.3.0 起 `dsh-question-workbench` 旧包不再更新,功能已并入本包。
113
79
 
114
80
  ## License
115
81
 
package/client.js ADDED
@@ -0,0 +1,378 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'question-workbench-mcp',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const dict = {
7
+ zh: {
8
+ title: '题目工作台', open: '题目工作台', close: '收起', reset: '重新开始',
9
+ s1: '① 加图片', s2: '② 识别结果与讲义', pasteClipboard: '从剪贴板粘贴', pasteFail: '读取剪贴板失败,请手动 Ctrl+V 粘贴',
10
+ pick: '选择题目图片', optional: '已有题目文字(可选)', recognize: '提交识题',
11
+ sending: '发送中…', sent: '已发送,请在聊天中查看回复', needPhoto: '请先添加至少一张题目图片', needText: '请先粘贴或录入题目内容',
12
+ hint1: '在面板内直接 Ctrl+V 粘贴截图,或点「选择题目图片」;图片会随提示发给当前会话。',
13
+ pasteHint: '把回复中的【题目】【图形】【待确认】粘贴到这里,删掉多余解释。',
14
+ textLabel: '题目与图形(可编辑)', placeholder: '粘贴识别结果或手工录入…',
15
+ pending: '待确认:', verified: '已核对题目(可选)', pasted: '已粘贴图片', next: '下一步', back: '上一步', toCheck: '下一步:核对题目', verifiedFirst: '请先勾选“我已对照原图核对”', pasteWait: '等模型回复后,把【题目】【图形】【待确认】粘到下面',
16
+ analysis: '思路分析', solve: '完整解题', summary: '知识总结', all: '一键全流程',
17
+ copy: '复制提示', copied: '已复制', copyFail: '复制失败,请手动选择文本',
18
+ print: '打印', exportHtml: '导出讲义', exportHint: '已导出讲义 HTML:用浏览器打开后按 Ctrl+P 可预览 A4 分页并打印。', exportFail: '导出失败:', preview: '预览', hidePreview: '关闭预览', includeImg: '打印含原图', optimize: '优化原图(裁剪·去阴影·增强)', optimizing: '正在优化图片…', optimizeFail: '部分图片优化失败,已使用原图', showPrompt: '查看将发送的提示', printFail: '打印调用失败,请改用系统打印(Ctrl+P)', printHint: '已调用打印;若没有出现打印对话框或预览,请点「导出讲义」,用浏览器打开后按 Ctrl+P 预览并打印',
19
+ fail: '发送失败:', noSession: '当前会话不可用,请先打开一个会话',
20
+ sendAsk: '发送', notesLabel: '解答 / 解析', notesPlaceholder: '把模型的思路、解答或总结粘贴到这里;会打印在题目之后', autoFilled: '已自动填入模型回复', waiting: '已发送,等待模型回复后自动填入…', autoFail: '未自动获取到回复,可用「从剪贴板粘贴」手动补充', saved: '文字自动保存在本机浏览器(按会话)', diagramNote: '图形以原图为准:打印默认附原图,文本里的「图形」一行仅作排版提示。', limit: '最多 12 张,单张 ≤15MB',
21
+ src: '已核对题目:\n', rule: '以下内容已由用户对照原图人工核对,直接作为已知条件使用;不要重新质疑,也不要补充未确认的关系。\n\n',
22
+ rec: '只做识别,严格按三段输出,不要解释或额外分节,总字数≤300字:\n【题目】逐字转录印刷文字,保留题号、选项、符号和公式;看不清写[待核实:简短原因],不要猜。\n【图形】每张图一行,≤25字,只写可见关键元素,例如:图1 三角形ABC,P在内部,BM、CN交于P。\n【待确认】最多3条、每条≤15字;没有写“无”。',
23
+ askA: '只给思路,不要完整计算:①考点1行 ②关键思路3-5步。≤200字。',
24
+ askS: '给完整解题过程:分步推导+最终答案,公式简洁。≤400字。',
25
+ askM: '只总结:3-5条知识点与易错点,每条一行。≤150字。',
26
+ askF: '先给3-5步思路,再给完整解答和最终答案,最后1-2句易错点提醒;不重复题目。≤600字。'
27
+ },
28
+ en: {
29
+ title: 'Question workbench', open: 'Question workbench', close: 'Close', reset: 'Start over',
30
+ s1: '1 Photo', s2: '2 Result and worksheet', pasteClipboard: 'Paste from clipboard', pasteFail: 'Could not read the clipboard; paste manually',
31
+ pick: 'Choose photos', optional: 'Existing text (optional)', recognize: 'Recognize',
32
+ sending: 'Sending…', sent: 'Sent. Read the reply in chat.', needPhoto: 'Add at least one photo first', needText: 'Paste or type the question first',
33
+ hint1: 'Paste a screenshot with Ctrl+V inside the panel, or choose photos; they are sent with the prompt.',
34
+ pasteHint: 'Paste the reply here and delete extra explanation.',
35
+ textLabel: 'Question and diagram (editable)', placeholder: 'Paste the reply or type manually…',
36
+ pending: 'To verify: ', verified: 'Question checked (optional)', pasted: 'Image pasted', next: 'Next', back: 'Back', toCheck: 'Next: check text', verifiedFirst: 'Tick "I checked against the photos" first', pasteWait: 'When the reply arrives, paste the three sections below',
37
+ analysis: 'Reasoning', solve: 'Full solution', summary: 'Key points', all: 'Full workflow',
38
+ copy: 'Copy prompt', copied: 'Copied', copyFail: 'Copy failed; select the text manually',
39
+ print: 'Print', exportHtml: 'Export worksheet', exportHint: 'Worksheet exported. Open it in a browser and press Ctrl+P to preview A4 pages and print.', exportFail: 'Export failed: ', preview: 'Preview', hidePreview: 'Hide preview', includeImg: 'Include photos in print', optimize: 'Clean up photos (crop, shadows, contrast)', optimizing: 'Cleaning up photos…', optimizeFail: 'Some photos could not be cleaned; originals used', showPrompt: 'Show prompt to be sent', printFail: 'Print call failed; use Ctrl+P instead', printHint: 'Print dialog opened; press Ctrl+P if it did not appear',
40
+ fail: 'Send failed: ', noSession: 'No usable session; open a conversation first',
41
+ sendAsk: 'Send', notesLabel: 'Solution', notesPlaceholder: 'Paste the reasoning or solution here; it prints after the question', autoFilled: 'Model reply filled in automatically', waiting: 'Sent. Waiting for the reply to fill in…', autoFail: 'No reply captured; use "Paste from clipboard"', saved: 'Text is saved in this browser per session', diagramNote: 'The original photo is the diagram source; printing includes it by default. The one-line diagram note is for layout only.', limit: 'Up to 12 photos, 15 MB each',
42
+ src: 'Checked question:\n', rule: 'The user checked the following against the photos; use it as given. Do not re-question it or add unconfirmed relations.\n\n',
43
+ rec: 'Transcribe only. Output exactly three sections, no extra explanation, ≤300 words:\n[Question] literal printed text, keeping numbering, symbols and formulas; write [verify: short reason] instead of guessing.\n[Diagram] one line per figure, ≤25 words, only visible key elements, e.g. Fig.1 triangle ABC, P inside, BM and CN meet at P.\n[Checks] at most 3 items, ≤15 words each; write "none" if none.',
44
+ askA: 'Reasoning only: 1 line of key concepts, then 3-5 steps. ≤200 words.',
45
+ askS: 'Full solution: step-by-step work and final answer, concise formulas. ≤400 words.',
46
+ askM: 'Key points only: 3-5 lines of concepts and common mistakes. ≤150 words.',
47
+ askF: 'Give 3-5 reasoning steps, then the full solution and answer, then 1-2 lines of pitfalls; do not restate the question. ≤600 words.'
48
+ }
49
+ };
50
+ const css = `.qwb{font:inherit;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:12px;margin-bottom:8px}.qwb *{box-sizing:border-box}.qwb-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.qwb-head{justify-content:space-between;margin-bottom:8px}.qwb b{font-size:14px}.qwb-steps{display:flex;gap:6px;margin:6px 0 10px;font-size:12px}.qwb-steps .qwb-step{flex:1;text-align:center;padding:4px 6px;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;color:var(--dsw-alias-label-secondary)}.qwb-steps .qwb-step.on{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-brand-primary)}.qwb-steps .qwb-step.done{color:var(--dsw-alias-state-success-primary)}.qwb button,.qwb-up{font:inherit;font-size:12px;cursor:pointer;border:1px solid var(--dsw-alias-border-l1);border-radius:7px;padding:5px 10px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}.qwb button:disabled{opacity:.45;cursor:not-allowed}.qwb button:focus-visible,.qwb-up:focus-within{outline:2px solid var(--dsw-alias-brand-primary)}.qwb textarea{width:100%;font:inherit;font-size:13px;min-height:120px;resize:vertical;padding:8px;border:1px solid var(--dsw-alias-border-l1);border-radius:7px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary)}.qwb textarea.sm{min-height:56px}.qwb label{font-size:12px;color:var(--dsw-alias-label-secondary)}.qwb-up input{display:none}.qwb-thumbs{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0}.qwb-th{position:relative;width:56px;height:56px}.qwb-th img{width:100%;height:100%;object-fit:cover;border-radius:6px;border:1px solid var(--dsw-alias-border-l1)}.qwb-th button{position:absolute;top:-6px;right:-6px;padding:0 4px;border-radius:10px;line-height:16px}.qwb-v{white-space:pre-wrap;overflow-wrap:anywhere;font-size:13px;border:1px solid var(--dsw-alias-border-l1);border-radius:7px;padding:8px;margin:6px 0}.qwb-bad{color:var(--dsw-alias-state-error-primary);font-weight:600}.qwb-msg{font-size:12px;margin:6px 0}.qwb-msg.bad{color:var(--dsw-alias-state-error-primary)}.qwb-details{font-size:12px;color:var(--dsw-alias-label-secondary)}.qwb-details pre{white-space:pre-wrap;font-size:11px;max-height:120px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;padding:6px;margin:6px 0}.qwb-sheet{background:#fff;color:#161616;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:14px;margin:8px 0;max-height:46vh;overflow:auto}.qwb-sheet h4{font-size:15px;margin:0 0 8px}.qwb-pg{display:block;max-width:100%;margin:8px 0;border:1px solid #ddd}.qwb-launch{font:inherit;font-size:12px;cursor:pointer;background:none;border:1px solid var(--dsw-alias-border-l1);border-radius:7px;color:var(--dsw-alias-label-secondary);padding:3px 9px;margin-bottom:5px}`;
51
+ const marker = /([待核实[^]\n]{0,80}]|\[verify[^\]\n]{0,80}\])/gi;
52
+ const hasMarker = v => /[待核实[^]\n]*]|\[verify[^\]\n]*\]/i.test(v);
53
+ const stripChecks = v => String(v)
54
+ .replace(/(?:^|\n)\s*【(?:待确认|待核实)】[\s\S]*?(?=\n\s*【|$)/g, '')
55
+ .replace(/(?:^|\n)\s*\[(?:Checks|Items to verify)\][\s\S]*?(?=\n\s*\[|$)/gi, '')
56
+ .replace(/\n{3,}/g, '\n\n')
57
+ .trim();
58
+ const esc = v => String(v).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
59
+ const inl = v => esc(v).replace(marker,'<b class="bad">$1</b>');
60
+ const frags = v => String(v).split(marker).map((p,i) => /^(?:[待核实[^]\n]*]|\[verify[^\]\n]*\])$/i.test(p) ? h('b',{className:'qwb-bad',key:i},p) : p);
61
+ const count = v => (String(v).match(/[待核实[^]\n]*]|\[verify[^\]\n]*\]/gi)||[]).length;
62
+ const IMG_TYPES = ['image/png','image/jpeg','image/webp','image/gif'];
63
+ function loadImg(src) { return new Promise((ok, no) => { const im = new Image(); im.onload = () => ok(im); im.onerror = () => no(new Error('image load failed')); im.src = src; }); }
64
+ function maxFilter(gray, w, h, r) {
65
+ const out = new Uint8ClampedArray(w * h);
66
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
67
+ let m = 0;
68
+ for (let dy = -r; dy <= r; dy++) { const yy = y + dy; if (yy < 0 || yy >= h) continue;
69
+ for (let dx = -r; dx <= r; dx++) { const xx = x + dx; if (xx < 0 || xx >= w) continue; const v = gray[yy * w + xx]; if (v > m) m = v; } }
70
+ out[y * w + x] = m;
71
+ }
72
+ return out;
73
+ }
74
+ async function enhance(src) {
75
+ const img = await loadImg(src);
76
+ const scale = Math.min(1, 1500 / Math.max(img.width || 1, img.height || 1));
77
+ const w = Math.max(1, Math.round((img.width || 1) * scale)), h = Math.max(1, Math.round((img.height || 1) * scale));
78
+ const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
79
+ const g = cv.getContext('2d'); g.drawImage(img, 0, 0, w, h);
80
+ const px = g.getImageData(0, 0, w, h);
81
+ const d = px.data, n = w * h, lum = new Uint8ClampedArray(n);
82
+ for (let i = 0; i < n; i++) { const j = i * 4; lum[i] = (d[j] * 299 + d[j + 1] * 587 + d[j + 2] * 114) / 1000; }
83
+ const sw = Math.max(1, Math.round(w / 8)), sh = Math.max(1, Math.round(h / 8));
84
+ const sm = document.createElement('canvas'); sm.width = sw; sm.height = sh;
85
+ const sg = sm.getContext('2d'); sg.drawImage(cv, 0, 0, sw, sh);
86
+ const sp = sg.getImageData(0, 0, sw, sh).data;
87
+ const sl = new Uint8ClampedArray(sw * sh);
88
+ for (let i = 0; i < sw * sh; i++) { const j = i * 4; sl[i] = (sp[j] * 299 + sp[j + 1] * 587 + sp[j + 2] * 114) / 1000; }
89
+ const bgSmall = maxFilter(sl, sw, sh, 4);
90
+ const bc = document.createElement('canvas'); bc.width = sw; bc.height = sh;
91
+ const bgc = bc.getContext('2d'); const bimg = bgc.createImageData(sw, sh);
92
+ for (let i = 0; i < sw * sh; i++) { const j = i * 4; bimg.data[j] = bimg.data[j + 1] = bimg.data[j + 2] = bgSmall[i]; bimg.data[j + 3] = 255; }
93
+ bgc.putImageData(bimg, 0, 0);
94
+ const up = document.createElement('canvas'); up.width = w; up.height = h;
95
+ const ug = up.getContext('2d'); ug.imageSmoothingEnabled = true; ug.drawImage(bc, 0, 0, w, h);
96
+ const bg = ug.getImageData(0, 0, w, h).data;
97
+ // Divide by the estimated paper brightness: flattens shadows and lifts contrast.
98
+ for (let i = 0; i < n; i++) {
99
+ const j = i * 4, base = Math.max(24, bg[j]);
100
+ for (let k = 0; k < 3; k++) { const v = d[j + k] * 255 / base; d[j + k] = v > 255 ? 255 : v; }
101
+ }
102
+ // Content bounds for an automatic margin/shadow crop.
103
+ let minX = w, minY = h, maxX = -1, maxY = -1;
104
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
105
+ const j = (y * w + x) * 4;
106
+ const v = (d[j] * 299 + d[j + 1] * 587 + d[j + 2] * 114) / 1000;
107
+ if (v < 235) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; }
108
+ }
109
+ let x0 = 0, y0 = 0, x1 = w - 1, y1 = h - 1;
110
+ if (maxX > minX + 8 && maxY > minY + 8 && (maxX - minX) * (maxY - minY) > n * 0.08) {
111
+ const pad = 6; x0 = Math.max(0, minX - pad); y0 = Math.max(0, minY - pad); x1 = Math.min(w - 1, maxX + pad); y1 = Math.min(h - 1, maxY + pad);
112
+ }
113
+ const ow = x1 - x0 + 1, oh = y1 - y0 + 1;
114
+ const out = document.createElement('canvas'); out.width = ow; out.height = oh;
115
+ const og = out.getContext('2d');
116
+ const clean = og.createImageData(w, h); clean.data.set(d);
117
+ const tmp = document.createElement('canvas'); tmp.width = w; tmp.height = h;
118
+ tmp.getContext('2d').putImageData(clean, 0, 0);
119
+ og.drawImage(tmp, x0, y0, ow, oh, 0, 0, ow, oh);
120
+ return out.toDataURL('image/jpeg', 0.92);
121
+ }
122
+ function useT(ctx) {
123
+ const [snap,setSnap] = React.useState(() => ctx.locale.getLocale());
124
+ React.useEffect(() => ctx.locale.subscribe(() => setSnap(ctx.locale.getLocale())), []);
125
+ return dict[String(snap.active||'').toLowerCase().startsWith('zh') ? 'zh' : 'en'];
126
+ }
127
+ function printDoc(t, state) {
128
+ const lines = v => inl(stripChecks(v)).split('\n').map(l => '<div>' + (l || '&nbsp;') + '</div>').join('');
129
+ const pics = state.images ? state.photos.map((p,i) => '<figure><img src="' + p.data + '" alt="' + esc(p.name) + '"><figcaption>' + esc(p.name) + '</figcaption></figure>').join('') : '';
130
+ const notes = state.notes && String(state.notes).trim() ? '<h2>' + esc(t.notesLabel) + '</h2><section>' + lines(state.notes) + '</section>' : '';
131
+ return '<!doctype html><html><head><meta charset="utf-8"><title>' + esc(t.title) + '</title><style>@page{size:A4;margin:16mm}body{font:12pt/1.7 system-ui,sans-serif;color:#161616}h1{font-size:18pt}h2{font-size:13pt;margin-top:16px;border-bottom:1px solid #999}section{white-space:pre-wrap;overflow-wrap:anywhere}figure{break-inside:avoid;margin:14px 0}figure img{max-width:100%;max-height:235mm;object-fit:contain}figcaption{font-size:9pt;color:#666}.bad{color:#b42318;background:#fff0ec}button{display:none}</style></head><body><h1>' + esc(t.title) + '</h1><section>' + lines(state.text || '') + '</section>' + pics + notes + '</body></html>';
132
+ }
133
+ function Bench({ ctx, t, sessionId }) {
134
+ const [open,setOpen] = React.useState(false);
135
+ const [step,setStep] = React.useState(1);
136
+ const [photos,setPhotos] = React.useState([]);
137
+ const [text,setText] = React.useState('');
138
+ const [notes,setNotes] = React.useState('');
139
+ const [checked,setChecked] = React.useState(false);
140
+ const [busy,setBusy] = React.useState(false);
141
+ const [msg,setMsg] = React.useState({ text:'', bad:false });
142
+ const [includeImg,setIncludeImg] = React.useState(true);
143
+ const [showPrev,setShowPrev] = React.useState(false);
144
+ const [proc,setProc] = React.useState({});
145
+ const [optimize,setOptimize] = React.useState(true);
146
+ const srcOf = p => (optimize && proc[p.url]) || p.data;
147
+ const photosRef = React.useRef([]);
148
+ const procRef = React.useRef({});
149
+ const optimizeRef = React.useRef(true);
150
+ React.useEffect(() => { photosRef.current = photos; procRef.current = proc; optimizeRef.current = optimize; }, [photos, proc, optimize]);
151
+ const printPhotos = () => photosRef.current.map(p => ({ name: p.name, data: (optimizeRef.current && procRef.current[p.url]) || p.data }));
152
+ const urls = React.useRef(new Set());
153
+ const key = 'question-workbench:v3:' + sessionId;
154
+ React.useEffect(() => { try { const saved = JSON.parse(localStorage.getItem(key) || '{}'); if (saved && typeof saved.text === 'string') setText(saved.text); if (saved && typeof saved.notes === 'string') setNotes(saved.notes); } catch (e) {} }, [key]);
155
+ React.useEffect(() => { try { localStorage.setItem(key, JSON.stringify({ text, notes })); } catch (e) {} }, [key, text, notes]);
156
+ React.useEffect(() => {
157
+ if (!open) return;
158
+ const onPaste = (ev) => {
159
+ const dt = ev.clipboardData; if (!dt || !dt.items) return;
160
+ const files = Array.from(dt.items)
161
+ .filter(it => it.kind === 'file' && String(it.type || '').startsWith('image/'))
162
+ .map(it => { try { return it.getAsFile(); } catch (e) { return null; } })
163
+ .filter(Boolean);
164
+ if (!files.length) return;
165
+ ev.preventDefault();
166
+ addFiles(files).catch(err => say(t.fail + String(err), true));
167
+ };
168
+ document.addEventListener('paste', onPaste);
169
+ return () => document.removeEventListener('paste', onPaste);
170
+ }, [open, photos.length, optimize]);
171
+ React.useEffect(() => () => { for (const u of urls.current) URL.revokeObjectURL(u); urls.current.clear(); }, []);
172
+ React.useEffect(() => {
173
+ if (!optimize || !photos.length) return;
174
+ const missing = photos.filter(p => !proc[p.url]);
175
+ if (!missing.length) return;
176
+ let cancelled = false;
177
+ (async () => {
178
+ const next = {};
179
+ for (const p of missing) { try { next[p.url] = await enhance(p.url); } catch (e) {} }
180
+ if (!cancelled && Object.keys(next).length) setProc(old => Object.assign({}, old, next));
181
+ })();
182
+ return () => { cancelled = true; };
183
+ }, [optimize, photos, proc]);
184
+ const sessions = ctx.get('sessions');
185
+ const binding = sessions ? sessions.binding(sessionId) : undefined;
186
+ const waitRef = React.useRef(null);
187
+ const timerRef = React.useRef(null);
188
+ const lastSeq = () => {
189
+ const w = binding && binding.eventSource ? binding.eventSource.getSnapshot() : null;
190
+ const entries = (w && w.entries) || [];
191
+ let max = 0;
192
+ for (const e of entries) { const ev = e && e.event; if (ev && typeof ev.seq === 'number' && ev.seq > max) max = ev.seq; }
193
+ return max;
194
+ };
195
+ const assistantText = (ev) => {
196
+ const content = ev && ev.data && ev.data.content;
197
+ if (!Array.isArray(content)) return '';
198
+ return content.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim();
199
+ };
200
+ const latestAssistantAfter = (since) => {
201
+ const w = binding && binding.eventSource ? binding.eventSource.getSnapshot() : null;
202
+ const entries = (w && w.entries) || [];
203
+ let best = '';
204
+ for (const e of entries) {
205
+ if (!e || e.type !== 'event') continue;
206
+ const ev = e.event;
207
+ if (!ev || ev.type !== 'assistant/message') continue;
208
+ if (typeof ev.seq === 'number' && ev.seq <= since) continue;
209
+ const text = assistantText(ev);
210
+ if (text) best = text;
211
+ }
212
+ return best;
213
+ };
214
+ React.useEffect(() => {
215
+ if (!binding || !binding.eventSource) return;
216
+ return binding.eventSource.subscribe(() => {
217
+ const w = waitRef.current;
218
+ if (!w) return;
219
+ const text = latestAssistantAfter(w.since);
220
+ if (!text) return;
221
+ waitRef.current = null;
222
+ if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
223
+ if (w.kind === 'notes') {
224
+ setNotes(text);
225
+ say(t.autoFilled);
226
+ if (w.export) setTimeout(() => exportDoc({ notes: text }), 50);
227
+ } else {
228
+ setText(text);
229
+ say(t.autoFilled);
230
+ }
231
+ });
232
+ }, [binding]);
233
+ const pending = count(text);
234
+ React.useEffect(() => () => { if (timerRef.current) clearTimeout(timerRef.current); }, []);
235
+ function say(text, bad) { setMsg({ text: text || '', bad: !!bad }); }
236
+ async function addFiles(files) {
237
+ files = Array.from(files || []);
238
+ if (!files.length) return;
239
+ if (photos.length + files.length > 12 || files.some(f => !['image/png','image/jpeg','image/webp','image/gif'].includes(f.type) || f.size > 15*1024*1024)) { say(t.limit, true); return; }
240
+ const items = await Promise.all(files.map(f => new Promise((ok, no) => { const r = new FileReader(); r.onload = () => { const u = URL.createObjectURL(f); urls.current.add(u); ok({ name: f.name || 'pasted.png', mediaType: f.type, data: String(r.result), url: u }); }; r.onerror = () => no(r.error); r.readAsDataURL(f); })));
241
+ setPhotos(old => old.concat(items)); say(t.pasted || '');
242
+ if (optimize) {
243
+ say(t.optimizing);
244
+ const next = {}; let failed = 0;
245
+ for (const it of items) { try { next[it.url] = await enhance(it.url); } catch (err) { failed++; } }
246
+ if (Object.keys(next).length) setProc(old => Object.assign({}, old, next));
247
+ say(failed ? t.optimizeFail : '');
248
+ }
249
+ }
250
+ async function addPhotos(e) {
251
+ const files = Array.from(e.target.files || []); e.target.value = '';
252
+ return addFiles(files);
253
+ }
254
+ function dropPhoto(i) { setPhotos(old => { const p = old[i]; if (p) { URL.revokeObjectURL(p.url); urls.current.delete(p.url); } return old.filter((x,j) => j !== i); }); }
255
+ async function send(prompt) {
256
+ if (!sessions) { say(t.noSession, true); return false; }
257
+ const binding = sessions.binding(sessionId);
258
+ if (!binding) { say(t.noSession, true); return false; }
259
+ setBusy(true); say('');
260
+ try {
261
+ const parts = [];
262
+ for (const p of photos) {
263
+ const blob = await (await fetch(p.url)).blob();
264
+ const b64 = await new Promise((ok, no) => { const r = new FileReader(); r.onload = () => ok(String(r.result).slice(String(r.result).indexOf(',') + 1)); r.onerror = () => no(r.error); r.readAsDataURL(blob); });
265
+ parts.push({ type: 'image', mediaType: p.mediaType, data: b64, name: p.name });
266
+ }
267
+ const res = await binding.session.prompt([{ type: 'text', text: prompt }].concat(parts), 'queue');
268
+ const ok = !!(res && res.ok);
269
+ say(ok ? t.sent : t.fail + ((res && res.error && res.error.message) || 'unknown'), !ok);
270
+ return ok;
271
+ } catch (e) { say(t.fail + String((e && e.message) || e), true); return false; } finally { setBusy(false); }
272
+ }
273
+ async function doRecognize() {
274
+ if (!photos.length) { say(t.needPhoto, true); return; }
275
+ const extra = text.trim() ? t.optional + ':\n' + text.trim() + '\n\n' : '';
276
+ const since = lastSeq();
277
+ const ok = await send(extra + t.rec);
278
+ if (!ok) return;
279
+ waitRef.current = { kind: 'text', since };
280
+ if (timerRef.current) clearTimeout(timerRef.current);
281
+ timerRef.current = setTimeout(() => { waitRef.current = null; say(t.autoFail, true); }, 180000);
282
+ say(t.waiting);
283
+ setStep(2);
284
+ }
285
+ function askPrompt(ask) { return t.src + text.trim() + '\n\n' + t.rule + ask; }
286
+ async function doAsk(ask) {
287
+ if (!text.trim()) { say(t.needText, true); return; }
288
+ const full = ask === t.askF;
289
+ const since = lastSeq();
290
+ const ok = await send(askPrompt(ask));
291
+ if (!ok) return;
292
+ waitRef.current = { kind: 'notes', since, export: full };
293
+ if (timerRef.current) clearTimeout(timerRef.current);
294
+ timerRef.current = setTimeout(() => { waitRef.current = null; say(t.autoFail, true); }, 300000);
295
+ say(t.waiting);
296
+ }
297
+ async function copyPrompt(ask) { try { await navigator.clipboard.writeText(askPrompt(ask)); say(t.copied); } catch (e) { say(t.copyFail, true); } }
298
+ function exportDoc(override) {
299
+ try {
300
+ const docText = override && typeof override.text === 'string' ? override.text : text;
301
+ const docNotes = override && typeof override.notes === 'string' ? override.notes : notes;
302
+ const blob = new Blob([printDoc(t, { text: docText, notes: docNotes, photos: printPhotos(), images: includeImg })], { type: 'text/html;charset=utf-8' });
303
+ const url = URL.createObjectURL(blob);
304
+ const a = document.createElement('a');
305
+ a.href = url; a.download = t.title + '.html';
306
+ document.body.appendChild(a); a.click(); a.remove();
307
+ setTimeout(() => URL.revokeObjectURL(url), 10000);
308
+ say(t.exportHint);
309
+ } catch (e) { say(t.exportFail + String((e && e.message) || e), true); }
310
+ }
311
+ function doPrint() {
312
+ let frame;
313
+ try {
314
+ frame = document.createElement('iframe');
315
+ frame.setAttribute('aria-hidden', 'true');
316
+ frame.setAttribute('title', t.title);
317
+ frame.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;';
318
+ document.body.appendChild(frame);
319
+ const doc = frame.contentDocument;
320
+ doc.open(); doc.write(printDoc(t, { text, notes, photos: printPhotos(), images: includeImg })); doc.close();
321
+ } catch (e) { if (frame) frame.remove(); say(t.printFail, true); return; }
322
+ setTimeout(() => {
323
+ try { frame.contentWindow.focus(); frame.contentWindow.print(); say(t.printHint); } catch (e) { say(t.printFail, true); }
324
+ setTimeout(() => { try { frame.remove(); } catch (e) {} }, 60000);
325
+ }, 500);
326
+ }
327
+ function go(n) {
328
+ if (n === 1) { setStep(1); return; }
329
+ setStep(2);
330
+ }
331
+ async function pasteClipboard() {
332
+ try {
333
+ const s = await navigator.clipboard.readText();
334
+ if (!s || !s.trim()) { say(t.needText, true); return; }
335
+ setText(s); say('');
336
+ } catch (e) { say(t.pasteFail, true); }
337
+ }
338
+ const stepBar = h('div',{className:'qwb-steps'},[[1,t.s1],[2,t.s2]].map(([n,label]) => h('button',{key:n,type:'button',className:'qwb-step' + (step === n ? ' on' : (step > n ? ' done' : '')),'aria-current': step === n ? 'step' : undefined,onClick:() => go(n)}, label)));
339
+ const msgLine = msg.text ? h('p',{className:'qwb-msg' + (msg.bad ? ' bad' : ''),role:'status'},msg.text) : null;
340
+ const thumbs = h('div',{className:'qwb-thumbs'},photos.map((p,i) => h('div',{className:'qwb-th',key:p.url},h('img',{src:p.url,alt:p.name}),h('button',{type:'button',title:'×',onClick:() => dropPhoto(i)},'×'))));
341
+ const asks = [[t.analysis,t.askA],[t.solve,t.askS],[t.summary,t.askM],[t.all,t.askF]];
342
+ let body;
343
+ if (step === 1) body = h(React.Fragment,null,
344
+ h('div',{className:'qwb-row'},h('label',{className:'qwb-up'},t.pick,h('input',{type:'file',multiple:true,accept:'image/png,image/jpeg,image/webp,image/gif',onChange:e => { addPhotos(e).catch(err => say(t.fail + String(err), true)); }})),h('span',{className:'qwb-msg'},t.limit)),
345
+ thumbs,
346
+ h('label',null,t.optional),h('textarea',{className:'sm',value:text,placeholder:t.placeholder,onChange:e => setText(e.target.value)}),
347
+ h('p',{className:'qwb-msg'},t.hint1),
348
+ h('div',{className:'qwb-row'},h('button',{type:'button',disabled:busy || !photos.length,onClick:doRecognize},busy ? t.sending : t.recognize),h('button',{type:'button',onClick:() => go(2)},t.toCheck + ' →'),msgLine)
349
+ );
350
+ if (step === 2) body = h(React.Fragment,null,
351
+ h('p',{className:'qwb-msg'},t.pasteWait),
352
+ h('div',{className:'qwb-row'},h('button',{type:'button',onClick:pasteClipboard},t.pasteClipboard),h('button',{type:'button',onClick:() => go(1)},t.back)),
353
+ h('textarea',{value:text,placeholder:t.placeholder,onChange:e => { setText(e.target.value); setChecked(false); }}),
354
+ h('label',null,t.notesLabel),h('textarea',{value:notes,placeholder:t.notesPlaceholder,onChange:e => setNotes(e.target.value)}),
355
+ pending ? h('p',{className:'qwb-bad',role:'alert'},t.pending + pending) : null,
356
+ text ? h('div',{className:'qwb-v'},frags(text)) : null,
357
+ h('p',{className:'qwb-msg'},t.saved + ' ' + t.diagramNote),
358
+ h('div',{className:'qwb-row'},asks.map(([label,ask]) => h('button',{type:'button',key:label,disabled:busy || !text.trim(),onClick:() => doAsk(ask)},label))),
359
+ h('div',{className:'qwb-row'},h('label',null,h('input',{type:'checkbox',checked:optimize,onChange:e => setOptimize(e.target.checked)}),t.optimize),h('label',null,h('input',{type:'checkbox',checked:includeImg,onChange:e => setIncludeImg(e.target.checked)}),t.includeImg),h('button',{type:'button','aria-expanded':showPrev,onClick:() => setShowPrev(!showPrev)},showPrev ? t.hidePreview : t.preview),h('button',{type:'button',onClick:exportDoc},t.exportHtml),h('button',{type:'button',onClick:doPrint},t.print)),
360
+ showPrev ? h('div',{className:'qwb-sheet'},h('h4',null,t.title),h('div',{className:'qwb-v'},frags(text)),notes.trim() ? h('div',null,h('h4',null,t.notesLabel),h('div',{className:'qwb-v'},frags(notes))) : null,includeImg ? photos.map((p,i) => h('img',{className:'qwb-pg',key:p.url,src:srcOf(p),alt:p.name})) : null) : null,
361
+ h('details',{className:'qwb-details'},h('summary',null,t.showPrompt),h('pre',null,askPrompt(t.askF)),h('div',{className:'qwb-row'},h('button',{type:'button',onClick:() => copyPrompt(t.askF)},t.copy))),
362
+ msgLine
363
+ );
364
+ const panel = h('section',{className:'qwb','aria-label':t.title},
365
+ h('style',null,css),
366
+ h('div',{className:'qwb-row qwb-head'},h('b',null,t.title),h('span',{className:'qwb-row'},h('button',{type:'button',onClick:() => { setStep(1); setPhotos([]); setText(''); setChecked(false); say(''); }},t.reset),h('button',{type:'button',onClick:() => setOpen(false)},t.close))),
367
+ stepBar, body
368
+ );
369
+ return h(React.Fragment,null,
370
+ open ? panel : h('button',{type:'button',className:'qwb-launch',onClick:() => setOpen(true)},'▧ ' + t.open)
371
+ );
372
+ }
373
+ return { inject:['slots','locale'], apply(ctx) {
374
+ ctx.slots.inject('conversation.input.dock', () => ctx.slots.register({ name:'conversation.input.dock', id:'question-workbench', order:35, label:() => useTLabel(ctx) }, function DockEntry(props) { const t = useT(ctx); return h(Bench,{ctx,t,sessionId:props.sessionId}); }));
375
+ } };
376
+ function useTLabel(ctx) { return dict[String(ctx.locale.getLocale().active||'').toLowerCase().startsWith('zh') ? 'zh' : 'en'].title; }
377
+ }
378
+ });
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: question-workbench
3
+ name: 'question-workbench-mcp'
4
+ disabled: false
package/icon.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="10" y="6" width="44" height="52" rx="7" fill="#246ba5"/><path d="M20 19h24M20 28h16M20 40h10m9 0h7M35 35v12" stroke="#fff" stroke-width="3" stroke-linecap="round"/><circle cx="43" cy="43" r="10" fill="none" stroke="#fff" stroke-width="2"/></svg>
package/index.js ADDED
@@ -0,0 +1,132 @@
1
+ /** Host half: the Client owns the worksheet UI; the Host also exposes the workbook as agent tools. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const PROMPTS = {
6
+ zh: {
7
+ recognition: '只做识别,严格按三段输出,不要解释或额外分节,总字数≤300字:\n【题目】逐字转录印刷文字,保留题号、选项、符号和公式;看不清写[待核实:简短原因],不要猜。\n【图形】每张图一行,≤25字,只写可见关键元素,例如:图1 三角形ABC,P在内部,BM、CN交于P。\n【待确认】最多3条、每条≤15字;没有写“无”。',
8
+ analysis: '以下内容已由用户对照原图人工核对,直接作为已知条件使用;不要重新质疑,也不要补充未确认的关系。\n\n已核对题目:\n{text}\n\n只给思路,不要完整计算:①考点1行 ②关键思路3-5步。≤200字。',
9
+ solution: '以下内容已由用户对照原图人工核对,直接作为已知条件使用;不要重新质疑,也不要补充未确认的关系。\n\n已核对题目:\n{text}\n\n给完整解题过程:分步推导+最终答案,公式简洁。≤400字。',
10
+ summary: '以下内容已由用户对照原图人工核对,直接作为已知条件使用;不要重新质疑,也不要补充未确认的关系。\n\n已核对题目:\n{text}\n\n只总结:3-5条知识点与易错点,每条一行。≤150字。',
11
+ full: '以下内容已由用户对照原图人工核对,直接作为已知条件使用;不要重新质疑,也不要补充未确认的关系。\n\n已核对题目:\n{text}\n\n先给3-5步思路,再给完整解答和最终答案,最后1-2句易错点提醒;不重复题目。≤600字。',
12
+ worksheetTitle: '题目讲义',
13
+ solutionLabel: '解答'
14
+ },
15
+ en: {
16
+ recognition: 'Transcribe only. Output exactly three sections, no extra explanation, ≤300 words:\n[Question] literal printed text, keeping numbering, symbols and formulas; write [verify: short reason] instead of guessing.\n[Diagram] one line per figure, ≤25 words, only visible key elements, e.g. Fig.1 triangle ABC, P inside, BM and CN meet at P.\n[Checks] at most 3 items, ≤15 words each; write "none" if none.',
17
+ analysis: 'The user checked the following against the photos; use it as given. Do not re-question it or add unconfirmed relations.\n\nChecked question:\n{text}\n\nReasoning only: 1 line of key concepts, then 3-5 steps. ≤200 words.',
18
+ solution: 'The user checked the following against the photos; use it as given. Do not re-question it or add unconfirmed relations.\n\nChecked question:\n{text}\n\nFull solution: step-by-step work and final answer, concise formulas. ≤400 words.',
19
+ summary: 'The user checked the following against the photos; use it as given. Do not re-question it or add unconfirmed relations.\n\nChecked question:\n{text}\n\nKey points only: 3-5 lines of concepts and common mistakes. ≤150 words.',
20
+ full: 'The user checked the following against the photos; use it as given. Do not re-question it or add unconfirmed relations.\n\nChecked question:\n{text}\n\nGive 3-5 reasoning steps, then the full solution and answer, then 1-2 lines of pitfalls; do not restate the question. ≤600 words.',
21
+ worksheetTitle: 'Question worksheet',
22
+ solutionLabel: 'Solution'
23
+ }
24
+ };
25
+
26
+ const MODES = ['recognition', 'analysis', 'solution', 'summary', 'full'];
27
+ const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
28
+
29
+ const escape = (v) => String(v).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
30
+ const marker = /([待核实[^]\n]{0,160}]|\[verify[^\]\n]{0,160}\])/gi;
31
+ const marked = (v) => escape(v).replace(marker, '<b class="bad">$1</b>');
32
+ const stripChecks = (v) => String(v)
33
+ .replace(/(?:^|\n)\s*【(?:待确认|待核实)】[\s\S]*?(?=\n\s*【|$)/g, '')
34
+ .replace(/(?:^|\n)\s*\[(?:Checks|Items to verify)\][\s\S]*?(?=\n\s*\[|$)/gi, '')
35
+ .replace(/\n{3,}/g, '\n\n')
36
+ .trim();
37
+
38
+ export function buildPrompt(mode, text, language) {
39
+ if (!MODES.includes(mode)) throw new Error(`mode must be one of: ${MODES.join(', ')}`);
40
+ const lang = language === 'en' ? 'en' : 'zh';
41
+ const body = text && String(text).trim();
42
+ if (mode !== 'recognition' && !body) throw new Error('text is required for mode ' + mode);
43
+ return PROMPTS[lang][mode].replace('{text}', body || '');
44
+ }
45
+
46
+ export function buildWorksheet(options = {}) {
47
+ const lang = options.language === 'en' ? 'en' : 'zh';
48
+ const t = PROMPTS[lang];
49
+ const title = options.title && String(options.title).trim() ? String(options.title).trim() : t.worksheetTitle;
50
+ const text = options.skipChecks === false ? String(options.text || '') : stripChecks(options.text || '');
51
+ const figures = (Array.isArray(options.images) ? options.images : []).map((file) => {
52
+ const p = path.resolve(file);
53
+ const ext = path.extname(p).toLowerCase();
54
+ if (!MIME[ext]) throw new Error('unsupported image type: ' + p);
55
+ return { name: path.basename(p), data: `data:${MIME[ext]};base64,${fs.readFileSync(p).toString('base64')}` };
56
+ });
57
+ const lines = (v) => marked(v).split('\n').map((l) => `<div>${l || '&nbsp;'}</div>`).join('');
58
+ const html = '<!doctype html><html><head><meta charset="utf-8"><title>' + escape(title) + '</title>'
59
+ + '<style>@page{size:A4;margin:16mm}body{font:12pt/1.7 system-ui,sans-serif;color:#161616}h1{font-size:18pt}h2{font-size:13pt;margin-top:16px;border-bottom:1px solid #999}section{white-space:pre-wrap;overflow-wrap:anywhere}figure{break-inside:avoid;margin:14px 0}figure img{max-width:100%;max-height:235mm;object-fit:contain}figcaption{font-size:9pt;color:#666}.bad{color:#b42318;background:#fff0ec}</style></head><body>'
60
+ + '<h1>' + escape(title) + '</h1>'
61
+ + (options.grade ? '<p>' + escape(options.grade) + '</p>' : '')
62
+ + '<section>' + lines(text) + '</section>'
63
+ + figures.map((f) => '<figure><img src="' + f.data + '" alt="' + escape(f.name) + '"><figcaption>' + escape(f.name) + '</figcaption></figure>').join('')
64
+ + (options.notes ? '<h2>' + escape(t.solutionLabel) + '</h2><section>' + lines(options.notes) + '</section>' : '')
65
+ + '</body></html>';
66
+ const target = options.outputPath
67
+ ? path.resolve(options.outputPath)
68
+ : path.join(process.cwd(), `question-worksheet-${Date.now()}.html`);
69
+ if (path.extname(target).toLowerCase() !== '.html') throw new Error('outputPath must end with .html');
70
+ const dir = path.dirname(target);
71
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
72
+ fs.writeFileSync(target, html, 'utf8');
73
+ return { path: target, bytes: Buffer.byteLength(html), images: figures.length };
74
+ }
75
+
76
+ const textRender = (args, value) => [{ type: 'text', text: String(value && value.text || '') }];
77
+
78
+ export const inject = ['tools'];
79
+
80
+ export function apply(ctx) {
81
+ ctx.effect(() => ctx.tools.register({
82
+ name: 'question_workbench_prompt',
83
+ description: '题目工作台提示词:recognition 生成三段式识图提示;analysis/solution/summary/full 基于已核对题目生成思路/解题/总结/全流程提示,再由模型按该提示作答。',
84
+ parameters: {
85
+ type: 'object',
86
+ additionalProperties: false,
87
+ properties: {
88
+ mode: { type: 'string', enum: MODES, description: '要生成的提示类型。' },
89
+ text: { type: 'string', description: '已人工核对的题目全文;除 recognition 外必填。' },
90
+ language: { type: 'string', enum: ['zh', 'en'], description: '提示语言,默认 zh。' }
91
+ },
92
+ required: ['mode']
93
+ },
94
+ output: {
95
+ schema: { type: 'object', properties: { text: { type: 'string' }, mode: { type: 'string' } }, required: ['text', 'mode'] },
96
+ render: textRender
97
+ },
98
+ async execute(args) {
99
+ const prompt = buildPrompt(args.mode, args.text, args.language);
100
+ return { text: prompt, mode: args.mode };
101
+ }
102
+ }));
103
+
104
+ ctx.effect(() => ctx.tools.register({
105
+ name: 'question_workbench_worksheet',
106
+ description: '把题目与解答生成 A4 讲义 HTML 并写入文件,返回绝对路径;可用浏览器打开后 Ctrl+P 预览分页并打印。默认跳过【待确认】段。',
107
+ parameters: {
108
+ type: 'object',
109
+ additionalProperties: false,
110
+ properties: {
111
+ text: { type: 'string', description: '题目文字(可含已核对的三段式识别结果)。' },
112
+ notes: { type: 'string', description: '可选:思路、解答或总结,打印在题目之后。' },
113
+ title: { type: 'string', description: '讲义标题,默认“题目讲义”。' },
114
+ grade: { type: 'string', description: '可选:学科/年级行。' },
115
+ images: { type: 'array', items: { type: 'string' }, description: '可选:本地图片绝对路径(png/jpg/jpeg/webp/gif),嵌入讲义。' },
116
+ outputPath: { type: 'string', description: '输出 .html 路径,默认为当前工作目录。' },
117
+ skipChecks: { type: 'boolean', description: '是否删除【待确认】整段,默认 true。' },
118
+ language: { type: 'string', enum: ['zh', 'en'], description: '讲义语言,默认 zh。' }
119
+ },
120
+ required: ['text']
121
+ },
122
+ output: {
123
+ schema: { type: 'object', properties: { text: { type: 'string' }, path: { type: 'string' }, bytes: { type: 'integer' } }, required: ['text', 'path'] },
124
+ render: textRender
125
+ },
126
+ async execute(args) {
127
+ const out = buildWorksheet(args);
128
+ const message = `Worksheet written: ${out.path} (${out.bytes} bytes, ${out.images} image(s))`;
129
+ return { text: message, ...out };
130
+ }
131
+ }));
132
+ }
package/locale/en.json ADDED
@@ -0,0 +1 @@
1
+ {"meta":{"title":"Question workbench","description":"Question photo recognition, three-step checking, reasoning/solutions and A4 worksheet printing; the same package also ships MCP tools (question-workbench-mcp)."}}
package/locale/zh.json ADDED
@@ -0,0 +1 @@
1
+ {"meta":{"title":"题目工作台","description":"题目图片识别、三步核对、思路/解题/总结与 A4 讲义打印;同一包也提供 MCP 工具(question-workbench-mcp)。"}}
package/package.json CHANGED
@@ -1,11 +1,34 @@
1
1
  {
2
2
  "name": "question-workbench-mcp",
3
- "version": "0.2.1",
4
- "description": "MCP server for the question-workbench flow: structured recognition/solution prompts and A4 worksheet HTML generation, usable from Codex, WorkBuddy and any MCP-capable agent.",
3
+ "version": "0.3.3",
4
+ "description": "Question workbench: photos in, checked text, reasoning or solutions, A4 worksheet out. One package, two installs: a DeepSeek Harness bundle (UI + agent tools) and an MCP stdio server for Codex, WorkBuddy and other MCP clients.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
+ "keywords": ["dsh", "dsh-plugin", "deepseek-harness", "mcp", "worksheet", "print", "education"],
7
8
  "bin": { "question-workbench-mcp": "./server.js" },
8
- "files": ["server.js", "README.md", "LICENSE", "codex-config.example.toml", "mcp-config.example.json", "workbuddy-mcp.example.json"],
9
- "keywords": ["mcp", "question", "worksheet", "print", "education"],
10
- "engines": { "node": ">=18" }
9
+ "exports": {
10
+ ".": "./index.js",
11
+ "./client": "./client.js",
12
+ "./server": "./server.js",
13
+ "./locale/*.json": "./locale/*.json",
14
+ "./icon": "./icon.svg"
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "client.js",
19
+ "server.js",
20
+ "cordis.patch.yml",
21
+ "locale/*.json",
22
+ "icon.svg",
23
+ "README.md",
24
+ "LICENSE",
25
+ "codex-config.example.toml",
26
+ "mcp-config.example.json",
27
+ "workbuddy-mcp.example.json"
28
+ ],
29
+ "engines": { "node": ">=18" },
30
+ "dsh": {
31
+ "bundle": { "patch": "./cordis.patch.yml" },
32
+ "client": { "platform": "web", "immediately": true, "inject": ["@deepseek-ai/dsh-client-ui-conversation"] }
33
+ }
11
34
  }
package/server.js CHANGED
@@ -154,7 +154,8 @@ function callTool(name, args = {}) {
154
154
  ? path.resolve(args.outputPath)
155
155
  : path.join(process.cwd(), `question-worksheet-${Date.now()}.html`);
156
156
  if (path.extname(target).toLowerCase() !== '.html') throw new Error('outputPath must end with .html');
157
- fs.mkdirSync(path.dirname(target), { recursive: true });
157
+ const dir = path.dirname(target);
158
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
158
159
  fs.writeFileSync(target, html, 'utf8');
159
160
  const names = images.map((i) => i.name).join(', ');
160
161
  return `Worksheet written: ${target} (${Buffer.byteLength(html)} bytes, ${images.length} image(s)${names ? ': ' + names : ''}${args.skipChecks === false ? '' : ', 待确认 section skipped'})`;