Skip to content

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

app_settings: registry, host and routes for bots changing app settings

aivsomkar053ef196558d
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.ts
new file mode 100644
index 0000000000..0c86813a46
--- /dev/null
+++ b/server/app-settings/host.test.ts
@@ -0,0 +1,269 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import type { ServerResponse } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { AppConfig } from "../config.ts";
+import { flushDecisionLog, readDecisions } from "../decision-log.ts";
+import { UNDO_STALE } from "../direct-apply.ts";
+import type { BotRecord } from "../store.ts";
+import { createAppSettings, WRITE_BUDGET } from "./host.ts";
+import { createSettingsRegistry } from "./registry.ts";
+
+const OPENAI_KEY = "sk-live-9f8e7d6c5b4a3210";
+const dirs: string[] = [];
+afterEach(() => {
+ vi.useRealTimers();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function fixture(options: { owner?: boolean; guest?: boolean; group?: boolean; window?: boolean } = {}) {
+ const dataDir = mkdtempSync(join(tmpdir(), "app-settings-"));
+ dirs.push(dataDir);
+ const bots: BotRecord[] = [
+ { id: "kiwi", name: "Kiwi", color: "#0f0", threadId: "t-kiwi", approvalMode: "full", section: "Sales" } as unknown as BotRecord,
+ { id: "clive", name: "Clive", color: "#00f", threadId: "t-clive", approvalMode: "ask" } as unknown as BotRecord,
+ ];
+ const cfg = { language: "en", rooms: { turnTimeoutMinutes: 30 }, mcp: {}, threads: { maxConcurrentPerBot: 3 }, openai: { key: OPENAI_KEY }, anthropic: { url: "https://api.anthropic.com" } } as AppConfig;
+ const saved: Record<string, unknown>[] = [];
+ const messages: Array<Record<string, any>> = [];
+ const windowValues = new Map<string, unknown>(options.window === false ? [] : [["appearance.skin", "daylight"]]);
+ const store = {
+ appendMessage: (threadId: string, message: Record<string, unknown>) => {
+ const row = { ...message, id: `m${messages.length + 1}`, threadId };
+ messages.push(row);
+ return row as never;
+ },
+ bot: (id: string) => bots.find((bot) => bot.id === id),
+ messagesFor: (threadId: string) => messages.filter((message) => message.threadId === threadId) as never,
+ patchMessage: (threadId: string, messageId: string, patch: Record<string, unknown>) => {
+ const row = messages.find((message) => message.threadId === threadId && message.id === messageId);
+ if (row) Object.assign(row, patch);
+ return null;
+ },
+ setActivity: () => null,
+ setTaskActivity: () => null,
+ taskByThread: () => ({ busy: true }),
+ };
+ const credentialCards: Record<string, unknown>[] = [];
+ const entries = createSettingsRegistry({
+ cfg: () => cfg,
+ saveConfig: async (patch) => {
+ if (patch.anthropic && typeof patch.anthropic === "object" && (patch.anthropic as { url?: string }).url === "https://refused.example") return "the provider refused it";
+ saved.push(patch);
+ Object.assign(cfg, patch);
+ return null;
+ },
+ bots: () => bots,
+ sections: () => ["Sales"],
+ reorderBots: async (botIds) => { bots.sort((a, b) => botIds.indexOf(a.id) - botIds.indexOf(b.id)); return null; },
+ groupBots: async (name, botIds) => { for (const bot of bots) if (botIds.includes(bot.id)) (bot as { section?: string }).section = name || undefined; return null; },
+ credentials: () => cfg,
+ window: {
+ read: (id) => windowValues.get(id),
+ write: (id, value) => { if (!windowValues.size) return "Open MausBot on this computer first."; windowValues.set(id, value); return null; },
+ },
+ });
+ const notified: unknown[] = [];
+ const host = createAppSettings({
+ store: store as never, dataDir, entries, holdMs: 1_000,
+ turnOwner: () => (options.owner === false ? null : "owner"),
+ guestDriven: () => options.guest === true,
+ requestCredential: async (_bot, _threadId, body) => { credentialCards.push(body); return { status: 201, body: { messageId: "secret-1", label: "OpenAI API key" } }; },
+ connectorThread: () => ({ group: options.group ? { id: "g", name: "Room" } as never : undefined }),
+ activeGroupTurnForBot: () => null,
+ notify: (notification) => notified.push(notification),
+ language: () => undefined,
+ });
+ const turn = { botId: "kiwi", threadId: "t-kiwi", generation: "gen-1" };
+ const set = (id: string, value?: unknown, generation = turn.generation) => host.handle({ action: "set", id, ...(value === undefined ? {} : { value }) }, { ...turn, generation });
+ const answer = (requestId: string, behavior: "allow" | "deny", ownerReview = true) => {
+ let sent: { status: number; body: unknown } | null = null;
+ const res = { writeHead: (status: number) => { sent = { status, body: null }; }, end: (text: string) => { sent = { status: sent?.status ?? 0, body: JSON.parse(text) }; } } as unknown as ServerResponse;
+ const claimed = host.resolveAndSend(res, { threadId: turn.threadId, requestId, behavior }, ownerReview);
+ return { claimed, sent: sent as { status: number; body: Record<string, unknown> } | null };
+ };
+ const cards = () => messages.filter((message) => message.card?.appSettingRequest);
+ return { host, cfg, saved, messages, cards, credentialCards, notified, windowValues, bots, turn, set, answer, dataDir };
+}
+
+describe("reads", () => {
+ it("find lists matches with tier, value and where; get adds help and allowed values", async () => {
+ const { host, turn } = fixture();
+ const found = await host.handle({ action: "find", query: "dark mode" }, turn);
+ const hits = JSON.parse(String(found.body.text)) as Array<Record<string, unknown>>;
+ expect(hits[0]).toMatchObject({ id: "appearance.skin", tier: "safe", value: "daylight", where: "Settings → Appearance" });
+ const got = await host.handle({ action: "get", id: "rooms.turnTimeoutMinutes" }, turn);
+ expect(JSON.parse(String(got.body.text))).toMatchObject({ id: "rooms.turnTimeoutMinutes", value: "30", allowed: "1 to 1440 minutes", change: "set applies at once, with Undo on the card" });
+ });
+
+ it("works in a turn that is not the owner's, where writes are refused", async () => {
+ const { host, turn, set, saved } = fixture({ owner: false });
+ expect((await host.handle({ action: "get", id: "general.language" }, turn)).status).toBe(200);
+ const refused = await set("general.language", "de");
+ expect(refused.status).toBe(403);
+ expect(refused.body.error).toContain("owner's own conversation");
+ expect(saved).toEqual([]);
+ });
+
+ it("refuses writes in a guest-driven conversation", async () => {
+ const { set, saved } = fixture({ guest: true });
+ expect((await set("general.language", "de")).status).toBe(403);
+ expect(saved).toEqual([]);
+ });
+
+ it("refuses an unknown id and a value the schema rejects", async () => {
+ const { set, saved } = fixture();
+ expect((await set("nope.nothing", 1)).status).toBe(404);
+ const bad = await set("rooms.turnTimeoutMinutes", 100_000);
+ expect(bad.status).toBe(400);
+ expect(bad.body.error).toContain("1 to 1440 minutes");
+ expect(saved).toEqual([]);
+ });
+});
+
+describe("safe tier", () => {
+ it("applies at once, posts an applied card with Undo, and logs a decision", async () => {
+ const { set, saved, cards, dataDir } = fixture();
+ const result = await set("rooms.turnTimeoutMinutes", 45);
+ expect(result.status).toBe(200);
+ expect(result.body.text).toContain("Changed Room turn timeout from 30 to 45");
+ expect(saved).toEqual([{ rooms: { turnTimeoutMinutes: 45 } }]);
+ expect(cards()[0]!.card).toMatchObject({ autoApplied: true, answered: "allow", options: [], tool: "app_settings", appSettingRequest: { settingId: "rooms.turnTimeoutMinutes", before: "30", after: "45", tier: "safe" } });
+ await flushDecisionLog(dataDir);
+ expect(readDecisions(dataDir, 10)).toMatchObject([{ decision: "auto-approved", source: "app-settings", tool: "app_settings", summary: "rooms.turnTimeoutMinutes: 30 → 45", botId: "kiwi" }]);
+ });
+
+ it("undo restores the earlier value only while the current one is still the applied one", async () => {
+ const { host, set, cfg, cards, turn, saved } = fixture();
+ await set("rooms.turnTimeoutMinutes", 45);
+ const requestId = String(cards()[0]!.card.requestId);
+ cfg.rooms = { turnTimeoutMinutes: 60 };
+ expect(await host.undo({ threadId: turn.threadId, requestId })).toMatchObject({ claimed: true, state: "invalid", error: UNDO_STALE, stale: true });
+ cfg.rooms = { turnTimeoutMinutes: 45 };
+ expect(await host.undo({ threadId: turn.threadId, requestId })).toEqual({ claimed: true, state: "undone" });
+ expect(saved.at(-1)).toEqual({ rooms: { turnTimeoutMinutes: 30 } });
+ expect(cards()[0]!.card.undone).toBe(true);
+ expect(await host.undo({ threadId: turn.threadId, requestId })).toEqual({ claimed: true, state: "already_undone" });
+ });
+
+ it("reorders and groups bots through the registry, with typed values kept for undo", async () => {
+ const { host, set, bots, cards, turn } = fixture();
+ expect((await set("bots.order", ["clive", "kiwi"])).status).toBe(200);
+ expect(bots.map((bot) => bot.id)).toEqual(["clive", "kiwi"]);
+ expect(await host.undo({ threadId: turn.threadId, requestId: String(cards()[0]!.card.requestId) })).toEqual({ claimed: true, state: "undone" });
+ expect(bots.map((bot) => bot.id)).toEqual(["kiwi", "clive"]);
+ expect((await set("bots.groups", { Ops: ["clive"] })).status).toBe(200);
+ expect(bots.map((bot) => bot.section)).toEqual([undefined, "Ops"]);
+ expect(await host.undo({ threadId: turn.threadId, requestId: String(cards()[1]!.card.requestId) })).toEqual({ claimed: true, state: "undone" });
+ expect(bots.map((bot) => bot.section)).toEqual(["Sales", undefined]);
+ });
+
+ it("a window preference refuses until a window has reported, then pushes the change", async () => {
+ const closed = fixture({ window: false });
+ const refused = await closed.set("appearance.skin", "midnight");
+ expect(refused.status).toBe(409);
+ expect(refused.body.error).toContain("Open MausBot on this computer first");
+ const open = fixture();
+ expect((await open.set("appearance.skin", "midnight")).status).toBe(200);
+ expect(open.windowValues.get("appearance.skin")).toBe("midnight");
+ expect((await open.set("appearance.skin", "neon")).status).toBe(400);
+ });
+
+ it(`stops after ${WRITE_BUDGET} writes in one turn and allows the next turn`, async () => {
+ const { set } = fixture();
+ for (let index = 0; index < WRITE_BUDGET; index += 1) expect((await set("rooms.turnTimeoutMinutes", 10 + index)).status).toBe(200);
+ const over = await set("rooms.turnTimeoutMinutes", 99);
+ expect(over.status).toBe(429);
+ expect(over.body.error).toContain(`${WRITE_BUDGET} settings`);
+ expect((await set("rooms.turnTimeoutMinutes", 99, "gen-2")).status).toBe(200);
+ });
+});
+
+describe("confirm tier", () => {
+ it("always shows a Change/Cancel card, applies on an owner's Allow, and refuses a second open card", async () => {
+ const { set, cards, answer, saved, dataDir } = fixture();
+ const pending = set("providers.anthropic.url", "https://proxy.example/v1");
+ await vi.waitFor(() => expect(cards()).toHaveLength(1));
+ const card = cards()[0]!.card;
+ expect(card).toMatchObject({ title: "Change Anthropic address?", options: ["Change", "Cancel"], fixedOptions: true, appSettingRequest: { tier: "confirm", before: "https://api.anthropic.com", after: "https://proxy.example/v1" } });
+ expect(saved).toEqual([]);
+ const second = await set("providers.xai.url", "https://other.example");
+ expect(second.status).toBe(409);
+ expect(second.body.error).toContain("already waiting");
+ const shell = answer(String(card.requestId), "allow", false);
+ expect(shell.sent).toMatchObject({ status: 403 });
+ expect(saved).toEqual([]);
+ const owner = answer(String(card.requestId), "allow");
+ expect(owner.sent).toMatchObject({ status: 200, body: { ok: true, outcome: "allowed-once" } });
+ const result = await pending;
+ expect(result.status).toBe(200);
+ expect(result.body.text).toContain("Changed Anthropic address from https://api.anthropic.com to https://proxy.example/v1");
+ expect(saved).toEqual([{ anthropic: { url: "https://proxy.example/v1" } }]);
+ expect(cards()[0]!.card.answered).toBe("allow");
+ await flushDecisionLog(dataDir);
+ expect(readDecisions(dataDir, 10).map((row) => row.decision)).toEqual(["card-shown", "user-approved"]);
+ });
+
+ it("Cancel refuses with a line telling the bot not to retry, and the user sees the failure of a refused write", async () => {
+ const { set, cards, answer, saved } = fixture();
+ const pending = set("providers.anthropic.url", "https://proxy.example/v1");
+ await vi.waitFor(() => expect(cards()).toHaveLength(1));
+ expect(answer(String(cards()[0]!.card.requestId), "deny").sent).toMatchObject({ status: 200, body: { outcome: "rejected" } });
+ const result = await pending;
+ expect(result.status).toBe(409);
+ expect(result.body.error).toContain("cancelled");
+ expect(result.body.error).toContain("Do not retry");
+ expect(saved).toEqual([]);
+ const refused = set("providers.anthropic.url", "https://refused.example");
+ await vi.waitFor(() => expect(cards()).toHaveLength(2));
+ answer(String(cards()[1]!.card.requestId), "allow");
+ expect((await refused).body.error).toContain("the provider refused it");
+ });
+
+ it("times out, patches the card as unavailable, and refuses the write", async () => {
+ vi.useFakeTimers();
+ const { set, cards, saved } = fixture();
+ const pending = set("providers.anthropic.url", "https://proxy.example/v1");
+ await vi.waitFor(() => expect(cards()).toHaveLength(1));
+ await vi.advanceTimersByTimeAsync(1_000);
+ const result = await pending;
+ expect(result.status).toBe(409);
+ expect(result.body.error).toContain("Nobody answered");
+ expect(cards()[0]!.card).toMatchObject({ answered: "unavailable", dismissed: true });
+ expect(saved).toEqual([]);
+ });
+});
+
+describe("secret tier", () => {
+ it("never takes a value, posts the secret card instead, and shows keys only as set or not set", async () => {
+ const { host, set, credentialCards, messages, turn, dataDir } = fixture();
+ const withValue = await set("keys.openaiApiKey", OPENAI_KEY);
+ expect(withValue.status).toBe(400);
+ expect(credentialCards).toEqual([]);
+ const carded = await set("keys.openaiApiKey");
+ expect(carded.status).toBe(200);
+ expect(credentialCards).toEqual([{ credentialId: "openaiApiKey", reason: undefined }]);
+ const got = await host.handle({ action: "get", id: "keys.openaiApiKey" }, turn);
+ expect(JSON.parse(String(got.body.text))).toMatchObject({ tier: "secret", value: "set" });
+ const found = await host.handle({ action: "find", query: "anthropic key" }, turn);
+ expect(JSON.parse(String(found.body.text))).toContainEqual(expect.objectContaining({ id: "keys.anthropicApiKey", value: "not set" }));
+ await flushDecisionLog(dataDir);
+ const everything = JSON.stringify([withValue, carded, got, found, messages, readDecisions(dataDir, 10)]);
+ expect(everything).not.toContain(OPENAI_KEY);
+ });
+});
+
+describe("owner-only tier", () => {
+ it("explains and refuses with where to change it, approval modes included", async () => {
+ const { host, set, turn } = fixture();
+ const got = await host.handle({ action: "get", id: "bots.approvalModes" }, turn);
+ expect(JSON.parse(String(got.body.text))).toMatchObject({ tier: "owner-only", value: "Kiwi: full; Clive: ask", change: "only the owner, in a bot's Settings" });
+ const refused = await set("bots.approvalModes", { kiwi: "full" });
+ expect(refused.status).toBe(403);
+ expect(refused.body.error).toContain("a bot's Settings");
+ expect((await set("remote.access", "tunnel")).status).toBe(403);
+ });
+});
diff --git a/server/app-settings/host.ts b/server/app-settings/host.ts
new file mode 100644
index 0000000000..4a0df742ff
--- /dev/null
+++ b/server/app-settings/host.ts
@@ -0,0 +1,265 @@
+// The app_settings tool for one turn: find, get and set over the registry, where the entry's tier is the whole policy.
+// Writes happen only in the owner's own turn, a confirm setting always waits on a card the owner answers (Full access
+// never skips it), a secret never passes through the bot, and an owner-only setting is only explained.
+import { randomUUID } from "node:crypto";
+import type { ServerResponse } from "node:http";
+
+import type { AppSettingRequest } from "../../shared/app-settings.ts";
+import type { Notification } from "../../shared/notification.ts";
+import type { OptionCardData } from "../../shared/wire.ts";
+import { appendDecision } from "../decision-log.ts";
+import { UNDO_STALE } from "../direct-apply.ts";
+import { json } from "../harness/http.ts";
+import { buildNotification } from "../notify.ts";
+import { serverLine } from "../server-lines.ts";
+import type { BotRecord, GroupRecord, Store } from "../store.ts";
+import { turnWaitedOnPerson } from "../waiting-on-person.ts";
+import { display, findSettings, type SettingEntry, type WritableEntry } from "./registry.ts";
+
+export const TOOL = "app_settings";
+/** How long a "Change X?" card waits on the person. */
+export const APP_SETTINGS_HOLD_MS = 9 * 60_000;
+/** Writes one turn (generation) may make. */
+export const WRITE_BUDGET = 10;
+const FIND_LIMIT = 8;
+const NOT_RETRY = "Do not retry it; ask the user what they would like instead.";
+/** What the bot reads for an unset value. */
+const NOT_SET = "not set";
+const text = (value: string) => value || NOT_SET;
+
+export interface Turn {
+ botId: string;
+ threadId: string;
+ generation: string;
+}
+
+type Outcome = { kind: "applied"; text: string } | { kind: "failed"; error: string } | { kind: "denied" } | { kind: "timeout" };
+interface Held {
+ botId: string;
+ threadId: string;
+ entry: WritableEntry;
+ value: unknown;
+ before: string;
+ earlier: unknown;
+ settle(outcome: Outcome): void;
+ timer: ReturnType<typeof setTimeout>;
+ answered?: true;
+}
+/** `before`: the typed value read before the write; `after`: what it read as once applied, so Undo can tell it changed since. */
+interface Undoable {
+ entry: WritableEntry;
+ before: unknown;
+ after: string;
+}
+
+export type UndoResult =
+ | { claimed: false }
+ | { claimed: true; state: "already_undone" | "undone" }
+ | { claimed: true; state: "invalid"; error: string; status: number; stale?: true };
+
+export interface AppSettingsDeps {
+ store: Pick<Store, "appendMessage" | "bot" | "messagesFor" | "patchMessage" | "setActivity" | "setTaskActivity" | "taskByThread">;
+ dataDir: string;
+ entries: readonly SettingEntry[];
+ holdMs?: number;
+ /** Non-null when the turn is the owner's own (phones.turnOwner). */
+ turnOwner(turn: Turn): string | null;
+ guestDriven(threadId: string): boolean;
+ /** The secret card, as request_credential posts it. */
+ requestCredential(bot: BotRecord, threadId: string, body: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }>;
+ connectorThread(botId: string, threadId: string): { group?: GroupRecord } | null;
+ activeGroupTurnForBot(botId: string): { threadId: string } | null;
+ notify(notification: Notification | null): void;
+ language(threadId: string): string | undefined;
+}
+
+export function createAppSettings(deps: AppSettingsDeps) {
+ const { store, entries } = deps;
+ const holdMs = deps.holdMs ?? APP_SETTINGS_HOLD_MS;
+ const held = new Map<string, Held>();
+ const openByBot = new Map<string, string>();
+ const undoable = new Map<string, Undoable>();
+ const writes = new Map<string, number>();
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
+
+ const reply = (status: number, body: Record<string, unknown>) => ({ status, body });
+ const refuse = (status: number, error: string) => reply(status, { error });
+ const describe = (entry: SettingEntry) => ({ id: entry.id, label: entry.label, tier: entry.tier, value: text(entry.read()), where: entry.where });
+ const decide = (turn: Turn, bot: BotRecord | undefined, entry: SettingEntry, summary: string, decision: "auto-approved" | "card-shown", requestId?: string) =>
+ appendDecision(deps.dataDir, { threadId: turn.threadId, ...(requestId ? { requestId } : {}), botId: turn.botId, botName: bot?.name, tool: TOOL, summary: `${entry.id}: ${summary}`, decision, source: "app-settings" });
+ const from = (bot: BotRecord, threadId: string) => (deps.connectorThread(bot.id, threadId)?.group ? { from: { botId: bot.id, name: bot.name, color: bot.color } } : {});
+ const card = (bot: BotRecord, threadId: string, entry: WritableEntry, before: string, after: string, requestId: string, options: string[], settled: Partial<OptionCardData>) => {
+ const language = deps.language(threadId);
+ const shown = (value: string) => value || serverLine(language, "server.appSettings.notSet");
+ const appSettingRequest: AppSettingRequest = { settingId: entry.id, label: entry.label, before, after, tier: entry.tier };
+ return store.appendMessage(threadId, {
+ role: "bot", kind: "options", ...from(bot, threadId),
+ card: { title: serverLine(language, "server.appSettings.change", { label: entry.label }), subtitle: `${shown(before)} → ${shown(after)}`, options, requestId, tool: TOOL, fixedOptions: true, appSettingRequest, ...settled },
+ });
+ };
+ const spendWrite = (turn: Turn): string | null => {
+ const spent = writes.get(turn.generation) ?? 0;
+ if (spent >= WRITE_BUDGET) return `This turn has already changed ${WRITE_BUDGET} settings. Ask the user to send a new message before changing more.`;
+ writes.set(turn.generation, spent + 1);
+ if (writes.size > 200) writes.delete(writes.keys().next().value!);
+ return null;
+ };
+
+ async function apply(entry: WritableEntry, value: unknown, before: string): Promise<Outcome> {
+ const refusal = await entry.write(value);
+ if (refusal) return { kind: "failed", error: refusal };
+ return { kind: "applied", text: `Changed ${entry.label} from ${text(before)} to ${text(entry.read())}.` };
+ }
+
+ async function setSafe(turn: Turn, bot: BotRecord, entry: WritableEntry, value: unknown, before: string) {
+ const earlier = entry.current();
+ const outcome = await apply(entry, value, before);
+ if (outcome.kind !== "applied") return refuse(409, outcome.kind === "failed" ? outcome.error : "The change was not applied.");
+ const after = entry.read();
+ const requestId = randomUUID();
+ card(bot, turn.threadId, entry, before, after, requestId, [], { answered: "allow", dismissed: true, autoApplied: true });
+ undoable.set(requestId, { entry, before: earlier, after });
+ decide(turn, bot, entry, `${text(before)} → ${text(after)}`, "auto-approved", requestId);
+ return reply(200, { text: `${outcome.text} The user can undo it from the card in the conversation.` });
+ }
+
+ async function setConfirm(turn: Turn, bot: BotRecord, entry: WritableEntry, value: unknown, before: string) {
+ if (openByBot.has(bot.id)) return refuse(409, "A settings change is already waiting on the user. End your turn and wait for the answer.");
+ const requestId = randomUUID();
+ const after = display(value);
+ let settle!: (outcome: Outcome) => void;
+ const answer = new Promise<Outcome>((resolve) => { settle = resolve; });
+ const timer = setTimeout(() => settleHold(requestId, { kind: "timeout" }), holdMs);
+ timer.unref?.();
+ held.set(requestId, { botId: bot.id, threadId: turn.threadId, entry, value, before, earlier: entry.current(), settle, timer });
+ openByBot.set(bot.id, requestId);
+ const message = card(bot, turn.threadId, entry, before, after, requestId, ["Change", "Cancel"], {});
+ decide(turn, bot, entry, `${text(before)} → ${text(after)}`, "card-shown", requestId);
+ waiting(bot, turn.threadId, true);
+ deps.notify(buildNotification("approval", bot, turn.threadId, message.card!.subtitle, { avatarUrl: bot.avatarUrl }));
+ const outcome = await answer;
+ held.delete(requestId);
+ if (openByBot.get(bot.id) === requestId) openByBot.delete(bot.id);
+ waiting(bot, turn.threadId, false);
+ if (outcome.kind === "timeout") {
+ const stale = store.messagesFor(turn.threadId).find((candidate) => candidate.id === message.id);
+ if (stale?.card && !stale.card.answered) store.patchMessage(turn.threadId, stale.id, { card: { ...stale.card, answered: "unavailable", dismissed: true } });
+ return refuse(409, `Nobody answered the "${entry.label}" card in time, so nothing changed. ${NOT_RETRY}`);
+ }
+ if (outcome.kind === "denied") return refuse(409, `The user cancelled the change to ${entry.label}. ${NOT_RETRY}`);
+ if (outcome.kind === "failed") return refuse(409, `The user allowed it, but the change failed: ${outcome.error}`);
+ return reply(200, { text: outcome.text });
+ }
+
+ function waiting(bot: BotRecord, threadId: string, on: boolean) {
+ const group = deps.connectorThread(bot.id, threadId)?.group;
+ if (group) {
+ if (deps.activeGroupTurnForBot(bot.id)?.threadId === threadId && (on || turnWaitedOnPerson(store.bot(bot.id)))) store.setActivity(bot.id, on ? "waiting-on-you" : "working");
+ } else if (on ? store.taskByThread(bot.id, threadId)?.busy : turnWaitedOnPerson(store.taskByThread(bot.id, threadId))) {
+ store.setTaskActivity(bot.id, threadId, on ? "waiting-on-you" : "working");
+ }
+ }
+
+ function settleHold(requestId: string, outcome: Outcome) {
+ const entry = held.get(requestId);
+ if (!entry || entry.answered) return;
+ entry.answered = true;
+ clearTimeout(entry.timer);
+ entry.settle(outcome);
+ }
+
+ async function set(turn: Turn, body: Record<string, unknown>) {
+ const entry = typeof body.id === "string" ? byId.get(body.id) : undefined;
+ if (!entry) return refuse(404, `No setting with id ${JSON.stringify(body.id ?? null)}. Use action find first.`);
+ const bot = store.bot(turn.botId);
+ if (!bot) return refuse(404, "This bot no longer exists.");
+ if (entry.tier === "owner-only") return refuse(403, `${entry.label} is changed only by the owner, in ${entry.where}. Tell the user where to find it; do not try another way.`);
+ if (deps.guestDriven(turn.threadId) || deps.turnOwner(turn) === null) return refuse(403, "Settings change only in the owner's own conversation. This turn was not started by the owner here, so nothing changed; you may still read settings.");
+ if (entry.tier === "secret") {
+ if (body.value !== undefined) return refuse(400, `Never send a key or token as a value. Call set on ${entry.id} with no value: a secure card asks the user for it, and you never see it.`);
+ const budget = spendWrite(turn);
+ if (budget) return refuse(429, budget);
+ const posted = await deps.requestCredential(bot, turn.threadId, { credentialId: entry.credentialId, reason: typeof body.reason === "string" ? body.reason : undefined });
+ if (!posted.body.error && posted.body.alreadyConfigured === true) return reply(200, { text: `${entry.label} is already set. To replace it, the user changes it in ${entry.where}.` });
+ if (posted.status >= 300) return refuse(posted.status, String(posted.body.error ?? "The secure card could not be shown."));
+ return reply(200, { text: `A secure card for ${entry.label} is ready in MausBot. End this turn now and say in one line that you are waiting for it; MausBot resumes you when the user saves it or declines. You never see the key.` });
+ }
+ const parsed = entry.value.safeParse(body.value);
+ if (!parsed.success) return refuse(400, `${entry.label} takes ${entry.allowed}. ${parsed.error.issues.map((issue) => issue.message).join("; ")}`);
+ const budget = spendWrite(turn);
+ if (budget) return refuse(429, budget);
+ const before = entry.read();
+ return entry.tier === "safe" ? setSafe(turn, bot, entry, parsed.data, before) : setConfirm(turn, bot, entry, parsed.data, before);
+ }
+
+ return {
+ /** POST /api/internal/app-settings. */
+ async handle(body: Record<string, unknown>, turn: Turn): Promise<{ status: number; body: Record<string, unknown> }> {
+ if (body.action === "find") {
+ const query = typeof body.query === "string" ? body.query : "";
+ const hits = findSettings(entries, query, FIND_LIMIT).map(describe);
+ return reply(200, { text: hits.length ? JSON.stringify(hits) : `No setting matches ${JSON.stringify(query)}. Try other words, or tell the user it is not something bots can change.` });
+ }
+ if (body.action === "get") {
+ const entry = typeof body.id === "string" ? byId.get(body.id) : undefined;
+ if (!entry) return refuse(404, `No setting with id ${JSON.stringify(body.id ?? null)}. Use action find first.`);
+ return reply(200, { text: JSON.stringify({ ...describe(entry), help: entry.help, ...("allowed" in entry ? { allowed: entry.allowed } : {}),
+ change: entry.tier === "owner-only" ? `only the owner, in ${entry.where}` : entry.tier === "secret" ? "set with no value opens a secure card" : entry.tier === "confirm" ? "set shows the user a Change/Cancel card and waits" : "set applies at once, with Undo on the card" }) });
+ }
+ if (body.action === "set") return set(turn, body);
+ return refuse(400, "action must be find, get or set.");
+ },
+
+ /** The person's answer to a "Change X?" card; Allow counts only from an owner's review. */
+ resolveAndSend(res: ServerResponse, args: { threadId: string; requestId: string; behavior: string }, ownerReview: boolean): boolean {
+ const message = store.messagesFor(args.threadId).find((candidate) => candidate.card?.requestId === args.requestId && candidate.card.appSettingRequest);
+ const current = message?.card;
+ if (!message || !current) return false;
+ if (args.behavior === "allow" && !ownerReview) {
+ json(res, 403, { error: "Approve settings changes from the desktop app or a paired Full-access device. In a local browser, wait until every bot is idle." });
+ return true;
+ }
+ const hold = held.get(args.requestId);
+ if (!hold || hold.threadId !== args.threadId) {
+ if (!current.answered) store.patchMessage(args.threadId, message.id, { card: { ...current, answered: "unavailable", dismissed: true } });
+ json(res, 200, { ok: true, outcome: "unavailable" });
+ return true;
+ }
+ if (hold.answered) {
+ json(res, 200, { ok: true, outcome: "rejected", alreadySettled: true });
+ return true;
+ }
+ const allowed = args.behavior === "allow";
+ const bot = store.bot(hold.botId);
+ store.patchMessage(args.threadId, message.id, { card: { ...current, answered: allowed ? "allow" : "deny" } });
+ appendDecision(deps.dataDir, { threadId: args.threadId, requestId: args.requestId, botId: hold.botId, botName: bot?.name, tool: TOOL, summary: `${hold.entry.id}: ${current.subtitle}`, decision: allowed ? "user-approved" : "user-denied", source: "user" });
+ if (!allowed) {
+ settleHold(args.requestId, { kind: "denied" });
+ json(res, 200, { ok: true, outcome: "rejected" });
+ return true;
+ }
+ void apply(hold.entry, hold.value, hold.before).then((outcome) => {
+ if (outcome.kind === "applied") undoable.set(args.requestId, { entry: hold.entry, before: hold.earlier, after: hold.entry.read() });
+ settleHold(args.requestId, outcome);
+ });
+ json(res, 200, { ok: true, outcome: "allowed-once" });
+ return true;
+ },
+
+ /** Undo on an applied card: restores the value read before the change, unless it changed since. */
+ async undo(args: { threadId: string; requestId: string }): Promise<UndoResult> {
+ const message = store.messagesFor(args.threadId).find((candidate) => candidate.card?.requestId === args.requestId && candidate.card.appSettingRequest);
+ const current = message?.card;
+ if (!message || !current) return { claimed: false };
+ if (current.undone) return { claimed: true, state: "already_undone" };
+ const change = undoable.get(args.requestId);
+ if (!change || current.answered !== "allow") return { claimed: true, state: "invalid", error: "This change can't be undone here.", status: 409 };
+ if (change.entry.read() !== change.after) return { claimed: true, state: "invalid", error: UNDO_STALE, status: 409, stale: true };
+ const refusal = change.before === undefined ? "The earlier value is not one that can be set back." : await change.entry.write(change.before);
+ if (refusal) return { claimed: true, state: "invalid", error: refusal, status: 409 };
+ undoable.delete(args.requestId);
+ store.patchMessage(args.threadId, message.id, { card: { ...current, undone: true } });
+ return { claimed: true, state: "undone" };
+ },
+ };
+}
diff --git a/server/app-settings/registry.ts b/server/app-settings/registry.ts
new file mode 100644
index 0000000000..075ba8a675
--- /dev/null
+++ b/server/app-settings/registry.ts
@@ -0,0 +1,196 @@
+import { z } from "zod";
+
+import { credentialIsConfigured, CREDENTIAL_TARGETS, PROVIDER_CREDENTIAL_TARGETS, type CredentialConfig, type CredentialTargetId } from "../../shared/credential-request.ts";
+import { WINDOW_PREFS, type WindowPrefId } from "../../shared/app-settings.ts";
+import { MAX_CONCURRENT_BOT_THREADS } from "../bot-thread-limits.ts";
+import { MAX_MCP_CALL_TIMEOUT_MINUTES, MAX_ROOM_TURN_TIMEOUT_MINUTES, MIN_MCP_CALL_TIMEOUT_MINUTES, MIN_ROOM_TURN_TIMEOUT_MINUTES, type AppConfig } from "../config.ts";
+import type { BotRecord } from "../store.ts";
+
+/** Where the person changes it by hand, as the bot tells them. */
+type Where = "Settings → Appearance" | "Settings → General" | "Settings → AI" | "Settings → AI → API keys" | "Settings → You and your bots"
+ | "Settings → Phone & devices" | "Settings → Vault" | "Settings → Data" | "Settings → Your account" | "Settings → Desktops & browser" | "the sidebar" | "a bot's Settings";
+
+interface Base {
+ id: string;
+ label: string;
+ help: string;
+ where: Where;
+ synonyms: string[];
+ /** What a person or bot sees. Never a secret: a key reads as set or not set. */
+ read(): string;
+}
+/** `value` checks what the bot sends at the boundary; `current` is the typed value as `write` takes it, kept for Undo. */
+interface Writable {
+ tier: "safe" | "confirm";
+ value: z.ZodType;
+ allowed: string;
+ current(): unknown;
+ write(value: unknown): Promise<string | null>;
+}
+interface Secret {
+ tier: "secret";
+ credentialId: CredentialTargetId;
+}
+interface OwnerOnly {
+ tier: "owner-only";
+}
+export type SettingEntry = Base & (Writable | Secret | OwnerOnly);
+export type WritableEntry = Base & Writable;
+
+export interface RegistryDeps {
+ cfg(): AppConfig;
+ /** PUT /api/config as Settings does; a refusal comes back as its text. */
+ saveConfig(patch: Record<string, unknown>): Promise<string | null>;
+ bots(): BotRecord[];
+ sections(): string[];
+ reorderBots(botIds: string[]): Promise<string | null>;
+ /** Moves bots into a sidebar group, making it when new; an empty name ungroups them. */
+ groupBots(name: string, botIds: string[]): Promise<string | null>;
+ credentials(): CredentialConfig;
+ window: { read(id: WindowPrefId): unknown; write(id: WindowPrefId, value: unknown): string | null };
+}
+
+/** A setting's value for a person or bot; empty when unset, so each edge can say "not set" in its own words. */
+export const display = (value: unknown): string => (value === undefined || value === null || value === "" ? "" : typeof value === "string" ? value : JSON.stringify(value));
+const url = z.string().trim().max(2048).refine((text) => text === "" || /^https?:\/\/\S+$/.test(text), "an http(s) address, or empty to clear");
+
+const KEY_WHERE: Partial<Record<CredentialTargetId, Where>> = {
+ ttsKey: "Settings → General", geminiTtsKey: "Settings → General", fishAudioKey: "Settings → General",
+ onePasswordToken: "Settings → Vault", boxToken: "Settings → Desktops & browser", composioApiKey: "Settings → AI",
+};
+
+type WritableSpec = Omit<Base, "read"> & Omit<Writable, "write"> & { read?(): string; write(value: never): Promise<string | null> };
+
+export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {
+ const cfg = deps.cfg;
+ const names = (ids: readonly string[]) => ids.map((id) => deps.bots().find((bot) => bot.id === id)?.name ?? id).join(", ");
+ const writable = (spec: WritableSpec): SettingEntry => ({ ...spec, read: spec.read ?? (() => display(spec.current())), write: spec.write as Writable["write"] });
+ const config = <V,>(patch: (value: V) => Record<string, unknown>) => (value: V) => deps.saveConfig(patch(value));
+ const windowPref = (id: WindowPrefId, label: string, help: string, where: Where, synonyms: string[], allowed: string): SettingEntry =>
+ writable({ id, label, help, where, synonyms, tier: "safe", value: WINDOW_PREFS[id], allowed, current: () => deps.window.read(id), write: async (value: unknown) => deps.window.write(id, value) });
+ const enumOf = (values: readonly string[]) => values.join(", ");
+ const groups = () => Object.fromEntries(deps.sections().map((section) => [section, deps.bots().filter((bot) => bot.section === section).map((bot) => bot.id)]));
+
+ const safe: SettingEntry[] = [
+ windowPref("appearance.skin", "Skin", "The window's look; \"system\" follows the computer's light or dark mode.", "Settings → Appearance", ["theme", "dark mode", "light mode", "colors", "look"], enumOf(WINDOW_PREFS["appearance.skin"].options)),
+ windowPref("appearance.advanced", "Advanced mode", "Advanced shows every setting and tool; Simple keeps the everyday ones.", "Settings → Appearance", ["simple mode", "advanced mode", "interface mode"], "true or false"),
+ windowPref("appearance.font", "Font", "The app's typeface.", "Settings → Appearance", ["typeface", "typography"], enumOf(WINDOW_PREFS["appearance.font"].options)),
+ windowPref("appearance.chatWidth", "Chat width", "How wide the chat column is.", "Settings → Appearance", ["layout", "column", "wide"], enumOf(WINDOW_PREFS["appearance.chatWidth"].options)),
+ windowPref("general.sendKey", "Send key", "Which key sends a message in the composer.", "Settings → General", ["enter", "typing", "keyboard", "shortcut"], enumOf(WINDOW_PREFS["general.sendKey"].options)),
+ windowPref("general.notificationSounds", "Notification sounds", "Play a sound when a bot needs you or finishes.", "Settings → General", ["sound", "sounds", "mute", "alerts", "notifications"], "true or false"),
+ writable({
+ id: "general.language", label: "Language", help: "The app's language, as a tag such as en, de or pt-br; empty follows the computer.", where: "Settings → General",
+ synonyms: ["locale", "translation"], tier: "safe", value: z.string().trim().max(16).regex(/^[a-z]{2,3}(-[a-z0-9]{2,8})*$|^$/i, "a language tag such as en or pt-br"), allowed: "a language tag such as en, de, ja, pt-br, zh-tw; empty to follow the computer",
+ current: () => cfg().language ?? "", write: config((language: string) => ({ language })),
+ }),
+ writable({
+ id: "bots.order", label: "Bot order", help: "The order bots are listed in the sidebar and on phones. Send bot ids from list_bots; bots you leave out keep their places.", where: "the sidebar",
+ synonyms: ["reorder", "sidebar order", "sort bots", "move bot", "arrange"], tier: "safe", value: z.array(z.string().regex(/^[\w-]+$/)).min(1).max(100), allowed: "an array of bot ids in the wanted order",
+ current: () => deps.bots().map((bot) => bot.id), read: () => names(deps.bots().map((bot) => bot.id)), write: (botIds: string[]) => deps.reorderBots(botIds),
+ }),
+ writable({
+ id: "bots.groups", label: "Sidebar groups", help: "Which bots sit in which sidebar group (department). Send an object of group name to bot ids; a bot in no listed group is ungrouped.", where: "the sidebar",
+ synonyms: ["group", "groups", "department", "departments", "section", "sections", "team", "folder"], tier: "safe",
+ value: z.record(z.string().trim().min(1).max(60), z.array(z.string().regex(/^[\w-]+$/)).max(100)), allowed: "an object: group name → array of bot ids",
+ current: groups,
+ read: () => {
+ const grouped = Object.entries(groups()).map(([section, ids]) => `${section}: ${names(ids) || "(empty)"}`);
+ const loose = deps.bots().filter((bot) => !bot.section).map((bot) => bot.id);
+ return [...grouped, ...(loose.length ? [`ungrouped: ${names(loose)}`] : [])].join("; ");
+ },
+ write: async (wanted: Record<string, string[]>) => {
+ const listed = new Set(Object.values(wanted).flat());
+ const loosen = deps.bots().filter((bot) => bot.section && !listed.has(bot.id)).map((bot) => bot.id);
+ for (const [name, botIds] of Object.entries(wanted)) {
+ const refusal = await deps.groupBots(name, botIds);
+ if (refusal) return refusal;
+ }
+ return loosen.length ? deps.groupBots("", loosen) : null;
+ },
+ }),
+ writable({
+ id: "threads.maxConcurrentPerBot", label: "Threads per bot", help: "How many conversations one bot may work on at once.", where: "Settings → You and your bots",
+ synonyms: ["concurrent", "parallel", "limit", "limits", "thread limit"], tier: "safe", value: z.number().int().min(1).max(MAX_CONCURRENT_BOT_THREADS), allowed: `1 to ${MAX_CONCURRENT_BOT_THREADS}`,
+ current: () => cfg().threads?.maxConcurrentPerBot, write: config((maxConcurrentPerBot: number) => ({ threads: { maxConcurrentPerBot } })),
+ }),
+ writable({
+ id: "threads.eventLogRetentionDays", label: "Thread log retention", help: "Days a closed conversation's event logs are kept; null keeps them forever.", where: "Settings → Data",
+ synonyms: ["cleanup", "clean up", "retention", "logs", "delete old", "storage"], tier: "safe", value: z.number().int().min(1).max(3650).nullable(), allowed: "1 to 3650 days, or null to keep forever",
+ current: () => cfg().threads?.eventLogRetentionDays ?? null, read: () => display(cfg().threads?.eventLogRetentionDays ?? "forever"),
+ write: config((eventLogRetentionDays: number | null) => ({ threads: { eventLogRetentionDays } })),
+ }),
+ writable({
+ id: "rooms.turnTimeoutMinutes", label: "Room turn timeout", help: "Minutes a bot's turn in a room may run before it is stopped.", where: "Settings → You and your bots",
+ synonyms: ["room", "channel", "timeout", "turn limit"], tier: "safe", value: z.number().int().min(MIN_ROOM_TURN_TIMEOUT_MINUTES).max(MAX_ROOM_TURN_TIMEOUT_MINUTES), allowed: `${MIN_ROOM_TURN_TIMEOUT_MINUTES} to ${MAX_ROOM_TURN_TIMEOUT_MINUTES} minutes`,
+ current: () => cfg().rooms?.turnTimeoutMinutes, write: config((turnTimeoutMinutes: number) => ({ rooms: { turnTimeoutMinutes } })),
+ }),
+ writable({
+ id: "mcp.callTimeoutMinutes", label: "MCP call timeout", help: "Minutes one MCP tool call may run.", where: "Settings → AI",
+ synonyms: ["mcp", "tool timeout", "call timeout"], tier: "safe", value: z.number().int().min(MIN_MCP_CALL_TIMEOUT_MINUTES).max(MAX_MCP_CALL_TIMEOUT_MINUTES), allowed: `${MIN_MCP_CALL_TIMEOUT_MINUTES} to ${MAX_MCP_CALL_TIMEOUT_MINUTES} minutes`,
+ current: () => cfg().mcp?.callTimeoutMinutes, write: config((callTimeoutMinutes: number) => ({ mcp: { callTimeoutMinutes } })),
+ }),
+ writable({
+ id: "bots.defaultModel", label: "Default model for new bots", help: "The engine and model a newly created bot starts on; existing bots keep theirs. Ids come from list_models.", where: "Settings → You and your bots",
+ synonyms: ["default model", "new bots", "model", "engine"], tier: "safe", value: z.object({ instanceId: z.string().min(1).max(80), model: z.string().min(1).max(200) }), allowed: "{ instanceId, model } from list_models",
+ current: () => cfg().defaultModelSelection, read: () => { const selection = cfg().defaultModelSelection; return selection ? `${selection.instanceId} / ${selection.model}` : ""; },
+ write: config((defaultModelSelection: { instanceId: string; model: string }) => ({ defaultModelSelection })),
+ }),
+ ];
+
+ const provider = (id: string, label: string, synonyms: string[], current: () => string | undefined, patch: (text: string) => Record<string, unknown>): SettingEntry => writable({
+ id, label, help: `${label}: the address MausBot sends requests to. Empty uses the provider's own.`, where: "Settings → AI", synonyms: [...synonyms, "url", "base url", "endpoint", "address", "proxy"],
+ tier: "confirm", value: url, allowed: "an http(s) address, or empty to clear", current: () => current() ?? "", write: config(patch),
+ });
+ const confirm: SettingEntry[] = [
+ provider("providers.anthropic.url", "Anthropic address", ["anthropic", "claude"], () => cfg().anthropic?.url, (text) => ({ anthropic: { ...cfg().anthropic, url: text } })),
+ provider("providers.xai.url", "xAI address", ["xai", "grok"], () => cfg().xai?.url, (text) => ({ xai: { ...cfg().xai, url: text } })),
+ provider("providers.groq.url", "Groq address", ["groq"], () => cfg().groq?.url, (text) => ({ groq: { ...cfg().groq, url: text } })),
+ provider("providers.meta.url", "Meta address", ["meta", "llama"], () => cfg().meta?.url, (text) => ({ meta: { ...cfg().meta, url: text } })),
+ provider("providers.openaiCompat.url", "OpenAI-compatible address", ["openai compatible", "custom provider", "ollama", "lm studio", "openrouter"], () => cfg().openaiCompat?.url, (text) => ({ openaiCompat: { ...cfg().openaiCompat, url: text } })),
+ writable({
+ id: "providers.openaiCompat.model", label: "OpenAI-compatible model", help: "The model name sent to the OpenAI-compatible provider.", where: "Settings → AI",
+ synonyms: ["openai compatible", "custom provider", "model name"], tier: "confirm", value: z.string().trim().max(200), allowed: "a model name, or empty to clear",
+ current: () => cfg().openaiCompat?.model ?? "", write: config((model: string) => ({ openaiCompat: { ...cfg().openaiCompat, model } })),
+ }),
+ provider("voice.baseUrl", "Voice server address", ["tts", "voice", "speech", "chatterbox"], () => cfg().tts?.baseUrl, (text) => ({ tts: { ...cfg().tts, baseUrl: text } })),
+ ];
+
+ const secret: SettingEntry[] = (Object.keys(CREDENTIAL_TARGETS) as CredentialTargetId[]).map((credentialId) => {
+ const target = CREDENTIAL_TARGETS[credentialId];
+ return {
+ id: `keys.${credentialId}`, label: target.label, help: target.description, synonyms: ["key", "api key", "token", "credential", target.label.split(" ")[0]!.toLowerCase()],
+ where: KEY_WHERE[credentialId] ?? ((PROVIDER_CREDENTIAL_TARGETS as readonly string[]).includes(credentialId) ? "Settings → AI → API keys" : "Settings → AI"),
+ tier: "secret", credentialId, read: () => (credentialIsConfigured(deps.credentials(), credentialId) ? "set" : ""),
+ };
+ });
+
+ const ownerOnly = (id: string, label: string, help: string, where: Where, synonyms: string[], read: () => string): SettingEntry => ({ id, label, help, where, synonyms, tier: "owner-only", read });
+ const owner: SettingEntry[] = [
+ ownerOnly("bots.approvalModes", "Approval modes", "What each bot may do without asking (Ask, Approve for me, Full access).", "a bot's Settings", ["permissions", "full access", "approve", "ask", "approval", "autonomy"],
+ () => deps.bots().map((bot) => `${bot.name}: ${bot.approvalMode}`).join("; ")),
+ ownerOnly("remote.access", "Remote access", "How phones and other devices reach this computer (local network, tunnel, Tailscale or a public address).", "Settings → Phone & devices", ["remote", "tunnel", "tailscale", "public url", "phone", "pair", "relay"],
+ () => display(cfg().cliStartup?.access ?? "local")),
+ ownerOnly("cloud.account", "MausBot Cloud account", "The account this app is signed in with, and its plan.", "Settings → Your account", ["account", "sign in", "sign out", "plan", "billing", "subscription"], () => "managed in Settings"),
+ ownerOnly("vault.logins", "Vault and logins", "Saved website logins and secrets bots may use.", "Settings → Vault", ["vault", "password", "passwords", "login", "logins", "1password"], () => "managed in Settings"),
+ ownerOnly("data.backups", "Backups", "Backing up and restoring this app's data.", "Settings → Data", ["backup", "backups", "restore", "export", "import"], () => "managed in Settings"),
+ ownerOnly("computer.sharing", "Computer sharing", "Lending this computer to other places and people.", "Settings → Desktops & browser", ["share computer", "lend", "lending", "shared computers", "desktop"], () => "managed in Settings"),
+ ];
+
+ return [...safe, ...confirm, ...secret, ...owner];
+}
+
+/** Up to `limit` entries whose id, label, help or synonyms carry a word of the query, best first. */
+export function findSettings(entries: readonly SettingEntry[], query: string, limit = 8): SettingEntry[] {
+ const words = query.toLowerCase().split(/[^a-z0-9.-]+/).filter((word) => word.length > 1);
+ if (!words.length) return [];
+ const phrase = words.join(" ");
+ const scored = entries.map((entry) => {
+ const label = entry.label.toLowerCase(), id = entry.id.toLowerCase();
+ const synonyms = entry.synonyms.map((synonym) => synonym.toLowerCase());
+ const loose = [entry.help, ...synonyms].join(" ").toLowerCase();
+ const whole = id === phrase || label === phrase || synonyms.includes(phrase) ? 10 : 0;
+ const score = words.reduce((sum, word) => sum + (id === word || label === word ? 6 : label.includes(word) || id.includes(word) ? 3 : loose.includes(word) ? 1 : 0), whole);
+ return { entry, score };
+ }).filter((hit) => hit.score > 0).sort((a, b) => b.score - a.score);
+ return scored.slice(0, limit).map((hit) => hit.entry);
+}
diff --git a/server/decision-log.ts b/server/decision-log.ts
index 8cf0887882..bea0cd4822 100644
--- a/server/decision-log.ts
+++ b/server/decision-log.ts
@@ -40,6 +40,7 @@ export type DecisionSource =
| "outbound"
| "team-memory"
| "outside-write"
+ | "app-settings"
| "auto-review"
| "auto-review-shadow";
diff --git a/server/routes/app-settings.ts b/server/routes/app-settings.ts
new file mode 100644
index 0000000000..04feb58063
--- /dev/null
+++ b/server/routes/app-settings.ts
@@ -0,0 +1,45 @@
+import { isWindowPrefId, WINDOW_PREFS, windowPrefReportSchema, type WindowPrefId } from "../../shared/app-settings.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
+
+export const INTERNAL_APP_SETTINGS_PATH = "/api/internal/app-settings";
+export const WINDOW_PREFS_PATH = "/api/window-prefs";
+
+/** Only dispatch inside the internal capability gate, with its guarded body reader; never in the global route table. */
+export function createInternalAppSettingsRoutes(deps: {
+ readBody(): ReturnType<RouteContext["readBody"]>;
+ handle(body: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }>;
+}): RouteHandler {
+ return async ({ res, path, method, json }) => {
+ if (method !== "POST" || path !== INTERNAL_APP_SETTINGS_PATH) return PASS;
+ const result = await deps.handle(await deps.readBody());
+ return json(res, result.status, result.body);
+ };
+}
+
+/** The window's own preferences (skin, Simple or Advanced, font, chat width, send key, sounds) live in its
+ * localStorage. The window reports them here; the server keeps the last report and pushes a change back as a
+ * `window-pref` frame. Nothing is reported until a window has, so `set` can tell the bot to open the app first. */
+export function createWindowPrefs(deps: { broadcast(frame: Record<string, unknown>, options: { adminOnly: true }): void; ownerOrAdmin(auth: RequestAuth): boolean }) {
+ const values = new Map<WindowPrefId, unknown>();
+ const routes: RouteHandler = async ({ req, res, path, method, auth, json, readBody }) => {
+ if (method !== "PUT" || path !== WINDOW_PREFS_PATH) return PASS;
+ if (!deps.ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner's window reports its preferences." });
+ const parsed = windowPrefReportSchema.safeParse(await readBody(req));
+ if (!parsed.success) return json(res, 400, { error: "values must be an object of preference id to value" });
+ for (const [id, value] of Object.entries(parsed.data.values)) {
+ if (isWindowPrefId(id) && WINDOW_PREFS[id].safeParse(value).success) values.set(id, value);
+ }
+ return json(res, 200, { ok: true });
+ };
+ return {
+ routes,
+ read: (id: WindowPrefId) => values.get(id),
+ write(id: WindowPrefId, value: unknown): string | null {
+ if (!values.size) return "Open MausBot on this computer first: this preference lives in the app window.";
+ values.set(id, value);
+ deps.broadcast({ kind: "window-pref", id, value }, { adminOnly: true });
+ return null;
+ },
+ };
+}
diff --git a/server/routes/call-route.test.ts b/server/routes/call-route.test.ts
new file mode 100644
index 0000000000..0338fa8dec
--- /dev/null
+++ b/server/routes/call-route.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import type { RequestAuth } from "../request-auth.ts";
+import { createBotOrderRoutes } from "./bot-order.ts";
+import { callRoute } from "./call-route.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+const auth: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
+
+describe("callRoute", () => {
+ it("runs a real route with the given body and returns what it wrote", async () => {
+ const bots = [{ id: "a" }, { id: "b" }];
+ const route = createBotOrderRoutes({
+ store: { bot: (id) => bots.find((bot) => bot.id === id) as never, bots: bots as never, reorderBots: (ids) => { bots.sort((x, y) => ids.indexOf(x.id) - ids.indexOf(y.id)); return bots as never; } },
+ visibleFor: () => ({ bot: () => true }) as never,
+ });
+ expect(await callRoute(route, { method: "PUT", path: "/api/bots/order", body: { botIds: ["b", "a"] }, auth })).toEqual({ status: 200, body: { botIds: ["b", "a"] } });
+ expect(bots.map((bot) => bot.id)).toEqual(["b", "a"]);
+ expect(await callRoute(route, { method: "PUT", path: "/api/bots/order", body: { botIds: [] }, auth })).toMatchObject({ status: 400 });
+ });
+
+ it("reports a route that declines or answers nothing", async () => {
+ const declines: RouteHandler = async () => PASS;
+ expect(await callRoute(declines, { method: "GET", path: "/api/nothing", auth })).toMatchObject({ status: 404 });
+ const silent: RouteHandler = async () => undefined;
+ expect(await callRoute(silent, { method: "GET", path: "/api/quiet?x=1", auth })).toMatchObject({ status: 500 });
+ });
+});
diff --git a/server/routes/call-route.ts b/server/routes/call-route.ts
new file mode 100644
index 0000000000..c5a9411818
--- /dev/null
+++ b/server/routes/call-route.ts
@@ -0,0 +1,31 @@
+import type { IncomingMessage, ServerResponse } from "node:http";
+
+import type { RequestAuth } from "../request-auth.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+export interface RouteCall {
+ method: string;
+ path: string;
+ body?: unknown;
+ auth: RequestAuth;
+}
+
+export interface RouteReply {
+ status: number;
+ body: Record<string, unknown>;
+}
+
+/** Runs a route handler as the app's own window would call it, so a change made from a chat gets the same checks, side
+ * effects and broadcasts as Settings, and the caller reads the reply the route wrote. */
+export async function callRoute(route: RouteHandler, call: RouteCall): Promise<RouteReply> {
+ let reply: RouteReply | null = null;
+ const url = new URL(call.path, "http://127.0.0.1");
+ const res = { headersSent: false, writableEnded: false } as ServerResponse;
+ const out = await route({
+ req: {} as IncomingMessage, res, url, path: url.pathname, method: call.method, auth: call.auth,
+ json: (_res, status, body) => { reply = { status, body: (body ?? {}) as Record<string, unknown> }; },
+ readBody: async () => call.body,
+ });
+ if (reply) return reply;
+ return out === PASS ? { status: 404, body: { error: `no route for ${call.method} ${call.path}` } } : { status: 500, body: { error: "the route sent no reply" } };
+}
diff --git a/shared/app-settings.ts b/shared/app-settings.ts
new file mode 100644
index 0000000000..5883ac6a1d
--- /dev/null
+++ b/shared/app-settings.ts
@@ -0,0 +1,57 @@
+// The app_settings tool's wire shapes: a setting's tier (the whole policy), the card a change rides on, and the
+// preferences that live in the window's localStorage, which the server reaches through an SSE frame.
+import { z } from "zod";
+
+export type SettingTier = "safe" | "confirm" | "secret" | "owner-only";
+
+/** On a card: display values only, never a key. */
+export interface AppSettingRequest {
+ settingId: string;
+ label: string;
+ before?: string;
+ after: string;
+ tier: SettingTier;
+}
+
+export const SKIN_IDS = [
+ "midnight",
+ "atelier",
+ "foundry",
+ "lagoon",
+ "graphite",
+ "linen",
+ "dusk",
+ "daylight",
+ "meadow",
+ "pop",
+ "halloween",
+ "diwali",
+ "aurora",
+] as const;
+export const FONT_IDS = ["skin", "system", "inter", "poppins", "serif"] as const;
+export const CHAT_WIDTH_IDS = ["standard", "wide", "full"] as const;
+/** The Enter-adds-a-line modes are for input methods that confirm a conversion with Enter (Japanese). */
+export const SEND_KEYS = ["enter", "shift-enter", "mod-enter"] as const;
+
+/** Preferences kept in the window, by setting id; the renderer applies a frame with the matching setter. */
+export const WINDOW_PREFS = {
+ "appearance.skin": z.enum([...SKIN_IDS, "system"]),
+ "appearance.advanced": z.boolean(),
+ "appearance.font": z.enum(FONT_IDS),
+ "appearance.chatWidth": z.enum(CHAT_WIDTH_IDS),
+ "general.sendKey": z.enum(SEND_KEYS),
+ "general.notificationSounds": z.boolean(),
+} as const;
+export type WindowPrefId = keyof typeof WINDOW_PREFS;
+export type WindowPrefValue<I extends WindowPrefId> = z.infer<(typeof WINDOW_PREFS)[I]>;
+export const WINDOW_PREF_IDS = Object.keys(WINDOW_PREFS) as WindowPrefId[];
+export const isWindowPrefId = (id: string): id is WindowPrefId => Object.hasOwn(WINDOW_PREFS, id);
+
+export interface WindowPrefFrame {
+ kind: "window-pref";
+ id: WindowPrefId;
+ value: unknown;
+}
+
+/** What the window reports as its current values (PUT /api/window-prefs). */
+export const windowPrefReportSchema = z.object({ values: z.record(z.string(), z.unknown()) }).strict();
diff --git a/shared/wire.ts b/shared/wire.ts
index 290d8576c9..90e3dd2f96 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -21,6 +21,7 @@ import type { ServerTextLine, ServerTextParams } from "./server-text.ts";
import type { WireTool } from "./wire-tool.ts";
import type { ModelRequestCardData } from "./model-request.ts";
import type { ConnectorCardData } from "./connector-card.ts"; import type { McpChangeRequest } from "./mcp-request.ts";
+import type { AppSettingRequest, WindowPrefFrame } from "./app-settings.ts";
import type { SkillRequestCardData } from "./skill-request.ts"; import type { OutsideWriteCardField } from "./outside-write.ts";
import type { QuestionRequestCardData } from "./ask-question.ts";
import type { AutomationLine, RoutineRunCardData } from "./routine-run.ts";
@@ -703,6 +704,8 @@ export interface OptionCardData extends WaitCardField, ComputerAskField, AccessR
teamSetupRequest?: TeamSetupRequest;
/** A bot's MCP server change waiting on the person (Ask, Edits or Auto). */
mcpRequest?: McpChangeRequest;
+ /** A bot's change to one of the app's own settings: applied with Undo, or waiting on Change/Cancel. */
+ appSettingRequest?: AppSettingRequest;
/** A durable learned-skill proposal. */
skillRequest?: SkillRequestCardData;
/** A provider's structured question set. */
@@ -991,6 +994,7 @@ export type ServerFrame =
| { kind: "bot.deleted"; botId: string }
/** The whole fleet in its new order (PUT /api/bots/order); a member is sent only the bots they see. */
| { kind: "bots.order"; botIds: string[] }
+ | WindowPrefFrame
| { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }
/** A job is waiting for the phone whose registry key this is; it polls now. */
| { kind: "device.job"; phone: string; id: string }
diff --git a/src/lib/chat-width.ts b/src/lib/chat-width.ts
index 9383f1fc37..3b40226625 100644
--- a/src/lib/chat-width.ts
+++ b/src/lib/chat-width.ts
@@ -1,4 +1,6 @@
-export const CHAT_WIDTH_IDS = ["standard", "wide", "full"] as const;
+import { CHAT_WIDTH_IDS } from "../../shared/app-settings";
+
+export { CHAT_WIDTH_IDS };
export type ChatWidthId = (typeof CHAT_WIDTH_IDS)[number];
export const DEFAULT_CHAT_WIDTH: ChatWidthId = "standard";
diff --git a/src/lib/fonts.ts b/src/lib/fonts.ts
index 1ff9a6b0c6..b103690a13 100644
--- a/src/lib/fonts.ts
+++ b/src/lib/fonts.ts
@@ -1,4 +1,6 @@
-export const FONT_IDS = ["skin", "system", "inter", "poppins", "serif"] as const;
+import { FONT_IDS } from "../../shared/app-settings";
+
+export { FONT_IDS };
export type FontId = (typeof FONT_IDS)[number];
export const DEFAULT_FONT: FontId = "skin";
diff --git a/src/lib/send-key.ts b/src/lib/send-key.ts
index 2f49bbeedc..fde4c48a67 100644
--- a/src/lib/send-key.ts
+++ b/src/lib/send-key.ts
@@ -1,12 +1,12 @@
import { useSyncExternalStore } from "react";
+import { SEND_KEYS } from "../../shared/app-settings";
import { activeLocale } from "./i18n";
import { isMacPlatform } from "./keyboard-shortcuts";
export const SEND_KEY_KEY = "omb-send-key";
-/** The Enter-adds-a-line modes are for input methods that confirm a conversion with Enter (Japanese). */
-export const SEND_KEYS = ["enter", "shift-enter", "mod-enter"] as const;
+export { SEND_KEYS };
export type SendKey = (typeof SEND_KEYS)[number];
export function defaultSendKey(locale: string = activeLocale()): SendKey {
diff --git a/src/lib/skins.ts b/src/lib/skins.ts
index 54f906604e..d660e65379 100644
--- a/src/lib/skins.ts
+++ b/src/lib/skins.ts
@@ -1,21 +1,8 @@
+import { SKIN_IDS } from "../../shared/app-settings";
import { paintAuroraField } from "./aurora-field";
import { hasPriorRun } from "./prior-run";
-export const SKIN_IDS = [
- "midnight",
- "atelier",
- "foundry",
- "lagoon",
- "graphite",
- "linen",
- "dusk",
- "daylight",
- "meadow",
- "pop",
- "halloween",
- "diwali",
- "aurora",
-] as const;
+export { SKIN_IDS };
export type SkinId = (typeof SKIN_IDS)[number];
export type Skin = {
diff --git a/src/locales/de.json b/src/locales/de.json
index 2ccdf09135..957592a35c 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -147,6 +147,8 @@
"server.mcp.testFailed": "Test: fehlgeschlagen",
"server.mcp.askedTurnOn": "Einschalten von MCP-Server {name} angefragt",
"server.mcp.askedChange": "Änderung von MCP-Server {name} angefragt",
+ "server.appSettings.change": "{label} ändern?",
+ "server.appSettings.notSet": "nicht gesetzt",
"server.mcp.askedRemove": "Entfernen von MCP-Server {name} angefragt",
"server.mcp.card.turnOn": "{name} einschalten?",
"server.mcp.card.change": "{name} ändern?",
diff --git a/src/locales/en.json b/src/locales/en.json
index bf963b7654..62db401f14 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -279,6 +279,8 @@
"server.mcp.testFailed": "Test: failed",
"server.mcp.askedTurnOn": "Asked to turn on MCP server {name}",
"server.mcp.askedChange": "Asked to change MCP server {name}",
+ "server.appSettings.change": "Change {label}?",
+ "server.appSettings.notSet": "not set",
"server.mcp.askedRemove": "Asked to remove MCP server {name}",
"server.mcp.card.turnOn": "Turn on {name}?",
"server.mcp.card.change": "Change {name}?",