Skip to content

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

app_settings: every remaining setting, each on a Change/Cancel card

aivsomkar2d5a53925f80
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.ts
index 558d1e515c..16e96299fd 100644
--- a/server/app-settings/host.test.ts
+++ b/server/app-settings/host.test.ts
@@ -24,12 +24,14 @@ function fixture(options: { owner?: boolean; guest?: boolean; group?: boolean; w
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,
+ { id: "kiwi", name: "Kiwi", color: "green", threadId: "t-kiwi", approvalMode: "full", section: "Sales", modelSelection: { instanceId: "claude", model: "opus" } } as unknown as BotRecord,
+ { id: "clive", name: "Clive", color: "blue", threadId: "t-clive", approvalMode: "ask", modelSelection: { instanceId: "claude", model: "sonnet" } } 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" },
instances: { "openai-compat-gw": { driver: "openai-compat", displayName: "Gateway", config: { key: GATEWAY_KEY, url: "https://gw.example/v1" } } } } as unknown as AppConfig;
const engineCalls: unknown[] = [];
+ const botPatches: Array<{ botId: string; body: Record<string, unknown> }> = [];
+ const routeCalls: unknown[] = [];
const chosen = new Set<string>(options.chosen ?? []);
const saved: Record<string, unknown>[] = [];
const messages: Array<Record<string, any>> = [];
@@ -63,6 +65,8 @@ function fixture(options: { owner?: boolean; guest?: boolean; group?: boolean; w
bots: () => bots,
sections: () => ["Sales"],
reorderBots: async (botIds) => { bots.sort((a, b) => botIds.indexOf(a.id) - botIds.indexOf(b.id)); return null; },
+ patchBot: async (botId, body) => { botPatches.push({ botId, body }); Object.assign(bots.find((bot) => bot.id === botId)!, body); return null; },
+ call: async (route, method, path, body) => { routeCalls.push({ route, method, path, body }); return null; },
pinBot: async (botId, pinned) => { (bots.find((bot) => bot.id === botId) as { pinned?: boolean }).pinned = pinned || undefined; 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,
@@ -95,7 +99,7 @@ function fixture(options: { owner?: boolean; guest?: boolean; group?: boolean; w
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, engineCalls };
+ return { host, cfg, saved, messages, cards, credentialCards, notified, windowValues, bots, turn, set, answer, dataDir, engineCalls, botPatches, routeCalls };
}
describe("reads", () => {
@@ -400,13 +404,114 @@ describe("secret tier", () => {
});
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);
+ it("explains and refuses with where to change it: sign-in, logins, pairing, backups", async () => {
+ const { host, set, turn, cards } = fixture();
+ const got = await host.handle({ action: "get", id: "vault.logins" }, turn);
+ expect(JSON.parse(String(got.body.text))).toMatchObject({ tier: "owner-only", change: "only the owner, in Settings → Vault" });
+ for (const id of ["cloud.account", "vault.logins", "phone.pairing", "data.backups"]) {
+ const refused = await set(id, "on");
+ expect(refused.status, id).toBe(403);
+ expect(refused.body.error, id).toContain("is changed only by the owner");
+ }
+ expect(cards()).toEqual([]);
+ });
+});
+
+describe("every other setting, on a Change card", () => {
+ /** Starts a set and returns its waiting card. */
+ const carded = async (fx: ReturnType<typeof fixture>, id: string, value: unknown) => {
+ const pending = fx.set(id, typeof value === "string" ? value : JSON.stringify(value));
+ await vi.waitFor(() => expect(fx.cards().filter((card) => !card.card.answered)).toHaveLength(1));
+ return { pending, card: fx.cards().at(-1)!.card };
+ };
+ const written = (fx: ReturnType<typeof fixture>) => JSON.stringify([fx.botPatches, fx.saved, fx.routeCalls, [...fx.windowValues]]);
+
+ it.each([
+ ["a bot's own setting", "bots.name", { botId: "clive", name: "Clover" }, "Rename Clive to \"Clover\"", (fx: ReturnType<typeof fixture>) => expect(fx.botPatches).toEqual([{ botId: "clive", body: { name: "Clover" } }])],
+ ["a server setting", "profile.name", "Ada", "not set → Ada", (fx: ReturnType<typeof fixture>) => expect(fx.saved).toEqual([{ profile: { name: "Ada" } }])],
+ ["another Settings route", "remote.domain", "bots.example.com", "Serve this place at bots.example.com (checked live), and give it in new pairing links",
+ (fx: ReturnType<typeof fixture>) => expect(fx.routeCalls).toEqual([{ route: "customDomain", method: "POST", path: "/api/settings/custom-domain", body: { domain: "bots.example.com" } }])],
+ ["a window preference", "remote.relay", true, "Let your paired phones reach this computer from anywhere, through MausBot's relay", (fx: ReturnType<typeof fixture>) => expect(fx.windowValues.get("remote.relay")).toBe(true)],
+ ])("%s waits on its card: Cancel writes nothing, and only the owner's Change writes it", async (_kind, id, value, subtitle, check) => {
+ const fx = fixture();
+ const before = written(fx);
+ const cancelled = await carded(fx, id, value);
+ expect(cancelled.card).toMatchObject({ options: ["Change", "Cancel"], subtitle, appSettingRequest: { settingId: id, tier: "confirm" } });
+ expect(fx.answer(String(cancelled.card.requestId), "allow", false).sent).toMatchObject({ status: 403 });
+ fx.answer(String(cancelled.card.requestId), "deny");
+ expect((await cancelled.pending).body.error).toContain("cancelled");
+ expect(written(fx)).toBe(before);
+ const changed = await carded(fx, id, value);
+ expect(written(fx)).toBe(before);
+ fx.answer(String(changed.card.requestId), "allow");
+ expect((await changed.pending).status).toBe(200);
+ check(fx);
+ });
+
+ it("an approval mode change says what it allows, at Full access too, and a loopback Allow can't approve it", async () => {
+ const fx = fixture();
+ const got = JSON.parse(String((await fx.host.handle({ action: "get", id: "bots.approvalModes" }, fx.turn)).body.text));
+ expect(got).toMatchObject({ tier: "confirm", value: "Kiwi: Full access; Clive: Ask for approval" });
+ const { pending, card } = await carded(fx, "bots.approvalModes", { botId: "clive", mode: "full" });
+ expect(card.subtitle).toBe("Let Clive act without asking (Full access)");
+ expect(fx.answer(String(card.requestId), "allow", false).sent).toMatchObject({ status: 403 });
+ expect(fx.botPatches).toEqual([]);
+ fx.answer(String(card.requestId), "allow");
+ expect((await pending).status).toBe(200);
+ expect(fx.botPatches).toEqual([{ botId: "clive", body: { approvalMode: "full", applyToAllThreads: true } }]);
+ });
+
+ it("refuses before any card an unknown bot, an invalid mode, Custom, and Approve for me on this computer's own desktop", async () => {
+ const fx = fixture();
+ expect((await fx.set("bots.approvalModes", JSON.stringify({ botId: "ghost", mode: "ask" })))).toMatchObject({ status: 409, body: { error: "No bot has the id ghost. Use list_bots for the ids." } });
+ expect((await fx.set("bots.name", JSON.stringify({ botId: "ghost", name: "Boo" }))).status).toBe(409);
+ expect((await fx.set("bots.approvalModes", JSON.stringify({ botId: "clive", mode: "custom" }))).status).toBe(400);
+ (fx.bots[1] as { computer?: string }).computer = "local";
+ expect((await fx.set("bots.approvalModes", JSON.stringify({ botId: "clive", mode: "auto" }))).body.error).toMatch(/needs a warning only Clive's Settings shows/);
+ expect((await fx.set("bots.model", JSON.stringify({ botId: "clive", instanceId: "nowhere", model: "x" }))).body.error).toContain("No engine has the id nowhere");
+ expect(fx.cards()).toEqual([]);
+ expect(fx.botPatches).toEqual([]);
+ });
+
+ it("never takes a key or token in a value", async () => {
+ const fx = fixture();
+ for (const [id, value] of [["bots.settings", { botId: "kiwi", apiKey: OPENAI_KEY }], ["ai.routing", { enabled: true, openrouterKey: OPENAI_KEY }], ["ai.images", { key: OPENAI_KEY }]] as const) {
+ const refused = await fx.set(id, JSON.stringify(value));
+ expect(refused.status, id).toBe(400);
+ expect(refused.body.error, id).toContain("Never put a key or token in the value");
+ }
+ expect(fx.cards()).toEqual([]);
+ expect(JSON.stringify(fx.messages)).not.toContain(OPENAI_KEY);
+ });
+
+ it("a window preference on a card is refused while no window is open, before any card", async () => {
+ const fx = fixture({ window: false });
+ const pending = fx.set("general.openAtLogin", true);
+ await vi.waitFor(() => expect(fx.cards()).toHaveLength(1));
+ expect(fx.cards()[0]!.card.subtitle).toBe("Open MausBot when you log in");
+ fx.answer(String(fx.cards()[0]!.card.requestId), "allow");
+ expect((await pending).body.error).toContain("Open MausBot on this computer first");
+ expect(fx.windowValues.size).toBe(0);
+ });
+
+ it("a browser profile is added on a card naming whose browser it uses, and never removed by a bot", async () => {
+ const fx = fixture();
+ (fx.cfg as { browserProfiles?: unknown }).browserProfiles = [{ id: "work", name: "Work" }];
+ expect((await fx.set("desktops.browserProfiles", JSON.stringify([]))).body.error).toMatch(/^Removing the browser profile "Work" deletes its saved logins/);
+ expect(fx.cards()).toEqual([]);
+ const { pending, card } = await carded(fx, "desktops.browserProfiles", [{ id: "work", name: "Work" }, { name: "Mine", browser: "chrome" }]);
+ expect(card.subtitle).toBe("Browser profiles: add the profile \"Mine\" on your own running Chrome, with its logins");
+ fx.answer(String(card.requestId), "allow");
+ await pending;
+ expect(fx.saved).toEqual([{ browserProfiles: [{ id: "work", name: "Work" }, { id: expect.stringMatching(/^profile-[0-9a-f]{32}$/), name: "Mine", browser: "chrome" }], expectedBrowserProfiles: [{ id: "work", name: "Work" }] }]);
+ });
+
+ it("other bot settings name each change, and a computer change says what it hands over", async () => {
+ const fx = fixture();
+ const { pending, card } = await carded(fx, "bots.settings", { botId: "kiwi", memoryEnabled: false, computer: "local" });
+ expect(card.subtitle).toBe("Kiwi: memory off; computer use this computer's own desktop, as you");
+ fx.answer(String(card.requestId), "allow");
+ await pending;
+ expect(fx.botPatches).toEqual([{ botId: "kiwi", body: { memoryEnabled: false, computer: "local" } }]);
});
});
diff --git a/server/app-settings/registry-bots.ts b/server/app-settings/registry-bots.ts
new file mode 100644
index 0000000000..563d75ec37
--- /dev/null
+++ b/server/app-settings/registry-bots.ts
@@ -0,0 +1,129 @@
+// One bot's own settings, as its Settings panel edits them: every change is a Change/Cancel card naming the bot and the
+// exact effect, written through PATCH /api/bots/:id so that route's checks still run.
+import { z } from "zod";
+
+import { approvalModeFor, type ApprovalMode } from "../../shared/approval-mode.ts";
+import { BOT_PROFILE_LIMITS } from "../../shared/bot-profile.ts";
+import { EFFORT_LEVELS, MAUS_COLOR_NAMES } from "../../shared/wire.ts";
+import type { BotRecord } from "../store.ts";
+import { withoutKeys, type RegistryDeps, type SettingEntry, type WritableSpec } from "./registry.ts";
+
+const botId = z.string().regex(/^[\w-]{1,120}$/);
+const forBot = <S extends z.ZodRawShape>(shape: S) => withoutKeys(z.object({ botId, ...shape }).strict());
+
+const APPROVAL: Record<Exclude<ApprovalMode, "custom">, { label: string; effect: (name: string) => string }> = {
+ ask: { label: "Ask for approval", effect: (name) => `Make ${name} ask you before each command or file change` },
+ edits: { label: "Auto-accept edits", effect: (name) => `Let ${name} edit files without asking; other actions still ask you` },
+ auto: { label: "Approve for me", effect: (name) => `Let ${name}'s engine approve routine actions and ask you about the rest` },
+ full: { label: "Full access", effect: (name) => `Let ${name} act without asking` },
+};
+const approvalName = (mode: ApprovalMode) => (mode === "custom" ? "Custom" : APPROVAL[mode].label);
+
+const COMPUTER = {
+ auto: "pick its own computer", cloud: "use a cloud desktop", vm: "use a private desktop on this computer",
+ local: "use this computer's own desktop, as you", browser: "use only the built-in browser", off: "use no computer",
+} as const;
+const onOff = (on: boolean | null) => (on === null ? "follow the app's setting" : on ? "on" : "off");
+/** The other fields the bot panel edits that a loopback caller may set while a bot works; the route checks each one. */
+const OTHER = {
+ title: { label: "title", value: z.string().max(BOT_PROFILE_LIMITS.title), shown: (text: unknown) => `"${String(text)}"` },
+ description: { label: "description", value: z.string().max(BOT_PROFILE_LIMITS.description), shown: (text: unknown) => `"${String(text)}"` },
+ soul: { label: "instructions", value: z.string().max(4000), shown: (text: unknown) => `"${String(text).slice(0, 120)}${String(text).length > 120 ? "…" : ""}"` },
+ notifications: { label: "notifications", value: z.boolean(), shown: onOff },
+ speakReplies: { label: "spoken replies", value: z.boolean(), shown: onOff },
+ replyStyle: { label: "reply style", value: z.enum(["default", "conversational"]), shown: String },
+ voice: { label: "voice", value: z.string().max(BOT_PROFILE_LIMITS.voice), shown: String },
+ voiceNotes: { label: "voice notes", value: z.boolean(), shown: onOff },
+ voiceNoteEveryReply: { label: "a voice note with every reply", value: z.boolean().nullable(), shown: onOff },
+ memoryEnabled: { label: "memory", value: z.boolean(), shown: onOff },
+ memoryUpkeep: { label: "memory upkeep", value: z.boolean(), shown: onOff },
+ helperModel: { label: "helper model", value: z.boolean(), shown: onOff },
+ browser: { label: "built-in browser", value: z.boolean(), shown: onOff },
+ recordBrowserSteps: { label: "saving browser steps", value: z.boolean(), shown: onOff },
+ composio: { label: "Composio apps", value: z.boolean(), shown: onOff },
+ xResearch: { label: "X research", value: z.boolean(), shown: onOff },
+ parkDirectMessages: { label: "holding direct messages behind delegated work", value: z.boolean(), shown: onOff },
+ cacheKeepWarm: { label: "keeping its cache warm", value: z.boolean().nullable(), shown: onOff },
+ autoStartVps: { label: "starting its own server", value: z.boolean(), shown: onOff },
+ computer: { label: "computer", value: z.enum(["auto", "cloud", "vm", "local", "browser", "off"]), shown: (kind: unknown) => COMPUTER[kind as keyof typeof COMPUTER] },
+} as const;
+type OtherField = keyof typeof OTHER;
+
+export function botEntries(deps: Pick<RegistryDeps, "bots" | "engines" | "patchBot">, writable: (spec: WritableSpec) => SettingEntry): SettingEntry[] {
+ const bot = (id: string) => deps.bots().find((candidate) => candidate.id === id);
+ const missing = (id: string) => ({ refusal: `No bot has the id ${id}. Use list_bots for the ids.` });
+ const everyBot = (line: (one: BotRecord) => string) => () => deps.bots().map((one) => `${one.name}: ${line(one)}`).join("; ");
+ /** A per-bot entry: `effect` names the change for the card, or refuses it, once the bot is known to exist. */
+ const perBot = <V extends { botId: string }>(spec: Omit<WritableSpec, "tier" | "current" | "write" | "describe" | "value"> & {
+ value: z.ZodType<V>; effect(one: BotRecord, value: V): { change: string } | { refusal: string }; patch(one: BotRecord, value: V): Record<string, unknown>;
+ }) => writable({
+ ...spec, tier: "confirm", current: () => undefined,
+ describe: (value: V) => { const one = bot(value.botId); return one ? spec.effect(one, value) : missing(value.botId); },
+ write: (value: V) => { const one = bot(value.botId); return one ? deps.patchBot(one.id, spec.patch(one, value)) : Promise.resolve(missing(value.botId).refusal); },
+ });
+
+ return [
+ perBot({
+ id: "bots.approvalModes", label: "Approval mode", help: "What one bot may do without asking you, on every one of its conversations.", where: "a bot's Settings",
+ synonyms: ["permissions", "full access", "approve", "ask", "approval", "autonomy", "approve for me", "auto-accept edits"],
+ value: forBot({ mode: z.enum(["ask", "edits", "auto", "full"]) }),
+ allowed: '{"botId","mode"} with mode ask (Ask for approval), edits (Auto-accept edits), auto (Approve for me) or full (Full access). Custom is chosen only in the desktop app',
+ read: everyBot((one) => approvalName(approvalModeFor(one))),
+ effect: (one, { mode }) => {
+ if (approvalModeFor(one) === "custom") return { refusal: `${one.name} is on Custom approval, which is changed only in the desktop app, in ${one.name}'s Settings. Tell the user where.` };
+ // The route takes Approve for me on this computer's own desktop only with the warning its Settings dialog shows.
+ if (mode === "auto" && one.computer === "local") return { refusal: `Approve for me while ${one.name} uses this computer's own desktop needs a warning only ${one.name}'s Settings shows. Tell the user to choose it there.` };
+ return { change: `${APPROVAL[mode].effect(one.name)} (${APPROVAL[mode].label})` };
+ },
+ patch: (_one, { mode }) => ({ approvalMode: mode, applyToAllThreads: true }),
+ }),
+ perBot({
+ id: "bots.name", label: "Bot name", help: "A bot's name, as the sidebar and chats show it.", where: "a bot's Settings", synonyms: ["rename", "name", "call", "bot name"],
+ value: forBot({ name: z.string().trim().min(1).max(BOT_PROFILE_LIMITS.name) }), allowed: '{"botId","name"}', read: everyBot((one) => one.name),
+ effect: (one, { name }) => ({ change: `Rename ${one.name} to "${name}"` }), patch: (_one, { name }) => ({ name }),
+ }),
+ perBot({
+ id: "bots.color", label: "Bot colour", help: "A bot's colour in the sidebar and its chat.", where: "a bot's Settings", synonyms: ["color", "colour", "tint", "bot color"],
+ value: forBot({ color: z.enum(MAUS_COLOR_NAMES) }), allowed: `{"botId","color"} with color one of ${MAUS_COLOR_NAMES.join(", ")}`, read: everyBot((one) => one.color),
+ effect: (one, { color }) => ({ change: `Make ${one.name} ${color}` }), patch: (_one, { color }) => ({ color }),
+ }),
+ perBot({
+ id: "bots.model", label: "Bot model", help: "The engine and model one bot runs on, for its conversations. Ids come from list_models.", where: "a bot's Settings",
+ synonyms: ["model", "engine", "switch model", "change model", "effort", "reasoning"],
+ value: forBot({ instanceId: z.string().min(1).max(120), model: z.string().min(1).max(200), effort: z.enum(EFFORT_LEVELS).optional() }),
+ allowed: '{"botId","instanceId","model","effort"?} from list_models', read: everyBot((one) => `${one.modelSelection.instanceId} / ${one.modelSelection.model}`),
+ effect: (one, { instanceId, model, effort }) => {
+ const engine = deps.engines().find((candidate) => candidate.instanceId === instanceId);
+ if (!engine) return { refusal: `No engine has the id ${instanceId}. Use list_models for engine and model ids.` };
+ return { change: `Move ${one.name} to ${engine.name}, model ${model}${effort ? `, ${effort} effort` : ""}` };
+ },
+ patch: (_one, { instanceId, model, effort }) => ({ modelSelection: { instanceId, model, ...(effort ? { effort } : {}) }, requireAvailableModel: true }),
+ }),
+ perBot({
+ id: "bots.archived", label: "Archived bots", help: "Archive a bot to take it out of the sidebar, keeping its chats; false brings it back.", where: "the sidebar",
+ synonyms: ["archive", "unarchive", "restore bot", "hide bot", "show bot", "hidden"],
+ value: forBot({ archived: z.boolean() }), allowed: '{"botId","archived":true|false}', read: () => deps.bots().filter((one) => one.hidden).map((one) => one.name).join(", "),
+ effect: (one, { archived }) => one.defaultBot && archived ? { refusal: `${one.name} is this place's own bot and is never archived. To take it out of the sidebar use sidebar.showHelper.` }
+ : { change: archived ? `Archive ${one.name}: it leaves the sidebar and keeps its chats${one.chiefOfStaff ? ", and stops being Chief of Staff" : ""}` : `Bring ${one.name} back to the sidebar` },
+ patch: (one, { archived }) => ({ hidden: archived, ...(archived && one.chiefOfStaff ? { chiefOfStaff: false } : {}) }),
+ }),
+ writable({
+ id: "sidebar.showHelper", label: "Show MausBot in the sidebar", help: "Whether this place's own bot, MausBot, has a row in the sidebar; it keeps working either way.", where: "Settings → Overview",
+ synonyms: ["helper", "starter", "default bot", "mausbot", "show helper"], tier: "confirm", value: z.boolean(), allowed: "true or false",
+ current: () => { const helper = deps.bots().find((one) => one.defaultBot); return helper ? !helper.sidebarHidden : undefined; },
+ describe: (show: boolean) => (deps.bots().some((one) => one.defaultBot) ? { change: show ? "Show MausBot in the sidebar" : "Take MausBot out of the sidebar; it keeps working" } : { refusal: "This place has no MausBot of its own." }),
+ write: (show: boolean) => { const helper = deps.bots().find((one) => one.defaultBot); return helper ? deps.patchBot(helper.id, { sidebarHidden: !show }) : Promise.resolve("This place has no MausBot of its own."); },
+ }),
+ perBot({
+ id: "bots.settings", label: "Other bot settings", help: `More of one bot's own settings: ${Object.values(OTHER).map((field) => field.label).join(", ")}.`, where: "a bot's Settings",
+ synonyms: ["voice", "voice notes", "memory", "notifications", "browser", "instructions", "soul", "title", "description", "reply style", "computer", "desktop", "composio", "x research", "keep warm"],
+ value: forBot(Object.fromEntries(Object.entries(OTHER).map(([field, spec]) => [field, spec.value.optional()])) as { [F in OtherField]: z.ZodOptional<(typeof OTHER)[F]["value"]> })
+ .refine((value) => Object.keys(value).length > 1, "name at least one setting besides botId"),
+ allowed: `{"botId", ...one or more of ${(Object.keys(OTHER) as OtherField[]).join(", ")}}`,
+ read: () => "use get on a bot's own fields through list_bots",
+ effect: (one, value) => ({ change: `${one.name}: ${(Object.keys(value) as Array<OtherField | "botId">).filter((field) => field !== "botId")
+ .map((field) => `${OTHER[field as OtherField].label} ${OTHER[field as OtherField].shown(value[field as OtherField] as never)}`).join("; ")}` }),
+ patch: (_one, { botId: _id, computer, ...rest }) => ({ ...rest, ...(computer ? { computer: computer === "auto" ? null : computer } : {}) }),
+ }),
+ ];
+}
diff --git a/server/app-settings/registry-config.ts b/server/app-settings/registry-config.ts
new file mode 100644
index 0000000000..3114a1f901
--- /dev/null
+++ b/server/app-settings/registry-config.ts
@@ -0,0 +1,217 @@
+// The server's own settings from the Settings pages, each on a Change/Cancel card. Writes go through PUT /api/config
+// (or the one route the page itself calls), so that route's checks, side effects and broadcasts still run.
+import { randomUUID } from "node:crypto";
+
+import { z } from "zod";
+
+import { IMAGE_PROVIDERS } from "../../shared/image-generation.ts";
+import { EFFORT_LEVELS } from "../../shared/wire.ts";
+import { DEFAULT_WINDOW_MINUTES } from "../cache-keepwarm.ts";
+import { CONFIG_PATCH_FIELDS as F, MAX_THREAD_EVENT_LOG_BYTES, MIN_THREAD_EVENT_LOG_BYTES } from "../config.ts";
+import { display, withoutKeys, type RegistryDeps, type SettingEntry, type Where, type WritableSpec } from "./registry.ts";
+
+/** Security: what a bot or card reads of a section never carries a key, token, secret or password field. */
+const visible = (value: unknown): unknown => (value && typeof value === "object" && !Array.isArray(value)
+ ? Object.fromEntries(Object.entries(value).filter(([field]) => !/key|token|secret|password/i.test(field)).map(([field, inner]) => [field, visible(inner)]))
+ : value);
+const fields = (value: object) => Object.entries(value).map(([field, inner]) => `${field} ${display(inner) || "cleared"}`).join(", ");
+const quoted = (text: string) => `"${text.length > 160 ? `${text.slice(0, 160)}…` : text}"`;
+const nonEmpty = <T extends z.ZodType<object>>(schema: T) => schema.refine((value) => Object.keys(value).length > 0, "name at least one field");
+type BrowserProfileChange = { id?: string; name: string; browser?: "chrome" };
+const imageSlot = z.object({ provider: z.enum(IMAGE_PROVIDERS), model: z.string().trim().max(200).optional() }).strict();
+
+export function configEntries(deps: Pick<RegistryDeps, "cfg" | "saveConfig" | "bots" | "call">, writable: (spec: WritableSpec) => SettingEntry): SettingEntry[] {
+ const cfg = deps.cfg;
+ /** A confirm setting saved with PUT /api/config; `says` is the card's line, else it shows before → after. */
+ const section = <V,>(spec: { id: string; label: string; help: string; where: Where; synonyms: string[]; value: z.ZodType<V>; allowed: string;
+ current(): unknown; patch(value: V): Record<string, unknown>; says?(value: V): string; read?(): string }) => writable({
+ id: spec.id, label: spec.label, help: spec.help, where: spec.where, synonyms: spec.synonyms, tier: "confirm", value: spec.value, allowed: spec.allowed,
+ current: spec.current, read: spec.read ?? (() => display(visible(spec.current()))), write: (value: V) => deps.saveConfig(spec.patch(value)),
+ ...(spec.says ? { describe: (value: V) => ({ change: spec.says!(value) }) } : {}),
+ });
+ const feature = (id: string, label: string, help: string, where: Where, synonyms: string[], field: string, onUnlessFalse: boolean, yes: string, no: string) => section({
+ id, label, help, where, synonyms, value: z.boolean(), allowed: "true or false",
+ current: () => { const set = (cfg().features as Record<string, unknown> | undefined)?.[field]; return onUnlessFalse ? set !== false : set === true; },
+ patch: (on: boolean) => ({ features: { [field]: on } }), says: (on: boolean) => (on ? yes : no),
+ });
+ const routed = (spec: Omit<WritableSpec, "tier" | "current"> & { current?(): unknown }) => writable({ ...spec, tier: "confirm", current: spec.current ?? (() => undefined) });
+ const botName = (id: string) => deps.bots().find((bot) => bot.id === id)?.name;
+
+ return [
+ section({
+ id: "ai.backupModel", label: "Automatic recovery", help: "When a bot's engine fails before any work starts, try once more on a backup model.", where: "Settings → AI",
+ synonyms: ["backup model", "fallback", "recovery", "automatic recovery"], value: F.automaticRecovery.unwrap(), allowed: '{"enabled":false} or {"enabled":true,"backup":{"instanceId","model"}} from list_models',
+ current: () => cfg().automaticRecovery ?? { enabled: false }, patch: (automaticRecovery) => ({ automaticRecovery }),
+ says: ({ enabled, backup }) => (enabled && backup ? `Turn on automatic recovery: a bot whose engine fails before any work starts tries once more on ${backup.instanceId} / ${backup.model}` : "Turn off automatic recovery"),
+ }),
+ section({
+ id: "ai.routing", label: "Decision and extraction", help: "The small model that decides who answers in rooms and sorts the inbox (Jev or OpenRouter). Its keys are set with keys.* or in Settings.", where: "Settings → AI",
+ synonyms: ["decision", "extraction", "routing", "who answers", "jev", "openrouter", "workers ai", "cloudflare"],
+ value: nonEmpty(withoutKeys(F.decider.unwrap().omit({ key: true, openrouterKey: true, workersAiToken: true }).strict())),
+ allowed: '{"enabled"?,"provider"?:"jev"|"openrouter"|"off","openrouterModel"?,"openrouterApi"?:"chat"|"decisions","jobs"?:{"roomRouting"?,"inboxTriage"?},"workersAiAccountId"?, addresses?}',
+ current: () => cfg().decider ?? {}, patch: (decider) => ({ decider }),
+ says: (decider) => `Decision and extraction: ${fields(decider)}. Decisions send conversation text to the chosen provider, off this computer`,
+ }),
+ section({
+ id: "ai.images", label: "Image generation", help: "Which provider and model make images, a fallback, and how many images one turn may make. Keys are set with keys.* or in Settings.", where: "Settings → AI",
+ synonyms: ["images", "image generation", "picture", "generate"],
+ value: nonEmpty(withoutKeys(z.object({ primary: imageSlot.optional(), fallback: imageSlot.nullable().optional(), maxPerTurn: z.number().int().min(1).max(10).optional(), customUrl: z.string().trim().max(2048).optional() }).strict())),
+ allowed: `{"primary"?:{"provider","model"?},"fallback"?:{...}|null,"maxPerTurn"?:1-10,"customUrl"?} with provider one of ${IMAGE_PROVIDERS.join(", ")}`,
+ current: () => cfg().imageGen ?? {}, patch: (imageGen) => ({ imageGen }),
+ says: (imageGen) => `Image generation: ${fields(imageGen)}. Image prompts go to the chosen provider, off this computer`,
+ }),
+ section({
+ id: "profile.name", label: "Your name", help: "What bots call you.", where: "Settings → You and your bots", synonyms: ["my name", "name", "profile", "about me"],
+ value: z.string().trim().max(200), allowed: "your name, or empty to clear", current: () => cfg().profile?.name ?? "", patch: (name) => ({ profile: { name } }),
+ }),
+ section({
+ id: "profile.email", label: "Your email", help: "Your email address, for bots that write on your behalf. It stays on this computer.", where: "Settings → You and your bots", synonyms: ["email", "my email", "profile"],
+ value: z.union([z.literal(""), z.string().trim().email().max(320)]), allowed: "an email address, or empty to clear", current: () => cfg().profile?.email ?? "", patch: (email) => ({ profile: { email } }),
+ }),
+ section({
+ id: "profile.aboutMe", label: "About you", help: "What every bot knows about you.", where: "Settings → You and your bots", synonyms: ["about me", "about you", "profile", "bio"],
+ value: z.string().max(4000), allowed: "text up to 4000 characters, or empty to clear", current: () => cfg().profile?.aboutMe ?? "", read: () => cfg().profile?.aboutMe ?? "",
+ patch: (aboutMe) => ({ profile: { aboutMe } }), says: (text) => (text ? `Tell every bot this about you: ${quoted(text)}` : "Clear what every bot knows about you"),
+ }),
+ section({
+ id: "profile.photo", label: "Your photo", help: "Your profile photo. A bot can only remove it; a new one is picked in Settings.", where: "Settings → You and your bots", synonyms: ["photo", "avatar", "profile picture"],
+ value: z.literal(""), allowed: '"" to remove it', current: () => undefined, read: () => (cfg().profile?.avatarUrl ? "set" : ""),
+ patch: () => ({ profile: { avatarUrl: "" } }), says: () => "Remove your profile photo",
+ }),
+ section({
+ id: "bots.everyBotRules", label: "Rules for every bot", help: "Instructions every bot follows, ahead of its own.", where: "Settings → You and your bots", synonyms: ["rules", "rules for every bot", "instructions", "every bot"],
+ value: z.string().max(4000), allowed: "text up to 4000 characters, or empty to clear", current: () => cfg().everyBotRules ?? "", read: () => cfg().everyBotRules ?? "",
+ patch: (everyBotRules) => ({ everyBotRules }), says: (text) => (text ? `Make every bot follow: ${quoted(text)}` : "Clear the rules every bot follows"),
+ }),
+ section({
+ id: "bots.newBotEffort", label: "Effort for new bots", help: "The reasoning effort a new bot starts with when its model names none; null uses the engine's own.", where: "Settings → You and your bots",
+ synonyms: ["effort", "reasoning", "new bots", "thinking"], value: z.enum(EFFORT_LEVELS).nullable(), allowed: `${EFFORT_LEVELS.join(", ")}, or null`,
+ current: () => cfg().newBots?.effort ?? null, patch: (effort) => ({ newBots: { effort } }),
+ }),
+ section({
+ id: "bots.newBotTemplate", label: "New-bot template", help: "Everything a new bot starts with (profile, model, approval level, skills), as the new-bot dialog saves it. get shows the current template.", where: "Settings → You and your bots",
+ synonyms: ["new bots", "defaults", "template", "preset"], value: withoutKeys(F.newBotDefaults.unwrap()), allowed: "the whole template object, as get shows it",
+ current: () => cfg().newBotDefaults, patch: (newBotDefaults) => ({ newBotDefaults }),
+ says: (template) => `Replace the template every new bot starts from with: ${display(visible(template)).slice(0, 400)}`,
+ }),
+ section({
+ id: "bots.keepWarm", label: "Keep caches warm", help: "After a turn, keep each bot's prompt cache warm so its next reply is faster and cheaper; it costs a few tokens.", where: "Settings → You and your bots",
+ synonyms: ["keep warm", "cache", "prompt cache"], value: F.cacheKeepWarm.unwrap(), allowed: '{"enabled":true|false,"windowMinutes"?:15-1440}',
+ current: () => cfg().cacheKeepWarm ?? { enabled: false }, patch: (cacheKeepWarm) => ({ cacheKeepWarm }),
+ says: ({ enabled, windowMinutes }) => (enabled ? `Keep prompt caches warm for ${windowMinutes ?? DEFAULT_WINDOW_MINUTES} minutes after each turn (spends tokens)` : "Stop keeping prompt caches warm"),
+ }),
+ feature("bots.skillAuthoring", "Bots write their own skills", "Bots may draft skills for your review.", "Settings → You and your bots", ["skills", "write skills", "early", "experimental"], "skillAuthoring", true,
+ "Let bots draft skills for your review", "Stop bots drafting skills"),
+ section({
+ id: "bots.skillReview", label: "Skill review", help: "The bot's engine reviews long conversations and updates its learned skills, every so many tool steps.", where: "Settings → You and your bots",
+ synonyms: ["skill review", "learned skills", "early"], value: z.object({ enabled: z.boolean(), steps: z.number().int().min(3).max(100).optional() }).strict(), allowed: '{"enabled":true|false,"steps"?:3-100}',
+ current: () => ({ enabled: cfg().features?.skillReview === true, ...(cfg().features?.skillReviewSteps ? { steps: cfg().features?.skillReviewSteps } : {}) }),
+ patch: ({ enabled, steps }) => ({ features: { skillReview: enabled, ...(steps ? { skillReviewSteps: steps } : {}) } }),
+ says: ({ enabled, steps }) => (enabled ? `Let each bot's engine review long conversations${steps ? ` every ${steps} tool steps` : ""} and update its skills` : "Stop reviewing conversations for skills"),
+ }),
+ section({
+ id: "bots.shareLearnedSkills", label: "Share learned skills", help: "Whether a skill one bot learns goes to the shared library: off, ask you first, or automatically.", where: "Settings → You and your bots",
+ synonyms: ["share skills", "skills library", "learned skills"], value: z.enum(["off", "ask", "auto"]), allowed: "off, ask or auto",
+ current: () => cfg().features?.shareLearnedSkills ?? "off", patch: (shareLearnedSkills) => ({ features: { shareLearnedSkills } }),
+ }),
+ section({
+ id: "threads.eventLogMaxBytes", label: "Thread log size limit", help: "The most bytes each conversation's event log keeps; null keeps it all.", where: "Settings → Data",
+ synonyms: ["log size", "storage", "event log", "cleanup"], value: z.number().int().min(MIN_THREAD_EVENT_LOG_BYTES).max(MAX_THREAD_EVENT_LOG_BYTES).nullable(),
+ allowed: `${MIN_THREAD_EVENT_LOG_BYTES} to ${MAX_THREAD_EVENT_LOG_BYTES} bytes, or null for no limit`,
+ current: () => cfg().threads?.eventLogMaxBytes ?? null, read: () => display(cfg().threads?.eventLogMaxBytes ?? "no limit"), patch: (eventLogMaxBytes) => ({ threads: { eventLogMaxBytes } }),
+ }),
+ feature("appearance.toolCalls", "Show tool calls", "Show each tool a bot runs in the conversation.", "Settings → Appearance", ["tool calls", "tools", "show tools"], "showToolCalls", false,
+ "Show each tool a bot runs in its conversation", "Hide tool runs from conversations"),
+ feature("desktops.browser", "Built-in browser", "Bots may use the built-in browser; each bot also has its own switch.", "Settings → Desktops & browser", ["browser", "built-in browser"], "browser", true,
+ "Let bots use the built-in browser", "Turn off the built-in browser for every bot"),
+ section({
+ id: "desktops.browserLocalNetwork", label: "Browser on your local network", help: "Whether bots' browsers may open sites on this computer's local network.", where: "Settings → Desktops & browser",
+ synonyms: ["local network", "lan", "browser sites", "intranet"], value: z.boolean(), allowed: "true or false",
+ current: () => cfg().browserEngine?.egress?.localNetwork === true, patch: (localNetwork) => ({ browserEngine: { egress: { localNetwork } } }),
+ says: (on) => (on ? "Let bots' browsers open sites on your local network" : "Keep bots' browsers off your local network"),
+ }),
+ section({
+ id: "desktops.browserEngine", label: "Browser engine", help: "What runs bots' browsers: agent-browser (the default) or MausBot's own Chrome driver (early).", where: "Settings → Desktops & browser",
+ synonyms: ["browser engine", "chrome", "new browser", "agent-browser"], value: z.enum(["agent-browser", "chrome"]), allowed: "agent-browser or chrome",
+ current: () => cfg().browserEngine?.engine ?? "agent-browser", patch: (engine) => ({ browserEngine: { engine } }),
+ }),
+ feature("desktops.savedSteps", "Saved steps", "Bots may repeat saved browser steps without AI.", "Settings → Desktops & browser", ["saved steps", "repeat", "without ai"], "savedSteps", true,
+ "Let bots repeat saved steps without AI", "Turn off saved steps"),
+ section({
+ id: "desktops.privateDesktop", label: "Private desktops", help: "How bots share private desktops on this computer: one shared, one per bot, or a pool; how many; and minutes before an idle one stops.", where: "Settings → Desktops & browser",
+ synonyms: ["private desktop", "vm", "docker", "podman", "container", "sandbox"],
+ value: nonEmpty(F.localVm.unwrap().pick({ mode: true, maxInstances: true, idleTimeoutMinutes: true }).strict()), allowed: '{"mode"?:"shared"|"per-bot"|"pool","maxInstances"?,"idleTimeoutMinutes"?}',
+ current: () => cfg().localVm ?? {}, patch: (localVm) => ({ localVm }), says: (localVm) => `Private desktops: ${fields(localVm)}`,
+ }),
+ feature("computer.sharing", "Computer sharing", "Whether every paired device may lend its computer to bots here. Each lent folder or app is still picked and confirmed on that device.", "Settings → Desktops & browser",
+ ["share computer", "shared computers", "lend", "lending"], "sharedComputers", false,
+ "Let every paired device lend its computer to bots here, not only your own. A lent folder can be used to reach a shell", "Stop every device, your own included, lending its computer to bots here"),
+ writable({
+ id: "desktops.browserProfiles", label: "Browser profiles", help: "Named browser profiles bots use, each keeping its own logins. Send the full list; leave out id for a new one. Removing one deletes its logins, so only the user does that.",
+ where: "Settings → Desktops & browser", synonyms: ["browser profiles", "profiles", "my chrome", "logins"], tier: "confirm",
+ value: z.array(z.object({ id: z.string().regex(/^[a-z0-9-]{1,80}$/).optional(), name: z.string().trim().min(1).max(40), browser: z.literal("chrome").optional() }).strict()).max(20),
+ allowed: '[{"id"?,"name","browser"?:"chrome"}]; "chrome" uses your own running Chrome', current: () => undefined,
+ read: () => (cfg().browserProfiles ?? []).map((profile) => `${profile.id}: ${profile.name}${profile.browser ? " (your Chrome)" : ""}`).join("; "),
+ describe: (next: BrowserProfileChange[]) => {
+ const current = cfg().browserProfiles ?? [];
+ const gone = current.find((profile) => !next.some((wanted) => wanted.id === profile.id));
+ if (gone) return { refusal: `Removing the browser profile "${gone.name}" deletes its saved logins, so only the user does that, in Settings → Desktops & browser. Send every current profile.` };
+ const unknown = next.find((wanted) => wanted.id && !current.some((profile) => profile.id === wanted.id));
+ if (unknown) return { refusal: `No browser profile has the id ${unknown.id}. Leave out id for a new profile.` };
+ const where = (profile: BrowserProfileChange) => (profile.browser ? "your own running Chrome, with its logins" : "the built-in browser");
+ const lines = next.flatMap((wanted) => {
+ const before = current.find((profile) => profile.id === wanted.id);
+ if (!before) return [`add the profile "${wanted.name}" on ${where(wanted)}`];
+ return [...(before.name !== wanted.name ? [`rename "${before.name}" to "${wanted.name}"`] : []), ...(Boolean(before.browser) !== Boolean(wanted.browser) ? [`move "${wanted.name}" to ${where(wanted)}`] : [])];
+ });
+ return lines.length ? { change: `Browser profiles: ${lines.join("; ")}` } : { refusal: "That list is the same as the current one." };
+ },
+ write: (next: BrowserProfileChange[]) => {
+ const current = (cfg().browserProfiles ?? []).map(({ id, name, browser }) => ({ id, name, ...(browser ? { browser } : {}) }));
+ const browserProfiles = next.map((profile) => ({ ...profile, id: profile.id ?? `profile-${randomUUID().replaceAll("-", "")}` }));
+ return deps.saveConfig({ browserProfiles, expectedBrowserProfiles: current });
+ },
+ }),
+ section({
+ id: "people.signIn", label: "Who may sign in", help: "On a self-hosted server: the email addresses or @domains that may sign in with an emailed code. Admins get every setting; members only chat. Send both full lists.",
+ where: "Settings → Your account", synonyms: ["people", "members", "invite", "roles", "admins", "sign in access"],
+ value: z.object({ admins: z.array(z.string().trim().min(3).max(320)).max(500), members: z.array(z.string().trim().min(3).max(320)).max(5000) }).strict(),
+ allowed: '{"admins":[emails or @domains],"members":[...]}', current: () => ({ admins: cfg().signIn?.admins ?? [], members: cfg().signIn?.members ?? [] }),
+ patch: (signIn) => ({ signIn }),
+ says: ({ admins, members }) => {
+ const was = { admins: cfg().signIn?.admins ?? [], members: cfg().signIn?.members ?? [] };
+ const added = (list: string[], before: string[]) => list.filter((entry) => !before.includes(entry));
+ const lines = [...added(admins, was.admins).map((entry) => `let ${entry} sign in as an admin, with every setting`), ...added(members, was.members).map((entry) => `let ${entry} sign in as a member`),
+ ...[...was.admins, ...was.members].filter((entry) => !admins.includes(entry) && !members.includes(entry)).map((entry) => `stop ${entry} signing in`)];
+ return lines.length ? `Sign-in: ${lines.join("; ")}` : "Keep who may sign in as it is";
+ },
+ }),
+ routed({
+ id: "remote.domain", label: "Custom domain", help: "The web address this self-hosted server answers on; it is checked live, and new pairing links use it.", where: "Settings → Overview",
+ synonyms: ["domain", "custom domain", "dns", "https", "public url", "remote access"], value: z.string().trim().max(253), allowed: "a domain such as bots.example.com, or empty to remove it",
+ read: () => cfg().customDomain ?? "", current: () => cfg().customDomain ?? "",
+ describe: (domain: string) => ({ change: domain ? `Serve this place at ${domain} (checked live), and give it in new pairing links` : "Remove this place's custom domain; new pairing links use its other address" }),
+ write: (domain: string) => (domain ? deps.call("customDomain", "POST", "/api/settings/custom-domain", { domain }) : deps.call("customDomain", "DELETE", "/api/settings/custom-domain")),
+ }),
+ routed({
+ id: "bots.awake", label: "Bots kept awake", help: "On a Starter Cloud, which bots stay awake past the plan's limit; the rest pause. Send exactly as many as the plan keeps.", where: "Settings → You and your bots",
+ synonyms: ["awake", "paused bots", "starter", "limit"], value: z.array(z.string().regex(/^[\w-]{1,120}$/)).min(1).max(100), allowed: "a list of bot ids",
+ read: () => "", describe: (ids: string[]) => { const missing = ids.find((id) => !botName(id)); return missing ? { refusal: `No bot has the id ${missing}. Use list_bots for the ids.` } : { change: `Keep ${ids.map(botName).join(", ")} awake; your other bots pause` }; },
+ write: (awake: string[]) => deps.call("starterAwake", "POST", "/api/starter/awake", { awake }),
+ }),
+ routed({
+ id: "skills.library", label: "Skills library", help: "Turn a library skill on or off, or give it to every bot. Library skills are listed in Settings.", where: "Settings → You and your bots",
+ synonyms: ["skills", "skill library", "library", "every bot skill"],
+ value: z.object({ name: z.string().regex(/^[a-z0-9-]{1,64}$/), enabled: z.boolean().optional(), everyBot: z.boolean().optional() }).strict().refine((value) => (value.enabled === undefined) !== (value.everyBot === undefined), "send enabled or everyBot, one of them"),
+ allowed: '{"name","enabled":true|false} or {"name","everyBot":true|false}', read: () => "",
+ describe: ({ name, enabled, everyBot }: { name: string; enabled?: boolean; everyBot?: boolean }) => ({ change: enabled !== undefined ? `${enabled ? "Turn on" : "Turn off"} the library skill ${name}` : `${everyBot ? "Give" : "Stop giving"} the library skill ${name} to every bot` }),
+ write: ({ name, ...change }: { name: string; enabled?: boolean; everyBot?: boolean }) => deps.call("skills", "PATCH", `/api/skills-library/${name}`, change),
+ }),
+ routed({
+ id: "bots.skills", label: "A bot's library skills", help: "Which library skills one bot uses. Send the full list.", where: "a bot's Settings", synonyms: ["skills", "assign skills", "bot skills"],
+ value: z.object({ botId: z.string().regex(/^[\w-]{1,120}$/), skills: z.array(z.string().min(1).max(64)).max(200) }).strict(), allowed: '{"botId","skills":[names]}', read: () => "",
+ describe: ({ botId, skills }: { botId: string; skills: string[] }) => { const name = botName(botId); return name ? { change: skills.length ? `Give ${name} the library skills ${skills.join(", ")}` : `Take every library skill from ${name}` } : { refusal: `No bot has the id ${botId}. Use list_bots for the ids.` }; },
+ write: ({ botId, skills }: { botId: string; skills: string[] }) => deps.call("skills", "PUT", `/api/bots/${encodeURIComponent(botId)}/skills-library`, { skills }),
+ }),
+ ];
+}
diff --git a/server/app-settings/registry-window.ts b/server/app-settings/registry-window.ts
new file mode 100644
index 0000000000..866134c287
--- /dev/null
+++ b/server/app-settings/registry-window.ts
@@ -0,0 +1,64 @@
+// Preferences the app window keeps, or reaches through the desktop app's bridge, that change only on a Change/Cancel
+// card. The window is told only once the owner taps Change, and a window that can't apply one (a browser has no desktop
+// bridge) is refused before any card shows.
+import { z } from "zod";
+
+import { PLACE_SWATCHES, TALK_KEYS } from "../../shared/app-settings.ts";
+import type { SettingEntry, WindowPref } from "./registry.ts";
+
+const turn = (on: boolean, yes: string, no: string) => (on ? yes : no);
+
+export function windowEntries(windowPref: WindowPref): SettingEntry[] {
+ const flag = (id: Parameters<WindowPref>[0], label: string, help: string, where: Parameters<WindowPref>[3], synonyms: string[], yes: string, no: string) =>
+ windowPref(id, label, help, where, synonyms, "true or false", { says: (on: boolean) => turn(on, yes, no) });
+ return [
+ flag("appearance.userBubbles", "Coloured messages", "Your own messages take the bot's colour.", "Settings → Appearance", ["bubbles", "message color", "my messages"],
+ "Colour your messages with each bot's colour", "Show your messages in plain grey"),
+ flag("appearance.runCard", "This run card", "Show the card that follows a bot's run while it works.", "Settings → Appearance", ["this run", "run card", "progress"],
+ "Show the card that follows each run", "Hide the card that follows each run"),
+ flag("appearance.showThreads", "Threads in the sidebar", "List each bot's conversations under it in the sidebar.", "Settings → Appearance", ["threads", "conversations", "sidebar"],
+ "List each bot's threads in the sidebar", "Hide threads from the sidebar"),
+ windowPref("appearance.toolsLayout", "Sidebar tools layout", "How the sidebar shows its tools: rows, or a toolbar of icons.", "Settings → Appearance", ["tools layout", "toolbar", "rows"], "rows or toolbar",
+ { says: (layout: "rows" | "toolbar") => (layout === "rows" ? "Show the sidebar's tools as rows" : "Show the sidebar's tools as a toolbar of icons") }),
+ flag("appearance.pinnedCircles", "Pinned bots as circles", "Pinned bots show as a row of circles at the top of the sidebar.", "Settings → Appearance", ["pinned", "circles", "pins"],
+ "Show pinned bots as circles", "Show pinned bots as rows"),
+ flag("appearance.universalPins", "Universal pins", "Pinned bots stay pinned in every place on the rail.", "Settings → Appearance", ["universal pins", "pins everywhere"],
+ "Keep pinned bots pinned in every place", "Pin bots in each place on its own"),
+ windowPref("appearance.pinnedPages", "Pinned pages", "Web pages pinned beside the chat. Send the full list; chat pages pinned from a conversation stay.", "Settings → Appearance",
+ ["pinned panels", "pinned pages", "web panel", "side page"], 'a list of up to 6 {"name","url"} with http(s) addresses; an empty list unpins every web page',
+ { says: (pages: Array<{ name: string; url: string }>) => (pages.length ? `Pin these pages beside the chat: ${pages.map((page) => `${page.name} (${page.url})`).join(", ")}` : "Unpin every web page beside the chat") }),
+ flag("appearance.showComputers", "Show your computers", "The rail of places down the side of the window (desktop app).", "Settings → Appearance", ["rail", "show your computers", "places"],
+ "Show the rail of your computers and Clouds", "Hide the rail of your computers and Clouds"),
+ flag("appearance.windowFrame", "Window frame", "Draw the system's own title bar around the window (desktop app; on Windows after a restart).", "Settings → Appearance", ["window frame", "title bar"],
+ "Draw the system title bar around the window", "Draw the window without the system title bar"),
+ windowPref("appearance.sidebarColor", "Sidebar colour", "This place's colour, tinting its sidebar and its circle on the rail (desktop app).", "Settings → Overview", ["sidebar color", "sidebar colour", "tint", "cloud color", "place color"],
+ `${PLACE_SWATCHES.join(", ")} or none`, { says: (swatch: string) => (swatch === "none" ? "Take the colour off this place's sidebar" : `Tint this place's sidebar ${swatch}`) }),
+ windowPref("general.followUp", "Follow-up while a bot works", "What sending does while a bot is busy: steer its current run, or queue the message.", "Settings → General", ["follow up", "steer", "queue"], "steer or queue",
+ { says: (choice: "steer" | "queue") => (choice === "steer" ? "Send follow-ups into the bot's current run" : "Queue follow-ups until the bot's run ends") }),
+ flag("general.finishedNotifications", "Notifications on this device", "A system notification when a bot finishes or needs you; turning it on asks the system first.", "Settings → General", ["notify", "system notifications", "desktop notifications"],
+ "Show a system notification when a bot finishes or needs you", "Stop system notifications from bots"),
+ flag("general.notificationFeed", "Notification feed", "Keep a feed of what bots did in the notifications panel.", "Settings → General", ["feed", "notification feed", "inbox"],
+ "Keep a feed of bot updates", "Turn off the feed of bot updates"),
+ flag("general.analytics", "Usage analytics", "Send anonymous usage data to MausBot (PostHog) to improve the app.", "Settings → General", ["analytics", "telemetry", "privacy", "tracking"],
+ "Send anonymous usage data from this app to MausBot's analytics (PostHog), off this computer", "Stop sending usage analytics"),
+ flag("general.openAtLogin", "Open at login", "Start MausBot when you log in to this computer (desktop app).", "Settings → General", ["startup", "launch", "login", "open at login"],
+ "Open MausBot when you log in", "Don't open MausBot at login"),
+ windowPref("general.talkShortcut", "Talk shortcut", "A key held anywhere on this Mac to talk to MausBot (desktop app).", "Settings → General", ["talk", "voice", "dictation", "microphone", "hotkey"],
+ `{"enabled":true|false,"key":${TALK_KEYS.map((key) => `"${key}"`).join(" | ")}}`, {
+ value: z.object({ enabled: z.boolean(), key: z.enum(TALK_KEYS) }).strict(),
+ says: ({ enabled, key }: { enabled: boolean; key: string }) => (enabled ? `Hold ${key.replaceAll("-", "+")} anywhere to talk to MausBot` : "Turn off the talk shortcut"),
+ }),
+ flag("account.productEmails", "Product update emails", "MausBot emails you product updates.", "Settings → Your account", ["emails", "newsletter", "product updates", "email updates"],
+ "Get MausBot product update emails (your email address is sent to MausBot)", "Stop MausBot product update emails"),
+ flag("remote.wifi", "Same Wi-Fi", "Paired phones reach this computer on the same Wi-Fi network.", "Settings → Phone & devices", ["wifi", "wi-fi", "lan", "local network", "remote access"],
+ "Let your paired phones reach this computer on the same Wi-Fi", "Stop paired phones reaching this computer over Wi-Fi"),
+ flag("remote.relay", "Reach from anywhere", "Paired phones reach this computer from anywhere through MausBot's relay (needs a MausBot sign-in).", "Settings → Phone & devices", ["relay", "anywhere", "away", "remote access"],
+ "Let your paired phones reach this computer from anywhere, through MausBot's relay", "Stop paired phones reaching this computer from anywhere"),
+ flag("remote.tailscale", "Tailscale", "Paired devices reach this computer over your Tailscale network (Tailscale must be installed and signed in).", "Settings → Phone & devices", ["tailscale", "tailnet", "remote access"],
+ "Let your devices reach this computer over Tailscale", "Stop devices reaching this computer over Tailscale"),
+ windowPref("remote.httpsAddress", "HTTPS address", "This computer's public HTTPS address for paired devices. It is set up while pairing; a bot can only turn it off.", "Settings → Phone & devices",
+ ["https", "public address", "remote access"], "false", { value: z.literal(false), says: () => "Turn off this computer's HTTPS address for paired devices" }),
+ flag("remote.keepAwake", "Keep awake", "Keep this computer awake while a way in is on, so paired phones can reach it.", "Settings → Phone & devices", ["sleep", "awake", "overnight"],
+ "Keep this computer awake so paired phones can reach it", "Let this computer sleep"),
+ ];
+}
diff --git a/server/app-settings/registry.ts b/server/app-settings/registry.ts
index 484d512920..fdc7648cc5 100644
--- a/server/app-settings/registry.ts
+++ b/server/app-settings/registry.ts
@@ -16,9 +16,12 @@ import { callRoute, type RouteReply } from "../routes/call-route.ts";
import { engineChosen } from "../routes/instances.ts";
import type { RouteHandler } from "../routes/table.ts";
import type { BotRecord, Store } from "../store.ts";
+import { botEntries } from "./registry-bots.ts";
+import { configEntries } from "./registry-config.ts";
+import { windowEntries } from "./registry-window.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"
+export type Where = "Settings → Overview" | "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 {
@@ -51,6 +54,7 @@ interface OwnerOnly {
export type SettingEntry = Base & (Writable | Secret | OwnerOnly);
export type WritableEntry = Base & Writable;
+export type AppRoute = "customDomain" | "starterAwake" | "skills";
export interface RegistryDeps {
cfg(): AppConfig;
/** PUT /api/config as Settings does; a refusal comes back as its text. */
@@ -61,6 +65,10 @@ export interface RegistryDeps {
/** Moves bots into a sidebar group, making it when new; an empty name ungroups them. */
groupBots(name: string, botIds: string[]): Promise<string | null>;
pinBot(botId: string, pinned: boolean): Promise<string | null>;
+ /** PATCH /api/bots/:id as the bot's Settings panel does; a refusal comes back as its text. */
+ patchBot(botId: string, body: Record<string, unknown>): Promise<string | null>;
+ /** Another of the Settings window's routes, called as the window calls it. */
+ call(route: AppRoute, method: "POST" | "PUT" | "PATCH" | "DELETE", path: string, body?: Record<string, unknown>): Promise<string | null>;
credentials(): CredentialConfig;
window: { read(id: WindowPrefId): unknown; write(id: WindowPrefId, value: unknown): string | null };
/** The engines Settings → AI lists; never a key. */
@@ -80,7 +88,17 @@ const KEY_WHERE: Partial<Record<CredentialTargetId, Where>> = {
onePasswordToken: "Settings → Vault", boxToken: "Settings → Desktops & browser", composioApiKey: "Settings → AI",
};
-type WritableSpec = Omit<Base, "read"> & Omit<Writable, "write" | "describe"> & { read?(): string; write(value: never): Promise<string | null>; describe?(value: never): { change: string } | { refusal: string } };
+export type WritableSpec = Omit<Base, "read"> & Omit<Writable, "write" | "describe"> & { read?(): string; write(value: never): Promise<string | null>; describe?(value: never): { change: string } | { refusal: string } };
+export type WindowPref = (id: WindowPrefId, label: string, help: string, where: Where, synonyms: string[], allowed: string,
+ confirm?: { says(value: never): string; value?: z.ZodType }) => SettingEntry;
+
+/** Security: a key never passes through the bot. A value naming a key, token, secret or password field is refused at
+ * the boundary; `except` lets through a field that only names a saved key. */
+export const withoutKeys = <T extends z.ZodType>(schema: T, except: readonly string[] = []) => z.record(z.string(), z.unknown())
+ .refine((fields) => !Object.keys(fields).some((field) => !except.includes(field) && /key|token|secret|password/i.test(field)),
+ "Never put a key or token in the value. Save it first with set on keys.<id> (a secure card asks the user), then name that id in keyFrom.")
+ // The record check above already holds an object; the schema decides its shape.
+ .pipe(schema as unknown as z.ZodType<z.output<T>, Record<string, unknown>>);
const PROVIDER_KEY_SECTION = {
openaiApiKey: "openai", anthropicApiKey: "anthropic", openrouterApiKey: "openrouter", mistralApiKey: "mistral", cerebrasApiKey: "cerebras",
@@ -94,15 +112,12 @@ const engineName = z.string().trim().min(1).max(80);
const engineUrl = z.string().trim().min(1).max(512);
/** Security: a key never passes through the bot. An engine that needs one names a key the person saved through the
* secure card (`keyFrom`), and the server reads it at the moment the owner taps Change. */
-const engineChange = z.record(z.string(), z.unknown())
- .refine((fields) => !Object.keys(fields).some((field) => field !== "keyFrom" && /key|token|secret|password/i.test(field)),
- "Never put a key or token in the value. Save it first with set on keys.<id> (a secure card asks the user), then name that id in keyFrom.")
- .pipe(z.discriminatedUnion("kind", [
+const engineChange = withoutKeys(z.discriminatedUnion("kind", [
z.object({ kind: z.enum(["ollama", "lmstudio"]), name: engineName.optional(), url: engineUrl }).strict(),
z.object({ kind: z.literal("openai-compat"), name: engineName, url: engineUrl, keyFrom: z.enum(PROVIDER_CREDENTIAL_TARGETS), models: z.array(z.string().trim().min(1).max(200)).max(64).optional() }).strict(),
z.object({ kind: z.literal("bedrock"), name: engineName, awsProfile: z.string().trim().min(1).max(128), awsRegion: z.string().trim().min(1).max(40), model: z.string().trim().min(1).max(160) }).strict(),
z.object({ kind: z.literal("remove"), instanceId: z.string().regex(/^[\w.-]{1,120}$/) }).strict(),
- ]));
+ ]), ["keyFrom"]);
type EngineChange = z.infer<typeof engineChange>;
/** The engines a bot may remove: added without a sign-in. Accounts and the built-in engines stay with the owner. */
const removableKind = (instanceId: string, entry: InstanceConfig | undefined) => isAddedEndpoint(instanceId, entry) ? "OpenAI-compatible server"
@@ -113,8 +128,12 @@ export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {
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) });
+ /** With `confirm`, a Change/Cancel card says what the new value does, and the window is told only on Change. */
+ const windowPref: WindowPref = (id, label, help, where, synonyms, allowed, confirm) => writable({
+ id, label, help, where, synonyms, tier: confirm ? "confirm" : "safe", value: confirm?.value ?? WINDOW_PREFS[id], allowed,
+ current: () => deps.window.read(id), write: async (value: unknown) => deps.window.write(id, value),
+ ...(confirm ? { describe: (value: never) => ({ change: confirm.says(value) }) } : {}),
+ });
const enumOf = (values: readonly string[]) => values.join(", ");
const pinned = () => deps.bots().filter((bot) => bot.pinned).map((bot) => bot.id);
const groups = () => Object.fromEntries(deps.sections().map((section) => [section, deps.bots().filter((bot) => bot.section === section).map((bot) => bot.id)]));
@@ -276,17 +295,23 @@ export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {
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"),
+ ownerOnly("data.backups", "Backups", "Making a backup (it takes a password), restoring or deleting one, and the daily company backup (it takes a typed confirmation).", "Settings → Data",
+ ["backup", "backups", "restore", "export", "import", "schedule"], () => "managed in Settings"),
+ ownerOnly("phone.pairing", "Paired devices", "Pairing a phone or computer with a code, removing one, and what each paired device may do.", "Settings → Phone & devices",
+ ["pair", "pairing", "qr", "code", "paired", "revoke", "remove device", "device access"], () => "managed in Settings"),
+ ownerOnly("computer.lending", "Lending this computer", "Which folders and apps this computer lends to a Cloud or server; each grant is picked and confirmed in the desktop app's own dialogs.", "Settings → Desktops & browser",
+ ["lend", "lending", "share computer", "share folders", "pause sharing"], () => "managed in Settings"),
+ ownerOnly("data.keepHere", "Keep bots on this computer", "Whether this computer's bots stay here or move to My Cloud; the desktop app takes it only from the person's own click.", "Settings → Data",
+ ["keep here", "move to cloud", "move back", "bring back"], () => "managed in Settings"),
+ ownerOnly("appearance.sidebarPicture", "Sidebar picture", "The picture at the top of the sidebar; it is a file the person picks or removes.", "Settings → Overview",
+ ["wallpaper", "background", "banner", "sidebar image", "picture"], () => "managed in Settings"),
+ ownerOnly("account.organization", "Organization", "Joining or leaving a company's managed MausBot; it signs in through the company's portal.", "Settings → Your account",
+ ["organization", "organisation", "company", "managed"], () => "managed in Settings"),
];
- return [...safe, ...confirm, engines, ...secret, ...owner];
+ return [...safe, ...confirm, engines, ...botEntries(deps, writable), ...configEntries(deps, writable), ...windowEntries(windowPref), ...secret, ...owner];
}
export function findSettings(entries: readonly SettingEntry[], query: string, limit = 8): SettingEntry[] {
@@ -308,18 +333,27 @@ export function findSettings(entries: readonly SettingEntry[], query: string, li
export function routeBackedRegistry(deps: {
cfg(): AppConfig;
store: Pick<Store, "bots" | "sections" | "tasks">;
- routes: { config: RouteHandler; botOrder: RouteHandler; botPatch: RouteHandler; sections: RouteHandler; instances: RouteHandler };
+ routes: { config: RouteHandler; botOrder: RouteHandler; botPatch: RouteHandler; sections: RouteHandler; instances: RouteHandler } & Record<AppRoute, RouteHandler>;
providers: Pick<ProviderRegistry, "instances" | "lastSnapshot">;
credentials(): CredentialConfig;
window: RegistryDeps["window"];
}): SettingEntry[] {
const auth: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
- const refusal = async (reply: Promise<RouteReply>) => { const { status, body } = await reply; return status < 300 ? null : String(body.error ?? `HTTP ${status}`); };
+ const refusal = async (reply: Promise<RouteReply>) => {
+ try {
+ const { status, body } = await reply;
+ return status < 300 ? null : String(body.error ?? `HTTP ${status}`);
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ };
return createSettingsRegistry({
cfg: deps.cfg, bots: () => deps.store.bots, sections: () => deps.store.sections, credentials: deps.credentials, window: deps.window,
saveConfig: (patch) => refusal(callRoute(deps.routes.config, { method: "PUT", path: "/api/config", body: patch, auth })),
reorderBots: (botIds) => refusal(callRoute(deps.routes.botOrder, { method: "PUT", path: "/api/bots/order", body: { botIds }, auth })),
pinBot: (botId, pinned) => refusal(callRoute(deps.routes.botPatch, { method: "PATCH", path: `/api/bots/${encodeURIComponent(botId)}`, body: { pinned }, auth })),
+ patchBot: (botId, body) => refusal(callRoute(deps.routes.botPatch, { method: "PATCH", path: `/api/bots/${encodeURIComponent(botId)}`, body, auth })),
+ call: (route, method, path, body) => refusal(callRoute(deps.routes[route], { method, path, ...(body ? { body } : {}), auth })),
groupBots: (name, botIds) => refusal(callRoute(deps.routes.sections, { method: "POST", path: "/api/sidebar-sections", body: { name, botIds }, auth })),
engines: () => deps.providers.instances().filter((instance) => instance.enabled).map((instance) => ({
instanceId: instance.instanceId, working: deps.providers.lastSnapshot(instance.instanceId)?.state === "available",
diff --git a/server/config.ts b/server/config.ts
index 39ecc3b994..e98765a072 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -427,7 +427,7 @@ const storedAppConfigSchema = appConfigSchema.extend(helperStoredShape).extend({
}).optional(),
});
const appConfigPatchSchema = appConfigSchema.omit({ instances: true, mcpServers: true, cliStartup: true, customDomain: true })
- .extend({ threads: threadsPatchSchema.optional(), newBots: newBotsPatchSchema.optional(), imageGen: imageGenPatchSchema.optional() });
+ .extend({ threads: threadsPatchSchema.optional(), newBots: newBotsPatchSchema.optional(), imageGen: imageGenPatchSchema.optional() }); export const CONFIG_PATCH_FIELDS = appConfigPatchSchema.shape;
const jsonObjectSchema = z.record(z.string(), z.json());
export interface AppConfig extends HelperConfig {
diff --git a/server/index.ts b/server/index.ts
index 69e2c1c3e2..547afecd61 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -597,7 +597,7 @@ import { createUpdateCheckRoutes, updateRouteDeps } from "./routes/update-check.
import { createBrowserSiteRoutes } from "./routes/browser-sites.ts";
import { createInternalSignInRoutes } from "./routes/sign-in.ts";
import { createInternalMcpRoutes } from "./routes/internal-mcp.ts";
-import { createInternalAppSettingsRoutes, createWindowPrefs } from "./routes/app-settings.ts";
+import { createInternalAppSettingsRoutes, createWindowPrefs } from "./routes/app-settings.ts"; import { createCustomDomainRoutes } from "./routes/custom-domain.ts";
import { createAppSettings } from "./app-settings/host.ts";
import { routeBackedRegistry } from "./app-settings/registry.ts";
import { createTrustAnswers } from "./host/trust-answers.ts";
@@ -798,7 +798,6 @@ const customDomainVerifier = createCustomDomainVerifier({ environmentId: ENVIRON
const emailSignIn = createEmailSignIn({
allow: signInAllowList,
});
-let customDomainRevision = 0;
function savedCustomDomain(): string | null {
if (DESKTOP_MANAGED || !cfg.customDomain) return null;
try { return normalizeCustomDomain(cfg.customDomain); }
@@ -12058,7 +12057,7 @@ const cloudMoveRoutes = createCloudMoveRoutes();
// `workspaceAccess` is assigned at boot, after this line: read it per request.
ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") })); ROUTES.push(createStopLineRoutes());
const orgInstallStatuses = () => orgLibrary?.installStatuses() ?? new Map();
-ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) })); ROUTES.push(createStarterAwakeRoutes({ awake: starterAwake }));
+ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) })); const starterAwakeRoutes = createStarterAwakeRoutes({ awake: starterAwake }); ROUTES.push(starterAwakeRoutes);
ROUTES.push(createSharedComputerRoutes({ enabled: (auth) => lendingEnabled() || (ownerLends() && ownHome.owner(auth)), computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,
cloudHomeLender: CLOUD_HOME ? CLOUD_HOME_LENDER : null, principal: sessionLendingPrincipal, personKey, power: () => cloudPower, links: CLOUD_HOME ? deviceLinks : null, upgrades, asks: computerAsks?.asks ?? null, answerer: cardAnswererFor }));
// `routines` is assigned at boot, so it is read per request.
@@ -12132,7 +12131,7 @@ ROUTES.push(createBotLifecycleRoutes({
store, routines: () => routines, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,
activeGroupTurnForBot, cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle, deleteRefusal: (auth, botId) => memberDeleteRefusal(auth, store.bot(botId), Boolean(CLOUD_TEAM)),
}));
-ROUTES.push(createBotSkillsRoutes({ store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing }));
+const skillsRoutes = createBotSkillsRoutes({ store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing }); ROUTES.push(skillsRoutes);
ROUTES.push(createEmailRoutes({ service: emailService }));
ROUTES.push(phones.routes);
ROUTES.push(createSkillShareRoutes({ enabled: () => skillsHost.mode() !== "off", botExists: (id) => Boolean(store.bot(id)),
@@ -12359,7 +12358,7 @@ const instanceRoutes = createInstanceRoutes({
providerConfigBusy: { get: () => providerConfigBusy, set: (busy) => { providerConfigBusy = busy; } },
providerInstancesChanging, describeInstances, persistProviderInstance, configStatus, broadcast, testCliBinary,
cliProbeEnvironment, threadBusy, botForThread, activeGroupTurnForBot, checkInstance: testedAi.check,
-}); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const appSettings = createAppSettings({ store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, botPatch: botPatchRoutes, sections: sidebarRoutes, instances: instanceRoutes }, providers: registry, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs }), turnOwner: (turn) => phones.turnOwner(turn), guestDriven: cloudGuestDriven, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, activeGroupTurnForBot, notify, language: threadLanguage }); ROUTES.push(instanceRoutes, windowPrefs.routes);
+}); const customDomainRoutes = createCustomDomainRoutes({ desktopManaged: DESKTOP_MANAGED, status: customDomainStatus, verify: (domain) => customDomainVerifier.verify(domain), save: (origin) => { saveConfig({ customDomain: origin }); cfg.customDomain = origin; }, sessionEnded: (auth) => auth.kind === "session" && !sessions.isLive(auth.session.id) }); ROUTES.push(customDomainRoutes); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const appSettings = createAppSettings({ store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, botPatch: botPatchRoutes, sections: sidebarRoutes, instances: instanceRoutes, customDomain: customDomainRoutes, starterAwake: starterAwakeRoutes, skills: skillsRoutes }, providers: registry, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs }), turnOwner: (turn) => phones.turnOwner(turn), guestDriven: cloudGuestDriven, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, activeGroupTurnForBot, notify, language: threadLanguage }); ROUTES.push(instanceRoutes, windowPrefs.routes);
ROUTES.push(createMcpServerRoutes({
cfg, bot: (id) => store.bot(id), sessions, mcpOAuth, teamConnections,
cloudHome: CLOUD_HOME,
@@ -12762,35 +12761,6 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
});
}
if (method === "GET" && path === "/api/auth/pairing") return json(res, 200, { pairings: sessions.openPairings(), publicUrl: publicUrl(), ...(phoneRelay ? { relay: phoneRelay.status() } : {}) });
- // Admin-only by request-auth's default deny; only future pairing links change.
- if (path === "/api/settings/custom-domain") {
- res.setHeader("cache-control", "no-store");
- if (method === "GET") return json(res, 200, customDomainStatus());
- if (method === "POST" || method === "DELETE") {
- if (DESKTOP_MANAGED) return json(res, 409, { error: "Custom domains are configured on a self-hosted OpenMausBot server, not the desktop companion." });
- if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) {
- return json(res, 415, { error: "content-type must be application/json" });
- }
- if (method === "DELETE") {
- saveConfig({ customDomain: "" });
- cfg.customDomain = "";
- customDomainRevision++;
- return json(res, 200, customDomainStatus());
- }
- const body = await readBody(req, 4096);
- if (typeof body?.domain !== "string") return json(res, 400, { error: "Enter your domain name." });
- const revision = customDomainRevision;
- const verified = await customDomainVerifier.verify(body.domain);
- if (auth.kind === "session" && !sessions.isLive(auth.session.id)) {
- return json(res, 401, { error: "Your session ended. Sign in again before connecting a domain." });
- }
- if (revision !== customDomainRevision) return json(res, 409, { error: "Domain settings changed during verification. Try again." });
- saveConfig({ customDomain: verified.origin });
- cfg.customDomain = verified.origin;
- customDomainRevision++;
- return json(res, 200, customDomainStatus());
- }
- }
m = path.match(/^\/api\/auth\/pairing\/([\w-]+)$/);
if (m && method === "DELETE") {
const cancelled = sessions.cancelPairing(m[1]);
diff --git a/server/routes/custom-domain.ts b/server/routes/custom-domain.ts
new file mode 100644
index 0000000000..600f653b1f
--- /dev/null
+++ b/server/routes/custom-domain.ts
@@ -0,0 +1,39 @@
+import type { RequestAuth } from "../request-auth.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+export const CUSTOM_DOMAIN_PATH = "/api/settings/custom-domain";
+
+/** Admin-only by request-auth's default deny; only future pairing links change. */
+export function createCustomDomainRoutes(deps: {
+ desktopManaged: boolean;
+ status(): Record<string, unknown>;
+ /** Checks the domain's DNS and HTTPS live; throws a refusal the person reads. */
+ verify(domain: string): Promise<{ origin: string }>;
+ save(origin: string): void;
+ sessionEnded(auth: RequestAuth): boolean;
+}): RouteHandler {
+ let revision = 0;
+ const save = (origin: string) => { deps.save(origin); revision++; };
+ return async ({ req, res, path, method, auth, json, readBody }) => {
+ if (path !== CUSTOM_DOMAIN_PATH) return PASS;
+ res.setHeader?.("cache-control", "no-store");
+ if (method === "GET") return json(res, 200, deps.status());
+ if (method !== "POST" && method !== "DELETE") return PASS;
+ if (deps.desktopManaged) return json(res, 409, { error: "Custom domains are configured on a self-hosted OpenMausBot server, not the desktop companion." });
+ if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) {
+ return json(res, 415, { error: "content-type must be application/json" });
+ }
+ if (method === "DELETE") {
+ save("");
+ return json(res, 200, deps.status());
+ }
+ const body = await readBody(req, 4096);
+ if (typeof body?.domain !== "string") return json(res, 400, { error: "Enter your domain name." });
+ const started = revision;
+ const verified = await deps.verify(body.domain);
+ if (deps.sessionEnded(auth)) return json(res, 401, { error: "Your session ended. Sign in again before connecting a domain." });
+ if (started !== revision) return json(res, 409, { error: "Domain settings changed during verification. Try again." });
+ save(verified.origin);
+ return json(res, 200, deps.status());
+ };
+}