Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Assist: Smart, Free and Manual run on any connected provider

Adarshdd9e27ac4d0a
diff --git a/src/app/api/assist/route.ts b/src/app/api/assist/route.ts
index 75c9e927..90a96e19 100644
--- a/src/app/api/assist/route.ts
+++ b/src/app/api/assist/route.ts
@@ -32,7 +32,7 @@ export async function POST(request: Request) {
const r = await resolveMode(mode);
let thread;
try {
- thread = createThread({ engine, autoApprove, agent: r.agent, projectId: projectId ?? null, mode: r.mode, model: r.model, effort: r.effort });
+ thread = createThread({ engine, autoApprove, agent: r.agent, projectId: projectId ?? null, mode: r.mode, provider: r.provider, model: r.model, effort: r.effort });
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: 404 });
}
diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsx
index 158de973..ac719ab8 100644
--- a/src/components/assist-view.tsx
+++ b/src/components/assist-view.tsx
@@ -32,8 +32,9 @@ const STARTER_SKILLS = ["product-photoshoot", "ugc-video", "thumbnail-generation
const AGENT_HINT: Record<AssistThread["agent"], string> = {
claude: "Claude plans the shoot, picks models and runs them with your approval.",
+ hosted: "Runs on a model from a provider you've connected (Settings → AI helper). It plans the shoot, picks models and runs them with your approval.",
local: "Runs on your local model (Ollama, LM Studio or Unsloth Studio). Smaller local models follow instructions less reliably than Claude.",
- offline: "A simple rule-based planner. Add an Anthropic API key, or run a local model (Ollama, LM Studio or Unsloth Studio), for the full assistant that picks models, chains steps and checks results.",
+ offline: "A simple rule-based planner. Add a key in Settings → AI helper (Anthropic, OpenAI, Google, OpenRouter…), or run a local model (Ollama, LM Studio or Unsloth Studio), for the full assistant that picks models, chains steps and checks results.",
};
export function AskFirst({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
diff --git a/src/lib/assist-models.ts b/src/lib/assist-models.ts
index 9530494f..7a39b58b 100644
--- a/src/lib/assist-models.ts
+++ b/src/lib/assist-models.ts
@@ -1,4 +1,4 @@
-import { ASSIST_EFFORTS, type AssistEffort } from "./assist";
+import { ASSIST_EFFORTS, type AssistEffort, type AssistModelOption } from "./assist";
import { KNOWN_LOCAL_MODELS, LLM_PROVIDERS, priceOn, type LlmModelDef, type LlmProviderDef, type PriceStep } from "./catalog/llm-providers";
/**
@@ -53,6 +53,8 @@ export interface World {
today: string;
/** A model that can see checks pictures for a planner that can't (check_generations look). */
checker: boolean;
+ /** Providers whose free requests are used up for now: their free models are skipped. */
+ spent?: string[];
}
export interface Choice {
@@ -122,6 +124,7 @@ function disabledWhy(w: World, p: LlmProviderDef, m: LlmModelDef, conn: Connecte
if (p.freePlan.tooSmall) return p.freePlan.tooSmall;
}
if (p.id === "openrouter" && conn.freeTier && m.free !== "model") return "No credits on OpenRouter yet: only its free models run";
+ if (w.spent?.includes(p.id) && (m.free === "model" || (m.free === "plan" && conn.freeTick))) return `${p.short}'s free requests are used up for now`;
return undefined;
}
@@ -360,6 +363,27 @@ export function priceText(c: Choice): string {
return c.next && c.price.until ? `${now} until ${day(c.price.until)}, then ${money(c.next.in, c.cny)} / ${money(c.next.out, c.cny)}` : now;
}
+/** What the browser gets for a choice: words and flags, never a key or an address. */
+export function toOption(c: Choice): AssistModelOption {
+ const open = openLabel(c);
+ return {
+ provider: c.provider,
+ model: c.model,
+ name: c.name,
+ providerLabel: c.providerLabel,
+ agent: c.agent,
+ price: priceText(c),
+ ...(c.note && { note: c.note }),
+ ...(open && { open }),
+ ...(c.caveat && { caveat: c.caveat }),
+ sees: c.sees,
+ free: c.free,
+ efforts: c.efforts,
+ ...(c.disabled && { disabled: c.disabled }),
+ ...(c.manualOnly && { manualOnly: c.manualOnly }),
+ };
+}
+
/** "Open weights · MIT · runs on DeepSeek's servers"; undefined for a closed (or not confirmed open) model. */
export function openLabel(c: Choice): string | undefined {
if (c.local) return "Open weights · on this machine";
diff --git a/src/lib/assist-schedule.ts b/src/lib/assist-schedule.ts
index db0002c9..313603e7 100644
--- a/src/lib/assist-schedule.ts
+++ b/src/lib/assist-schedule.ts
@@ -41,7 +41,7 @@ export interface ScheduleView {
capUsd: number | null;
engine: "cloud" | "open";
/** The mode choice runs start with (null: the default from Settings). The local agent is "local"; tasks saved before LM Studio and Unsloth Studio support say "ollama" (read as "local"). */
- mode: { mode: "free" | "smart" | "manual"; agent?: "claude" | "local" | "ollama" | "offline"; model?: string | null; effort?: "low" | "medium" | "high" | "xhigh" | "max" | null } | null;
+ mode: { mode: "free" | "smart" | "manual"; agent?: "claude" | "hosted" | "local" | "ollama" | "offline"; provider?: string | null; model?: string | null; effort?: "low" | "medium" | "high" | "xhigh" | "max" | null } | null;
/** Whether runs may use the connectors in Settings (Claude runs only). Their tools run without asking, so it's off unless the task opts in. */
connectors: boolean;
paused: boolean;
diff --git a/src/lib/assist.ts b/src/lib/assist.ts
index 353204d3..227c6f9a 100644
--- a/src/lib/assist.ts
+++ b/src/lib/assist.ts
@@ -6,6 +6,7 @@
* `/name` invocation), Memory (categories, import parsing) and the context the agent is given
* (rendered once per chat, then updated with append-only "Context update" messages).
*/
+import { getLlmModel } from "./catalog/llm-providers";
import type { Engine, Generation, MediaKind, Operation } from "./catalog/types";
/** One job the agent wants to run, priced before the user approves it. */
@@ -50,16 +51,20 @@ export type AssistItem =
export type AssistStatus = "idle" | "running" | "waiting";
-export type AssistAgent = "claude" | "local" | "offline";
+export type AssistAgent = "claude" | "hosted" | "local" | "offline";
/** Chats saved before LM Studio and Unsloth Studio came along call the local model "ollama". */
-export const normalizeAgent = (a: string | null | undefined): AssistAgent | undefined => (a === "ollama" ? "local" : a === "claude" || a === "local" || a === "offline" ? a : undefined);
+export const normalizeAgent = (a: string | null | undefined): AssistAgent | undefined =>
+ a === "ollama" ? "local" : a === "claude" || a === "hosted" || a === "local" || a === "offline" ? a : undefined;
export interface AssistThread {
id: string;
title: string;
status: AssistStatus;
- /** "claude" = Claude; "local" = a local model (Ollama, LM Studio, Unsloth Studio…); "offline" = a rule-based planner (no LLM). */
+ /**
+ * "claude" = Claude; "hosted" = another provider's model on the owner's key (OpenAI, Gemini, DeepSeek, OpenRouter…);
+ * "local" = a local model (Ollama, LM Studio, Unsloth Studio…); "offline" = a rule-based planner (no LLM).
+ */
agent: AssistAgent;
engine: Engine;
/** Run plans without the approval card. */
@@ -71,8 +76,10 @@ export interface AssistThread {
projectId?: string | null;
/** How the LLM was chosen (Free / Smart / Manual). */
mode?: AssistMode;
- /** Claude model id, or the local model's name (null: the default). */
+ /** The model's id at its provider, or the local model's name (null: the default). */
model?: string | null;
+ /** Hosted models: the provider ("openai", "openrouter"…; src/lib/catalog/llm-providers.ts). */
+ provider?: string | null;
effort?: AssistEffort | null;
/** Skills loaded into this chat (by `/name` or by the agent). */
skills?: string[];
@@ -123,8 +130,8 @@ export type AssistMode = "free" | "smart" | "manual";
export type AssistEffort = "low" | "medium" | "high" | "xhigh" | "max";
export const ASSIST_MODES: { id: AssistMode; label: string; hint: string }[] = [
- { id: "smart", label: "Smart", hint: "Claude plans, picks models and checks results" },
- { id: "free", label: "Free", hint: "A local model (Ollama, LM Studio or Unsloth Studio), or the offline planner — no API cost" },
+ { id: "smart", label: "Smart", hint: "The best model you've connected plans, picks models and checks results" },
+ { id: "free", label: "Free", hint: "Free models only (on this machine, OpenRouter's free models, free plans), then the offline planner" },
{ id: "manual", label: "Manual", hint: "Pick the model and how hard it thinks" },
];
@@ -146,14 +153,39 @@ export const CLAUDE_MODELS: { id: string; label: string; hint: string }[] = [
export const DEFAULT_CLAUDE_MODEL = "claude-opus-5-5";
export const DEFAULT_EFFORT: AssistEffort = "medium";
-/** What the composer's mode picker sends. `agent` only matters in Manual mode. */
+/** What the composer's mode picker sends. `agent`, `provider` and `model` only matter in Manual mode. */
export interface AssistModeChoice {
mode: AssistMode;
agent?: AssistAgent;
+ /** Hosted models: the provider of `model`. */
+ provider?: string | null;
model?: string | null;
effort?: AssistEffort | null;
}
+/** A model the mode picker offers (GET /api/assist): words and flags only, never a key or an address. */
+export interface AssistModelOption {
+ provider: string;
+ model: string;
+ name: string;
+ providerLabel: string;
+ agent: "claude" | "hosted" | "local";
+ /** "$2 in, $10 out per million tokens", "Free · 20 a minute, 50 a day". */
+ price: string;
+ note?: string;
+ /** "Open weights · MIT · runs on DeepSeek's servers". */
+ open?: string;
+ caveat?: string;
+ sees: boolean;
+ free: boolean;
+ /** The effort levels it offers. */
+ efforts: AssistEffort[];
+ /** Why it can't be picked now. */
+ disabled?: string;
+ /** Smart and Free never pick it ("Most capable, slowest, priciest"). */
+ manualOnly?: string;
+}
+
/** The local model server behind Free and Manual's local models (Ollama, LM Studio, Unsloth Studio, or another OpenAI-compatible one). */
export interface AssistLocal {
/** "ollama" | "lmstudio" | "unsloth" | "custom"; null: Automatic found none. */
@@ -178,17 +210,37 @@ export interface AssistAvailability {
local: AssistLocal;
/** Settings → AI helper is "none": every chat runs the offline planner. */
aiOff: boolean;
- /** Smart when Claude can run, else Free. */
+ /** Smart when its planner is a paid model, else Free. */
defaultMode: AssistMode;
+ /** The model Smart plans with, the one that checks pictures for a planner that can't, and the sentence that says so. */
+ smart: { plan: AssistModelOption | null; check: AssistModelOption | null; text: string };
+ /** The model Free runs on and the sentence that says so (with its limits). */
+ free: { pick: AssistModelOption | null; text: string; caveat?: string };
+ /** Manual: the connected providers' models, grouped, and the providers without a key. */
+ manual: { groups: { id: string; label: string; status: string; models: AssistModelOption[] }[]; missing: { id: string; label: string }[] };
+ /** Settings → Engine is Open source only: only open-weight models run. */
+ openOnly: boolean;
+ /** The day the model list was last checked against the providers' pages. */
+ checked: string;
}
-export function modeLabel(t: Pick<AssistThread, "mode" | "agent" | "model" | "effort">): string {
+/** "Smart · GPT-6.1 Sol", "Free · Nemotron 3 Ultra", "GPT-6.1 Sol · Medium" (Manual), "Offline planner". */
+export function modeLabel(t: Pick<AssistThread, "mode" | "agent" | "model" | "effort" | "provider">): string {
if (t.agent === "offline") return "Offline planner";
- if (t.agent === "local") return t.model ? `Local · ${t.model}` : "Local LLM";
- const m = CLAUDE_MODELS.find((x) => x.id === (t.model ?? DEFAULT_CLAUDE_MODEL));
const effort = ASSIST_EFFORTS.find((e) => e.id === (t.effort ?? DEFAULT_EFFORT))?.label;
- if (t.mode === "manual") return `${m?.label.replace("Claude ", "") ?? t.model} · ${effort}`;
- return "Smart";
+ let name: string;
+ if (t.agent === "local") {
+ if (t.mode === "manual" || !t.model) return t.model ? `Local · ${t.model}` : "Local LLM";
+ name = t.model;
+ } else if (t.agent === "hosted") {
+ name = getLlmModel(t.provider, t.model)?.name ?? t.model ?? "a hosted model";
+ if (t.mode === "manual") return `${name} · ${effort}`;
+ } else {
+ const m = CLAUDE_MODELS.find((x) => x.id === (t.model ?? DEFAULT_CLAUDE_MODEL));
+ if (t.mode === "manual") return `${m?.label.replace("Claude ", "") ?? t.model} · ${effort}`;
+ name = m?.label ?? "Claude";
+ }
+ return `${t.mode === "free" ? "Free" : "Smart"} · ${name}`;
}
// ---------------------------------------------------------------------------
diff --git a/src/lib/catalog/llm-providers.ts b/src/lib/catalog/llm-providers.ts
index 949a7fea..6a48b801 100644
--- a/src/lib/catalog/llm-providers.ts
+++ b/src/lib/catalog/llm-providers.ts
@@ -620,7 +620,7 @@ export const LLM_PROVIDERS: LlmProviderDef[] = [
quirks: { effortField: "reasoning.effort", replayReasoning: "preserve", headers: { "X-OpenRouter-Title": "Fuobe" } },
freeLimits: {
text: "20 a minute, 50 a day (1,000 a day once you've bought 10 credits)",
- caveat: "Some free models' providers may log prompts (OpenRouter → Settings → Privacy).",
+ caveat: "Some free models' providers may log prompts (see the privacy settings on OpenRouter's site).",
shared: true,
},
models: [
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index 125ded30..c4c704b5 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -27,10 +27,16 @@ import {
type AssistThreadView,
type SkillMeta,
} from "@/lib/assist";
+import { freePick, manualGroups, smartPick, toOption, choices, type Choice, type ConnectedProvider, type World } from "@/lib/assist-models";
+import { getLlmModel, getLlmProvider, LLM_REGISTRY_CHECKED } from "@/lib/catalog/llm-providers";
import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
import { db } from "../db";
import { getGeneration } from "../generations";
import { activeLocal, aiHelper, chatLocal, emptyReply, localLabel, localProblem, localSoon, pinnedKind, toChatMessages, type Ready } from "../llm";
+import { chatHosted, connectedHosted, endpointFor, freePlanOn, freeSpent, isRejected, markFreeSpent, openRouterKey } from "../llm/hosted";
+import { FreeLimitError } from "../llm/hosted-errors";
+import { toHostedMessages } from "../llm/hosted-messages";
+import type { Replay } from "../llm/types";
import { offeredDefault } from "../model-access";
import { engineMode, getSetting } from "../settings";
import { getSkill } from "../skills";
@@ -63,14 +69,21 @@ export interface ModelRequest {
messages: MessageParam[];
tools: Anthropic.Beta.BetaTool[];
ctx: ToolContext;
- /** The chat's model choice (Manual mode): a Claude model id or a local model's name, and the effort. */
- settings?: { model?: string | null; effort?: AssistEffort | null };
+ /** The chat's model: a Claude model id, a hosted provider and its model, or a local model's name; and the effort. */
+ settings?: { model?: string | null; effort?: AssistEffort | null; provider?: string | null };
+ /** The chat's id (hosted providers that cache by conversation get a hash of it). */
+ threadId?: string;
/** Skills loaded in the chat (the offline planner uses their hints). */
skills?: SkillMeta[];
/** Custom MCP connectors (Settings → Assist): Claude gets them through the MCP connector; other agents can't use them. */
connectors?: Connector[];
}
-export type ModelCall = (req: ModelRequest) => Promise<Anthropic.Beta.BetaMessage>;
+/** A reply: Claude's shape, plus what a hosted provider needs back on this turn and a one-time notice about the chat's price. */
+export type ModelReply = Anthropic.Beta.BetaMessage & { replay?: Replay; priceNote?: string };
+export type ModelCall = (req: ModelRequest) => Promise<ModelReply>;
+
+/** A stored turn: Claude's shape, with a hosted provider's replay data on its own assistant turns. */
+type Stored = MessageParam & { replay?: Replay };
const MAX_STEPS = 16;
const MAX_IMAGE_BYTES = 3_500_000;
@@ -108,6 +121,7 @@ interface StateRow {
mode: AssistMode | null;
model: string | null;
effort: AssistEffort | null;
+ provider: string | null;
skills_json: string;
context: string | null;
sent_json: string | null;
@@ -123,6 +137,8 @@ interface Ext {
mode: AssistMode | null;
model: string | null;
effort: AssistEffort | null;
+ /** A hosted model's provider (null: Claude, a local model or the offline planner). */
+ provider: string | null;
skills: string[];
/** The chat's frozen context block (null until the first model call). */
context: string | null;
@@ -156,6 +172,7 @@ function loadExt(id: string): Ext {
mode: r?.mode ?? null,
model: r?.model ?? null,
effort: r?.effort ?? null,
+ provider: r?.provider ?? null,
skills: r ? (JSON.parse(r.skills_json) as string[]) : [],
context: r?.context ?? null,
sent: r?.sent_json ? (JSON.parse(r.sent_json) as Record<string, string>) : null,
@@ -173,6 +190,7 @@ function withExt(t: AssistThread, e: Ext): AssistThread {
mode: e.mode ?? (t.agent === "claude" ? "smart" : "free"),
model: e.model,
effort: e.effort,
+ provider: e.provider,
skills: e.skills,
...(e.scheduleId && { scheduleId: e.scheduleId }),
...(e.capUsd !== null && { capUsd: e.capUsd, spentUsd: e.spentUsd }),
@@ -238,9 +256,9 @@ function save(s: State): void {
});
db()
.prepare(
- `INSERT INTO assist_thread_state (thread_id, project_id, mode, model, effort, skills_json, context, sent_json, schedule_id, cap_usd, spent_usd, connectors)
- VALUES (@thread_id, @project_id, @mode, @model, @effort, @skills_json, @context, @sent_json, @schedule_id, @cap_usd, @spent_usd, @connectors)
- ON CONFLICT(thread_id) DO UPDATE SET project_id = @project_id, mode = @mode, model = @model, effort = @effort,
+ `INSERT INTO assist_thread_state (thread_id, project_id, mode, model, effort, provider, skills_json, context, sent_json, schedule_id, cap_usd, spent_usd, connectors)
+ VALUES (@thread_id, @project_id, @mode, @model, @effort, @provider, @skills_json, @context, @sent_json, @schedule_id, @cap_usd, @spent_usd, @connectors)
+ ON CONFLICT(thread_id) DO UPDATE SET project_id = @project_id, mode = @mode, model = @model, effort = @effort, provider = @provider,
skills_json = @skills_json, context = @context, sent_json = @sent_json, schedule_id = @schedule_id, cap_usd = @cap_usd, spent_usd = @spent_usd,
connectors = @connectors`,
)
@@ -250,6 +268,7 @@ function save(s: State): void {
mode: s.ext.mode,
model: s.ext.model,
effort: s.ext.effort,
+ provider: s.ext.provider,
skills_json: JSON.stringify(s.ext.skills),
context: s.ext.context,
sent_json: s.ext.sent ? JSON.stringify(s.ext.sent) : null,
@@ -353,12 +372,7 @@ export async function updateThread(id: string, patch: ThreadPatch): Promise<Assi
}
if (patch.mode) {
if (s.thread.status === "running" || runs.has(id)) throw new AssistBusyError("Wait for this reply to finish, then switch");
- const r = await resolveMode(patch.mode);
- s.thread.agent = r.agent;
- s.ext.mode = r.mode;
- s.ext.model = r.model;
- s.ext.effort = r.effort;
- if (r.note) push(s, { role: "notice", tone: "info", text: r.note });
+ applyMode(s, await resolveMode(patch.mode));
connectorNote(s);
}
save(s);
@@ -376,17 +390,11 @@ function localDownNote(): string {
}
/**
- * Which LLM drives new chats by default: Claude when a key is set (on open-source-only installs only when
- * picked explicitly), else a local model that answers (Ollama, LM Studio, Unsloth Studio…), else the offline planner.
+ * Which LLM drives new chats by default: the agent of the default mode (resolveMode with no choice): Smart's
+ * planner when that is a paid model, else Free's pick, else the offline planner.
*/
export async function resolveAgent(): Promise<AssistThread["agent"]> {
- const choice = aiHelper();
- const key = !!getSetting("anthropicKey");
- if (choice === "none") return "offline";
- if (choice === "anthropic") return key ? "claude" : "offline";
- if (choice === "local") return "local";
- if (key && engineMode() !== "open") return "claude";
- return (await localSoon()) ? "local" : "offline";
+ return (await resolveMode()).agent;
}
const claudeAllowed = () => !!getSetting("anthropicKey") && (engineMode() !== "open" || aiHelper() === "anthropic");
@@ -399,21 +407,65 @@ function localInfo(ready: Ready | null): AssistLocal {
return { kind: server.kind, label: server.label, ok: true, models: models.slice(0, 50), model: status.model };
}
+/** How long the panel waits for OpenRouter's key check (an older answer is used meanwhile). */
+const KEY_WAIT_MS = 1500;
+
+/**
+ * What the owner has connected, for the model picks (src/lib/assist-models.ts): the providers with a key (Anthropic's,
+ * the hosted ones'), the local server that answers, and Settings. No call is made to a paid API.
+ */
+async function world(ready?: Ready | null): Promise<World> {
+ const local = ready === undefined ? await localSoon() : ready;
+ const providers: ConnectedProvider[] = [];
+ if (getSetting("anthropicKey")) providers.push({ id: "anthropic" });
+ for (const ep of connectedHosted()) {
+ const c: ConnectedProvider = { id: ep.provider.id, ...(ep.cny && { cny: true }), ...(freePlanOn(ep.provider) && { freeTick: true }), ...(isRejected(ep) && { rejected: true }) };
+ if (ep.provider.id === "openrouter") {
+ const k = await openRouterKey(false, KEY_WAIT_MS);
+ if (k) Object.assign(c, { freeTier: k.freeTier, freeLeft: k.left, freeLimit: k.limit });
+ }
+ providers.push(c);
+ }
+ const info = local ? localInfo(local) : null;
+ return {
+ providers,
+ local: info ? { kind: info.kind ?? "custom", label: info.label, ok: info.ok, model: info.model, models: info.models.map((id) => ({ id })) } : null,
+ openOnly: engineMode() === "open",
+ helper: aiHelper(),
+ smartPlan: getSetting("smartPlan") || "auto",
+ freeOrder: getSetting("freeOrder") === "local" ? "local" : "best",
+ today: new Date().toISOString().slice(0, 10),
+ checker: false,
+ spent: freeSpent(),
+ };
+}
+
export async function availability(): Promise<AssistAvailability> {
const ready = await localSoon();
- const aiOff = aiHelper() === "none";
- const claude = claudeAllowed();
+ const w = await world(ready);
+ const aiOff = w.helper === "none";
+ const smart = smartPick(w);
+ const free = freePick(w);
+ const manual = manualGroups(w);
+ const opt = (c: Choice | null) => (c ? toOption(c) : null);
return {
- claude,
+ claude: claudeAllowed(),
local: localInfo(ready),
aiOff,
- defaultMode: !aiOff && claude && aiHelper() !== "local" ? "smart" : "free",
+ defaultMode: !aiOff && smart.plan && !smart.plan.free && w.helper !== "local" ? "smart" : "free",
+ smart: { plan: opt(smart.plan), check: opt(smart.check), text: smart.text },
+ free: { pick: opt(free.pick), text: free.text, ...(free.pick?.caveat && { caveat: free.pick.caveat }) },
+ manual: { groups: manual.groups.map((g) => ({ ...g, models: g.models.map(toOption) })), missing: manual.missing },
+ openOnly: w.openOnly,
+ checked: LLM_REGISTRY_CHECKED,
};
}
export interface ResolvedMode {
mode: AssistMode;
agent: AssistAgent;
+ /** A hosted model's provider (null otherwise). */
+ provider: string | null;
model: string | null;
effort: AssistEffort | null;
/** Why the chat didn't get what was asked (no key, AI helper off…). */
@@ -423,37 +475,89 @@ export interface ResolvedMode {
/** A local model's name: Ollama's "qwen3:8b", LM Studio's "qwen/qwen3-8b@q4_k_m", Unsloth's "unsloth/Qwen3-8B-GGUF:Q4_K_M". */
const LOCAL_NAME = /^[\w.:/@+-]{1,200}$/;
+/** A pick as the chat stores it. The local model stays the server's default (null), so a model swapped on the server is used. */
+function fromChoice(mode: AssistMode, c: Choice, effort: AssistEffort | null | undefined, note?: string): ResolvedMode {
+ if (c.local) return { mode, agent: "local", provider: null, model: null, effort: null, ...(note && { note }) };
+ const e = effort && c.efforts.includes(effort) ? effort : c.efforts.includes(DEFAULT_EFFORT) ? DEFAULT_EFFORT : (c.efforts[0] ?? null);
+ return { mode, agent: c.agent, provider: c.agent === "hosted" ? c.provider : null, model: c.model, effort: e, ...(note && { note }) };
+}
+
/**
- * Supercomputer's modes on Fuobe's agents: Smart = Claude Opus 5.5; Free = a local model (Ollama,
- * LM Studio, Unsloth Studio…; the offline planner when none answers); Manual = the model and effort
- * you pick. Without a choice, the default from Settings (resolveAgent).
+ * Supercomputer's modes on Fuobe's agents: Smart = the best model the owner has connected (Claude, OpenAI, Gemini,
+ * DeepSeek, OpenRouter… or the local model; src/lib/assist-models.ts); Free = free models only (OpenRouter's free
+ * models, Z.ai's free GLM Flash, free plans the owner ticked, the local model; the offline planner when none);
+ * Manual = the model and effort you pick, when it can run here. Without a choice, the default mode.
*/
export async function resolveMode(choice?: Partial<AssistModeChoice>): Promise<ResolvedMode> {
- const free = async (note?: string): Promise<ResolvedMode> =>
- (await localSoon()) ? { mode: "free", agent: "local", model: null, effort: null, note } : { mode: "free", agent: "offline", model: null, effort: null, note };
if (aiHelper() === "none") {
- return { mode: choice?.mode ?? "free", agent: "offline", model: null, effort: null, ...(choice?.mode && choice.mode !== "free" && { note: "The AI helper is off in Settings, so this chat uses the offline planner." }) };
- }
- if (!choice?.mode) {
- const agent = await resolveAgent();
- return { mode: agent === "claude" ? "smart" : "free", agent, model: null, effort: null };
+ return {
+ mode: choice?.mode ?? "free",
+ agent: "offline",
+ provider: null,
+ model: null,
+ effort: null,
+ ...(choice?.mode && choice.mode !== "free" && { note: "The AI helper is off in Settings, so this chat uses the offline planner." }),
+ };
}
- const noKey = "Smart and Claude need an Anthropic API key (Settings → AI helper) — using Free instead.";
- if (choice.mode === "smart") return claudeAllowed() ? { mode: "smart", agent: "claude", model: DEFAULT_CLAUDE_MODEL, effort: DEFAULT_EFFORT } : free(noKey);
+ const w = await world();
+ const free = (note?: string): ResolvedMode => {
+ const f = freePick(w);
+ return f.pick ? fromChoice("free", f.pick, null, note) : { mode: "free", agent: "offline", provider: null, model: null, effort: null, ...(note && { note }) };
+ };
+ const smart = smartPick(w);
+ if (!choice?.mode) return smart.plan && !smart.plan.free && w.helper !== "local" ? fromChoice("smart", smart.plan, DEFAULT_EFFORT) : free();
+ if (choice.mode === "smart") return smart.plan ? fromChoice("smart", smart.plan, DEFAULT_EFFORT) : free(`${smart.text} Using Free instead.`);
if (choice.mode === "free") return free();
// Manual
const agent = normalizeAgent(choice.agent) ?? "claude";
- if (agent === "claude") {
- if (!getSetting("anthropicKey")) return free(noKey);
- const model = CLAUDE_MODELS.some((m) => m.id === choice.model) ? choice.model! : DEFAULT_CLAUDE_MODEL;
+ if (agent === "claude" || agent === "hosted") {
+ const provider = agent === "claude" ? "anthropic" : (choice.provider ?? "");
+ const model = agent === "claude" && !CLAUDE_MODELS.some((m) => m.id === choice.model) ? DEFAULT_CLAUDE_MODEL : choice.model;
+ const c = choices(w).find((x) => x.provider === provider && x.model === model && !x.local);
+ const label = getLlmProvider(provider)?.label ?? "That provider";
+ if (!c) return free(agent === "claude" ? "Claude needs an Anthropic API key (Settings → AI helper) — using Free instead." : `${label} isn't connected (Settings → AI helper) — using Free instead.`);
+ if (c.disabled) return free(`${c.name} can't run here: ${c.disabled.replace(/\.$/, "")} — using Free instead.`);
const effort = ASSIST_EFFORTS.some((e) => e.id === choice.effort) ? choice.effort! : DEFAULT_EFFORT;
- return { mode: "manual", agent: "claude", model, effort };
+ return { ...fromChoice("manual", c, effort), ...(agent === "claude" && { effort }) };
}
if (agent === "local") {
const model = choice.model && LOCAL_NAME.test(choice.model) ? choice.model : null;
- return { mode: "manual", agent: "local", model, effort: null, ...(!(await localSoon()) && { note: localDownNote() }) };
+ return { mode: "manual", agent: "local", provider: null, model, effort: null, ...(!(await localSoon()) && { note: localDownNote() }) };
}
- return { mode: "manual", agent: "offline", model: null, effort: null };
+ return { mode: "manual", agent: "offline", provider: null, model: null, effort: null };
+}
+
+/** The chat takes a resolved mode (and says why it isn't what was asked, when it isn't). */
+function applyMode(s: State, r: ResolvedMode): void {
+ s.thread.agent = r.agent;
+ s.ext.mode = r.mode;
+ s.ext.provider = r.provider;
+ s.ext.model = r.model;
+ s.ext.effort = r.effort;
+ if (r.note) push(s, { role: "notice", tone: "info", text: r.note });
+}
+
+/** What a chat's model is called in a notice: "GPT-6.1 Sol (OpenAI)", "qwen3.8:27b (Ollama)", "the offline planner". */
+function modelName(agent: AssistAgent, provider: string | null, model: string | null): string {
+ if (agent === "offline") return "the offline planner";
+ if (agent === "local") return model ? `${model} (${localLabel()})` : `the local model (${localLabel()})`;
+ if (agent === "claude") return CLAUDE_MODELS.find((m) => m.id === (model ?? DEFAULT_CLAUDE_MODEL))?.label ?? "Claude";
+ return `${getLlmModel(provider, model)?.name ?? model} (${getLlmProvider(provider)?.short ?? provider})`;
+}
+
+/**
+ * Smart and Free keep the model they picked; when its provider's key is gone (or a hosted model can't run here any
+ * more), the next message picks again and says so. Manual keeps the model the person picked.
+ */
+async function repick(s: State): Promise<void> {
+ if (s.ext.mode === "manual" || s.thread.agent !== "hosted") return;
+ const c = choices(await world()).find((x) => x.provider === s.ext.provider && x.model === s.ext.model && !x.local);
+ if (c && !c.disabled) return;
+ const was = getLlmProvider(s.ext.provider)?.short ?? "Its provider";
+ const mode = s.ext.mode ?? "smart";
+ const r = await resolveMode({ mode });
+ applyMode(s, { ...r, note: undefined });
+ push(s, { role: "notice", tone: "info", text: `${mode === "free" ? "Free" : "Smart"} now uses ${modelName(r.agent, r.provider, r.model)} (${c ? `${c.name} can't run here now` : `${was}'s key was removed`}).` });
}
/** The connectors Claude gets in this chat: none on other agents, or in a scheduled run that leaves them off. */
@@ -464,7 +568,8 @@ function connectorNote(s: State): void {
if (s.thread.agent === "claude" || !s.ext.connectors || s.thread.items.some((i) => i.role === "notice" && i.text.startsWith(CONNECTOR_NOTE))) return;
const names = activeConnectors().map((c) => c.name);
if (!names.length) return;
- push(s, { role: "notice", tone: "info", text: `${CONNECTOR_NOTE} (${names.slice(0, 3).join(", ")}${names.length > 3 ? "…" : ""}); this chat runs on ${s.thread.agent === "local" ? "a local model" : "the offline planner"}, so it can't use them.` });
+ const on = s.thread.agent === "local" ? "a local model" : s.thread.agent === "hosted" ? modelName("hosted", s.ext.provider, s.ext.model) : "the offline planner";
+ push(s, { role: "notice", tone: "info", text: `${CONNECTOR_NOTE} (${names.slice(0, 3).join(", ")}${names.length > 3 ? "…" : ""}); this chat runs on ${on}, so it can't use them.` });
}
const CONNECTOR_NOTE = "Connectors work in Claude chats";
@@ -476,6 +581,8 @@ export function createThread(opts: {
title?: string;
projectId?: string | null;
mode?: AssistMode | null;
+ /** A hosted model's provider. */
+ provider?: string | null;
model?: string | null;
effort?: AssistEffort | null;
/** A scheduled run: the task that started it, and auto-run's cost cap for it. */
@@ -497,6 +604,7 @@ export function createThread(opts: {
mode: opts.mode ?? null,
model: opts.model ?? null,
effort: opts.effort ?? null,
+ provider: opts.provider ?? null,
skills: [],
context: null,
sent: null,
@@ -624,7 +732,7 @@ export const claude: ModelCall = async ({ system, messages, tools, settings, con
// deleted mid-chat changes `tools` (and a deleted one's history is rewritten below), so Claude's
// earlier thinking in that chat is dropped (drop_block) and re-done — a cost, not an error.
const mcp = mcpParams(connectors ?? []);
- const history = withoutMissingServers(messages, new Set(mcp?.mcp_servers.map((m) => m.name)));
+ const history = withoutMissingServers(forAnthropic(messages), new Set(mcp?.mcp_servers.map((m) => m.name)));
// Streamed, so long thinking at high effort never runs into an HTTP timeout; only the final
// message is used (the UI shows the reply once it's complete).
const stream = client.beta.messages.stream({
@@ -649,6 +757,52 @@ export const claude: ModelCall = async ({ system, messages, tools, settings, con
return stream.finalMessage();
};
+/** The history without the replay data hosted providers keep on their turns: Anthropic refuses fields it doesn't know. */
+export function forAnthropic(messages: Stored[]): MessageParam[] {
+ return messages.map((m) => {
+ if (!("replay" in m)) return m;
+ const { replay: _replay, ...rest } = m;
+ return rest;
+ });
+}
+
+/** Claude's reply shape for a model that answered through another wire. */
+function reply(r: { text: string; toolCalls: { id: string; name: string; input: unknown }[]; stop: "end" | "tool_use" | "length"; model: string }, id: string): Anthropic.Beta.BetaMessage {
+ const content: Anthropic.Beta.BetaContentBlock[] = [];
+ if (r.text) content.push({ type: "text", text: r.text, citations: null } as Anthropic.Beta.BetaTextBlock);
+ for (const c of r.toolCalls) content.push({ type: "tool_use", id: c.id, name: c.name, input: c.input } as unknown as Anthropic.Beta.BetaToolUseBlock);
+ const stop: Anthropic.Beta.BetaStopReason = r.toolCalls.length ? "tool_use" : r.stop === "length" ? "max_tokens" : "end_turn";
+ if (!content.length) content.push({ type: "text", text: "…", citations: null } as Anthropic.Beta.BetaTextBlock);
+ return { id, type: "message", role: "assistant", model: r.model, content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null } as unknown as Anthropic.Beta.BetaMessage;
+}
+
+/**
+ * A hosted model on the owner's key (OpenAI, Gemini, xAI, DeepSeek, Kimi, GLM, Qwen, OpenRouter…; src/server/llm/hosted.ts),
+ * answering in Claude's shape. The history goes out shaped for that provider (hosted-messages.ts), with what it needs back
+ * on its own turns (`replay`), and the reply's replay comes back for step() to keep on the stored turn.
+ */
+export const hosted: ModelCall = async ({ system, messages, tools, settings, threadId }) => {
+ const id = settings?.provider ?? "";
+ const p = getLlmProvider(id);
+ const ep = endpointFor(id);
+ if (!p || !ep) throw new Error(`${p?.label ?? "That provider"} isn't connected any more — add its key in Settings → AI helper, or pick another mode.`);
+ const model = p.models.find((m) => m.id === settings?.model);
+ if (!model) throw new Error(`${p.label} has no model ${settings?.model ?? "set"} in Fuobe's list — pick another in Manual.`);
+ const r = await chatHosted(ep, model, {
+ messages: toHostedMessages(system, (await hydrate(messages as MessageParam[])) as Stored[], { provider: p, model }),
+ tools: tools.map((t) => ({ name: t.name, description: t.description, parameters: t.input_schema })),
+ effort: settings?.effort ?? DEFAULT_EFFORT,
+ ...(threadId && { threadKey: threadId }),
+ });
+ if (!r.text && !r.toolCalls.length && r.stop === "length") throw new Error(`${model.name} spent its whole reply thinking and ran out of room. Try a lower effort, or another model.`);
+ const over = model.longContext && (r.usage?.input ?? 0) > model.longContext.above;
+ return {
+ ...reply(r, `msg_${p.id}_${nanoid(8)}`),
+ replay: r.replay,
+ ...(over && { priceNote: `This chat is now long enough to cost more on ${model.name}: ${model.longContext!.text.charAt(0).toLowerCase()}${model.longContext!.text.slice(1)}. A new chat costs less.` }),
+ };
+};
+
/**
* A local model through its server's tool calling (Ollama, LM Studio, Unsloth Studio or another
* OpenAI-compatible server; qwen3, llama3.x, mistral, gemma…), answering in the same shape as Claude.
@@ -669,12 +823,7 @@ export const local: ModelCall = async ({ system, messages, tools, settings }) =>
});
// A thinking model that ran out of room says so, rather than "the reply was cut short".
if (!r.text && !r.toolCalls.length && r.stop === "length") throw emptyReply(server, r);
- const content: Anthropic.Beta.BetaContentBlock[] = [];
- if (r.text) content.push({ type: "text", text: r.text, citations: null } as Anthropic.Beta.BetaTextBlock);
- for (const c of r.toolCalls) content.push({ type: "tool_use", id: c.id, name: c.name, input: c.input } as unknown as Anthropic.Beta.BetaToolUseBlock);
- const stop: Anthropic.Beta.BetaStopReason = r.toolCalls.length ? "tool_use" : r.stop === "length" ? "max_tokens" : "end_turn";
- if (!content.length) content.push({ type: "text", text: "…", citations: null } as Anthropic.Beta.BetaTextBlock);
- return { id: `msg_local_${nanoid(8)}`, type: "message", role: "assistant", model: r.model, content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null } as unknown as Anthropic.Beta.BetaMessage;
+ return reply(r, `msg_local_${nanoid(8)}`);
};
/** A rule-based planner with the same shape as a model reply, for installs without an LLM. */
@@ -1143,7 +1292,8 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
messages: update ? [...s.messages, update] : s.messages,
tools: apiTools(),
ctx,
- settings: { model: s.ext.model, effort: s.ext.effort },
+ settings: { model: s.ext.model, effort: s.ext.effort, provider: s.ext.provider },
+ threadId: s.thread.id,
skills: active,
...(connectors.length && { connectors }),
});
@@ -1162,7 +1312,9 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
s.messages.push(update);
s.ext.sent = sent;
}
- s.messages.push({ role: "assistant", content: res.content });
+ // A hosted provider's replay data stays on its turn (it goes back only to that provider; forAnthropic strips it).
+ s.messages.push({ role: "assistant", content: res.content, ...(res.replay && { replay: res.replay }) } as MessageParam);
+ if (res.priceNote && !s.thread.items.some((i) => i.role === "notice" && i.text === res.priceNote)) push(s, { role: "notice", tone: "info", text: res.priceNote });
connectorItems(s, res.content);
const text = res.content
.filter((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text")
@@ -1242,7 +1394,23 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
return "continue";
}
-const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, local, offline };
+const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, hosted, local, offline };
+
+/**
+ * A free model's limit ran out mid-chat (Free, or a Smart pick that was free): the chat moves to the next free choice
+ * (never a paid one) and says so. A limit shared by all of a provider's free models (OpenRouter's) skips them all.
+ * True when the step should be tried again.
+ */
+async function nextFree(s: State, e: FreeLimitError): Promise<boolean> {
+ markFreeSpent(e.provider, e.span);
+ const was = modelName(s.thread.agent, s.ext.provider, s.ext.model);
+ const r = await resolveMode({ mode: "free" });
+ applyMode(s, { ...r, mode: s.ext.mode === "manual" ? "free" : (s.ext.mode ?? "free"), note: undefined });
+ const p = getLlmProvider(e.provider)?.short ?? e.provider;
+ const when = e.span === "day" ? "for today" : "for the moment";
+ push(s, { role: "notice", tone: "info", text: `${p}'s free requests are used up ${when}, so this chat goes on with ${modelName(r.agent, r.provider, r.model)} instead of ${was}.` });
+ return r.agent !== "offline";
+}
/**
* Run the agent until it ends its turn or waits for approval. Call it right after addMessage or
@@ -1254,14 +1422,24 @@ export async function run(id: string, model?: ModelCall): Promise<void> {
try {
const s = load(id);
if (!s) return;
- const call = model ?? MODELS[s.thread.agent];
+ if (!model) await repick(s).catch(() => {});
+ let call = model ?? MODELS[s.thread.agent];
s.thread.status = "running";
save(s);
+ let moved = false;
for (let i = 0; i < MAX_STEPS; i++) {
let next: "continue" | "stop";
try {
next = await step(s, call);
} catch (e) {
+ // A free limit that ran out: once per run, the chat moves to the next free model and the step is tried again.
+ if (e instanceof FreeLimitError && !model && !moved && (await nextFree(s, e))) {
+ moved = true;
+ call = MODELS[s.thread.agent];
+ save(s);
+ i--;
+ continue;
+ }
push(s, { role: "notice", tone: "error", text: errorText(e) });
next = "stop";
}
diff --git a/src/server/assist/schedules.ts b/src/server/assist/schedules.ts
index 6c80143f..987a02ed 100644
--- a/src/server/assist/schedules.ts
+++ b/src/server/assist/schedules.ts
@@ -320,6 +320,7 @@ export async function startSchedule(id: string, o: { now?: number; model?: Model
title: `${r.title} · ${formatWhen(now, r.tz)}`,
projectId: r.project_id,
mode: m.mode,
+ provider: m.provider,
model: m.model,
effort: m.effort,
scheduleId: r.id,
diff --git a/src/server/assist/schemas.ts b/src/server/assist/schemas.ts
index 0b4ff703..6d93b085 100644
--- a/src/server/assist/schemas.ts
+++ b/src/server/assist/schemas.ts
@@ -11,10 +11,12 @@ export const ModeChoice = z.object({
mode: z.enum(ASSIST_MODES.map((m) => m.id) as ["free", "smart", "manual"]),
// "ollama": the local agent's old name, from browsers that saved a choice before.
agent: z
- .enum(["claude", "local", "ollama", "offline"])
+ .enum(["claude", "hosted", "local", "ollama", "offline"])
.optional()
.transform((a) => normalizeAgent(a)),
- // LM Studio ids can be long (publisher/model@quant).
+ // A hosted model's provider (checked against the registry when the choice is resolved).
+ provider: z.string().regex(/^[a-z0-9-]{2,32}$/).nullish(),
+ // LM Studio ids can be long (publisher/model@quant); OpenRouter's say vendor/model:free, Fireworks' accounts/….
model: z.string().max(200).nullish(),
effort: z.enum(ASSIST_EFFORTS.map((e) => e.id) as ["low", "medium", "high", "xhigh", "max"]).nullish(),
});
diff --git a/src/server/db.ts b/src/server/db.ts
index d6d5e328..821de8bf 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -646,6 +646,12 @@ function open(): Database.Database {
db.prepare("INSERT INTO _migrations (id) VALUES (?)").run(i);
})();
});
+ // Assist on hosted LLM providers (src/lib/catalog/llm-providers.ts): the provider of a chat's model ("openai",
+ // "openrouter"…); chats from before read agent "claude" as Anthropic. Added when it's missing rather than as a
+ // numbered migration, so branches that add migrations never clash over its place in the list.
+ if (!(db.prepare("PRAGMA table_info(assist_thread_state)").all() as { name: string }[]).some((c) => c.name === "provider")) {
+ db.exec("ALTER TABLE assist_thread_state ADD COLUMN provider TEXT");
+ }
// An account's own runs (its list, its active runs) are found through this index, not by reading every run. Not a
// numbered migration, so branches that add migrations never clash over it; a failure only leaves lists slower.
try {
diff --git a/src/server/llm/hosted-errors.ts b/src/server/llm/hosted-errors.ts
index 7637e478..3213fc67 100644
--- a/src/server/llm/hosted-errors.ts
+++ b/src/server/llm/hosted-errors.ts
@@ -85,7 +85,7 @@ export function hostedError(p: LlmProviderDef, status: number, body: string, mod
}
if (CONTEXT.test(detail) || /"context_length_exceeded"/.test(body)) return new ContextError(tooLongText(model ?? { name: "this model" }));
if (p.id === "openrouter" && status === 404 && /data policy|no endpoints/i.test(detail)) {
- return new HostedError(`No OpenRouter provider serves ${model?.name ?? "that model"} with your privacy settings. Allow it in OpenRouter → Settings → Privacy, or pick another free model.`, 404, p.id);
+ return new HostedError(`No OpenRouter provider serves ${model?.name ?? "that model"} with your privacy settings. Allow it in the privacy settings on OpenRouter's site, or pick another free model.`, 404, p.id);
}
if (status === 404 || NO_MODEL.test(detail)) return new HostedError(`${label} has no model ${model?.id ?? "by that name"} today (it may have been retired). Pick another in Manual.`, status, p.id);
if (status === 429) {
diff --git a/src/server/llm/hosted.ts b/src/server/llm/hosted.ts
index d4916b8d..aaeaa17e 100644
--- a/src/server/llm/hosted.ts
+++ b/src/server/llm/hosted.ts
@@ -263,7 +263,11 @@ export async function postHosted(ep: Endpoint, path: string, body: unknown, opts
if ((e as Error)?.name === "TimeoutError") throw new HostedError(`${p.label} took too long to answer. Try again, or pick a faster model.`, 504, p.id);
throw new HostedError(`Couldn't reach ${p.label} (${reason(e, ep.key)})`, 0, p.id);
}
- if (res.ok) return res;
+ if (res.ok) {
+ rejected().delete(keyName(ep));
+ return res;
+ }
+ if (res.status === 401 || res.status === 403) rejected().add(keyName(ep));
const text = await res.text().catch(() => "");
const wait = retryAfter(res.headers.get("retry-after"));
if (attempt === 0 && RETRY.has(res.status) && (wait ?? 2) <= 30) {
@@ -274,6 +278,31 @@ export async function postHosted(ep: Endpoint, path: string, body: unknown, opts
}
}
+declare global {
+ /** Keys a provider rejected on a real call (by hash): "Key rejected" until the key changes or works again. */
+ var __fuobeRejectedKeys: Set<string> | undefined;
+ /** Providers whose free requests are used up, until when (ms). */
+ var __fuobeFreeSpent: Map<string, number> | undefined;
+}
+const rejected = () => (globalThis.__fuobeRejectedKeys ??= new Set());
+const spent = () => (globalThis.__fuobeFreeSpent ??= new Map());
+const keyName = (ep: Endpoint) => createHash("sha256").update(`${ep.provider.id}|${ep.key}`).digest("hex");
+
+/** The provider rejected this key on a real call (and it hasn't worked since). */
+export const isRejected = (ep: Endpoint): boolean => rejected().has(keyName(ep));
+
+/** A free limit ran out: the provider's free models are skipped until the day's (UTC) or the minute's limit resets. */
+export function markFreeSpent(provider: string, span: "day" | "minute"): void {
+ const now = new Date();
+ spent().set(provider, span === "day" ? Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1) : now.getTime() + 60_000);
+}
+
+/** Providers whose free requests are used up right now. */
+export function freeSpent(): string[] {
+ const now = Date.now();
+ return [...spent()].flatMap(([p, until]) => (until > now ? [p] : []));
+}
+
/** A short, stable name for a chat (xAI caches by it): never the chat's own id. */
const chatName = (key: string) => createHash("sha256").update(`fuobe:${key}`).digest("hex").slice(0, 32);
@@ -366,13 +395,24 @@ declare global {
var __fuobeOpenRouterKey: { hash: string; at: number; info: OpenRouterKey | null } | undefined;
}
-/** OpenRouter's GET /api/v1/key (a free call): whether credits were ever bought, and the free requests left today. Kept 60 s. */
-export async function openRouterKey(force = false): Promise<OpenRouterKey | null> {
+/**
+ * OpenRouter's GET /api/v1/key (a free call): whether credits were ever bought, and the free requests left today.
+ * Kept 60 s. `waitMs`: how long a person's question (Assist's panel) waits; an older answer is used meanwhile.
+ */
+export async function openRouterKey(force = false, waitMs?: number): Promise<OpenRouterKey | null> {
const ep = endpointFor("openrouter");
if (!ep) return null;
const hash = createHash("sha256").update(`${ep.baseUrl}|${ep.key}`).digest("hex");
const c = globalThis.__fuobeOpenRouterKey;
if (!force && c?.hash === hash && Date.now() - c.at < 60_000) return c.info;
+ const fresh = readOpenRouterKey(ep, hash);
+ if (waitMs === undefined) return fresh;
+ const late = new Promise<"late">((r) => setTimeout(() => r("late"), waitMs).unref?.());
+ const first = await Promise.race([fresh, late]);
+ return first === "late" ? (c?.hash === hash ? c.info : null) : first;
+}
+
+async function readOpenRouterKey(ep: Endpoint, hash: string): Promise<OpenRouterKey | null> {
let info: OpenRouterKey | null = null;
try {
const res = await getHosted(ep, "/key");
diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.ts
index 01637746..e5015c17 100644
--- a/tests/assist-context.test.ts
+++ b/tests/assist-context.test.ts
@@ -181,9 +181,9 @@ describe("a chat's context", () => {
});
describe("modes", () => {
- it("falls back from Smart and Manual Claude to Free without a key, with a note", async () => {
+ it("falls back from Smart and Manual Claude to Free with nothing connected, with a note", async () => {
setSetting("anthropicKey", "");
- expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ mode: "free", agent: "offline", note: expect.stringMatching(/Anthropic API key/) });
+ expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ mode: "free", agent: "offline", note: expect.stringMatching(/Smart needs a model: add a key in Settings \(Anthropic, OpenAI, Google, OpenRouter…\)/) });
expect(await agent.resolveMode({ mode: "manual", agent: "claude", model: "claude-haiku-5-5" })).toMatchObject({ agent: "offline", note: expect.any(String) });
expect(await agent.resolveMode({ mode: "manual", agent: "offline" })).toMatchObject({ mode: "manual", agent: "offline" });
expect(await agent.resolveMode({ mode: "manual", agent: "local", model: "llama3.2:3b" })).toMatchObject({
diff --git a/tests/assist-providers.test.ts b/tests/assist-providers.test.ts
new file mode 100644
index 00000000..ef8828d0
--- /dev/null
+++ b/tests/assist-providers.test.ts
@@ -0,0 +1,219 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { claudeStream } from "./fixtures/claude-sse";
+import { fakeLlm, type FakeLlm, type Mode } from "./helpers/fake-llm";
+
+/*
+ * Assist end to end on hosted providers, against fakes that enforce each provider's rules: Smart on an
+ * OpenAI key alone reaches an approval card and carries OpenAI's reasoning through the tool loop; a chat
+ * moves Claude → DeepSeek → Gemini → Claude and each provider takes the history (DeepSeek gets other
+ * models' calls as text, Gemini the documented dummy signature, and Anthropic never sees replay data);
+ * Free on OpenRouter's free models moves to the local model when the day's free requests run out, and
+ * tries the step again.
+ */
+
+vi.setConfig({ testTimeout: 60_000 });
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-providers-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+for (const k of Object.keys(process.env)) if (/_API_KEY$|^HF_TOKEN$|^FUOBE_LLM_|^LM_API_TOKEN$|^LMSTUDIO_|^UNSLOTH_|^FUOBE_ENHANCE_PROVIDER$/.test(k)) delete process.env[k];
+
+const { setSetting, SETTINGS } = await import("@/server/settings");
+const agent = await import("@/server/assist/agent");
+const { modeLabel } = await import("@/lib/assist");
+const { LLM_PROVIDERS, getLlmProvider } = await import("@/lib/catalog/llm-providers");
+
+const fakes: FakeLlm[] = [];
+const bases = new Map<string, string>();
+async function fake(mode: Mode, provider: string = mode): Promise<FakeLlm> {
+ const f = fakeLlm(mode, `${provider}-key-0123456789abcdef`);
+ await f.start();
+ fakes.push(f);
+ setSetting(getLlmProvider(provider)!.keySetting as never, f.key);
+ bases.set(provider, `${f.url}/v1`);
+ process.env.FUOBE_LLM_TEST_BASE = [...bases].map(([k, v]) => `${k}=${v}`).join(",");
+ return f;
+}
+/** Every provider key off, and the local server pinned to an address nothing answers. */
+function disconnect() {
+ for (const p of LLM_PROVIDERS) if (p.keySetting) setSetting(p.keySetting as keyof typeof SETTINGS, "");
+ setSetting("llmProvider", "custom");
+ setSetting("llmUrl", "http://127.0.0.1:9/v1");
+ setSetting("llmKey", "");
+ globalThis.__fuobeFreeSpent?.clear();
+ globalThis.__fuobeOpenRouterKey = undefined;
+}
+beforeEach(disconnect);
+afterAll(async () => {
+ await Promise.all(fakes.map((f) => f.close()));
+ delete process.env.FUOBE_LLM_TEST_BASE;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const job = { model_id: "nano-banana-pro", prompt: "a red fox in snow, golden hour" };
+const items = (id: string) => agent.getThread(id)!.thread.items;
+
+describe("Smart on an OpenAI key alone", () => {
+ it("plans with GPT-6.1 Sol, reaches the approval card, and keeps OpenAI's reasoning through the loop", async () => {
+ const f = await fake("openai");
+ const turn = [
+ { type: "reasoning", id: "rs_1", summary: [], encrypted_content: "gAAAA-thinking" },
+ { type: "message", id: "msg_1", role: "assistant", status: "completed", content: [{ type: "output_text", text: "I'll make the fox photo.", annotations: [] }] },
+ { type: "function_call", id: "fc_1", call_id: "call_gen1", name: "generate", arguments: JSON.stringify({ summary: "A fox photo", jobs: [job] }), status: "completed" },
+ ];
+ f.replies = [{ output: turn }, { text: "No problem — tell me what to change." }];
+ const can = await agent.availability();
+ expect(can.smart.plan).toMatchObject({ provider: "openai", model: "gpt-6.1-sol" });
+ expect(can.smart.text).toBe("Smart uses GPT-6.1 Sol (OpenAI) to plan, pick models and check results.");
+ expect(can.defaultMode).toBe("smart");
+ const r = await agent.resolveMode({ mode: "smart" });
+ expect(r).toMatchObject({ mode: "smart", agent: "hosted", provider: "openai", model: "gpt-6.1-sol", effort: "medium" });
+ const t = agent.createThread({ engine: "cloud", agent: r.agent, mode: r.mode, provider: r.provider, model: r.model, effort: r.effort });
+ agent.addMessage(t.id, "A photo of a fox in snow");
+ await agent.run(t.id);
+ const view = agent.getThread(t.id)!.thread;
+ expect(view.status).toBe("waiting");
+ expect(view.items.find((i) => i.role === "approval")).toMatchObject({ summary: expect.stringContaining("fox"), status: "pending" });
+ expect(view.items.some((i) => i.role === "assistant" && i.text === "I'll make the fox photo.")).toBe(true);
+ expect(modeLabel(view)).toBe("Smart · GPT-6.1 Sol");
+ // The first request: stateless, the system prompt as instructions, Fuobe's tools.
+ const first = f.chats()[0];
+ expect(first).toMatchObject({ model: "gpt-6.1-sol", store: false, reasoning: { effort: "medium" } });
+ expect(String(first.instructions)).toContain("You are Fuobe Assist");
+ // Declining sends the result back with OpenAI's own items (the fake refuses the call without its reasoning).
+ await agent.answerApproval(t.id, false);
+ await agent.run(t.id);
+ const second = f.chats()[1].input as Record<string, unknown>[];
+ expect(second).toContainEqual(turn[0]);
+ expect(second).toContainEqual(expect.objectContaining({ type: "function_call_output", call_id: "call_gen1" }));
+ expect(items(t.id).at(-1)).toMatchObject({ role: "assistant", text: "No problem — tell me what to change." });
+ });
+});
+
+describe("a chat that changes model", () => {
+ it("moves Claude → DeepSeek → Gemini → Claude, each provider taking the history", async () => {
+ setSetting("anthropicKey", "sk-ant-test-0123456789");
+ const ds = await fake("deepseek");
+ const gm = await fake("google");
+ ds.issued.add("call_ds1");
+ ds.replies = [{ reasoning: { field: "reasoning_content", text: "List models first." }, calls: [{ id: "call_ds1", name: "search_models", args: { kind: "video" } }] }, { reasoning: { field: "reasoning_content", text: "Done." }, text: "Two video models fit." }];
+ gm.replies = [{ text: "Looking again.", calls: [{ id: "function-call-9", name: "search_models", args: { kind: "audio" }, extra: { google: { thought_signature: "Z2VtaW5p" } } }] }, { text: "Here are the audio ones." }];
+ const anthropic: Record<string, unknown>[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ if (!String(url).includes("api.anthropic.com")) return realFetch(url, init);
+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ anthropic.push(body);
+ return anthropic.length === 1
+ ? claudeStream({ content: [{ type: "text", text: "Checking." }, { type: "tool_use", id: "toolu_01Claude", name: "search_models", input: { kind: "image" } }], stop_reason: "tool_use" })
+ : claudeStream({ content: [{ type: "text", text: anthropic.length === 2 ? "Found some." : "Back on Claude." }], stop_reason: "end_turn" });
+ }) as typeof fetch;
+ try {
+ const t = agent.createThread({ engine: "cloud", agent: "claude", mode: "manual", model: "claude-sonnet-5-5", effort: "low" });
+ agent.addMessage(t.id, "Which image models do I have?");
+ await agent.run(t.id);
+ await agent.updateThread(t.id, { mode: { mode: "manual", agent: "hosted", provider: "deepseek", model: "deepseek-v4-pro", effort: "high" } });
+ agent.addMessage(t.id, "And video?");
+ await agent.run(t.id);
+ expect(items(t.id).at(-1)).toMatchObject({ role: "assistant", text: "Two video models fit." });
+ // Claude's call went to DeepSeek as words; DeepSeek's own turn carried its reasoning back.
+ const dsLast = ds.chats().at(-1)!.messages!;
+ expect(JSON.stringify(dsLast)).toContain("search_models");
+ expect(dsLast.some((m) => m.tool_calls?.some((c) => c.id === "toolu_01Claude"))).toBe(false);
+ expect(dsLast.find((m) => m.tool_calls?.[0]?.id === "call_ds1")!.reasoning_content).toBe("List models first.");
+ expect(ds.chats()[0]).toMatchObject({ reasoning_effort: "high", thinking: { type: "enabled" } });
+
+ await agent.updateThread(t.id, { mode: { mode: "manual", agent: "hosted", provider: "google", model: "gemini-3.8-flash" } });
+ agent.addMessage(t.id, "And audio?");
+ await agent.run(t.id);
+ expect(items(t.id).at(-1)).toMatchObject({ role: "assistant", text: "Here are the audio ones." });
+ const gmLast = gm.chats().at(-1)!.messages!.filter((m) => m.tool_calls?.length);
+ expect(gmLast.map((m) => (m.tool_calls![0].extra_content as { google: { thought_signature: string } }).google.thought_signature)).toEqual(["skip_thought_signature_validator", "skip_thought_signature_validator", "Z2VtaW5p"]);
+
+ await agent.updateThread(t.id, { mode: { mode: "manual", agent: "claude", model: "claude-sonnet-5-5" } });
+ agent.addMessage(t.id, "Thanks");
+ await agent.run(t.id);
+ expect(items(t.id).at(-1)).toMatchObject({ role: "assistant", text: "Back on Claude." });
+ const last = JSON.stringify(anthropic.at(-1));
+ expect(last).not.toContain("replay");
+ expect(last).not.toContain("reasoning_content");
+ expect(last).toContain("call_ds1");
+ expect(last).toContain("function-call-9");
+ expect(modeLabel(agent.getThread(t.id)!.thread)).toBe("Sonnet 5.5 · Medium");
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+});
+
+describe("Free", () => {
+ it("runs on OpenRouter's free models, then moves to the local model when the day's free requests run out", async () => {
+ const or = await fake("openrouter");
+ or.keyInfo = { is_free_tier: true, free_model_daily_requests: { used: 47, limit: 50, remaining: 3 } };
+ or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: { error: { code: 429, message: "Rate limit exceeded: free-models-per-day", metadata: { error_type: "rate_limit_exceeded" } } } }];
+ const local = fakeLlm("local", "sk-local-0123456789");
+ await local.start();
+ fakes.push(local);
+ local.models = ["qwen3.8:27b"];
+ local.replies = [{ text: "Here's the plan, from this machine." }];
+ setSetting("llmUrl", `${local.url}/v1`);
+ setSetting("llmKey", local.key);
+
+ const can = await agent.availability();
+ expect(can.free.pick).toMatchObject({ provider: "openrouter", model: "nvidia/nemotron-3-ultra-550b-a55b:free", free: true });
+ expect(can.free.text).toMatch(/^Runs on Nemotron 3 Ultra through OpenRouter — free: 20 a minute, 50 a day .*\(3 left today\)\. When those run out: qwen3\.8:27b on your local server\.$/);
+ // No credits on OpenRouter: Smart plans on its best free model too, and says how to do better.
+ expect(can.smart.text).toMatch(/^Smart uses Nemotron 3 Ultra \(free, through OpenRouter\)/);
+ expect(can.manual.groups.find((g) => g.id === "openrouter")!.models.find((m) => m.model === "x-ai/grok-4.7")!.disabled).toMatch(/No credits on OpenRouter/);
+
+ const r = await agent.resolveMode({ mode: "free" });
+ expect(r).toMatchObject({ mode: "free", agent: "hosted", provider: "openrouter", model: "nvidia/nemotron-3-ultra-550b-a55b:free" });
+ const t = agent.createThread({ engine: "open", agent: r.agent, mode: r.mode, provider: r.provider, model: r.model, effort: r.effort });
+ agent.addMessage(t.id, "A fox in snow");
+ await agent.run(t.id);
+ const thread = agent.getThread(t.id)!.thread;
+ expect(thread.items.find((i) => i.role === "notice")).toMatchObject({ text: expect.stringMatching(/^OpenRouter's free requests are used up for today, so this chat goes on with the local model \(your local server\) instead of Nemotron 3 Ultra \(OpenRouter\)\.$/) });
+ expect(thread.items.at(-1)).toMatchObject({ role: "assistant", text: "Here's the plan, from this machine." });
+ expect(thread).toMatchObject({ agent: "local", mode: "free" });
+ // Free never moves to a paid model, and later Free chats skip OpenRouter until the limit resets.
+ expect((await agent.resolveMode({ mode: "free" })).agent).toBe("local");
+ });
+});
+
+describe("Manual", () => {
+ it("runs a connected provider's model, and says why another can't run", async () => {
+ await fake("deepseek");
+ expect(await agent.resolveMode({ mode: "manual", agent: "hosted", provider: "deepseek", model: "deepseek-flash", effort: "xhigh" })).toMatchObject({ mode: "manual", agent: "hosted", provider: "deepseek", model: "deepseek-flash", effort: "xhigh" });
+ expect(await agent.resolveMode({ mode: "manual", agent: "hosted", provider: "xai", model: "grok-4.7" })).toMatchObject({ mode: "free", note: "xAI (Grok) isn't connected (Settings → AI helper) — using Free instead." });
+ expect(await agent.resolveMode({ mode: "manual", agent: "hosted", provider: "deepseek", model: "not-a-model" })).toMatchObject({ mode: "free" });
+ setSetting("engineMode", "open");
+ try {
+ await fake("moonshot");
+ expect(await agent.resolveMode({ mode: "manual", agent: "hosted", provider: "moonshot", model: "kimi-k3.1-pro" })).toMatchObject({ mode: "free", note: expect.stringMatching(/Not open weights/) });
+ expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ agent: "hosted", provider: "deepseek", model: "deepseek-v4-pro" });
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ });
+
+ it("Smart picks again, and says so, when its provider's key is removed", async () => {
+ await fake("deepseek");
+ const local = fakes.find((f) => f.mode === "local")!;
+ setSetting("llmUrl", `${local.url}/v1`);
+ setSetting("llmKey", local.key);
+ local.replies = [{ text: "Local now." }];
+ const r = await agent.resolveMode({ mode: "smart" });
+ const t = agent.createThread({ engine: "cloud", agent: r.agent, mode: r.mode, provider: r.provider, model: r.model, effort: r.effort });
+ setSetting("deepseekKey", "");
+ agent.addMessage(t.id, "Hi");
+ await agent.run(t.id);
+ expect(items(t.id).find((i) => i.role === "notice")).toMatchObject({ text: "Smart now uses the local model (your local server) (DeepSeek's key was removed)." });
+ expect(items(t.id).at(-1)).toMatchObject({ role: "assistant", text: "Local now." });
+ });
+});
diff --git a/tests/helpers/fake-llm.ts b/tests/helpers/fake-llm.ts
index 393126a7..7297eda1 100644
--- a/tests/helpers/fake-llm.ts
+++ b/tests/helpers/fake-llm.ts
@@ -61,7 +61,9 @@ export type Mode =
| "together"
| "qwen"
| "xai"
- | "huggingface";
+ | "huggingface"
+ /** A local OpenAI-compatible server (llama-server, vLLM…): answers unstreamed calls too. */
+ | "local";
const sse = (o: unknown) => `data: ${JSON.stringify(o)}\n\n`;
@@ -303,6 +305,10 @@ export function fakeLlm(mode: Mode, key = "sk-test-0123456789abcdefghij"): FakeL
res.writeHead(200, { "content-type": "text/event-stream" });
return res.end(responsesStream(reply, model));
}
+ if (mode === "local" && body.stream !== true) {
+ const calls = (reply.calls ?? []).map((c, i) => ({ id: c.id ?? `call_${i}`, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args ?? {}) } }));
+ return json(200, { id: "c1", object: "chat.completion", model, choices: [{ index: 0, finish_reason: calls.length ? "tool_calls" : "stop", message: { role: "assistant", content: reply.text ?? "", ...(calls.length && { tool_calls: calls }) } }] });
+ }
const wrong = broken(mode, body, f.issued);
if (wrong) return json(400, { error: { message: wrong, type: "invalid_request_error" } });
for (const c of reply.calls ?? []) if (c.id) f.issued.add(c.id);