Fifth revision: share-link AI safety, sturdier generation, cleaner UI
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
- Malformed model JSON is sent back for repair, then retried; a failed job starts over once before it fails. Visitors can dismiss failed sets. - Generated sets get a short distinct name and description; flashcards are atomic and have no hints; standard study shows known/learning counts. - Share links: "In progress" list, finished sets join the normal lists with a "New" tag, plain progress steps, newest exam first. - Share-link AI expires after a week, can be limited to the US or Arizona (DB-IP Lite or Cloudflare headers) and is locked by abuse protection (migration 8). - The assistant never answers from general knowledge; MCP and web search tools load without a manual test. - Plain-text copy, no question count in exam mode, filler text removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d8df5edf30
commit
85d5c9186d
46 changed files with 1242 additions and 283 deletions
|
|
@ -571,7 +571,7 @@ const TOOLS: ToolSpec[] = [
|
|||
['type', 'stem', 'options', 'rationale'],
|
||||
),
|
||||
},
|
||||
cards: { type: 'array', items: obj({ front: S, back: S, hint: S }, ['front', 'back']) },
|
||||
cards: { type: 'array', items: obj({ front: S, back: S }, ['front', 'back']) },
|
||||
content: { ...S, description: 'Markdown body, for kind = note.' },
|
||||
},
|
||||
['kind', 'title'],
|
||||
|
|
@ -1110,8 +1110,8 @@ function systemPrompt(app: AppContext, context: AssistantContext, opts: { web?:
|
|||
- Use tools instead of guessing. To answer questions about their material, search or read the documents first and base the answer on what you find.
|
||||
- Cite document passages inline with the ref id in square brackets right after the claim, exactly as given, e.g. [c42]. Only cite refs that a tool returned in this conversation. ${
|
||||
opts.web
|
||||
? 'If the documents do not cover something, say so and ask whether to search the web (see Web search below) instead of answering from your own knowledge.'
|
||||
: 'If the documents do not cover something, say so, then answer from general knowledge and label it as such.'
|
||||
? 'Never answer factual questions from your own general knowledge. If the documents do not cover something, say so and ask whether to search the web (see Web search below); if the user says no, tell them you do not have information to answer it.'
|
||||
: 'Never answer factual questions from your own general knowledge. If the documents do not cover something, say that you do not have information on it in their class materials.'
|
||||
}
|
||||
- You can browse everything: list_materials and search_library for quizzes, flashcards and notes; get_quiz, get_deck and read_note to open them; search_documents and read_document for uploaded files.
|
||||
- When you mention a specific quiz, deck, note or document, link it with Markdown using the url the tool gave you, for example [Cardiac drug cards](/decks/abc123). Never invent a url.
|
||||
|
|
|
|||
|
|
@ -366,9 +366,8 @@ const CARD_SCHEMA = {
|
|||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
front: { type: 'string', description: 'Prompt side: one specific question or term.' },
|
||||
back: { type: 'string', description: 'Answer side. Markdown allowed.' },
|
||||
hint: { type: 'string', description: 'Optional memory hook or mnemonic. Empty string if none.' },
|
||||
front: { type: 'string', description: 'Prompt side: one specific question about one fact.' },
|
||||
back: { type: 'string', description: 'Only the answer: a word, number or short phrase. No explanation.' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '1-2 short topic tags.' },
|
||||
},
|
||||
required: ['front', 'back'],
|
||||
|
|
@ -402,8 +401,9 @@ ${NUMERIC_RULE}`;
|
|||
|
||||
|
||||
const CARD_RULES: Record<string, string> = {
|
||||
concise: 'Each card tests exactly one fact. Fronts are specific questions or terms; backs are short (a phrase or one or two lines).',
|
||||
detailed: 'Each card covers one concept. Backs may use a short bullet list (up to 5 bullets) for the key points.',
|
||||
concise:
|
||||
`Atomic cards: each card tests exactly one fact, so it can be learned in one look. The front asks one specific question (never "describe" or "explain"). The back is only the answer: a word, a number with its unit, or a short phrase, ideally under 10 words and never more than one short sentence. No explanations, reasons, lists or paragraphs on the back. Split anything with several parts (a drug's class, action and side effects; the signs of a condition) into separate cards.`,
|
||||
detailed: 'Each card covers one concept. The back is at most 3 short bullet points (a few words each), no paragraphs.',
|
||||
medication:
|
||||
'Make medication cards. Front: the generic drug name (with a common brand name in parentheses when well known). Back: a Markdown list with **Class**, **Action**, **Uses**, **Adverse effects** (the most important ones), **Nursing considerations** and **Client teaching**. Only include what the material supports.',
|
||||
definition: 'Make term and definition cards. Front: the term. Back: a precise definition in one or two sentences, plus an example when useful.',
|
||||
|
|
@ -787,7 +787,7 @@ export function startGeneration(
|
|||
const controller = new AbortController();
|
||||
running.set(draftId, controller);
|
||||
if (opts.onProgress) progressListeners.set(draftId, opts.onProgress);
|
||||
const done = runGeneration(app, draftId, req, controller.signal)
|
||||
const done = runWithRestart(app, draftId, req, controller.signal)
|
||||
.catch((err) => {
|
||||
const message = err instanceof AIError ? err.message : err instanceof Error && 'status' in err ? err.message : 'Generation failed unexpectedly.';
|
||||
if (!(err instanceof AIError) && !(err instanceof Error && 'status' in err)) app.log('error', 'Generation failed', err);
|
||||
|
|
@ -824,6 +824,31 @@ function autoSaveDraft(app: AppContext, draftId: string, description: string): v
|
|||
}
|
||||
}
|
||||
|
||||
/** Failures worth starting the whole job over for: bad output and passing provider trouble. */
|
||||
const RESTARTABLE = new Set(['invalid_response', 'server', 'timeout', 'network', 'rate_limit']);
|
||||
|
||||
/**
|
||||
* Runs a generation job, and when it fails on bad model output (or a passing provider error)
|
||||
* starts it over once with the same request. A second failure fails the draft.
|
||||
*/
|
||||
async function runWithRestart(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal): Promise<void> {
|
||||
try {
|
||||
await runGeneration(app, draftId, req, signal);
|
||||
} catch (err) {
|
||||
if (signal.aborted || !(err instanceof AIError) || !RESTARTABLE.has(err.code)) throw err;
|
||||
app.log('warn', 'Generation failed; starting it over once', err.message);
|
||||
const kind = req.kind;
|
||||
app.db.run(
|
||||
`UPDATE drafts SET payload = ?, progress = 0.02, progress_label = 'Starting over', updated_at = ? WHERE id = ? AND status = 'generating'`,
|
||||
JSON.stringify(emptyPayload(kind, req.title ?? '')),
|
||||
now(),
|
||||
draftId,
|
||||
);
|
||||
progressListeners.get(draftId)?.('Starting over');
|
||||
await runGeneration(app, draftId, req, signal);
|
||||
}
|
||||
}
|
||||
|
||||
async function runGeneration(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal): Promise<void> {
|
||||
const { db } = app;
|
||||
const resolved = resolveModel(app, 'generate', req.modelId);
|
||||
|
|
@ -904,7 +929,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
: [
|
||||
`Write ${want} flashcards${req.focus ? ` about: ${req.focus}` : ''}.`,
|
||||
sources.groups.length > 0 ? 'Cover the most testable facts across all of the excerpts.' : '',
|
||||
req.source.quizId ? 'Turn the quiz questions into flashcards: the front asks for the key fact, the back states it with the essential reasoning.' : '',
|
||||
req.source.quizId ? 'Turn the quiz questions into flashcards: the front asks for the key fact, the back states only that fact.' : '',
|
||||
'Do not write hints.',
|
||||
];
|
||||
if (written.length > 0) ask.push(`Already written (do not repeat or closely paraphrase these):\n${written.slice(-80).join('\n')}`);
|
||||
// Med math is standard material: the excerpts would only cost tokens.
|
||||
|
|
@ -1011,6 +1037,16 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
notes.push(...checked.notes);
|
||||
}
|
||||
|
||||
// A short name and description of what this particular set covers.
|
||||
if (!req.title) {
|
||||
setProgress(db, draftId, 0.99, 'Naming the set', draft);
|
||||
const named = await nameSet(app, draft, { classId: req.classId ?? null, modelId: req.modelId, signal, difficulty, math: numericCount() > 0 });
|
||||
if (named) {
|
||||
draft.title = named.title;
|
||||
draft.description = named.description;
|
||||
}
|
||||
}
|
||||
|
||||
db.run(
|
||||
`UPDATE drafts SET status = 'ready', title = ?, payload = ?, meta = ?, progress = 1, progress_label = '', error = '', updated_at = ? WHERE id = ?`,
|
||||
draft.title,
|
||||
|
|
@ -1021,6 +1057,70 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
);
|
||||
}
|
||||
|
||||
const NAME_SCHEMA = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Short, specific name for this set: 2-6 words naming what it covers.' },
|
||||
description: { type: 'string', description: 'One sentence (at most 25 words) saying what the set covers.' },
|
||||
},
|
||||
required: ['title', 'description'],
|
||||
};
|
||||
|
||||
/**
|
||||
* Asks the model for a short, distinctive title and a one-line description of a finished quiz
|
||||
* or flashcard set, different from the class's other titles. Null when naming fails (the
|
||||
* generic title stays).
|
||||
*/
|
||||
export async function nameSet(
|
||||
app: AppContext,
|
||||
draft: QuizDraft | DeckDraft,
|
||||
opts: { classId: string | null; modelId?: string | null; signal?: AbortSignal; difficulty?: string; math?: boolean },
|
||||
): Promise<{ title: string; description: string } | null> {
|
||||
const isQuiz = draft.kind === 'quiz';
|
||||
const taken = opts.classId
|
||||
? app.db.all<{ title: string }>(`SELECT title FROM ${isQuiz ? 'quizzes' : 'decks'} WHERE class_id = ? ORDER BY created_at DESC LIMIT 80`, opts.classId).map((r) => r.title)
|
||||
: [];
|
||||
const lines = isQuiz
|
||||
? (() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const q of draft.questions) counts.set(q.topic || 'General', (counts.get(q.topic || 'General') ?? 0) + 1);
|
||||
const topics = [...counts].sort((a, b) => b[1] - a[1]).map(([t, n]) => `${t} (${n})`).join(', ');
|
||||
return [`A quiz of ${draft.questions.length} questions. Topics: ${topics}.`, ...draft.questions.slice(0, 40).map((q) => `- ${q.stem.replace(/\s+/g, ' ').slice(0, 110)}`)];
|
||||
})()
|
||||
: [`A flashcard set of ${draft.cards.length} cards.`, ...draft.cards.slice(0, 60).map((c) => `- ${c.front.replace(/\s+/g, ' ').slice(0, 90)}`)];
|
||||
try {
|
||||
const result = await generateStructured(app, {
|
||||
task: 'generate',
|
||||
purpose: 'naming a set',
|
||||
modelId: opts.modelId,
|
||||
system: `You name study sets for a nursing student. The title is 2-6 words in title case and names the actual subject matter (for example "Heart Failure and Diuretics" or "Stroke Priorities"). Never use generic words such as Quiz, Flashcards, Practice, NCLEX, Exam, Review or Set, and no dates or numbers of items.${
|
||||
opts.math ? ' The set includes medication math, so the title may mention it.' : ''
|
||||
} The description is one plain sentence on what it covers.`,
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: `${lines.join('\n')}${taken.length ? `\n\nTitles already used in this class (yours must differ from all of them):\n${taken.map((t) => `- ${t}`).join('\n')}` : ''}` }] }],
|
||||
toolName: 'name_set',
|
||||
toolDescription: 'Submit the title and description.',
|
||||
schema: NAME_SCHEMA,
|
||||
maxOutputTokens: 400,
|
||||
signal: opts.signal,
|
||||
});
|
||||
const value = result.data as { title?: unknown; description?: unknown };
|
||||
let title = typeof value.title === 'string' ? value.title.replace(/\s+/g, ' ').replace(/^["'“]+|["'”.]+$/g, '').trim().slice(0, 80) : '';
|
||||
const description = typeof value.description === 'string' ? value.description.replace(/\s+/g, ' ').trim().slice(0, 300) : '';
|
||||
if (!title) return null;
|
||||
const lower = new Set(taken.map((t) => t.toLowerCase()));
|
||||
if (lower.has(title.toLowerCase())) {
|
||||
let n = 2;
|
||||
while (lower.has(`${title} ${n}`.toLowerCase())) n += 1;
|
||||
title = `${title} ${n}`;
|
||||
}
|
||||
return { title, description };
|
||||
} catch (err) {
|
||||
if (opts.signal?.aborted) throw err;
|
||||
app.log('warn', 'Naming a generated set failed; keeping the default title', err instanceof Error ? err.message : err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function generateNote(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal, budgetTokens: number, window: number): Promise<void> {
|
||||
const { db } = app;
|
||||
const resolved = resolveModel(app, 'generate', req.modelId);
|
||||
|
|
|
|||
|
|
@ -27,6 +27,8 @@ export type McpAreas = Record<McpArea, boolean>;
|
|||
export const DEFAULT_MCP_AREAS: McpAreas = { chat: true, explain: true, generate: false, check: false, share: false };
|
||||
const PROTOCOL_VERSION = '2025-06-18';
|
||||
const LIST_TIMEOUT_MS = 10_000;
|
||||
/** A first connection (sign-in refresh, session set-up) can take longer than a warm listing. */
|
||||
const FIRST_LIST_TIMEOUT_MS = 20_000;
|
||||
const CALL_TIMEOUT_MS = 90_000;
|
||||
const TOOLS_TTL_MS = 5 * 60_000;
|
||||
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
|
||||
|
|
@ -742,11 +744,19 @@ export async function loadMcpTools(app: AppContext, area: McpArea, signal?: Abor
|
|||
const lists = await Promise.all(
|
||||
servers.map(async (s) => {
|
||||
try {
|
||||
return { s, tools: await listTools(app, s, anySignal([signal, AbortSignal.timeout(LIST_TIMEOUT_MS)])) };
|
||||
} catch (err) {
|
||||
app.log('warn', `MCP server "${s.name}" is unavailable`, err instanceof Error ? err.message : err);
|
||||
unavailable.push(s.name);
|
||||
return { s, tools: [] as McpTool[] };
|
||||
const warm = sessions.has(s.id);
|
||||
return { s, tools: await listTools(app, s, anySignal([signal, AbortSignal.timeout(warm ? LIST_TIMEOUT_MS : FIRST_LIST_TIMEOUT_MS)])) };
|
||||
} catch (first) {
|
||||
if (signal?.aborted) return { s, tools: [] as McpTool[] };
|
||||
// One more try on a fresh connection before giving up on the server for this turn.
|
||||
try {
|
||||
forget(s.id);
|
||||
return { s, tools: await listTools(app, s, anySignal([signal, AbortSignal.timeout(FIRST_LIST_TIMEOUT_MS)]), true) };
|
||||
} catch (err) {
|
||||
app.log('warn', `MCP server "${s.name}" is unavailable`, err instanceof Error ? err.message : (first instanceof Error ? first.message : err));
|
||||
unavailable.push(s.name);
|
||||
return { s, tools: [] as McpTool[] };
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
|
@ -802,7 +812,7 @@ export function mcpPromptNote(mcp: LoadedMcp, opts: { askBeforeWeb?: boolean } =
|
|||
const others = mcp.servers.filter((s) => s.builtin !== 'web');
|
||||
if (web) {
|
||||
const when = opts.askBeforeWeb
|
||||
? 'Their own documents come first. When the documents do not answer a question, do not answer from your own knowledge and do not search on your own: call ask_user with one choice question, e.g. "Your class materials do not cover this. Should I look it up on the web?" with the options "Search the web" (first, the default) and "Answer from general knowledge", then stop. Search straight away only when the user asked you to search or look something up online, or already said yes to searching in this conversation.'
|
||||
? 'Their own documents come first. When the documents do not answer a question, never answer from your own knowledge and do not search on your own: call ask_user with one choice question, e.g. "Your class materials do not cover this. Should I look it up on the web?" with the options "Search the web" (first, the default) and "No, skip it", then stop. If they choose not to search, say you do not have information to answer it. Search straight away only when the user asked you to search or look something up online, or already said yes to searching in this conversation.'
|
||||
: "Use it for current facts, guidelines, drug information and anything the student's own material does not cover. For questions about their course material, use their documents first.";
|
||||
lines.push(
|
||||
`Web search: you can search the web with web_search and read specific pages with web_fetch${web.research ? ', and answer a hard question in depth with web_research (slower; use it sparingly)' : ''}. ${when}${
|
||||
|
|
@ -823,6 +833,29 @@ export function mcpPromptNote(mcp: LoadedMcp, opts: { askBeforeWeb?: boolean } =
|
|||
}
|
||||
|
||||
/** Connects afresh, lists the tools and records the outcome on the server. */
|
||||
/**
|
||||
* Connects to every enabled server and lists its tools in the background, so the web search and
|
||||
* MCP tools are ready the first time the AI needs them (no manual connection test).
|
||||
*/
|
||||
export function warmMcpServers(app: AppContext): void {
|
||||
if (app.config.env === 'test') return;
|
||||
for (const s of load(app).filter((x) => x.enabled)) {
|
||||
void listTools(app, s, AbortSignal.timeout(FIRST_LIST_TIMEOUT_MS), true).catch((err) => app.log('warn', `MCP server "${s.name}" could not be reached yet`, err instanceof Error ? err.message : err));
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the tool lists warm while the server runs. */
|
||||
export function startMcpWarmup(app: AppContext): () => void {
|
||||
const first = setTimeout(() => warmMcpServers(app), 3_000);
|
||||
const timer = setInterval(() => warmMcpServers(app), TOOLS_TTL_MS - 30_000);
|
||||
first.unref();
|
||||
timer.unref();
|
||||
return () => {
|
||||
clearTimeout(first);
|
||||
clearInterval(timer);
|
||||
};
|
||||
}
|
||||
|
||||
export async function testMcpServer(app: AppContext, id: string): Promise<{ ok: boolean; message: string; tools: { name: string; description: string }[]; latencyMs: number }> {
|
||||
const servers = load(app);
|
||||
const s = servers.find((x) => x.id === id);
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ export function parseToolArguments(raw: unknown, provider: string, toolName: str
|
|||
}
|
||||
throw new AIError('invalid_response', `${provider} produced a tool call for "${toolName}" with arguments that are not valid JSON.`, {
|
||||
providerMessage: text.length > 300 ? `${text.slice(0, 300)}…` : text,
|
||||
rawOutput: text,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -661,21 +661,54 @@ export async function generateStructured(app: AppContext, opts: StructuredOption
|
|||
return { data: parseLooseJson(res.text), usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
};
|
||||
if (!resolved.model.capabilities.tools) return promptJson();
|
||||
try {
|
||||
const chatOpts: ChatOptions = { ...opts, tools: [tool], toolChoice: { name: opts.toolName } };
|
||||
const chatOpts: ChatOptions = { ...opts, tools: [tool], toolChoice: { name: opts.toolName } };
|
||||
const once = async () => {
|
||||
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 (call && call.type === 'tool_call') return { data: call.input as unknown, 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' };
|
||||
if (res.stopReason === 'refusal') throw new AIError('content_filter', 'The model declined this request.');
|
||||
if (res.stopReason === 'max_tokens') throw new AIError('invalid_response', 'The model ran out of output space before finishing. Ask for fewer items at a time, or raise the output limit in Settings.');
|
||||
throw new AIError('invalid_response', 'The model returned nothing usable.', { retryable: true });
|
||||
};
|
||||
try {
|
||||
return await once();
|
||||
} catch (err) {
|
||||
if (err instanceof AIError && err.code === 'unsupported') return promptJson();
|
||||
throw err;
|
||||
if (!(err instanceof AIError) || err.code !== 'invalid_response' || opts.signal?.aborted) throw err;
|
||||
// Malformed output (jsonrepair could not fix it): the model repairs its own JSON when we
|
||||
// have it, otherwise it gets one more try at the same request.
|
||||
if (err.rawOutput) {
|
||||
try {
|
||||
return await repairStructured(app, opts, tool, err.rawOutput);
|
||||
} catch (repairErr) {
|
||||
app.log('warn', `Repairing malformed ${opts.toolName} output failed; asking again`, repairErr instanceof Error ? repairErr.message : repairErr);
|
||||
}
|
||||
}
|
||||
return await once();
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends malformed tool-call arguments back to the model to be rewritten as valid JSON. */
|
||||
async function repairStructured(app: AppContext, opts: StructuredOptions, tool: ToolDef, raw: string) {
|
||||
const res = await runChat(app, {
|
||||
task: opts.task,
|
||||
purpose: `${opts.purpose ?? 'structured output'} (JSON repair)`,
|
||||
modelId: opts.modelId,
|
||||
system: 'You repair malformed JSON. Call the tool once with the same content, corrected so it is valid JSON that matches the tool schema. Keep every item and all of its wording; do not add, drop or rewrite content.',
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: `These arguments for "${tool.name}" are not valid JSON:
|
||||
|
||||
${raw}` }] }],
|
||||
tools: [tool],
|
||||
toolChoice: { name: tool.name },
|
||||
maxOutputTokens: opts.maxOutputTokens,
|
||||
signal: opts.signal,
|
||||
});
|
||||
const call = res.message.content.find((p) => p.type === 'tool_call');
|
||||
if (!call || call.type !== 'tool_call') throw new AIError('invalid_response', 'The repair returned no tool call.');
|
||||
return { data: call.input as unknown, usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
}
|
||||
|
||||
/* ------------------------------ reporting ------------------------------ */
|
||||
|
||||
export function usageSummary(db: DB, days: number) {
|
||||
|
|
|
|||
|
|
@ -184,14 +184,20 @@ export class AIError extends Error {
|
|||
retryable: boolean;
|
||||
/** Raw (already secret-scrubbed) provider message, for the details disclosure in the UI. */
|
||||
providerMessage?: string;
|
||||
/**
|
||||
* The model's unparseable output (tool-call arguments), kept so it can be sent back for
|
||||
* repair. Server-side only: never serialised to a response.
|
||||
*/
|
||||
declare rawOutput?: string;
|
||||
|
||||
constructor(code: AIErrorCode, message: string, opts: { status?: number; retryable?: boolean; providerMessage?: string; cause?: unknown } = {}) {
|
||||
constructor(code: AIErrorCode, message: string, opts: { status?: number; retryable?: boolean; providerMessage?: string; rawOutput?: string; cause?: unknown } = {}) {
|
||||
super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);
|
||||
this.name = 'AIError';
|
||||
this.code = code;
|
||||
this.status = opts.status;
|
||||
this.retryable = opts.retryable ?? (code === 'rate_limit' || code === 'server' || code === 'network' || code === 'timeout');
|
||||
this.providerMessage = opts.providerMessage;
|
||||
if (opts.rawOutput !== undefined) Object.defineProperty(this, 'rawOutput', { value: opts.rawOutput, enumerable: false });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue