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
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:
parent
5ea61c882c
commit
031f7bec31
45 changed files with 2918 additions and 397 deletions
|
|
@ -10,6 +10,7 @@ import type { DB } from '../db.ts';
|
|||
import { HttpError, notFound, type AppContext } from '../http.ts';
|
||||
import { getSetting, setSetting } from '../settings.ts';
|
||||
import { newId, now, parseJson } from '../util.ts';
|
||||
import { loadMcpTools, mcpPromptNote, type McpArea } from './mcp.ts';
|
||||
import { cachedInputPrice, cacheWriteRatio, getAdapter, lookupModelDefaults, priceMultiplier } from './providers/index.ts';
|
||||
import {
|
||||
AIError,
|
||||
|
|
@ -17,6 +18,7 @@ import {
|
|||
PROVIDER_KINDS,
|
||||
REASONING_EFFORTS,
|
||||
type ChatMessage,
|
||||
type ContentPart,
|
||||
type ChatRequest,
|
||||
type DiscoveredModel,
|
||||
type ModelCapabilities,
|
||||
|
|
@ -580,11 +582,59 @@ export function parseLooseJson(text: string): unknown {
|
|||
}
|
||||
}
|
||||
|
||||
const MCP_ROUNDS = 4;
|
||||
|
||||
/**
|
||||
* runChat with the MCP tools allowed in `area`. The model may call them for up to MCP_ROUNDS
|
||||
* rounds; the result is the first reply with no MCP calls (or any call to the caller's own
|
||||
* tools), so callers handle it exactly like a plain runChat result.
|
||||
*/
|
||||
export async function runChatWithMcp(app: AppContext, opts: ChatOptions, area: McpArea, hooks: { onTool?: (label: string) => void } = {}): Promise<ChatResult> {
|
||||
const resolved = resolveModel(app, opts.task, opts.modelId);
|
||||
if (!resolved.model.capabilities.tools) return runChat(app, opts);
|
||||
const mcp = await loadMcpTools(app, area, opts.signal);
|
||||
if (!mcp.tools.length) return runChat(app, opts);
|
||||
const own = new Set((opts.tools ?? []).map((t) => t.name));
|
||||
const forced = opts.toolChoice === 'required' || typeof opts.toolChoice === 'object';
|
||||
const system = `${opts.system ?? ''}${mcpPromptNote(mcp)}${forced ? `\n\nYou may call the external tools first if they help; finish by calling ${typeof opts.toolChoice === 'object' ? opts.toolChoice.name : 'the required tool'}.` : ''}`;
|
||||
const tools = [...(opts.tools ?? []), ...mcp.tools.map((t) => t.def)];
|
||||
const messages = [...opts.messages];
|
||||
for (let round = 0; ; round += 1) {
|
||||
const last = round >= MCP_ROUNDS;
|
||||
// While MCP rounds remain a forced choice becomes "some tool"; on the last round the original choice returns.
|
||||
const toolChoice = last ? (forced ? opts.toolChoice : 'none') : forced ? 'required' : (opts.toolChoice ?? 'auto');
|
||||
const res = await runChat(app, { ...opts, system, messages, tools, toolChoice });
|
||||
const calls = res.message.content.filter((p): p is Extract<ContentPart, { type: 'tool_call' }> => p.type === 'tool_call');
|
||||
const external = calls.filter((c) => !own.has(c.name) && mcp.tools.some((t) => t.def.name === c.name));
|
||||
if (last || external.length === 0 || calls.some((c) => own.has(c.name))) return res;
|
||||
const results: ContentPart[] = [];
|
||||
for (const call of calls) {
|
||||
const binding = mcp.tools.find((t) => t.def.name === call.name);
|
||||
let output: string;
|
||||
let isError = false;
|
||||
try {
|
||||
if (!binding) throw new Error(`Unknown tool "${call.name}"`);
|
||||
hooks.onTool?.(`${binding.serverName}: ${binding.toolName}`);
|
||||
output = await binding.call(call.input, opts.signal);
|
||||
} catch (err) {
|
||||
if (opts.signal?.aborted) throw new AIError('aborted', 'Cancelled.');
|
||||
isError = true;
|
||||
output = JSON.stringify({ error: err instanceof Error ? err.message : 'Tool failed' });
|
||||
}
|
||||
if (output.length > 24_000) output = `${output.slice(0, 24_000)}… [truncated]`;
|
||||
results.push({ type: 'tool_result', toolCallId: call.id, name: call.name, output, isError });
|
||||
}
|
||||
messages.push(res.message, { role: 'user', content: results });
|
||||
}
|
||||
}
|
||||
|
||||
export interface StructuredOptions extends Omit<ChatOptions, 'tools' | 'toolChoice' | 'jsonMode'> {
|
||||
/** Name + description of the "function" whose arguments are the result. */
|
||||
toolName: string;
|
||||
toolDescription: string;
|
||||
schema: Record<string, unknown>;
|
||||
/** Offer the MCP tools allowed in this area before the structured answer. */
|
||||
mcpArea?: McpArea;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -602,7 +652,8 @@ export async function generateStructured(app: AppContext, opts: StructuredOption
|
|||
};
|
||||
if (!resolved.model.capabilities.tools) return promptJson();
|
||||
try {
|
||||
const res = await runChat(app, { ...opts, tools: [tool], toolChoice: { name: opts.toolName } });
|
||||
const chatOpts: ChatOptions = { ...opts, tools: [tool], toolChoice: { name: opts.toolName } };
|
||||
const res = opts.mcpArea ? await runChatWithMcp(app, chatOpts, opts.mcpArea) : await runChat(app, chatOpts);
|
||||
const call = res.message.content.find((p) => p.type === 'tool_call');
|
||||
if (call && call.type === 'tool_call') return { data: call.input, usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
if (res.text.trim()) return { data: parseLooseJson(res.text), usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue