Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat: 支持单独选择记忆维护模型

Zhehui Bi978076bd9dcc
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 26b5bb041e..829e79789c 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -380,6 +380,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {
* MEMORY.md and topic files, adds facts about the person to About me and
* tidies nightly. On unless explicitly false. */
memoryUpkeep?: boolean;
+ memoryModel?: { instanceId: string; model: string };
/** Prompt-cache keep-warm for this bot's Claude threads: true or false overrides the workspace setting; absent follows it. */
cacheKeepWarm?: boolean;
checkWork?: import("./check-work.ts").CheckWork;
diff --git a/server/contracts.ts b/server/contracts.ts
index 24573c2315..7d646d6ba2 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -600,6 +600,8 @@ export interface ProviderInstance {
readonly displayName: string | undefined;
readonly enabled: boolean;
readonly models: ModelCatalog;
+ /** An unmanaged OpenRouter connection, where upkeep can name a model from this account's catalog. */
+ readonly openRouter?: true;
/** True while the catalog is the driver's fixed list or a failed read's leftover, not a list the engine gave. */
readonly modelsUnconfirmed?: boolean;
/** Set with modelsUnconfirmed when the engine's last read of its list failed: why, for the picker to say. */
diff --git a/server/drivers/openai-chat-refusals.ts b/server/drivers/openai-chat-refusals.ts
index b0a59ce9f8..795a3f22c7 100644
--- a/server/drivers/openai-chat-refusals.ts
+++ b/server/drivers/openai-chat-refusals.ts
@@ -34,6 +34,14 @@ export function httpErrorDetail(body: string, limit = 500): string {
export class UnsupportedChatToolsError extends Error {}
+export class ChatHttpError extends Error {
+ readonly status: number;
+ constructor(status: number, message: string) {
+ super(message);
+ this.status = status;
+ }
+}
+
/** The provider closed the stream with neither finish_reason nor [DONE]; resending repeats nothing. */
export class StreamTruncatedError extends ChatProtocolError {}
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 6aef286429..0a86b84115 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -21,7 +21,7 @@ import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent,
import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";
import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";
import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, replayableToolCalls, toolArguments, type ChatToolCall } from "./openai-chat-protocol.ts";
-import { completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, sseData, StreamTruncatedError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";
+import { ChatHttpError, completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, sseData, StreamTruncatedError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";
import { ChatRepeatGuard } from "./chat-repeat-guard.ts";
import { TextCallHoldback, textToolCalls } from "./chat-text-tool-calls.ts";
import { createModelRoutes, isOpenAIAddress, ModelRouteRefused, noRouteLeft, readResponsesStream, responsesRequest, routeRefusal, selectedReasoningEffort, type ModelRoute, type ResponseItem } from "./openai-responses.ts";
@@ -307,7 +307,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (messages.some((entry) => entry.reasoning_content !== undefined) && rejectsReasoningReplay(status, body)) {
return new UnsupportedReasoningReplayError(message);
}
- return new Error(message);
+ return new ChatHttpError(status, message);
};
if (!response.ok) throw failure(response.status, await response.text().catch(() => ""));
noteKeyAccepted(options.apiUrl, options.apiKey);
diff --git a/server/drivers/openrouter-free.test.ts b/server/drivers/openrouter-free.test.ts
index bd8c13aa2b..a2b99e9707 100644
--- a/server/drivers/openrouter-free.test.ts
+++ b/server/drivers/openrouter-free.test.ts
@@ -2,6 +2,8 @@ import { readFileSync } from "node:fs";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { RuntimeEvent } from "../contracts.ts";
import { recordEvents } from "../testing/events.ts";
+import { createSideJobs } from "../side-jobs.ts";
+import type { MemoryModelRun } from "../../shared/memory-model.ts";
import { engineFailureKind } from "./engine-errors.ts";
import { OpenAICompatDriver } from "./openai-compat.ts";
import {
@@ -81,6 +83,94 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe("the OpenRouter memory upkeep model", () => {
+ const model = "deepseek/deepseek-v4.1-flash-1017";
+ const selection = { instanceId: "openrouter", model };
+
+ async function memory(chat: (body: { model: string }) => Response) {
+ const { bodies } = stubOpenRouter({ freeTier: true, chat });
+ const instance = await openRouterInstance(fixtureKey());
+ const runs: MemoryModelRun[] = [];
+ const book = vi.fn();
+ const assertWithinBudget = vi.fn();
+ const bot = { id: "scout", name: "Scout", threadId: "chat", modelSelection: { instanceId: "openrouter", model: PREFERRED }, memoryModel: selection };
+ const jobs = createSideJobs({
+ bot: () => bot,
+ instance: () => instance,
+ refusal: () => undefined,
+ helper: () => null,
+ smallModels: { refused: () => new Set(), remember: () => {} },
+ assertWithinBudget,
+ book,
+ });
+ const ask = () => jobs.text("memory", bot.id)!.generateText("memory prompt", { onMemoryModel: (run) => runs.push(run) });
+ return { instance, ask, bodies, runs, book, assertWithinBudget };
+ }
+
+ const answer = (model: string) => Response.json({ model, choices: [{ message: { content: "remembered" } }],
+ usage: { prompt_tokens: 10, completion_tokens: 2 } });
+
+ it("books the selected model and falls back once when OpenRouter explicitly has no endpoints for it", async () => {
+ let available = true;
+ const fixture = await memory((body) => !available && body.model === model
+ ? Response.json({ error: { code: 404, message: `No endpoints found for ${model}.` } }, { status: 404 })
+ : answer(body.model === PREFERRED ? "vendor/actual-model" : body.model));
+ try {
+ expect(await fixture.ask()).toBe("remembered");
+ available = false;
+ expect(await fixture.ask()).toBe("remembered");
+ available = true;
+ expect(await fixture.ask()).toBe("remembered");
+ expect(fixture.bodies.map(({ model }) => model)).toEqual([model, model, PREFERRED, model]);
+ expect(fixture.runs).toEqual([
+ { ...selection, state: "selected" },
+ { ...selection, state: "fallback", used: "vendor/actual-model" },
+ { ...selection, state: "selected" },
+ ]);
+ expect(fixture.book.mock.calls.map(([row]) => [row.instanceId, row.model])).toEqual([
+ ["openrouter", model], ["openrouter", "vendor/actual-model"], ["openrouter", model],
+ ]);
+ expect(fixture.assertWithinBudget).toHaveBeenCalledTimes(4);
+ } finally {
+ await fixture.instance.dispose();
+ }
+ });
+
+ it.each([
+ [401, "Invalid API key", "authentication"],
+ [402, "Insufficient credits", "credits"],
+ [403, "Request blocked", "forbidden"],
+ [404, "No endpoints found matching your data policy", "request"],
+ [408, "Request timed out", "timeout"],
+ [429, "Rate limit exceeded", "rateLimit"],
+ [503, "No provider available", "request"],
+ ])("does not send the prompt to another model on HTTP %s", async (status, message, reason) => {
+ const fixture = await memory(() => Response.json({ error: { message } }, { status }));
+ try {
+ await expect(fixture.ask()).rejects.toThrow(`HTTP ${status}`);
+ expect(fixture.bodies.map(({ model }) => model)).toEqual([model]);
+ expect(fixture.runs).toEqual([{ ...selection, state: "failed", reason }]);
+ expect(fixture.book).not.toHaveBeenCalled();
+ } finally {
+ await fixture.instance.dispose();
+ }
+ });
+
+ it("checks the spending limit again before sending the automatic request", async () => {
+ const fixture = await memory(() => Response.json({ error: { code: 404, message: "No endpoints for this model found." } }, { status: 404 }));
+ fixture.assertWithinBudget.mockImplementationOnce(() => {}).mockImplementationOnce(() => {
+ throw Object.assign(new Error("The spending limit was reached"), { code: "spend_cap" });
+ });
+ try {
+ await expect(fixture.ask()).rejects.toThrow("The spending limit was reached");
+ expect(fixture.bodies.map(({ model }) => model)).toEqual([model]);
+ expect(fixture.runs).toEqual([{ ...selection, state: "failed", reason: "budget" }]);
+ } finally {
+ await fixture.instance.dispose();
+ }
+ });
+});
+
describe("free OpenRouter models", () => {
it("finds the free models that take tools in OpenRouter's order", () => {
expect(freeToolModels(CATALOG)).toEqual(FREE_TOOL_IDS);
diff --git a/server/drivers/openrouter-free.ts b/server/drivers/openrouter-free.ts
index 1dea777d75..4101c71710 100644
--- a/server/drivers/openrouter-free.ts
+++ b/server/drivers/openrouter-free.ts
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
import type { ModelCatalog, ProviderInstance } from "../contracts.ts";
import { checkProviderKey } from "../provider-key-check.ts";
import { httpStatusOf } from "./engine-errors.ts";
+import { ChatHttpError } from "./openai-chat-refusals.ts";
/** Free models that call tools well, best first; when none is listed, the first free tool-capable model wins. */
export const FREE_MODEL_PREFERENCE: readonly string[] = [
@@ -105,6 +106,14 @@ export function openRouterFailure(text: string, model: string): string | null {
return null;
}
+export function openRouterModelUnavailable(error: unknown, model: string): boolean {
+ if (!(error instanceof ChatHttpError) || ![400, 404].includes(error.status)) return false;
+ if (/ \((?:model_not_found|model_unavailable)\)$/.test(error.message)) return true;
+ const detail = error.message.replace(/^upstream HTTP 404: /, "").replace(/\.$/, "").toLowerCase();
+ return error.status === 404 && (detail === "no endpoints for this model found" ||
+ detail === `no endpoints found for ${model.toLowerCase()}`);
+}
+
/** A turn or helper call without a chosen model waits briefly for `loading` (the key's tier and the catalog), so it
* runs on the free default; OpenRouter's refusals reach the chat in plain words. */
export function withOpenRouterTurns(instance: ProviderInstance, loading: Promise<unknown>): ProviderInstance {
@@ -135,5 +144,5 @@ export function withOpenRouterTurns(instance: ProviderInstance, loading: Promise
return generate(prompt, options);
};
}
- return Object.assign(instance, { startupModelRefresh: loading.then(() => {}) });
+ return Object.assign(instance, { openRouter: true as const, startupModelRefresh: loading.then(() => {}) });
}
diff --git a/server/memory-upkeep.ts b/server/memory-upkeep.ts
index 8ed8f8d904..b529dacadd 100644
--- a/server/memory-upkeep.ts
+++ b/server/memory-upkeep.ts
@@ -1,6 +1,7 @@
import { mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
+import type { MemoryModelRun, MemoryModelStatus } from "../shared/memory-model.ts";
import { writeFileAtomic } from "./atomic.ts";
import { DATA_DIR } from "./config.ts";
import { CaptureBuffer, captureItemLimit, capturePrompt, captureSize, newCandidates, parseCandidates, statedInConversation, worthCapturing, type Candidate, type CaptureBatch, type CaptureTurn } from "./memory-capture.ts";
@@ -12,6 +13,7 @@ import { isForgotten } from "./profile-learned.ts";
import { applyMoves, MAX_MOVES, organizeCandidates, organizePrompt, parseMoves } from "./memory-organize.ts";
import { recordMemoryChange } from "./memory-journal.ts";
import { applyTidy, contradictionCandidates, contradictionPrompt, parseContradictions, planChanges, planTidy, type Contradiction } from "./memory-tidy.ts";
+import type { SideJobTextOptions } from "./side-jobs.ts";
import { appendMemoryArchive, ARCHIVE_TOPIC, ensureWorkspace, listMemoryTopics, memoryDate, memoryEntry, memoryTopicIndex, readMemoryText, updateMemory, workspaceDir, writeMemoryFile, writeMemoryTopic } from "./workspace.ts";
export { dreamConversations } from "./memory-dream.ts";
@@ -33,7 +35,8 @@ export const MAX_PENDING_THREADS = 50;
export const TOPIC_MAX_BYTES = 64 * 1024;
export interface UpkeepEngine {
- generateText?: (prompt: string, options?: { signal?: AbortSignal; timeoutMs?: number }) => Promise<string>;
+ memoryModel?: MemoryModelStatus;
+ generateText?: (prompt: string, options?: SideJobTextOptions) => Promise<string>;
}
export interface UpkeepBot {
@@ -107,6 +110,7 @@ interface UpkeepState {
core?: string[];
topicCursor?: string;
lastDream?: DreamReport;
+ lastModel?: MemoryModelRun;
/** The last time a dream's model call answered: the next dream reads the chats after it. */
dreamedTo?: number;
}>;
@@ -214,7 +218,7 @@ function readRaw(botId: string, relative: string): string | null {
}
}
-async function askModel(engine: UpkeepEngine, prompt: string, timeoutMs = MODEL_TIMEOUT_MS): Promise<string | null> {
+async function askModel(engine: UpkeepEngine, prompt: string, timeoutMs = MODEL_TIMEOUT_MS, onMemoryModel?: SideJobTextOptions["onMemoryModel"]): Promise<string | null> {
if (!engine.generateText) return null;
const expiry = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -222,12 +226,14 @@ async function askModel(engine: UpkeepEngine, prompt: string, timeoutMs = MODEL_
timer = setTimeout(() => {
const error = new DOMException("The background model call timed out.", "TimeoutError");
expiry.abort(error);
+ const selection = engine.memoryModel;
+ if (selection?.model) onMemoryModel?.({ instanceId: selection.instanceId, model: selection.model, state: "failed", reason: "timeout" });
reject(error);
}, timeoutMs);
timer.unref?.();
});
try {
- const answer = await Promise.race([engine.generateText(prompt, { signal: expiry.signal, timeoutMs }), expired]);
+ const answer = await Promise.race([engine.generateText(prompt, { signal: expiry.signal, timeoutMs, ...(onMemoryModel ? { onMemoryModel } : {}) }), expired]);
return typeof answer === "string" ? answer : null;
} catch {
return null;
@@ -262,7 +268,7 @@ export interface MemoryUpkeep {
dream(botId: string): Promise<DreamReport>;
/** The last dream's ideas while they are fresh, with how many chats it read. */
ideas(botId: string): { ideas: string[]; conversations: number };
- status(botId: string): { lastTidy?: TidyReport; lastCapture?: CaptureReport; lastDream?: DreamReport; modelSteps: boolean };
+ status(botId: string): { lastTidy?: TidyReport; lastCapture?: CaptureReport; lastDream?: DreamReport; modelSteps: boolean; memoryModel?: MemoryModelStatus };
tick(): Promise<void>;
start(): void;
stop(): void;
@@ -322,7 +328,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
return promise.finally(end);
}
- const record = (botId: string, patch: { lastTidy?: TidyReport; lastCapture?: CaptureReport; topicCursor?: string; lastDream?: DreamReport; dreamedTo?: number; core?: string[] }) => {
+ const record = (botId: string, patch: UpkeepState["bots"][string]) => {
// a capture or tidy that was out when its bot was deleted leaves nothing behind
if (!deps.bot(botId)) return;
const state = loaded();
@@ -335,6 +341,13 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
for (const batch of open) batch.dirty = true;
};
+ const ask = (botId: string, engine: UpkeepEngine, prompt: string, timeoutMs?: number) => {
+ const started = generation;
+ return askModel(engine, prompt, timeoutMs, engine.memoryModel?.model ? (lastModel) => {
+ if (!cancelled(started) && upkeepEnabled(deps.bot(botId))) record(botId, { lastModel });
+ } : undefined);
+ };
+
const track = <T>(promise: Promise<T>): Promise<T> => {
inflight.add(promise);
void promise.finally(() => inflight.delete(promise)).catch(() => undefined);
@@ -437,7 +450,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
}
ensureWorkspace(id);
const today = memoryDate(now());
- const answer = await askModel(engine, capturePrompt({
+ const answer = await ask(id, engine, capturePrompt({
botName: bot.name,
conversations: conversations.map((conversation) => conversation.turns),
notebook: readRaw(id, "MEMORY.md") ?? "",
@@ -560,7 +573,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const first = readRaw(botId, "MEMORY.md") ?? "";
const candidates = organizeCandidates(first, today, core);
if (!candidates.length) return 0;
- const answer = await askModel(engine, organizePrompt(candidates, memoryTopicIndex(botId), today));
+ const answer = await ask(botId, engine, organizePrompt(candidates, memoryTopicIndex(botId), today));
if (answer === null || cancelled(started) || !upkeepEnabled(deps.bot(botId))) return 0;
const before = readRaw(botId, "MEMORY.md") ?? "";
if (before !== first) return 0;
@@ -648,7 +661,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
if (!engine?.generateText) note = NO_TEXT_ENGINE;
else if (candidates.length < MIN_ENTRIES_FOR_CONTRADICTIONS) note = `Contradictions are checked from ${MIN_ENTRIES_FOR_CONTRADICTIONS} notes on.`;
else {
- const answer = await askModel(engine, contradictionPrompt(candidates));
+ const answer = await ask(botId, engine, contradictionPrompt(candidates));
if (answer === null) note = "The contradiction check did not answer in time.";
else {
contradictions = parseContradictions(answer, candidates.length);
@@ -694,7 +707,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
else {
topicChecks++;
topicCursor = topic.name;
- const answer = await askModel(engine, contradictionPrompt(topicCandidates), remaining);
+ const answer = await ask(botId, engine, contradictionPrompt(topicCandidates), remaining);
if (cancelled(started) || !upkeepEnabled(deps.bot(botId))) return stopped;
if (readRaw(botId, path) !== topicBefore) {
topicsDeferred++;
@@ -774,7 +787,7 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
const today = memoryDate(now());
const first = readRaw(botId, "MEMORY.md") ?? "";
const notebook = contradictionCandidates(first, today);
- const answer = await askModel(engine, dreamPrompt({ botName: bot.name, today, conversations, notebook, topics: memoryTopicIndex(botId) }), DREAM_TIMEOUT_MS);
+ const answer = await ask(botId, engine, dreamPrompt({ botName: bot.name, today, conversations, notebook, topics: memoryTopicIndex(botId) }), DREAM_TIMEOUT_MS);
if (cancelled(started) || !upkeepEnabled(deps.bot(botId))) return report("Memory upkeep was stopped, switched off or paused during the dream; no changes were made.", conversations.length);
if (answer === null) {
const late = report("The dream did not answer in time.", conversations.length);
@@ -904,8 +917,12 @@ export function createMemoryUpkeep(deps: UpkeepDeps): MemoryUpkeep {
return last && now().getTime() - last.at < IDEAS_FOR_MS ? { ideas: last.ideas, conversations: last.conversations } : { ideas: [], conversations: 0 };
},
status(botId) {
- const { lastTidy, lastCapture, lastDream } = loaded().bots[botId] ?? {};
- return { ...(lastTidy ? { lastTidy } : {}), ...(lastCapture ? { lastCapture } : {}), ...(lastDream ? { lastDream } : {}), modelSteps: Boolean(deps.engine(botId)?.generateText) };
+ const { lastTidy, lastCapture, lastDream, lastModel } = loaded().bots[botId] ?? {};
+ const engine = deps.engine(botId);
+ const selection = engine?.memoryModel;
+ const last = selection?.instanceId === lastModel?.instanceId && selection?.model === lastModel?.model ? lastModel : undefined;
+ return { ...(lastTidy ? { lastTidy } : {}), ...(lastCapture ? { lastCapture } : {}), ...(lastDream ? { lastDream } : {}),
+ modelSteps: Boolean(engine?.generateText), ...(selection ? { memoryModel: { ...selection, ...(last ? { last } : {}) } } : {}) };
},
tick,
start() {
diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.ts
index 8dbe49d79b..32b7d2016a 100644
--- a/server/routes/bot-patch.test.ts
+++ b/server/routes/bot-patch.test.ts
@@ -8,7 +8,7 @@ import type { ConnectorScopes } from "../../shared/connector-scopes.ts";
import type { WireBot } from "../../shared/wire.ts";
import { VPS_BOT_ALIAS_CHANGE_ERROR, VPS_BOT_ALIAS_LIFECYCLE_ERROR, VPS_BOT_ALIAS_RESOURCES_ERROR } from "../cloud-backend.ts";
import { DATA_DIR, type AppConfig } from "../config.ts";
-import type { ModelSelection } from "../contracts.ts";
+import type { ModelSelection, ProviderInstance } from "../contracts.ts";
import type { RequestAuth } from "../request-auth.ts";
import { Store, type BotRecord } from "../store.ts";
import * as vps from "../vps-computer.ts";
@@ -86,6 +86,24 @@ function fixture(extra: Partial<BotPatchRouteDeps> = {}) {
return { store, bot, activeVpsThreads, privateThreads, patch };
}
+describe("PATCH /api/bots/:id memory model", () => {
+ it("saves a model from the bot's OpenRouter connection and restores Automatic on null", async () => {
+ const memoryModel = { instanceId: "router", model: "vendor/memory" };
+ const provider = { openRouter: true, enabled: true, models: { options: [{ id: memoryModel.model }] } } as ProviderInstance;
+ const { store, bot, patch } = fixture({ registry: { get: () => provider } });
+ const chatModel = { instanceId: "router", model: "vendor/chat" };
+ store.patchBot(bot.id, { modelSelection: chatModel });
+
+ expect((await patch(bot.id, { memoryModel: { ...memoryModel, instanceId: "other" } })).status).toBe(400);
+ expect((await patch(bot.id, { memoryModel: { ...memoryModel, model: "vendor/unknown" } })).status).toBe(400);
+ expect((await patch(bot.id, { memoryModel }, { headers: { "x-openmausbot-companion": "1" } })).status).toBe(403);
+ expect(await patch(bot.id, { memoryModel })).toMatchObject({ status: 200, body: { bot: { modelSelection: chatModel, memoryModel } } });
+ expect(new Store(() => sonnet).bot(bot.id)?.memoryModel).toEqual(memoryModel);
+ expect((await patch(bot.id, { memoryModel: null })).status).toBe(200);
+ expect(new Store(() => sonnet).bot(bot.id)?.memoryModel).toBeUndefined();
+ });
+});
+
describe("PATCH /api/bots/:id vpsAlias relocation guard", () => {
it("skips the guard when pinning a bot to the host it already uses", async () => {
const { bot, patch } = fixture();
diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts
index 842778f58b..001ad294b1 100644
--- a/server/routes/bot-patch.ts
+++ b/server/routes/bot-patch.ts
@@ -6,6 +6,7 @@ import { isBotLiveVoice } from "../../shared/live-call.ts";
import { normalizeOutboundPolicy } from "../../shared/outbound.ts";
import { normalizePhoneApps } from "../../shared/phone-apps.ts";
import { parseToolScope, toolScopeWidens } from "../../shared/tool-scope.ts";
+import type { MemoryModelSelection } from "../../shared/memory-model.ts";
import { parseToolsOff, TOOL_GROUPS } from "../../shared/tool-groups.ts";
import { isMausColor, MAUS_COLOR_NAMES, type BotUpdateResponse, type WireBot, type WireGroup } from "../../shared/wire.ts";
import { dropRemovedGrants, MAX_ALWAYS_ALLOW } from "../always-allow.ts";
@@ -372,6 +373,16 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
if (typeof body.memoryUpkeep !== "boolean") return json(res, 400, { error: "memoryUpkeep must be true or false" });
patch.memoryUpkeep = body.memoryUpkeep;
}
+ let memoryModel: MemoryModelSelection | undefined;
+ if (body.memoryModel !== undefined) {
+ const parsed = z.object({
+ instanceId: z.string().min(1).max(200),
+ model: z.string().min(1).max(500).regex(/^[A-Za-z0-9][\x21-\x7e]*$/),
+ }).strict().nullable().safeParse(body.memoryModel);
+ if (!parsed.success) return json(res, 400, { error: "memoryModel must name a connection and model, or be null for Automatic" });
+ memoryModel = parsed.data ?? undefined;
+ patch.memoryModel = memoryModel;
+ }
// true/false overrides the workspace, null follows it.
if (body.cacheKeepWarm !== undefined) {
if (body.cacheKeepWarm !== null && typeof body.cacheKeepWarm !== "boolean") return json(res, 400, { error: "cacheKeepWarm must be true, false or null" });
@@ -660,6 +671,15 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
sectionKey(existingBot?.section) !== sectionKey(section);
let bot: BotRecord | null;
const freshBrowserBot = store.bot(m[1]);
+ if (memoryModel && freshBrowserBot) {
+ const { instanceId, model } = memoryModel;
+ const instance = registry.get(instanceId);
+ if (instanceId !== (normalizedSelection ?? freshBrowserBot.modelSelection).instanceId || !instance?.openRouter ||
+ !instance.enabled || !instance.models.options.some((option) => option.id === model) ||
+ hostedModels?.allows({ instanceId, model }) === false) {
+ return json(res, 400, { error: "Choose a model from this bot's current OpenRouter connection." });
+ }
+ }
// Rechecked: the awaits above can yield after the first memory check.
if (freshBrowserBot && body.memoryEnabled !== undefined &&
body.memoryEnabled !== (freshBrowserBot.memoryEnabled !== false) &&
diff --git a/server/side-jobs.test.ts b/server/side-jobs.test.ts
index 9f25ea8a90..f34825aa8e 100644
--- a/server/side-jobs.test.ts
+++ b/server/side-jobs.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DATA_DIR, loadConfig, parseConfigPatch, parseStoredConfig } from "./config.ts";
import type { TextGenerationOptions } from "./contracts.ts";
+import { ChatHttpError } from "./drivers/openai-chat-refusals.ts";
import { createMemoryUpkeep, NO_TEXT_ENGINE, type UpkeepBot } from "./memory-upkeep.ts";
import { closeMessageDb } from "./message-db.ts";
import { createJobSlots } from "./job-slots.ts";
@@ -586,6 +587,24 @@ describe("memory upkeep through the resolver", () => {
});
const memory = () => readFileSync(join(workspaceDir(BOT.id), "MEMORY.md"), "utf8");
+ it("persists the actual fallback model in the upkeep status for the configured choice", async () => {
+ const { jobs, state } = setup();
+ const selection = { instanceId: "openrouter", model: "vendor/memory" };
+ state.bots.set(BOT.id, { ...bot(BOT.id, selection.instanceId), memoryModel: selection });
+ const calls = vi.fn(async (prompt: string, options?: TextGenerationOptions) => {
+ if (options?.model === selection.model) throw new ChatHttpError(404, "upstream HTTP 404: No endpoints for this model found.");
+ options?.onUsage?.({ model: "vendor/served" });
+ return prompt.includes("CAPTURE step") ? facts : '{"moves": []}';
+ });
+ const own = state.instances.get(selection.instanceId)!;
+ state.instances.set(selection.instanceId, { ...own, openRouter: true, models: { default: "vendor/auto", options: [] }, generateText: calls });
+ const service = upkeep(jobs);
+
+ expect(await service.capture({ botId: BOT.id, threadId: "t1", turns })).toMatchObject({ added: 1 });
+ expect(calls.mock.calls.map(([, options]) => options?.model)).toEqual([selection.model, "vendor/auto"]);
+ expect(upkeep(jobs).status(BOT.id).memoryModel).toEqual({ ...selection, last: { ...selection, state: "fallback", used: "vendor/served" } });
+ });
+
it("captures for a Pi bot once a helper is set", async () => {
const { jobs, state } = setup();
state.instances.set("claude", textEngine("claude", "claudeAgent", (prompt) => (prompt.includes("CAPTURE step") ? facts : '{"moves": []}')).instance);
diff --git a/server/side-jobs.ts b/server/side-jobs.ts
index b60cff4cc8..463d023d48 100644
--- a/server/side-jobs.ts
+++ b/server/side-jobs.ts
@@ -4,6 +4,9 @@ import { randomUUID } from "node:crypto";
import { z } from "zod";
import { helperModelAllowed } from "../shared/wire.ts";
+import type { MemoryModelFailure, MemoryModelOutcome, MemoryModelRun, MemoryModelSelection, MemoryModelStatus } from "../shared/memory-model.ts";
+import { ChatHttpError } from "./drivers/openai-chat-refusals.ts";
+import { openRouterModelUnavailable } from "./drivers/openrouter-free.ts";
import { backgroundTextSlots, type JobSlots } from "./job-slots.ts";
import type { ProviderAdapter, ProviderInstance, SmallModelFallback, TextGenerationOptions } from "./contracts.ts";
import { refusesModel } from "./quick-model-fallback.ts";
@@ -38,7 +41,7 @@ export function helperSelection(cfg: HelperConfig, env: Record<string, string |
/** "representative": a person's assistant answering a teammate's question for them, which must never get tools. */
export type SideJob = "compaction" | "memory" | "skill-review" | "setup-suggestions" | "representative" | "status-reply";
-export type SideJobInstance = Pick<ProviderInstance, "instanceId" | "driverKind" | "enabled" | "generateText" | "generateMemoryText" | "models" | "quickModelsUsable"> & {
+export type SideJobInstance = Pick<ProviderInstance, "instanceId" | "driverKind" | "enabled" | "generateText" | "generateMemoryText" | "models" | "quickModelsUsable" | "openRouter"> & {
adapter: { capabilities: Pick<ProviderAdapter["capabilities"], "agentsMcp"> };
};
@@ -48,17 +51,23 @@ export interface SideJobBot {
/** Where a spend alert a call raises is shown. */
threadId: string;
modelSelection: { instanceId: string; model?: string };
+ memoryModel?: MemoryModelSelection;
helperModel?: boolean;
}
export interface SideJobText {
via: "engine" | "helper";
+ memoryModel?: MemoryModelStatus;
generateText: (prompt: string, options?: SideJobTextOptions) => Promise<string>;
}
/** `waiting`: the call has to wait for a free slot (other bots' background calls); `started`: it starts now, after waiting
* or at once. A call that is never queued calls neither. */
-export type SideJobTextOptions = Pick<TextGenerationOptions, "signal" | "timeoutMs"> & { waiting?(): void; started?(): void };
+export type SideJobTextOptions = Pick<TextGenerationOptions, "signal" | "timeoutMs"> & {
+ waiting?(): void;
+ started?(): void;
+ onMemoryModel?(result: MemoryModelRun): void;
+};
export interface SideJobsDeps {
bot: (botId: string) => SideJobBot | null | undefined;
@@ -97,6 +106,21 @@ const NEVER_QUEUED: ReadonlySet<SideJob> = new Set(["compaction", "representativ
/** A person sees these soon (a new bot's suggestions card): they wait ahead of memory upkeep and skill review. */
const SEEN_SOON: ReadonlySet<SideJob> = new Set(["setup-suggestions"]);
+function memoryModelFailure(error: unknown): MemoryModelFailure {
+ if (error instanceof DOMException && error.name === "TimeoutError") return "timeout";
+ if (error instanceof Error && "code" in error && error.code === "spend_cap") return "budget";
+ if (error instanceof ChatHttpError) {
+ switch (error.status) {
+ case 401: return "authentication";
+ case 402: return "credits";
+ case 403: return "forbidden";
+ case 408: return "timeout";
+ case 429: return "rateLimit";
+ }
+ }
+ return "request";
+}
+
export function createSideJobs(deps: SideJobsDeps): SideJobs {
// Logged once per change, not once per call.
let said: string | null = null;
@@ -139,25 +163,74 @@ export function createSideJobs(deps: SideJobsDeps): SideJobs {
async (prompt, options) => {
deps.assertWithinBudget();
const threadId = `${job}-${randomUUID()}`;
+ const generation = fixed();
return call(prompt, {
...options,
- ...fixed(),
- onUsage: (usage) => deps.book({
- botId: bot.id,
- botName: bot.name,
- threadId,
- instanceId: instance.instanceId,
- driverKind: instance.driverKind,
- model: usage.model,
- input: usage.input ?? 0,
- output: usage.output ?? 0,
- ...(usage.cachedInput !== undefined ? { cachedInput: usage.cachedInput } : {}),
- costUsd: usage.costUsd ?? null,
- trigger,
- }, usage.input !== undefined && usage.output !== undefined, bot.threadId),
+ ...generation,
+ onUsage: (usage) => {
+ deps.book({
+ botId: bot.id,
+ botName: bot.name,
+ threadId,
+ instanceId: instance.instanceId,
+ driverKind: instance.driverKind,
+ model: usage.model,
+ input: usage.input ?? 0,
+ output: usage.output ?? 0,
+ ...(usage.cachedInput !== undefined ? { cachedInput: usage.cachedInput } : {}),
+ costUsd: usage.costUsd ?? null,
+ trigger,
+ }, usage.input !== undefined && usage.output !== undefined, bot.threadId);
+ generation.onUsage?.(usage);
+ },
});
};
+ const writeMemory = (bot: SideJobBot, own: SideJobInstance, call: TextCall, selected: MemoryModelSelection): SideJobText["generateText"] =>
+ async (prompt, { onMemoryModel, ...options } = {}) => {
+ const report = (result: MemoryModelOutcome) => onMemoryModel?.({ ...selected, ...result });
+ const allowed = (model: string) => deps.modelAllowed?.({ instanceId: own.instanceId, model }) !== false;
+ const stillSelected = () => {
+ const current = deps.bot(bot.id);
+ return current?.modelSelection.instanceId === own.instanceId && current.memoryModel?.instanceId === own.instanceId &&
+ current.memoryModel.model === selected.model && deps.instance(own.instanceId) === own && !deps.refusal(own);
+ };
+ const trigger: UsageTrigger = { kind: "bot", botId: bot.id };
+ options.signal?.throwIfAborted();
+ if (!stillSelected()) throw new Error("The memory model selection changed.");
+ if (!allowed(selected.model)) {
+ report({ state: "failed", reason: "forbidden" });
+ throw new Error("The memory model is not assigned to this workspace.");
+ }
+ try {
+ const answer = await booked("memory", bot, own, call, trigger, () => ({ model: selected.model }))(prompt, options);
+ if (!options.signal?.aborted) report({ state: "selected" });
+ return answer;
+ } catch (error) {
+ options.signal?.throwIfAborted();
+ if (!openRouterModelUnavailable(error, selected.model)) {
+ report({ state: "failed", reason: memoryModelFailure(error) });
+ throw error;
+ }
+ const fallback = own.models.default;
+ if (!stillSelected() || !fallback || fallback === selected.model || !allowed(fallback)) {
+ report({ state: "failed", reason: "unavailable" });
+ throw error;
+ }
+ let used = fallback;
+ try {
+ const answer = await booked("memory", bot, own, call, trigger, () => ({
+ model: fallback, onUsage: (usage) => { used = usage.model; },
+ }))(prompt, options);
+ if (!options.signal?.aborted) report({ state: "fallback", used });
+ return answer;
+ } catch (fallbackError) {
+ if (!options.signal?.aborted) report({ state: "failed", reason: memoryModelFailure(fallbackError) });
+ throw fallbackError;
+ }
+ }
+ };
+
/** Whatever the lookup throws reads as no helper: a helper never fails a job or the turn waiting on one. */
function usableHelper(): { instance: SideJobInstance; call: TextCall; model?: string } | null {
try {
@@ -196,7 +269,7 @@ export function createSideJobs(deps: SideJobsDeps): SideJobs {
const slots = deps.slots ?? backgroundTextSlots;
const queued = (job: SideJob, found: SideJobText | null): SideJobText | null => found && !NEVER_QUEUED.has(job)
- ? { via: found.via, generateText: (prompt, { waiting, started, ...options } = {}) => slots.run(() => {
+ ? { ...found, generateText: (prompt, { waiting, started, ...options } = {}) => slots.run(() => {
started?.();
return found.generateText(prompt, options);
}, { signal: options.signal, interactive: SEEN_SOON.has(job), onWait: waiting }) }
@@ -206,6 +279,8 @@ export function createSideJobs(deps: SideJobsDeps): SideJobs {
const bot = deps.bot(botId);
const own = at.instance ?? (bot ? deps.instance(bot.modelSelection.instanceId) : null);
if (!bot || !own || deps.refusal(own)) return null;
+ const selectedMemory = job === "memory" && bot.memoryModel?.instanceId === own.instanceId ? bot.memoryModel : undefined;
+ if (selectedMemory && (!own.openRouter || !own.enabled || !own.generateText)) return null;
// The review's changes are written with the bot's own skill tools, whoever read the conversation.
if (job === "skill-review" && own.adapter.capabilities.agentsMcp !== true) return null;
const call = ownCall(job, own);
@@ -217,6 +292,13 @@ export function createSideJobs(deps: SideJobsDeps): SideJobs {
const write = booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => ({ fallback: ownFallback(bot, own), ...quick }));
return { via: "engine", generateText: quick.model ? rememberRefusal(write, own, quick.model) : write };
}
+ if (job === "memory" && own.openRouter && own.enabled && own.generateText) {
+ return {
+ via: "engine",
+ memoryModel: selectedMemory ?? { instanceId: own.instanceId },
+ generateText: selectedMemory ? writeMemory(bot, own, call, selectedMemory) : booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => ({})),
+ };
+ }
return { via: "engine", generateText: booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => ({ fallback: ownFallback(bot, own) })) };
}
if (!helperModelAllowed(bot)) return null;
diff --git a/shared/memory-model.ts b/shared/memory-model.ts
new file mode 100644
index 0000000000..fa2e2c6ed8
--- /dev/null
+++ b/shared/memory-model.ts
@@ -0,0 +1,19 @@
+export interface MemoryModelSelection {
+ instanceId: string;
+ model: string;
+}
+
+export type MemoryModelFailure = "unavailable" | "authentication" | "credits" | "budget" | "forbidden" | "rateLimit" | "timeout" | "request";
+
+export type MemoryModelOutcome =
+ | { state: "selected" }
+ | { state: "fallback"; used: string }
+ | { state: "failed"; reason: MemoryModelFailure };
+
+export type MemoryModelRun = MemoryModelSelection & MemoryModelOutcome;
+
+export interface MemoryModelStatus {
+ instanceId: string;
+ model?: string;
+ last?: MemoryModelRun;
+}
diff --git a/src/components/bot-panel/MemoryUpkeepCards.dom.test.ts b/src/components/bot-panel/MemoryUpkeepCards.dom.test.ts
index 9eee294720..7f2b1dfac0 100644
--- a/src/components/bot-panel/MemoryUpkeepCards.dom.test.ts
+++ b/src/components/bot-panel/MemoryUpkeepCards.dom.test.ts
@@ -5,14 +5,22 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { Bot } from "@/state/store";
import type { MemoryJournalRow } from "@/lib/memory";
+import type { MemoryModelStatus } from "../../../shared/memory-model";
-const fixture = vi.hoisted(() => ({ api: vi.fn(), dispatch: vi.fn(), journal: [] as unknown[], review: undefined as unknown }));
+const fixture = vi.hoisted(() => ({
+ api: vi.fn(), dispatch: vi.fn(), journal: [] as unknown[], review: undefined as unknown,
+ memoryModel: undefined as MemoryModelStatus | undefined,
+}));
vi.mock("@/state/store", async (importOriginal) => ({
...(await importOriginal<typeof import("@/state/store")>()),
api: (...args: unknown[]) => fixture.api(...args),
- useStore: () => ({ state: {}, dispatch: fixture.dispatch }),
+ useStore: () => ({
+ state: { instances: [{ instanceId: "openrouter", models: { options: [{ id: "vendor/next", label: "Next model" }] } }] },
+ dispatch: fixture.dispatch,
+ }),
}));
vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, readAdvancedMode: () => false, setAdvancedMode: vi.fn() }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
const { MemoryUpkeepCards } = await import("./MemoryUpkeepCards");
@@ -34,9 +42,15 @@ beforeEach(() => {
fixture.dispatch = vi.fn();
fixture.journal = [];
fixture.review = undefined;
+ fixture.memoryModel = undefined;
onChanged.mockClear();
fixture.api.mockReset();
- fixture.api.mockImplementation(async (path: string) => {
+ fixture.api.mockImplementation(async (path: string, init?: RequestInit) => {
+ if (path.endsWith("/memory/upkeep")) return { enabled: true, modelSteps: true, memoryModel: fixture.memoryModel };
+ if (path === "/api/bots/scout" && init?.method === "PATCH") {
+ fixture.memoryModel = JSON.parse(String(init.body)).memoryModel ?? { instanceId: "openrouter" };
+ return { ok: true };
+ }
if (path.includes("/memory/journal?")) return { entries: fixture.journal };
if (path.endsWith("/memory")) return { index: {}, topics: [], logs: [], ...(fixture.review ? { lendingReview: fixture.review } : {}) };
return { ok: true };
@@ -57,6 +71,22 @@ it("switches Memory upkeep off and shows no Changes before there are any", async
expect(fixture.dispatch).toHaveBeenCalledWith({ type: "updateBot", botId: "scout", patch: { memoryUpkeep: false } });
});
+it("keeps the selected model visible after fallback and saves an independent memory selection", async () => {
+ const selection = { instanceId: "openrouter", model: "vendor/previous" };
+ fixture.memoryModel = { ...selection, last: { ...selection, state: "fallback", used: "vendor/auto" } };
+ await render();
+ const select = host.querySelector<HTMLSelectElement>('[data-panel-row="memory-model"] select')!;
+ expect(select.value).toBe(selection.model);
+ expect(host.querySelector('[data-panel-row="memory-model"] [role="status"]')?.textContent).toContain("used vendor/auto");
+
+ await act(async () => { select.value = "vendor/next"; select.dispatchEvent(new Event("change", { bubbles: true })); });
+ expect(fixture.api).toHaveBeenCalledWith("/api/bots/scout", {
+ method: "PATCH", body: JSON.stringify({ memoryModel: { instanceId: "openrouter", model: "vendor/next" } }),
+ });
+ expect(select.value).toBe("vendor/next");
+ expect(host.querySelector('[data-panel-row="memory-model"] [role="status"]')).toBeNull();
+});
+
it("undoes an upkeep change from Changes and shows the lending review until it is marked reviewed", async () => {
fixture.journal = [row];
fixture.review = { token: "tok", changed: ["MEMORY.md"] };
diff --git a/src/components/bot-panel/MemoryUpkeepCards.tsx b/src/components/bot-panel/MemoryUpkeepCards.tsx
index 9eae0e70e4..c5fd0f5f1d 100644
--- a/src/components/bot-panel/MemoryUpkeepCards.tsx
+++ b/src/components/bot-panel/MemoryUpkeepCards.tsx
@@ -4,6 +4,7 @@ import { t } from "@/lib/i18n";
import { fetchMemoryJournal, fetchMemoryOverview, markMemoryReviewed, revertMemoryChange, type LendingReview, type MemoryJournalRow } from "@/lib/memory";
import { ApiError, type Bot } from "@/state/store";
import { LendingReviewNotice, MemoryJournalList } from "../bot-settings/MemorySection";
+import { MemoryModelSetting } from "../bot-settings/MemoryModelSetting";
import { Card, SwitchRow } from "./rows";
import { useStoreDispatch } from "@/state/store-select";
@@ -61,6 +62,7 @@ export function MemoryUpkeepCards({ bot, onChanged }: { bot: Bot; onChanged: ()
color={bot.color}
onChange={() => dispatch({ type: "updateBot", botId: bot.id, patch: { memoryUpkeep: bot.memoryUpkeep === false } })}
/>
+ {bot.memoryUpkeep !== false && <MemoryModelSetting key={bot.id} bot={bot} />}
</Card>
{rows.length > 0 && (
<Card label={t("memory.changes")}>
diff --git a/src/components/bot-settings/MemoryModelSetting.tsx b/src/components/bot-settings/MemoryModelSetting.tsx
new file mode 100644
index 0000000000..19345367f5
--- /dev/null
+++ b/src/components/bot-settings/MemoryModelSetting.tsx
@@ -0,0 +1,75 @@
+import { useEffect, useState } from "react";
+
+import type { MemoryModelStatus } from "../../../shared/memory-model";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { fetchUpkeepStatus } from "@/lib/memory";
+import { useMinuteTick } from "@/lib/minute-tick";
+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
+import { api, type Bot } from "@/state/store";
+import { useStoreSelector } from "@/state/store-select";
+import { Select } from "../Select";
+
+export function MemoryModelSetting({ bot, active = true, className = "px-3.5" }: { bot: Bot; active?: boolean; className?: string }) {
+ const [setting, setSetting] = useState<MemoryModelStatus>();
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState("");
+ const minute = useMinuteTick();
+ const canEdit = useOwnerOrAdmin();
+ const botInstanceId = bot.modelSelection.instanceId;
+ const models = useStoreSelector((state) => state.instances?.find((instance) => instance.instanceId === setting?.instanceId)?.models.options);
+
+ useEffect(() => {
+ if (!active || saving) return;
+ let current = true;
+ void fetchUpkeepStatus(bot.id).then(({ memoryModel }) => {
+ if (current) setSetting(memoryModel);
+ }).catch(() => {});
+ return () => { current = false; };
+ }, [active, bot.id, bot.busy, botInstanceId, minute, saving]);
+
+ if (!setting) return null;
+ const { instanceId } = setting;
+ const showSavedChoice = Boolean(setting.model && !models?.some((model) => model.id === setting.model));
+ const save = async (model: string) => {
+ setSaving(true);
+ setError("");
+ try {
+ await api(`/api/bots/${encodeURIComponent(bot.id)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ memoryModel: model ? { instanceId, model } : null }),
+ });
+ setSetting({ instanceId, ...(model ? { model } : {}) });
+ } catch (cause) {
+ setError(cause instanceof Error && cause.message ? cause.message : t("common.tryAgain"));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const last = setting.last;
+ return (
+ <div data-panel-row="memory-model" className={cn("border-t border-hairline/40 py-3", className)}>
+ <label className="flex flex-wrap items-center justify-between gap-2 text-[13px] font-medium text-ink">
+ {t("memory.upkeep.model")}
+ <Select size="sm" className="max-w-full sm:max-w-[65%]" value={setting.model ?? ""} disabled={saving || canEdit !== true}
+ onChange={(event) => void save(event.target.value)}>
+ <option value="">{t("memory.upkeep.modelAuto")}</option>
+ {showSavedChoice && <option value={setting.model}>{setting.model}</option>}
+ {models?.map(({ id, label }) => <option key={id} value={id}>{label}</option>)}
+ </Select>
+ </label>
+ {last?.state === "fallback" && (
+ <p role="status" className="mt-2 break-words text-[12px] text-ink-secondary">
+ {t("memory.upkeep.modelFallback", { model: last.model, used: last.used })}
+ </p>
+ )}
+ {last?.state === "failed" && (
+ <p role="status" className="mt-2 break-words text-[12px] text-ink-secondary">
+ {t(`memory.upkeep.modelFailure.${last.reason}`, { model: last.model })}
+ </p>
+ )}
+ {error && <p role="alert" className="mt-2 text-[12px] text-danger">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/components/bot-settings/MemorySection.tsx b/src/components/bot-settings/MemorySection.tsx
index ffd6db46b4..b2a3e07889 100644
--- a/src/components/bot-settings/MemorySection.tsx
+++ b/src/components/bot-settings/MemorySection.tsx
@@ -1,5 +1,5 @@
import { FileText, FolderOpen, RotateCcw, Trash2 } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import { cn } from "@/lib/cn";
import {
@@ -40,6 +40,7 @@ import { useDesktopCapabilities } from "../DesktopCapabilities";
import { inputCls } from "./field";
import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { useMinuteTick } from "@/lib/minute-tick";
+import { MemoryModelSetting } from "./MemoryModelSetting";
const buttonCls = "rounded-lg bg-control px-3 py-1.5 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50";
const quietButtonCls = "rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50";
@@ -355,6 +356,7 @@ export function MemorySection({ bot, active = true, onToggle }: { bot: Bot; acti
onToggle={toggleUpkeep}
onTidy={() => void tidyNow()}
rooms={{ enabled: learnFromRooms, saving: roomsSaving, error: roomsError, onToggle: () => void toggleRooms() }}
+ model={bot.memoryUpkeep !== false ? <MemoryModelSetting key={bot.id} bot={bot} active={active} className="mt-3" /> : undefined}
/>}
{editing && (
@@ -484,6 +486,7 @@ export function MemoryUpkeepCard({
onToggle,
onTidy,
rooms,
+ model,
}: {
enabled: boolean;
status: UpkeepStatus | null;
@@ -491,6 +494,7 @@ export function MemoryUpkeepCard({
onToggle: () => void;
onTidy: () => void;
rooms?: { enabled: boolean; saving: boolean; error: string; onToggle: () => void };
+ model?: ReactNode;
}) {
return (
<div className="rounded-xl bg-card p-4">
@@ -501,6 +505,7 @@ export function MemoryUpkeepCard({
</div>
<Switch checked={enabled} aria-label={t("memory.upkeep.title")} onClick={onToggle} />
</div>
+ {model}
{enabled && rooms && (
<div className="mt-3 flex items-start justify-between gap-3 border-t border-hairline/40 pt-3">
<div className="min-w-0">
diff --git a/src/lib/memory.ts b/src/lib/memory.ts
index 9d7e2745d0..b2df37de8a 100644
--- a/src/lib/memory.ts
+++ b/src/lib/memory.ts
@@ -1,3 +1,4 @@
+import type { MemoryModelStatus } from "../../shared/memory-model";
import { ApiError, api } from "@/state/store";
import { intlLocale, t } from "@/lib/i18n";
import { serverErrorText } from "@/lib/server-error";
@@ -134,6 +135,7 @@ export interface CaptureReport {
export interface UpkeepStatus {
enabled: boolean;
modelSteps: boolean;
+ memoryModel?: MemoryModelStatus;
lastTidy?: TidyReport;
lastCapture?: CaptureReport;
}
diff --git a/src/locales/en.json b/src/locales/en.json
index b40b7035e4..e40bbb005f 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -7770,6 +7770,17 @@
"memory.undo": "Undo",
"memory.cantUndo": "Can't undo",
"memory.upkeep.help": "Keeps these notes in shape without the bot having to remember: notices facts you mention in chats and files them (core facts here, detail in topic files it creates) and tidies up every night: expired notes are archived, duplicates merged, contradicted notes crossed out. Facts about you are added to About me (Settings → You and your bots), where every bot reads them and you can remove any. Every change shows below and can be undone.",
+ "memory.upkeep.model": "Memory upkeep model",
+ "memory.upkeep.modelAuto": "Automatic",
+ "memory.upkeep.modelFailure.authentication": "Memory upkeep stopped because OpenRouter refused the API key.",
+ "memory.upkeep.modelFailure.budget": "Memory upkeep stopped because the workspace reached its spending limit.",
+ "memory.upkeep.modelFailure.credits": "Memory upkeep stopped because the OpenRouter connection has insufficient credits.",
+ "memory.upkeep.modelFailure.forbidden": "Memory upkeep could not use the model because of an access restriction.",
+ "memory.upkeep.modelFailure.rateLimit": "Memory upkeep stopped at an OpenRouter rate limit.",
+ "memory.upkeep.modelFailure.request": "The last memory upkeep request could not complete.",
+ "memory.upkeep.modelFailure.timeout": "The last memory upkeep request timed out.",
+ "memory.upkeep.modelFailure.unavailable": "{model} was unavailable for the last memory upkeep request.",
+ "memory.upkeep.modelFallback": "{model} was unavailable. The last memory upkeep request used {used}.",
"memory.upkeep.lastTidy": "Last tidy-up {time}: {summary}.",
"memory.source.undo": "undone",
"memory.source.disk": "changed outside the app",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index d3e18a45bc..1978ec8e98 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -6932,6 +6932,17 @@
"memory.undo": "撤销",
"memory.cantUndo": "无法撤销",
"memory.upkeep.help": "无需机器人自己记着,也能让这些笔记保持整齐:它会留意你在聊天中提到的事实并归档(核心事实放在这里,细节写进它创建的主题文件),每晚还会整理一次:过期笔记归档、重复项合并、互相矛盾的笔记划掉。关于你的事实会加入「关于我」(设置 → 你和你的机器人),每个机器人都能读到,你也可以删除任意一条。每次改动都会显示在下方,并可以撤销。",
+ "memory.upkeep.model": "记忆维护模型",
+ "memory.upkeep.modelAuto": "自动",
+ "memory.upkeep.modelFailure.authentication": "OpenRouter 拒绝了 API Key,本次记忆维护已停止。",
+ "memory.upkeep.modelFailure.budget": "工作区已达到支出上限,本次记忆维护已停止。",
+ "memory.upkeep.modelFailure.credits": "OpenRouter 连接额度不足,本次记忆维护已停止。",
+ "memory.upkeep.modelFailure.forbidden": "访问受限,本次记忆维护无法使用该模型。",
+ "memory.upkeep.modelFailure.rateLimit": "触发 OpenRouter 限流,本次记忆维护已停止。",
+ "memory.upkeep.modelFailure.request": "最近一次记忆维护请求未能完成。",
+ "memory.upkeep.modelFailure.timeout": "最近一次记忆维护请求超时。",
+ "memory.upkeep.modelFailure.unavailable": "最近一次记忆维护请求无法使用 {model}。",
+ "memory.upkeep.modelFallback": "{model} 不可用。最近一次记忆维护请求使用了 {used}。",
"memory.upkeep.lastTidy": "上次整理于 {time}:{summary}。",
"memory.source.undo": "被撤销",
"memory.source.disk": "在应用外被改动",