Second revision: MCP servers, shared-link AI, flashcard modes, document previews
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s

Generation
- Every quiz is NCLEX style; "Practice exam" writes 50 questions.
- Calculation questions only when the material involves calculations (max 5 per exam).
- Broad topics: the class's topics are listed in the prompt, a quick grouping call maps
  narrow labels onto broad ones, and leftover variants are merged.
- Exact select-all count per batch; option order shuffled.
- Python check: at most 3 runs, fixed problems count as passed, cosmetic remarks ignored.

Assistant
- Text, tool steps and cards appear in the order they happen, with paragraph breaks
  between steps.
- Optional thinking box: fixed height, follows the newest text, can be scrolled back.
- "+" opens a material picker listing recent items; items can be dragged in from class
  pages; shorter placeholder.

MCP servers
- Streamable HTTP client; encrypted headers.
- Per-server instructions and switches for chat, Explain, generation and the quiz check.
- Settings UI.

Share links
- Optional "Explain this" and "Ask about this material" per link, off by default.
- Items are loaded on the server and checked against the share; no tools; rate-limited.
- Migration 4 stores the switches.

Study and documents
- Standard flashcard mode (optionally repeat missed cards until known) next to spaced
  repetition.
- Streak visuals restyled in the app palette.
- Side by side / Original document views, with sandboxed previews of Word and PowerPoint
  files.

Other
- Built-in embedding model baked into the image; sharp stubbed if it cannot load; real
  load error shown in Settings.
- Python runner blocks network and process modules in JavaScript too.
- "View questions and answers" removed from the quiz start screen.
- Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 15:48:54 -07:00
parent 5ea61c882c
commit 031f7bec31
45 changed files with 2918 additions and 397 deletions

View file

@ -19,6 +19,7 @@ import {
startImprove,
updateDraftPayload,
} from '../ai/generate.ts';
import { deleteMcpServer, listMcpServers, mcpServerInputSchema, mcpServerPatchSchema, saveMcpServer, testMcpServer } from '../ai/mcp.ts';
import { CATALOG_UPDATED, listAdapterMeta } from '../ai/providers/index.ts';
import {
addManualModel,
@ -34,6 +35,7 @@ import {
patchModel,
providerInputSchema,
runChat,
runChatWithMcp,
saveProvider,
saveTaskSettings,
TASK_INFO,
@ -41,13 +43,14 @@ import {
usageSummary,
} from '../ai/service.ts';
import { embedTexts, embeddingSettingsSchema, getEmbeddingSettings, embeddingStatus, rebuildIndex, saveEmbeddingSettings, scheduleIndexing } from '../services/semantic.ts';
import { EXPLAIN_SYSTEM, explainPrompt } from '../ai/explain.ts';
import { AIError } from '../ai/types.ts';
import { badRequest, HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
type Emit<T> = (event: T) => void;
/** Server-sent events with ordered writes, keep-alive pings and abort propagation. */
function sse<T extends { type: string }>(c: Context, run: (emit: Emit<T>, signal: AbortSignal) => Promise<void>) {
export function sse<T extends { type: string }>(c: Context, run: (emit: Emit<T>, signal: AbortSignal) => Promise<void>) {
c.header('X-Accel-Buffering', 'no');
c.header('Cache-Control', 'no-cache, no-transform');
return streamSSE(c, async (stream) => {
@ -96,8 +99,6 @@ const contentDraftSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('note'), title: z.string().max(200), content: z.string().max(400000) }),
]);
const EXPLAIN_SYSTEM = `You are a patient nursing instructor helping a student while they study. Explain clearly and briefly (aim for under 200 words unless asked for more).
Use Markdown. Lead with the key idea, explain the reasoning, and connect it to patient care. If answer choices are given, say why the correct one is right and, in a line each, why the others are wrong. Do not restate the whole question.`;
export function aiRoutes(app: AppContext): Hono {
const { db } = app;
@ -131,6 +132,16 @@ export function aiRoutes(app: AppContext): Hono {
return c.json({ ...result, models: listModels(db) });
});
// MCP servers the assistant can call as tools.
r.get('/ai/mcp', (c) => c.json({ servers: listMcpServers(app) }));
r.post('/ai/mcp', async (c) => c.json({ server: saveMcpServer(app, null, await readBody(c, mcpServerInputSchema)) }, 201));
r.patch('/ai/mcp/:id', async (c) => c.json({ server: saveMcpServer(app, idParam(c), await readBody(c, mcpServerPatchSchema)) }));
r.delete('/ai/mcp/:id', (c) => {
deleteMcpServer(app, idParam(c));
return c.json({ ok: true });
});
r.post('/ai/mcp/:id/test', async (c) => c.json({ result: await testMcpServer(app, idParam(c)) }));
r.get('/ai/models', (c) => c.json({ models: listModels(db) }));
r.post('/ai/models', async (c) => c.json({ model: addManualModel(app, await readBody(c, manualModelSchema)) }, 201));
r.patch('/ai/models/:id', async (c) => c.json({ model: patchModel(db, idParam(c), await readBody(c, modelPatchSchema)) }));
@ -278,36 +289,35 @@ export function aiRoutes(app: AppContext): Hono {
r.post('/ai/explain', async (c) => {
const body = await readBody(c, explainSchema);
let prompt: string;
if (body.kind === 'question') {
prompt = [
`Question:\n${body.stem}`,
`Choices:\n${body.options.map((o) => `- ${o.text}${o.correct ? ' (correct)' : ''}`).join('\n')}`,
body.selected?.length ? `The student chose: ${body.selected.join('; ')}` : '',
body.rationale ? `Existing rationale:\n${body.rationale}` : '',
body.ask ? `The student asks: ${body.ask}` : 'Explain this question so it finally makes sense. If the student chose wrongly, address the misunderstanding behind their choice.',
]
.filter(Boolean)
.join('\n\n');
} else if (body.kind === 'card') {
prompt = `Flashcard front:\n${body.front}\n\nFlashcard back:\n${body.back}\n\n${body.ask ? `The student asks: ${body.ask}` : 'Explain this card in more depth and give one way to remember it.'}`;
} else {
prompt = `${body.text}\n\n${body.ask ? `The student asks: ${body.ask}` : 'Explain this passage in simpler terms and point out what is most important to remember.'}`;
}
const prompt = explainPrompt(body);
if (!prompt.trim()) throw badRequest('Nothing to explain');
return sse<{ type: 'text'; delta: string } | { type: 'error'; message: string; code: string } | { type: 'done' }>(c, async (emit, signal) => {
try {
await runChat(app, {
task: 'quick',
purpose: 'explanation',
system: EXPLAIN_SYSTEM,
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
maxOutputTokens: 1500,
signal,
onEvent: (e) => {
if (e.type === 'text') emit({ type: 'text', delta: e.delta });
let wrote = false;
await runChatWithMcp(
app,
{
task: 'quick',
purpose: 'explanation',
system: EXPLAIN_SYSTEM,
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
maxOutputTokens: 1500,
signal,
onEvent: (e) => {
if (e.type !== 'text') return;
wrote = true;
emit({ type: 'text', delta: e.delta });
},
},
});
'explain',
{
// Text before a tool call ends its paragraph.
onTool: () => {
if (wrote) emit({ type: 'text', delta: '\n\n' });
wrote = false;
},
},
);
} catch (err) {
const ai = err instanceof AIError ? err : null;
if (ai?.code !== 'aborted') emit({ type: 'error', code: ai?.code ?? 'server', message: ai?.message ?? 'The explanation could not be generated.' });

View file

@ -10,6 +10,7 @@ import { badRequest, HttpError, idParam, readBody, type AppContext } from '../ht
import { getClass, mapClass, resolveFolder } from '../services/content.ts';
import { deleteDocument, documentPath, enqueue, getDocument, ingestUpload, listChunks, mapDocument, sourceLabel } from '../services/documents.ts';
import { now } from '../util.ts';
import { officePreviewHtml, PREVIEW_CSP } from '../documents/preview.ts';
import { shareFor } from './library.ts';
const IMAGE_TYPES: Record<string, { ext: string; test: (b: Uint8Array) => boolean }> = {
@ -113,6 +114,29 @@ export function documentRoutes(app: AppContext): Hono {
});
});
// Word and PowerPoint files as a sandboxed HTML page, to read the original next to the extracted text.
r.get('/documents/:id/preview', async (c) => {
const doc = getDocument(db, idParam(c));
if (doc.kind !== 'docx' && doc.kind !== 'pptx') throw new HttpError(404, 'not_found', 'Only Word and PowerPoint files have a preview');
const file = documentPath(app, doc);
if (!fs.existsSync(file)) throw new HttpError(404, 'not_found', 'The original file is missing from storage');
let html: string;
try {
html = await officePreviewHtml(doc.kind, new Uint8Array(await fs.promises.readFile(file)), doc.title);
} catch (err) {
app.log('warn', 'Document preview failed', err instanceof Error ? err.message : err);
throw new HttpError(422, 'preview_failed', 'This file could not be shown. Download it to open it instead.');
}
return new Response(html, {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': PREVIEW_CSP,
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'private, max-age=3600',
},
});
});
r.patch('/documents/:id', async (c) => {
const doc = getDocument(db, idParam(c));
const body = await readBody(c, z.object({ title: titleSchema.optional(), folderId: z.string().nullish() }));

View file

@ -1,10 +1,17 @@
import fs from 'node:fs';
import path from 'node:path';
import { Hono } from 'hono';
import { Hono, type Context } from 'hono';
import { z } from 'zod';
import { clientIp } from '../auth.ts';
import { EXPLAIN_SYSTEM, explainPrompt } from '../ai/explain.ts';
import { aiStatus, runChat } from '../ai/service.ts';
import { AIError, type ChatMessage } from '../ai/types.ts';
import { HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
import { listCards, listQuestions } from '../services/content.ts';
import { newId, newToken, now } from '../util.ts';
import { searchChunks, sourceLabel, type ChunkHit } from '../services/documents.ts';
import { hybridSearch } from '../services/semantic.ts';
import { newId, newToken, now, parseJson } from '../util.ts';
import { sse } from './ai.ts';
const KINDS = ['quiz', 'deck', 'folder', 'class', 'note', 'document'] as const;
type ShareKind = (typeof KINDS)[number];
@ -19,8 +26,19 @@ interface ShareRow {
last_viewed_at: number | null;
created_at: number;
updated_at: number;
ai: string;
}
/** AI features a share's visitors may use. Both are off until the owner turns them on. */
export interface ShareAi {
/** "Explain this" on shared questions and flashcards. */
explain: boolean;
/** A chat assistant that answers from the shared material only. */
assistant: boolean;
}
const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ explain: false, assistant: false, ...parseJson<Partial<ShareAi>>(row.ai, {}) });
const TABLE: Record<ShareKind, { table: string; title: string }> = {
quiz: { table: 'quizzes', title: 'title' },
deck: { table: 'decks', title: 'title' },
@ -40,6 +58,7 @@ function mapShare(row: ShareRow) {
viewCount: row.view_count,
lastViewedAt: row.last_viewed_at,
createdAt: row.created_at,
ai: shareAi(row),
};
}
@ -86,9 +105,12 @@ export function shareRoutes(app: AppContext): Hono {
r.patch('/shares/:id', async (c) => {
const id = idParam(c);
const body = await readBody(c, z.object({ enabled: z.boolean() }));
const { changes } = db.run('UPDATE shares SET enabled = ?, updated_at = ? WHERE id = ?', body.enabled ? 1 : 0, now(), id);
if (!changes) throw notFound('Share link');
const body = await readBody(c, z.object({ enabled: z.boolean().optional(), ai: z.object({ explain: z.boolean(), assistant: z.boolean() }).partial().optional() }));
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id);
if (!row) throw notFound('Share link');
const enabled = body.enabled ?? Boolean(row.enabled);
const ai = { ...shareAi(row), ...body.ai };
db.run('UPDATE shares SET enabled = ?, ai = ?, updated_at = ? WHERE id = ?', enabled ? 1 : 0, JSON.stringify(ai), now(), id);
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
});
@ -111,6 +133,64 @@ export function shareRoutes(app: AppContext): Hono {
/* ------------------------------ public (no auth) ------------------------------ */
/** Visitor AI requests: per visitor per link, and per link overall, so a public link can't run up the owner's bill. */
const VISITOR_LIMIT = { max: 20, windowMs: 10 * 60_000 };
const LINK_LIMIT = { max: 150, windowMs: 60 * 60_000 };
const aiHits = new Map<string, number[]>();
function hit(key: string, limit: { max: number; windowMs: number }, at: number): void {
const list = (aiHits.get(key) ?? []).filter((t) => at - t < limit.windowMs);
if (list.length >= limit.max) {
aiHits.set(key, list);
const retry = Math.max(1, Math.ceil((list[0] + limit.windowMs - at) / 60_000));
throw new HttpError(429, 'rate_limited', `Too many AI requests on this link. Try again in ${retry} minute${retry === 1 ? '' : 's'}.`);
}
list.push(at);
aiHits.set(key, list);
}
function limitVisitor(shareId: string, ip: string): void {
const at = Date.now();
if (aiHits.size > 5000) aiHits.clear();
hit(`link:${shareId}`, LINK_LIMIT, at);
hit(`ip:${shareId}:${ip}`, VISITOR_LIMIT, at);
}
export function resetShareAiLimits(): void {
aiHits.clear();
}
const clipText = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}\n…(more not shown)` : text);
/** What the shared assistant may read: the shared item (or the one being viewed) and the documents in scope. */
function sharedMaterial(app: AppContext, share: ShareRow, viewing?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string }): { title: string; text: string; documentIds: string[] } {
const meta = TABLE[share.kind];
const title = app.db.get<{ title: string }>(`SELECT ${meta.title} AS title FROM ${meta.table} WHERE id = ?`, share.target_id)?.title ?? 'Shared material';
const describe = (kind: 'quiz' | 'deck' | 'note' | 'document', id: string): { text: string; documentIds: string[] } => {
if (kind === 'quiz') {
const quiz = publicQuiz(app, id);
return { text: `Quiz "${quiz.title}":\n${quiz.questions.map((q, i) => `${i + 1}. ${q.stem}\n${q.options.map((o) => ` - ${o.text}${o.correct ? ' (correct)' : ''}`).join('\n')}${q.rationale ? `\n Rationale: ${q.rationale}` : ''}`).join('\n')}`, documentIds: [] };
}
if (kind === 'deck') {
const deck = publicDeck(app, id);
return { text: `Flashcards "${deck.title}":\n${deck.cards.map((c) => `- ${c.front} :: ${c.back}`).join('\n')}`, documentIds: [] };
}
if (kind === 'note') {
const note = publicNote(app, id);
return { text: `Note "${note.title}":\n${note.content}`, documentIds: [] };
}
return { text: '', documentIds: [id] };
};
if (share.kind === 'class' || share.kind === 'folder') {
const items = collectionItems(app, share);
const listing = `Materials in this shared ${share.kind}:\n${items.map((i) => `- ${i.kind}: ${i.title}`).join('\n')}`;
const current = viewing ? describe(viewing.kind, viewing.id) : { text: '', documentIds: [] };
return { title, text: clipText([current.text ? `The visitor is looking at this:\n${current.text}` : '', listing].filter(Boolean).join('\n\n'), 24_000), documentIds: items.filter((i) => i.kind === 'document').map((i) => i.id) };
}
const own = describe(share.kind, share.target_id);
return { title, text: clipText(own.text, 24_000), documentIds: own.documentIds };
}
const gone = () => new HttpError(404, 'share_not_found', 'This link is no longer available');
function publicQuiz(app: AppContext, id: string) {
@ -185,6 +265,14 @@ export function publicRoutes(app: AppContext): Hono {
const { db } = app;
const r = new Hono();
/** The switches visitors see: on only when the owner allowed it and a model is configured. */
const publicAi = (share: ShareRow): ShareAi => {
const flags = shareAi(share);
if (!flags.explain && !flags.assistant) return flags;
const ready = aiStatus(app).ready;
return { explain: flags.explain && ready, assistant: flags.assistant && ready };
};
const load = (token: string): ShareRow => {
if (!token || token.length < 16 || token.length > 64) throw gone();
const share = db.get<ShareRow>('SELECT * FROM shares WHERE token = ?', token);
@ -197,26 +285,27 @@ export function publicRoutes(app: AppContext): Hono {
db.run('UPDATE shares SET view_count = view_count + 1, last_viewed_at = ? WHERE id = ?', now(), share.id);
c.header('Cache-Control', 'no-store');
c.header('X-Robots-Tag', 'noindex, nofollow');
const ai = publicAi(share);
switch (share.kind) {
case 'quiz':
return c.json(publicQuiz(app, share.target_id));
return c.json({ ...publicQuiz(app, share.target_id), ai });
case 'deck':
return c.json(publicDeck(app, share.target_id));
return c.json({ ...publicDeck(app, share.target_id), ai });
case 'note':
return c.json(publicNote(app, share.target_id));
return c.json({ ...publicNote(app, share.target_id), ai });
case 'document':
return c.json(publicDocument(app, share.target_id));
return c.json({ ...publicDocument(app, share.target_id), ai });
case 'folder': {
const folder = db.get<{ id: string; name: string; class_id: string }>('SELECT id, name, class_id FROM folders WHERE id = ?', share.target_id);
if (!folder) throw gone();
const cls = db.get<{ name: string; color: string }>('SELECT name, color FROM classes WHERE id = ?', folder.class_id);
return c.json({ kind: 'collection' as const, title: folder.name, subtitle: cls?.name ?? '', color: cls?.color ?? 'cobalt', folders: [], items: collectionItems(app, share) });
return c.json({ kind: 'collection' as const, title: folder.name, subtitle: cls?.name ?? '', color: cls?.color ?? 'cobalt', folders: [], items: collectionItems(app, share), ai });
}
case 'class': {
const cls = db.get<{ id: string; name: string; code: string; description: string; color: string }>('SELECT * FROM classes WHERE id = ?', share.target_id);
if (!cls) throw gone();
const folders = db.all<{ id: string; name: string }>('SELECT id, name FROM folders WHERE class_id = ? ORDER BY sort_order, created_at', cls.id);
return c.json({ kind: 'collection' as const, title: cls.name, subtitle: cls.code, description: cls.description, color: cls.color, folders, items: collectionItems(app, share) });
return c.json({ kind: 'collection' as const, title: cls.name, subtitle: cls.code, description: cls.description, color: cls.color, folders, items: collectionItems(app, share), ai });
}
default:
throw gone();
@ -233,10 +322,11 @@ export function publicRoutes(app: AppContext): Hono {
if (!allowed) throw gone();
c.header('Cache-Control', 'no-store');
c.header('X-Robots-Tag', 'noindex, nofollow');
if (kind === 'quiz') return c.json(publicQuiz(app, id));
if (kind === 'deck') return c.json(publicDeck(app, id));
if (kind === 'document') return c.json(publicDocument(app, id));
return c.json(publicNote(app, id));
const ai = publicAi(share);
if (kind === 'quiz') return c.json({ ...publicQuiz(app, id), ai });
if (kind === 'deck') return c.json({ ...publicDeck(app, id), ai });
if (kind === 'document') return c.json({ ...publicDocument(app, id), ai });
return c.json({ ...publicNote(app, id), ai });
});
const sendDocument = (documentId: string) => {
@ -264,6 +354,100 @@ export function publicRoutes(app: AppContext): Hono {
return sendDocument(share.target_id);
});
/* ------------------------------ AI for visitors ------------------------------ */
/** True when the item is the shared target or sits inside the shared class or folder. */
const inScope = (share: ShareRow, kind: 'quiz' | 'deck' | 'note' | 'document', id: string): boolean =>
share.kind === kind ? share.target_id === id : (share.kind === 'class' || share.kind === 'folder') && collectionItems(app, share).some((i) => i.kind === kind && i.id === id);
const requireAi = (c: Context, share: ShareRow, feature: keyof ShareAi) => {
if (!shareAi(share)[feature]) throw new HttpError(403, 'ai_disabled', 'The owner has not turned this on for this link.');
if (!aiStatus(app).ready) throw new HttpError(503, 'ai_unavailable', 'AI is not available right now.');
limitVisitor(share.id, clientIp(c, app.config.trustProxy));
};
const explainSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('question'), quizId: z.string().max(64), questionId: z.string().max(64), selected: z.array(z.string().max(4000)).max(12).optional(), ask: z.string().max(500).optional() }),
z.object({ kind: z.literal('card'), deckId: z.string().max(64), cardId: z.string().max(64), ask: z.string().max(500).optional() }),
]);
/**
* "Explain this" for visitors. The request names a question or card; its content is loaded
* here (never taken from the request), so a link can't be used as a general-purpose model.
*/
r.post('/:token/explain', async (c) => {
const share = load(c.req.param('token'));
const body = await readBody(c, explainSchema);
requireAi(c, share, 'explain');
let prompt: string;
if (body.kind === 'question') {
if (!inScope(share, 'quiz', body.quizId)) throw gone();
const q = listQuestions(db, body.quizId).find((x) => x.id === body.questionId);
if (!q) throw gone();
const texts = new Set(q.options.map((o) => o.text));
prompt = explainPrompt({ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected: body.selected?.filter((s) => texts.has(s) || q.type === 'numeric').map((s) => s.slice(0, 200)), rationale: q.rationale, ask: body.ask });
} else {
if (!inScope(share, 'deck', body.deckId)) throw gone();
const card = listCards(db, body.deckId).find((x) => x.id === body.cardId);
if (!card) throw gone();
prompt = explainPrompt({ kind: 'card', front: card.front, back: card.back, ask: body.ask });
}
return sse<{ type: 'text'; delta: string } | { type: 'error'; message: string; code: string } | { type: 'done' }>(c, async (emit, signal) => {
try {
// No MCP tools on public links: visitors never reach the owner's connected services.
await runChat(app, { task: 'quick', purpose: 'shared explanation', system: EXPLAIN_SYSTEM, messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }], maxOutputTokens: 1500, signal, onEvent: (e) => e.type === 'text' && emit({ type: 'text', delta: e.delta }) });
} catch (err) {
const ai = err instanceof AIError ? err : null;
if (ai?.code !== 'aborted') emit({ type: 'error', code: ai?.code ?? 'server', message: 'The explanation could not be generated. Try again later.' });
}
emit({ type: 'done' });
});
});
const chatSchema = z.object({
messages: z
.array(z.object({ role: z.enum(['user', 'assistant']), text: z.string().trim().min(1).max(4000) }))
.min(1)
.max(16)
.refine((m) => m[m.length - 1].role === 'user', 'The last message must be from the visitor'),
/** The item the visitor is looking at inside a shared class or folder. */
item: z.object({ kind: z.enum(['quiz', 'deck', 'note', 'document']), id: z.string().max(64) }).optional(),
});
/** A chat that answers from the shared material only: no tools, no library access, nothing saved. */
r.post('/:token/chat', async (c) => {
const share = load(c.req.param('token'));
const body = await readBody(c, chatSchema);
requireAi(c, share, 'assistant');
const question = body.messages[body.messages.length - 1].text;
const material = sharedMaterial(app, share, body.item && inScope(share, body.item.kind, body.item.id) ? body.item : undefined);
let hits: ChunkHit[] = [];
if (material.documentIds.length) {
const scope = { documentIds: material.documentIds };
hits = await hybridSearch(app, question, scope, 6).catch(() => searchChunks(db, question, scope, 6));
}
const excerpts = hits.map((h) => `[${sourceLabel(h)}]\n${h.text}`).join('\n\n---\n\n');
const system = [
`You are a study assistant on a page someone shared: "${material.title}". Help the visitor understand and remember this material.`,
'Answer from the shared material below and from general nursing knowledge. You cannot see anything else of the owner\'s, and you cannot change anything. If a question has nothing to do with studying this material, politely say you can only help with it.',
'When you use a document excerpt, name its source in parentheses, e.g. (Lecture 3, p. 4). Be concise and use Markdown.',
material.text ? `SHARED MATERIAL:\n${material.text}` : '',
excerpts ? `RELEVANT DOCUMENT EXCERPTS:\n${excerpts}` : '',
]
.filter(Boolean)
.join('\n\n');
const messages: ChatMessage[] = body.messages.map((m) => ({ role: m.role, content: [{ type: 'text', text: m.text }] }));
return sse<{ type: 'text'; delta: string } | { type: 'error'; message: string; code: string } | { type: 'done' }>(c, async (emit, signal) => {
try {
await runChat(app, { task: 'chat', purpose: 'shared assistant', system, messages, maxOutputTokens: 1500, signal, onEvent: (e) => e.type === 'text' && emit({ type: 'text', delta: e.delta }) });
} catch (err) {
const ai = err instanceof AIError ? err : null;
if (ai?.code !== 'aborted') emit({ type: 'error', code: ai?.code ?? 'server', message: 'The assistant could not answer. Try again later.' });
}
emit({ type: 'done' });
});
});
/** Download for a document inside a shared class or folder. Membership is re-checked. */
r.get('/:token/items/document/:id/file', (c) => {
const share = load(c.req.param('token'));