@thanh01.pmt/curriculum-kit 1.4.10 → 1.4.12

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/dist/index.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var fs2 = require('fs');
4
4
  var path3 = require('path');
5
+ var jsonrepair = require('jsonrepair');
5
6
  var zod = require('zod');
6
7
  var google = require('@ai-sdk/google');
7
8
  var openai = require('@ai-sdk/openai');
@@ -12,7 +13,6 @@ var fsPromises = require('fs/promises');
12
13
  var crypto = require('crypto');
13
14
  var supabaseJs = require('@supabase/supabase-js');
14
15
  var url = require('url');
15
- var jsonrepair = require('jsonrepair');
16
16
  var rest = require('@octokit/rest');
17
17
 
18
18
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -1174,6 +1174,488 @@ var init_artifactLinter = __esm({
1174
1174
  "src/pipeline/artifactLinter.ts"() {
1175
1175
  }
1176
1176
  });
1177
+
1178
+ // src/parsers/lessonFlowParser.ts
1179
+ function parseLessonFlow(lessonMarkdown) {
1180
+ const result = {
1181
+ lessonId: "",
1182
+ lessonTitle: "",
1183
+ pedagogicalModel: "5e",
1184
+ estimatedDuration: "90 mins",
1185
+ activities: [],
1186
+ phases: [],
1187
+ rawContent: lessonMarkdown
1188
+ };
1189
+ if (!lessonMarkdown || typeof lessonMarkdown !== "string") {
1190
+ return result;
1191
+ }
1192
+ const fmMatch = lessonMarkdown.match(/^---\s*\n([\s\S]*?)\n---/);
1193
+ if (fmMatch) {
1194
+ const fm = fmMatch[1];
1195
+ const idMatch = fm.match(/id:\s*["']?([^"'\n]+)["']?/i);
1196
+ if (idMatch) result.lessonId = idMatch[1].trim();
1197
+ const titleMatch = fm.match(/title:\s*["']?([^"'\n]+)["']?/i);
1198
+ if (titleMatch) result.lessonTitle = titleMatch[1].trim();
1199
+ const typeMatch = fm.match(/type:\s*["']?([^"'\n]+)["']?/i);
1200
+ if (typeMatch) {
1201
+ const t = typeMatch[1].toLowerCase();
1202
+ if (t.includes("edp")) result.pedagogicalModel = "edp";
1203
+ else if (t.includes("pbl")) result.pedagogicalModel = "pbl";
1204
+ else if (t.includes("cra")) result.pedagogicalModel = "cra";
1205
+ else if (t.includes("5e")) result.pedagogicalModel = "5e";
1206
+ else result.pedagogicalModel = typeMatch[1].trim();
1207
+ }
1208
+ }
1209
+ const durMatch = lessonMarkdown.match(/Estimated Duration:\s*([^\n]+)/i);
1210
+ if (durMatch) result.estimatedDuration = durMatch[1].trim();
1211
+ const contractMatch = lessonMarkdown.match(/SLIDE must visualize:?\s*([^\n]+)/i);
1212
+ if (contractMatch) result.slideContract = contractMatch[1].trim();
1213
+ const actSeqSectionMatch = lessonMarkdown.match(/###\s*(?:\d+\.\s*)?Activity Sequence[\s\S]*?(?=(?:###|\n##\s+|$))/i);
1214
+ if (actSeqSectionMatch) {
1215
+ const tableText = actSeqSectionMatch[0];
1216
+ const lines = tableText.split("\n");
1217
+ let inTable = false;
1218
+ let headerParsed = false;
1219
+ for (const line of lines) {
1220
+ const trimmed = line.trim();
1221
+ if (trimmed.startsWith("|") && trimmed.endsWith("|")) {
1222
+ if (!inTable) {
1223
+ inTable = true;
1224
+ continue;
1225
+ }
1226
+ if (trimmed.includes("---")) {
1227
+ headerParsed = true;
1228
+ continue;
1229
+ }
1230
+ if (headerParsed) {
1231
+ const cells = trimmed.split("|").map((c) => c.trim()).filter((_, idx, arr) => idx > 0 && idx < arr.length - 1);
1232
+ if (cells.length >= 7) {
1233
+ const seqNum = parseInt(cells[0], 10) || result.activities.length + 1;
1234
+ result.activities.push({
1235
+ seq: seqNum,
1236
+ phase: cells[1] || `Phase ${seqNum}`,
1237
+ activityType: cells[2] || "",
1238
+ actor: cells[3] || "",
1239
+ purpose: cells[4] || "",
1240
+ studentAction: cells[5] || "",
1241
+ teacherMove: cells[6] || "",
1242
+ time: cells[9] || cells[cells.length - 2] || "",
1243
+ artifactContract: cells[cells.length - 1] || ""
1244
+ });
1245
+ }
1246
+ }
1247
+ } else if (inTable && trimmed.length > 0 && !trimmed.startsWith(">")) {
1248
+ inTable = false;
1249
+ }
1250
+ }
1251
+ }
1252
+ const flowMatch = lessonMarkdown.match(/##\s*\[?REQUIRED\]?\s*B\.\s*Lesson Flow([\s\S]*?)$/i);
1253
+ const flowSection = flowMatch ? flowMatch[1] : lessonMarkdown;
1254
+ const phaseRegex = /###\s*(?:(\d+)\.\s*)?([^\n—\-]+)(?:[—\-]\s*\[?([^\]\n]+)\]?)?\s*\n([\s\S]*?)(?=(?:###\s*(?:\d+\.)?|$))/gi;
1255
+ let pMatch;
1256
+ while ((pMatch = phaseRegex.exec(flowSection)) !== null) {
1257
+ const rawPhaseName = pMatch[2].trim();
1258
+ const timing = pMatch[3]?.trim();
1259
+ const content = pMatch[4].trim();
1260
+ const codeSnippets = [];
1261
+ const codeRegex = /```(?:[a-zA-Z0-9_\-]+)?\s*\n([\s\S]*?)```/g;
1262
+ let cMatch;
1263
+ while ((cMatch = codeRegex.exec(content)) !== null) {
1264
+ if (!cMatch[1].includes("graph TD") && !cMatch[1].includes("graph LR")) {
1265
+ codeSnippets.push(cMatch[1].trim());
1266
+ }
1267
+ }
1268
+ const mermaidDiagrams = [];
1269
+ const mermaidRegex = /```mermaid\s*\n([\s\S]*?)```/g;
1270
+ let mMatch;
1271
+ while ((mMatch = mermaidRegex.exec(content)) !== null) {
1272
+ mermaidDiagrams.push(mMatch[1].trim());
1273
+ }
1274
+ result.phases.push({
1275
+ phaseName: rawPhaseName,
1276
+ title: rawPhaseName,
1277
+ timing,
1278
+ content,
1279
+ codeSnippets,
1280
+ mermaidDiagrams
1281
+ });
1282
+ }
1283
+ return result;
1284
+ }
1285
+ var init_lessonFlowParser = __esm({
1286
+ "src/parsers/lessonFlowParser.ts"() {
1287
+ }
1288
+ });
1289
+
1290
+ // src/ai/prompts/slideBlueprintPrompt.ts
1291
+ function buildSlideBlueprintPrompt(params) {
1292
+ const { lessonFlow, targetSlideCount = 20, stylePresetName = "Blue Professional" } = params;
1293
+ const activitiesSummary = lessonFlow.activities.map(
1294
+ (a) => `Seq ${a.seq} [${a.phase}]: ${a.purpose} (Teacher: ${a.teacherMove} | Student: ${a.studentAction} | Time: ${a.time})`
1295
+ ).join("\n");
1296
+ const phasesSummary = lessonFlow.phases.map(
1297
+ (p) => `Phase "${p.phaseName}" (${p.timing || "Standard"}):
1298
+ ${p.content.slice(0, 500)}...`
1299
+ ).join("\n\n");
1300
+ return `
1301
+ You are @illustrator, Chief Slide Architect for the Course Builder OS.
1302
+ Your task is to analyze the canonical LESSON plan and architect an authoritative, high-fidelity **SLIDE BLUEPRINT** of EXACTLY ${targetSlideCount} slides.
1303
+
1304
+ ### \u{1F3DB}\uFE0F PEDAGOGICAL GROUND TRUTH (FROM CANONICAL LESSON):
1305
+ - Lesson Title: "${lessonFlow.lessonTitle}"
1306
+ - Pedagogical Framework: "${lessonFlow.pedagogicalModel.toUpperCase()}"
1307
+ - Target Duration: ${lessonFlow.estimatedDuration}
1308
+ - Active Visual Style: "${stylePresetName}"
1309
+ ${lessonFlow.slideContract ? `- Slide Artifact Contract: "${lessonFlow.slideContract}"` : ""}
1310
+
1311
+ ### \u{1F5FA}\uFE0F CANONICAL ACTIVITY SEQUENCE:
1312
+ ${activitiesSummary || "Standard phased sequence"}
1313
+
1314
+ ### \u{1F4D6} LESSON FLOW EXCERPT:
1315
+ ${phasesSummary || lessonFlow.rawContent.slice(0, 3e3)}
1316
+
1317
+ ---
1318
+
1319
+ ### \u{1F3AF} ARCHITECTURAL RULES (STRICTLY INVARIANT):
1320
+ 1. **PEDAGOGICAL FIDELITY (1-TO-1 PROJECTION)**:
1321
+ - The slide sequence MUST follow the EXACT flow of the LESSON phases (${lessonFlow.pedagogicalModel.toUpperCase()}).
1322
+ - Do NOT invent artificial phases that do not exist in the lesson plan.
1323
+ - For example:
1324
+ * If 5E: Engage (slides 1-4) -> Explore (slides 5-8) -> Explain (slides 9-13) -> Elaborate (slides 14-17) -> Evaluate (slides 18-20).
1325
+ * If EDP: Ask/Problem (slides 1-4) -> Imagine & Plan (slides 5-8) -> Create & Prototype (slides 9-14) -> Test & Debug (slides 15-17) -> Improve & Share (slides 18-20).
1326
+ * If PBL: Driving Question (slides 1-4) -> Inquiry (slides 5-9) -> Milestone Sprint (slides 10-15) -> Review & Exhibition (slides 16-20).
1327
+
1328
+ 2. **CHUNKY CLUSTERS (3 TO 4 CLUSTERS)**:
1329
+ - Group the ${targetSlideCount} slides into 3 to 4 natural clusters (each cluster contains 4 to 6 slides).
1330
+ - Each cluster corresponds to a major pedagogical transition in the lesson.
1331
+
1332
+ 3. **SEMANTIC LAYOUT SLOTS (CHOOSE FROM VERIFIED TEMPLATES)**:
1333
+ Use one of these valid layoutIds for each slide:
1334
+ - \`hero-cover\`: Title, subtitle, topic badge, metadata.
1335
+ - \`split-concept-code\`: Left side explanation/bullets, right side prominent code card or diagram.
1336
+ - \`two-columns-compare\`: Side-by-side comparison (Before vs After, Scratch vs Swift, Theory vs Practice).
1337
+ - \`three-cards-grid\`: 3 architectural pillars, components, or principles.
1338
+ - \`timeline-steps\`: Step-by-step workflow, pipeline sequence, or execution trace.
1339
+ - \`metric-callout\`: High-impact statistical or performance highlight.
1340
+ - \`checkpoint-quiz\`: Formative diagnostic question with multiple choice.
1341
+ - \`tiered-practice-3cards\`: Bronze, Silver, Gold hands-on challenge specs.
1342
+ - \`summary-takeaways\`: Final recap, key rules, and next milestone.
1343
+
1344
+ ---
1345
+
1346
+ ### \u{1F4E4} OUTPUT FORMAT:
1347
+ Output ONLY a valid JSON array of ${targetSlideCount} objects. Do NOT include markdown text outside the JSON.
1348
+ Format:
1349
+ \`\`\`json
1350
+ [
1351
+ {
1352
+ "slideIndex": 1,
1353
+ "clusterId": 1,
1354
+ "clusterTitle": "Opening & Hook",
1355
+ "lessonPhase": "Engage",
1356
+ "layoutId": "hero-cover",
1357
+ "title": "Title of Slide 1",
1358
+ "pedagogicalGoal": "Specific learning goal of this slide",
1359
+ "contentFocus": ["Bullet 1 focus", "Bullet 2 focus"],
1360
+ "codeSnippetIntent": "Description of code snippet to show, if any",
1361
+ "visualIntent": "Description of visual diagram to display, if any"
1362
+ }
1363
+ ]
1364
+ \`\`\`
1365
+ `.trim();
1366
+ }
1367
+ var init_slideBlueprintPrompt = __esm({
1368
+ "src/ai/prompts/slideBlueprintPrompt.ts"() {
1369
+ }
1370
+ });
1371
+
1372
+ // src/ai/prompts/slideBatchPrompt.ts
1373
+ function buildSlideBatchPrompt(params) {
1374
+ const {
1375
+ clusterId,
1376
+ clusterTitle,
1377
+ clusterSlides,
1378
+ lessonFlow,
1379
+ lessonExcerpt,
1380
+ skillPrompt,
1381
+ language = "Vietnamese",
1382
+ languageDirective = "",
1383
+ headingDirective = ""
1384
+ } = params;
1385
+ const slidesSpec = clusterSlides.map((s) => `
1386
+ - Slide ${s.slideIndex} [Phase: ${s.lessonPhase}] -> Layout: "${s.layoutId}"
1387
+ Title: "${s.title}"
1388
+ Pedagogical Goal: ${s.pedagogicalGoal}
1389
+ Key Bullet Targets: ${s.contentFocus.join("; ")}
1390
+ ${s.codeSnippetIntent ? `Code Focus: ${s.codeSnippetIntent}` : ""}
1391
+ ${s.visualIntent ? `Visual Focus: ${s.visualIntent}` : ""}
1392
+ `).join("\n");
1393
+ const systemPrompt = `
1394
+ ${skillPrompt}
1395
+
1396
+ ---
1397
+ ### OPERATIONAL GROUND RULES FOR CHUNK GENERATION:
1398
+ ${languageDirective}
1399
+ ${headingDirective}
1400
+ 1. **FOCUS ON CLUSTER ${clusterId}: "${clusterTitle}"**:
1401
+ Generate EXACTLY the ${clusterSlides.length} slides requested in the user prompt.
1402
+ 2. **ZERO ABBREVIATION / NO "// TODO"**:
1403
+ All code snippets MUST be real, fully authored, compilable code relevant to ${lessonFlow.lessonTitle}. Never write placeholders, stubs, or "<CODE>".
1404
+ 3. **MANDATORY 3-PART PRESENTER NOTES ON EVERY SLIDE**:
1405
+ Every slide object MUST have a "notes" field formatted with:
1406
+ - SCRIPT: 60-90s spoken teacher talk track with an intuitive analogy.
1407
+ - COLD CALL / CHECK: One targeted question to check for student understanding.
1408
+ - SCAFFOLDING / GOTCHA: One common misconception or bug to watch out for.
1409
+ 4. **OUTPUT FORMAT**:
1410
+ Output ONLY a valid JSON array of ${clusterSlides.length} slide objects.
1411
+ `.trim();
1412
+ const userPrompt = `
1413
+ ### LESSON GROUND TRUTH:
1414
+ - Lesson Title: "${lessonFlow.lessonTitle}"
1415
+ - Target Duration: ${lessonFlow.estimatedDuration}
1416
+ - Pedagogy: "${lessonFlow.pedagogicalModel.toUpperCase()}"
1417
+ - Language: "${language}"
1418
+
1419
+ ### LESSON PHASE CONTENT (SOURCE OF TRUTH):
1420
+ ${lessonExcerpt || lessonFlow.rawContent.slice(0, 4e3)}
1421
+
1422
+ ---
1423
+
1424
+ ### REQUIRED SLIDES TO GENERATE FOR THIS CLUSTER:
1425
+ ${slidesSpec}
1426
+
1427
+ ---
1428
+
1429
+ ### OUTPUT SCHEMA:
1430
+ Output a single JSON array of slide objects strictly matching the layout slots:
1431
+ \`\`\`json
1432
+ [
1433
+ {
1434
+ "id": "slide-${clusterSlides[0]?.slideIndex || 1}",
1435
+ "layoutId": "${clusterSlides[0]?.layoutId || "split-concept-code"}",
1436
+ "title": "${clusterSlides[0]?.title || "Slide Title"}",
1437
+ "slots": {
1438
+ "lead": "One clear, punchy subtitle or thesis statement",
1439
+ "bullets": [
1440
+ "First key insight (8-12 words max)",
1441
+ "Second key insight (8-12 words max)",
1442
+ "Third key insight (8-12 words max)"
1443
+ ],
1444
+ "code": "// Executable code here",
1445
+ "codeLanguage": "swift",
1446
+ "codeHighlight": "1-3",
1447
+ "card1Title": "...",
1448
+ "card1Desc": "..."
1449
+ },
1450
+ "notes": "SCRIPT: ...\\nCOLD CALL: ...\\nSCAFFOLDING: ..."
1451
+ }
1452
+ ]
1453
+ \`\`\`
1454
+ `.trim();
1455
+ return { systemPrompt, userPrompt };
1456
+ }
1457
+ var init_slideBatchPrompt = __esm({
1458
+ "src/ai/prompts/slideBatchPrompt.ts"() {
1459
+ }
1460
+ });
1461
+
1462
+ // src/services/slideProductionWorkflow.ts
1463
+ var slideProductionWorkflow_exports = {};
1464
+ __export(slideProductionWorkflow_exports, {
1465
+ executeSlideProductionWorkflow: () => executeSlideProductionWorkflow
1466
+ });
1467
+ function extractCleanJson(raw) {
1468
+ const fenceMatch = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
1469
+ const candidate = fenceMatch ? fenceMatch[1] : raw;
1470
+ return candidate.trim();
1471
+ }
1472
+ async function executeSlideProductionWorkflow(options) {
1473
+ const {
1474
+ lessonMarkdown,
1475
+ lessonCode,
1476
+ lessonTitle,
1477
+ targetSlideCount = 20,
1478
+ stylePresetId = "blue-professional",
1479
+ language = "Vietnamese",
1480
+ languageDirective = "",
1481
+ headingDirective = "",
1482
+ satelliteContext,
1483
+ runnerOptions,
1484
+ onProgress
1485
+ } = options;
1486
+ let presentationKitSkills = null;
1487
+ let presentationKitCore = null;
1488
+ try {
1489
+ presentationKitSkills = await import('@thanh01.pmt/presentation-kit/skills');
1490
+ } catch {
1491
+ }
1492
+ try {
1493
+ presentationKitCore = await import('@thanh01.pmt/presentation-kit');
1494
+ } catch {
1495
+ }
1496
+ onProgress?.("@illustrator", `[1/4] Ph\xE2n t\xEDch m\u1EA1ch b\xE0i gi\u1EA3ng LESSON & L\u1EADp D\xE0n \xFD ${targetSlideCount} Slides...`);
1497
+ const lessonFlow = parseLessonFlow(lessonMarkdown);
1498
+ const stylePreset = presentationKitSkills?.getStylePreset ? presentationKitSkills.getStylePreset(stylePresetId) : { name: "Blue Professional" };
1499
+ const blueprintPrompt = buildSlideBlueprintPrompt({
1500
+ lessonFlow,
1501
+ targetSlideCount,
1502
+ stylePresetName: stylePreset?.name || "Blue Professional"
1503
+ });
1504
+ const rawBlueprint = await runCurriculumAIInference(
1505
+ [{ role: "user", content: blueprintPrompt }],
1506
+ satelliteContext,
1507
+ runnerOptions,
1508
+ (chunk, type) => {
1509
+ onProgress?.("@illustrator", chunk, { type: type || "content", artifactType: "SLIDE" });
1510
+ }
1511
+ );
1512
+ let blueprintItems = [];
1513
+ try {
1514
+ blueprintItems = JSON.parse(extractCleanJson(rawBlueprint));
1515
+ } catch {
1516
+ try {
1517
+ blueprintItems = JSON.parse(jsonrepair.jsonrepair(extractCleanJson(rawBlueprint)));
1518
+ } catch (e) {
1519
+ console.warn(`[SlideProductionWorkflow] Failed parsing blueprint JSON, constructing fallback:`, e);
1520
+ blueprintItems = Array.from({ length: targetSlideCount }, (_, i) => ({
1521
+ slideIndex: i + 1,
1522
+ clusterId: Math.floor(i / 5) + 1,
1523
+ clusterTitle: `Cluster ${Math.floor(i / 5) + 1}`,
1524
+ lessonPhase: lessonFlow.phases[Math.min(i, lessonFlow.phases.length - 1)]?.phaseName || "Content",
1525
+ layoutId: i === 0 ? "hero-cover" : i === targetSlideCount - 1 ? "summary-takeaways" : "split-concept-code",
1526
+ title: `Slide ${i + 1}: ${lessonTitle}`,
1527
+ pedagogicalGoal: `Teach step ${i + 1} of ${lessonTitle}`,
1528
+ contentFocus: ["Key point 1", "Key point 2", "Key point 3"]
1529
+ }));
1530
+ }
1531
+ }
1532
+ const clustersMap = /* @__PURE__ */ new Map();
1533
+ for (const item of blueprintItems) {
1534
+ const cId = item.clusterId || Math.floor((item.slideIndex - 1) / 5) + 1;
1535
+ if (!clustersMap.has(cId)) clustersMap.set(cId, []);
1536
+ clustersMap.get(cId).push(item);
1537
+ }
1538
+ const clusters = Array.from(clustersMap.entries()).sort(([a], [b]) => a - b);
1539
+ const allGeneratedSlides = [];
1540
+ const skillPrompt = presentationKitSkills?.getFrontendSlidesSkillPrompt ? presentationKitSkills.getFrontendSlidesSkillPrompt({ stylePresetId }) : "";
1541
+ let clusterIdx = 0;
1542
+ for (const [cId, clusterSlides] of clusters) {
1543
+ clusterIdx++;
1544
+ const clusterTitle = clusterSlides[0]?.clusterTitle || `Giai \u0111o\u1EA1n ${clusterIdx}`;
1545
+ onProgress?.("@illustrator", `[2/4] Sinh chi ti\u1EBFt C\u1EE5m ${clusterIdx}/${clusters.length}: "${clusterTitle}" (${clusterSlides.length} slides)...`);
1546
+ const clusterPhaseNames = new Set(clusterSlides.map((s) => s.lessonPhase.toLowerCase()));
1547
+ const matchingPhases = lessonFlow.phases.filter(
1548
+ (p) => clusterPhaseNames.has(p.phaseName.toLowerCase())
1549
+ );
1550
+ const lessonExcerpt = matchingPhases.length > 0 ? matchingPhases.map((p) => `### ${p.phaseName}
1551
+ ${p.content}`).join("\n\n") : lessonFlow.rawContent.slice(0, 3500);
1552
+ const { systemPrompt, userPrompt } = buildSlideBatchPrompt({
1553
+ clusterId: cId,
1554
+ clusterTitle,
1555
+ clusterSlides,
1556
+ lessonFlow,
1557
+ lessonExcerpt,
1558
+ skillPrompt,
1559
+ language,
1560
+ languageDirective,
1561
+ headingDirective
1562
+ });
1563
+ const rawBatch = await runCurriculumAIInference(
1564
+ [
1565
+ { role: "system", content: systemPrompt },
1566
+ { role: "user", content: userPrompt }
1567
+ ],
1568
+ satelliteContext,
1569
+ runnerOptions,
1570
+ (chunk, type) => {
1571
+ onProgress?.("@illustrator", chunk, { type: type || "content", artifactType: "SLIDE" });
1572
+ }
1573
+ );
1574
+ let batchSlides = [];
1575
+ try {
1576
+ batchSlides = JSON.parse(extractCleanJson(rawBatch));
1577
+ } catch {
1578
+ try {
1579
+ batchSlides = JSON.parse(jsonrepair.jsonrepair(extractCleanJson(rawBatch)));
1580
+ } catch (err) {
1581
+ console.warn(`[SlideProductionWorkflow] Batch ${cId} JSON parse failed, synthesizing slides:`, err);
1582
+ batchSlides = clusterSlides.map((s) => ({
1583
+ id: `slide-${s.slideIndex}`,
1584
+ layoutId: s.layoutId,
1585
+ title: s.title,
1586
+ slots: {
1587
+ lead: s.pedagogicalGoal,
1588
+ bullets: s.contentFocus,
1589
+ code: s.codeSnippetIntent || "// Executable demo code"
1590
+ },
1591
+ notes: `SCRIPT: Spoken explanation for ${s.title}.
1592
+ COLD CALL: What happens when this logic runs?
1593
+ SCAFFOLDING: Ensure proper syntax and indentation.`
1594
+ }));
1595
+ }
1596
+ }
1597
+ if (Array.isArray(batchSlides)) {
1598
+ allGeneratedSlides.push(...batchSlides);
1599
+ }
1600
+ }
1601
+ onProgress?.("@illustrator", `[3/4] Chu\u1EA9n h\xF3a b\u1ED1 c\u1EE5c v\xE0 bi\xEAn d\u1ECBch 1920\xD71080 Stage Deck (${allGeneratedSlides.length} slides)...`);
1602
+ const normalizer = presentationKitCore?.normalizeSlideSlots;
1603
+ const normalizedSlides = allGeneratedSlides.map((s, idx) => {
1604
+ const base = normalizer ? normalizer(s) : s;
1605
+ if (!base.id) base.id = `slide-${idx + 1}`;
1606
+ return base;
1607
+ });
1608
+ const deckJson = {
1609
+ id: `deck-${lessonCode}`,
1610
+ title: lessonTitle,
1611
+ theme: stylePresetId,
1612
+ slides: normalizedSlides
1613
+ };
1614
+ let compiledHtml;
1615
+ const compiler = presentationKitCore?.compileHtmlDeck;
1616
+ if (compiler) {
1617
+ try {
1618
+ const compiled = compiler(deckJson);
1619
+ if (compiled?.html) {
1620
+ compiledHtml = compiled.html;
1621
+ }
1622
+ } catch (compErr) {
1623
+ console.warn(`[SlideProductionWorkflow] Failed compiling HTML deck:`, compErr);
1624
+ }
1625
+ }
1626
+ const markdownWrapper = `---
1627
+ id: "SLIDE_${lessonCode}"
1628
+ title: "${lessonTitle}"
1629
+ type: "SLIDE"
1630
+ format: "html-deck"
1631
+ engine: "html"
1632
+ phase: "P2"
1633
+ deliverable: "P2-T09"
1634
+ version: "v2.0"
1635
+ date: "${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}"
1636
+ ---
1637
+
1638
+ \`\`\`json
1639
+ ${JSON.stringify(deckJson, null, 2)}
1640
+ \`\`\`
1641
+ `;
1642
+ onProgress?.("@illustrator", `[4/4] Ho\xE0n t\u1EA5t b\u1ED9 tr\xECnh chi\u1EBFu HTML 20 trang \u0111\u1EA1t chu\u1EA9n Fixed 16:9 Stage!`);
1643
+ return {
1644
+ deckJson,
1645
+ compiledHtml,
1646
+ markdownWrapper,
1647
+ blueprint: blueprintItems,
1648
+ slideCount: normalizedSlides.length
1649
+ };
1650
+ }
1651
+ var init_slideProductionWorkflow = __esm({
1652
+ "src/services/slideProductionWorkflow.ts"() {
1653
+ init_lessonFlowParser();
1654
+ init_slideBlueprintPrompt();
1655
+ init_slideBatchPrompt();
1656
+ init_streamRunner();
1657
+ }
1658
+ });
1177
1659
  var LearningObjectiveRowSchema = zod.z.object({
1178
1660
  code: zod.z.string().describe('LO code, e.g. "LO1"'),
1179
1661
  objective: zod.z.string().describe("Bloom-tagged learning objective"),
@@ -5459,6 +5941,11 @@ Every slide MUST include notes with:
5459
5941
  - Cold-Call: 1 check question
5460
5942
  - Scaffolding Tip: 1 analogy or hint
5461
5943
 
5944
+ ### \u26A0\uFE0F STRICT SLIDE FORMATTING INVARIANTS:
5945
+ 1. Every slide MUST store its content fields inside "slots": { ... }. NEVER put "title", "content", or points at the top level of a slide!
5946
+ 2. All code slots MUST contain real, executable, high-fidelity code. Never use placeholders like "<CODE>" or "...".
5947
+ 3. All point and card slots MUST contain concrete, rich pedagogical explanations. Never use placeholder dots or empty cards.
5948
+
5462
5949
  ### Output JSON Format:
5463
5950
  \`\`\`json
5464
5951
  {
@@ -25326,106 +25813,44 @@ ${buildHeadingDirective("QUIZ", slcMarkdown, targetLang)}`;
25326
25813
  const isHtmlEngine = options.slidesEngine === "html";
25327
25814
  if (isHtmlEngine) {
25328
25815
  let presentationKitAi = null;
25816
+ let presentationKitCore = null;
25329
25817
  try {
25330
25818
  presentationKitAi = await import('@thanh01.pmt/presentation-kit/ai');
25331
25819
  } catch {
25332
25820
  }
25333
- const slidePrompt = buildHtmlDeckSlidePrompt({
25821
+ try {
25822
+ presentationKitCore = await import('@thanh01.pmt/presentation-kit');
25823
+ } catch {
25824
+ }
25825
+ const { executeSlideProductionWorkflow: executeSlideProductionWorkflow2 } = await Promise.resolve().then(() => (init_slideProductionWorkflow(), slideProductionWorkflow_exports));
25826
+ const workflowResult = await executeSlideProductionWorkflow2({
25827
+ lessonMarkdown: lessonContent || "",
25334
25828
  lessonCode,
25335
25829
  lessonTitle,
25336
- pedagogyLabel,
25830
+ targetSlideCount: 20,
25831
+ stylePresetId: "blue-professional",
25832
+ language: targetLang || "Vietnamese",
25337
25833
  languageDirective,
25338
25834
  headingDirective: buildHeadingDirective("SLIDE", slcMarkdown, targetLang),
25339
- glossaryBlock: glossaryContext ? `[GLOSSARY TERMS (use these exact definitions)]:
25340
- ${glossaryContext}` : void 0,
25341
- customContract: presentationKitAi?.SLIDE_HTML_PROMPT_CONTRACT
25342
- });
25343
- const rawSlide = await runCurriculumAIInference(
25344
- [{ role: "user", content: slidePrompt }],
25345
25835
  satelliteContext,
25346
25836
  runnerOptions,
25347
- (chunk, type) => {
25348
- options.onProgress?.("@illustrator", chunk, { type: type || "content", artifactType: "SLIDE" });
25349
- }
25350
- );
25351
- if (!rawSlide || rawSlide.startsWith("\u26A0\uFE0F") || rawSlide.length < 200) {
25352
- throw createAiInferenceError({
25353
- errorCode: "ERR_AI_RESPONSE_MALFORMED",
25354
- agent: "@illustrator",
25355
- artifactType: "SLIDE",
25356
- lessonId: lessonCode,
25357
- message: `Agent @illustrator failed to author valid HTML Slides for ${lessonCode}.`,
25358
- rawError: rawSlide || "Empty AI response"
25359
- });
25360
- }
25361
- let deckJson = null;
25362
- const extractCleanJson = (str) => {
25363
- const fenceMatch = str.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
25364
- const candidate = fenceMatch ? fenceMatch[1] : str;
25365
- return candidate.trim();
25366
- };
25367
- try {
25368
- deckJson = JSON.parse(extractCleanJson(rawSlide));
25369
- } catch {
25370
- try {
25371
- const { jsonrepair: jsonrepair2 } = await import('jsonrepair');
25372
- deckJson = JSON.parse(jsonrepair2(extractCleanJson(rawSlide)));
25373
- } catch {
25374
- }
25375
- }
25376
- let validation = presentationKitAi?.validateHtmlSlideDeck ? presentationKitAi.validateHtmlSlideDeck(deckJson, true) : deckJson && Array.isArray(deckJson.slides) ? { valid: true, score: 95, issues: [], slideCount: deckJson.slides.length, notesCoveragePercent: 100 } : { valid: false, score: 0, issues: [{ message: "Malformed JSON slide deck" }], slideCount: 0, notesCoveragePercent: 0 };
25377
- if (!validation.valid && presentationKitAi?.validateHtmlSlideDeck) {
25378
- const repairIssues = (validation.issues || []).map((i) => `- Slide ${i.slideIndex ?? "?"}: ${i.message}`).join("\n");
25379
- onProgress?.("@illustrator", `\u26A0\uFE0F HTML slide deck failed schema validation \u2014 retrying once with targeted repair feedback...`);
25380
- const repairPrompt = `Your previous slide deck failed strict schema validation:
25381
- ${repairIssues}
25382
-
25383
- Fix ALL issues and output the complete corrected JSON object strictly matching the schema:`;
25384
- const repairedRaw = await runCurriculumAIInference(
25385
- [{ role: "user", content: repairPrompt }],
25386
- satelliteContext,
25387
- runnerOptions,
25388
- (chunk, type) => {
25389
- options.onProgress?.("@illustrator", chunk, { type: type || "content", artifactType: "SLIDE" });
25390
- }
25391
- );
25392
- try {
25393
- deckJson = JSON.parse(extractCleanJson(repairedRaw));
25394
- validation = presentationKitAi.validateHtmlSlideDeck(deckJson, true);
25395
- } catch {
25396
- try {
25397
- const { jsonrepair: jsonrepair2 } = await import('jsonrepair');
25398
- deckJson = JSON.parse(jsonrepair2(extractCleanJson(repairedRaw)));
25399
- validation = presentationKitAi.validateHtmlSlideDeck(deckJson, true);
25400
- } catch {
25401
- }
25837
+ onProgress: (agent, msg, meta) => {
25838
+ options.onProgress?.(agent, msg, meta || { type: "content", artifactType: "SLIDE" });
25402
25839
  }
25403
- }
25404
- const markdownWrapper = `---
25405
- id: "SLIDE_${lessonCode}"
25406
- title: "${titleHeader(lessonTitle)}"
25407
- type: "SLIDE"
25408
- format: "html-deck"
25409
- engine: "html"
25410
- phase: "P2"
25411
- deliverable: "P2-T09"
25412
- version: "v1.0"
25413
- date: "${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}"
25414
- ---
25415
-
25416
- \`\`\`json
25417
- ${JSON.stringify(deckJson || {}, null, 2)}
25418
- \`\`\`
25419
- `;
25840
+ });
25841
+ let deckJson = workflowResult.deckJson;
25842
+ const markdownWrapper = workflowResult.markdownWrapper;
25843
+ let validation = presentationKitAi?.validateHtmlSlideDeck ? presentationKitAi.validateHtmlSlideDeck(deckJson, true) : deckJson && Array.isArray(deckJson.slides) ? { valid: true, score: 95, issues: [], slideCount: deckJson.slides.length} : { valid: false, score: 0, issues: [{ message: "Malformed JSON slide deck" }], slideCount: 0};
25420
25844
  await storage.saveArtifact(projectId, slideRelPath, markdownWrapper);
25421
25845
  producedArtifacts.push(`SLIDE_${lessonCode}.md`);
25422
25846
  if (deckJson) {
25423
25847
  const deckJsonStr = JSON.stringify(deckJson, null, 2);
25424
25848
  await storage.saveArtifact(projectId, `_content/${unitCode}/SLIDE_${lessonCode}.deck.json`, deckJsonStr);
25425
25849
  producedArtifacts.push(`SLIDE_${lessonCode}.deck.json`);
25426
- if (presentationKitAi?.compileHtmlDeck) {
25850
+ const compiler = presentationKitCore?.compileHtmlDeck || presentationKitAi?.compileHtmlDeck;
25851
+ if (compiler) {
25427
25852
  try {
25428
- const compiled = presentationKitAi.compileHtmlDeck(deckJson);
25853
+ const compiled = compiler(deckJson);
25429
25854
  if (compiled?.html) {
25430
25855
  await storage.saveArtifact(projectId, `_content/${unitCode}/SLIDE_${lessonCode}.html`, compiled.html);
25431
25856
  producedArtifacts.push(`SLIDE_${lessonCode}.html`);
@@ -28053,6 +28478,9 @@ function isTranslationDue(target, context) {
28053
28478
  const total = context.totalLessonsByUnit[unit] ?? 0;
28054
28479
  return total > 0 && done >= total;
28055
28480
  }
28481
+
28482
+ // src/services/index.ts
28483
+ init_slideProductionWorkflow();
28056
28484
  var LocalWorkspaceManager = class {
28057
28485
  baseDir;
28058
28486
  constructor(baseDir) {
@@ -30647,6 +31075,7 @@ exports.ensureExpositionForLesson = ensureExpositionForLesson;
30647
31075
  exports.ensureKnowledgeExposition = ensureKnowledgeExposition;
30648
31076
  exports.evaluateStandardsCoverage = evaluateStandardsCoverage;
30649
31077
  exports.executeCurriculumCommand = executeCurriculumCommand;
31078
+ exports.executeSlideProductionWorkflow = executeSlideProductionWorkflow;
30650
31079
  exports.exportAllProjectQuizzes = exportAllProjectQuizzes;
30651
31080
  exports.expositionCacheKey = expositionCacheKey;
30652
31081
  exports.extractScopeSequenceRows = extractScopeSequenceRows;