Fourth revision: OpenRouter, live tool stages, Explain layout, share sections
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s

- Interactive blocks are encouraged by default; Explain gets a reduced library
  and never writes practice questions.
- Assistant tool steps breathe while running, show live stages from generation
  and the Python check, and read in the past tense when done.
- The assistant asks before searching the web when class materials do not
  cover a question; clarifying questions list every class's exams and never
  ask about format (always NCLEX).
- Explain opens beside the question from 900px wide, moving the question left
  while open and back on the next one.
- Generate dialog drops the practice set/exam switch (presets cover it) and the
  Generate buttons lose their icon.
- Python check notes are green when every check passed, applied fixes neutral.
- Share pages group by exam, then Quizzes, Flashcards, Notes, Class Materials,
  hiding empty groups; the class page uses the same order. "Documents" is now
  "Class Materials".
- OpenRouter provider replaces the Ollama type; migration 6 turns Ollama
  connections into OpenAI-compatible ones at /v1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 21:54:39 -07:00
parent c595e0ff2c
commit 25bc03ea75
45 changed files with 663 additions and 329 deletions

View file

@ -151,9 +151,10 @@ const TABLES: Record<ProviderKind, Record<string, Entry>> = {
anthropic: ANTHROPIC,
gemini: GEMINI,
deepseek: DEEPSEEK,
// Aggregators and local servers host arbitrary models at their own prices.
// Aggregators and local servers host arbitrary models at their own prices (OpenRouter
// reports them in its model list).
openrouter: {},
openai_compatible: {},
ollama: {},
};
/**
@ -230,7 +231,8 @@ export function catalogModelIds(kind: ProviderKind): string[] {
* fraction of the normal input price. These are the providers' published discounts for
* their current models: OpenAI GPT-5 and later, Claude cache reads and Gemini 2.5 and later
* all bill cached input at 10%. Older OpenAI models (GPT-4.1 25%, GPT-4o / o-series 50%)
* discount less. Servers behind the compatible adapter and Ollama have no known discount.
* discount less. OpenRouter reports each model's cache-read price itself; servers behind the
* compatible adapter have no known discount.
*/
export function cachedInputRatio(kind: ProviderKind, modelId: string): number {
const id = modelId.slice(modelId.lastIndexOf('/') + 1);

View file

@ -43,7 +43,7 @@ function clip(text: string, max = 800): string {
/* ------------------------------------------------------------------ */
export interface ErrorContext {
/** Human provider label used in messages ("OpenAI", "Ollama"). */
/** Human provider label used in messages ("OpenAI", "OpenRouter"). */
provider: string;
/** Values that must never appear in an error (API key, custom header values). */
secrets?: Array<string | null | undefined>;

View file

@ -2,17 +2,17 @@ import { AIError, type ProviderAdapter, type ProviderKind } from '../types.ts';
import { anthropicAdapter } from './anthropic.ts';
import { deepseekAdapter } from './deepseek.ts';
import { geminiAdapter } from './gemini.ts';
import { ollamaAdapter } from './ollama.ts';
import { openaiAdapter } from './openai.ts';
import { openaiCompatibleAdapter } from './openaiCompatible.ts';
import { openrouterAdapter } from './openrouter.ts';
const ADAPTERS: Record<ProviderKind, ProviderAdapter> = {
openai: openaiAdapter,
anthropic: anthropicAdapter,
gemini: geminiAdapter,
deepseek: deepseekAdapter,
openrouter: openrouterAdapter,
openai_compatible: openaiCompatibleAdapter,
ollama: ollamaAdapter,
};
export function getAdapter(kind: ProviderKind): ProviderAdapter {

View file

@ -1,104 +0,0 @@
/**
* Ollama (local models). Chat goes through Ollama's OpenAI-compatible endpoint
* (`{base}/v1/chat/completions`), which handles tools and streaming; discovery
* uses the native API because it reports what each model can do:
* GET /api/tags -> installed models
* POST /api/show -> { capabilities: ["completion","tools","vision","thinking"], model_info }
* https://docs.ollama.com/api · https://docs.ollama.com/openai
*/
import { AIError, type DiscoveredModel, type ModelCapabilities, type ProviderAdapter, type ProviderConfig, type TestResult } from '../types.ts';
import { num, runTest, str, TEST_TIMEOUT_MS } from './common.ts';
import { isRecord, requestJson, trimBaseUrl, type ErrorContext } from './http.ts';
import { compatEmbed, streamChatCompletions, type CompatOptions } from './openaiCompatible.ts';
const LABEL = 'Ollama';
const DEFAULT_BASE_URL = 'http://localhost:11434';
function root(cfg: ProviderConfig): string {
return trimBaseUrl(cfg.baseUrl || DEFAULT_BASE_URL).replace(/\/(v1|api)$/, '');
}
function ctx(cfg: ProviderConfig): ErrorContext {
return { provider: LABEL, secrets: [cfg.apiKey, ...Object.values(cfg.headers ?? {})] };
}
function headers(cfg: ProviderConfig): Record<string, string> {
const h: Record<string, string> = { ...cfg.headers };
if (cfg.apiKey) h.Authorization = `Bearer ${cfg.apiKey}`; // only needed behind an authenticating proxy
return h;
}
function compat(cfg: ProviderConfig): CompatOptions {
return { kind: 'ollama', label: LABEL, baseUrl: `${root(cfg)}/v1`, apiKey: cfg.apiKey, headers: cfg.headers };
}
async function listModels(cfg: ProviderConfig, signal?: AbortSignal, timeoutMs?: number): Promise<DiscoveredModel[]> {
let tags: unknown;
try {
tags = await requestJson(`${root(cfg)}/api/tags`, { ...ctx(cfg), headers: headers(cfg), signal, firstByteTimeoutMs: timeoutMs ?? 15_000, totalTimeoutMs: timeoutMs ?? 30_000 });
} catch (err) {
if (err instanceof AIError && err.code === 'network') {
throw new AIError('network', `Could not reach Ollama at ${root(cfg)}. Is it running, and reachable from the Study Desk container?`, { retryable: true });
}
throw err;
}
const list = isRecord(tags) && Array.isArray(tags.models) ? tags.models.filter(isRecord) : [];
const models: DiscoveredModel[] = [];
// /api/show is one cheap local call per model; cap it so a huge library cannot stall the settings page.
await Promise.all(
list.slice(0, 60).map(async (m) => {
const id = str(m.model) || str(m.name);
if (!id) return;
const model: DiscoveredModel = { id, label: str(m.name) || id, priceIn: 0, priceOut: 0 };
try {
const show = await requestJson<Record<string, unknown>>(`${root(cfg)}/api/show`, {
...ctx(cfg),
headers: headers(cfg),
body: { model: id },
signal,
firstByteTimeoutMs: 10_000,
totalTimeoutMs: 10_000,
});
if (Array.isArray(show.capabilities)) {
const caps = show.capabilities.map(String);
if (!caps.includes('completion')) return; // embedding-only model
const c: Partial<ModelCapabilities> = { tools: caps.includes('tools'), vision: caps.includes('vision'), reasoning: caps.includes('thinking'), pdf: false, temperature: true };
model.capabilities = c;
}
if (isRecord(show.model_info)) {
const key = Object.keys(show.model_info).find((k) => k.endsWith('.context_length'));
if (key && num(show.model_info[key])) model.contextWindow = num(show.model_info[key]);
}
} catch {
/* older Ollama versions: keep the model with unknown capabilities */
}
models.push(model);
}),
);
return models.sort((a, b) => a.id.localeCompare(b.id));
}
async function test(cfg: ProviderConfig): Promise<TestResult> {
return runTest(LABEL, async () => {
const count = (await listModels(cfg, undefined, TEST_TIMEOUT_MS)).length;
return count === 0 ? { modelCount: 0, note: 'Connected to Ollama, but no models are installed. Run `ollama pull <model>` first.' } : { modelCount: count };
});
}
export const ollamaAdapter: ProviderAdapter = {
kind: 'ollama',
meta: {
label: LABEL,
defaultBaseUrl: DEFAULT_BASE_URL,
requiresApiKey: false,
requiresBaseUrl: false,
supportsDiscovery: true,
docsUrl: 'https://docs.ollama.com',
keyHint: 'Not needed',
},
stream: (cfg, req) => streamChatCompletions(compat(cfg), req),
listModels: (cfg, signal) => listModels(cfg, signal),
// Ollama serves OpenAI-style embeddings at /v1/embeddings (e.g. nomic-embed-text).
embed: (cfg, req) => compatEmbed(compat(cfg), req),
test,
};

View file

@ -1,7 +1,7 @@
/**
* Generic Chat Completions (`POST {base}/chat/completions`) for OpenRouter, Groq,
* Together, LM Studio, vLLM, llama.cpp and friends, and the engine behind the
* Ollama adapter.
* Generic Chat Completions (`POST {base}/chat/completions`) for Groq, Together, LM Studio,
* vLLM, llama.cpp, Ollama and friends, and the engine behind the DeepSeek and OpenRouter
* adapters.
*
* These servers agree on the basics and disagree on everything else, so this
* adapter is deliberately forgiving:
@ -358,6 +358,8 @@ export async function listCompatModels(o: CompatOptions, signal?: AbortSignal, t
const pout = Number(m.pricing.completion);
if (Number.isFinite(pin) && pin >= 0) model.priceIn = Math.round(pin * 1e9) / 1e3;
if (Number.isFinite(pout) && pout >= 0) model.priceOut = Math.round(pout * 1e9) / 1e3;
const pcache = Number(m.pricing.input_cache_read);
if (m.pricing.input_cache_read !== undefined && Number.isFinite(pcache) && pcache >= 0) model.priceCachedIn = Math.round(pcache * 1e9) / 1e3;
}
const caps: Partial<ModelCapabilities> = {};
if (Array.isArray(m.supported_parameters)) {
@ -373,7 +375,7 @@ export async function listCompatModels(o: CompatOptions, signal?: AbortSignal, t
return withCatalogDefaults(o.kind, found);
}
/** OpenAI-style `/embeddings`, shared with Ollama's compatible endpoint. */
/** OpenAI-style `/embeddings` (OpenAI-compatible servers, Ollama's included). */
export async function compatEmbed(o: CompatOptions, req: EmbedRequest): Promise<EmbedResult> {
const body: Record<string, unknown> = { model: req.model, input: req.inputs, encoding_format: 'float' };
if (req.dimensions && /text-embedding-3/.test(req.model)) body.dimensions = req.dimensions;

View file

@ -0,0 +1,81 @@
/**
* OpenRouter — one key for models from many labs, over Chat Completions at
* https://openrouter.ai/api/v1.
* https://openrouter.ai/docs/api/reference/overview · https://openrouter.ai/docs/guides/best-practices/reasoning-tokens
*
* The wire format is OpenAI-compatible, so this reuses the compatible engine with what
* OpenRouter does differently:
* - Reasoning is controlled with `reasoning: { effort }` (xhigh, high, medium, low, minimal)
* instead of `reasoning_effort`, and streams back as `delta.reasoning`.
* - `/models` is public and rich: context length, top provider output limit, per-token prices
* (including cache reads), supported parameters and input modalities.
* - `/key` describes the API key, which is how a test proves the key works (the model list
* would answer without one).
* - `X-Title` names the app in the user's OpenRouter activity log.
*/
import { AIError, type DiscoveredModel, type ProviderAdapter, type ProviderConfig, type TestResult } from '../types.ts';
import { runTest, TEST_TIMEOUT_MS } from './common.ts';
import { isRecord, requestJson, trimBaseUrl } from './http.ts';
import { listCompatModels, streamChatCompletions, type CompatOptions } from './openaiCompatible.ts';
export const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';
const LABEL = 'OpenRouter';
function base(cfg: ProviderConfig): string {
return trimBaseUrl(cfg.baseUrl?.trim() || OPENROUTER_BASE_URL);
}
function options(cfg: ProviderConfig): CompatOptions {
if (!cfg.apiKey) throw new AIError('not_configured', `Add your OpenRouter API key for "${cfg.name}" in Settings.`);
return {
kind: 'openrouter',
label: cfg.name || LABEL,
baseUrl: base(cfg),
apiKey: cfg.apiKey,
headers: { 'X-Title': 'Study Desk', ...cfg.headers },
adjustBody: (body) => {
// OpenRouter's unified reasoning switch.
if (typeof body.reasoning_effort === 'string') {
body.reasoning = { effort: body.reasoning_effort };
delete body.reasoning_effort;
}
},
};
}
async function listModels(cfg: ProviderConfig, signal?: AbortSignal, timeoutMs?: number): Promise<DiscoveredModel[]> {
return listCompatModels(options(cfg), signal, timeoutMs);
}
async function test(cfg: ProviderConfig): Promise<TestResult> {
return runTest(cfg.name || LABEL, async () => {
const o = options(cfg);
const key = await requestJson(`${base(cfg)}/key`, {
provider: o.label,
secrets: [o.apiKey, ...Object.values(o.headers ?? {})],
headers: { ...o.headers, Authorization: `Bearer ${o.apiKey}` },
firstByteTimeoutMs: TEST_TIMEOUT_MS,
totalTimeoutMs: TEST_TIMEOUT_MS,
});
const data = isRecord(key) && isRecord(key.data) ? key.data : {};
const models = (await listModels(cfg, undefined, TEST_TIMEOUT_MS)).length;
const remaining = typeof data.limit_remaining === 'number' ? data.limit_remaining : null;
return { modelCount: models, ...(remaining !== null && remaining <= 0 ? { note: 'Connected, but this key has no credit left. Add credit on openrouter.ai to use paid models.' } : {}) };
});
}
export const openrouterAdapter: ProviderAdapter = {
kind: 'openrouter',
meta: {
label: LABEL,
defaultBaseUrl: OPENROUTER_BASE_URL,
requiresApiKey: true,
requiresBaseUrl: false,
supportsDiscovery: true,
docsUrl: 'https://openrouter.ai/settings/keys',
keyHint: 'Starts with sk-or-',
},
stream: (cfg, req) => streamChatCompletions(options(cfg), req),
listModels: (cfg, signal) => listModels(cfg, signal),
test,
};

View file

@ -11,7 +11,7 @@ import { nearestEffort } from './common.ts';
import { deepseekAdapter } from './deepseek.ts';
import { toGeminiSchema, geminiAdapter } from './gemini.ts';
import { parseSSE } from './http.ts';
import { ollamaAdapter } from './ollama.ts';
import { openrouterAdapter } from './openrouter.ts';
import { openaiAdapter } from './openai.ts';
import { normalizeCompatBase, openaiCompatibleAdapter } from './openaiCompatible.ts';
@ -368,16 +368,16 @@ const compatKit = chatCompletionsKit({
model: 'meta/llama-3',
streamUrl: 'https://router.example.com/api/v1/chat/completions',
});
const ollamaKit = chatCompletionsKit({
name: 'ollama',
adapter: ollamaAdapter,
key: 'ollama-proxy-secret-1234',
cfg: cfgOf('ollama', 'ollama-proxy-secret-1234'),
model: 'llama3',
streamUrl: 'http://localhost:11434/v1/chat/completions',
const openrouterKit = chatCompletionsKit({
name: 'openrouter',
adapter: openrouterAdapter,
key: 'sk-or-v1-TESTKEY-0987654321',
cfg: cfgOf('openrouter', 'sk-or-v1-TESTKEY-0987654321'),
model: 'meta-llama/llama-4-maverick',
streamUrl: 'https://openrouter.ai/api/v1/chat/completions',
});
const kits = [anthropicKit, openaiKit, geminiKit, compatKit, ollamaKit];
const kits = [anthropicKit, openaiKit, geminiKit, compatKit, openrouterKit];
/* ------------------------------------------------------------------ */
/* Shared behaviour across all five adapters */
@ -728,7 +728,7 @@ describe('toGeminiSchema', () => {
});
/* ------------------------------------------------------------------ */
/* OpenAI-compatible and Ollama specifics */
/* OpenAI-compatible specifics */
/* ------------------------------------------------------------------ */
describe('openai-compatible stream_options fallback', () => {
@ -930,46 +930,57 @@ describe('openai-compatible listModels', () => {
});
});
describe('ollama listModels', () => {
it('uses /api/tags + /api/show, drops embedding-only models and keeps models whose /show fails', async () => {
stubFetch((c) => {
if (c.url.endsWith('/api/tags')) {
return jsonResponse({
models: [
{ name: 'old:1b', model: 'old:1b' },
{ name: 'nomic-embed-text:latest', model: 'nomic-embed-text:latest' },
{ name: 'llama3:latest', model: 'llama3:latest' },
],
});
}
if (c.url.endsWith('/api/show')) {
if (c.body.model === 'llama3:latest') return jsonResponse({ capabilities: ['completion', 'tools'], model_info: { 'llama.context_length': 8192 } });
if (c.body.model === 'nomic-embed-text:latest') return jsonResponse({ capabilities: ['embedding'] });
return jsonResponse({ error: 'unsupported' }, 404);
}
return new Response('?', { status: 404 });
});
const models = await ollamaAdapter.listModels(ollamaKit.cfg);
expect(calls[0]!.url).toBe('http://localhost:11434/api/tags');
expect(calls.filter((c) => c.url.endsWith('/api/show')).map((c) => c.method)).toEqual(['POST', 'POST', 'POST']);
ollamaKit.assertAuth(calls[0]!.headers);
expect(models).toEqual([
{
id: 'llama3:latest',
label: 'llama3:latest',
priceIn: 0,
priceOut: 0,
contextWindow: 8192,
capabilities: { tools: true, vision: false, reasoning: false, pdf: false, temperature: true },
},
{ id: 'old:1b', label: 'old:1b', priceIn: 0, priceOut: 0 },
]);
describe('openrouter adapter', () => {
it('sends reasoning as reasoning.effort, names the app and uses the default endpoint', async () => {
stubFetch(queue(() => sseResponse(compatKit.text(['ok']))));
await run(openrouterAdapter, openrouterKit.cfg, { model: 'deepseek/deepseek-v4-flash', messages: [user('hi')], reasoningEffort: 'high', capabilities: { reasoning: true } });
expect(calls[0]!.url).toBe('https://openrouter.ai/api/v1/chat/completions');
expect(calls[0]!.headers['X-Title']).toBe('Study Desk');
expect(calls[0]!.body.reasoning).toEqual({ effort: 'high' });
expect(calls[0]!.body.reasoning_effort).toBeUndefined();
});
it('strips /v1 from a configured base URL', async () => {
stubFetch(queue(() => jsonResponse({ models: [] })));
await ollamaAdapter.listModels({ ...ollamaKit.cfg, baseUrl: 'http://box:11434/v1/' });
expect(calls[0]!.url).toBe('http://box:11434/api/tags');
it('sends no reasoning settings when the effort is "none"', async () => {
stubFetch(queue(() => sseResponse(compatKit.text(['ok']))));
await run(openrouterAdapter, openrouterKit.cfg, { model: 'x/y', messages: [user('hi')], reasoningEffort: 'none', capabilities: { reasoning: true } });
expect(calls[0]!.body.reasoning).toBeUndefined();
expect(calls[0]!.body.reasoning_effort).toBeUndefined();
});
it('reads context, output limit, prices (with cache reads), tools and vision from /models', async () => {
stubFetch(
queue(() =>
jsonResponse({
data: [
{
id: 'anthropic/claude-sonnet-5-5',
name: 'Anthropic: Claude Sonnet 5.5',
context_length: 1_000_000,
top_provider: { max_completion_tokens: 64_000 },
pricing: { prompt: '0.000003', completion: '0.000015', input_cache_read: '0.0000003' },
supported_parameters: ['tools', 'reasoning', 'max_tokens'],
architecture: { input_modalities: ['text', 'image', 'file'] },
},
{ id: 'openai/text-embedding-3-small', name: 'Embedding', pricing: { prompt: '0.00000002', completion: '0' } },
],
}),
),
);
const models = await openrouterAdapter.listModels(openrouterKit.cfg);
expect(calls[0]!.url).toBe('https://openrouter.ai/api/v1/models');
expect(models).toHaveLength(1);
expect(models[0]).toMatchObject({ id: 'anthropic/claude-sonnet-5-5', label: 'Anthropic: Claude Sonnet 5.5', contextWindow: 1_000_000, maxOutput: 64_000, priceIn: 3, priceOut: 15, priceCachedIn: 0.3 });
expect(models[0]!.capabilities).toMatchObject({ tools: true, reasoning: true, vision: true });
});
it('tests the key with /key before counting models, and needs a key', async () => {
stubFetch((c) => (c.url.endsWith('/key') ? jsonResponse({ data: { label: 'sk-or-v1-abc...', limit_remaining: 4.2 } }) : jsonResponse({ data: [{ id: 'a/b' }, { id: 'c/d' }] })));
const result = await openrouterAdapter.test(openrouterKit.cfg);
expect(calls.map((c) => c.url)).toEqual(['https://openrouter.ai/api/v1/key', 'https://openrouter.ai/api/v1/models']);
expect(calls[0]!.headers.Authorization).toBe(`Bearer ${openrouterKit.key}`);
expect(result).toMatchObject({ ok: true, modelCount: 2 });
const missing = await failure(openrouterAdapter.listModels({ ...openrouterKit.cfg, apiKey: null }));
expect(missing.code).toBe('not_configured');
});
});
@ -1012,7 +1023,7 @@ describe('lookupModelDefaults', () => {
it('returns {} for unknown models and for kinds without a table', () => {
expect(lookupModelDefaults('openai', 'totally-unknown-model')).toEqual({});
expect(lookupModelDefaults('anthropic', '')).toEqual({});
expect(lookupModelDefaults('ollama', 'llama3')).toEqual({});
expect(lookupModelDefaults('openrouter', 'meta-llama/llama-4-maverick')).toEqual({});
});
it('borrows capabilities but not prices or temperature for router ids', () => {
const d = lookupModelDefaults('openai_compatible', 'anthropic/claude-sonnet-5-5');