@studious-lms/server 1.4.4 → 1.4.6

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 (93) hide show
  1. package/dist/index.js +3 -17
  2. package/dist/index.js.map +1 -1
  3. package/dist/lib/config/cors.d.ts.map +1 -1
  4. package/dist/lib/config/cors.js +8 -3
  5. package/dist/lib/config/cors.js.map +1 -1
  6. package/dist/models/comment.d.ts +163 -0
  7. package/dist/models/comment.d.ts.map +1 -1
  8. package/dist/models/comment.js +145 -3
  9. package/dist/models/comment.js.map +1 -1
  10. package/dist/models/conversation.d.ts +22 -0
  11. package/dist/models/conversation.d.ts.map +1 -1
  12. package/dist/models/conversation.js +13 -2
  13. package/dist/models/conversation.js.map +1 -1
  14. package/dist/models/labChat.d.ts +3 -0
  15. package/dist/models/labChat.d.ts.map +1 -1
  16. package/dist/models/message.d.ts +2 -0
  17. package/dist/models/message.d.ts.map +1 -1
  18. package/dist/models/newtonChat.d.ts +1 -0
  19. package/dist/models/newtonChat.d.ts.map +1 -1
  20. package/dist/models/worksheet.d.ts +2 -0
  21. package/dist/models/worksheet.d.ts.map +1 -1
  22. package/dist/pipelines/aiLabChat.d.ts.map +1 -1
  23. package/dist/pipelines/aiLabChat.js +4 -3
  24. package/dist/pipelines/aiLabChat.js.map +1 -1
  25. package/dist/routers/_app.d.ts +665 -1
  26. package/dist/routers/_app.d.ts.map +1 -1
  27. package/dist/routers/_app.js +4 -2
  28. package/dist/routers/_app.js.map +1 -1
  29. package/dist/routers/announcement.d.ts +8 -0
  30. package/dist/routers/announcement.d.ts.map +1 -1
  31. package/dist/routers/assignment.d.ts +230 -0
  32. package/dist/routers/assignment.d.ts.map +1 -1
  33. package/dist/routers/assignment.js +207 -2
  34. package/dist/routers/assignment.js.map +1 -1
  35. package/dist/routers/comment.d.ts +37 -0
  36. package/dist/routers/comment.d.ts.map +1 -1
  37. package/dist/routers/comment.js +14 -5
  38. package/dist/routers/comment.js.map +1 -1
  39. package/dist/routers/conversation.d.ts +14 -0
  40. package/dist/routers/conversation.d.ts.map +1 -1
  41. package/dist/routers/conversation.js +6 -3
  42. package/dist/routers/conversation.js.map +1 -1
  43. package/dist/routers/labChat.d.ts +2 -0
  44. package/dist/routers/labChat.d.ts.map +1 -1
  45. package/dist/routers/search.d.ts +41 -0
  46. package/dist/routers/search.d.ts.map +1 -0
  47. package/dist/routers/search.js +15 -0
  48. package/dist/routers/search.js.map +1 -0
  49. package/dist/routers/worksheet.d.ts +2 -0
  50. package/dist/routers/worksheet.d.ts.map +1 -1
  51. package/dist/services/comment.d.ts +28 -2
  52. package/dist/services/comment.d.ts.map +1 -1
  53. package/dist/services/comment.js +97 -19
  54. package/dist/services/comment.js.map +1 -1
  55. package/dist/services/conversation.d.ts +8 -0
  56. package/dist/services/conversation.d.ts.map +1 -1
  57. package/dist/services/conversation.js +24 -6
  58. package/dist/services/conversation.js.map +1 -1
  59. package/dist/services/labChat.d.ts +2 -0
  60. package/dist/services/labChat.d.ts.map +1 -1
  61. package/dist/services/message.d.ts.map +1 -1
  62. package/dist/services/message.js +9 -2
  63. package/dist/services/message.js.map +1 -1
  64. package/dist/services/search.d.ts +21 -0
  65. package/dist/services/search.d.ts.map +1 -0
  66. package/dist/services/search.js +352 -0
  67. package/dist/services/search.js.map +1 -0
  68. package/dist/services/worksheet.d.ts +2 -0
  69. package/dist/services/worksheet.d.ts.map +1 -1
  70. package/package.json +1 -1
  71. package/prisma/migrations/20260417083000_add_conversation_member_hidden_at/migration.sql +2 -0
  72. package/prisma/migrations/20260502230500_assignment_submission_comments/migration.sql +60 -0
  73. package/prisma/schema.prisma +10 -0
  74. package/src/index.ts +1 -17
  75. package/src/lib/config/cors.ts +8 -1
  76. package/src/models/comment.ts +148 -1
  77. package/src/models/conversation.ts +12 -0
  78. package/src/pipelines/aiLabChat.ts +2 -1
  79. package/src/routers/_app.ts +2 -0
  80. package/src/routers/assignment.ts +224 -1
  81. package/src/routers/comment.ts +19 -2
  82. package/src/routers/conversation.ts +7 -0
  83. package/src/routers/search.ts +14 -0
  84. package/src/services/comment.ts +113 -18
  85. package/src/services/conversation.ts +27 -3
  86. package/src/services/message.ts +8 -0
  87. package/src/services/search.ts +397 -0
  88. package/tests/lib/cors.test.ts +13 -1
  89. package/tests/routers/assignment.test.ts +68 -2
  90. package/tests/routers/comment.test.ts +42 -1
  91. package/tests/routers/conversation.test.ts +114 -2
  92. package/tests/routers/search.test.ts +109 -0
  93. package/vercel.json +8 -0
@@ -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 { GenerationStatus } from \"@prisma/client\";\nimport { pusher, teacherChannel } from \"../lib/pusher.js\";\nimport type { Assignment, Class, File, Section, User } from \"@prisma/client\";\nimport { inference, sendAIMessage } 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 { type LabChatResponse, labChatResponseSchema } from \"./aiLabChatContract.js\";\nimport { buildLabChatResponseMessages } from \"./labChatPrompt.js\";\n\nconst LAB_CHAT_RESPONSE_TIMEOUT_MS = 90_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 * Generate labchat responses\n * Allow for the generation of the following:\n * - Assignment(s) either individual or bulk as an lesson / course plan.\n * - Worksheet(s) either individual or bulk as an lesson / course plan.\n * - Files (PDFs)\n * @param labChatId \n */\n// export const sendAiLabChatResponsePipeline = async (labChatId: string) => {\n// const message = await prisma?.message.create({\n// data: {\n// content: \"GENERATING_CONTENT\",\n// senderId: getAIUserId(),\n// conversationId: labChatId,\n// status: GenerationStatus.PENDING, \n// },\n// });\n\n// try {\n\n// inference(`\n// `)\n// }\n \n// };\n\n\n/**\n * Generate and send AI introduction for lab chat\n * Uses the stored context directly from database\n */\nexport const generateAndSendLabIntroduction = async (\n labChatId: string,\n conversationId: string,\n _contextString: string,\n subject: string\n ): Promise<void> => {\n try {\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 await sendAIMessage(introMessage, conversationId, { subject });\n \n logger.info('AI Introduction sent', { labChatId, conversationId });\n \n } catch (error) {\n logger.error('Failed to generate AI introduction:', { error, labChatId });\n \n // Send fallback introduction\n try {\n const fallbackIntro = `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 await sendAIMessage(fallbackIntro, conversationId, {\n subject,\n });\n \n logger.info('Fallback AI introduction sent', { labChatId });\n \n } catch (fallbackError) {\n logger.error('Failed to send fallback AI introduction:', { error: fallbackError, labChatId });\n }\n }\n }\n \n /**\n * Generate and send AI response to teacher message\n * Uses the stored context directly from database\n * @param emitOptions - When provided, emits lab-response-completed/failed on teacher channel\n * `_teacherMessage` is retained for caller compatibility while generation is anchored by `emitOptions.messageId`.\n */\n export const generateAndSendLabResponse = async (\n labChatId: string,\n _teacherMessage: string,\n emitOptions?: { classId: string; messageId: 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 const recentMessages = await loadRecentLabChatMessages(\n conversationId,\n emitOptions?.messageId,\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 messages = buildLabChatResponseMessages({\n context: fullLabChat.context,\n classContext,\n recentMessages: recentMessages.reverse(),\n isAIUser,\n });\n \n \n // const completion = await inferenceClient.chat.completions.create({\n // model: 'command-a-03-2025',\n // messages,\n // temperature: 0.7,\n // response_format: zodTextFormat(labChatResponseSchema, \"lab_chat_response_format\"),\n // });\n\n const response = await withTimeout(\n inference<LabChatResponse>(messages, labChatResponseSchema, {\n reason: 'lab_chat_response',\n metadata: {\n labChatId,\n conversationId,\n classId: fullLabChat.classId,\n ...(emitOptions?.messageId ? { messageId: emitOptions.messageId } : {}),\n },\n }),\n LAB_CHAT_RESPONSE_TIMEOUT_MS,\n \"Lab chat response generation\",\n );\n \n if (!response) {\n throw new Error('No response generated from inference API');\n }\n // Parse the JSON response and generate PDF if docs are provided\n try {\n const jsonData = response;\n \n \n const attachmentIds: string[] = [];\n // Generate PDFs if docs are provided\n if (jsonData.docs && Array.isArray(jsonData.docs)) {\n \n \n for (let i = 0; i < jsonData.docs.length; i++) {\n const doc = jsonData.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 // Send the text response to the conversation\n await sendAIMessage(jsonData.text, conversationId, {\n attachments: {\n connect: attachmentIds.map(id => ({ id })),\n },\n meta: {\n assignmentsToCreate: jsonData.assignmentsToCreate?.map(assignment => ({\n ...assignment,\n id: v4(),\n })) || null,\n worksheetsToCreate: jsonData.worksheetsToCreate?.map(worksheet => ({\n ...worksheet,\n id: v4(),\n })) || null,\n sectionsToCreate: jsonData.sectionsToCreate?.map(section => ({\n ...section,\n id: v4(),\n })) || null,\n },\n subject: fullLabChat.class?.subject || 'Lab',\n });\n } catch (parseError) {\n logger.error('Failed to parse AI response or generate PDF:', { error: parseError, labChatId });\n // Fallback: send the raw response if parsing fails\n await sendAIMessage(response.text, conversationId, {\n subject: fullLabChat.class?.subject || 'Lab',\n });\n }\n\n if (emitOptions) {\n await prisma.message.update({\n where: { id: emitOptions.messageId },\n data: { status: GenerationStatus.COMPLETED },\n });\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-completed\", {\n labChatId,\n messageId: emitOptions.messageId,\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response completed:\", { error: broadcastError });\n }\n }\n\n logger.info('AI response sent', { labChatId, conversationId });\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 });\n\n if (emitOptions) {\n try {\n await prisma.message.update({\n where: { id: emitOptions.messageId },\n data: { status: GenerationStatus.FAILED },\n });\n } catch (statusError) {\n logger.error(\"Failed to set message status FAILED:\", {\n error: statusError,\n labChatId,\n messageId: emitOptions.messageId,\n });\n }\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-failed\", {\n labChatId,\n messageId: emitOptions.messageId,\n error: \"AI response generation failed\",\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response failed:\", { error: broadcastError });\n }\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,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AAEtD,OAAO,EAAwB,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAElE,MAAM,4BAA4B,GAAG,KAAM,CAAC;AAE5C,MAAM,WAAW,GAAG,KAAK,EACvB,IAAgB,EAChB,SAAiB,EACjB,aAAqB,EACT,EAAE;IACd,IAAI,aAAyC,CAAC;IAC9C,MAAM,cAAc,GAAG,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;QACtD,aAAa,GAAG,UAAU,CAAC,GAAG,EAAE;YAC9B,MAAM,C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E,WAAW;oBAClB,SAAS;oBACT,SAAS,EAAE,WAAW,CAAC,SAAS;iBACjC,CAAC,CAAC;YACL,CAAC;YACD,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,qBAAqB,EAAE;oBAC/E,SAAS;oBACT,SAAS,EAAE,WAAW,CAAC,SAAS;oBAChC,KAAK,EAAE,+BAA+B;iBACvC,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,cAAc,EAAE,CAAC;gBACxB,MAAM,CAAC,KAAK,CAAC,0CAA0C,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;YACtF,CAAC;QACH,CAAC;QAED,MAAM,KAAK,CAAC,CAAC,yDAAyD;IACxE,CAAC;AACH,CAAC,CAAA","debug_id":"9e1c8d5f-8cb6-52e4-b180-55ace3db9ca5"}
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 { GenerationStatus } from \"@prisma/client\";\nimport { pusher, teacherChannel } from \"../lib/pusher.js\";\nimport type { Assignment, Class, File, Section, User } from \"@prisma/client\";\nimport { inference, sendAIMessage } 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 { type LabChatResponse, labChatResponseSchema } from \"./aiLabChatContract.js\";\nimport { buildLabChatResponseMessages } from \"./labChatPrompt.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 * Generate labchat responses\n * Allow for the generation of the following:\n * - Assignment(s) either individual or bulk as an lesson / course plan.\n * - Worksheet(s) either individual or bulk as an lesson / course plan.\n * - Files (PDFs)\n * @param labChatId \n */\n// export const sendAiLabChatResponsePipeline = async (labChatId: string) => {\n// const message = await prisma?.message.create({\n// data: {\n// content: \"GENERATING_CONTENT\",\n// senderId: getAIUserId(),\n// conversationId: labChatId,\n// status: GenerationStatus.PENDING, \n// },\n// });\n\n// try {\n\n// inference(`\n// `)\n// }\n \n// };\n\n\n/**\n * Generate and send AI introduction for lab chat\n * Uses the stored context directly from database\n */\nexport const generateAndSendLabIntroduction = async (\n labChatId: string,\n conversationId: string,\n _contextString: string,\n subject: string\n ): Promise<void> => {\n try {\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 await sendAIMessage(introMessage, conversationId, { subject });\n \n logger.info('AI Introduction sent', { labChatId, conversationId });\n \n } catch (error) {\n logger.error('Failed to generate AI introduction:', { error, labChatId });\n \n // Send fallback introduction\n try {\n const fallbackIntro = `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 await sendAIMessage(fallbackIntro, conversationId, {\n subject,\n });\n \n logger.info('Fallback AI introduction sent', { labChatId });\n \n } catch (fallbackError) {\n logger.error('Failed to send fallback AI introduction:', { error: fallbackError, labChatId });\n }\n }\n }\n \n /**\n * Generate and send AI response to teacher message\n * Uses the stored context directly from database\n * @param emitOptions - When provided, emits lab-response-completed/failed on teacher channel\n * `_teacherMessage` is retained for caller compatibility while generation is anchored by `emitOptions.messageId`.\n */\n export const generateAndSendLabResponse = async (\n labChatId: string,\n _teacherMessage: string,\n emitOptions?: { classId: string; messageId: 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 const recentMessages = await loadRecentLabChatMessages(\n conversationId,\n emitOptions?.messageId,\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 messages = buildLabChatResponseMessages({\n context: fullLabChat.context,\n classContext,\n recentMessages: recentMessages.reverse(),\n isAIUser,\n });\n \n \n // const completion = await inferenceClient.chat.completions.create({\n // model: 'command-a-03-2025',\n // messages,\n // temperature: 0.7,\n // response_format: zodTextFormat(labChatResponseSchema, \"lab_chat_response_format\"),\n // });\n\n const response = await withTimeout(\n inference<LabChatResponse>(messages, labChatResponseSchema, {\n reason: 'lab_chat_response',\n metadata: {\n labChatId,\n conversationId,\n classId: fullLabChat.classId,\n ...(emitOptions?.messageId ? { messageId: emitOptions.messageId } : {}),\n },\n }),\n LAB_CHAT_RESPONSE_TIMEOUT_MS,\n \"Lab chat response generation\",\n );\n \n if (!response) {\n throw new Error('No response generated from inference API');\n }\n // Parse the JSON response and generate PDF if docs are provided\n try {\n const jsonData = response;\n \n \n const attachmentIds: string[] = [];\n // Generate PDFs if docs are provided\n if (jsonData.docs && Array.isArray(jsonData.docs)) {\n \n \n for (let i = 0; i < jsonData.docs.length; i++) {\n const doc = jsonData.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 // Send the text response to the conversation\n await sendAIMessage(jsonData.text, conversationId, {\n attachments: {\n connect: attachmentIds.map(id => ({ id })),\n },\n meta: {\n assignmentsToCreate: jsonData.assignmentsToCreate?.map(assignment => ({\n ...assignment,\n id: v4(),\n })) || null,\n worksheetsToCreate: jsonData.worksheetsToCreate?.map(worksheet => ({\n ...worksheet,\n id: v4(),\n })) || null,\n sectionsToCreate: jsonData.sectionsToCreate?.map(section => ({\n ...section,\n id: v4(),\n })) || null,\n },\n subject: fullLabChat.class?.subject || 'Lab',\n });\n } catch (parseError) {\n logger.error('Failed to parse AI response or generate PDF:', { error: parseError, labChatId });\n // Fallback: send the raw response if parsing fails\n await sendAIMessage(response.text, conversationId, {\n subject: fullLabChat.class?.subject || 'Lab',\n });\n }\n\n if (emitOptions) {\n await prisma.message.update({\n where: { id: emitOptions.messageId },\n data: { status: GenerationStatus.COMPLETED },\n });\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-completed\", {\n labChatId,\n messageId: emitOptions.messageId,\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response completed:\", { error: broadcastError });\n }\n }\n\n logger.info('AI response sent', { labChatId, conversationId });\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 });\n\n if (emitOptions) {\n try {\n await prisma.message.update({\n where: { id: emitOptions.messageId },\n data: { status: GenerationStatus.FAILED },\n });\n } catch (statusError) {\n logger.error(\"Failed to set message status FAILED:\", {\n error: statusError,\n labChatId,\n messageId: emitOptions.messageId,\n });\n }\n try {\n await pusher.trigger(teacherChannel(emitOptions.classId), \"lab-response-failed\", {\n labChatId,\n messageId: emitOptions.messageId,\n error: \"AI response generation failed\",\n });\n } catch (broadcastError) {\n logger.error(\"Failed to broadcast lab response failed:\", { error: broadcastError });\n }\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,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AAEtD,OAAO,EAAwB,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAA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