@studious-lms/server 1.14.0 → 1.16.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 (129) hide show
  1. package/dist/lib/inferDocumentFormat.d.ts +10 -0
  2. package/dist/lib/inferDocumentFormat.d.ts.map +1 -0
  3. package/dist/lib/inferDocumentFormat.js +48 -0
  4. package/dist/lib/inferDocumentFormat.js.map +1 -0
  5. package/dist/models/announcement.d.ts +45 -45
  6. package/dist/models/assignment.d.ts +75 -75
  7. package/dist/models/class.d.ts +13 -13
  8. package/dist/models/comment.d.ts +6 -6
  9. package/dist/models/conversation.d.ts +23 -23
  10. package/dist/models/event.d.ts +18 -18
  11. package/dist/models/file.d.ts +9 -9
  12. package/dist/models/labChat.d.ts +4 -4
  13. package/dist/models/message.d.ts +13 -13
  14. package/dist/models/newtonChat.d.ts +3 -3
  15. package/dist/models/notification.d.ts +4 -4
  16. package/dist/models/worksheet.d.ts +121 -121
  17. package/dist/pipelines/aiLabChat.d.ts +7 -1
  18. package/dist/pipelines/aiLabChat.d.ts.map +1 -1
  19. package/dist/pipelines/aiLabChat.js +145 -67
  20. package/dist/pipelines/aiLabChat.js.map +1 -1
  21. package/dist/pipelines/aiLabChatContract.d.ts +34 -195
  22. package/dist/pipelines/aiLabChatContract.d.ts.map +1 -1
  23. package/dist/pipelines/aiLabChatContract.js +9 -19
  24. package/dist/pipelines/aiLabChatContract.js.map +1 -1
  25. package/dist/pipelines/gradeWorksheet.d.ts +6 -6
  26. package/dist/pipelines/gradeWorksheet.d.ts.map +1 -1
  27. package/dist/pipelines/gradeWorksheet.js +75 -36
  28. package/dist/pipelines/gradeWorksheet.js.map +1 -1
  29. package/dist/pipelines/labChatPrompt.d.ts +8 -3
  30. package/dist/pipelines/labChatPrompt.d.ts.map +1 -1
  31. package/dist/pipelines/labChatPrompt.js +49 -14
  32. package/dist/pipelines/labChatPrompt.js.map +1 -1
  33. package/dist/pipelines/pdfToWorksheet.d.ts +1 -1
  34. package/dist/routers/_app.d.ts +524 -516
  35. package/dist/routers/_app.d.ts.map +1 -1
  36. package/dist/routers/announcement.d.ts +40 -40
  37. package/dist/routers/assignment.d.ts +121 -121
  38. package/dist/routers/class.d.ts +8 -8
  39. package/dist/routers/comment.d.ts +5 -5
  40. package/dist/routers/conversation.d.ts +6 -6
  41. package/dist/routers/discussion.d.ts +3 -3
  42. package/dist/routers/embedding.d.ts +6 -2
  43. package/dist/routers/embedding.d.ts.map +1 -1
  44. package/dist/routers/embedding.js +44 -36
  45. package/dist/routers/embedding.js.map +1 -1
  46. package/dist/routers/event.d.ts +18 -18
  47. package/dist/routers/file.d.ts +2 -2
  48. package/dist/routers/labChat.d.ts +3 -3
  49. package/dist/routers/notifications.d.ts +4 -4
  50. package/dist/routers/search.d.ts +2 -2
  51. package/dist/routers/worksheet.d.ts +44 -44
  52. package/dist/routes/aiStream.d.ts.map +1 -1
  53. package/dist/routes/aiStream.js +41 -11
  54. package/dist/routes/aiStream.js.map +1 -1
  55. package/dist/seedDatabase.d.ts +1 -1
  56. package/dist/services/aiChatStream.d.ts +18 -0
  57. package/dist/services/aiChatStream.d.ts.map +1 -1
  58. package/dist/services/aiChatStream.js +81 -11
  59. package/dist/services/aiChatStream.js.map +1 -1
  60. package/dist/services/aiModifierTools.d.ts +0 -16
  61. package/dist/services/aiModifierTools.d.ts.map +1 -1
  62. package/dist/services/aiModifierTools.js +112 -3
  63. package/dist/services/aiModifierTools.js.map +1 -1
  64. package/dist/services/aiProposalTools.d.ts.map +1 -1
  65. package/dist/services/aiProposalTools.js +25 -25
  66. package/dist/services/aiProposalTools.js.map +1 -1
  67. package/dist/services/announcement.d.ts +34 -34
  68. package/dist/services/assignment.d.ts +111 -111
  69. package/dist/services/assignment.d.ts.map +1 -1
  70. package/dist/services/assignment.js +4 -2
  71. package/dist/services/assignment.js.map +1 -1
  72. package/dist/services/class.d.ts +6 -6
  73. package/dist/services/class.d.ts.map +1 -1
  74. package/dist/services/class.js +7 -3
  75. package/dist/services/class.js.map +1 -1
  76. package/dist/services/comment.d.ts +5 -5
  77. package/dist/services/conversation.d.ts +6 -6
  78. package/dist/services/discussion.d.ts.map +1 -1
  79. package/dist/services/discussion.js +9 -2
  80. package/dist/services/discussion.js.map +1 -1
  81. package/dist/services/embedding.d.ts +19 -1
  82. package/dist/services/embedding.d.ts.map +1 -1
  83. package/dist/services/embedding.js +154 -8
  84. package/dist/services/embedding.js.map +1 -1
  85. package/dist/services/event.d.ts +18 -18
  86. package/dist/services/file.d.ts +4 -4
  87. package/dist/services/folder.d.ts.map +1 -1
  88. package/dist/services/folder.js +32 -2
  89. package/dist/services/folder.js.map +1 -1
  90. package/dist/services/labChat.d.ts +3 -3
  91. package/dist/services/notification.d.ts +4 -4
  92. package/dist/services/openaiDocumentGen.d.ts +25 -0
  93. package/dist/services/openaiDocumentGen.d.ts.map +1 -0
  94. package/dist/services/openaiDocumentGen.js +195 -0
  95. package/dist/services/openaiDocumentGen.js.map +1 -0
  96. package/dist/services/search.d.ts +1 -1
  97. package/dist/services/search.d.ts.map +1 -1
  98. package/dist/services/search.js +27 -2
  99. package/dist/services/search.js.map +1 -1
  100. package/dist/services/worksheet.d.ts +66 -49
  101. package/dist/services/worksheet.d.ts.map +1 -1
  102. package/dist/services/worksheet.js +48 -3
  103. package/dist/services/worksheet.js.map +1 -1
  104. package/dist/workers/processors/embedContent.d.ts.map +1 -1
  105. package/dist/workers/processors/embedContent.js +16 -25
  106. package/dist/workers/processors/embedContent.js.map +1 -1
  107. package/package.json +1 -1
  108. package/prisma/migrations/20260610140000_expand_embedding_source_types/migration.sql +4 -0
  109. package/prisma/schema.prisma +3 -0
  110. package/src/lib/inferDocumentFormat.ts +58 -0
  111. package/src/pipelines/aiLabChat.ts +185 -74
  112. package/src/pipelines/aiLabChatContract.ts +7 -17
  113. package/src/pipelines/gradeWorksheet.ts +95 -38
  114. package/src/pipelines/labChatPrompt.ts +61 -14
  115. package/src/routers/embedding.ts +44 -39
  116. package/src/routes/aiStream.ts +47 -9
  117. package/src/services/aiChatStream.ts +103 -8
  118. package/src/services/aiModifierTools.ts +154 -1
  119. package/src/services/aiProposalTools.ts +26 -25
  120. package/src/services/assignment.ts +3 -0
  121. package/src/services/class.ts +7 -1
  122. package/src/services/discussion.ts +13 -0
  123. package/src/services/embedding.ts +167 -6
  124. package/src/services/folder.ts +31 -0
  125. package/src/services/openaiDocumentGen.ts +237 -0
  126. package/src/services/search.ts +25 -1
  127. package/src/services/worksheet.ts +68 -1
  128. package/src/workers/processors/embedContent.ts +18 -22
  129. package/tests/unit/lib/inferDocumentFormat.test.ts +33 -0
@@ -57,6 +57,12 @@ type RecentLabChatMessage = {
57
57
  displayName: string | null;
58
58
  } | null;
59
59
  } | null;
60
+ attachments: {
61
+ id: string;
62
+ name: string;
63
+ type: string;
64
+ path: string;
65
+ }[];
60
66
  };
61
67
  /**
62
68
  * `messages` must be ordered newest-first.
@@ -95,7 +101,7 @@ export declare const generateAndSendLabIntroduction: (labChatId: string, convers
95
101
  * conversation history is reloaded from the DB anchored on the AI
96
102
  * placeholder.
97
103
  */
98
- export declare const generateAndSendLabResponse: (labChatId: string, _teacherMessage: string, emitOptions: {
104
+ export declare const generateAndSendLabResponse: (labChatId: string, teacherMessage: string, emitOptions: {
99
105
  classId: string;
100
106
  aiMessageId: string;
101
107
  }) => Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"aiLabChat.d.ts","sourceRoot":"/","sources":["pipelines/aiLabChat.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAwC7E,wDAAwD;AACxD,KAAK,gBAAgB,GAAG;IACtB,KAAK,EAAE,KAAK,CAAC;IACb,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,WAAW,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KA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,CAAC;IAChB,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC;QACX,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;QACxB,OAAO,EAAE;YACP,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;SAC5B,GAAG,IAAI,CAAC;KACV,GAAG,IAAI,CAAC;IACT,WAAW,EAAE;QACX,EAAE,EAAE,MAAM,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,EAAE,CAAC;CACL,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,GACrC,UAAU,oBAAoB,EAAE,EAChC,kBAAkB,MAAM,EACxB,cAAU,2BAYX,CAAC;AAwIF;;;GAGG;AACH,eAAO,MAAM,sBAAsB,GAAI,MAAM,gBAAgB,KAAG,MAsF/D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,KAAK,EACd,SAAS,IAAI,EAAE,EACf,aAAa,UAAU,EAAE,EACzB,OAAO,IAAI,EAAE,EACb,UAAU,OAAO,EAAE,KAClB,MAYF,CAAC;AAIF;;;;;;GAMG;AACH,eAAO,MAAM,8BAA8B,GACvC,WAAW,MAAM,EACjB,gBAAgB,MAAM,EACtB,gBAAgB,MAAM,EACtB,UAAU,MAAM,EAChB,aAAa,MAAM,KAClB,OAAO,CAAC,IAAI,CAgBd,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,0BAA0B,GACrC,WAAW,MAAM,EACjB,gBAAgB,MAAM,EACtB,aAAa;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,KACpD,OAAO,CAAC,IAAI,CA4Td,CAAA"}
@@ -1,20 +1,22 @@
1
1
  /**
2
2
  * AI lab chat pipeline – generates lab introductions and responses.
3
- * Can create worksheets, sections, assignments, and PDF docs from AI output.
3
+ * Can create worksheets, sections, assignments, and generated files from AI output.
4
4
  */
5
5
 
6
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4bfeb1af-edc2-540a-acc7-d36c999b18a3")}catch(e){}}();
6
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d3703630-d937-5008-878a-ce235919a235")}catch(e){}}();
7
7
  import { isAIUser } from "../utils/aiUser.js";
8
8
  import { prisma } from "../lib/prisma.js";
9
- import { pusher, teacherChannel } from "../lib/pusher.js";
9
+ import { pusher, chatChannel, teacherChannel } from "../lib/pusher.js";
10
10
  import { completePendingAIMessage, failPendingAIMessage, } from "../utils/inference.js";
11
11
  import { logger } from "../utils/logger.js";
12
- import { createPdf } from "../lib/jsonConversion.js";
13
12
  import { v4 } from "uuid";
14
- import { bucket } from "../lib/googleCloudStorage.js";
13
+ import { bucket, getSignedUrl } from "../lib/googleCloudStorage.js";
14
+ import { generateDocumentWithOpenAI } from "../services/openaiDocumentGen.js";
15
+ import { inferDocumentFormat } from "../lib/inferDocumentFormat.js";
16
+ import { normalizeDocumentFormat } from "../services/openaiDocumentGen.js";
15
17
  import { broadcastTextChunks, broadcastStreamComplete } from "../utils/streamBroadcast.js";
16
18
  import { buildLabChatAgentMessages } from "./labChatPrompt.js";
17
- import { streamChatResponse } from "../services/aiChatStream.js";
19
+ import { applyResolvedFormatsToStreamParts, enrichStreamPartsWithGeneratedFiles, streamChatResponse, } from "../services/aiChatStream.js";
18
20
  import { aiTools } from "../services/aiTools.js";
19
21
  import { labProposalTools, createLabProposals } from "../services/aiProposalTools.js";
20
22
  /** Cap model wait time; leave headroom after inference for PDF/GCS/DB within Vercel maxDuration (500s). */
@@ -67,6 +69,14 @@ const loadRecentLabChatMessages = async (conversationId, anchorMessageId) => {
67
69
  },
68
70
  },
69
71
  },
72
+ attachments: {
73
+ select: {
74
+ id: true,
75
+ name: true,
76
+ type: true,
77
+ path: true,
78
+ },
79
+ },
70
80
  };
71
81
  const newestMessages = await prisma.message.findMany({
72
82
  where: baseQuery,
@@ -126,6 +136,34 @@ const loadRecentLabChatMessages = async (conversationId, anchorMessageId) => {
126
136
  })
127
137
  .slice(0, limit);
128
138
  };
139
+ /**
140
+ * Resolves signed URLs for image attachments in messages so the LLM can see them.
141
+ * Non-image files are passed as text descriptions only.
142
+ */
143
+ async function resolveAttachmentUrls(messages) {
144
+ const resolved = [];
145
+ for (const msg of messages) {
146
+ const attachments = msg.attachments ?? [];
147
+ if (attachments.length === 0) {
148
+ resolved.push({ ...msg, attachments: [] });
149
+ continue;
150
+ }
151
+ const withUrls = await Promise.all(attachments.map(async (a) => {
152
+ if (a.type.startsWith('image/')) {
153
+ try {
154
+ const url = await getSignedUrl(a.path);
155
+ return { id: a.id, name: a.name, type: a.type, url };
156
+ }
157
+ catch {
158
+ return { id: a.id, name: a.name, type: a.type };
159
+ }
160
+ }
161
+ return { id: a.id, name: a.name, type: a.type };
162
+ }));
163
+ resolved.push({ ...msg, attachments: withUrls });
164
+ }
165
+ return resolved;
166
+ }
129
167
  /**
130
168
  * Builds schema-aware context for the AI from class data.
131
169
  * Formats entities with IDs so the model can reference them when creating assignments.
@@ -235,7 +273,7 @@ export const getBaseSystemPrompt = (context, members, assignments, files, sectio
235
273
  * COMPLETED with the intro content, or to FAILED on a hard error.
236
274
  */
237
275
  export const generateAndSendLabIntroduction = async (labChatId, conversationId, _contextString, _subject, aiMessageId) => {
238
- const introMessage = "Hello teaching team! I'm your AI assistant for course material development. I'll help you create educational content - when you have a clear request, I'll produce it directly. I only ask questions when I need to clarify the topic or scope. What would you like to work on?";
276
+ const introMessage = "Hello teaching team! I'm your AI assistant for course material development. I can create worksheets, assignments, and downloadable files — PDFs, Word docs, PowerPoints, spreadsheets, and more. When you have a clear request, I'll produce it directly. I only ask questions when I need to clarify the topic or scope. What would you like to work on?";
239
277
  try {
240
278
  await broadcastTextChunks(conversationId, aiMessageId, introMessage);
241
279
  await completePendingAIMessage(aiMessageId, introMessage);
@@ -264,7 +302,7 @@ export const generateAndSendLabIntroduction = async (labChatId, conversationId,
264
302
  * conversation history is reloaded from the DB anchored on the AI
265
303
  * placeholder.
266
304
  */
267
- export const generateAndSendLabResponse = async (labChatId, _teacherMessage, emitOptions) => {
305
+ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emitOptions) => {
268
306
  try {
269
307
  // Get lab context from database
270
308
  const fullLabChat = await prisma.labChat.findUnique({
@@ -348,10 +386,12 @@ export const generateAndSendLabResponse = async (labChatId, _teacherMessage, emi
348
386
  teachers: classData.teachers,
349
387
  assignments: classData.assignments,
350
388
  });
389
+ // Resolve signed URLs for image attachments so the LLM can see them
390
+ const messagesWithAttachments = await resolveAttachmentUrls(recentMessages.reverse());
351
391
  const { system, messages } = buildLabChatAgentMessages({
352
392
  context: fullLabChat.context,
353
393
  classContext,
354
- recentMessages: recentMessages.reverse(),
394
+ recentMessages: messagesWithAttachments,
355
395
  isAIUser,
356
396
  });
357
397
  // Genuine agentic generation: the model streams prose token-by-token and
@@ -363,7 +403,7 @@ export const generateAndSendLabResponse = async (labChatId, _teacherMessage, emi
363
403
  ...aiTools(fullLabChat.classId),
364
404
  ...labProposalTools(proposals),
365
405
  };
366
- const { text: streamedText, parts: streamParts } = await withTimeout(streamChatResponse({
406
+ const { text: streamedText, parts: rawStreamParts } = await withTimeout(streamChatResponse({
367
407
  conversationId,
368
408
  aiMessageId: emitOptions.aiMessageId,
369
409
  system,
@@ -376,70 +416,108 @@ export const generateAndSendLabResponse = async (labChatId, _teacherMessage, emi
376
416
  // Real text + tool-call events were already broadcast inline (in order)
377
417
  // during the stream by `streamChatResponse`. Just close the stream.
378
418
  await broadcastStreamComplete(conversationId, emitOptions.aiMessageId);
379
- // Generate PDFs for any proposed documents and persist the message.
419
+ // `generate_document` is an inline tool that only QUEUES into `proposals.docs`
420
+ // during the stream. OpenAI Code Interpreter renders files here, after the
421
+ // stream ends, then we link them to this message.
380
422
  try {
381
423
  const attachmentIds = [];
382
- // Generate PDFs if docs were proposed
383
- if (proposals.docs.length > 0) {
384
- for (let i = 0; i < proposals.docs.length; i++) {
385
- const doc = proposals.docs[i];
386
- if (!doc.title || !doc.blocks || !Array.isArray(doc.blocks)) {
387
- logger.error(`Document ${i + 1} is missing title or blocks`);
388
- continue;
389
- }
390
- try {
391
- let pdfBytes = await createPdf(doc.blocks);
392
- if (pdfBytes) {
393
- // Sanitize filename - remove special characters and limit length
394
- const sanitizedTitle = doc.title
395
- .replace(/[^a-zA-Z0-9\s\-_]/g, '')
396
- .replace(/\s+/g, '_')
397
- .substring(0, 50);
398
- const filename = `${sanitizedTitle}_${v4().substring(0, 8)}.pdf`;
399
- const filePath = `class/generated/${fullLabChat.classId}/${filename}`;
400
- logger.info(`PDF ${i + 1} generated successfully`, { labChatId, title: doc.title });
401
- // Upload directly to Google Cloud Storage
402
- const gcsFile = bucket.file(filePath);
403
- await gcsFile.save(Buffer.from(pdfBytes), {
404
- metadata: {
405
- contentType: 'application/pdf',
406
- }
407
- });
408
- logger.info(`PDF ${i + 1} uploaded successfully`, { labChatId, filename });
409
- const file = await prisma.file.create({
410
- data: {
411
- name: filename,
412
- path: filePath,
413
- type: 'application/pdf',
414
- size: pdfBytes.length,
415
- userId: fullLabChat.createdById,
416
- uploadStatus: 'COMPLETED',
417
- uploadedAt: new Date(),
418
- },
419
- });
420
- attachmentIds.push(file.id);
421
- }
422
- else {
423
- logger.error(`PDF ${i + 1} creation returned undefined/null`, { labChatId, title: doc.title });
424
- }
425
- }
426
- catch (pdfError) {
427
- logger.error(`PDF creation threw an error for document ${i + 1}:`, {
428
- error: pdfError instanceof Error ? {
429
- message: pdfError.message,
430
- stack: pdfError.stack,
431
- name: pdfError.name
432
- } : pdfError,
424
+ const generatedDocFiles = [];
425
+ const resolvedDocs = [];
426
+ for (const doc of proposals.docs) {
427
+ if (!doc.title || !doc.content?.trim()) {
428
+ logger.error('Document missing title or content', { labChatId, doc });
429
+ continue;
430
+ }
431
+ const format = inferDocumentFormat(doc.title, doc.content, doc.format, teacherMessage);
432
+ resolvedDocs.push({ title: doc.title, format });
433
+ if (format !== normalizeDocumentFormat(doc.format)) {
434
+ logger.info('Document format overridden from model default', {
435
+ labChatId,
436
+ title: doc.title,
437
+ modelFormat: doc.format,
438
+ resolvedFormat: format,
439
+ });
440
+ }
441
+ try {
442
+ const generated = await generateDocumentWithOpenAI({
443
+ title: doc.title,
444
+ content: doc.content,
445
+ format,
446
+ });
447
+ if (!generated) {
448
+ logger.error('OpenAI document generation returned null', {
433
449
  labChatId,
434
- title: doc.title
450
+ title: doc.title,
451
+ format: doc.format,
435
452
  });
453
+ continue;
436
454
  }
455
+ const sanitizedTitle = doc.title
456
+ .replace(/[^a-zA-Z0-9\s\-_]/g, '')
457
+ .replace(/\s+/g, '_')
458
+ .substring(0, 50);
459
+ const filename = `${sanitizedTitle}_${v4().substring(0, 8)}.${generated.format}`;
460
+ const filePath = `class/generated/${fullLabChat.classId}/${filename}`;
461
+ await bucket.file(filePath).save(generated.bytes, {
462
+ metadata: { contentType: generated.mimeType },
463
+ });
464
+ const file = await prisma.file.create({
465
+ data: {
466
+ name: filename,
467
+ path: filePath,
468
+ type: generated.mimeType,
469
+ size: generated.bytes.length,
470
+ userId: fullLabChat.createdById,
471
+ conversationId,
472
+ messageId: emitOptions.aiMessageId,
473
+ uploadStatus: 'COMPLETED',
474
+ uploadedAt: new Date(),
475
+ },
476
+ });
477
+ attachmentIds.push(file.id);
478
+ generatedDocFiles.push({
479
+ title: doc.title,
480
+ fileId: file.id,
481
+ fileName: filename,
482
+ format: generated.format,
483
+ });
484
+ }
485
+ catch (docError) {
486
+ logger.error('Document generation failed', {
487
+ error: docError instanceof Error ? {
488
+ message: docError.message,
489
+ stack: docError.stack,
490
+ name: docError.name,
491
+ } : docError,
492
+ labChatId,
493
+ title: doc.title,
494
+ format: doc.format,
495
+ });
496
+ }
497
+ }
498
+ const streamParts = enrichStreamPartsWithGeneratedFiles(applyResolvedFormatsToStreamParts(rawStreamParts, resolvedDocs), generatedDocFiles);
499
+ for (const part of streamParts) {
500
+ if (part.type === 'tool' &&
501
+ part.toolName === 'generate_document' &&
502
+ part.fileId) {
503
+ await pusher
504
+ .trigger(chatChannel(conversationId), 'message-tool-call', {
505
+ messageId: emitOptions.aiMessageId,
506
+ toolCallId: part.toolCallId,
507
+ toolName: part.toolName,
508
+ ...(part.title ? { title: part.title } : {}),
509
+ ...(part.format ? { format: part.format } : {}),
510
+ fileId: part.fileId,
511
+ fileName: part.fileName,
512
+ status: 'completed',
513
+ })
514
+ .catch(() => { });
437
515
  }
438
516
  }
439
517
  await completePendingAIMessage(emitOptions.aiMessageId, streamedText, {
440
- attachments: {
441
- connect: attachmentIds.map(id => ({ id })),
442
- },
518
+ ...(attachmentIds.length > 0 && {
519
+ attachments: { connect: attachmentIds.map((id) => ({ id })) },
520
+ }),
443
521
  meta: {
444
522
  assignmentsToCreate: proposals.assignments.length > 0
445
523
  ? proposals.assignments.map(assignment => ({ ...assignment, id: v4() }))
@@ -499,4 +577,4 @@ export const generateAndSendLabResponse = async (labChatId, _teacherMessage, emi
499
577
  }
500
578
  };
501
579
  //# sourceMappingURL=aiLabChat.js.map
502
- //# debugId=4bfeb1af-edc2-540a-acc7-d36c999b18a3
580
+ //# debugId=d3703630-d937-5008-878a-ce235919a235
@@ -1 +1 @@
1
- {"version":3,"file":"aiLabChat.js","sources":["pipelines/aiLabChat.ts"],"sourceRoot":"/","sourcesContent":["/**\n * AI lab chat pipeline – generates lab introductions and responses.\n * Can create worksheets, sections, assignments, and PDF docs from AI output.\n */\nimport { isAIUser } from \"../utils/aiUser.js\";\nimport { prisma } from \"../lib/prisma.js\";\nimport { pusher, teacherChannel } from \"../lib/pusher.js\";\nimport type { Assignment, Class, File, Section, User } from \"@prisma/client\";\nimport {\n completePendingAIMessage,\n failPendingAIMessage,\n} from \"../utils/inference.js\";\nimport { logger } from \"../utils/logger.js\";\nimport { createPdf } from \"../lib/jsonConversion.js\";\nimport { v4 } from \"uuid\";\nimport { bucket } from \"../lib/googleCloudStorage.js\";\nimport { DocumentBlock } from \"../lib/jsonStyles.js\";\nimport { broadcastTextChunks, broadcastStreamComplete } from \"../utils/streamBroadcast.js\";\nimport { buildLabChatAgentMessages } from \"./labChatPrompt.js\";\nimport { streamChatResponse } from \"../services/aiChatStream.js\";\nimport { aiTools } from \"../services/aiTools.js\";\nimport { labProposalTools, createLabProposals } from \"../services/aiProposalTools.js\";\n\n/** Cap model wait time; leave headroom after inference for PDF/GCS/DB within Vercel maxDuration (500s). */\nconst LAB_CHAT_RESPONSE_TIMEOUT_MS = 400_000;\n\nconst withTimeout = async <T>(\n task: Promise<T>,\n timeoutMs: number,\n operationName: string,\n): Promise<T> => {\n let timeoutHandle: NodeJS.Timeout | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutHandle = setTimeout(() => {\n reject(new Error(`${operationName} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([task, timeoutPromise]);\n } finally {\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n }\n};\n\n/** Extended class data for AI context (schema-aware) */\ntype ClassContextData = {\n class: Class;\n sections: Section[];\n markSchemes: { id: string; structured: string }[];\n gradingBoundaries: { id: string; structured: string }[];\n worksheets: { id: string; name: string; questionCount: number }[];\n files: File[];\n students: { id: string; username: string; profile?: { displayName: string | null } | null }[];\n teachers: { id: string; username: string; profile?: { displayName: string | null } | null }[];\n assignments: (Assignment & {\n section?: { id: string; name: string; order?: number | null } | null;\n markScheme?: { id: string } | null;\n gradingBoundary?: { id: string } | null;\n })[];\n};\n\ntype RecentLabChatMessage = {\n id: string;\n content: string;\n senderId: string;\n createdAt: Date;\n sender: {\n id: string;\n username: string | null;\n profile: {\n displayName: string | null;\n } | null;\n } | null;\n};\n\n/**\n * `messages` must be ordered newest-first.\n * When `anchorMessageId` is provided, `sliceMessagesThroughAnchor` returns the\n * anchor message and older messages only, capped to `limit`.\n */\nexport const sliceMessagesThroughAnchor = (\n messages: RecentLabChatMessage[],\n anchorMessageId?: string,\n limit = 10,\n) => {\n if (!anchorMessageId) {\n return messages.slice(0, limit);\n }\n\n const anchorIndex = messages.findIndex((message) => message.id === anchorMessageId);\n if (anchorIndex === -1) {\n return messages.slice(0, limit);\n }\n\n return messages.slice(anchorIndex, anchorIndex + limit);\n};\n\nconst loadRecentLabChatMessages = async (\n conversationId: string,\n anchorMessageId?: string,\n): Promise<RecentLabChatMessage[]> => {\n const limit = 10;\n const baseQuery = {\n conversationId,\n };\n const include = {\n sender: {\n select: {\n id: true,\n username: true,\n profile: {\n select: {\n displayName: true,\n },\n },\n },\n },\n };\n\n const newestMessages = await prisma.message.findMany({\n where: baseQuery,\n include,\n orderBy: {\n createdAt: 'desc',\n },\n take: 25,\n });\n\n const anchoredMessages = sliceMessagesThroughAnchor(newestMessages, anchorMessageId, limit);\n if (!anchorMessageId || anchoredMessages.some((message) => message.id === anchorMessageId)) {\n return anchoredMessages;\n }\n\n const anchorMessage = await prisma.message.findUnique({\n where: { id: anchorMessageId },\n include,\n });\n\n if (!anchorMessage) {\n throw new Error(`Anchor message ${anchorMessageId} not found`);\n }\n\n if (anchorMessage.conversationId !== conversationId) {\n throw new Error(`Anchor message ${anchorMessageId} does not belong to conversation ${conversationId}`);\n }\n\n const olderMessages = await prisma.message.findMany({\n where: {\n conversationId,\n createdAt: {\n lte: anchorMessage.createdAt,\n },\n },\n include,\n orderBy: {\n createdAt: 'desc',\n },\n take: limit,\n });\n\n const dedupedMessages = new Map<string, RecentLabChatMessage>();\n dedupedMessages.set(anchorMessage.id, anchorMessage);\n\n olderMessages.forEach((message) => {\n if (!dedupedMessages.has(message.id)) {\n dedupedMessages.set(message.id, message);\n }\n });\n\n return Array.from(dedupedMessages.values())\n .sort((left, right) => {\n const timeDelta = right.createdAt.getTime() - left.createdAt.getTime();\n if (timeDelta !== 0) {\n return timeDelta;\n }\n if (left.id === anchorMessage.id) {\n return -1;\n }\n if (right.id === anchorMessage.id) {\n return 1;\n }\n\n return right.id.localeCompare(left.id);\n })\n .slice(0, limit);\n};\n\n/**\n * Builds schema-aware context for the AI from class data.\n * Formats entities with IDs so the model can reference them when creating assignments.\n */\nexport const buildClassContextForAI = (data: ClassContextData): string => {\n const { class: cls, sections, markSchemes, gradingBoundaries, worksheets, files, students, assignments } = data;\n\n const sectionList = sections\n .sort((a, b) => (a.order ?? 999) - (b.order ?? 999))\n .map((s) => ` - id: ${s.id} | name: \"${s.name}\" | color: ${s.color ?? \"default\"}`)\n .join(\"\\n\");\n\n const markSchemeList = markSchemes\n .map((ms) => {\n let preview = \"structured rubric\";\n try {\n const parsed = JSON.parse(ms.structured || \"{}\");\n preview = parsed.name || Object.keys(parsed).slice(0, 2).join(\", \") || \"rubric\";\n } catch {\n /* ignore */\n }\n return ` - id: ${ms.id} | ${preview}`;\n })\n .join(\"\\n\");\n\n const gradingBoundaryList = gradingBoundaries\n .map((gb) => {\n let preview = \"grading scale\";\n try {\n const parsed = JSON.parse(gb.structured || \"{}\");\n preview = parsed.name || Object.keys(parsed).slice(0, 2).join(\", \") || \"scale\";\n } catch {\n /* ignore */\n }\n return ` - id: ${gb.id} | ${preview}`;\n })\n .join(\"\\n\");\n\n const worksheetList = worksheets\n .map((w) => ` - id: ${w.id} | name: \"${w.name}\" | questions: ${w.questionCount}`)\n .join(\"\\n\");\n\n const fileList = files\n .filter((f) => f.type === \"application/pdf\" || f.type?.includes(\"document\"))\n .map((f) => ` - id: ${f.id} | name: \"${f.name}\" | type: ${f.type}`)\n .join(\"\\n\");\n const otherFiles = files.filter((f) => f.type !== \"application/pdf\" && !f.type?.includes(\"document\"));\n const otherFileList = otherFiles.length\n ? otherFiles.map((f) => ` - id: ${f.id} | name: \"${f.name}\"`).join(\"\\n\")\n : \" (none)\";\n\n const studentList = students\n .map((u) => ` - id: ${u.id} | username: ${u.username} | displayName: ${u.profile?.displayName ?? \"—\"}`)\n .join(\"\\n\");\n\n const assignmentSummary = assignments\n .map((a) => {\n const sectionName = a.section?.name ?? \"—\";\n return ` - id: ${a.id} | title: \"${a.title}\" | type: ${a.type} | section: \"${sectionName}\" | due: ${a.dueDate.toISOString().slice(0, 10)}`;\n })\n .join(\"\\n\");\n\n return `\nCLASS: ${cls.name} | Subject: ${cls.subject} | Section: ${cls.section}\nSyllabus: ${cls.syllabus ? cls.syllabus.slice(0, 200) + (cls.syllabus.length > 200 ? \"…\" : \"\") : \"(none)\"}\n\nSECTIONS (use sectionId when creating assignments):\n${sectionList || \" (none - suggest sectionsToCreate first)\"}\n\nMARK SCHEMES (use markSchemeId when creating assignments):\n${markSchemeList || \" (none - suggest creating one or omit markSchemeId)\"}\n\nGRADING BOUNDARIES (use gradingBoundaryId when creating assignments):\n${gradingBoundaryList || \" (none - suggest creating one or omit gradingBoundaryId)\"}\n\nWORKSHEETS (use worksheetIds when acceptWorksheet is true):\n${worksheetList || \" (none - use worksheetsToCreate or create via docs first)\"}\n\nFILES - PDFs/Documents (for assignment attachments):\n${fileList || \" (none)\"}\n\nFILES - Other (for assignment attachments):\n${otherFileList}\n\nSTUDENTS (use studentIds for specific assignment; empty array = all students):\n${studentList || \" (none)\"}\n\nEXISTING ASSIGNMENTS (for reference, avoid duplicates):\n${assignmentSummary || \" (none)\"}\n`.trim();\n};\n\n/**\n * @deprecated Use buildClassContextForAI for schema-aware context. Kept for compatibility.\n */\nexport const getBaseSystemPrompt = (\n context: Class,\n members: User[],\n assignments: Assignment[],\n files: File[],\n sections: Section[]\n): string => {\n return buildClassContextForAI({\n class: context,\n sections,\n markSchemes: [],\n gradingBoundaries: [],\n worksheets: [],\n files,\n students: members,\n teachers: [],\n assignments,\n });\n};\n\n\n\n/**\n * Fill the AI introduction placeholder for a brand-new lab chat.\n *\n * The caller (service layer) must have already created a PENDING AI Message\n * row — `aiMessageId` is that placeholder. This function flips it to\n * COMPLETED with the intro content, or to FAILED on a hard error.\n */\nexport const generateAndSendLabIntroduction = async (\n labChatId: string,\n conversationId: string,\n _contextString: string,\n _subject: string,\n aiMessageId: string,\n ): Promise<void> => {\n const introMessage =\n \"Hello teaching team! I'm your AI assistant for course material development. I'll help you create educational content - when you have a clear request, I'll produce it directly. I only ask questions when I need to clarify the topic or scope. What would you like to work on?\";\n\n try {\n await broadcastTextChunks(conversationId, aiMessageId, introMessage);\n await completePendingAIMessage(aiMessageId, introMessage);\n logger.info('AI Introduction sent', { labChatId, conversationId, aiMessageId });\n } catch (error) {\n logger.error('Failed to complete AI introduction placeholder:', {\n error,\n labChatId,\n aiMessageId,\n });\n await failPendingAIMessage(aiMessageId, { reason: 'lab_intro_complete_failed' });\n }\n }\n \n /**\n * Fill the AI response placeholder for a teacher reply in a lab chat.\n *\n * `aiMessageId` is the PENDING AI Message row created by the service\n * layer; the pipeline flips it to COMPLETED with content / attachments /\n * meta, or FAILED on error. Teacher-channel `lab-response-{pending,\n * completed,failed}` events fire alongside the chat-channel status flips\n * (which `completePendingAIMessage` / `failPendingAIMessage` already\n * broadcast) so the lab list \"AI busy\" indicator stays accurate.\n *\n * `_teacherMessage` is retained for caller compatibility — the actual\n * conversation history is reloaded from the DB anchored on the AI\n * placeholder.\n */\n export const generateAndSendLabResponse = async (\n labChatId: string,\n _teacherMessage: string,\n emitOptions: { classId: string; aiMessageId: string }\n ): Promise<void> => {\n try {\n // Get lab context from database\n const fullLabChat = await prisma.labChat.findUnique({\n where: { id: labChatId },\n include: {\n class: {\n select: {\n name: true,\n subject: true,\n },\n },\n },\n });\n \n if (!fullLabChat) {\n throw new Error('Lab chat not found');\n }\n \n const conversationId = fullLabChat.conversationId;\n \n // Anchor history on the AI placeholder — the slice will include the\n // placeholder itself (empty content) at the top; drop it so the model\n // does not see an empty assistant turn at the very end.\n const anchoredMessages = await loadRecentLabChatMessages(\n conversationId,\n emitOptions.aiMessageId,\n );\n const recentMessages = anchoredMessages.filter(\n (msg) => msg.id !== emitOptions.aiMessageId,\n );\n \n const classData = await prisma.class.findUnique({\n where: {\n id: fullLabChat.classId,\n },\n include: {\n assignments: {\n include: {\n section: { select: { id: true, name: true, order: true } },\n markScheme: { select: { id: true } },\n gradingBoundary: { select: { id: true } },\n },\n },\n sections: true,\n markSchemes: { select: { id: true, structured: true } },\n gradingBoundaries: { select: { id: true, structured: true } },\n worksheets: {\n select: {\n id: true,\n name: true,\n _count: { select: { questions: true } },\n },\n },\n students: {\n select: {\n id: true,\n username: true,\n profile: { select: { displayName: true } },\n },\n },\n teachers: {\n select: {\n id: true,\n username: true,\n profile: { select: { displayName: true } },\n },\n },\n classFiles: {\n include: {\n files: true,\n },\n },\n },\n });\n\n if (!classData) {\n throw new Error('Class not found');\n }\n\n const classContext = buildClassContextForAI({\n class: classData,\n sections: classData.sections,\n markSchemes: classData.markSchemes,\n gradingBoundaries: classData.gradingBoundaries,\n worksheets: classData.worksheets.map((w) => ({\n id: w.id,\n name: w.name,\n questionCount: w._count.questions,\n })),\n files: classData.classFiles?.files ?? [],\n students: classData.students,\n teachers: classData.teachers,\n assignments: classData.assignments,\n });\n\n const { system, messages } = buildLabChatAgentMessages({\n context: fullLabChat.context,\n classContext,\n recentMessages: recentMessages.reverse(),\n isAIUser,\n });\n\n // Genuine agentic generation: the model streams prose token-by-token and\n // calls real tools inline — read-only RAG lookups plus \"propose_*\" tools\n // that record create-actions into `proposals`. `streamChatResponse`\n // broadcasts the real text chunks and tool-call events as they happen.\n const proposals = createLabProposals();\n const tools = {\n ...aiTools(fullLabChat.classId),\n ...labProposalTools(proposals),\n };\n\n const { text: streamedText, parts: streamParts } = await withTimeout(\n streamChatResponse({\n conversationId,\n aiMessageId: emitOptions.aiMessageId,\n system,\n messages,\n tools,\n temperature: 0.7,\n maxOutputTokens: 4096,\n maxSteps: 8,\n }),\n LAB_CHAT_RESPONSE_TIMEOUT_MS,\n \"Lab chat response generation\",\n );\n\n // Real text + tool-call events were already broadcast inline (in order)\n // during the stream by `streamChatResponse`. Just close the stream.\n await broadcastStreamComplete(conversationId, emitOptions.aiMessageId);\n\n // Generate PDFs for any proposed documents and persist the message.\n try {\n const attachmentIds: string[] = [];\n // Generate PDFs if docs were proposed\n if (proposals.docs.length > 0) {\n \n \n for (let i = 0; i < proposals.docs.length; i++) {\n const doc = proposals.docs[i];\n if (!doc.title || !doc.blocks || !Array.isArray(doc.blocks)) {\n logger.error(`Document ${i + 1} is missing title or blocks`);\n continue;\n } \n \n \n try {\n let pdfBytes = await createPdf(doc.blocks as DocumentBlock[]); \n if (pdfBytes) {\n // Sanitize filename - remove special characters and limit length\n const sanitizedTitle = doc.title\n .replace(/[^a-zA-Z0-9\\s\\-_]/g, '')\n .replace(/\\s+/g, '_')\n .substring(0, 50);\n \n const filename = `${sanitizedTitle}_${v4().substring(0, 8)}.pdf`;\n const filePath = `class/generated/${fullLabChat.classId}/${filename}`;\n \n logger.info(`PDF ${i + 1} generated successfully`, { labChatId, title: doc.title });\n \n // Upload directly to Google Cloud Storage\n const gcsFile = bucket.file(filePath);\n await gcsFile.save(Buffer.from(pdfBytes), {\n metadata: {\n contentType: 'application/pdf',\n }\n });\n \n logger.info(`PDF ${i + 1} uploaded successfully`, { labChatId, filename });\n \n const file = await prisma.file.create({\n data: {\n name: filename,\n path: filePath,\n type: 'application/pdf',\n size: pdfBytes.length,\n userId: fullLabChat.createdById,\n uploadStatus: 'COMPLETED',\n uploadedAt: new Date(),\n },\n });\n attachmentIds.push(file.id);\n } else {\n logger.error(`PDF ${i + 1} creation returned undefined/null`, { labChatId, title: doc.title });\n }\n } catch (pdfError) {\n logger.error(`PDF creation threw an error for document ${i + 1}:`, { \n error: pdfError instanceof Error ? {\n message: pdfError.message,\n stack: pdfError.stack,\n name: pdfError.name\n } : pdfError, \n labChatId,\n title: doc.title\n });\n }\n }\n }\n \n await completePendingAIMessage(emitOptions.aiMessageId, streamedText, {\n attachments: {\n connect: attachmentIds.map(id => ({ id })),\n },\n meta: {\n assignmentsToCreate: proposals.assignments.length > 0\n ? proposals.assignments.map(assignment => ({ ...assignment, id: v4() }))\n : null,\n worksheetsToCreate: proposals.worksheets.length > 0\n ? proposals.worksheets.map(worksheet => ({ ...worksheet, id: v4() }))\n : null,\n sectionsToCreate: proposals.sections.length > 0\n ? proposals.sections.map(section => ({ ...section, id: v4() }))\n : null,\n streamParts: streamParts.length > 0 ? streamParts : null,\n },\n });\n } catch (persistError) {\n logger.error('Failed to persist AI response or generate PDF:', { error: persistError, labChatId });\n // Fallback: complete the placeholder with the raw text so the\n // teacher still sees something useful instead of FAILED.\n await completePendingAIMessage(emitOptions.aiMessageId, streamedText);\n }\n\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-completed\", {\n labChatId,\n messageId: emitOptions.aiMessageId,\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response completed:\", { error: broadcastError });\n }\n\n logger.info('AI response sent', { labChatId, conversationId, aiMessageId: emitOptions.aiMessageId });\n\n } catch (error) {\n console.error('Full error object:', error);\n logger.error('Failed to generate AI response:', {\n error: error instanceof Error ? {\n message: error.message,\n stack: error.stack,\n name: error.name\n } : error,\n labChatId,\n aiMessageId: emitOptions.aiMessageId,\n });\n\n await failPendingAIMessage(emitOptions.aiMessageId, {\n reason: 'lab_response_generation_failed',\n });\n\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-failed\", {\n labChatId,\n messageId: emitOptions.aiMessageId,\n error: \"AI response generation failed\",\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response failed:\", { error: broadcastError });\n }\n\n throw error; // Re-throw to see the full error in the calling function\n }\n }\n"],"names":[],"mappings":"AAAA;;;GAGG;;;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CA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,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC;QAC3C,MAAM,CAAC,KAAK,CAAC,iCAAiC,EAAE;YAC9C,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC;gBAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,IAAI,EAAE,KAAK,CAAC,IAAI;aACjB,CAAC,CAAC,CAAC,KAAK;YACT,SAAS;YACT,WAAW,EAAE,WAAW,CAAC,WAAW;SACrC,CAAC,CAAC;QAEH,MAAM,oBAAoB,CAAC,WAAW,CAAC,WAAW,EAAE;YAClD,MAAM,EAAE,gCAAgC;SACzC,CAAC,CAAC;QAEH,IAAI,CAAC;YACH,MAAM,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,qBAAqB,EAAE;gBAC/E,SAAS;gBACT,SAAS,EAAE,WAAW,CAAC,WAAW;gBAClC,KAAK,EAAE,+BAA+B;aACvC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,cAAc,EAAE,CAAC;YACxB,MAAM,CAAC,KAAK,CAAC,0CAA0C,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;QACtF,CAAC;QAED,MAAM,KAAK,CAAC,CAAC,yDAAyD;IACxE,CAAC;AACH,CAAC,CAAA","debug_id":"4bfeb1af-edc2-540a-acc7-d36c999b18a3"}
1
+ {"version":3,"file":"aiLabChat.js","sources":["pipelines/aiLabChat.ts"],"sourceRoot":"/","sourcesContent":["/**\n * AI lab chat pipeline – generates lab introductions and responses.\n * Can create worksheets, sections, assignments, and generated files from AI output.\n */\nimport { isAIUser } from \"../utils/aiUser.js\";\nimport { prisma } from \"../lib/prisma.js\";\nimport { pusher, chatChannel, teacherChannel } from \"../lib/pusher.js\";\nimport type { Assignment, Class, File, Section, User } from \"@prisma/client\";\nimport {\n completePendingAIMessage,\n failPendingAIMessage,\n} from \"../utils/inference.js\";\nimport { logger } from \"../utils/logger.js\";\nimport { v4 } from \"uuid\";\nimport { bucket, getSignedUrl } from \"../lib/googleCloudStorage.js\";\nimport { generateDocumentWithOpenAI } from \"../services/openaiDocumentGen.js\";\nimport { inferDocumentFormat } from \"../lib/inferDocumentFormat.js\";\nimport { normalizeDocumentFormat } from \"../services/openaiDocumentGen.js\";\nimport { broadcastTextChunks, broadcastStreamComplete } from \"../utils/streamBroadcast.js\";\nimport { buildLabChatAgentMessages } from \"./labChatPrompt.js\";\nimport type { ConversationMessage } from \"./labChatPrompt.js\";\nimport {\n applyResolvedFormatsToStreamParts,\n enrichStreamPartsWithGeneratedFiles,\n streamChatResponse,\n type GeneratedDocFileLink,\n type StreamPart,\n} from \"../services/aiChatStream.js\";\nimport { aiTools } from \"../services/aiTools.js\";\nimport { labProposalTools, createLabProposals } from \"../services/aiProposalTools.js\";\n\n/** Cap model wait time; leave headroom after inference for PDF/GCS/DB within Vercel maxDuration (500s). */\nconst LAB_CHAT_RESPONSE_TIMEOUT_MS = 400_000;\n\nconst withTimeout = async <T>(\n task: Promise<T>,\n timeoutMs: number,\n operationName: string,\n): Promise<T> => {\n let timeoutHandle: NodeJS.Timeout | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutHandle = setTimeout(() => {\n reject(new Error(`${operationName} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([task, timeoutPromise]);\n } finally {\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n }\n};\n\n/** Extended class data for AI context (schema-aware) */\ntype ClassContextData = {\n class: Class;\n sections: Section[];\n markSchemes: { id: string; structured: string }[];\n gradingBoundaries: { id: string; structured: string }[];\n worksheets: { id: string; name: string; questionCount: number }[];\n files: File[];\n students: { id: string; username: string; profile?: { displayName: string | null } | null }[];\n teachers: { id: string; username: string; profile?: { displayName: string | null } | null }[];\n assignments: (Assignment & {\n section?: { id: string; name: string; order?: number | null } | null;\n markScheme?: { id: string } | null;\n gradingBoundary?: { id: string } | null;\n })[];\n};\n\ntype RecentLabChatMessage = {\n id: string;\n content: string;\n senderId: string;\n createdAt: Date;\n sender: {\n id: string;\n username: string | null;\n profile: {\n displayName: string | null;\n } | null;\n } | null;\n attachments: {\n id: string;\n name: string;\n type: string;\n path: string;\n }[];\n};\n\n/**\n * `messages` must be ordered newest-first.\n * When `anchorMessageId` is provided, `sliceMessagesThroughAnchor` returns the\n * anchor message and older messages only, capped to `limit`.\n */\nexport const sliceMessagesThroughAnchor = (\n messages: RecentLabChatMessage[],\n anchorMessageId?: string,\n limit = 10,\n) => {\n if (!anchorMessageId) {\n return messages.slice(0, limit);\n }\n\n const anchorIndex = messages.findIndex((message) => message.id === anchorMessageId);\n if (anchorIndex === -1) {\n return messages.slice(0, limit);\n }\n\n return messages.slice(anchorIndex, anchorIndex + limit);\n};\n\nconst loadRecentLabChatMessages = async (\n conversationId: string,\n anchorMessageId?: string,\n): Promise<RecentLabChatMessage[]> => {\n const limit = 10;\n const baseQuery = {\n conversationId,\n };\n const include = {\n sender: {\n select: {\n id: true,\n username: true,\n profile: {\n select: {\n displayName: true,\n },\n },\n },\n },\n attachments: {\n select: {\n id: true,\n name: true,\n type: true,\n path: true,\n },\n },\n };\n\n const newestMessages = await prisma.message.findMany({\n where: baseQuery,\n include,\n orderBy: {\n createdAt: 'desc',\n },\n take: 25,\n });\n\n const anchoredMessages = sliceMessagesThroughAnchor(newestMessages, anchorMessageId, limit);\n if (!anchorMessageId || anchoredMessages.some((message) => message.id === anchorMessageId)) {\n return anchoredMessages;\n }\n\n const anchorMessage = await prisma.message.findUnique({\n where: { id: anchorMessageId },\n include,\n });\n\n if (!anchorMessage) {\n throw new Error(`Anchor message ${anchorMessageId} not found`);\n }\n\n if (anchorMessage.conversationId !== conversationId) {\n throw new Error(`Anchor message ${anchorMessageId} does not belong to conversation ${conversationId}`);\n }\n\n const olderMessages = await prisma.message.findMany({\n where: {\n conversationId,\n createdAt: {\n lte: anchorMessage.createdAt,\n },\n },\n include,\n orderBy: {\n createdAt: 'desc',\n },\n take: limit,\n });\n\n const dedupedMessages = new Map<string, RecentLabChatMessage>();\n dedupedMessages.set(anchorMessage.id, anchorMessage);\n\n olderMessages.forEach((message) => {\n if (!dedupedMessages.has(message.id)) {\n dedupedMessages.set(message.id, message);\n }\n });\n\n return Array.from(dedupedMessages.values())\n .sort((left, right) => {\n const timeDelta = right.createdAt.getTime() - left.createdAt.getTime();\n if (timeDelta !== 0) {\n return timeDelta;\n }\n if (left.id === anchorMessage.id) {\n return -1;\n }\n if (right.id === anchorMessage.id) {\n return 1;\n }\n\n return right.id.localeCompare(left.id);\n })\n .slice(0, limit);\n};\n\n/**\n * Resolves signed URLs for image attachments in messages so the LLM can see them.\n * Non-image files are passed as text descriptions only.\n */\nasync function resolveAttachmentUrls(\n messages: RecentLabChatMessage[],\n): Promise<ConversationMessage[]> {\n const resolved: ConversationMessage[] = [];\n\n for (const msg of messages) {\n const attachments = msg.attachments ?? [];\n if (attachments.length === 0) {\n resolved.push({ ...msg, attachments: [] });\n continue;\n }\n\n const withUrls = await Promise.all(\n attachments.map(async (a) => {\n if (a.type.startsWith('image/')) {\n try {\n const url = await getSignedUrl(a.path);\n return { id: a.id, name: a.name, type: a.type, url };\n } catch {\n return { id: a.id, name: a.name, type: a.type };\n }\n }\n return { id: a.id, name: a.name, type: a.type };\n }),\n );\n\n resolved.push({ ...msg, attachments: withUrls });\n }\n\n return resolved;\n}\n\n/**\n * Builds schema-aware context for the AI from class data.\n * Formats entities with IDs so the model can reference them when creating assignments.\n */\nexport const buildClassContextForAI = (data: ClassContextData): string => {\n const { class: cls, sections, markSchemes, gradingBoundaries, worksheets, files, students, assignments } = data;\n\n const sectionList = sections\n .sort((a, b) => (a.order ?? 999) - (b.order ?? 999))\n .map((s) => ` - id: ${s.id} | name: \"${s.name}\" | color: ${s.color ?? \"default\"}`)\n .join(\"\\n\");\n\n const markSchemeList = markSchemes\n .map((ms) => {\n let preview = \"structured rubric\";\n try {\n const parsed = JSON.parse(ms.structured || \"{}\");\n preview = parsed.name || Object.keys(parsed).slice(0, 2).join(\", \") || \"rubric\";\n } catch {\n /* ignore */\n }\n return ` - id: ${ms.id} | ${preview}`;\n })\n .join(\"\\n\");\n\n const gradingBoundaryList = gradingBoundaries\n .map((gb) => {\n let preview = \"grading scale\";\n try {\n const parsed = JSON.parse(gb.structured || \"{}\");\n preview = parsed.name || Object.keys(parsed).slice(0, 2).join(\", \") || \"scale\";\n } catch {\n /* ignore */\n }\n return ` - id: ${gb.id} | ${preview}`;\n })\n .join(\"\\n\");\n\n const worksheetList = worksheets\n .map((w) => ` - id: ${w.id} | name: \"${w.name}\" | questions: ${w.questionCount}`)\n .join(\"\\n\");\n\n const fileList = files\n .filter((f) => f.type === \"application/pdf\" || f.type?.includes(\"document\"))\n .map((f) => ` - id: ${f.id} | name: \"${f.name}\" | type: ${f.type}`)\n .join(\"\\n\");\n const otherFiles = files.filter((f) => f.type !== \"application/pdf\" && !f.type?.includes(\"document\"));\n const otherFileList = otherFiles.length\n ? otherFiles.map((f) => ` - id: ${f.id} | name: \"${f.name}\"`).join(\"\\n\")\n : \" (none)\";\n\n const studentList = students\n .map((u) => ` - id: ${u.id} | username: ${u.username} | displayName: ${u.profile?.displayName ?? \"—\"}`)\n .join(\"\\n\");\n\n const assignmentSummary = assignments\n .map((a) => {\n const sectionName = a.section?.name ?? \"—\";\n return ` - id: ${a.id} | title: \"${a.title}\" | type: ${a.type} | section: \"${sectionName}\" | due: ${a.dueDate.toISOString().slice(0, 10)}`;\n })\n .join(\"\\n\");\n\n return `\nCLASS: ${cls.name} | Subject: ${cls.subject} | Section: ${cls.section}\nSyllabus: ${cls.syllabus ? cls.syllabus.slice(0, 200) + (cls.syllabus.length > 200 ? \"…\" : \"\") : \"(none)\"}\n\nSECTIONS (use sectionId when creating assignments):\n${sectionList || \" (none - suggest sectionsToCreate first)\"}\n\nMARK SCHEMES (use markSchemeId when creating assignments):\n${markSchemeList || \" (none - suggest creating one or omit markSchemeId)\"}\n\nGRADING BOUNDARIES (use gradingBoundaryId when creating assignments):\n${gradingBoundaryList || \" (none - suggest creating one or omit gradingBoundaryId)\"}\n\nWORKSHEETS (use worksheetIds when acceptWorksheet is true):\n${worksheetList || \" (none - use worksheetsToCreate or create via docs first)\"}\n\nFILES - PDFs/Documents (for assignment attachments):\n${fileList || \" (none)\"}\n\nFILES - Other (for assignment attachments):\n${otherFileList}\n\nSTUDENTS (use studentIds for specific assignment; empty array = all students):\n${studentList || \" (none)\"}\n\nEXISTING ASSIGNMENTS (for reference, avoid duplicates):\n${assignmentSummary || \" (none)\"}\n`.trim();\n};\n\n/**\n * @deprecated Use buildClassContextForAI for schema-aware context. Kept for compatibility.\n */\nexport const getBaseSystemPrompt = (\n context: Class,\n members: User[],\n assignments: Assignment[],\n files: File[],\n sections: Section[]\n): string => {\n return buildClassContextForAI({\n class: context,\n sections,\n markSchemes: [],\n gradingBoundaries: [],\n worksheets: [],\n files,\n students: members,\n teachers: [],\n assignments,\n });\n};\n\n\n\n/**\n * Fill the AI introduction placeholder for a brand-new lab chat.\n *\n * The caller (service layer) must have already created a PENDING AI Message\n * row — `aiMessageId` is that placeholder. This function flips it to\n * COMPLETED with the intro content, or to FAILED on a hard error.\n */\nexport const generateAndSendLabIntroduction = async (\n labChatId: string,\n conversationId: string,\n _contextString: string,\n _subject: string,\n aiMessageId: string,\n ): Promise<void> => {\n const introMessage =\n \"Hello teaching team! I'm your AI assistant for course material development. I can create worksheets, assignments, and downloadable files — PDFs, Word docs, PowerPoints, spreadsheets, and more. When you have a clear request, I'll produce it directly. I only ask questions when I need to clarify the topic or scope. What would you like to work on?\";\n\n try {\n await broadcastTextChunks(conversationId, aiMessageId, introMessage);\n await completePendingAIMessage(aiMessageId, introMessage);\n logger.info('AI Introduction sent', { labChatId, conversationId, aiMessageId });\n } catch (error) {\n logger.error('Failed to complete AI introduction placeholder:', {\n error,\n labChatId,\n aiMessageId,\n });\n await failPendingAIMessage(aiMessageId, { reason: 'lab_intro_complete_failed' });\n }\n }\n \n /**\n * Fill the AI response placeholder for a teacher reply in a lab chat.\n *\n * `aiMessageId` is the PENDING AI Message row created by the service\n * layer; the pipeline flips it to COMPLETED with content / attachments /\n * meta, or FAILED on error. Teacher-channel `lab-response-{pending,\n * completed,failed}` events fire alongside the chat-channel status flips\n * (which `completePendingAIMessage` / `failPendingAIMessage` already\n * broadcast) so the lab list \"AI busy\" indicator stays accurate.\n *\n * `_teacherMessage` is retained for caller compatibility — the actual\n * conversation history is reloaded from the DB anchored on the AI\n * placeholder.\n */\n export const generateAndSendLabResponse = async (\n labChatId: string,\n teacherMessage: string,\n emitOptions: { classId: string; aiMessageId: string }\n ): Promise<void> => {\n try {\n // Get lab context from database\n const fullLabChat = await prisma.labChat.findUnique({\n where: { id: labChatId },\n include: {\n class: {\n select: {\n name: true,\n subject: true,\n },\n },\n },\n });\n \n if (!fullLabChat) {\n throw new Error('Lab chat not found');\n }\n \n const conversationId = fullLabChat.conversationId;\n \n // Anchor history on the AI placeholder — the slice will include the\n // placeholder itself (empty content) at the top; drop it so the model\n // does not see an empty assistant turn at the very end.\n const anchoredMessages = await loadRecentLabChatMessages(\n conversationId,\n emitOptions.aiMessageId,\n );\n const recentMessages = anchoredMessages.filter(\n (msg) => msg.id !== emitOptions.aiMessageId,\n );\n \n const classData = await prisma.class.findUnique({\n where: {\n id: fullLabChat.classId,\n },\n include: {\n assignments: {\n include: {\n section: { select: { id: true, name: true, order: true } },\n markScheme: { select: { id: true } },\n gradingBoundary: { select: { id: true } },\n },\n },\n sections: true,\n markSchemes: { select: { id: true, structured: true } },\n gradingBoundaries: { select: { id: true, structured: true } },\n worksheets: {\n select: {\n id: true,\n name: true,\n _count: { select: { questions: true } },\n },\n },\n students: {\n select: {\n id: true,\n username: true,\n profile: { select: { displayName: true } },\n },\n },\n teachers: {\n select: {\n id: true,\n username: true,\n profile: { select: { displayName: true } },\n },\n },\n classFiles: {\n include: {\n files: true,\n },\n },\n },\n });\n\n if (!classData) {\n throw new Error('Class not found');\n }\n\n const classContext = buildClassContextForAI({\n class: classData,\n sections: classData.sections,\n markSchemes: classData.markSchemes,\n gradingBoundaries: classData.gradingBoundaries,\n worksheets: classData.worksheets.map((w) => ({\n id: w.id,\n name: w.name,\n questionCount: w._count.questions,\n })),\n files: classData.classFiles?.files ?? [],\n students: classData.students,\n teachers: classData.teachers,\n assignments: classData.assignments,\n });\n\n // Resolve signed URLs for image attachments so the LLM can see them\n const messagesWithAttachments = await resolveAttachmentUrls(recentMessages.reverse());\n\n const { system, messages } = buildLabChatAgentMessages({\n context: fullLabChat.context,\n classContext,\n recentMessages: messagesWithAttachments,\n isAIUser,\n });\n\n // Genuine agentic generation: the model streams prose token-by-token and\n // calls real tools inline — read-only RAG lookups plus \"propose_*\" tools\n // that record create-actions into `proposals`. `streamChatResponse`\n // broadcasts the real text chunks and tool-call events as they happen.\n const proposals = createLabProposals();\n const tools = {\n ...aiTools(fullLabChat.classId),\n ...labProposalTools(proposals),\n };\n\n const { text: streamedText, parts: rawStreamParts } = await withTimeout(\n streamChatResponse({\n conversationId,\n aiMessageId: emitOptions.aiMessageId,\n system,\n messages,\n tools,\n temperature: 0.7,\n maxOutputTokens: 4096,\n maxSteps: 8,\n }),\n LAB_CHAT_RESPONSE_TIMEOUT_MS,\n \"Lab chat response generation\",\n );\n\n // Real text + tool-call events were already broadcast inline (in order)\n // during the stream by `streamChatResponse`. Just close the stream.\n await broadcastStreamComplete(conversationId, emitOptions.aiMessageId);\n\n // `generate_document` is an inline tool that only QUEUES into `proposals.docs`\n // during the stream. OpenAI Code Interpreter renders files here, after the\n // stream ends, then we link them to this message.\n try {\n const attachmentIds: string[] = [];\n const generatedDocFiles: GeneratedDocFileLink[] = [];\n const resolvedDocs: Array<{ title: string; format: string }> = [];\n\n for (const doc of proposals.docs) {\n if (!doc.title || !doc.content?.trim()) {\n logger.error('Document missing title or content', { labChatId, doc });\n continue;\n }\n\n const format = inferDocumentFormat(\n doc.title,\n doc.content,\n doc.format,\n teacherMessage,\n );\n resolvedDocs.push({ title: doc.title, format });\n\n if (format !== normalizeDocumentFormat(doc.format)) {\n logger.info('Document format overridden from model default', {\n labChatId,\n title: doc.title,\n modelFormat: doc.format,\n resolvedFormat: format,\n });\n }\n\n try {\n const generated = await generateDocumentWithOpenAI({\n title: doc.title,\n content: doc.content,\n format,\n });\n if (!generated) {\n logger.error('OpenAI document generation returned null', {\n labChatId,\n title: doc.title,\n format: doc.format,\n });\n continue;\n }\n\n const sanitizedTitle = doc.title\n .replace(/[^a-zA-Z0-9\\s\\-_]/g, '')\n .replace(/\\s+/g, '_')\n .substring(0, 50);\n const filename = `${sanitizedTitle}_${v4().substring(0, 8)}.${generated.format}`;\n const filePath = `class/generated/${fullLabChat.classId}/${filename}`;\n\n await bucket.file(filePath).save(generated.bytes, {\n metadata: { contentType: generated.mimeType },\n });\n\n const file = await prisma.file.create({\n data: {\n name: filename,\n path: filePath,\n type: generated.mimeType,\n size: generated.bytes.length,\n userId: fullLabChat.createdById,\n conversationId,\n messageId: emitOptions.aiMessageId,\n uploadStatus: 'COMPLETED',\n uploadedAt: new Date(),\n },\n });\n\n attachmentIds.push(file.id);\n generatedDocFiles.push({\n title: doc.title,\n fileId: file.id,\n fileName: filename,\n format: generated.format,\n });\n } catch (docError) {\n logger.error('Document generation failed', {\n error: docError instanceof Error ? {\n message: docError.message,\n stack: docError.stack,\n name: docError.name,\n } : docError,\n labChatId,\n title: doc.title,\n format: doc.format,\n });\n }\n }\n \n const streamParts: StreamPart[] = enrichStreamPartsWithGeneratedFiles(\n applyResolvedFormatsToStreamParts(rawStreamParts, resolvedDocs),\n generatedDocFiles,\n );\n\n for (const part of streamParts) {\n if (\n part.type === 'tool' &&\n part.toolName === 'generate_document' &&\n part.fileId\n ) {\n await pusher\n .trigger(chatChannel(conversationId), 'message-tool-call', {\n messageId: emitOptions.aiMessageId,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n ...(part.title ? { title: part.title } : {}),\n ...(part.format ? { format: part.format } : {}),\n fileId: part.fileId,\n fileName: part.fileName,\n status: 'completed',\n })\n .catch(() => {});\n }\n }\n\n await completePendingAIMessage(emitOptions.aiMessageId, streamedText, {\n ...(attachmentIds.length > 0 && {\n attachments: { connect: attachmentIds.map((id) => ({ id })) },\n }),\n meta: {\n assignmentsToCreate: proposals.assignments.length > 0\n ? proposals.assignments.map(assignment => ({ ...assignment, id: v4() }))\n : null,\n worksheetsToCreate: proposals.worksheets.length > 0\n ? proposals.worksheets.map(worksheet => ({ ...worksheet, id: v4() }))\n : null,\n sectionsToCreate: proposals.sections.length > 0\n ? proposals.sections.map(section => ({ ...section, id: v4() }))\n : null,\n streamParts: streamParts.length > 0 ? streamParts : null,\n },\n });\n } catch (persistError) {\n logger.error('Failed to persist AI response or generate PDF:', { error: persistError, labChatId });\n // Fallback: complete the placeholder with the raw text so the\n // teacher still sees something useful instead of FAILED.\n await completePendingAIMessage(emitOptions.aiMessageId, streamedText);\n }\n\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-completed\", {\n labChatId,\n messageId: emitOptions.aiMessageId,\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response completed:\", { error: broadcastError });\n }\n\n logger.info('AI response sent', { labChatId, conversationId, aiMessageId: emitOptions.aiMessageId });\n\n } catch (error) {\n console.error('Full error object:', error);\n logger.error('Failed to generate AI response:', {\n error: error instanceof Error ? {\n message: error.message,\n stack: error.stack,\n name: error.name\n } : error,\n labChatId,\n aiMessageId: emitOptions.aiMessageId,\n });\n\n await failPendingAIMessage(emitOptions.aiMessageId, {\n reason: 'lab_response_generation_failed',\n });\n\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-failed\", {\n labChatId,\n messageId: emitOptions.aiMessageId,\n error: \"AI response generation failed\",\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response failed:\", { error: broadcastError });\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