@studious-lms/server 1.16.0 → 1.16.1

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 (151) hide show
  1. package/.github/workflows/deploy.yml +1 -1
  2. package/dist/instrument.js +3 -3
  3. package/dist/instrument.js.map +1 -1
  4. package/dist/lib/chatAttachmentPrompt.d.ts +47 -0
  5. package/dist/lib/chatAttachmentPrompt.d.ts.map +1 -0
  6. package/dist/lib/chatAttachmentPrompt.js +190 -0
  7. package/dist/lib/chatAttachmentPrompt.js.map +1 -0
  8. package/dist/lib/inferDocumentFormat.js +3 -3
  9. package/dist/lib/inferDocumentFormat.js.map +1 -1
  10. package/dist/lib/legal.d.ts +3 -0
  11. package/dist/lib/legal.d.ts.map +1 -0
  12. package/dist/lib/legal.js +6 -0
  13. package/dist/lib/legal.js.map +1 -0
  14. package/dist/models/announcement.d.ts +2 -0
  15. package/dist/models/announcement.d.ts.map +1 -1
  16. package/dist/models/auth.d.ts +8 -0
  17. package/dist/models/auth.d.ts.map +1 -1
  18. package/dist/models/auth.js +4 -2
  19. package/dist/models/auth.js.map +1 -1
  20. package/dist/models/event.d.ts +2 -0
  21. package/dist/models/event.d.ts.map +1 -1
  22. package/dist/models/file.d.ts +24 -0
  23. package/dist/models/file.d.ts.map +1 -1
  24. package/dist/models/marketing.d.ts +2 -15
  25. package/dist/models/marketing.d.ts.map +1 -1
  26. package/dist/models/marketing.js +12 -4
  27. package/dist/models/marketing.js.map +1 -1
  28. package/dist/pipelines/aiLabChat.d.ts.map +1 -1
  29. package/dist/pipelines/aiLabChat.js +39 -59
  30. package/dist/pipelines/aiLabChat.js.map +1 -1
  31. package/dist/pipelines/aiLabChatContract.d.ts +2 -2
  32. package/dist/pipelines/aiNewtonChat.d.ts +1 -1
  33. package/dist/pipelines/aiNewtonChat.d.ts.map +1 -1
  34. package/dist/pipelines/aiNewtonChat.js +20 -19
  35. package/dist/pipelines/aiNewtonChat.js.map +1 -1
  36. package/dist/pipelines/gradeWorksheet.d.ts +1 -0
  37. package/dist/pipelines/gradeWorksheet.d.ts.map +1 -1
  38. package/dist/pipelines/gradeWorksheet.js +84 -13
  39. package/dist/pipelines/gradeWorksheet.js.map +1 -1
  40. package/dist/pipelines/labChatPrompt.d.ts +4 -20
  41. package/dist/pipelines/labChatPrompt.d.ts.map +1 -1
  42. package/dist/pipelines/labChatPrompt.js +24 -64
  43. package/dist/pipelines/labChatPrompt.js.map +1 -1
  44. package/dist/routers/_app.d.ts +236 -26
  45. package/dist/routers/_app.d.ts.map +1 -1
  46. package/dist/routers/assignment.d.ts +10 -0
  47. package/dist/routers/assignment.d.ts.map +1 -1
  48. package/dist/routers/auth.d.ts +2 -0
  49. package/dist/routers/auth.d.ts.map +1 -1
  50. package/dist/routers/auth.js +15 -2
  51. package/dist/routers/auth.js.map +1 -1
  52. package/dist/routers/class.d.ts +4 -0
  53. package/dist/routers/class.d.ts.map +1 -1
  54. package/dist/routers/event.d.ts +2 -0
  55. package/dist/routers/event.d.ts.map +1 -1
  56. package/dist/routers/marketing.d.ts +0 -13
  57. package/dist/routers/marketing.d.ts.map +1 -1
  58. package/dist/routers/school.d.ts +4 -0
  59. package/dist/routers/school.d.ts.map +1 -1
  60. package/dist/routers/user.d.ts +89 -0
  61. package/dist/routers/user.d.ts.map +1 -1
  62. package/dist/routers/user.js +19 -2
  63. package/dist/routers/user.js.map +1 -1
  64. package/dist/routers/worksheet.d.ts +7 -0
  65. package/dist/routers/worksheet.d.ts.map +1 -1
  66. package/dist/routers/worksheet.js +8 -3
  67. package/dist/routers/worksheet.js.map +1 -1
  68. package/dist/seedDatabase.d.ts +2 -0
  69. package/dist/seedDatabase.d.ts.map +1 -1
  70. package/dist/services/aiChatStream.d.ts +2 -0
  71. package/dist/services/aiChatStream.d.ts.map +1 -1
  72. package/dist/services/aiChatStream.js +31 -4
  73. package/dist/services/aiChatStream.js.map +1 -1
  74. package/dist/services/aiProposalTools.d.ts.map +1 -1
  75. package/dist/services/aiProposalTools.js +9 -9
  76. package/dist/services/aiProposalTools.js.map +1 -1
  77. package/dist/services/aiTools.js +3 -3
  78. package/dist/services/aiTools.js.map +1 -1
  79. package/dist/services/assignment.d.ts +10 -0
  80. package/dist/services/assignment.d.ts.map +1 -1
  81. package/dist/services/auth.d.ts +2 -0
  82. package/dist/services/auth.d.ts.map +1 -1
  83. package/dist/services/auth.js +13 -4
  84. package/dist/services/auth.js.map +1 -1
  85. package/dist/services/class.d.ts +4 -0
  86. package/dist/services/class.d.ts.map +1 -1
  87. package/dist/services/event.d.ts +2 -0
  88. package/dist/services/event.d.ts.map +1 -1
  89. package/dist/services/marketing.d.ts +1 -14
  90. package/dist/services/marketing.d.ts.map +1 -1
  91. package/dist/services/marketing.js +5 -5
  92. package/dist/services/marketing.js.map +1 -1
  93. package/dist/services/newtonChat.d.ts.map +1 -1
  94. package/dist/services/newtonChat.js +2 -8
  95. package/dist/services/newtonChat.js.map +1 -1
  96. package/dist/services/openaiDocumentGen.d.ts +12 -0
  97. package/dist/services/openaiDocumentGen.d.ts.map +1 -1
  98. package/dist/services/openaiDocumentGen.js +173 -65
  99. package/dist/services/openaiDocumentGen.js.map +1 -1
  100. package/dist/services/school.d.ts +4 -0
  101. package/dist/services/school.d.ts.map +1 -1
  102. package/dist/services/userPrivacy.d.ts +86 -0
  103. package/dist/services/userPrivacy.d.ts.map +1 -0
  104. package/dist/services/userPrivacy.js +184 -0
  105. package/dist/services/userPrivacy.js.map +1 -0
  106. package/dist/services/worksheet.d.ts +1 -0
  107. package/dist/services/worksheet.d.ts.map +1 -1
  108. package/dist/services/worksheet.js +13 -3
  109. package/dist/services/worksheet.js.map +1 -1
  110. package/dist/utils/email.d.ts.map +1 -1
  111. package/dist/utils/email.js +7 -3
  112. package/dist/utils/email.js.map +1 -1
  113. package/dist/workers/processors/aiNewtonChat.d.ts.map +1 -1
  114. package/dist/workers/processors/aiNewtonChat.js +3 -3
  115. package/dist/workers/processors/aiNewtonChat.js.map +1 -1
  116. package/package.json +2 -1
  117. package/prisma/migrations/20260611120000_add_user_terms_acceptance/migration.sql +3 -0
  118. package/prisma/schema.prisma +3 -0
  119. package/src/instrument.ts +1 -1
  120. package/src/lib/chatAttachmentPrompt.ts +270 -0
  121. package/src/lib/inferDocumentFormat.ts +1 -1
  122. package/src/lib/legal.ts +2 -0
  123. package/src/models/auth.ts +4 -0
  124. package/src/models/marketing.ts +10 -2
  125. package/src/pipelines/aiLabChat.ts +46 -71
  126. package/src/pipelines/aiNewtonChat.ts +20 -23
  127. package/src/pipelines/gradeWorksheet.ts +87 -11
  128. package/src/pipelines/labChatPrompt.ts +29 -98
  129. package/src/routers/auth.ts +13 -0
  130. package/src/routers/user.ts +26 -0
  131. package/src/routers/worksheet.ts +11 -0
  132. package/src/services/aiChatStream.ts +30 -3
  133. package/src/services/aiProposalTools.ts +8 -7
  134. package/src/services/aiTools.ts +1 -1
  135. package/src/services/auth.ts +14 -2
  136. package/src/services/marketing.ts +3 -3
  137. package/src/services/newtonChat.ts +0 -7
  138. package/src/services/openaiDocumentGen.ts +190 -66
  139. package/src/services/userPrivacy.ts +196 -0
  140. package/src/services/worksheet.ts +20 -1
  141. package/src/utils/email.ts +5 -1
  142. package/src/workers/processors/aiNewtonChat.ts +0 -1
  143. package/tests/helpers/registerInput.ts +20 -0
  144. package/tests/integration/globalSetup.ts +10 -18
  145. package/tests/integration/routers/auth.test.ts +13 -18
  146. package/tests/integration/routers/newtonChat.test.ts +9 -8
  147. package/tests/unit/lib/chatAttachmentPrompt.test.ts +135 -0
  148. package/tests/unit/lib/inferDocumentFormat.test.ts +10 -0
  149. package/tests/unit/pipelines/labChatPrompt.test.ts +6 -6
  150. package/tests/unit/services/aiChatStream.test.ts +92 -0
  151. package/tests/unit/services/openaiDocumentGen.test.ts +65 -0
@@ -45,6 +45,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
45
45
  email: string;
46
46
  password: string;
47
47
  verified: boolean;
48
+ termsAcceptedAt: Date | null;
49
+ termsVersion: string | null;
48
50
  schoolId: string | null;
49
51
  }[];
50
52
  students: {
@@ -53,6 +55,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
53
55
  email: string;
54
56
  password: string;
55
57
  verified: boolean;
58
+ termsAcceptedAt: Date | null;
59
+ termsVersion: string | null;
56
60
  schoolId: string | null;
57
61
  }[];
58
62
  } & {
@@ -99,6 +103,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
99
103
  email: string;
100
104
  password: string;
101
105
  verified: boolean;
106
+ termsAcceptedAt: Date | null;
107
+ termsVersion: string | null;
102
108
  schoolId: string | null;
103
109
  }[];
104
110
  students: {
@@ -107,6 +113,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
107
113
  email: string;
108
114
  password: string;
109
115
  verified: boolean;
116
+ termsAcceptedAt: Date | null;
117
+ termsVersion: string | null;
110
118
  schoolId: string | null;
111
119
  }[];
112
120
  } & {
@@ -169,6 +177,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
169
177
  email: string;
170
178
  password: string;
171
179
  verified: boolean;
180
+ termsAcceptedAt: Date | null;
181
+ termsVersion: string | null;
172
182
  schoolId: string | null;
173
183
  }[];
174
184
  students: {
@@ -177,6 +187,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
177
187
  email: string;
178
188
  password: string;
179
189
  verified: boolean;
190
+ termsAcceptedAt: Date | null;
191
+ termsVersion: string | null;
180
192
  schoolId: string | null;
181
193
  }[];
182
194
  } & {
@@ -222,6 +234,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
222
234
  email: string;
223
235
  password: string;
224
236
  verified: boolean;
237
+ termsAcceptedAt: Date | null;
238
+ termsVersion: string | null;
225
239
  schoolId: string | null;
226
240
  }[];
227
241
  students: {
@@ -230,6 +244,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
230
244
  email: string;
231
245
  password: string;
232
246
  verified: boolean;
247
+ termsAcceptedAt: Date | null;
248
+ termsVersion: string | null;
233
249
  schoolId: string | null;
234
250
  }[];
235
251
  } & {
@@ -277,6 +293,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
277
293
  email: string;
278
294
  password: string;
279
295
  verified: boolean;
296
+ termsAcceptedAt: Date | null;
297
+ termsVersion: string | null;
280
298
  schoolId: string | null;
281
299
  };
282
300
  } & {
@@ -318,6 +336,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
318
336
  email: string;
319
337
  password: string;
320
338
  verified: boolean;
339
+ termsAcceptedAt: Date | null;
340
+ termsVersion: string | null;
321
341
  schoolId: string | null;
322
342
  }[];
323
343
  students: {
@@ -326,6 +346,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
326
346
  email: string;
327
347
  password: string;
328
348
  verified: boolean;
349
+ termsAcceptedAt: Date | null;
350
+ termsVersion: string | null;
329
351
  schoolId: string | null;
330
352
  }[];
331
353
  } & {
@@ -373,6 +395,8 @@ export declare function findFileById(fileId: string): import("@prisma/client/run
373
395
  email: string;
374
396
  password: string;
375
397
  verified: boolean;
398
+ termsAcceptedAt: Date | null;
399
+ termsVersion: string | null;
376
400
  schoolId: string | null;
377
401
  };
378
402
  } & {
@@ -1 +1 @@
1
- {"version":3,"file":"file.d.ts","sourceRoot":"/","sources":["models/file.ts"],"names":[],"mappings":"AAqBA,0GAA0G;AAC1G,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAQ1D;AAED,4BAA4B;AAC5B,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAI5C"}
@@ -61,8 +61,8 @@ export declare function createSchoolDevelopmentProgram(data: {
61
61
  additionalInformation: string | null;
62
62
  reviewedAt: Date | null;
63
63
  }>;
64
- /** @returns School development program by ID. */
65
- export declare function findSchoolDevelopmentProgramById(id: string): import("@prisma/client/runtime/library.js").DynamicModelExtensionFluentApi<import(".prisma/client").Prisma.TypeMap<import("@prisma/client/runtime/library.js").InternalArgs & {
64
+ /** Public status lookup — omits contact PII (email, phone, address). */
65
+ export declare function findSchoolDevelopmentProgramStatusById(id: string): import("@prisma/client/runtime/library.js").DynamicModelExtensionFluentApi<import(".prisma/client").Prisma.TypeMap<import("@prisma/client/runtime/library.js").InternalArgs & {
66
66
  result: {
67
67
  userProfile: {
68
68
  profilePicture: () => {
@@ -87,25 +87,12 @@ export declare function findSchoolDevelopmentProgramById(id: string): import("@p
87
87
  query: {};
88
88
  client: {};
89
89
  }, {}>, "SchoolDevelopementProgram", "findUnique", null> & import("@prisma/client/runtime/library.js").PrismaPromise<{
90
- type: string;
91
90
  status: string;
92
91
  id: string;
93
- website: string | null;
94
92
  name: string;
95
93
  submittedAt: Date | null;
96
- address: string;
97
94
  city: string;
98
95
  country: string;
99
- numberOfStudents: number;
100
- numberOfTeachers: number;
101
- contactName: string | null;
102
- contactRole: string | null;
103
- contactEmail: string | null;
104
- contactPhone: string | null;
105
- eligibilityInformation: string | null;
106
- whyHelp: string | null;
107
- additionalInformation: string | null;
108
- reviewedAt: Date | null;
109
96
  } | null>;
110
97
  /** Create an early access request. */
111
98
  export declare function createEarlyAccessRequest(data: {
@@ -1 +1 @@
1
- {"version":3,"file":"marketing.d.ts","sourceRoot":"/","sources":["models/marketing.ts"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EAAE,MAAM,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAIA;AAED,wEAAwE;AACxE,wBAAgB,sCAAsC,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAYhE;AAED,sCAAsC;AACtC,wBAAgB,wBAAwB,CAAC,IAAI,EAAE;IAC7C,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,MAAM,CAAC;CACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAIA"}
@@ -2,7 +2,7 @@
2
2
  * Marketing model – school development programs, early access requests.
3
3
  */
4
4
 
5
- !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]="fdc418fa-ea66-5ab4-9ecd-ec50207cf861")}catch(e){}}();
5
+ !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]="0ace5974-3200-5f1b-97d3-6b30aa4af12e")}catch(e){}}();
6
6
  import { prisma } from "../lib/prisma.js";
7
7
  /** Create a school development program application. */
8
8
  export function createSchoolDevelopmentProgram(data) {
@@ -10,10 +10,18 @@ export function createSchoolDevelopmentProgram(data) {
10
10
  data,
11
11
  });
12
12
  }
13
- /** @returns School development program by ID. */
14
- export function findSchoolDevelopmentProgramById(id) {
13
+ /** Public status lookup — omits contact PII (email, phone, address). */
14
+ export function findSchoolDevelopmentProgramStatusById(id) {
15
15
  return prisma.schoolDevelopementProgram.findUnique({
16
16
  where: { id },
17
+ select: {
18
+ id: true,
19
+ name: true,
20
+ city: true,
21
+ country: true,
22
+ status: true,
23
+ submittedAt: true,
24
+ },
17
25
  });
18
26
  }
19
27
  /** Create an early access request. */
@@ -23,4 +31,4 @@ export function createEarlyAccessRequest(data) {
23
31
  });
24
32
  }
25
33
  //# sourceMappingURL=marketing.js.map
26
- //# debugId=fdc418fa-ea66-5ab4-9ecd-ec50207cf861
34
+ //# debugId=0ace5974-3200-5f1b-97d3-6b30aa4af12e
@@ -1 +1 @@
1
- {"version":3,"file":"marketing.js","sources":["models/marketing.ts"],"sourceRoot":"/","sourcesContent":["/**\n * Marketing model – school development programs, early access requests.\n */\nimport { prisma } from \"../lib/prisma.js\";\n\n/** Create a school development program application. */\nexport function createSchoolDevelopmentProgram(data: {\n id: string;\n name: string;\n type: string;\n address: string;\n city: string;\n country: string;\n numberOfStudents: number;\n numberOfTeachers: number;\n website?: string;\n contactName?: string;\n contactRole?: string;\n contactEmail?: string;\n contactPhone?: string;\n eligibilityInformation?: string;\n whyHelp?: string;\n additionalInformation?: string;\n}) {\n return prisma.schoolDevelopementProgram.create({\n data,\n });\n}\n\n/** @returns School development program by ID. */\nexport function findSchoolDevelopmentProgramById(id: string) {\n return prisma.schoolDevelopementProgram.findUnique({\n where: { id },\n });\n}\n\n/** Create an early access request. */\nexport function createEarlyAccessRequest(data: {\n email: string;\n institutionSize: string;\n}) {\n return prisma.earlyAccessRequest.create({\n data,\n });\n}\n"],"names":[],"mappings":"AAAA;;GAEG;;;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,uDAAuD;AACvD,MAAM,UAAU,8BAA8B,CAAC,IAiB9C;IACC,OAAO,MAAM,CAAC,yBAAyB,CAAC,MAAM,CAAC;QAC7C,IAAI;KACL,CAAC,CAAC;AACL,CAAC;AAED,iDAAiD;AACjD,MAAM,UAAU,gCAAgC,CAAC,EAAU;IACzD,OAAO,MAAM,CAAC,yBAAyB,CAAC,UAAU,CAAC;QACjD,KAAK,EAAE,EAAE,EAAE,EAAE;KACd,CAAC,CAAC;AACL,CAAC;AAED,sCAAsC;AACtC,MAAM,UAAU,wBAAwB,CAAC,IAGxC;IACC,OAAO,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC;QACtC,IAAI;KACL,CAAC,CAAC;AACL,CAAC","debug_id":"fdc418fa-ea66-5ab4-9ecd-ec50207cf861"}
1
+ {"version":3,"file":"marketing.js","sources":["models/marketing.ts"],"sourceRoot":"/","sourcesContent":["/**\n * Marketing model – school development programs, early access requests.\n */\nimport { prisma } from \"../lib/prisma.js\";\n\n/** Create a school development program application. */\nexport function createSchoolDevelopmentProgram(data: {\n id: string;\n name: string;\n type: string;\n address: string;\n city: string;\n country: string;\n numberOfStudents: number;\n numberOfTeachers: number;\n website?: string;\n contactName?: string;\n contactRole?: string;\n contactEmail?: string;\n contactPhone?: string;\n eligibilityInformation?: string;\n whyHelp?: string;\n additionalInformation?: string;\n}) {\n return prisma.schoolDevelopementProgram.create({\n data,\n });\n}\n\n/** Public status lookup — omits contact PII (email, phone, address). */\nexport function findSchoolDevelopmentProgramStatusById(id: string) {\n return prisma.schoolDevelopementProgram.findUnique({\n where: { id },\n select: {\n id: true,\n name: true,\n city: true,\n country: true,\n status: true,\n submittedAt: true,\n },\n });\n}\n\n/** Create an early access request. */\nexport function createEarlyAccessRequest(data: {\n email: string;\n institutionSize: string;\n}) {\n return prisma.earlyAccessRequest.create({\n data,\n });\n}\n"],"names":[],"mappings":"AAAA;;GAEG;;;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,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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;AAoGF;;;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,CAoUd,CAAA"}
@@ -3,20 +3,20 @@
3
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]="d3703630-d937-5008-878a-ce235919a235")}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]="34f3e5c6-5811-5644-b688-13b9a35600d2")}catch(e){}}();
7
7
  import { isAIUser } from "../utils/aiUser.js";
8
8
  import { prisma } from "../lib/prisma.js";
9
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
12
  import { v4 } from "uuid";
13
- import { bucket, getSignedUrl } from "../lib/googleCloudStorage.js";
14
- import { generateDocumentWithOpenAI } from "../services/openaiDocumentGen.js";
13
+ import { bucket } from "../lib/googleCloudStorage.js";
14
+ import { generateDocumentWithOpenAI, normalizeDocumentFormat, } from "../services/openaiDocumentGen.js";
15
15
  import { inferDocumentFormat } from "../lib/inferDocumentFormat.js";
16
- import { normalizeDocumentFormat } from "../services/openaiDocumentGen.js";
17
16
  import { broadcastTextChunks, broadcastStreamComplete } from "../utils/streamBroadcast.js";
17
+ import { AI_CHAT_MODEL } from "../lib/chatAttachmentPrompt.js";
18
18
  import { buildLabChatAgentMessages } from "./labChatPrompt.js";
19
- import { applyResolvedFormatsToStreamParts, enrichStreamPartsWithGeneratedFiles, streamChatResponse, } from "../services/aiChatStream.js";
19
+ import { applyResolvedFormatsToStreamParts, enrichStreamPartsWithGeneratedFiles, finalizeDeferredToolParts, streamChatResponse, } from "../services/aiChatStream.js";
20
20
  import { aiTools } from "../services/aiTools.js";
21
21
  import { labProposalTools, createLabProposals } from "../services/aiProposalTools.js";
22
22
  /** Cap model wait time; leave headroom after inference for PDF/GCS/DB within Vercel maxDuration (500s). */
@@ -136,34 +136,6 @@ const loadRecentLabChatMessages = async (conversationId, anchorMessageId) => {
136
136
  })
137
137
  .slice(0, limit);
138
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
- }
167
139
  /**
168
140
  * Builds schema-aware context for the AI from class data.
169
141
  * Formats entities with IDs so the model can reference them when creating assignments.
@@ -386,12 +358,10 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
386
358
  teachers: classData.teachers,
387
359
  assignments: classData.assignments,
388
360
  });
389
- // Resolve signed URLs for image attachments so the LLM can see them
390
- const messagesWithAttachments = await resolveAttachmentUrls(recentMessages.reverse());
391
- const { system, messages } = buildLabChatAgentMessages({
361
+ const { system, messages } = await buildLabChatAgentMessages({
392
362
  context: fullLabChat.context,
393
363
  classContext,
394
- recentMessages: messagesWithAttachments,
364
+ recentMessages: recentMessages.reverse(),
395
365
  isAIUser,
396
366
  });
397
367
  // Genuine agentic generation: the model streams prose token-by-token and
@@ -406,6 +376,7 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
406
376
  const { text: streamedText, parts: rawStreamParts } = await withTimeout(streamChatResponse({
407
377
  conversationId,
408
378
  aiMessageId: emitOptions.aiMessageId,
379
+ model: AI_CHAT_MODEL,
409
380
  system,
410
381
  messages,
411
382
  tools,
@@ -423,9 +394,10 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
423
394
  const attachmentIds = [];
424
395
  const generatedDocFiles = [];
425
396
  const resolvedDocs = [];
426
- for (const doc of proposals.docs) {
397
+ for (let i = 0; i < proposals.docs.length; i++) {
398
+ const doc = proposals.docs[i];
427
399
  if (!doc.title || !doc.content?.trim()) {
428
- logger.error('Document missing title or content', { labChatId, doc });
400
+ logger.error(`Document ${i + 1} is missing title or content`, { labChatId, doc });
429
401
  continue;
430
402
  }
431
403
  const format = inferDocumentFormat(doc.title, doc.content, doc.format, teacherMessage);
@@ -445,10 +417,10 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
445
417
  format,
446
418
  });
447
419
  if (!generated) {
448
- logger.error('OpenAI document generation returned null', {
420
+ logger.error(`Document ${i + 1} generation returned null`, {
449
421
  labChatId,
450
422
  title: doc.title,
451
- format: doc.format,
423
+ format,
452
424
  });
453
425
  continue;
454
426
  }
@@ -458,9 +430,15 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
458
430
  .substring(0, 50);
459
431
  const filename = `${sanitizedTitle}_${v4().substring(0, 8)}.${generated.format}`;
460
432
  const filePath = `class/generated/${fullLabChat.classId}/${filename}`;
433
+ logger.info(`Document ${i + 1} generated successfully`, {
434
+ labChatId,
435
+ title: doc.title,
436
+ format: generated.format,
437
+ });
461
438
  await bucket.file(filePath).save(generated.bytes, {
462
439
  metadata: { contentType: generated.mimeType },
463
440
  });
441
+ logger.info(`Document ${i + 1} uploaded successfully`, { labChatId, filename });
464
442
  const file = await prisma.file.create({
465
443
  data: {
466
444
  name: filename,
@@ -483,7 +461,7 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
483
461
  });
484
462
  }
485
463
  catch (docError) {
486
- logger.error('Document generation failed', {
464
+ logger.error(`Document generation failed for item ${i + 1}:`, {
487
465
  error: docError instanceof Error ? {
488
466
  message: docError.message,
489
467
  stack: docError.stack,
@@ -495,24 +473,26 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
495
473
  });
496
474
  }
497
475
  }
498
- const streamParts = enrichStreamPartsWithGeneratedFiles(applyResolvedFormatsToStreamParts(rawStreamParts, resolvedDocs), generatedDocFiles);
476
+ const streamParts = finalizeDeferredToolParts(enrichStreamPartsWithGeneratedFiles(applyResolvedFormatsToStreamParts(rawStreamParts, resolvedDocs), generatedDocFiles));
477
+ // While the message is still PENDING, resolve deferred tool indicators
478
+ // (spinner → attachment or error) before the final persist event.
499
479
  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(() => { });
480
+ if (part.type !== 'tool' || part.toolName !== 'generate_document') {
481
+ continue;
515
482
  }
483
+ if (part.status === 'executing')
484
+ continue;
485
+ await pusher
486
+ .trigger(chatChannel(conversationId), 'message-tool-call', {
487
+ messageId: emitOptions.aiMessageId,
488
+ toolCallId: part.toolCallId,
489
+ toolName: part.toolName,
490
+ ...(part.title ? { title: part.title } : {}),
491
+ ...(part.format ? { format: part.format } : {}),
492
+ ...(part.fileId ? { fileId: part.fileId, fileName: part.fileName } : {}),
493
+ status: part.status,
494
+ })
495
+ .catch(() => { });
516
496
  }
517
497
  await completePendingAIMessage(emitOptions.aiMessageId, streamedText, {
518
498
  ...(attachmentIds.length > 0 && {
@@ -577,4 +557,4 @@ export const generateAndSendLabResponse = async (labChatId, teacherMessage, emit
577
557
  }
578
558
  };
579
559
  //# sourceMappingURL=aiLabChat.js.map
580
- //# debugId=d3703630-d937-5008-878a-ce235919a235
560
+ //# debugId=34f3e5c6-5811-5644-b688-13b9a35600d2
@@ -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 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 });\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,MAAM,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAC3F,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAE/D,OAAO,EACL,iCAAiC,EACjC,mCAAmC,EACnC,kBAAkB,GAGnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD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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":"d3703630-d937-5008-878a-ce235919a235"}
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 } from \"../lib/googleCloudStorage.js\";\nimport {\n generateDocumentWithOpenAI,\n normalizeDocumentFormat,\n} from \"../services/openaiDocumentGen.js\";\nimport { inferDocumentFormat } from \"../lib/inferDocumentFormat.js\";\nimport { broadcastTextChunks, broadcastStreamComplete } from \"../utils/streamBroadcast.js\";\nimport { AI_CHAT_MODEL } from \"../lib/chatAttachmentPrompt.js\";\nimport { buildLabChatAgentMessages } from \"./labChatPrompt.js\";\nimport {\n applyResolvedFormatsToStreamParts,\n enrichStreamPartsWithGeneratedFiles,\n finalizeDeferredToolParts,\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 * 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 const { system, messages } = await 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: rawStreamParts } = await withTimeout(\n streamChatResponse({\n conversationId,\n aiMessageId: emitOptions.aiMessageId,\n model: AI_CHAT_MODEL,\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 (let i = 0; i < proposals.docs.length; i++) {\n const doc = proposals.docs[i];\n if (!doc.title || !doc.content?.trim()) {\n logger.error(`Document ${i + 1} is 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(`Document ${i + 1} generation returned null`, {\n labChatId,\n title: doc.title,\n 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 logger.info(`Document ${i + 1} generated successfully`, {\n labChatId,\n title: doc.title,\n format: generated.format,\n });\n\n await bucket.file(filePath).save(generated.bytes, {\n metadata: { contentType: generated.mimeType },\n });\n\n logger.info(`Document ${i + 1} uploaded successfully`, { labChatId, filename });\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 for item ${i + 1}:`, {\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[] = finalizeDeferredToolParts(\n enrichStreamPartsWithGeneratedFiles(\n applyResolvedFormatsToStreamParts(rawStreamParts, resolvedDocs),\n generatedDocFiles,\n ),\n );\n\n // While the message is still PENDING, resolve deferred tool indicators\n // (spinner → attachment or error) before the final persist event.\n for (const part of streamParts) {\n if (part.type !== 'tool' || part.toolName !== 'generate_document') {\n continue;\n }\n if (part.status === 'executing') continue;\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 ...(part.fileId ? { fileId: part.fileId, fileName: part.fileName } : {}),\n status: part.status,\n })\n .catch(() => {});\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 });\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,MAAM,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC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