@goscribe/server 1.2.0 → 1.3.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 (126) hide show
  1. package/check-difficulty.cjs +14 -0
  2. package/check-questions.cjs +14 -0
  3. package/db-summary.cjs +22 -0
  4. package/dist/context.d.ts +5 -1
  5. package/dist/lib/activity_human_description.d.ts +13 -0
  6. package/dist/lib/activity_human_description.js +221 -0
  7. package/dist/lib/activity_human_description.test.d.ts +1 -0
  8. package/dist/lib/activity_human_description.test.js +16 -0
  9. package/dist/lib/activity_log_service.d.ts +87 -0
  10. package/dist/lib/activity_log_service.js +276 -0
  11. package/dist/lib/activity_log_service.test.d.ts +1 -0
  12. package/dist/lib/activity_log_service.test.js +27 -0
  13. package/dist/lib/ai-session.d.ts +15 -2
  14. package/dist/lib/ai-session.js +147 -85
  15. package/dist/lib/constants.d.ts +13 -0
  16. package/dist/lib/constants.js +12 -0
  17. package/dist/lib/email.d.ts +11 -0
  18. package/dist/lib/email.js +193 -0
  19. package/dist/lib/env.d.ts +13 -0
  20. package/dist/lib/env.js +16 -0
  21. package/dist/lib/inference.d.ts +4 -1
  22. package/dist/lib/inference.js +3 -3
  23. package/dist/lib/logger.d.ts +4 -4
  24. package/dist/lib/logger.js +30 -8
  25. package/dist/lib/notification-service.d.ts +152 -0
  26. package/dist/lib/notification-service.js +473 -0
  27. package/dist/lib/notification-service.test.d.ts +1 -0
  28. package/dist/lib/notification-service.test.js +87 -0
  29. package/dist/lib/prisma.d.ts +2 -1
  30. package/dist/lib/prisma.js +5 -1
  31. package/dist/lib/pusher.d.ts +23 -0
  32. package/dist/lib/pusher.js +69 -5
  33. package/dist/lib/retry.d.ts +15 -0
  34. package/dist/lib/retry.js +37 -0
  35. package/dist/lib/storage.js +2 -2
  36. package/dist/lib/stripe.d.ts +9 -0
  37. package/dist/lib/stripe.js +36 -0
  38. package/dist/lib/subscription_service.d.ts +37 -0
  39. package/dist/lib/subscription_service.js +654 -0
  40. package/dist/lib/usage_service.d.ts +26 -0
  41. package/dist/lib/usage_service.js +59 -0
  42. package/dist/lib/worksheet-generation.d.ts +91 -0
  43. package/dist/lib/worksheet-generation.js +95 -0
  44. package/dist/lib/worksheet-generation.test.d.ts +1 -0
  45. package/dist/lib/worksheet-generation.test.js +20 -0
  46. package/dist/lib/workspace-access.d.ts +18 -0
  47. package/dist/lib/workspace-access.js +13 -0
  48. package/dist/routers/_app.d.ts +1349 -253
  49. package/dist/routers/_app.js +10 -0
  50. package/dist/routers/admin.d.ts +361 -0
  51. package/dist/routers/admin.js +633 -0
  52. package/dist/routers/annotations.d.ts +219 -0
  53. package/dist/routers/annotations.js +187 -0
  54. package/dist/routers/auth.d.ts +88 -7
  55. package/dist/routers/auth.js +339 -19
  56. package/dist/routers/chat.d.ts +6 -12
  57. package/dist/routers/copilot.d.ts +199 -0
  58. package/dist/routers/copilot.js +571 -0
  59. package/dist/routers/flashcards.d.ts +47 -81
  60. package/dist/routers/flashcards.js +143 -27
  61. package/dist/routers/members.d.ts +36 -7
  62. package/dist/routers/members.js +200 -19
  63. package/dist/routers/notifications.d.ts +99 -0
  64. package/dist/routers/notifications.js +127 -0
  65. package/dist/routers/payment.d.ts +89 -0
  66. package/dist/routers/payment.js +403 -0
  67. package/dist/routers/podcast.d.ts +8 -13
  68. package/dist/routers/podcast.js +54 -31
  69. package/dist/routers/studyguide.d.ts +1 -29
  70. package/dist/routers/studyguide.js +80 -71
  71. package/dist/routers/worksheets.d.ts +105 -38
  72. package/dist/routers/worksheets.js +258 -68
  73. package/dist/routers/workspace.d.ts +139 -60
  74. package/dist/routers/workspace.js +455 -315
  75. package/dist/scripts/purge-deleted-users.d.ts +1 -0
  76. package/dist/scripts/purge-deleted-users.js +149 -0
  77. package/dist/server.js +130 -10
  78. package/dist/services/flashcard-progress.service.d.ts +18 -66
  79. package/dist/services/flashcard-progress.service.js +51 -42
  80. package/dist/trpc.d.ts +20 -21
  81. package/dist/trpc.js +150 -1
  82. package/mcq-test.cjs +36 -0
  83. package/package.json +9 -2
  84. package/prisma/migrations/20260413143206_init/migration.sql +873 -0
  85. package/prisma/schema.prisma +471 -324
  86. package/src/context.ts +4 -1
  87. package/src/lib/activity_human_description.test.ts +28 -0
  88. package/src/lib/activity_human_description.ts +239 -0
  89. package/src/lib/activity_log_service.test.ts +37 -0
  90. package/src/lib/activity_log_service.ts +353 -0
  91. package/src/lib/ai-session.ts +79 -51
  92. package/src/lib/email.ts +213 -29
  93. package/src/lib/env.ts +23 -6
  94. package/src/lib/inference.ts +2 -2
  95. package/src/lib/notification-service.test.ts +106 -0
  96. package/src/lib/notification-service.ts +677 -0
  97. package/src/lib/prisma.ts +6 -1
  98. package/src/lib/pusher.ts +86 -2
  99. package/src/lib/stripe.ts +39 -0
  100. package/src/lib/subscription_service.ts +722 -0
  101. package/src/lib/usage_service.ts +74 -0
  102. package/src/lib/worksheet-generation.test.ts +31 -0
  103. package/src/lib/worksheet-generation.ts +139 -0
  104. package/src/routers/_app.ts +9 -0
  105. package/src/routers/admin.ts +710 -0
  106. package/src/routers/annotations.ts +41 -0
  107. package/src/routers/auth.ts +338 -28
  108. package/src/routers/copilot.ts +719 -0
  109. package/src/routers/flashcards.ts +201 -68
  110. package/src/routers/members.ts +280 -80
  111. package/src/routers/notifications.ts +142 -0
  112. package/src/routers/payment.ts +448 -0
  113. package/src/routers/podcast.ts +112 -83
  114. package/src/routers/studyguide.ts +12 -0
  115. package/src/routers/worksheets.ts +289 -66
  116. package/src/routers/workspace.ts +329 -122
  117. package/src/scripts/purge-deleted-users.ts +167 -0
  118. package/src/server.ts +137 -11
  119. package/src/services/flashcard-progress.service.ts +49 -37
  120. package/src/trpc.ts +184 -5
  121. package/test-generate.js +30 -0
  122. package/test-ratio.cjs +9 -0
  123. package/zod-test.cjs +22 -0
  124. package/prisma/migrations/20250826124819_add_worksheet_difficulty_and_estimated_time/migration.sql +0 -213
  125. package/prisma/migrations/20250826133236_add_worksheet_question_progress/migration.sql +0 -31
  126. package/prisma/seed.mjs +0 -135
@@ -0,0 +1,571 @@
1
+ import { TRPCError } from "@trpc/server";
2
+ import { z } from "zod";
3
+ import { router, verifiedProcedure } from "../trpc.js";
4
+ import inference from "../lib/inference.js";
5
+ import { sanitizeString } from "../lib/validation.js";
6
+ import { workspaceAccessFilter } from "../lib/workspace-access.js";
7
+ import PusherService from "../lib/pusher.js";
8
+ import { ArtifactType } from "../lib/constants.js";
9
+ const copilotArtifactType = z.enum([
10
+ "study-guide",
11
+ "worksheet",
12
+ "flashcards",
13
+ "notes",
14
+ ]);
15
+ const copilotContextSchema = z.object({
16
+ workspaceId: z.string().min(1),
17
+ artifactId: z.string().min(1),
18
+ artifactType: copilotArtifactType,
19
+ documentContent: z.string().min(1),
20
+ selectedText: z.string().optional(),
21
+ viewportText: z.string().optional(),
22
+ cursorPosition: z
23
+ .object({
24
+ start: z.number().int().min(0),
25
+ end: z.number().int().min(0),
26
+ })
27
+ .optional(),
28
+ metadata: z
29
+ .object({
30
+ flashcardId: z.string().optional(),
31
+ questionId: z.string().optional(),
32
+ documentId: z.string().optional(),
33
+ })
34
+ .optional(),
35
+ });
36
+ const highlightInstructionSchema = z.object({
37
+ start: z.number().int().min(0),
38
+ end: z.number().int().min(0),
39
+ label: z.string().optional(),
40
+ });
41
+ const flashcardSchema = z.object({
42
+ front: z.string().min(1),
43
+ back: z.string().min(1),
44
+ });
45
+ const RATE_LIMIT_WINDOW_MS = 60000;
46
+ const RATE_LIMIT_MAX_REQUESTS = 20;
47
+ const requestBuckets = new Map();
48
+ function enforceRateLimit(userId, workspaceId) {
49
+ const now = Date.now();
50
+ const key = `${userId}:${workspaceId}`;
51
+ const existing = requestBuckets.get(key) ?? [];
52
+ const recent = existing.filter((timestamp) => now - timestamp < RATE_LIMIT_WINDOW_MS);
53
+ if (recent.length >= RATE_LIMIT_MAX_REQUESTS) {
54
+ throw new TRPCError({
55
+ code: "TOO_MANY_REQUESTS",
56
+ message: "Too many copilot requests. Please wait a moment.",
57
+ });
58
+ }
59
+ recent.push(now);
60
+ requestBuckets.set(key, recent);
61
+ }
62
+ function contextWindow(context) {
63
+ // Pass the full document so the copilot has full context and does not make mistakes
64
+ return sanitizeString(context.documentContent, 5000000);
65
+ }
66
+ function extractJson(content) {
67
+ const fencedMatch = content.match(/```json\s*([\s\S]*?)```/i);
68
+ if (fencedMatch?.[1]) {
69
+ try {
70
+ return JSON.parse(fencedMatch[1]);
71
+ }
72
+ catch {
73
+ // fall through
74
+ }
75
+ }
76
+ const objectMatch = content.match(/\{[\s\S]*\}/);
77
+ if (objectMatch?.[0]) {
78
+ try {
79
+ return JSON.parse(objectMatch[0]);
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+ function getAnswerFromParsedJSON(parsed) {
88
+ if (!parsed)
89
+ return null;
90
+ const potentialKeys = [
91
+ "answer",
92
+ "summary",
93
+ "explanation",
94
+ "content",
95
+ "explanationText",
96
+ "response",
97
+ "result",
98
+ ];
99
+ for (const key of potentialKeys) {
100
+ if (typeof parsed[key] === "string" && parsed[key].length > 0) {
101
+ return parsed[key];
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+ async function assertWorkspaceAccess(ctx, workspaceId) {
107
+ const workspace = await ctx.db.workspace.findFirst({
108
+ where: {
109
+ id: workspaceId,
110
+ ...workspaceAccessFilter(ctx.session.user.id),
111
+ },
112
+ select: { id: true },
113
+ });
114
+ if (!workspace) {
115
+ throw new TRPCError({
116
+ code: "FORBIDDEN",
117
+ message: "You do not have access to this workspace",
118
+ });
119
+ }
120
+ }
121
+ async function assertConversationAccess(params) {
122
+ const conversation = await params.ctx.db.copilotConversation.findFirst({
123
+ where: {
124
+ id: params.conversationId,
125
+ workspaceId: params.workspaceId,
126
+ userId: params.ctx.session.user.id,
127
+ },
128
+ select: {
129
+ id: true,
130
+ },
131
+ });
132
+ if (!conversation) {
133
+ throw new TRPCError({
134
+ code: "NOT_FOUND",
135
+ message: "Conversation not found",
136
+ });
137
+ }
138
+ }
139
+ async function persistConversationExchange(params) {
140
+ if (!params.conversationId)
141
+ return;
142
+ await assertConversationAccess({
143
+ ctx: params.ctx,
144
+ workspaceId: params.workspaceId,
145
+ conversationId: params.conversationId,
146
+ });
147
+ const generatedTitle = sanitizeString(params.userMessage.replace(/\s+/g, " ").trim(), 80);
148
+ const conversation = await params.ctx.db.copilotConversation.findUnique({
149
+ where: { id: params.conversationId },
150
+ select: { title: true },
151
+ });
152
+ const shouldUpdateTitle = !!conversation &&
153
+ conversation.title.trim().toLowerCase() === "new chat" &&
154
+ generatedTitle.length > 0;
155
+ await params.ctx.db.copilotMessage.createMany({
156
+ data: [
157
+ {
158
+ conversationId: params.conversationId,
159
+ role: "USER",
160
+ content: sanitizeString(params.userMessage, 8000),
161
+ },
162
+ {
163
+ conversationId: params.conversationId,
164
+ role: "ASSISTANT",
165
+ content: sanitizeString(params.assistantMessage, 20000),
166
+ },
167
+ ],
168
+ });
169
+ await params.ctx.db.copilotConversation.update({
170
+ where: { id: params.conversationId },
171
+ data: {
172
+ updatedAt: new Date(),
173
+ ...(shouldUpdateTitle ? { title: generatedTitle } : {}),
174
+ },
175
+ });
176
+ }
177
+ async function callCopilotModel(params) {
178
+ const documentSnippet = contextWindow(params.context);
179
+ const selectedText = params.context.selectedText
180
+ ? sanitizeString(params.context.selectedText, 2000)
181
+ : "";
182
+ const viewportText = params.context.viewportText
183
+ ? sanitizeString(params.context.viewportText, 4000)
184
+ : "";
185
+ const message = sanitizeString(params.message, 4000);
186
+ const systemPrompt = [
187
+ "You are an AI study assistant for the Scribe learning platform.",
188
+ "Be concise, correct, and safe. Do not claim edits were applied unless asked and confirmed by the user.",
189
+ "Return valid JSON only.",
190
+ "",
191
+ "OUTPUT FORMAT:",
192
+ "{",
193
+ ' "answer": "markdown response for the user",',
194
+ ' "highlights": [{ "start": 0, "end": 10, "label": "optional" }],',
195
+ ' "flashcards": [{ "front": "question", "back": "answer" }]',
196
+ "}",
197
+ "Include only relevant keys for the task.",
198
+ "",
199
+ `MODE: ${params.mode}`,
200
+ `ARTIFACT_TYPE: ${params.context.artifactType}`,
201
+ ].join("\n");
202
+ const contextPrompt = [
203
+ "DOCUMENT:",
204
+ documentSnippet,
205
+ "",
206
+ "SELECTION:",
207
+ selectedText || "None",
208
+ "",
209
+ "VIEWPORT_TEXT:",
210
+ viewportText || "None",
211
+ ].join("\n");
212
+ const messages = [
213
+ { role: "system", content: systemPrompt },
214
+ { role: "user", content: contextPrompt },
215
+ ];
216
+ if (params.history && params.history.length > 0) {
217
+ params.history.forEach((msg) => {
218
+ messages.push({
219
+ role: msg.role === "user" ? "user" : "assistant",
220
+ content: msg.content,
221
+ });
222
+ });
223
+ }
224
+ messages.push({ role: "user", content: message });
225
+ const response = await inference(messages);
226
+ const content = response.choices?.[0]?.message?.content ?? "";
227
+ const parsed = extractJson(content);
228
+ return {
229
+ rawContent: content,
230
+ parsed,
231
+ };
232
+ }
233
+ export const copilot = router({
234
+ listConversations: verifiedProcedure
235
+ .input(z.object({
236
+ workspaceId: z.string().min(1),
237
+ }))
238
+ .query(async ({ ctx, input }) => {
239
+ await assertWorkspaceAccess(ctx, input.workspaceId);
240
+ const conversations = await ctx.db.copilotConversation.findMany({
241
+ where: {
242
+ workspaceId: input.workspaceId,
243
+ userId: ctx.session.user.id,
244
+ },
245
+ include: {
246
+ messages: {
247
+ orderBy: { createdAt: "desc" },
248
+ take: 1,
249
+ },
250
+ },
251
+ orderBy: { updatedAt: "desc" },
252
+ });
253
+ return conversations.map((conversation) => ({
254
+ id: conversation.id,
255
+ title: conversation.title,
256
+ updatedAt: conversation.updatedAt,
257
+ preview: conversation.messages[0]?.content ?? "",
258
+ }));
259
+ }),
260
+ getConversation: verifiedProcedure
261
+ .input(z.object({
262
+ workspaceId: z.string().min(1),
263
+ conversationId: z.string().min(1),
264
+ }))
265
+ .query(async ({ ctx, input }) => {
266
+ await assertWorkspaceAccess(ctx, input.workspaceId);
267
+ await assertConversationAccess({
268
+ ctx,
269
+ workspaceId: input.workspaceId,
270
+ conversationId: input.conversationId,
271
+ });
272
+ const conversation = await ctx.db.copilotConversation.findUnique({
273
+ where: { id: input.conversationId },
274
+ include: {
275
+ messages: {
276
+ orderBy: { createdAt: "asc" },
277
+ },
278
+ },
279
+ });
280
+ if (!conversation) {
281
+ throw new TRPCError({
282
+ code: "NOT_FOUND",
283
+ message: "Conversation not found",
284
+ });
285
+ }
286
+ return {
287
+ id: conversation.id,
288
+ title: conversation.title,
289
+ messages: conversation.messages.map((message) => ({
290
+ id: message.id,
291
+ role: message.role === "USER" ? "user" : "assistant",
292
+ content: message.content,
293
+ createdAt: message.createdAt,
294
+ })),
295
+ };
296
+ }),
297
+ createConversation: verifiedProcedure
298
+ .input(z.object({
299
+ workspaceId: z.string().min(1),
300
+ title: z.string().optional(),
301
+ }))
302
+ .mutation(async ({ ctx, input }) => {
303
+ await assertWorkspaceAccess(ctx, input.workspaceId);
304
+ const conversation = await ctx.db.copilotConversation.create({
305
+ data: {
306
+ workspaceId: input.workspaceId,
307
+ userId: ctx.session.user.id,
308
+ title: sanitizeString(input.title || "New Chat", 120),
309
+ },
310
+ });
311
+ return {
312
+ id: conversation.id,
313
+ title: conversation.title,
314
+ updatedAt: conversation.updatedAt,
315
+ };
316
+ }),
317
+ deleteConversation: verifiedProcedure
318
+ .input(z.object({
319
+ workspaceId: z.string().min(1),
320
+ conversationId: z.string().min(1),
321
+ }))
322
+ .mutation(async ({ ctx, input }) => {
323
+ await assertWorkspaceAccess(ctx, input.workspaceId);
324
+ await assertConversationAccess({
325
+ ctx,
326
+ workspaceId: input.workspaceId,
327
+ conversationId: input.conversationId,
328
+ });
329
+ await ctx.db.copilotConversation.delete({
330
+ where: { id: input.conversationId },
331
+ });
332
+ return { success: true };
333
+ }),
334
+ ask: verifiedProcedure
335
+ .input(z.object({
336
+ context: copilotContextSchema,
337
+ message: z.string().min(1),
338
+ conversationId: z.string().optional(),
339
+ }))
340
+ .mutation(async ({ ctx, input }) => {
341
+ enforceRateLimit(ctx.session.user.id, input.context.workspaceId);
342
+ await assertWorkspaceAccess(ctx, input.context.workspaceId);
343
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:thinking", {
344
+ status: "started",
345
+ });
346
+ let history = [];
347
+ if (input.conversationId) {
348
+ const messages = await ctx.db.copilotMessage.findMany({
349
+ where: { conversationId: input.conversationId },
350
+ orderBy: { createdAt: "asc" },
351
+ take: 50,
352
+ });
353
+ history = messages.map((m) => ({
354
+ role: m.role.toLowerCase(),
355
+ content: m.content,
356
+ }));
357
+ }
358
+ const model = await callCopilotModel({
359
+ mode: "ask",
360
+ context: input.context,
361
+ message: input.message,
362
+ history,
363
+ });
364
+ const answer = getAnswerFromParsedJSON(model.parsed) ||
365
+ model.rawContent ||
366
+ "I could not generate a response.";
367
+ const highlights = z.array(highlightInstructionSchema).safeParse(model.parsed?.highlights);
368
+ const safeHighlights = highlights.success
369
+ ? highlights.data.filter((item) => item.start < item.end &&
370
+ item.end <= Math.max(input.context.documentContent.length, 0))
371
+ : [];
372
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:response", {
373
+ status: "completed",
374
+ });
375
+ await persistConversationExchange({
376
+ ctx,
377
+ workspaceId: input.context.workspaceId,
378
+ conversationId: input.conversationId,
379
+ userMessage: input.message,
380
+ assistantMessage: answer,
381
+ });
382
+ return {
383
+ answer,
384
+ highlights: safeHighlights,
385
+ };
386
+ }),
387
+ explainSelection: verifiedProcedure
388
+ .input(z.object({
389
+ context: copilotContextSchema,
390
+ message: z.string().optional(),
391
+ conversationId: z.string().optional(),
392
+ }))
393
+ .mutation(async ({ ctx, input }) => {
394
+ enforceRateLimit(ctx.session.user.id, input.context.workspaceId);
395
+ await assertWorkspaceAccess(ctx, input.context.workspaceId);
396
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:thinking", {
397
+ status: "started",
398
+ });
399
+ const question = input.message && input.message.trim().length > 0
400
+ ? input.message
401
+ : "Explain the selected text in simple study-friendly terms and include one practical example.";
402
+ let history = [];
403
+ if (input.conversationId) {
404
+ const messages = await ctx.db.copilotMessage.findMany({
405
+ where: { conversationId: input.conversationId },
406
+ orderBy: { createdAt: "asc" },
407
+ take: 50,
408
+ });
409
+ history = messages.map((m) => ({
410
+ role: m.role.toLowerCase(),
411
+ content: m.content,
412
+ }));
413
+ }
414
+ const model = await callCopilotModel({
415
+ mode: "explainSelection",
416
+ context: input.context,
417
+ message: question,
418
+ history,
419
+ });
420
+ const answer = getAnswerFromParsedJSON(model.parsed) ||
421
+ model.rawContent ||
422
+ "I could not explain this selection.";
423
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:response", {
424
+ status: "completed",
425
+ });
426
+ await persistConversationExchange({
427
+ ctx,
428
+ workspaceId: input.context.workspaceId,
429
+ conversationId: input.conversationId,
430
+ userMessage: question,
431
+ assistantMessage: answer,
432
+ });
433
+ return { answer };
434
+ }),
435
+ suggestHighlights: verifiedProcedure
436
+ .input(z.object({
437
+ context: copilotContextSchema,
438
+ message: z.string().optional(),
439
+ conversationId: z.string().optional(),
440
+ }))
441
+ .mutation(async ({ ctx, input }) => {
442
+ enforceRateLimit(ctx.session.user.id, input.context.workspaceId);
443
+ await assertWorkspaceAccess(ctx, input.context.workspaceId);
444
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:thinking", {
445
+ status: "started",
446
+ });
447
+ const instruction = input.message && input.message.trim().length > 0
448
+ ? input.message
449
+ : "Suggest key highlights for the provided section.";
450
+ let history = [];
451
+ if (input.conversationId) {
452
+ const messages = await ctx.db.copilotMessage.findMany({
453
+ where: { conversationId: input.conversationId },
454
+ orderBy: { createdAt: "asc" },
455
+ take: 50,
456
+ });
457
+ history = messages.map((m) => ({
458
+ role: m.role.toLowerCase(),
459
+ content: m.content,
460
+ }));
461
+ }
462
+ const model = await callCopilotModel({
463
+ mode: "suggestHighlights",
464
+ context: input.context,
465
+ message: instruction,
466
+ history,
467
+ });
468
+ const parsedHighlights = z.array(highlightInstructionSchema).safeParse(model.parsed?.highlights);
469
+ const safeHighlights = parsedHighlights.success
470
+ ? parsedHighlights.data.filter((item) => item.start < item.end &&
471
+ item.end <= Math.max(input.context.documentContent.length, 0))
472
+ : [];
473
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:highlight_suggestions", {
474
+ highlights: safeHighlights,
475
+ });
476
+ const answer = getAnswerFromParsedJSON(model.parsed) ||
477
+ "Here are suggested highlights.";
478
+ await persistConversationExchange({
479
+ ctx,
480
+ workspaceId: input.context.workspaceId,
481
+ conversationId: input.conversationId,
482
+ userMessage: instruction,
483
+ assistantMessage: answer,
484
+ });
485
+ return {
486
+ answer,
487
+ highlights: safeHighlights,
488
+ };
489
+ }),
490
+ generateFlashcards: verifiedProcedure
491
+ .input(z.object({
492
+ context: copilotContextSchema,
493
+ message: z.string().optional(),
494
+ numCards: z.number().int().min(1).max(30).default(10),
495
+ conversationId: z.string().optional(),
496
+ }))
497
+ .mutation(async ({ ctx, input }) => {
498
+ enforceRateLimit(ctx.session.user.id, input.context.workspaceId);
499
+ await assertWorkspaceAccess(ctx, input.context.workspaceId);
500
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:thinking", {
501
+ status: "started",
502
+ });
503
+ const instruction = input.message && input.message.trim().length > 0
504
+ ? input.message
505
+ : `Generate ${input.numCards} concise study flashcards from this context.`;
506
+ let history = [];
507
+ if (input.conversationId) {
508
+ const messages = await ctx.db.copilotMessage.findMany({
509
+ where: { conversationId: input.conversationId },
510
+ orderBy: { createdAt: "asc" },
511
+ take: 50,
512
+ });
513
+ history = messages.map((m) => ({
514
+ role: m.role.toLowerCase(),
515
+ content: m.content,
516
+ }));
517
+ }
518
+ const model = await callCopilotModel({
519
+ mode: "generateFlashcards",
520
+ context: input.context,
521
+ message: instruction,
522
+ history,
523
+ });
524
+ const parsedFlashcards = z.array(flashcardSchema).safeParse(model.parsed?.flashcards);
525
+ const cards = (parsedFlashcards.success ? parsedFlashcards.data : []).slice(0, input.numCards);
526
+ if (cards.length === 0) {
527
+ throw new TRPCError({
528
+ code: "BAD_REQUEST",
529
+ message: "Copilot did not return valid flashcards.",
530
+ });
531
+ }
532
+ const artifact = await ctx.db.artifact.create({
533
+ data: {
534
+ workspaceId: input.context.workspaceId,
535
+ type: ArtifactType.FLASHCARD_SET,
536
+ title: `Copilot Flashcards - ${new Date().toLocaleString()}`,
537
+ createdById: ctx.session.user.id,
538
+ generating: false,
539
+ flashcards: {
540
+ create: cards.map((card, index) => ({
541
+ front: sanitizeString(card.front, 200),
542
+ back: sanitizeString(card.back, 500),
543
+ order: index,
544
+ tags: ["copilot-generated"],
545
+ })),
546
+ },
547
+ },
548
+ include: {
549
+ flashcards: true,
550
+ },
551
+ });
552
+ await PusherService.emitTaskComplete(input.context.workspaceId, "copilot:response", {
553
+ status: "completed",
554
+ flashcardSetId: artifact.id,
555
+ });
556
+ const answer = getAnswerFromParsedJSON(model.parsed) ||
557
+ `Generated ${artifact.flashcards.length} flashcards.`;
558
+ await persistConversationExchange({
559
+ ctx,
560
+ workspaceId: input.context.workspaceId,
561
+ conversationId: input.conversationId,
562
+ userMessage: instruction,
563
+ assistantMessage: answer,
564
+ });
565
+ return {
566
+ answer,
567
+ artifactId: artifact.id,
568
+ flashcards: artifact.flashcards,
569
+ };
570
+ }),
571
+ });