-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1955 lines (1843 loc) · 82.1 KB
/
Copy pathserver.js
File metadata and controls
1955 lines (1843 loc) · 82.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Lucubro 后端:静态页(注入 glue.js)+ 课程 API + kimi 子进程
const express = require('express');
const multer = require('multer');
const { spawn } = require('child_process');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const os = require('os');
const {
buildTutorPrompt,
withHumanizerSkill,
createTutorSessionState,
normalizeTutorSessionState,
isTutorSessionMissingError,
} = require('./lib/tutor-context');
const {
buildNextLessonPrompt,
captureNextLessonBaseline,
clearNextLessonTransaction,
createGeneratorSessionState,
generatorSessionIdForRun,
isGenerationJobActive,
isStaleGenerationJob,
normalizeGeneratorSessionState,
recoverInterruptedNextLesson,
writeNextLessonTransaction,
withTeachSkill,
} = require('./lib/next-lesson');
const {
cleanupNextLessonDelta,
validatePublishedLesson,
validateNextLessonDelta,
} = require('./lib/lesson-publish-validator');
const { normalizeLessonSpecShape, validateLessonSpec, scoreActivity, computeClaimProgress, toPublicLessonSpec } = require('./lib/activity-engine');
const { isPrivateCoursePath } = require('./lib/private-course-path');
const { deriveGenerationStatus } = require('./lib/generation-status');
const {
operationStateEnabled,
readOperation,
writeOperation,
projectOperation,
} = require('./lib/operation-state');
const { runTrackedKimi } = require('./lib/kimi-generation-runner');
const { appendGenerationEvent, readGenerationEvents, subscribeGenerationEvents } = require('./lib/generation-events');
const { listCourseSources } = require('./lib/source-manifest');
const { createArtifactStore, ArtifactError } = require('./lib/artifact-store');
const { runArtifactCritique, ArtifactCritiqueError } = require('./lib/artifact-critique');
const { appendCourseActivity, readCourseActivity: readCourseActivityFile, ActivityValidationError } = require('./lib/course-activity');
const { resolveDataDir, assertSafeRuntime } = require('./lib/runtime-config');
const { validateCuriosityDocument } = require('./lib/curiosity-contract');
const { createLearningActionService } = require('./lib/learning-action-router');
const {
MAX_STUDY_SURFACE_BYTES,
inspectStudySurfaceState,
normalizeStudySurfaceState,
studySurfaceByteLength,
} = require('./lib/study-surface-state');
const {
auditMissionSemantics,
answerMissionPrompt,
initialMissionPrompt,
isRepairableMissionError,
materializeMissionDocument,
readMissionPresentation,
parseMissionTurn,
promoteMissionSession,
readMissionSessionState,
repairMissionPrompt,
validateMissionDocument,
writeMissionDocument,
writeMissionSessionState,
} = require('./lib/standard-teach-mission');
const { buildSourceDigest } = require('./lib/source-digest');
const {
MAX_SOURCE_BYTES,
OnboardingError,
confirmMission,
createCourseDraft,
validateEpubArchive,
markGenerationFailed,
markGenerationReady,
markGenerationRunning,
markGenerationStarting,
markMissionFailed,
markMissionPlanning,
markMissionQuestion,
markMissionReady,
onboardingGenerationStage,
publicOnboarding,
readOnboarding,
resolveMissionAnswer,
reconcileOnboarding,
} = require('./lib/onboarding');
const ROOT = __dirname;
const DATA = resolveDataDir({ root: ROOT });
const SKILLS = path.join(ROOT, 'skills');
const MODEL = 'kimi-code/kimi-for-coding'; // K2.7 Coding
const PORT = process.env.PORT || 3000;
const POL_V2_ENABLED = process.env.LUCUBRO_POL_V2 === '1';
const RUNTIME = assertSafeRuntime({ root: ROOT, dataDir: DATA, port: PORT, env: process.env });
fs.mkdirSync(DATA, { recursive: true });
const artifactStore = createArtifactStore({ dataDir: DATA });
const artifactOperationLocks = new Set();
const selectLearningActions = createLearningActionService();
const MAP_INSTRUCTION =
`最后,把本课程工作区的内容汇总写入 map.json(严格 JSON,不要任何多余文字),格式:` +
`{"mission":{"title":"学习目标一句话","copy":"一段话","criteria":["成功标准"],"constraints":["约束"]},` +
`"promise":"课程承诺一句话","material":"材料理解一两句话",` +
`"methods":[{"name":"方法名","when":"何时使用","boundary":"边界"}],` +
`"path":["第一步","第二步"]}。内容取自 MISSION.md、RESOURCES.md、reference/ 和 learning-records/。`;
const ASSESSMENT_INSTRUCTION =
`\n\n互动教学要求:MISSION.md 是用户学习意图的权威来源;若已存在且已填写,不要重复 Mission 问答。` +
`按 skills/teach/ASSESSMENT-DESIGN.md 执行:分析材料单元,生成 learning claims、evidence requirements、` +
`assessment blueprint、misconceptions、answer-first question candidates 和 quality report。` +
`第一课与后续课使用同一发布合同:每课恰好 1 个 claim 和 2 个 activities,分别为 independent 单选 hinge 与 transfer short-answer。` +
`claim.description 必须说明该能力如何推进 MISSION.md 的期望产出或成功证据。transfer 必须直接形成、修订、判断或演练期望产出的一部分。` +
`short-answer minimumLength 至少 40,但它只表示输入完整性下限,不是质量或成功证据。` +
`为生成的 lessons/NNNN-name.html 同时写 assessments/NNNN-name.json,并在 HTML 中放置对应的 ` +
'`<div data-kimi-activity="activity-id"></div>`。' +
`普通选择、填空、排序题必须可确定性评分;答案和评分键只能放在 assessments/,不要写入 HTML。`;
const CURIOSITY_INSTRUCTION =
`
Curiosity 不是随机冷知识。完成课节与 Assessment 后,可选择生成 0—3 张高质量 Curiosity Card。` +
`只有当内容与本课目标高度相关、确实违反合理预期、一分钟内能理解且有可靠依据时才生成;达不到门槛就生成 0 张。` +
`写入 curiosity/<LESSON_BASE>.json,schemaVersion 为 1,lessonId 必须等于 LESSON_BASE。` +
`每张卡包含 id、hook、prediction.prompt、prediction.options(可选 2—4 项)、reveal、bridge、section 或 anchor、` +
`source.label 或 sourceRefs,以及 scores:relevance>=4、surprise>=3、clarity>=3、confidence>=4、load<=3。` +
`不得把答案、Assessment 评分键或无关趣闻写入 Curiosity。`;
const {
ASSESSMENT_MACHINE_CONTRACT_LINES,
LESSON_PEDAGOGY_CONTRACT_LINES,
preflightInstruction,
} = require('./lib/assessment-machine-contract');
// 首课与下一课共用同一段 Assessment wire schema(见 R6 P0.1「同一发布合同」)。
// 首课没有 transaction baseline,预检走 first-lesson-preflight(逐课验证 lessons/)。
const FIRST_LESSON_MACHINE_CONTRACT =
'\n\n' + LESSON_PEDAGOGY_CONTRACT_LINES.join('\n') + '\n\n' +
ASSESSMENT_MACHINE_CONTRACT_LINES.join('\n') + '\n' +
preflightInstruction(`node ${JSON.stringify(path.join(ROOT, 'lib', 'first-lesson-preflight.js'))}`).join('\n');
const FIRST_PROMPT = (ext) =>
`/skill:teach 用户上传了一本书想学习,材料是当前目录的 book${ext}` +
`(如为 epub 可用 unzip 提取文本,如为 pdf 请自行想办法提取文本)。` +
`请按 teach skill 的流程执行:先写 MISSION.md(mission:掌握这本书的核心内容)和 RESOURCES.md,` +
`然后生成第一课 lessons/0001-*.html。所有产出用中文。` +
`另外把书的封面图片提取保存到工作区根目录 cover.jpg(epub 解压后在 OPF manifest 里找 cover 项;` +
`pdf 可用 sips 把第一页转成 jpg)。` + ASSESSMENT_INSTRUCTION + FIRST_LESSON_MACHINE_CONTRACT + CURIOSITY_INSTRUCTION + MAP_INSTRUCTION;
const languageInstruction = (locale = 'en') => ({
'zh-CN': '所有面向用户的课程内容使用简体中文。',
ja: 'ユーザー向けのコース内容は日本語で作成する。',
en: 'Write all user-facing course content in English.',
}[locale] || 'Write all user-facing course content in English.');
const modeInstruction = (mode = 'student') => mode === 'goal'
? '这是一门目标导向课程:围绕用户当前要解决的现实问题组织材料、练习与产出物,优先要求用户做出可观察的作品或行动。'
: '这是一门学生课程:结合教材、试卷和练习证据诊断掌握情况,优先根据用户实际作答与练习表现调整后续内容。';
const FIRST_ONBOARDING_PROMPT = (ext, profile = {}) =>
`继续当前 teach Session。用户已经确认 MISSION.md;不要重新进行 Mission 访谈,也不要改写 Mission。` +
`材料是当前目录的 book${ext}。${modeInstruction(profile.mode)}读取已确认的 MISSION.md,写 RESOURCES.md,然后生成第一课 lessons/0001-*.html。${languageInstruction(profile.locale)}` +
`另外把书的封面图片提取保存到工作区根目录 cover.jpg(epub 解压后在 OPF manifest 里找 cover 项;` +
`pdf 可用 sips 把第一页转成 jpg)。` + ASSESSMENT_INSTRUCTION + FIRST_LESSON_MACHINE_CONTRACT + CURIOSITY_INSTRUCTION + MAP_INSTRUCTION;
const app = express();
// Scratch drawings can exceed Express' default 100kb JSON limit. Keep the
// larger parser scoped to this one bounded endpoint; all other APIs retain the
// default request-body limit.
app.use('/api/courses/:id/study-surface', express.json({ limit: '1mb' }));
app.use(express.json());
app.use((req, res, next) => { console.log(`[http] ${req.method} ${req.url}`); next(); });
app.get('/favicon.ico', (req, res) => res.status(204).end());
// ---- 冻结前端:原样输出,仅在响应中注入运行时资源 ----
const COMMON_FRONTEND_HEAD =
'<link rel="icon" href="/assets/brand/lucubro-mark.svg" type="image/svg+xml">' +
'<link rel="stylesheet" href="/vendor/geist/wght.css">' +
'<link rel="stylesheet" href="/vendor/phosphor/regular/style.css">' +
'<link rel="stylesheet" href="/design-system.css">' +
'<script src="/i18n.js" defer></script>';
const page = (file, { head = '', body = '', glue = true, features = false } = {}) => (req, res) => {
const featureConfig = features && POL_V2_ENABLED
? '<script>window.__LUCUBRO_FEATURES__={polV2:true}</script>'
: '';
const html = fs.readFileSync(path.join(ROOT, 'public', file), 'utf8')
.replace('</head>', `${COMMON_FRONTEND_HEAD}${featureConfig}${head}</head>`)
.replace('</body>', `${body}${glue ? '<script src="/glue.js"></script>' : ''}</body>`);
res.type('html').send(html);
};
app.get('/', page('index.html'));
app.get('/app', page('app.html', {
head: '<link rel="stylesheet" href="/library-polish.css">',
features: true,
}));
app.get('/notes', page('notes.html', {
head: '<link rel="stylesheet" href="/notes.css">',
body: '<script src="/notes.js"></script>',
}));
app.get('/new-course', page('new-course.html', {
head: '<link rel="stylesheet" href="/onboarding-polish.css">',
body: '<script src="/first-run-onboarding.js"></script>',
features: true,
}));
app.get('/course/:id', page('course.html', {
head: '<link rel="stylesheet" href="/generation-preview-product.css"><link rel="stylesheet" href="/source-viewer.css"><link rel="stylesheet" href="/frontend-shell.css"><link rel="stylesheet" href="/core-journey-polish.css"><link rel="stylesheet" href="/course-notes-index.css"><link rel="stylesheet" href="/study-surface.css"><link rel="stylesheet" href="/course-workspace-polish.css">',
body: '<script src="/assistant-markdown.js"></script><script src="/core-journey-progress.js"></script><script src="/generation-preview-product.js"></script><script src="/generation-events-client.js"></script><script src="/source-viewer.js"></script><script src="/course-notes-index.js"></script><script src="/study-surface.js"></script>',
features: true,
}));
if (POL_V2_ENABLED) {
app.get('/artifact/new', page('artifact-new.html', {
head: '<link rel="stylesheet" href="/artifact.css">',
body: '<script src="/artifact-new.js"></script>',
glue: false,
features: true,
}));
app.get('/artifact/:id', page('artifact.html', {
head: '<link rel="stylesheet" href="/artifact.css">',
body: '<script src="/artifact.js"></script>',
glue: false,
features: true,
}));
}
app.use('/vendor/lenis', express.static(path.join(ROOT, 'node_modules', 'lenis', 'dist')));
app.use('/vendor/pdfjs', express.static(path.join(ROOT, 'node_modules', 'pdfjs-dist')));
app.use('/vendor/epubjs', express.static(path.join(ROOT, 'node_modules', 'epubjs', 'dist')));
app.use('/vendor/jszip', express.static(path.join(ROOT, 'node_modules', 'jszip', 'dist')));
app.use('/vendor/geist', express.static(path.join(ROOT, 'node_modules', '@fontsource-variable', 'geist')));
app.use('/vendor/phosphor', express.static(path.join(ROOT, 'node_modules', '@phosphor-icons', 'web', 'src')));
app.use(express.static(path.join(ROOT, 'public'))); // 前端外壳资源
// ---- 课程工作区 ----
const locks = new Set(); // 每门课同时只跑一个 kimi 进程
const activeGenerationProcesses = new Map();
const cancelledGenerationRuns = new Set();
const operationStateOn = operationStateEnabled();
const dirOf = (id) => path.join(DATA, id);
const validId = (id) => /^[a-z0-9]+$/i.test(id);
const emitGenerationEvent = (id, event) => {
try { return appendGenerationEvent(dirOf(id), event); }
catch (error) {
console.log(`[generation ${id}] event log failed: ${error.message}`);
return null;
}
};
const jobFile = (id) => path.join(dirOf(id), 'job.json');
const writeJob = (id, job) => fs.writeFileSync(jobFile(id), JSON.stringify(job));
const readJob = (id) => { try { return JSON.parse(fs.readFileSync(jobFile(id), 'utf8')); } catch { return { stage: 'understanding' }; } };
const lessonsOf = (id) => {
const d = path.join(dirOf(id), 'lessons');
return fs.existsSync(d) ? fs.readdirSync(d).filter((f) => f.endsWith('.html') && f !== 'index.html').sort() : [];
};
const assessmentsOf = (id) => {
const d = path.join(dirOf(id), 'assessments');
return fs.existsSync(d) ? fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort() : [];
};
const operationRuntime = (id) => ({
courseDir: dirOf(id),
lessons: lessonsOf(id).length,
assessments: assessmentsOf(id).length,
busy: locks.has(id),
});
function operationProjection(id) {
if (!operationStateOn) return null;
const snapshot = readOperation(dirOf(id));
return projectOperation(snapshot, operationRuntime(id));
}
function persistOperation(id, patch, options = {}) {
if (!operationStateOn) return null;
return writeOperation(dirOf(id), patch, options);
}
function trackedGenerationSpawn(id, runId) {
return (command, args, options) => {
const child = spawn(command, args, options);
activeGenerationProcesses.set(id, { runId, child });
const clear = () => {
const active = activeGenerationProcesses.get(id);
if (active && active.child === child) activeGenerationProcesses.delete(id);
};
child.once('close', clear);
child.once('error', clear);
return child;
};
}
function runPrintKimi(id, prompt, { cont = false, sessionId = null } = {}) {
return new Promise((resolve, reject) => {
locks.add(id);
const args = ['-m', MODEL, '--skills-dir', SKILLS];
if (sessionId) args.push('--session', sessionId);
else if (cont) args.push('-c');
args.push('-p', prompt);
const sessionLabel = sessionId ? ' (tutor session)' : cont ? ' (continue)' : '';
console.log(`[kimi ${id}] start${sessionLabel}: ${prompt.slice(0, 50)}...`);
const p = spawn('kimi', args, { cwd: dirOf(id) });
let out = '', err = '';
p.stdout.on('data', (d) => (out += d));
p.stderr.on('data', (d) => (err += d));
p.on('error', (error) => {
locks.delete(id);
reject(error);
});
p.on('close', (code) => {
locks.delete(id);
console.log(`[kimi ${id}] exit ${code}`);
code === 0 ? resolve(out) : reject(new Error(err || `kimi exit ${code}`));
});
});
}
// 生成任务优先使用真实工具/文件事件;下一课额外记录本轮基线和独立 generator session。
function launchStandardMissionTurn(id, { answer = null, retry = false } = {}) {
const courseDir = dirOf(id);
if (locks.has(id)) throw new OnboardingError('MISSION_BUSY', 'Lucubro 正在处理上一轮回答', 409);
const record = markMissionPlanning(courseDir, { retry });
const state = readMissionSessionState(courseDir);
if (answer != null && (!state.initialized || !state.sessionId)) {
markMissionFailed(courseDir, new OnboardingError('MISSION_SESSION_MISSING', 'Mission 会话不可恢复', 409));
throw new OnboardingError('MISSION_SESSION_MISSING', 'Mission 会话不可恢复', 409);
}
const promptPromise = retry && state.initialized && state.sessionId
? Promise.resolve(repairMissionPrompt())
: answer == null
? buildSourceDigest(courseDir, record.source)
.then((digestResult) => initialMissionPrompt(record.source.extension, digestResult && digestResult.text, record.profile))
.catch((error) => {
console.log(`[mission ${id}] source digest unavailable, falling back to model-side skim: ${error.message}`);
return initialMissionPrompt(record.source.extension, '', record.profile);
})
: Promise.resolve(answerMissionPrompt(answer, record.profile));
const runMissionPrompt = (missionPrompt, sessionState) => runTrackedKimi({
cwd: courseDir,
prompt: missionPrompt,
sessionId: sessionState.sessionId,
preferredMode: sessionState.preferredMode,
model: MODEL,
skillsDir: SKILLS,
});
const persistMissionSession = (result, previousState) => {
const sessionId = result.sessionId || previousState.sessionId;
if (!sessionId) throw new OnboardingError('MISSION_SESSION_MISSING', '学习目标会话无法恢复', 502);
return writeMissionSessionState(courseDir, {
...previousState,
sessionId,
initialized: true,
preferredMode: result.mode || previousState.preferredMode,
});
};
const acceptMissionResult = async (result, previousState, allowRepair) => {
const nextState = persistMissionSession(result, previousState);
try {
const turn = parseMissionTurn(result.text);
if (turn.status === 'question') return markMissionQuestion(courseDir, turn);
const semanticWarnings = turn.mission ? auditMissionSemantics(turn.mission) : [];
if (allowRepair && semanticWarnings.length) {
throw new OnboardingError(
'MISSION_SEMANTIC_REPAIR_NEEDED',
'学习目标需要补充可检查的期望产出与成功证据',
502,
semanticWarnings,
);
}
if (semanticWarnings.length) {
console.log(`[mission ${id}] semantic warning after one repair: ${semanticWarnings.join('; ')}`);
}
materializeMissionDocument(courseDir, turn);
return markMissionReady(courseDir, turn);
} catch (error) {
if (allowRepair && isRepairableMissionError(error)) {
const repaired = await runMissionPrompt(repairMissionPrompt(), nextState);
return acceptMissionResult(repaired, nextState, false);
}
if (isRepairableMissionError(error)) {
throw new OnboardingError(
'MISSION_REPAIR_FAILED',
'学习目标没有整理完成。材料和已经填写的内容都已保留,可以重试。',
502,
);
}
throw error;
}
};
locks.add(id);
promptPromise
.then((prompt) => runMissionPrompt(prompt, state))
.then((result) => acceptMissionResult(result, state, true))
.catch((error) => {
try { markMissionFailed(courseDir, error); }
catch (persistError) { console.log(`[mission ${id}] failed to persist error: ${persistError.message}`); }
})
.finally(() => locks.delete(id));
return record;
}
function runKimi(id, prompt, {
cont = false,
track = false,
sessionId = null,
preferredMode = null,
kind = null,
baseline = null,
onResult = null,
} = {}) {
if (!track) return runPrintKimi(id, prompt, { cont, sessionId });
const runId = crypto.randomUUID();
const isNextLesson = kind === 'next-lesson';
const firstRunLessons = isNextLesson ? [] : lessonsOf(id);
const operationKind = isNextLesson ? 'next-lesson' : 'first-course';
const stage = lessonsOf(id).length ? 'generating' : 'understanding';
const startedAt = new Date().toISOString();
const job = {
stage,
runId,
kind: kind || 'course-generation',
phase: isNextLesson ? 'extracting' : null,
currentMessage: isNextLesson ? '正在读取学习记录并确定下一学习目标…' : null,
baselineLessons: isNextLesson ? baseline.lessons.length : undefined,
baselineAssessments: isNextLesson ? baseline.assessments.length : undefined,
startedAt,
updatedAt: startedAt,
};
try {
if (isNextLesson) writeNextLessonTransaction(dirOf(id), baseline);
locks.add(id);
writeJob(id, job);
persistOperation(id, {
operationId: runId,
kind: operationKind,
state: 'running',
phase: job.phase || 'extracting',
progressEvidence: { lessons: lessonsOf(id).length },
startedAt,
currentMessageKey: `${operationKind}.${job.phase || 'extracting'}`,
retryable: false,
}, { now: new Date(startedAt) });
emitGenerationEvent(id, {
runId,
kind: 'run-start',
key: `run:${runId}`,
phase: job.phase || undefined,
state: 'active',
message: isNextLesson ? job.currentMessage : lessonsOf(id).length ? '正在生成下一课…' : '正在开始创建课程…',
});
} catch (error) {
locks.delete(id);
if (isNextLesson) clearNextLessonTransaction(dirOf(id));
throw error;
}
const persistEvent = (event) => {
if (!event) return;
if (event.phase) job.phase = event.phase;
if (event.message) job.currentMessage = event.message;
job.updatedAt = new Date().toISOString();
writeJob(id, job);
persistOperation(id, {
operationId: runId,
kind: operationKind,
state: 'running',
phase: event.phase || job.phase || 'extracting',
progressEvidence: {
...(event.metrics || {}),
lessons: lessonsOf(id).length,
},
currentMessageKey: `${operationKind}.${event.phase || job.phase || 'extracting'}`,
retryable: false,
}, { now: new Date(job.updatedAt) });
emitGenerationEvent(id, { runId, ...event });
};
return runTrackedKimi({
cwd: dirOf(id),
prompt,
cont,
sessionId,
preferredMode,
model: MODEL,
skillsDir: SKILLS,
onEvent: persistEvent,
spawnImpl: trackedGenerationSpawn(id, runId),
}).then((result) => {
const { text, status, mode } = result;
if (status !== 'finished') throw new Error(`Kimi generation ended with status ${status}`);
if (isNextLesson) {
persistEvent({
kind: 'runner-complete',
key: `runner:${runId}`,
state: 'complete',
message: '模型生成步骤已经结束',
});
}
if (typeof onResult === 'function') onResult(result);
let newLesson = null;
if (isNextLesson) {
job.phase = 'validating';
job.currentMessage = '正在检查新增课节、活动挂载和评分规格…';
job.updatedAt = new Date().toISOString();
writeJob(id, job);
persistOperation(id, {
operationId: runId,
kind: operationKind,
state: 'running',
phase: 'validating',
progressEvidence: { lessons: lessonsOf(id).length },
currentMessageKey: `${operationKind}.validating`,
}, { now: new Date(job.updatedAt) });
emitGenerationEvent(id, {
runId,
kind: 'phase',
key: 'phase:validating',
phase: 'validating',
canvasVariant: 'validation',
state: 'active',
message: job.currentMessage,
});
const validation = validateNextLessonDelta(dirOf(id), baseline);
if (!validation.ok) {
throw new Error(`新增课节未通过发布验证:${validation.errors.join(';')}`);
}
if (validation.published?.warnings?.length) {
console.warn(`[lesson-publish] ${id}/${validation.newLesson}: ${validation.published.warnings.join(';')}`);
}
newLesson = validation.newLesson;
} else if (!lessonsOf(id).length) {
throw new Error('Kimi finished without generating a lesson');
} else {
const currentLessons = lessonsOf(id);
const firstLesson = currentLessons.find((name) => !firstRunLessons.includes(name)) || currentLessons[0];
const validation = validatePublishedLesson(dirOf(id), firstLesson);
if (!validation.ok) {
throw new Error(`第一课未通过发布验证:${validation.errors.join(';')}`);
}
if (validation.warnings?.length) {
console.warn(`[lesson-publish] ${id}/${firstLesson}: ${validation.warnings.join(';')}`);
}
newLesson = firstLesson;
}
if (isNextLesson) clearNextLessonTransaction(dirOf(id));
locks.delete(id);
const finishedAt = new Date().toISOString();
writeJob(id, {
...job,
stage: 'ready',
phase: 'complete',
currentMessage: isNextLesson ? '下一课已准备好' : '课程已准备好',
mode,
sessionId: result.sessionId || sessionId || null,
newLesson,
updatedAt: finishedAt,
finishedAt,
});
persistOperation(id, {
operationId: runId,
kind: operationKind,
state: 'ready',
phase: 'complete',
progressEvidence: { lessons: lessonsOf(id).length },
publishedArtifact: lessonsOf(id).length || null,
currentMessageKey: `${operationKind}.ready`,
retryable: false,
finishedAt,
}, { now: new Date(finishedAt) });
emitGenerationEvent(id, {
runId,
kind: 'run-complete',
key: `run:${runId}`,
phase: 'complete',
canvasVariant: 'ready',
state: 'complete',
message: isNextLesson ? '下一课已准备好' : '课程已准备好',
});
return { text, mode, sessionId: result.sessionId || sessionId || null, newLesson };
}).catch((error) => {
locks.delete(id);
const cancelled = cancelledGenerationRuns.delete(runId);
const cleanup = isNextLesson ? cleanupNextLessonDelta(dirOf(id), baseline) : {
removed: [],
changedExisting: [],
};
if (isNextLesson) clearNextLessonTransaction(dirOf(id));
const failedAt = new Date().toISOString();
const terminalMessage = cancelled
? (isNextLesson ? '下一课生成已取消' : '课程生成已取消')
: (isNextLesson ? '下一课生成没有完成,请重试' : '课程生成没有完成,请重试');
writeJob(id, {
...job,
stage: 'failed',
cancelled,
cleanupRemoved: cleanup.removed,
repairRequired: cleanup.changedExisting.length > 0,
changedExisting: cleanup.changedExisting,
currentMessage: terminalMessage,
updatedAt: failedAt,
failedAt,
error: cancelled ? 'generation cancelled' : String(error.message || error).slice(-500),
});
persistOperation(id, {
operationId: runId,
kind: operationKind,
state: cancelled ? 'cancelled' : 'failed',
phase: job.phase || 'extracting',
progressEvidence: { lessons: lessonsOf(id).length },
publishedArtifact: lessonsOf(id).length || null,
currentMessageKey: `${operationKind}.${cancelled ? 'cancelled' : 'failed'}`,
retryable: true,
finishedAt: failedAt,
}, { now: new Date(failedAt) });
emitGenerationEvent(id, {
runId,
kind: cancelled ? 'run-cancelled' : 'run-failed',
key: `run:${runId}`,
state: 'error',
message: terminalMessage,
});
throw error;
});
}
function firstLessonReadable(id) {
const [first] = lessonsOf(id);
if (!first) return false;
const file = path.join(dirOf(id), 'lessons', first);
try {
const stat = fs.lstatSync(file);
if (stat.isSymbolicLink() || !stat.isFile() || stat.size <= 0) return false;
const fd = fs.openSync(file, 'r');
try {
const probe = Buffer.alloc(1);
fs.readSync(fd, probe, 0, 1, 0);
} finally {
fs.closeSync(fd);
}
return true;
} catch {
return false;
}
}
function jobMtimeMs(id) {
try { return fs.statSync(jobFile(id)).mtimeMs; }
catch { return 0; }
}
function reconcileStaleGeneration(id, now = Date.now()) {
const job = readJob(id);
if (!isStaleGenerationJob(job, {
busy: locks.has(id),
mtimeMs: jobMtimeMs(id),
now,
})) return job;
const failedAt = new Date(now).toISOString();
const failed = job.kind === 'next-lesson'
? recoverInterruptedNextLesson(dirOf(id), job, { now: new Date(now) })
: {
...job,
stage: 'failed',
currentMessage: '课程生成已中断,请重试',
error: '课程生成已中断,请重试',
updatedAt: failedAt,
failedAt,
};
writeJob(id, failed);
persistOperation(id, {
operationId: failed.runId || `interrupted-${id}`,
kind: failed.kind === 'next-lesson' ? 'next-lesson' : 'first-course',
state: 'interrupted',
phase: failed.phase || 'extracting',
progressEvidence: { lessons: lessonsOf(id).length },
publishedArtifact: lessonsOf(id).length || null,
currentMessageKey: `${failed.kind === 'next-lesson' ? 'next-lesson' : 'first-course'}.interrupted`,
retryable: true,
finishedAt: failedAt,
}, { now: new Date(failedAt) });
emitGenerationEvent(id, {
runId: failed.runId || 'interrupted-run',
kind: 'run-failed',
key: `run:${failed.runId || 'interrupted-run'}`,
state: 'error',
message: failed.currentMessage,
});
return failed;
}
function reconcileCourseOnboarding(id) {
const record = readOnboarding(dirOf(id), { optional: true });
if (!record) return null;
const lessons = lessonsOf(id);
return reconcileOnboarding(dirOf(id), {
job: readJob(id),
busy: locks.has(id),
lessons: lessons.length,
lessonReadable: firstLessonReadable(id),
jobMtimeMs: jobMtimeMs(id),
});
}
function missionListFromSection(section) {
return String(section || '')
.split(/\r?\n/)
.map((line) => line.replace(/^\s*[-*+]\s+/, '').trim())
.filter(Boolean)
.slice(0, 8);
}
function readEditableMission(courseDir) {
const markdown = validateMissionDocument(courseDir);
const title = markdown.match(/^# Mission:\s*(.+)$/m)?.[1]?.trim() || '';
const section = (heading, nextHeading) => {
const startToken = `## ${heading}`;
const start = markdown.indexOf(startToken);
if (start < 0) return '';
const contentStart = markdown.indexOf('\n', start + startToken.length);
if (contentStart < 0) return '';
const end = nextHeading ? markdown.indexOf(`\n## ${nextHeading}`, contentStart + 1) : markdown.length;
return markdown.slice(contentStart + 1, end < 0 ? markdown.length : end).trim();
};
const successLooksLike = missionListFromSection(section('Success looks like', 'Constraints'));
return {
topic: title,
problemStatement: section('Why', 'Success looks like'),
expectedOutput: successLooksLike[0] || '',
successEvidence: successLooksLike.slice(1),
constraints: missionListFromSection(section('Constraints', 'Out of scope')),
outOfScope: missionListFromSection(section('Out of scope')),
};
}
function onboardingSnapshot(id, record = reconcileCourseOnboarding(id)) {
const job = readJob(id);
const stage = onboardingGenerationStage(record, job.stage);
const onboarding = publicOnboarding(record);
if (onboarding?.mission && ['ready', 'confirmed'].includes(onboarding.mission.status)) {
const presentation = readMissionPresentation(dirOf(id));
if (presentation) onboarding.mission.presentation = presentation;
try { onboarding.mission.editable = readEditableMission(dirOf(id)); } catch {}
}
return {
id,
onboarding,
generation: {
stage,
runId: stage === 'idle' ? null : job.runId || null,
busy: stage === 'idle' ? false : locks.has(id),
lessons: lessonsOf(id).length,
},
};
}
function sendOnboardingError(res, error) {
const known = error instanceof OnboardingError;
const body = {
error: known ? error.code : 'ONBOARDING_ERROR',
message: known ? error.message : '新手引导操作失败',
};
if (known && error.details) body.details = error.details;
if (known && error.courseId) body.id = error.courseId;
if (known && error.onboarding) body.onboarding = error.onboarding;
return res.status(known ? error.status : 500).json(body);
}
function launchOnboardingGeneration(id, { retry = false } = {}) {
const courseDir = dirOf(id);
let record = reconcileCourseOnboarding(id);
if (!record) throw new OnboardingError('ONBOARDING_NOT_FOUND', '未找到新手引导状态', 404);
if (record.state === 'ready') {
return { status: 200, reused: true, record };
}
if (record.state === 'starting' || record.state === 'generating') {
return { status: 202, reused: true, record };
}
if (locks.has(id)) {
throw new OnboardingError('GENERATION_BUSY', '课程当前有任务正在运行', 409);
}
record = markGenerationStarting(courseDir, { retry });
let run;
try {
const missionSession = readMissionSessionState(courseDir);
run = runKimi(id, FIRST_ONBOARDING_PROMPT(record.source.extension, record.profile), {
track: true,
sessionId: missionSession.sessionId,
preferredMode: missionSession.preferredMode,
});
record = markGenerationRunning(courseDir, readJob(id));
} catch (error) {
markGenerationFailed(courseDir, error);
throw error;
}
Promise.resolve(run)
.then(() => {
if (!firstLessonReadable(id)) {
throw new Error('Kimi finished but the first lesson is not readable');
}
markGenerationReady(courseDir, readJob(id));
})
.catch((error) => {
try { markGenerationFailed(courseDir, error); }
catch (stateError) { console.log(`[onboarding ${id}] failed to persist error: ${stateError.message}`); }
});
return { status: 202, reused: false, record };
}
// 上传一本书 -> 建课
const upload = multer({ dest: os.tmpdir() });
const onboardingUpload = multer({
dest: os.tmpdir(),
limits: { fileSize: MAX_SOURCE_BYTES, files: 1 },
});
app.post('/api/courses', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'missing file' });
const id = Date.now().toString(36);
fs.mkdirSync(dirOf(id), { recursive: true });
const ext = (path.extname(req.file.originalname) || '.txt').toLowerCase();
fs.renameSync(req.file.path, path.join(dirOf(id), 'book' + ext));
fs.writeFileSync(path.join(dirOf(id), 'meta.json'), JSON.stringify({
title: req.body.title || path.basename(req.file.originalname, ext),
}));
runKimi(id, FIRST_PROMPT(ext), { track: true })
.catch((e) => console.log(`[kimi ${id}] failed: ${e.message}`));
res.json({ id });
});
// Multer hands filenames through latin1; recover the original UTF-8 name when
// the re-decoded form is valid, otherwise keep what we got.
function decodeUploadFilename(name) {
const raw = String(name || '');
try {
const decoded = Buffer.from(raw, 'latin1').toString('utf8');
return decoded.includes('\uFFFD') ? raw : decoded;
} catch {
return raw;
}
}
app.post('/api/course-onboarding', (req, res) => {
onboardingUpload.single('file')(req, res, async (uploadError) => {
if (uploadError) {
if (uploadError.code === 'LIMIT_FILE_SIZE') {
return sendOnboardingError(res, new OnboardingError(
'FILE_TOO_LARGE',
'文件超过 200 MB 限制',
413,
{ maxBytes: MAX_SOURCE_BYTES },
));
}
return sendOnboardingError(res, new OnboardingError('UPLOAD_FAILED', '文件上传失败', 400));
}
if (!req.file) {
return sendOnboardingError(res, new OnboardingError('MISSING_FILE', '请选择学习材料', 400));
}
try {
// Deep EPUB validation (mimetype entry) before accepting the draft.
if (/\.epub$/i.test(req.file.originalname || '')) {
await validateEpubArchive(req.file.path);
}
const created = createCourseDraft({
dataRoot: DATA,
tempFile: req.file.path,
originalFilename: decodeUploadFilename(req.file.originalname),
mimeType: req.file.mimetype,
sizeBytes: req.file.size,
title: req.body && req.body.title,
mode: req.body && req.body.mode,
locale: req.body && req.body.locale,
});
launchStandardMissionTurn(created.courseId);
return res.status(202).json({
id: created.courseId,
onboarding: publicOnboarding(readOnboarding(created.courseDir)),
});
} catch (error) {
return sendOnboardingError(res, error);
} finally {
try { if (req.file && fs.existsSync(req.file.path)) fs.unlinkSync(req.file.path); } catch {}
}
});
});
// 课程列表(书架页真实数据)
function sendArtifactError(res, error) {
if (error instanceof ArtifactError || error instanceof ArtifactCritiqueError || error instanceof ActivityValidationError) {
return res.status(error.status || 400).json({
error: error.message,
code: error.code,
...(error.details != null ? { details: error.details } : {}),
});
}
console.log(`[artifact] ${error && error.stack || error}`);
return res.status(500).json({ error: 'Artifact operation failed', code: 'ARTIFACT_INTERNAL_ERROR' });
}
function artifactCourseSnapshot(courseId) {
if (!validId(courseId) || !fs.existsSync(dirOf(courseId))) throw new ArtifactError('COURSE_NOT_FOUND', 'Course not found', 404);
return readMissionPresentation(dirOf(courseId));
}
if (POL_V2_ENABLED) {
app.get('/api/artifacts', (req, res) => {
try {
const status = String(req.query.status || '').trim();
if (status && !['all', 'active', 'delivered', 'archived', 'draft', 'revising', 'ready', 'waiting_for_source', 'waiting_for_mission'].includes(status)) {
throw new ArtifactError('ARTIFACT_STATUS_INVALID', 'Invalid artifact status filter', 400);
}
return res.json({ artifacts: artifactStore.list({ status }).map(artifactStore.metadata) });
} catch (error) { return sendArtifactError(res, error); }
});
app.post('/api/artifacts', (req, res) => {
try {
const input = { ...(req.body || {}) };
if (input.primaryCourseId) input.missionSnapshot = artifactCourseSnapshot(String(input.primaryCourseId));
const artifact = artifactStore.create(input);
return res.status(201).json({ artifact });
} catch (error) { return sendArtifactError(res, error); }
});
app.get('/api/artifacts/:id', (req, res) => {
try {
const result = artifactStore.get(req.params.id);
let events = [];
if (result.artifact.primaryCourseId && fs.existsSync(dirOf(result.artifact.primaryCourseId))) {
events = readCourseActivity(result.artifact.primaryCourseId)
.filter((event) => event.artifactId === result.artifact.id)
.slice(-100);
}
return res.json({ ...result, events });
} catch (error) { return sendArtifactError(res, error); }
});
app.put('/api/artifacts/:id/draft', (req, res) => {
try {
const artifact = artifactStore.saveDraft(req.params.id, req.body || {});
return res.json({ ok: true, draftVersion: artifact.draftVersion, updatedAt: artifact.updatedAt });
} catch (error) { return sendArtifactError(res, error); }
});
app.post('/api/artifacts/:id/checkpoints', (req, res) => {
try {
const result = artifactStore.createCheckpoint(req.params.id, req.body || {});
if (result.artifact.primaryCourseId) {
appendCourseActivity(dirOf(result.artifact.primaryCourseId), {
type: 'artifact-revision',
artifactId: result.artifact.id,
revisionId: result.revision.id,
parentRevisionId: result.revision.parentRevisionId,
trigger: result.revision.trigger,
acceptedCritiqueIds: req.body && req.body.acceptedCritiqueIds,
rejectedCritiqueIds: req.body && req.body.rejectedCritiqueIds,
resolvedGapIds: req.body && req.body.resolvedGapIds,
});
}
return res.status(201).json({ revisionId: result.revision.id, sha256: result.revision.sha256 });
} catch (error) { return sendArtifactError(res, error); }
});
app.post('/api/artifacts/:id/link-course', (req, res) => {
try {
const courseId = String(req.body && req.body.courseId || '').trim();
const missionSnapshot = artifactCourseSnapshot(courseId);
const artifact = artifactStore.linkCourse(req.params.id, { courseId, missionSnapshot });
return res.json({ artifact });
} catch (error) { return sendArtifactError(res, error); }
});
app.post('/api/artifacts/:id/status', (req, res) => {
try {
const artifact = artifactStore.updateStatus(req.params.id, req.body && req.body.status);
return res.json({ artifact });
} catch (error) { return sendArtifactError(res, error); }
});
app.post('/api/artifacts/:id/critique', async (req, res) => {