@studious-lms/server 1.12.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dockerignore +28 -0
- package/.env.example +5 -0
- package/.github/workflows/deploy.yml +123 -0
- package/Dockerfile +54 -0
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/config/cors.d.ts.map +1 -1
- package/dist/lib/config/cors.js +31 -11
- package/dist/lib/config/cors.js.map +1 -1
- package/dist/lib/config/env.d.ts +17 -0
- package/dist/lib/config/env.d.ts.map +1 -1
- package/dist/lib/config/env.js +8 -2
- package/dist/lib/config/env.js.map +1 -1
- package/dist/lib/googleCloudStorage.d.ts +10 -0
- package/dist/lib/googleCloudStorage.d.ts.map +1 -1
- package/dist/lib/googleCloudStorage.js +22 -2
- package/dist/lib/googleCloudStorage.js.map +1 -1
- package/dist/lib/prisma.d.ts +104 -5
- package/dist/lib/prisma.d.ts.map +1 -1
- package/dist/lib/prisma.js +33 -2
- package/dist/lib/prisma.js.map +1 -1
- package/dist/models/agenda.d.ts +20 -20
- package/dist/models/announcement.d.ts +177 -69
- package/dist/models/announcement.d.ts.map +1 -1
- package/dist/models/assignment.d.ts +551 -353
- package/dist/models/assignment.d.ts.map +1 -1
- package/dist/models/attendance.d.ts +197 -71
- package/dist/models/attendance.d.ts.map +1 -1
- package/dist/models/auth.d.ts +348 -114
- package/dist/models/auth.d.ts.map +1 -1
- package/dist/models/class.d.ts +324 -188
- package/dist/models/class.d.ts.map +1 -1
- package/dist/models/class.js +9 -3
- package/dist/models/class.js.map +1 -1
- package/dist/models/cloudStorage.d.ts +146 -56
- package/dist/models/cloudStorage.d.ts.map +1 -1
- package/dist/models/comment.d.ts +269 -110
- package/dist/models/comment.d.ts.map +1 -1
- package/dist/models/comment.js +3 -2
- package/dist/models/comment.js.map +1 -1
- package/dist/models/conversation.d.ts +206 -63
- package/dist/models/conversation.d.ts.map +1 -1
- package/dist/models/conversation.js +13 -2
- package/dist/models/conversation.js.map +1 -1
- package/dist/models/department.d.ts +196 -70
- package/dist/models/department.d.ts.map +1 -1
- package/dist/models/event.d.ts +287 -125
- package/dist/models/event.d.ts.map +1 -1
- package/dist/models/file.d.ts +389 -263
- package/dist/models/file.d.ts.map +1 -1
- package/dist/models/folder.d.ts +433 -181
- package/dist/models/folder.d.ts.map +1 -1
- package/dist/models/labChat.d.ts +209 -83
- package/dist/models/labChat.d.ts.map +1 -1
- package/dist/models/marketing.d.ts +80 -26
- package/dist/models/marketing.d.ts.map +1 -1
- package/dist/models/message.d.ts +95 -41
- package/dist/models/message.d.ts.map +1 -1
- package/dist/models/newtonChat.d.ts +83 -29
- package/dist/models/newtonChat.d.ts.map +1 -1
- package/dist/models/notification.d.ts +61 -25
- package/dist/models/notification.d.ts.map +1 -1
- package/dist/models/school.d.ts +349 -133
- package/dist/models/school.d.ts.map +1 -1
- package/dist/models/section.d.ts +216 -72
- package/dist/models/section.d.ts.map +1 -1
- package/dist/models/tag.d.ts +156 -48
- package/dist/models/tag.d.ts.map +1 -1
- package/dist/models/user.d.ts +82 -28
- package/dist/models/user.d.ts.map +1 -1
- package/dist/models/worksheet.d.ts +1023 -410
- package/dist/models/worksheet.d.ts.map +1 -1
- package/dist/models/worksheet.js +19 -7
- package/dist/models/worksheet.js.map +1 -1
- package/dist/pipelines/aiLabChat.d.ts +0 -8
- package/dist/pipelines/aiLabChat.d.ts.map +1 -1
- package/dist/pipelines/aiLabChat.js +50 -67
- package/dist/pipelines/aiLabChat.js.map +1 -1
- package/dist/pipelines/aiLabChatContract.d.ts +393 -388
- package/dist/pipelines/aiLabChatContract.d.ts.map +1 -1
- package/dist/pipelines/aiLabChatContract.js +63 -69
- package/dist/pipelines/aiLabChatContract.js.map +1 -1
- package/dist/pipelines/aiNewtonChat.d.ts.map +1 -1
- package/dist/pipelines/aiNewtonChat.js +41 -41
- package/dist/pipelines/aiNewtonChat.js.map +1 -1
- package/dist/pipelines/gradeWorksheet.d.ts +8 -8
- package/dist/pipelines/gradeWorksheet.d.ts.map +1 -1
- package/dist/pipelines/gradeWorksheet.js +59 -14
- package/dist/pipelines/gradeWorksheet.js.map +1 -1
- package/dist/pipelines/labChatPrompt.d.ts +10 -8
- package/dist/pipelines/labChatPrompt.d.ts.map +1 -1
- package/dist/pipelines/labChatPrompt.js +47 -67
- package/dist/pipelines/labChatPrompt.js.map +1 -1
- package/dist/pipelines/pdfToWorksheet.d.ts +2 -2
- package/dist/routers/_app.d.ts +2268 -1898
- package/dist/routers/_app.d.ts.map +1 -1
- package/dist/routers/_app.js +4 -2
- package/dist/routers/_app.js.map +1 -1
- package/dist/routers/admin.d.ts +13 -13
- package/dist/routers/agenda.d.ts +18 -18
- package/dist/routers/announcement.d.ts +32 -28
- package/dist/routers/announcement.d.ts.map +1 -1
- package/dist/routers/announcement.js +6 -5
- package/dist/routers/announcement.js.map +1 -1
- package/dist/routers/assignment.d.ts +335 -327
- package/dist/routers/assignment.d.ts.map +1 -1
- package/dist/routers/assignment.js +4 -4
- package/dist/routers/assignment.js.map +1 -1
- package/dist/routers/attendance.d.ts +10 -10
- package/dist/routers/auth.d.ts +2 -2
- package/dist/routers/class.d.ts +170 -147
- package/dist/routers/class.d.ts.map +1 -1
- package/dist/routers/comment.d.ts +40 -16
- package/dist/routers/comment.d.ts.map +1 -1
- package/dist/routers/comment.js +6 -3
- package/dist/routers/comment.js.map +1 -1
- package/dist/routers/conversation.d.ts +17 -17
- package/dist/routers/department.d.ts +34 -34
- package/dist/routers/discussion.d.ts +65 -53
- package/dist/routers/discussion.d.ts.map +1 -1
- package/dist/routers/discussion.js +6 -2
- package/dist/routers/discussion.js.map +1 -1
- package/dist/routers/embedding.d.ts +69 -0
- package/dist/routers/embedding.d.ts.map +1 -0
- package/dist/routers/embedding.js +143 -0
- package/dist/routers/embedding.js.map +1 -0
- package/dist/routers/event.d.ts +39 -39
- package/dist/routers/file.d.ts +12 -12
- package/dist/routers/folder.d.ts +38 -38
- package/dist/routers/labChat.d.ts +19 -19
- package/dist/routers/marketing.d.ts +2 -2
- package/dist/routers/message.d.ts +13 -13
- package/dist/routers/newtonChat.d.ts +4 -4
- package/dist/routers/notifications.d.ts +9 -9
- package/dist/routers/permissions.d.ts +14 -14
- package/dist/routers/school.d.ts +55 -55
- package/dist/routers/search.d.ts +22 -1
- package/dist/routers/search.d.ts.map +1 -1
- package/dist/routers/search.js +9 -3
- package/dist/routers/search.js.map +1 -1
- package/dist/routers/section.d.ts +4 -4
- package/dist/routers/studentProgress.d.ts +1 -1
- package/dist/routers/tag.d.ts +7 -7
- package/dist/routers/user.d.ts +10 -10
- package/dist/routers/worksheet.d.ts +97 -56
- package/dist/routers/worksheet.d.ts.map +1 -1
- package/dist/routers/worksheet.js +28 -2
- package/dist/routers/worksheet.js.map +1 -1
- package/dist/routes/aiStream.d.ts +2 -0
- package/dist/routes/aiStream.d.ts.map +1 -0
- package/dist/routes/aiStream.js +696 -0
- package/dist/routes/aiStream.js.map +1 -0
- package/dist/seedDatabase.d.ts +2 -2
- package/dist/seedDatabase.js +6 -6
- package/dist/seedDatabase.js.map +1 -1
- package/dist/services/adminInstitution.d.ts +8 -8
- package/dist/services/adminRunJob.d.ts +4 -4
- package/dist/services/agenda.d.ts +18 -18
- package/dist/services/aiChatStream.d.ts +68 -0
- package/dist/services/aiChatStream.d.ts.map +1 -0
- package/dist/services/aiChatStream.js +157 -0
- package/dist/services/aiChatStream.js.map +1 -0
- package/dist/services/aiModifierTools.d.ts +32 -0
- package/dist/services/aiModifierTools.d.ts.map +1 -0
- package/dist/services/aiModifierTools.js +165 -0
- package/dist/services/aiModifierTools.js.map +1 -0
- package/dist/services/aiProposalTools.d.ts +32 -0
- package/dist/services/aiProposalTools.d.ts.map +1 -0
- package/dist/services/aiProposalTools.js +207 -0
- package/dist/services/aiProposalTools.js.map +1 -0
- package/dist/services/aiStream.d.ts +22 -0
- package/dist/services/aiStream.d.ts.map +1 -0
- package/dist/services/aiStream.js +142 -0
- package/dist/services/aiStream.js.map +1 -0
- package/dist/services/aiTools.d.ts +16 -0
- package/dist/services/aiTools.d.ts.map +1 -0
- package/dist/services/aiTools.js +271 -0
- package/dist/services/aiTools.js.map +1 -0
- package/dist/services/announcement.d.ts +12 -12
- package/dist/services/announcement.d.ts.map +1 -1
- package/dist/services/announcement.js +7 -2
- package/dist/services/announcement.js.map +1 -1
- package/dist/services/assignment.d.ts +293 -293
- package/dist/services/assignment.d.ts.map +1 -1
- package/dist/services/assignment.js +36 -15
- package/dist/services/assignment.js.map +1 -1
- package/dist/services/attendance.d.ts +10 -10
- package/dist/services/auth.d.ts +2 -2
- package/dist/services/class.d.ts +161 -138
- package/dist/services/class.d.ts.map +1 -1
- package/dist/services/class.js +25 -4
- package/dist/services/class.js.map +1 -1
- package/dist/services/comment.d.ts +34 -16
- package/dist/services/comment.d.ts.map +1 -1
- package/dist/services/comment.js +23 -2
- package/dist/services/comment.js.map +1 -1
- package/dist/services/conversation.d.ts +17 -17
- package/dist/services/conversation.d.ts.map +1 -1
- package/dist/services/conversation.js +9 -7
- package/dist/services/conversation.js.map +1 -1
- package/dist/services/department.d.ts +33 -33
- package/dist/services/discussion.d.ts +58 -58
- package/dist/services/discussion.d.ts.map +1 -1
- package/dist/services/discussion.js +8 -8
- package/dist/services/discussion.js.map +1 -1
- package/dist/services/discussionSummary.d.ts +21 -0
- package/dist/services/discussionSummary.d.ts.map +1 -0
- package/dist/services/discussionSummary.js +179 -0
- package/dist/services/discussionSummary.js.map +1 -0
- package/dist/services/embedding.d.ts +67 -0
- package/dist/services/embedding.d.ts.map +1 -0
- package/dist/services/embedding.js +226 -0
- package/dist/services/embedding.js.map +1 -0
- package/dist/services/event.d.ts +37 -37
- package/dist/services/file.d.ts +24 -24
- package/dist/services/folder.d.ts +36 -36
- package/dist/services/labChat.d.ts +19 -19
- package/dist/services/marketing.d.ts +2 -2
- package/dist/services/message.d.ts +11 -11
- package/dist/services/message.d.ts.map +1 -1
- package/dist/services/message.js +2 -2
- package/dist/services/message.js.map +1 -1
- package/dist/services/newtonChat.d.ts +4 -4
- package/dist/services/notification.d.ts +9 -9
- package/dist/services/notification.d.ts.map +1 -1
- package/dist/services/permissions.d.ts +14 -14
- package/dist/services/school.d.ts +50 -50
- package/dist/services/search.d.ts +12 -0
- package/dist/services/search.d.ts.map +1 -1
- package/dist/services/search.js +120 -2
- package/dist/services/search.js.map +1 -1
- package/dist/services/section.d.ts +3 -3
- package/dist/services/tag.d.ts +4 -4
- package/dist/services/user.d.ts +4 -4
- package/dist/services/user.d.ts.map +1 -1
- package/dist/services/user.js +10 -15
- package/dist/services/user.js.map +1 -1
- package/dist/services/worksheet.d.ts +62 -47
- package/dist/services/worksheet.d.ts.map +1 -1
- package/dist/services/worksheet.js +11 -4
- package/dist/services/worksheet.js.map +1 -1
- package/dist/utils/streamBroadcast.d.ts +11 -0
- package/dist/utils/streamBroadcast.d.ts.map +1 -0
- package/dist/utils/streamBroadcast.js +32 -0
- package/dist/utils/streamBroadcast.js.map +1 -0
- package/dist/workers/connection.d.ts +15 -0
- package/dist/workers/connection.d.ts.map +1 -1
- package/dist/workers/connection.js +20 -2
- package/dist/workers/connection.js.map +1 -1
- package/dist/workers/index.js +4 -2
- package/dist/workers/index.js.map +1 -1
- package/dist/workers/processors/createRunJobWorker.d.ts.map +1 -1
- package/dist/workers/processors/createRunJobWorker.js +31 -8
- package/dist/workers/processors/createRunJobWorker.js.map +1 -1
- package/dist/workers/processors/embedContent.d.ts +8 -0
- package/dist/workers/processors/embedContent.d.ts.map +1 -0
- package/dist/workers/processors/embedContent.js +76 -0
- package/dist/workers/processors/embedContent.js.map +1 -0
- package/dist/workers/queues.d.ts +6 -0
- package/dist/workers/queues.d.ts.map +1 -1
- package/dist/workers/queues.js +5 -3
- package/dist/workers/queues.js.map +1 -1
- package/package.json +5 -1
- package/prisma/migrations/20260609215135_init/migration.sql +1412 -0
- package/prisma/migrations/20260610130000_add_worksheet_tags/migration.sql +13 -0
- package/prisma/schema.prisma +39 -7
- package/src/index.ts +4 -0
- package/src/lib/config/cors.ts +32 -9
- package/src/lib/config/env.ts +6 -0
- package/src/lib/googleCloudStorage.ts +21 -0
- package/src/lib/prisma.ts +40 -1
- package/src/models/class.ts +10 -3
- package/src/models/comment.ts +1 -0
- package/src/models/conversation.ts +12 -0
- package/src/models/worksheet.ts +16 -7
- package/src/pipelines/aiLabChat.ts +54 -79
- package/src/pipelines/aiLabChatContract.ts +69 -69
- package/src/pipelines/aiNewtonChat.ts +46 -43
- package/src/pipelines/gradeWorksheet.ts +66 -15
- package/src/pipelines/labChatPrompt.ts +63 -88
- package/src/routers/_app.ts +2 -0
- package/src/routers/announcement.ts +4 -3
- package/src/routers/assignment.ts +2 -2
- package/src/routers/comment.ts +5 -0
- package/src/routers/discussion.ts +7 -0
- package/src/routers/embedding.ts +159 -0
- package/src/routers/search.ts +10 -1
- package/src/routers/worksheet.ts +29 -0
- package/src/routes/aiStream.ts +789 -0
- package/src/seedDatabase.ts +4 -4
- package/src/services/aiChatStream.ts +219 -0
- package/src/services/aiModifierTools.ts +188 -0
- package/src/services/aiProposalTools.ts +272 -0
- package/src/services/aiStream.ts +175 -0
- package/src/services/aiTools.ts +290 -0
- package/src/services/announcement.ts +7 -0
- package/src/services/assignment.ts +36 -14
- package/src/services/class.ts +30 -2
- package/src/services/comment.ts +22 -0
- package/src/services/conversation.ts +9 -4
- package/src/services/discussion.ts +9 -8
- package/src/services/discussionSummary.ts +226 -0
- package/src/services/embedding.ts +285 -0
- package/src/services/message.ts +2 -2
- package/src/services/search.ts +138 -0
- package/src/services/user.ts +9 -17
- package/src/services/worksheet.ts +10 -2
- package/src/utils/streamBroadcast.ts +48 -0
- package/src/workers/connection.ts +19 -0
- package/src/workers/index.ts +2 -0
- package/src/workers/processors/createRunJobWorker.ts +32 -6
- package/src/workers/processors/embedContent.ts +90 -0
- package/src/workers/queues.ts +5 -1
- package/tests/integration/routers/conversation.test.ts +9 -7
- package/tests/unit/pipelines/aiLabChatContract.test.ts +38 -21
- package/tests/unit/pipelines/labChatPrompt.test.ts +23 -36
- package/prisma/migrations/20250807062924_init/migration.sql +0 -436
- package/prisma/migrations/20250919063704_init2/migration.sql +0 -24
- package/prisma/migrations/20250920143543_add_profile_fields/migration.sql +0 -15
- package/prisma/migrations/20250922165147_add_chat_models/migration.sql +0 -68
- package/prisma/migrations/20250922165314_add_chat_roles/migration.sql +0 -5
- package/prisma/migrations/20250922171242_refactor_notification_system/migration.sql +0 -20
- package/prisma/migrations/20250922172208_add_mentions_system/migration.sql +0 -21
- package/prisma/migrations/20250925072732_add_lab_chat_system/migration.sql +0 -25
- package/prisma/migrations/20251020151505_add_upload_tracking_fields/migration.sql +0 -57
- package/prisma/migrations/20251109122857_annuoncements_comments/migration.sql +0 -30
- package/prisma/migrations/20251109135555_reactions_announcements_comments/migration.sql +0 -35
- package/prisma/migrations/20260410124000_add_submission_recommendation_state/migration.sql +0 -14
- package/prisma/migrations/20260415103500_add_session_type/migration.sql +0 -33
- package/prisma/migrations/20260415133000_add_ai_usage_logs/migration.sql +0 -19
- package/prisma/migrations/20260417083000_add_conversation_member_hidden_at/migration.sql +0 -2
- package/prisma/migrations/20260502230500_assignment_submission_comments/migration.sql +0 -60
- package/prisma/migrations/20260504071500_school_memberships/migration.sql +0 -81
- package/prisma/migrations/20260506162500_consolidate_run_job_and_unify_job_status/migration.sql +0 -166
- package/prisma/migrations/20260509220000_institution_overhaul/migration.sql +0 -184
- package/prisma/migrations/20260510170000_add_folder_permissions/migration.sql +0 -93
- package/prisma/migrations/20260510183000_add_discussions/migration.sql +0 -151
- /package/.github/workflows/{npm.yml → npm-publish.yml} +0 -0
package/src/seedDatabase.ts
CHANGED
|
@@ -42,7 +42,7 @@ export async function clearDatabase() {
|
|
|
42
42
|
// Discussion tree.
|
|
43
43
|
await prisma.discussionReply.deleteMany();
|
|
44
44
|
await prisma.discussion.deleteMany();
|
|
45
|
-
await prisma.
|
|
45
|
+
await prisma.classTag.deleteMany();
|
|
46
46
|
|
|
47
47
|
// Comments after their reactions are gone.
|
|
48
48
|
await prisma.comment.deleteMany();
|
|
@@ -1425,13 +1425,13 @@ export const seedDatabase = async () => {
|
|
|
1425
1425
|
// ---------------------------------------------------------------------
|
|
1426
1426
|
// 15. Discussions (with replies, tags, reads, reactions)
|
|
1427
1427
|
// ---------------------------------------------------------------------
|
|
1428
|
-
const bioTag = await prisma.
|
|
1428
|
+
const bioTag = await prisma.classTag.create({
|
|
1429
1429
|
data: { classId: biologyClass.id, name: "Lab", color: "#10B981" },
|
|
1430
1430
|
});
|
|
1431
|
-
const bioTagHomework = await prisma.
|
|
1431
|
+
const bioTagHomework = await prisma.classTag.create({
|
|
1432
1432
|
data: { classId: biologyClass.id, name: "Homework Help", color: "#F59E0B" },
|
|
1433
1433
|
});
|
|
1434
|
-
const mathTagAP = await prisma.
|
|
1434
|
+
const mathTagAP = await prisma.classTag.create({
|
|
1435
1435
|
data: { classId: mathClass.id, name: "AP Prep", color: "#DC2626" },
|
|
1436
1436
|
});
|
|
1437
1437
|
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared AI chat streaming helper.
|
|
3
|
+
*
|
|
4
|
+
* Runs a genuine token-by-token stream via the Vercel AI SDK (`streamText`)
|
|
5
|
+
* against OpenAI — the same provider the rest of the app's inference uses
|
|
6
|
+
* (`OPENAI_API_KEY`). Real text tokens are broadcast over Pusher as they are
|
|
7
|
+
* produced, and real tool calls are broadcast inline (in the order the model
|
|
8
|
+
* invokes them) instead of being derived after the fact from a JSON blob.
|
|
9
|
+
*
|
|
10
|
+
* Callers own persistence: this helper returns the accumulated text and the
|
|
11
|
+
* ordered tool calls so the pipeline can write `content`/`meta` and emit the
|
|
12
|
+
* terminal `message-stream-complete` / `message-updated` events.
|
|
13
|
+
*/
|
|
14
|
+
import { streamText, stepCountIs, type ModelMessage, type ToolSet } from 'ai';
|
|
15
|
+
import { openai } from '@ai-sdk/openai';
|
|
16
|
+
import { getRedis } from '../lib/redis.js';
|
|
17
|
+
import { pusher, chatChannel } from '../lib/pusher.js';
|
|
18
|
+
import { logger } from '../utils/logger.js';
|
|
19
|
+
|
|
20
|
+
const STREAM_REDIS_TTL = 600; // 10 minutes
|
|
21
|
+
const STREAM_KEY_PREFIX = 'stream:';
|
|
22
|
+
|
|
23
|
+
/** Default streaming model — matches the existing streamAIResponse path. */
|
|
24
|
+
export const DEFAULT_STREAM_MODEL = 'gpt-4o-mini';
|
|
25
|
+
|
|
26
|
+
export interface StreamedToolCall {
|
|
27
|
+
toolName: string;
|
|
28
|
+
/** Args the model passed to the tool. */
|
|
29
|
+
input: unknown;
|
|
30
|
+
/** Value the tool returned (undefined for client-side / no-result tools). */
|
|
31
|
+
output?: unknown;
|
|
32
|
+
status: 'completed' | 'failed';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* An ordered fragment of an AI message. The message is a sequence of these
|
|
37
|
+
* parts in the exact order the model produced them, so a tool call rendered
|
|
38
|
+
* "between paragraph 1 and 2" is represented as
|
|
39
|
+
* `[{text}, {tool}, {text}]` — enabling true inline rendering (and reload
|
|
40
|
+
* persistence) instead of text and tool calls living in separate buckets.
|
|
41
|
+
*/
|
|
42
|
+
export type StreamPart =
|
|
43
|
+
| { type: 'text'; text: string }
|
|
44
|
+
| {
|
|
45
|
+
type: 'tool';
|
|
46
|
+
toolCallId: string;
|
|
47
|
+
toolName: string;
|
|
48
|
+
/** Concrete entity label (e.g. assignment title / search query), if any. */
|
|
49
|
+
title?: string;
|
|
50
|
+
status: 'executing' | 'completed' | 'failed';
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Pull a human-meaningful label out of a tool's input args, if present. */
|
|
54
|
+
function toolTitleFromInput(input: unknown): string | undefined {
|
|
55
|
+
if (input && typeof input === 'object') {
|
|
56
|
+
const obj = input as Record<string, unknown>;
|
|
57
|
+
for (const key of ['title', 'name', 'query'] as const) {
|
|
58
|
+
const val = obj[key];
|
|
59
|
+
if (typeof val === 'string' && val.trim()) return val.trim();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface StreamChatOptions {
|
|
66
|
+
conversationId: string;
|
|
67
|
+
aiMessageId: string;
|
|
68
|
+
system: string;
|
|
69
|
+
messages: ModelMessage[];
|
|
70
|
+
tools?: ToolSet;
|
|
71
|
+
model?: string;
|
|
72
|
+
temperature?: number;
|
|
73
|
+
maxOutputTokens?: number;
|
|
74
|
+
/** Max agent steps (tool round-trips). Defaults to 6. */
|
|
75
|
+
maxSteps?: number;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface StreamChatResult {
|
|
79
|
+
text: string;
|
|
80
|
+
toolCalls: StreamedToolCall[];
|
|
81
|
+
/** Ordered text/tool parts, in the exact order the model produced them. */
|
|
82
|
+
parts: StreamPart[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Stream a chat completion, broadcasting real text chunks and tool-call
|
|
87
|
+
* events over Pusher. Does NOT persist the message or emit the terminal
|
|
88
|
+
* stream-complete event — the caller does that once it has assembled the
|
|
89
|
+
* final `content`/`meta` (e.g. PDF attachments, structured proposals).
|
|
90
|
+
*/
|
|
91
|
+
export async function streamChatResponse(
|
|
92
|
+
options: StreamChatOptions,
|
|
93
|
+
): Promise<StreamChatResult> {
|
|
94
|
+
const {
|
|
95
|
+
conversationId,
|
|
96
|
+
aiMessageId,
|
|
97
|
+
system,
|
|
98
|
+
messages,
|
|
99
|
+
tools,
|
|
100
|
+
model = DEFAULT_STREAM_MODEL,
|
|
101
|
+
temperature = 0.7,
|
|
102
|
+
maxOutputTokens = 4096,
|
|
103
|
+
maxSteps = 6,
|
|
104
|
+
} = options;
|
|
105
|
+
|
|
106
|
+
const redis = getRedis();
|
|
107
|
+
const streamKey = `${STREAM_KEY_PREFIX}${aiMessageId}`;
|
|
108
|
+
if (redis) {
|
|
109
|
+
await redis.set(streamKey, '', 'EX', STREAM_REDIS_TTL);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let fullText = '';
|
|
113
|
+
const parts: StreamPart[] = [];
|
|
114
|
+
const toolCalls: StreamedToolCall[] = [];
|
|
115
|
+
// Map AI SDK toolCallId -> index in `parts` so the executing indicator can
|
|
116
|
+
// be flipped to completed/failed in place (preserving its position).
|
|
117
|
+
const toolPartIndexById = new Map<string, number>();
|
|
118
|
+
|
|
119
|
+
const appendText = (text: string) => {
|
|
120
|
+
fullText += text;
|
|
121
|
+
const last = parts[parts.length - 1];
|
|
122
|
+
if (last && last.type === 'text') {
|
|
123
|
+
last.text += text;
|
|
124
|
+
} else {
|
|
125
|
+
parts.push({ type: 'text', text });
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const broadcast = async (event: string, payload: Record<string, unknown>) => {
|
|
130
|
+
try {
|
|
131
|
+
await pusher.trigger(chatChannel(conversationId), event, payload);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
logger.warn(`Failed to broadcast ${event}`, { err, aiMessageId });
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
const result = streamText({
|
|
139
|
+
model: openai(model),
|
|
140
|
+
system,
|
|
141
|
+
messages,
|
|
142
|
+
...(tools ? { tools } : {}),
|
|
143
|
+
temperature,
|
|
144
|
+
maxOutputTokens,
|
|
145
|
+
stopWhen: stepCountIs(maxSteps),
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// `fullStream` yields text deltas AND tool events in a single, correctly
|
|
149
|
+
// ordered sequence — this is what makes inline tool calls possible. We
|
|
150
|
+
// build an ordered `parts` list and broadcast each event as it happens.
|
|
151
|
+
for await (const part of result.fullStream) {
|
|
152
|
+
switch (part.type) {
|
|
153
|
+
case 'text-delta': {
|
|
154
|
+
appendText(part.text);
|
|
155
|
+
if (redis) {
|
|
156
|
+
await redis.append(streamKey, part.text).catch(() => {});
|
|
157
|
+
}
|
|
158
|
+
await broadcast('message-stream-chunk', {
|
|
159
|
+
messageId: aiMessageId,
|
|
160
|
+
chunk: part.text,
|
|
161
|
+
});
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
case 'tool-call': {
|
|
165
|
+
const title = toolTitleFromInput(part.input);
|
|
166
|
+
toolPartIndexById.set(part.toolCallId, parts.length);
|
|
167
|
+
parts.push({
|
|
168
|
+
type: 'tool',
|
|
169
|
+
toolCallId: part.toolCallId,
|
|
170
|
+
toolName: part.toolName,
|
|
171
|
+
...(title ? { title } : {}),
|
|
172
|
+
status: 'executing',
|
|
173
|
+
});
|
|
174
|
+
await broadcast('message-tool-call', {
|
|
175
|
+
messageId: aiMessageId,
|
|
176
|
+
toolCallId: part.toolCallId,
|
|
177
|
+
toolName: part.toolName,
|
|
178
|
+
...(title ? { title } : {}),
|
|
179
|
+
status: 'executing',
|
|
180
|
+
});
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
case 'tool-result':
|
|
184
|
+
case 'tool-error': {
|
|
185
|
+
const status: 'completed' | 'failed' =
|
|
186
|
+
part.type === 'tool-error' ? 'failed' : 'completed';
|
|
187
|
+
const idx = toolPartIndexById.get(part.toolCallId);
|
|
188
|
+
if (idx !== undefined) {
|
|
189
|
+
const existing = parts[idx];
|
|
190
|
+
if (existing && existing.type === 'tool') existing.status = status;
|
|
191
|
+
}
|
|
192
|
+
toolCalls.push({
|
|
193
|
+
toolName: part.toolName,
|
|
194
|
+
input: part.input,
|
|
195
|
+
output: part.type === 'tool-result' ? part.output : undefined,
|
|
196
|
+
status,
|
|
197
|
+
});
|
|
198
|
+
await broadcast('message-tool-call', {
|
|
199
|
+
messageId: aiMessageId,
|
|
200
|
+
toolCallId: part.toolCallId,
|
|
201
|
+
toolName: part.toolName,
|
|
202
|
+
...(toolTitleFromInput(part.input) ? { title: toolTitleFromInput(part.input) } : {}),
|
|
203
|
+
status,
|
|
204
|
+
});
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
default:
|
|
208
|
+
// ignore reasoning/source/step/finish/raw parts
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return { text: fullText, toolCalls, parts };
|
|
214
|
+
} finally {
|
|
215
|
+
if (redis) {
|
|
216
|
+
await redis.del(streamKey).catch(() => {});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI modifier "field-update" tools.
|
|
3
|
+
*
|
|
4
|
+
* Unlike the Lab-chat proposal tools (which only *record* a payload for the
|
|
5
|
+
* teacher to accept later), these tools DIRECTLY edit a single key of an
|
|
6
|
+
* existing assignment or worksheet and persist it immediately via the normal
|
|
7
|
+
* service layer. The modifier route locks the resource (Redis flag + Pusher
|
|
8
|
+
* `modifier-started`) while the stream runs, and each successful field write
|
|
9
|
+
* fires a callback so the route can broadcast `modifier-field-updated` to every
|
|
10
|
+
* open editor — they apply the change live and stay read-only until the run
|
|
11
|
+
* completes or fails.
|
|
12
|
+
*
|
|
13
|
+
* NOTE: like `aiTools.ts` / `aiProposalTools.ts`, these intentionally use
|
|
14
|
+
* `jsonSchema()` rather than the zod `tool()` helper to avoid the TS2589
|
|
15
|
+
* "excessively deep" compiler blow-up on nested schemas.
|
|
16
|
+
*/
|
|
17
|
+
import { jsonSchema, type ToolSet } from 'ai';
|
|
18
|
+
import { updateAssignmentRecord } from './assignment.js';
|
|
19
|
+
import { updateWorksheetRecord } from './worksheet.js';
|
|
20
|
+
|
|
21
|
+
/** A single field write that was applied to a resource. */
|
|
22
|
+
export interface ModifierFieldUpdate {
|
|
23
|
+
field: string;
|
|
24
|
+
value: unknown;
|
|
25
|
+
/** Human-readable label for the change, e.g. "title" or "due date". */
|
|
26
|
+
label: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const ASSIGNMENT_TYPES = [
|
|
30
|
+
'HOMEWORK', 'QUIZ', 'TEST', 'PROJECT', 'ESSAY', 'DISCUSSION', 'PRESENTATION', 'LAB', 'OTHER',
|
|
31
|
+
] as const;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Editable scalar keys of an assignment, with the coercion + human label used
|
|
35
|
+
* when the model passes a (string) value. Keys map 1:1 to
|
|
36
|
+
* `updateAssignmentRecord` input fields.
|
|
37
|
+
*/
|
|
38
|
+
const ASSIGNMENT_FIELDS: Record<
|
|
39
|
+
string,
|
|
40
|
+
{ label: string; type: 'string' | 'number' | 'boolean' | 'date' | 'enum'; enumValues?: readonly string[] }
|
|
41
|
+
> = {
|
|
42
|
+
title: { label: 'title', type: 'string' },
|
|
43
|
+
instructions: { label: 'instructions', type: 'string' },
|
|
44
|
+
dueDate: { label: 'due date', type: 'date' },
|
|
45
|
+
type: { label: 'type', type: 'enum', enumValues: ASSIGNMENT_TYPES },
|
|
46
|
+
maxGrade: { label: 'max grade', type: 'number' },
|
|
47
|
+
graded: { label: 'graded', type: 'boolean' },
|
|
48
|
+
weight: { label: 'weight', type: 'number' },
|
|
49
|
+
acceptFiles: { label: 'file submissions', type: 'boolean' },
|
|
50
|
+
acceptExtendedResponse: { label: 'extended response', type: 'boolean' },
|
|
51
|
+
acceptWorksheet: { label: 'worksheet submissions', type: 'boolean' },
|
|
52
|
+
aiPolicyLevel: { label: 'AI policy level', type: 'number' },
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const WORKSHEET_FIELDS: Record<string, { label: string; type: 'string' }> = {
|
|
56
|
+
name: { label: 'name', type: 'string' },
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Coerce a model-supplied string value into the type a field expects. */
|
|
60
|
+
function coerceValue(
|
|
61
|
+
raw: string,
|
|
62
|
+
spec: { type: 'string' | 'number' | 'boolean' | 'date' | 'enum'; enumValues?: readonly string[] },
|
|
63
|
+
): unknown {
|
|
64
|
+
switch (spec.type) {
|
|
65
|
+
case 'number': {
|
|
66
|
+
const n = Number(raw);
|
|
67
|
+
if (Number.isNaN(n)) throw new Error(`Expected a number but got "${raw}"`);
|
|
68
|
+
return n;
|
|
69
|
+
}
|
|
70
|
+
case 'boolean': {
|
|
71
|
+
const v = raw.trim().toLowerCase();
|
|
72
|
+
if (['true', 'yes', '1'].includes(v)) return true;
|
|
73
|
+
if (['false', 'no', '0'].includes(v)) return false;
|
|
74
|
+
throw new Error(`Expected a boolean but got "${raw}"`);
|
|
75
|
+
}
|
|
76
|
+
case 'date': {
|
|
77
|
+
const d = new Date(raw);
|
|
78
|
+
if (Number.isNaN(d.getTime())) throw new Error(`Expected an ISO date but got "${raw}"`);
|
|
79
|
+
return d.toISOString();
|
|
80
|
+
}
|
|
81
|
+
case 'enum': {
|
|
82
|
+
const v = raw.trim().toUpperCase();
|
|
83
|
+
if (spec.enumValues && !spec.enumValues.includes(v)) {
|
|
84
|
+
throw new Error(`Expected one of ${spec.enumValues.join(', ')} but got "${raw}"`);
|
|
85
|
+
}
|
|
86
|
+
return v;
|
|
87
|
+
}
|
|
88
|
+
default:
|
|
89
|
+
return raw;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Build the field-update tool for an assignment. The `onFieldUpdate` callback
|
|
95
|
+
* runs after a successful persist so the route can broadcast the change.
|
|
96
|
+
*/
|
|
97
|
+
export function assignmentModifierTools(
|
|
98
|
+
userId: string,
|
|
99
|
+
assignmentId: string,
|
|
100
|
+
classId: string,
|
|
101
|
+
onFieldUpdate: (update: ModifierFieldUpdate) => Promise<void> | void,
|
|
102
|
+
): ToolSet {
|
|
103
|
+
const fieldNames = Object.keys(ASSIGNMENT_FIELDS);
|
|
104
|
+
return {
|
|
105
|
+
update_assignment_field: {
|
|
106
|
+
description:
|
|
107
|
+
'Directly update a single field of the assignment and save it immediately. ' +
|
|
108
|
+
'Call this once per field the teacher wants changed. The assignment is locked ' +
|
|
109
|
+
'for editing until you finish.',
|
|
110
|
+
inputSchema: jsonSchema({
|
|
111
|
+
type: 'object',
|
|
112
|
+
properties: {
|
|
113
|
+
field: {
|
|
114
|
+
type: 'string',
|
|
115
|
+
enum: fieldNames,
|
|
116
|
+
description: 'The assignment field to update.',
|
|
117
|
+
},
|
|
118
|
+
value: {
|
|
119
|
+
type: 'string',
|
|
120
|
+
description:
|
|
121
|
+
'The new value as a string. Booleans use "true"/"false", numbers as digits, ' +
|
|
122
|
+
'dates as ISO 8601, type as one of the allowed enum values.',
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
required: ['field', 'value'],
|
|
126
|
+
}),
|
|
127
|
+
execute: async ({ field, value }: { field: string; value: string }) => {
|
|
128
|
+
const spec = ASSIGNMENT_FIELDS[field];
|
|
129
|
+
if (!spec) {
|
|
130
|
+
return `Unknown field "${field}". Allowed: ${fieldNames.join(', ')}.`;
|
|
131
|
+
}
|
|
132
|
+
let coerced: unknown;
|
|
133
|
+
try {
|
|
134
|
+
coerced = coerceValue(value, spec);
|
|
135
|
+
} catch (err) {
|
|
136
|
+
return `Could not update ${spec.label}: ${(err as Error).message}`;
|
|
137
|
+
}
|
|
138
|
+
const updateInput: Parameters<typeof updateAssignmentRecord>[1] = {
|
|
139
|
+
id: assignmentId,
|
|
140
|
+
classId,
|
|
141
|
+
};
|
|
142
|
+
(updateInput as Record<string, unknown>)[field] = coerced;
|
|
143
|
+
await updateAssignmentRecord(userId, updateInput);
|
|
144
|
+
await onFieldUpdate({ field, value: coerced, label: spec.label });
|
|
145
|
+
return `Updated ${spec.label}.`;
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Build the field-update tool for a worksheet. */
|
|
152
|
+
export function worksheetModifierTools(
|
|
153
|
+
worksheetId: string,
|
|
154
|
+
userId: string,
|
|
155
|
+
onFieldUpdate: (update: ModifierFieldUpdate) => Promise<void> | void,
|
|
156
|
+
): ToolSet {
|
|
157
|
+
const fieldNames = Object.keys(WORKSHEET_FIELDS);
|
|
158
|
+
return {
|
|
159
|
+
update_worksheet_field: {
|
|
160
|
+
description:
|
|
161
|
+
'Directly update a single field of the worksheet and save it immediately. ' +
|
|
162
|
+
'The worksheet is locked for editing until you finish.',
|
|
163
|
+
inputSchema: jsonSchema({
|
|
164
|
+
type: 'object',
|
|
165
|
+
properties: {
|
|
166
|
+
field: {
|
|
167
|
+
type: 'string',
|
|
168
|
+
enum: fieldNames,
|
|
169
|
+
description: 'The worksheet field to update.',
|
|
170
|
+
},
|
|
171
|
+
value: { type: 'string', description: 'The new value as a string.' },
|
|
172
|
+
},
|
|
173
|
+
required: ['field', 'value'],
|
|
174
|
+
}),
|
|
175
|
+
execute: async ({ field, value }: { field: string; value: string }) => {
|
|
176
|
+
const spec = WORKSHEET_FIELDS[field];
|
|
177
|
+
if (!spec) {
|
|
178
|
+
return `Unknown field "${field}". Allowed: ${fieldNames.join(', ')}.`;
|
|
179
|
+
}
|
|
180
|
+
const updateInput: Parameters<typeof updateWorksheetRecord>[2] = {};
|
|
181
|
+
(updateInput as Record<string, unknown>)[field] = value;
|
|
182
|
+
await updateWorksheetRecord(worksheetId, userId, updateInput);
|
|
183
|
+
await onFieldUpdate({ field, value, label: spec.label });
|
|
184
|
+
return `Updated ${spec.label}.`;
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|