dsh-learning-assistant 0.0.1 → 0.1.0

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.
Files changed (69) hide show
  1. package/README.md +41 -7
  2. package/assets/collect/README.md +55 -0
  3. package/assets/skills/course-inbox-sync.md +182 -0
  4. package/assets/skills/course-material-digest.md +173 -0
  5. package/assets/skills/one-to-one-tutor.md +320 -0
  6. package/assets/tools/pdf/pdf-render.ps1 +30 -0
  7. package/assets/tools/pptx-digest.py +99 -0
  8. package/assets/tools/pptx-map.py +98 -0
  9. package/assets/tools/pptx-media.py +101 -0
  10. package/assets/tools/qq-group-msg.py +258 -0
  11. package/assets/tools/qq-group-sync.py +265 -0
  12. package/docs//345/215/217/344/275/234/345/274/200/345/217/221.md +18 -10
  13. package/lib/client.js +110 -0
  14. package/lib/{index.d.mts → index.d.ts} +3 -1
  15. package/lib/index.js +392 -0
  16. package/package.json +8 -7
  17. package/src/client/settings.tsx +6 -4
  18. package/src/index.ts +36 -11
  19. package/src/practice/learn/api.mjs +393 -0
  20. package/src/practice/learn/cli.mjs +175 -0
  21. package/src/practice/learn/curriculum.mjs +292 -0
  22. package/src/practice/learn/handoff.mjs +73 -0
  23. package/src/practice/learn/jsonschema.mjs +171 -0
  24. package/src/practice/learn/mapping.mjs +90 -0
  25. package/src/practice/learn/progress.mjs +247 -0
  26. package/src/practice/learn/schema/curriculum.schema.json +88 -0
  27. package/src/practice/learn/schema/handoff.schema.json +56 -0
  28. package/src/practice/learn/schema/node-practice-map.schema.json +28 -0
  29. package/src/practice/learn/schema/progress.schema.json +66 -0
  30. package/src/practice/learn/schemas.mjs +53 -0
  31. package/src/practice/learn/store.mjs +247 -0
  32. package/src/practice/public/app.js +883 -0
  33. package/src/practice/public/index.html +19 -0
  34. package/src/practice/public/ink.js +349 -0
  35. package/src/practice/public/learn.css +20 -0
  36. package/src/practice/public/learn.js +329 -0
  37. package/src/practice/public/style.css +326 -0
  38. package/src/practice/public/vendor/katex/contrib/auto-render.min.js +1 -0
  39. package/src/practice/public/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  40. package/src/practice/public/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  41. package/src/practice/public/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  42. package/src/practice/public/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  43. package/src/practice/public/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  44. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
  45. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  46. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
  47. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
  48. package/src/practice/public/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  49. package/src/practice/public/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
  50. package/src/practice/public/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  51. package/src/practice/public/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  52. package/src/practice/public/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  53. package/src/practice/public/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
  54. package/src/practice/public/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  55. package/src/practice/public/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  56. package/src/practice/public/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  57. package/src/practice/public/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  58. package/src/practice/public/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  59. package/src/practice/public/vendor/katex/katex.min.css +1 -0
  60. package/src/practice/public/vendor/katex/katex.min.js +1 -0
  61. package/src/practice//346/234/215/345/212/241.mjs +443 -0
  62. package/src/practice//346/240/241/351/252/214/351/242/230/347/233/256.mjs +114 -0
  63. package/src/practice//347/255/211/345/276/205/346/217/220/344/272/244.mjs +100 -0
  64. package/src/practice-service.ts +99 -0
  65. package/src/practice-tool.ts +91 -0
  66. package/src/skills.ts +156 -0
  67. package/lib/client.d.mts +0 -10
  68. package/lib/client.mjs +0 -87
  69. package/lib/index.mjs +0 -29
@@ -0,0 +1,443 @@
1
+ // 练习台本地服务:静态页 + 题库 API + 提交写回 + 学习助手 /api/learn/*。
2
+ //
3
+ // 插件参数化版:与学习区原版的差别只有目录来源——
4
+ // <dataRoot>/练习台/{_题库,_记录,_笔迹,_收件箱} + <dataRoot>/学习助手数据
5
+ // dataRoot 解析优先级:--data-root 参数 > LEARN_DATA_BASE > 脚本所在目录(传统布局)。
6
+ // 端口:argv[1] > PRACTICE_PORT > 18800。
7
+ //
8
+ // 用法:node 服务.mjs [端口] [--data-root <目录>]
9
+ // 只监听 127.0.0.1,不对外。
10
+ import http from 'node:http';
11
+ import fs from 'node:fs';
12
+ import fsp from 'node:fs/promises';
13
+ import path from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ // 学习助手扩展(课程计划/进度/交接记录)。只追加 /api/learn/* 路由,
16
+ // 不改变本文件既有的题库、提交、收件箱行为。
17
+ import { handleLearnApi } from './learn/api.mjs';
18
+
19
+ const argv = process.argv.slice(2);
20
+
21
+ // ---- 目录解析 ----
22
+ function parseDataRoot() {
23
+ const i = argv.indexOf('--data-root');
24
+ if (i >= 0 && argv[i + 1]) return path.resolve(argv[i + 1]);
25
+ if (process.env.LEARN_DATA_BASE && path.isAbsolute(process.env.LEARN_DATA_BASE)) {
26
+ return path.resolve(process.env.LEARN_DATA_BASE);
27
+ }
28
+ // 传统布局:脚本住在 <工作区>/练习台/,工作区根即数据基目录
29
+ return path.dirname(path.dirname(fileURLToPath(import.meta.url)));
30
+ }
31
+ const BASE = parseDataRoot();
32
+
33
+ // 环境注入(供 learn/store.mjs 等模块读到与主服务一致的根)
34
+ process.env.LEARN_WORKSPACE = process.env.LEARN_WORKSPACE || BASE;
35
+ process.env.LEARN_PRACTICE_DIR = process.env.LEARN_PRACTICE_DIR || path.join(BASE, '练习台');
36
+
37
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
38
+ const PUBLIC = path.join(HERE, 'public');
39
+ const BANK = path.join(BASE, '练习台', '_题库');
40
+ const RECORDS = path.join(BASE, '练习台', '_记录');
41
+ const INBOX = path.join(BASE, '练习台', '_收件箱');
42
+ // 手写笔迹(填空/大题)一题一图落在这里。与 _记录 并列:
43
+ // _记录/<科目>/<练习>__<时间>.json 答卷(含每题 ink 路径与批改结果)
44
+ // _笔迹/<科目>/<练习>__<题号>__<时间>.png 该题的墨迹图,智能体直接读
45
+ const INK = path.join(BASE, '练习台', '_笔迹');
46
+ const PORT = Number(argv[0] && /^\d+$/.test(argv[0]) ? argv[0] : '') || Number(process.env.PRACTICE_PORT) || 18800;
47
+ const HOST = '127.0.0.1';
48
+
49
+ const MIME = {
50
+ '.html': 'text/html; charset=utf-8',
51
+ '.js': 'text/javascript; charset=utf-8',
52
+ '.mjs': 'text/javascript; charset=utf-8',
53
+ '.css': 'text/css; charset=utf-8',
54
+ '.json': 'application/json; charset=utf-8',
55
+ '.woff2': 'font/woff2',
56
+ '.woff': 'font/woff',
57
+ '.svg': 'image/svg+xml',
58
+ '.png': 'image/png',
59
+ '.ico': 'image/x-icon',
60
+ };
61
+
62
+ // 笔迹图片上限(解码后字节)。1400px 宽的手写 PNG 一般 60–250KB,
63
+ // 给到 6MB 是为了容纳「写得特别满」的大题,同时挡住误传的超大文件。
64
+ const INK_MAX_BYTES = 6 * 1024 * 1024;
65
+
66
+ const safe = (s) => String(s || '').replace(/[\\/:*?"<>|]/g, '_').slice(0, 80);
67
+
68
+ function json(res, code, obj) {
69
+ const body = JSON.stringify(obj);
70
+ res.writeHead(code, {
71
+ 'content-type': 'application/json; charset=utf-8',
72
+ 'cache-control': 'no-store',
73
+ });
74
+ res.end(body);
75
+ }
76
+
77
+ async function readBody(req, limit = 2 * 1024 * 1024) {
78
+ const chunks = [];
79
+ let n = 0;
80
+ for await (const c of req) {
81
+ n += c.length;
82
+ if (n > limit) throw new Error('body too large');
83
+ chunks.push(c);
84
+ }
85
+ return Buffer.concat(chunks).toString('utf8');
86
+ }
87
+
88
+ async function listDir(p) {
89
+ try { return await fsp.readdir(p, { withFileTypes: true }); } catch { return []; }
90
+ }
91
+
92
+ // 题库:_题库/<科目>/<练习>.json
93
+ async function library() {
94
+ const out = [];
95
+ for (const courseEnt of await listDir(BANK)) {
96
+ if (!courseEnt.isDirectory()) continue;
97
+ const course = courseEnt.name;
98
+ for (const f of await listDir(path.join(BANK, course))) {
99
+ if (!f.isFile() || !f.name.endsWith('.json')) continue;
100
+ const id = f.name.replace(/\.json$/, '');
101
+ let meta = {};
102
+ try {
103
+ meta = JSON.parse(await fsp.readFile(path.join(BANK, course, f.name), 'utf8'));
104
+ } catch { meta = {}; }
105
+ const recs = await recordsFor(course, id);
106
+ out.push({
107
+ course,
108
+ id,
109
+ title: meta.title || id,
110
+ topic: meta.topic || '',
111
+ source: meta.source || '',
112
+ count: (meta.questions || []).length,
113
+ attempts: recs.length,
114
+ best: recs.length ? Math.max(...recs.map((r) => r.rate || 0)) : null,
115
+ lastAt: recs.length ? recs[0].at : null,
116
+ });
117
+ }
118
+ }
119
+ out.sort((a, b) => (a.course === b.course ? a.id.localeCompare(b.id) : a.course.localeCompare(b.course)));
120
+ return out;
121
+ }
122
+
123
+ async function recordsFor(course, id) {
124
+ const dir = path.join(RECORDS, safe(course));
125
+ const out = [];
126
+ for (const f of await listDir(dir)) {
127
+ if (!f.isFile() || !f.name.startsWith(safe(id) + '__') || !f.name.endsWith('.json')) continue;
128
+ try {
129
+ const r = JSON.parse(await fsp.readFile(path.join(dir, f.name), 'utf8'));
130
+ out.push({ file: f.name, ...r });
131
+ } catch { /* 跳过坏文件 */ }
132
+ }
133
+ out.sort((a, b) => String(b.at).localeCompare(String(a.at)));
134
+ return out;
135
+ }
136
+
137
+ const stamp = () => {
138
+ const d = new Date();
139
+ const p = (n) => String(n).padStart(2, '0');
140
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
141
+ };
142
+
143
+ async function submit(payload) {
144
+ const course = safe(payload.course) || '未分类';
145
+ const id = safe(payload.practiceId) || 'practice';
146
+ const answers = Array.isArray(payload.answers) ? payload.answers : [];
147
+ const at = new Date().toISOString();
148
+ // 判分只对选择题有意义;填空/大题由智能体看笔迹图后批改,所以不计入 right。
149
+ // 注意:老客户端提交的答案没有 kind 字段,必须按 choice 处理(否则右分会被算成 0)。
150
+ const isChoice = (a) => !!a && (a.kind == null || a.kind === 'choice');
151
+ const auto = answers.filter(isChoice);
152
+ const right = auto.filter((a) => a && a.ok === true).length;
153
+ const rec = {
154
+ at,
155
+ course,
156
+ practiceId: id,
157
+ practiceTitle: payload.practiceTitle || id,
158
+ topic: payload.topic || '',
159
+ total: answers.length,
160
+ // 自动判分只覆盖选择题。填空题/大题写了笔迹但还没批改,
161
+ // 所以 rate 用 autoTotal 当分母,避免把「未批改」算成「错」。
162
+ right,
163
+ autoTotal: auto.length,
164
+ rate: auto.length ? right / auto.length : 0,
165
+ elapsedMs: Number(payload.elapsedMs) || 0,
166
+ wrong: auto.filter((a) => a && a.ok !== true).map((a) => a.id),
167
+ // 「不知道」单独列出来:它不是答错,是没学到,批改时该当缺口讲,不该当误区纠正。
168
+ dunno: answers.filter((a) => a && a.dunno === true).map((a) => a.id),
169
+ // 用户在「不知道」旁写下的具体卡点(可选)。批改时直接照着讲,不用再猜。
170
+ unclear: answers.filter((a) => a && a.dunno === true && String(a.note || '').trim())
171
+ .map((a) => ({ id: a.id, note: String(a.note).trim() })),
172
+ // 待批改的手写题:智能体读这些 ink 图片后回填 verdict(见 /api/grade)
173
+ pending: answers.filter((a) => !isChoice(a) && a.ink).map((a) => a.id),
174
+ answers: answers.map((a) => ({
175
+ id: a.id,
176
+ // 缺省 kind 视为 choice:老题库/老客户端没有这个字段
177
+ kind: !isChoice(a) ? (a.kind || 'fill') : 'choice',
178
+ header: a.header || '', stem: a.stem || '',
179
+ chosen: a.chosen || '', chosenText: a.chosenText || '',
180
+ // 手写题:ink 是相对数据基目录的笔迹图路径,typed 是用户在图上补打的文字(可空)
181
+ ink: a.ink || '', typed: String(a.typed || ''),
182
+ dunno: a.dunno === true,
183
+ note: a.dunno === true ? String(a.note || '').trim() : '',
184
+ answer: a.answer || '', ok: a.ok === true,
185
+ // 由 /api/grade 回填:'right' | 'partial' | 'wrong' | ''(未批)
186
+ verdict: a.verdict || '',
187
+ })),
188
+ };
189
+ await fsp.mkdir(path.join(RECORDS, course), { recursive: true });
190
+ await fsp.mkdir(INBOX, { recursive: true });
191
+ const name = `${id}__${stamp()}.json`;
192
+ await fsp.writeFile(path.join(RECORDS, course, name), JSON.stringify(rec, null, 2), 'utf8');
193
+ const line = JSON.stringify({
194
+ at, course, practiceId: id, practiceTitle: rec.practiceTitle,
195
+ score: `${right}/${answers.length}`, wrong: rec.wrong, dunno: rec.dunno, unclear: rec.unclear,
196
+ pending: rec.pending,
197
+ record: `练习台/_记录/${course}/${name}`,
198
+ });
199
+ await fsp.appendFile(path.join(INBOX, '待处理.jsonl'), line + '\n', 'utf8');
200
+ return {
201
+ ok: true,
202
+ record: `练习台/_记录/${course}/${name}`,
203
+ right, total: answers.length,
204
+ autoTotal: auto.length, pending: rec.pending,
205
+ };
206
+ }
207
+
208
+ /* ---------- 手写笔迹:落盘 / 回读 / 批改回填 ---------- */
209
+
210
+ // 把 dataURL 或裸 base64 存成 PNG,返回相对数据基目录的路径。
211
+ async function saveInk(payload) {
212
+ const course = safe(payload.course) || '未分类';
213
+ const practiceId = safe(payload.practiceId) || 'practice';
214
+ const qid = safe(payload.qid) || 'q';
215
+ let b64 = String(payload.dataUrl || payload.png || '');
216
+ const m = /^data:image\/png;base64,/.exec(b64);
217
+ if (m) b64 = b64.slice(m[0].length);
218
+ if (!b64) throw Object.assign(new Error('缺 dataUrl'), { code: 400 });
219
+ let buf;
220
+ try { buf = Buffer.from(b64, 'base64'); }
221
+ catch { throw Object.assign(new Error('base64 解码失败'), { code: 400 }); }
222
+ if (!buf.length) throw Object.assign(new Error('图片是空的'), { code: 400 });
223
+ if (buf.length > INK_MAX_BYTES) throw Object.assign(new Error(`图片 ${buf.length} 字节,超过上限`), { code: 413 });
224
+ // PNG 魔数校验:挡住把别的东西当图片传进来
225
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
226
+ if (!buf.subarray(0, 8).equals(PNG_SIG)) throw Object.assign(new Error('不是 PNG'), { code: 415 });
227
+
228
+ const dir = path.join(INK, course);
229
+ await fsp.mkdir(dir, { recursive: true });
230
+ const name = `${practiceId}__${qid}__${stamp()}.png`;
231
+ await fsp.writeFile(path.join(dir, name), buf);
232
+ return { path: `练习台/_笔迹/${course}/${name}`, bytes: buf.length };
233
+ }
234
+
235
+ // 批改回填:把智能体对每道手写题的判定写回答卷。
236
+ // payload: { record: "练习台/_记录/…json", grades: [{id, verdict, comment, score?}] }
237
+ async function grade(payload) {
238
+ const rel = String(payload.record || '').replace(/\\/g, '/');
239
+ if (!rel.startsWith('练习台/_记录/')) throw Object.assign(new Error('record 必须是 练习台/_记录/ 下的路径'), { code: 400 });
240
+ const abs = path.join(BASE, rel.replace(/^练习台\//, ''));
241
+ if (!abs.startsWith(RECORDS)) throw Object.assign(new Error('bad path'), { code: 403 });
242
+ let rec;
243
+ try { rec = JSON.parse(await fsp.readFile(abs, 'utf8')); }
244
+ catch { throw Object.assign(new Error('找不到这份答卷'), { code: 404 }); }
245
+
246
+ const OK = new Set(['right', 'partial', 'wrong']);
247
+ const byId = new Map((payload.grades || []).map((g) => [String(g && g.id), g]));
248
+ let graded = 0;
249
+ for (const a of rec.answers || []) {
250
+ const g = byId.get(String(a.id));
251
+ if (!g) continue;
252
+ if (!OK.has(g.verdict)) continue;
253
+ a.verdict = g.verdict;
254
+ if (g.comment != null) a.comment = String(g.comment);
255
+ if (g.score != null) a.score = Number(g.score);
256
+ graded++;
257
+ }
258
+ // 重新统计:选择题看 ok,手写题看 verdict
259
+ const isRight = (a) => (a.kind === 'choice' ? a.ok === true : a.verdict === 'right');
260
+ rec.right = (rec.answers || []).filter(isRight).length;
261
+ rec.rate = rec.total ? rec.right / rec.total : 0;
262
+ rec.pending = (rec.answers || []).filter((a) => a.kind !== 'choice' && !a.verdict).map((a) => a.id);
263
+ rec.gradedAt = new Date().toISOString();
264
+ await fsp.writeFile(abs, JSON.stringify(rec, null, 2), 'utf8');
265
+ return { ok: true, graded, right: rec.right, total: rec.total, pending: rec.pending, record: rel };
266
+ }
267
+
268
+ // 按路径读笔迹图(前端回看、或给智能体自检用)
269
+ async function readInk(relPath) {
270
+ const rel = String(relPath || '').replace(/\\/g, '/');
271
+ if (!rel.startsWith('练习台/_笔迹/')) throw Object.assign(new Error('只允许读 练习台/_笔迹/ 下的图片'), { code: 400 });
272
+ const abs = path.join(BASE, rel.replace(/^练习台\//, ''));
273
+ if (!abs.startsWith(INK)) throw Object.assign(new Error('bad path'), { code: 403 });
274
+ return fsp.readFile(abs);
275
+ }
276
+
277
+ async function serveStatic(req, res, urlPath) {
278
+ let rel = decodeURIComponent(urlPath.split('?')[0]);
279
+ if (rel === '/' || rel === '') rel = '/index.html';
280
+ const target = path.join(PUBLIC, path.normalize(rel).replace(/^([/\\])+/, ''));
281
+ if (!target.startsWith(PUBLIC)) { res.writeHead(403); return res.end('forbidden'); }
282
+ try {
283
+ const st = await fsp.stat(target);
284
+ if (st.isDirectory()) throw new Error('dir');
285
+ res.writeHead(200, {
286
+ 'content-type': MIME[path.extname(target).toLowerCase()] || 'application/octet-stream',
287
+ 'content-length': st.size,
288
+ 'cache-control': 'no-cache',
289
+ });
290
+ fs.createReadStream(target).pipe(res);
291
+ } catch {
292
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
293
+ res.end('404 ' + rel);
294
+ }
295
+ }
296
+
297
+ const server = http.createServer(async (req, res) => {
298
+ const u = new URL(req.url, `http://${HOST}:${PORT}`);
299
+ const p = u.pathname;
300
+ try {
301
+ if (p === '/api/ping') return json(res, 200, { ok: true });
302
+ if (p === '/api/health') return json(res, 200, { ok: true, root: BASE, port: PORT });
303
+ if (p === '/api/library') return json(res, 200, { items: await library() });
304
+ if (p === '/api/practice') {
305
+ const course = safe(u.searchParams.get('course'));
306
+ const id = safe(u.searchParams.get('id'));
307
+ const f = path.join(BANK, course, id + '.json');
308
+ if (!f.startsWith(BANK)) return json(res, 403, { error: 'bad path' });
309
+ const txt = await fsp.readFile(f, 'utf8');
310
+ return json(res, 200, { practice: JSON.parse(txt), records: await recordsFor(course, id) });
311
+ }
312
+ if (p === '/api/records') {
313
+ const course = safe(u.searchParams.get('course'));
314
+ const id = u.searchParams.get('id');
315
+ if (course && id) return json(res, 200, { items: await recordsFor(course, id) });
316
+ const out = [];
317
+ for (const c of await listDir(RECORDS)) {
318
+ if (!c.isDirectory()) continue;
319
+ for (const f of await listDir(path.join(RECORDS, c.name))) {
320
+ if (!f.isFile() || !f.name.endsWith('.json')) continue;
321
+ try { out.push(JSON.parse(await fsp.readFile(path.join(RECORDS, c.name, f.name), 'utf8'))); } catch { /* skip */ }
322
+ }
323
+ }
324
+ out.sort((a, b) => String(b.at).localeCompare(String(a.at)));
325
+ return json(res, 200, { items: out.slice(0, 200) });
326
+ }
327
+ if (p === '/api/submit' && req.method === 'POST') {
328
+ const body = JSON.parse(await readBody(req) || '{}');
329
+ const r = await submit(body);
330
+ console.log(`[练习台] 提交 ${r.record} ${r.right}/${r.total}` + (r.pending && r.pending.length ? ` 待批改: ${r.pending.join('、')}` : ''));
331
+ return json(res, 200, r);
332
+ }
333
+ // 上传一题的笔迹图(填空/大题)。前端逐题上传,返回相对路径写进答卷的 ink 字段。
334
+ if (p === '/api/ink' && req.method === 'POST') {
335
+ const body = JSON.parse(await readBody(req, INK_MAX_BYTES * 2) || '{}');
336
+ const r = await saveInk(body);
337
+ console.log(`[练习台] 笔迹 ${r.path} ${(r.bytes / 1024).toFixed(0)}KB`);
338
+ return json(res, 200, { ok: true, ink: r.path, bytes: r.bytes });
339
+ }
340
+ // 按路径回读笔迹图(成绩页显示老师视角的原始笔迹)
341
+ if (p === '/api/ink' && req.method === 'GET') {
342
+ const rel = u.searchParams.get('path') || '';
343
+ try {
344
+ const buf = await readInk(rel);
345
+ res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'no-store' });
346
+ return res.end(buf);
347
+ } catch (e) {
348
+ return json(res, e.code || 500, { error: String(e.message || e) });
349
+ }
350
+ }
351
+ // 批改回填:手写题由智能体看过图后写回 verdict
352
+ if (p === '/api/grade' && req.method === 'POST') {
353
+ const body = JSON.parse(await readBody(req) || '{}');
354
+ const r = await grade(body);
355
+ console.log(`[练习台] 批改 ${r.record} ${r.right}/${r.total}` + (r.pending.length ? ` 仍待批: ${r.pending.join('、')}` : ''));
356
+ return json(res, 200, r);
357
+ }
358
+ if (p === '/api/inbox' && req.method === 'POST') {
359
+ // 收件箱消费。body 三种形态:
360
+ // {"remove":["练习台/_记录/<科目>/<文件>.json", …]} —— 只删这些记录对应的行
361
+ // (推荐:多对话并行时只动自己那几条,不会把别的对话的提交一起吞掉)
362
+ // {"drop":N} —— 只删前 N 行(保留期间新到的提交)
363
+ // 不带 body 或都缺省 —— 全清(谨慎,会清掉别的对话的提交)
364
+ await fsp.mkdir(INBOX, { recursive: true });
365
+ const file = path.join(INBOX, '待处理.jsonl');
366
+ let body = {};
367
+ try { body = JSON.parse(await readBody(req) || '{}'); } catch { body = {}; }
368
+ let lines = [];
369
+ try { lines = (await fsp.readFile(file, 'utf8')).split('\n').filter((l) => l.trim()); } catch { lines = []; }
370
+
371
+ if (Array.isArray(body.remove)) {
372
+ const norm = (s) => String(s || '').replace(/\\/g, '/');
373
+ const remove = body.remove.map(norm);
374
+ const rest = lines.filter((l) => {
375
+ let o = null; try { o = JSON.parse(l); } catch { return true; }
376
+ return !remove.includes(norm(o.record));
377
+ });
378
+ await fsp.writeFile(file, rest.length ? rest.join('\n') + '\n' : '', 'utf8');
379
+ return json(res, 200, { ok: true, removed: lines.length - rest.length, kept: rest.length });
380
+ }
381
+
382
+ const drop = Number.isInteger(body.drop) && body.drop >= 0 ? body.drop : null;
383
+ let kept = 0;
384
+ if (drop === null) {
385
+ await fsp.writeFile(file, '', 'utf8');
386
+ } else {
387
+ const rest = lines.slice(drop);
388
+ kept = rest.length;
389
+ await fsp.writeFile(file, rest.length ? rest.join('\n') + '\n' : '', 'utf8');
390
+ }
391
+ return json(res, 200, { ok: true, dropped: drop, kept });
392
+ }
393
+ // 学习助手扩展接口(/api/learn/*):放在既有路由之后,不影响上面的任何行为
394
+ if (p.startsWith('/api/learn')) {
395
+ if (await handleLearnApi(req, res, u)) return;
396
+ }
397
+ return await serveStatic(req, res, p);
398
+ } catch (e) {
399
+ // 错误自带 code(400/403/404/413/415)时按它回,便于前端和调用方区分「参数错」与「服务炸了」。
400
+ const code = Number(e && e.code);
401
+ json(res, code >= 400 && code < 600 ? code : 500, { error: String((e && e.message) || e) });
402
+ }
403
+ });
404
+
405
+ // 多个对话可能同时想拉起练习台。端口被占时不要静默崩掉(exit 1 且日志里什么都没有,
406
+ // 排查起来只能靠猜),要分清两种情况:已有一个健康的练习台在跑 → 优雅退出;被别的程序占 → 说清楚。
407
+ // 注意:不要在 await fetch 之后立刻 process.exit —— Node 在 Windows 上会因句柄未收干净而
408
+ // 触发 libuv 断言。所以先置 exitCode,再让进程自己自然退出。
409
+ const die = (code, msg) => {
410
+ if (msg) console[code === 0 ? 'log' : 'error'](msg);
411
+ process.exitCode = code;
412
+ };
413
+
414
+ server.on('error', async (e) => {
415
+ if (e && e.code === 'EADDRINUSE') {
416
+ try {
417
+ const r = await fetch(`http://${HOST}:${PORT}/api/health`);
418
+ const j = await r.json();
419
+ if (j && j.ok) {
420
+ die(0, `[练习台] 端口 ${PORT} 上已有一个健康的练习台在运行(root: ${j.root}),无需重复启动,本进程退出。`);
421
+ return;
422
+ }
423
+ } catch { /* 占用者不是练习台,往下走 */ }
424
+ die(1, `[练习台] 端口 ${PORT} 被别的程序占用,且它不响应 /api/health。换个端口:node 服务.mjs 18801`);
425
+ return;
426
+ }
427
+ die(1, `[练习台] 服务出错:${e && e.stack ? e.stack : e}`);
428
+ });
429
+
430
+ process.on('uncaughtException', (e) => {
431
+ console.error('[练习台] 未捕获异常:', e);
432
+ process.exitCode = 1;
433
+ });
434
+ process.on('unhandledRejection', (e) => {
435
+ console.error('[练习台] 未处理的 Promise 拒绝(进程继续运行):', e);
436
+ });
437
+
438
+ server.listen(PORT, HOST, () => {
439
+ console.log(`练习台已启动: http://${HOST}:${PORT}/`);
440
+ console.log(`数据基目录: ${BASE}`);
441
+ console.log(`题库目录: ${BANK}`);
442
+ console.log(`记录目录: ${RECORDS}`);
443
+ });
@@ -0,0 +1,114 @@
1
+ // 校验题目(固定模板):机械检查一份题库 JSON 的硬错误。
2
+ // 用法: node 校验题目.mjs _题库/线性代数/矩阵与向量乘法-01.json
3
+ // 可以一次给多个文件。
4
+ // 退出码 0 = 全部通过;非 0 = 有问题(下面会逐条列出)。
5
+ //
6
+ // 查不出数学对错(那要人核对),但能挡住:答案不在选项里、id 重复、
7
+ // 选项 key 重复、公式少一个 $、字段缺失这类硬错。
8
+ //
9
+ // 题型(kind):
10
+ // choice(默认,省略即此)—— 选择题,必须有 options 与 answer
11
+ // fill —— 填空题,白板手写,必须给 answer(参考答案,供批改用)
12
+ // essay —— 大题,白板手写,必须给 explain(参考解答,供批改用)
13
+ // 手写题不写 options;answer/explain 是给智能体看的标准,不参与网页自动判分。
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ // 必须用 fileURLToPath 解码:目录名是中文,URL.pathname 会保留百分号编码。
19
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
20
+ const OK_IDS = new Set(['check-1', 'check-2', 'easy', 'mid', 'hard']);
21
+ const OK_LEVELS = new Set(['check', 'easy', 'mid', 'hard']);
22
+ const OK_KINDS = new Set(['choice', 'fill', 'essay']);
23
+
24
+ // 去掉转义的 \$ 后统计 $ 个数,奇数说明公式没闭合
25
+ const dollarOdd = (s) => {
26
+ const t = String(s ?? '').replace(/\\\$/g, '');
27
+ return (t.match(/\$/g) || []).length % 2 === 1;
28
+ };
29
+
30
+ let bad = 0;
31
+ let badHere = 0;
32
+ const fail = (f, msg) => { bad++; badHere++; console.log(` ✗ ${msg}`); };
33
+ const check = (file) => {
34
+ badHere = 0;
35
+ console.log(`\n== ${file}`);
36
+ const abs = path.isAbsolute(file) ? file : path.join(HERE, file);
37
+ let doc;
38
+ try { doc = JSON.parse(fs.readFileSync(abs, 'utf8')); }
39
+ catch (e) { fail(file, `读不了或不是合法 JSON:${e.message}`); return; }
40
+
41
+ for (const k of ['title', 'course', 'topic']) {
42
+ if (!doc[k] || !String(doc[k]).trim()) fail(file, `缺字段 ${k}`);
43
+ }
44
+ const qs = doc.questions;
45
+ if (!Array.isArray(qs) || qs.length === 0) { fail(file, 'questions 不是非空数组'); return; }
46
+ if (qs.length > 5) fail(file, `题目 ${qs.length} 道,超过 5 道(快速检查 1–2 + 易/中/难)`);
47
+
48
+ const seen = new Set();
49
+ qs.forEach((q, i) => {
50
+ const at = `第 ${i + 1} 题(${q && q.id ? q.id : '无id'})`;
51
+ if (!q || typeof q !== 'object') { fail(file, `${at} 不是对象`); return; }
52
+ if (!q.id) fail(file, `${at} 缺 id`);
53
+ else if (!OK_IDS.has(q.id)) fail(file, `${at} id 必须是 check-1/check-2/easy/mid/hard 之一`);
54
+ else if (seen.has(q.id)) fail(file, `${at} id 重复`);
55
+ else seen.add(q.id);
56
+ if (!q.level || !OK_LEVELS.has(q.level)) fail(file, `${at} level 必须是 check/easy/mid/hard 之一`);
57
+ if (!q.stem || !String(q.stem).trim()) fail(file, `${at} 缺 stem`);
58
+
59
+ // 题型:省略 = choice(老题库全部向后兼容)
60
+ const kind = q.kind == null ? 'choice' : String(q.kind);
61
+ if (!OK_KINDS.has(kind)) { fail(file, `${at} kind 必须是 choice/fill/essay 之一,现在是 ${JSON.stringify(q.kind)}`); return; }
62
+
63
+ if (dollarOdd(q.stem)) fail(file, `${at} stem 的 $ 数量是奇数,公式没闭合`);
64
+
65
+ if (kind !== 'choice') {
66
+ // ---- 填空题 / 大题:白板手写,不写 options,但要给批改依据 ----
67
+ if (q.options != null) fail(file, `${at} 是 ${kind} 题,不要写 options(手写题没有选项)`);
68
+ // 选择题的「答案必须落在选项里」对手写题不适用;改成必须有参考答案
69
+ if (kind === 'fill') {
70
+ if (!String(q.answer ?? '').trim()) fail(file, `${at} fill 题必须给 answer(参考答案,批改时对照)`);
71
+ } else {
72
+ if (!String(q.explain ?? '').trim()) fail(file, `${at} essay 题必须给 explain(参考解答,批改时对照)`);
73
+ if (q.answer != null && !String(q.answer).trim()) fail(file, `${at} essay 题的 answer 若写了就不能为空`);
74
+ }
75
+ // 图上能写多少字有上限,题干别长到画布放不下
76
+ const hintLen = String(q.inkHint || '').length;
77
+ if (hintLen > 200) fail(file, `${at} inkHint 超过 200 字,画板提示写不下`);
78
+ if (q.answer != null && dollarOdd(q.answer)) fail(file, `${at} answer 的 $ 数量是奇数,公式没闭合`);
79
+ if (q.explain != null && dollarOdd(q.explain)) fail(file, `${at} explain 的 $ 数量是奇数,公式没闭合`);
80
+ return;
81
+ }
82
+
83
+ const opts = q.options;
84
+ if (!Array.isArray(opts) || opts.length < 2) { fail(file, `${at} options 至少 2 个`); return; }
85
+ const keys = opts.map((o) => o && o.key);
86
+ if (keys.some((k) => !k)) fail(file, `${at} 有选项缺 key`);
87
+ if (new Set(keys).size !== keys.length) fail(file, `${at} 选项 key 重复:${keys.join(',')}`);
88
+ if (opts.some((o) => !o || !String(o.text ?? '').trim())) fail(file, `${at} 有选项缺 text`);
89
+ // 网页会自动在末尾补一个 E「不知道」,题库里再写 E 就重复了
90
+ if (keys.includes('E')) fail(file, `${at} 选项里不要写 E:「不知道」由网页自动补,题库只写 A–D`);
91
+ opts.forEach((o) => {
92
+ const t = String((o && o.text) || '').trim();
93
+ if (/^(以上都[对错]|以上皆是|都不对|不知道|其他)$/.test(t)) fail(file, `${at} 选项「${t}」是凑数项,去掉`);
94
+ });
95
+ if (!q.answer || !keys.includes(q.answer)) fail(file, `${at} answer=${JSON.stringify(q.answer)} 不在选项 key [${keys.join(',')}] 里`);
96
+ if (!q.explain || !String(q.explain).trim()) fail(file, `${at} 缺 explain`);
97
+
98
+ if (dollarOdd(q.explain)) fail(file, `${at} explain 的 $ 数量是奇数,公式没闭合`);
99
+ opts.forEach((o, j) => {
100
+ if (o && dollarOdd(o.text)) fail(file, `${at} 选项 ${j + 1} 的 $ 数量是奇数,公式没闭合`);
101
+ });
102
+ });
103
+
104
+ if (badHere === 0) console.log(` ✓ ${qs.length} 道题,字段与答案指向都没问题(数学对错仍需人核对)`);
105
+ };
106
+
107
+ const files = process.argv.slice(2);
108
+ if (files.length === 0) {
109
+ console.log('用法: node 校验题目.mjs <题库json> [更多…]');
110
+ process.exit(2);
111
+ }
112
+ for (const f of files) check(f);
113
+ console.log(bad === 0 ? '\n全部通过。' : `\n有 ${bad} 处问题,先修好再让用户做题。`);
114
+ process.exit(bad === 0 ? 0 : 1);
@@ -0,0 +1,100 @@
1
+ // 等待提交(固定模板,不要另写脚本)—— 插件参数化版
2
+ //
3
+ // 用法: node 等待提交.mjs [最长等待秒数,默认 3600] [只等这一份:<科目>/<练习id>] [--base <数据基目录>]
4
+ //
5
+ // 语义:盯着 _收件箱/待处理.jsonl,**只要出现属于本轮(匹配筛选)的提交,就立刻报出全部匹配行并退出 0**。
6
+ // 不看"启动时的行数基线",所以迟挂的探针也能自愈——用户在探针挂上之前先提交了,
7
+ // 探针启动后第一轮轮询就能看到,不会漏单。
8
+ //
9
+ // 为什么要带筛选参数:收件箱是所有对话共用的一个文件。不带筛选的探针会被**别的对话**的提交唤醒,
10
+ // 一次提交就把多个对话全部启动(白花钱)。带上 <科目>/<练习id> 后,只认自己这一轮。
11
+ //
12
+ // 作为后台 job 启动;job 结束会通知智能体 → 智能体据此批改。
13
+ // 本脚本**不删收件箱**:删除由智能体批改后调 POST /api/inbox 完成。
14
+ //
15
+ // 数据基目录解析:--base 参数 > LEARN_DATA_BASE 环境变量 > 脚本所在目录的上一级(传统布局)。
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ const argv = process.argv.slice(2);
21
+
22
+ // --base 可以出现在任意位置;其余位置参数按序取
23
+ let baseIdx = argv.indexOf('--base');
24
+ let BASE = null;
25
+ if (baseIdx >= 0 && argv[baseIdx + 1]) {
26
+ BASE = path.resolve(argv[baseIdx + 1]);
27
+ argv.splice(baseIdx, 2);
28
+ }
29
+ if (!BASE && process.env.LEARN_DATA_BASE && path.isAbsolute(process.env.LEARN_DATA_BASE)) {
30
+ BASE = path.resolve(process.env.LEARN_DATA_BASE);
31
+ }
32
+ if (!BASE) BASE = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
33
+
34
+ // 注意:必须用 fileURLToPath 解码,不能用 URL.pathname —— 目录名是中文,
35
+ // pathname 会保留 %E7%BB%83… 百分号编码,导致收件箱路径根本不存在(永远等不到提交)。
36
+ const INBOX = path.join(BASE, '练习台', '_收件箱', '待处理.jsonl');
37
+
38
+ const LIMIT = Number(argv[0] || 3600) * 1000;
39
+ const FILTER = String(argv[1] || '').trim();
40
+ const parts = FILTER ? FILTER.split('/') : [];
41
+ const wantCourse = parts.length > 1 ? parts[0] : '';
42
+ const wantId = parts.length > 1 ? parts[1] : (parts[0] || '');
43
+
44
+ const lines = () => {
45
+ try { return fs.readFileSync(INBOX, 'utf8').split('\n').filter((l) => l.trim()); }
46
+ catch { return []; }
47
+ };
48
+
49
+ const parse = (l) => { try { return JSON.parse(l); } catch { return null; } };
50
+
51
+ // 只认本轮:科目(若写了)+ 练习 id 都要对上
52
+ const mine = (o) => {
53
+ if (!o) return false;
54
+ if (!FILTER) return true;
55
+ if (wantCourse && String(o.course || '') !== wantCourse) return false;
56
+ return String(o.practiceId || '') === wantId;
57
+ };
58
+ const matched = () => lines().map(parse).filter(mine);
59
+
60
+ const started = Date.now();
61
+ const waitWhat = FILTER
62
+ ? `只等「${FILTER}」`
63
+ : '未指定筛选(任何提交都会唤醒;多对话并行时请务必带上 <科目>/<练习id>)';
64
+ process.stdout.write(`[等待提交] ${waitWhat};收件箱现有 ${lines().length} 条\n`);
65
+
66
+ const report = (hits) => {
67
+ process.stdout.write(`[等待提交] 收到 ${hits.length} 份属于本轮的提交:\n`);
68
+ for (const o of hits) {
69
+ const pending = o.pending && o.pending.length ? o.pending : [];
70
+ // 有手写题待批改时,score 里的分母只含选择题,别把「全对」说得像是整卷都对
71
+ const wrong = o.wrong && o.wrong.length ? ' 错题: ' + o.wrong.join('、') : (pending.length ? '' : ' 全对');
72
+ const dunno = o.dunno && o.dunno.length ? ` 不知道: ${o.dunno.join('、')}` : '';
73
+ const pendTxt = pending.length ? ` 待批改(手写): ${pending.join('、')}` : '';
74
+ process.stdout.write(` · ${o.course} / ${o.practiceTitle} → ${o.score}${wrong}${dunno}${pendTxt}\n`);
75
+ // 用户在 E 选项旁写的具体卡点,逐条打出来,别只报题号
76
+ if (Array.isArray(o.unclear)) {
77
+ for (const u of o.unclear) process.stdout.write(` 卡点 ${u.id}: ${u.note}\n`);
78
+ }
79
+ process.stdout.write(` 记录: ${o.record}\n`);
80
+ }
81
+ process.stdout.write('[等待提交] 请读上面每条的 记录 路径逐题批改。\n');
82
+ process.stdout.write(' · 选择题看 answers[].ok 即可;\n');
83
+ process.stdout.write(' · 手写题(kind=fill/essay)要先读 answers[].ink 指向的笔迹图,\n');
84
+ process.stdout.write(' 再把判定 POST 回 /api/grade:{record, grades:[{id, verdict:"right|partial|wrong", comment}]}。\n');
85
+ process.stdout.write(' · 批改完调 POST /api/inbox 带 {"remove":[<记录路径>]} 只删掉自己这几条。\n');
86
+ process.exit(0);
87
+ };
88
+
89
+ const tick = () => {
90
+ const hits = matched();
91
+ if (hits.length > 0) { clearInterval(timer); report(hits); return; }
92
+ if (Date.now() - started > LIMIT) {
93
+ clearInterval(timer);
94
+ process.stdout.write(`[等待提交] 超时:这段时间没有收到${FILTER ? `「${FILTER}」的` : ''}提交。收件箱里没有属于本轮的记录,没有漏单。\n`);
95
+ process.exit(0);
96
+ }
97
+ };
98
+
99
+ const timer = setInterval(tick, 1000);
100
+ tick();