Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
- Built-in Parallel web search (keyless; optional sign-in for higher limits and research) with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any MCP server, with token refresh and pre-registered client support - Friendly tool steps (icon, name, status; details on click) and ids stripped from results; per-chat tool switches; taller thinking box - Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only material for generation; class setting for what the groups are called - Assistant can ask clarifying questions in an inline form before generating - OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats - Explain beside the quiz on wide screens, grounded in the cited source pages - Quiz results: percentage ring coloured by score band, rainbow at 100 - Share links: assistant button like the owner's, hidden during quizzes; documents readable in the browser - Live draft and library updates over server-sent events Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
60cf2322f7
commit
c595e0ff2c
54 changed files with 4710 additions and 387 deletions
|
|
@ -21,7 +21,9 @@ import { dueCounts } from '../services/srs.ts';
|
|||
import { topicStats, totals } from '../services/stats.ts';
|
||||
import { newId, now, parseJson } from '../util.ts';
|
||||
import { cancelGeneration, createDraft, getDraft, startGeneration, startImprove } from './generate.ts';
|
||||
import { loadMcpTools, mcpPromptNote } from './mcp.ts';
|
||||
import { clipOutput, mcpActivity, type ToolActivity } from './activity.ts';
|
||||
import { genUiPrompt } from './genui.ts';
|
||||
import { loadMcpTools, mcpPromptNote, type WebSource } from './mcp.ts';
|
||||
import { runPython } from './sandbox.ts';
|
||||
import { resolveModel, runChat } from './service.ts';
|
||||
import { pythonOutput, pythonPrelude, quizForPython, RUN_PYTHON_DESCRIPTION } from './verify.ts';
|
||||
|
|
@ -33,16 +35,24 @@ export type UiItem =
|
|||
| { type: 'draft'; draftId: string; kind: 'quiz' | 'deck' | 'note'; title: string; count: number; status: string }
|
||||
| { type: 'action'; actionId: string; summary: string; changes: string[]; status: 'pending' | 'confirmed' | 'cancelled' | 'failed'; result?: string }
|
||||
| { type: 'sources'; items: { ref: string; chunkId: number; documentId: string; label: string }[] }
|
||||
| { type: 'link'; kind: 'quiz' | 'deck' | 'note' | 'document' | 'class' | 'attempt'; id: string; title: string };
|
||||
| { type: 'link'; kind: 'quiz' | 'deck' | 'note' | 'document' | 'class' | 'attempt'; id: string; title: string }
|
||||
/** Clarifying questions shown as an inline form; the user's answers arrive as the next message. */
|
||||
| { type: 'questions'; id: string; intro?: string; questions: AskQuestion[] };
|
||||
|
||||
export interface ToolActivity {
|
||||
export interface AskQuestion {
|
||||
id: string;
|
||||
name: string;
|
||||
label: string;
|
||||
status: 'running' | 'done' | 'error';
|
||||
summary?: string;
|
||||
question: string;
|
||||
/** 'choice' shows options (one or several), 'text' and 'number' a field. Choices also take a typed answer. */
|
||||
input: 'choice' | 'text' | 'number';
|
||||
options?: { label: string; description?: string }[];
|
||||
multi?: boolean;
|
||||
/** Labels pre-selected (choice) or the prefilled value (text, number). */
|
||||
defaults?: string[];
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export type { ToolActivity } from './activity.ts';
|
||||
|
||||
export type AssistantEvent =
|
||||
| { type: 'start'; conversationId: string; model: string }
|
||||
| { type: 'text'; delta: string }
|
||||
|
|
@ -56,6 +66,8 @@ export type AssistantEvent =
|
|||
|
||||
export interface AssistantContext {
|
||||
classId?: string | null;
|
||||
/** The exam (folder) of that class the user is viewing. */
|
||||
folderId?: string | null;
|
||||
documentIds?: string[];
|
||||
/** Materials the user tagged with @ in this message. */
|
||||
items?: TaggedItem[];
|
||||
|
|
@ -73,6 +85,9 @@ interface ToolRun {
|
|||
output: unknown;
|
||||
summary?: string;
|
||||
ui?: UiItem[];
|
||||
sources?: WebSource[];
|
||||
/** The turn ends after this step: the model waits for the user (ask_user). */
|
||||
endTurn?: boolean;
|
||||
}
|
||||
|
||||
interface ToolSpec {
|
||||
|
|
@ -99,6 +114,19 @@ function classIdOr(env: ToolEnv, given: unknown): string | undefined {
|
|||
return (typeof given === 'string' && given) || env.context.classId || undefined;
|
||||
}
|
||||
|
||||
/** The exam (folder) to work in: the one named, else the one in view when it belongs to the class. */
|
||||
function examIdOr(env: ToolEnv, classGiven: unknown, given: unknown): string | undefined {
|
||||
const classId = classIdOr(env, classGiven);
|
||||
const id = (typeof given === 'string' && given) || env.context.folderId || undefined;
|
||||
if (!id || !classId) return undefined;
|
||||
const folder = env.app.db.get<{ class_id: string }>('SELECT class_id FROM folders WHERE id = ?', id);
|
||||
if (!folder) {
|
||||
if (typeof given === 'string' && given) throw badRequest(`No exam with id ${given}. Use the exam ids listed in the system prompt or list_materials.`);
|
||||
return undefined;
|
||||
}
|
||||
return folder.class_id === classId ? id : undefined;
|
||||
}
|
||||
|
||||
function requireClass(env: ToolEnv, given: unknown): string {
|
||||
const id = classIdOr(env, given);
|
||||
if (!id) throw badRequest('class_id is required. Call list_classes to find it, or ask the user which class to use.');
|
||||
|
|
@ -177,6 +205,7 @@ const TOOLS: ToolSpec[] = [
|
|||
query: { ...S, description: 'Keywords to look for.' },
|
||||
class_id: { ...S, description: 'Limit to one class. Defaults to the current class.' },
|
||||
document_ids: { type: 'array', items: S, description: 'Limit to specific documents.' },
|
||||
exam_id: { ...S, description: 'Limit to one exam (folder) of the class.' },
|
||||
limit: { type: 'integer', description: 'Number of excerpts, 1-12. Default 6.' },
|
||||
},
|
||||
['query'],
|
||||
|
|
@ -184,7 +213,9 @@ const TOOLS: ToolSpec[] = [
|
|||
},
|
||||
label: (i) => `Searching documents for "${clip(String(i.query ?? ''), 50)}"`,
|
||||
run: async (input, env) => {
|
||||
const docIds = (Array.isArray(input.document_ids) && input.document_ids.length ? input.document_ids : env.context.documentIds) as string[] | undefined;
|
||||
const examId = typeof input.exam_id === 'string' && input.exam_id ? input.exam_id : undefined;
|
||||
const examDocs = examId ? env.app.db.all<{ id: string }>(`SELECT id FROM documents WHERE folder_id = ? AND status = 'ready'`, examId).map((d) => d.id) : [];
|
||||
const docIds = (Array.isArray(input.document_ids) && input.document_ids.length ? input.document_ids : examDocs.length ? examDocs : env.context.documentIds) as string[] | undefined;
|
||||
const scope = docIds?.length ? { documentIds: docIds } : { classId: classIdOr(env, input.class_id) ?? null };
|
||||
const limit = Math.max(1, Math.min(12, Number(input.limit) || 6));
|
||||
const hits = await hybridSearch(env.app, String(input.query ?? ''), scope, limit);
|
||||
|
|
@ -388,7 +419,8 @@ const TOOLS: ToolSpec[] = [
|
|||
difficulty: { type: 'string', enum: ['easy', 'medium', 'hard', 'mixed'] },
|
||||
sata_share: { type: 'number', description: 'Fraction (0-1) of select-all-that-apply questions.' },
|
||||
document_ids: { type: 'array', items: S, description: 'Documents to base the quiz on.' },
|
||||
use_all_class_documents: { type: 'boolean', description: 'Use every document in the class.' },
|
||||
use_all_class_documents: { type: 'boolean', description: 'Use every document in the class, or in the exam when there is an exam_id.' },
|
||||
exam_id: { ...S, description: 'Exam (folder) id: uses only the documents of that exam and saves the draft into it. Defaults to the exam the user is viewing.' },
|
||||
from_weak_areas: { type: 'boolean', description: 'Target the concepts behind the questions the user keeps missing.' },
|
||||
from_deck_id: { ...S, description: 'Convert this flashcard deck into quiz questions.' },
|
||||
instructions: { ...S, description: 'Any extra guidance from the user.' },
|
||||
|
|
@ -401,6 +433,7 @@ const TOOLS: ToolSpec[] = [
|
|||
runGenerate(env, {
|
||||
kind: 'quiz',
|
||||
classId: requireClass(env, input.class_id),
|
||||
folderId: examIdOr(env, input.class_id, input.exam_id),
|
||||
title: input.title || undefined,
|
||||
focus: input.topic || undefined,
|
||||
count: Math.max(1, Math.min(100, Number(input.count) || (input.format === 'exam' ? 50 : 15))),
|
||||
|
|
@ -428,7 +461,8 @@ const TOOLS: ToolSpec[] = [
|
|||
count: { type: 'integer', description: 'Number of cards, 1-200. Default 30.' },
|
||||
card_style: { type: 'string', enum: ['concise', 'detailed', 'medication', 'definition'] },
|
||||
document_ids: { type: 'array', items: S },
|
||||
use_all_class_documents: { type: 'boolean' },
|
||||
use_all_class_documents: { type: 'boolean', description: 'Use every document in the class, or in the exam when there is an exam_id.' },
|
||||
exam_id: { ...S, description: 'Exam (folder) id: uses only the documents of that exam and saves the draft into it. Defaults to the exam the user is viewing.' },
|
||||
from_quiz_id: { ...S, description: 'Convert this quiz into flashcards.' },
|
||||
instructions: S,
|
||||
},
|
||||
|
|
@ -440,6 +474,7 @@ const TOOLS: ToolSpec[] = [
|
|||
runGenerate(env, {
|
||||
kind: 'deck',
|
||||
classId: requireClass(env, input.class_id),
|
||||
folderId: examIdOr(env, input.class_id, input.exam_id),
|
||||
title: input.title || undefined,
|
||||
focus: input.topic || undefined,
|
||||
count: Math.max(1, Math.min(200, Number(input.count) || 30)),
|
||||
|
|
@ -463,7 +498,8 @@ const TOOLS: ToolSpec[] = [
|
|||
format: { type: 'string', enum: ['study_guide', 'summary', 'outline', 'cheat_sheet'] },
|
||||
topic: { ...S, description: 'Optional focus within the material (a chapter, section or concept).' },
|
||||
document_ids: { type: 'array', items: S },
|
||||
use_all_class_documents: { type: 'boolean' },
|
||||
use_all_class_documents: { type: 'boolean', description: 'Use every document in the class, or in the exam when there is an exam_id.' },
|
||||
exam_id: { ...S, description: 'Exam (folder) id: uses only the documents of that exam and saves the draft into it. Defaults to the exam the user is viewing.' },
|
||||
instructions: S,
|
||||
},
|
||||
[],
|
||||
|
|
@ -474,6 +510,7 @@ const TOOLS: ToolSpec[] = [
|
|||
runGenerate(env, {
|
||||
kind: 'note',
|
||||
classId: requireClass(env, input.class_id),
|
||||
folderId: examIdOr(env, input.class_id, input.exam_id),
|
||||
title: input.title || undefined,
|
||||
focus: input.topic || undefined,
|
||||
noteStyle: input.format || 'study_guide',
|
||||
|
|
@ -680,8 +717,75 @@ const TOOLS: ToolSpec[] = [
|
|||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
def: {
|
||||
name: 'ask_user',
|
||||
description:
|
||||
"Ask the user up to 4 short clarifying questions BEFORE doing the work, when a detail that changes the result is missing: which exam or materials to use, how many questions or cards, the difficulty or focus. They appear as a small inline form with your options; your turn ends and the answers arrive as the user's next message. Offer concrete options (the class's exams, its documents by title, sensible counts) with the usual choice first and in `defaults`. Do not ask what the user already said or what is clear from context, ask at most once per request, and do not write the answer in the same turn.",
|
||||
parameters: obj(
|
||||
{
|
||||
intro: { ...S, description: 'Optional: one short sentence shown above the questions.' },
|
||||
questions: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
maxItems: 4,
|
||||
items: obj(
|
||||
{
|
||||
id: { ...S, description: 'Short key, e.g. "exam", "count".' },
|
||||
question: { ...S, description: 'The question, e.g. "Which exam is this for?"' },
|
||||
input: { type: 'string', enum: ['choice', 'text', 'number'], description: 'choice (default when options are given), text or number.' },
|
||||
options: { type: 'array', maxItems: 12, items: obj({ label: S, description: { ...S, description: 'Optional short hint.' } }, ['label']) },
|
||||
multi: { type: 'boolean', description: 'Several options may be chosen (e.g. materials).' },
|
||||
defaults: { type: 'array', items: S, description: 'Option labels selected at first, or the prefilled value.' },
|
||||
placeholder: S,
|
||||
},
|
||||
['question'],
|
||||
),
|
||||
},
|
||||
},
|
||||
['questions'],
|
||||
),
|
||||
},
|
||||
label: () => 'Asking you a few questions',
|
||||
run: (input) => {
|
||||
const parsed = askSchema.parse(input);
|
||||
const questions: AskQuestion[] = parsed.questions.map((q, i) => ({
|
||||
id: q.id || `q${i + 1}`,
|
||||
question: q.question,
|
||||
input: q.options?.length ? (q.input === 'text' || q.input === 'number' ? q.input : 'choice') : q.input === 'number' ? 'number' : 'text',
|
||||
options: q.options?.length ? q.options : undefined,
|
||||
multi: q.multi || undefined,
|
||||
defaults: q.defaults?.length ? q.defaults : undefined,
|
||||
placeholder: q.placeholder || undefined,
|
||||
}));
|
||||
return {
|
||||
output: { status: 'waiting_for_answers', important: "The questions are shown to the user. Stop now and wait: their answers arrive as the next message. Don't guess the answers or start the work." },
|
||||
summary: `${questions.length} question${questions.length === 1 ? '' : 's'}`,
|
||||
ui: [{ type: 'questions', id: newId(), intro: parsed.intro || undefined, questions }],
|
||||
endTurn: true,
|
||||
};
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const askSchema = z.object({
|
||||
intro: z.string().trim().max(300).nullish(),
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().trim().max(40).nullish(),
|
||||
question: z.string().trim().min(1).max(300),
|
||||
input: z.enum(['choice', 'text', 'number']).nullish(),
|
||||
options: z.array(z.object({ label: z.string().trim().min(1).max(160), description: z.string().trim().max(200).nullish().transform((v) => v || undefined) })).max(12).nullish(),
|
||||
multi: z.boolean().nullish(),
|
||||
defaults: z.array(z.string().max(160)).max(12).nullish(),
|
||||
placeholder: z.string().max(120).nullish(),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(4),
|
||||
});
|
||||
|
||||
/* ------------------------------ confirmable changes ------------------------------ */
|
||||
|
||||
const changesSchema = z
|
||||
|
|
@ -903,7 +1007,15 @@ function loadHistory(db: DB, conversationId: string, budgetTokens: number): Chat
|
|||
for (let i = from; i < starts[s]; i += 1) total -= estimateMessageTokens(messages[i].msg);
|
||||
from = starts[s];
|
||||
}
|
||||
return messages.slice(from).map((m) => m.msg);
|
||||
const out: ChatMessage[] = [];
|
||||
for (const m of messages.slice(from)) {
|
||||
const prev = out[out.length - 1];
|
||||
// A turn that ended waiting for the user (ask_user) leaves tool results right before the
|
||||
// user's answer: send them as one user message, which every provider accepts.
|
||||
if (prev && prev.role === 'user' && m.msg.role === 'user' && prev.content.every((p) => p.type === 'tool_result')) out[out.length - 1] = { role: 'user', content: [...prev.content, ...m.msg.content] };
|
||||
else out.push(m.msg);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function systemPrompt(app: AppContext, context: AssistantContext): string {
|
||||
|
|
@ -916,9 +1028,26 @@ function systemPrompt(app: AppContext, context: AssistantContext): string {
|
|||
`Today is ${today}.`,
|
||||
classes.length ? `Their classes:\n${classes.map((c) => `- ${c.name}${c.code ? ` (${c.code})` : ''} — id ${c.id}`).join('\n')}` : 'They have not created any classes yet. Offer to create one with the organize tool when it would help.',
|
||||
];
|
||||
lines.push(
|
||||
"Clarifying questions: when a request to generate a quiz, flashcards or a study guide leaves out something that changes the result (which exam or which materials when the class has several, how many questions or cards), call ask_user once with those questions and concrete options, then stop. Don't ask when the user already said it, when the page in view makes it clear, or when they asked you to just go ahead; then use sensible defaults and say which you used.",
|
||||
);
|
||||
if (context.classId) {
|
||||
const cls = db.get<{ name: string }>('SELECT name FROM classes WHERE id = ?', context.classId);
|
||||
if (cls) lines.push(`The user is currently viewing the class "${cls.name}" (id ${context.classId}). Assume requests are about this class unless they say otherwise.`);
|
||||
const cls = db.get<{ name: string; group_label: string }>('SELECT name, group_label FROM classes WHERE id = ?', context.classId);
|
||||
if (cls) {
|
||||
lines.push(`The user is currently viewing the class "${cls.name}" (id ${context.classId}). Assume requests are about this class unless they say otherwise.`);
|
||||
const label = (cls.group_label || 'Exam').toLowerCase();
|
||||
const exams = db.all<{ id: string; name: string; docs: number }>(
|
||||
`SELECT f.id, f.name, (SELECT COUNT(*) FROM documents d WHERE d.folder_id = f.id AND d.status = 'ready') AS docs FROM folders f WHERE f.class_id = ? ORDER BY f.sort_order, f.created_at LIMIT 30`,
|
||||
context.classId,
|
||||
);
|
||||
if (exams.length) {
|
||||
lines.push(
|
||||
`This class is divided into ${label}s, each with its own documents, quizzes and flashcards:\n${exams.map((e) => `- ${e.name} — exam_id ${e.id} (${e.docs} document${e.docs === 1 ? '' : 's'})`).join('\n')}\nMaterial for one ${label} must come only from that ${label}'s documents: pass its exam_id when generating or searching.`,
|
||||
);
|
||||
}
|
||||
const current = context.folderId ? exams.find((e) => e.id === context.folderId) : undefined;
|
||||
if (current) lines.push(`They are looking at "${current.name}" (exam_id ${current.id}). Use it unless they name another ${label}.`);
|
||||
}
|
||||
}
|
||||
if (context.documentIds?.length) {
|
||||
const docs = db.all<{ id: string; title: string }>(`SELECT id, title FROM documents WHERE id IN (${context.documentIds.map(() => '?').join(',')})`, ...context.documentIds);
|
||||
|
|
@ -952,6 +1081,7 @@ function systemPrompt(app: AppContext, context: AssistantContext): string {
|
|||
- Be concise and concrete. Use Markdown. Teach like a good clinical instructor: explain the why, connect to patient care, and prefer current standard practice.
|
||||
- Talk while you work, like a person would: before a tool call that does real work (generating, checking, searching several places), first say in one short sentence what you are about to do ("I'll write 20 questions from the lecture, then check them with Python."), then call the tool in the same reply. After each step, say briefly what happened before the next one.
|
||||
- After a tool produces a draft or a session link, reply with one or two sentences; the card already shows the details.
|
||||
- Never mention tool names, ids (draft, search, extract or session ids) or raw tool output to the user. The app already shows each step as it happens; just say what you did and what you found.
|
||||
- Use run_python whenever exactness matters: dosage and rate calculations, unit conversions, counting questions, options or correct answers, checking that a quiz meets what was asked for. Quizzes from generate_quiz are already checked this way; when you write questions yourself with create_draft, check the draft with run_python (pass its draft_id) before telling the user it is ready, and fix problems you find.`,
|
||||
);
|
||||
return lines.join('\n\n');
|
||||
|
|
@ -963,11 +1093,14 @@ export const assistantRequestSchema = z.object({
|
|||
context: z
|
||||
.object({
|
||||
classId: z.string().nullish(),
|
||||
folderId: z.string().nullish(),
|
||||
documentIds: z.array(z.string()).max(20).optional(),
|
||||
items: z.array(z.object({ kind: z.enum(TAG_KINDS), id: z.string().max(60) })).max(20).optional(),
|
||||
})
|
||||
.optional(),
|
||||
modelId: z.string().nullish(),
|
||||
/** Tool sources (web search, MCP servers) switched off for this conversation. Saved with it. */
|
||||
toolsOff: z.array(z.string().max(60)).max(40).optional(),
|
||||
});
|
||||
|
||||
/** App paths for linking tagged items in answers (folders have no page of their own). */
|
||||
|
|
@ -1103,16 +1236,20 @@ export async function runAssistantTurn(
|
|||
// Tagged documents join the documents in focus so retrieval and generation use them.
|
||||
const taggedDocs = tags.filter((t) => t.kind === 'document').map((t) => t.id);
|
||||
const documentIds = [...new Set([...(req.context?.documentIds ?? []), ...taggedDocs])];
|
||||
const context: AssistantContext = { classId: req.context?.classId ?? null, documentIds: documentIds.length ? documentIds : undefined, items: tags };
|
||||
const context: AssistantContext = { classId: req.context?.classId ?? null, folderId: req.context?.folderId ?? null, documentIds: documentIds.length ? documentIds : undefined, items: tags };
|
||||
const resolved = resolveModel(app, 'chat', req.modelId);
|
||||
const at = now();
|
||||
|
||||
let conversationId = req.conversationId ?? null;
|
||||
let title = '';
|
||||
let toolsOff: string[] = req.toolsOff ?? [];
|
||||
if (conversationId) {
|
||||
const row = db.get<{ title: string }>('SELECT title FROM conversations WHERE id = ?', conversationId);
|
||||
const row = db.get<{ title: string; settings: string }>('SELECT title, settings FROM conversations WHERE id = ?', conversationId);
|
||||
if (!row) conversationId = null;
|
||||
else title = row.title;
|
||||
else {
|
||||
title = row.title;
|
||||
if (!req.toolsOff) toolsOff = parseJson<{ toolsOff?: string[] }>(row.settings, {}).toolsOff ?? [];
|
||||
}
|
||||
}
|
||||
if (!conversationId) {
|
||||
conversationId = newId();
|
||||
|
|
@ -1123,25 +1260,27 @@ export async function runAssistantTurn(
|
|||
db.run('INSERT INTO messages (conversation_id, role, content, meta, created_at) VALUES (?, ?, ?, ?, ?)', conversationId, role, JSON.stringify(message), JSON.stringify(meta), now());
|
||||
|
||||
save('user', { role: 'user', content: [{ type: 'text', text: req.message }] }, tags.length ? { tags } : {});
|
||||
db.run('UPDATE conversations SET updated_at = ? WHERE id = ?', now(), conversationId);
|
||||
db.run('UPDATE conversations SET updated_at = ?, settings = ? WHERE id = ?', now(), JSON.stringify({ toolsOff }), conversationId);
|
||||
onConversation?.(conversationId);
|
||||
emit({ type: 'start', conversationId, model: resolved.model.label });
|
||||
|
||||
const env: ToolEnv = { app, conversationId, context, signal, modelId: req.modelId };
|
||||
// Tools from the user's MCP servers join the built-in ones for this turn.
|
||||
const mcp = resolved.model.capabilities.tools ? await loadMcpTools(app, 'chat', signal) : { tools: [], servers: [], unavailable: [] };
|
||||
const mcp = resolved.model.capabilities.tools ? await loadMcpTools(app, 'chat', signal, { exclude: toolsOff }) : { tools: [], servers: [], unavailable: [] };
|
||||
const mcpByName = new Map(mcp.tools.map((b) => [b.def.name, b]));
|
||||
const mcpSpecs: ToolSpec[] = mcp.tools.map((b) => ({
|
||||
def: b.def,
|
||||
label: () => `${b.serverName}: ${b.toolName}`,
|
||||
label: (input) => mcpActivity(b, '', input).label,
|
||||
run: async (input, e) => {
|
||||
const text = await b.call(input, e.signal);
|
||||
return { output: text, summary: clip(text.replace(/\s+/g, ' ').trim(), 100) };
|
||||
const result = await b.call(input, e.signal);
|
||||
return { output: result.text, sources: result.sources };
|
||||
},
|
||||
}));
|
||||
const tools = resolved.model.capabilities.tools ? [...TOOLS, ...mcpSpecs] : [];
|
||||
const system =
|
||||
systemPrompt(app, context) +
|
||||
mcpPromptNote(mcp) +
|
||||
genUiPrompt() +
|
||||
(tools.length === 0 ? '\n\nNote: the selected model cannot use tools, so you cannot read the library or create drafts in this conversation. Say so if the user asks for that, and suggest choosing a tool-capable model in Settings.' : '');
|
||||
const window = resolved.model.contextWindow ?? 32_000;
|
||||
const historyBudget = Math.max(6_000, Math.floor(window * 0.6));
|
||||
|
|
@ -1173,10 +1312,14 @@ export async function runAssistantTurn(
|
|||
const activities: ToolActivity[] = [];
|
||||
const ui: UiItem[] = [];
|
||||
const results: ContentPart[] = [];
|
||||
let endTurn = false;
|
||||
|
||||
for (const call of calls) {
|
||||
const spec = tools.find((t) => t.def.name === call.name);
|
||||
const activity: ToolActivity = { id: call.id, name: call.name, label: spec ? spec.label(call.input) : call.name, status: 'running' };
|
||||
const binding = mcpByName.get(call.name);
|
||||
const activity: ToolActivity = binding
|
||||
? mcpActivity(binding, call.id, call.input)
|
||||
: { id: call.id, name: call.name, label: spec ? spec.label(call.input) : call.name, status: 'running', kind: 'tool', input: clip(JSON.stringify(call.input ?? {}, null, 2), 2000) };
|
||||
emit({ type: 'tool', tool: { ...activity } });
|
||||
let output: string;
|
||||
let isError = false;
|
||||
|
|
@ -1186,6 +1329,9 @@ export async function runAssistantTurn(
|
|||
output = typeof run.output === 'string' ? run.output : JSON.stringify(run.output);
|
||||
activity.status = 'done';
|
||||
activity.summary = run.summary;
|
||||
activity.sources = run.sources;
|
||||
activity.output = clipOutput(output);
|
||||
if (run.endTurn) endTurn = true;
|
||||
for (const item of run.ui ?? []) {
|
||||
ui.push(item);
|
||||
emit({ type: 'ui', item });
|
||||
|
|
@ -1212,6 +1358,8 @@ export async function runAssistantTurn(
|
|||
break;
|
||||
}
|
||||
save('user', { role: 'user', content: results }, { toolResults: true });
|
||||
// The model asked the user something: wait for the answers in the next message.
|
||||
if (endTurn) break;
|
||||
}
|
||||
} catch (err) {
|
||||
const ai = err instanceof AIError ? err : null;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue