Skip to content

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

feat(cli): openmausbot login, status, and bots, stop, threads and computers verbs

milind-soni3e0c2373c324
diff --git a/server/cli-pairing.ts b/server/cli-pairing.ts
index 4ea8007b30..ea27b6ba58 100644
--- a/server/cli-pairing.ts
+++ b/server/cli-pairing.ts
@@ -9,7 +9,7 @@ import type { PhoneRelayStatus } from "./phone-relay.ts";
export function desktopOwnedRefusal(status: number, body: unknown): string | null {
const error = (body as { error?: unknown } | null)?.error;
if (status !== 403 || typeof error !== "string" || !error.includes("must come from the desktop app")) return null;
- return "The OpenMausBot desktop app runs this server, so it only pairs devices from the app itself: open OpenMausBot on this computer and use Settings → Phone & devices.";
+ return `The OpenMausBot desktop app runs this server, so a command here needs you signed in first: run ${cliCommand("login")} once and press Allow in the app. To pair a phone or another computer, use Settings → Phone & devices in the app.`;
}
/** A clock time a code works until: "11:22", or "tomorrow 11:22" / a date when it runs past today. */
diff --git a/server/cli-printed-commands.test.ts b/server/cli-printed-commands.test.ts
index 2cfa7f8922..47b1704165 100644
--- a/server/cli-printed-commands.test.ts
+++ b/server/cli-printed-commands.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest";
import { parseArgs } from "./cli.ts";
import { browserSignInLines, formatSessions, pairingBlock } from "./cli-pairing.ts";
import { noRouteLines, reachLines } from "./cli-reach.ts";
-import { HEADLESS_VERB_NAMES, usage } from "./cli-usage.ts";
+import { HEADLESS_VERB_NAMES, routeCli, usage } from "./cli-usage.ts";
const PLACEHOLDERS: Record<string, string> = {
"https://…": "https://maus.example.com", "<id>": "a1", ID: "a1", NAME: "kitchen", FILE: "team.yaml", EMAIL: "[email protected]",
@@ -23,9 +23,11 @@ function printedCommands(text: string): string[][] {
return found;
}
+/** `account` takes login, logout or status; a flag the usage lists beside it is login's. */
function accepted(words: string[]): string | null {
- if (HEADLESS_VERB_NAMES.has(words[0]!)) return null;
- const parsed = parseArgs(words, {});
+ const routed = routeCli(words[0] === "account" && words[1]?.startsWith("--") ? ["account", "login", ...words.slice(1)] : words);
+ if (routed.headless) return null;
+ const parsed = parseArgs(routed.argv, {});
return "error" in parsed ? parsed.error : null;
}
@@ -42,7 +44,7 @@ describe("printed commands", () => {
it("finds the commands in what serve, pair and devices print", () => {
const commands = outputs.flatMap(printedCommands);
- expect(commands.map((words) => words[0])).toEqual(expect.arrayContaining(["pair", "serve", "status", "devices"]));
+ expect(commands.map((words) => words[0])).toEqual(expect.arrayContaining(["pair", "serve", "account", "devices"]));
for (const words of commands) expect([words.join(" "), accepted(words)]).toEqual([words.join(" "), null]);
});
@@ -62,7 +64,7 @@ describe("printed commands", () => {
checked.push(`${command} ${flag}`);
}
}
- expect(checked).toEqual(expect.arrayContaining(["serve --lan", "serve --public-url", "pair --phone", "pair --ttl"]));
+ expect(checked).toEqual(expect.arrayContaining(["serve --lan", "serve --public-url", "pair --phone", "pair --ttl", "account --email", "account --relay"]));
});
it("writes commands the way the CLI was started", () => {
diff --git a/server/cli-reach.test.ts b/server/cli-reach.test.ts
index dadd0d0c7b..d14789d771 100644
--- a/server/cli-reach.test.ts
+++ b/server/cli-reach.test.ts
@@ -46,7 +46,7 @@ describe("the Reach line", () => {
it("says what to fix when it doesn't, as a command that pastes", () => {
expect(reachLines("public-url", "https://maus.example.com", 8799, "npx openmausbot", { ok: false, kind: "unreachable", reason: "connection refused" })).toEqual([
"Reach ✗ https://maus.example.com doesn't reach this server (connection refused).",
- " Point your tunnel or proxy at http://127.0.0.1:8799 (on another machine: add --lan and use this machine's address), then run: npx openmausbot status",
+ " Point your tunnel or proxy at http://127.0.0.1:8799 (on another machine: add --lan and use this machine's address), then run: npx openmausbot account status",
]);
expect(reachLines("public-url", "https://maus.example.com", 8799, "openmausbot", { ok: false, kind: "other-server" })[0]).toContain("answers as a different server");
expect(reachLines("lan", "http://192.168.1.20:8799", 8799, "openmausbot")).toEqual(["Reach http://192.168.1.20:8799 this network only, not encrypted"]);
diff --git a/server/cli-reach.ts b/server/cli-reach.ts
index 9127cab498..c0cd00a853 100644
--- a/server/cli-reach.ts
+++ b/server/cli-reach.ts
@@ -73,7 +73,7 @@ export function reachLines(route: Route, origin: string, port: number, prefix: s
if (check.ok) return [`Reach ${origin} ✓ answers as this server (${clock(check.at)})${NOTE[route] ? ` · ${NOTE[route]}` : ""}`];
if (check.kind === "other-server") return [`Reach ✗ ${origin} answers as a different server.`, ` Check your tunnel or proxy points at this machine's port ${port}.`];
if (route === "domain") return [`Reach … ${origin} doesn't answer yet (${check.reason ?? "no answer"}).`, " Check the domain's DNS points at this machine and ports 80 and 443 are open; the certificate follows."];
- return [`Reach ✗ ${origin} doesn't reach this server (${check.reason ?? "no answer"}).`, ` Point your tunnel or proxy at http://127.0.0.1:${port} (on another machine: add --lan and use this machine's address), then run: ${prefix} status`];
+ return [`Reach ✗ ${origin} doesn't reach this server (${check.reason ?? "no answer"}).`, ` Point your tunnel or proxy at http://127.0.0.1:${port} (on another machine: add --lan and use this machine's address), then run: ${prefix} account status`];
}
/** `serve` with no way in: nothing to pair from elsewhere yet, so no code; the ways in, as commands that paste. */
diff --git a/server/cli-usage.ts b/server/cli-usage.ts
index cb2ef399ca..3e07c2d419 100644
--- a/server/cli-usage.ts
+++ b/server/cli-usage.ts
@@ -1,6 +1,22 @@
-export { HEADLESS_VERBS as HEADLESS_VERB_NAMES } from "./headless/args.ts";
+import { HEADLESS_VERBS } from "./headless/args.ts";
+
+export { HEADLESS_VERBS as HEADLESS_VERB_NAMES };
+
+/** Where a command line goes: the OpenMausBot account (`account login|logout|status`, and `login --email` or `--relay`
+ * as before) and the other classic commands to cli.ts, the headless verbs to headless/main.ts. */
+export function routeCli(argv: readonly string[]): { headless: boolean; argv: string[] } {
+ if (argv[0] === "account") return { headless: false, argv: ["login", "logout", "status"].includes(argv[1] ?? "") ? argv.slice(1) : ["--help"] };
+ if (argv[0] === "login" && argv.some((arg) => /^--(?:email|relay)(?:=|$)/.test(arg))) return { headless: false, argv: [...argv] };
+ return { headless: HEADLESS_VERBS.has((argv[0] === "help" ? argv[1] : argv[0]) ?? ""), argv: [...argv] };
+}
export const HEADLESS_USAGE = `Drive a running workspace (scripts, CI, other agents):
+ openmausbot login [SERVER] sign this terminal in once: MausBot shows a card to allow it (logout, whoami, use NAME, servers)
+ openmausbot status every bot at a glance: working, waiting on you, paused, failed or idle, and its computer
+ openmausbot bots delete|pause|resume|stop (BOT… | --team T | --all) act on bots; delete asks first (--yes, --dry-run)
+ openmausbot stop (BOT… | --team T | --all) stop their work now, without pausing
+ openmausbot threads list|clear|delete BOT a bot's conversations
+ openmausbot computers list|start|sleep the bots' cloud computers
openmausbot doctor check the server answers and an engine is ready
openmausbot doctor --host check this Linux machine can run a server (exit 7 if not)
openmausbot doctor --data [--fix] check (and safely repair) this computer's data folder (exit 8 if a problem is left)
@@ -18,9 +34,10 @@ export const HEADLESS_USAGE = `Drive a running workspace (scripts, CI, other age
openmausbot token create NAME --out FILE [--expires 90d] a token for CI that ends on its date (token list, token revoke ID)
openmausbot new-bot | new-channel | set-model | edit | mcp
- Server: --url URL (or OPENMAUSBOT_URL), --port N (or OMB_PORT), else this computer's.
- Token: OPENMAUSBOT_TOKEN or --token-file FILE. --json prints one JSON document;
- progress goes to stderr (--quiet drops it). openmausbot help VERB for the details.`;
+ Server: --url URL (or OPENMAUSBOT_URL), --port N (or OMB_PORT), else the one you signed in to, else this computer's.
+ Token: your openmausbot login, or OPENMAUSBOT_TOKEN or --token-file FILE for scripts. --json prints one JSON document;
+ progress goes to stderr (--quiet drops it). Exit: 0 done, 1 failed, 2 usage, 4 needs login, 5 not allowed,
+ 6 busy, 7 not found. openmausbot help VERB for the details.`;
/** The usage text, its commands written the way this CLI was started (`npx openmausbot …`). */
export function usage(prefix = "openmausbot"): string {
@@ -36,10 +53,8 @@ export const USAGE = `openmausbot — your team of AI bots, ready in a few steps
[--public-url https://host | --domain HOST | --tunnel | --tailscale] [--lan] [--relay]
openmausbot pair [--label NAME] [--phone [ios|android]] [--ttl 24h] [--public-url https://host]
openmausbot devices [revoke ID]
- openmausbot status
openmausbot --version
- openmausbot login [--email [email protected]] [--relay]
- openmausbot logout
+ openmausbot account login [--email [email protected]] [--relay] | logout | status
openmausbot access list | add EMAIL [--chat-only] | remove EMAIL
openmausbot service install [the same way-in options as serve] [--port N] [--data-dir DIR] | uninstall
[--sentinel] (the health scan below, every two minutes, instead of the server)
@@ -61,12 +76,11 @@ pair a new pairing code for the running server, with its link and QR
(--phone: chat and approvals only; --ttl keeps it open up to 24h,
still single use)
devices lists paired devices; "devices revoke ID" signs one out
-status the running server, the address others reach it at, and whether
- that address answers as this server
-login signs this machine in to an OpenMausBot account (an emailed code)
- and reserves its public address for --tunnel; with --relay it
- reserves none, for serve --relay
-logout releases that address and signs out
+account login signs this machine in to an OpenMausBot account (an emailed
+ code) and reserves its public address for --tunnel; with --relay it
+ reserves none, for serve --relay. account logout releases that
+ address and signs out. account status: the running server, the
+ address others reach it at, and whether that address answers as it
access who may sign in with an emailed code at /pair: an address or
@domain; --chat-only gives chat and approvals without settings.
Takes effect at once, no restart.
@@ -100,7 +114,7 @@ Ways in (pick one; --lan can join any):
when serve stops
--tunnel serve at a public https://c-… address through a
Cloudflare tunnel: no domain, no proxy, no open port. Run
- \`openmausbot login\` once on this machine first.
+ \`openmausbot account login\` once on this machine first.
--domain serve at https://HOST on your own domain: a pinned Caddy is
downloaded once and run alongside the server, and gets the
certificate itself. Point the domain's DNS at this machine and
@@ -109,7 +123,7 @@ Ways in (pick one; --lan can join any):
--relay phones only, and it can join any of the above except --tunnel:
the MausBot phone app pairs by QR through MausBot Relay,
end-to-end encrypted, with no address, open port or VPN. Run
- \`openmausbot login --relay\` once on this machine first. Not on a
+ \`openmausbot account login --relay\` once on this machine first. Not on a
machine with a tunnel address: the relay stays off there.
--no-open do not open a browser window
diff --git a/server/cli.test.ts b/server/cli.test.ts
index 6e59a7084d..f1a6ffcd2e 100644
--- a/server/cli.test.ts
+++ b/server/cli.test.ts
@@ -461,7 +461,7 @@ describe.skipIf(process.platform === "win32")("serve --tunnel", () => {
child.stderr?.on("data", (chunk) => (err += String(chunk)));
try {
expect(await exited(child)).toBe(1);
- expect(err).toContain("run openmausbot login first");
+ expect(err).toContain("run openmausbot account login first");
let dead = false;
try {
await fetch(`http://127.0.0.1:${port}/api/health`);
diff --git a/server/cli.ts b/server/cli.ts
index c812145d09..0d1f69f32c 100644
--- a/server/cli.ts
+++ b/server/cli.ts
@@ -6,9 +6,9 @@
// [--public-url https://host] [--tailscale | --tunnel | --domain HOST] [--relay] [--no-pair]
// openmausbot pair [--label "My MacBook"] [--client] [--public-url https://host]
// openmausbot sessions [revoke <id>]
-// openmausbot status
-// openmausbot login [--email [email protected]] [--relay]
-// openmausbot logout
+// openmausbot account status
+// openmausbot account login [--email [email protected]] [--relay]
+// openmausbot account logout
// openmausbot run | send | wait | doctor | team apply | export | …
//
// This module only exports: openmausbot.ts runs main(), so bundling this file into other entries never runs it twice.
@@ -38,7 +38,7 @@ import { startFleetAgent } from "./fleet-agent.ts";
import { fleetLayout } from "./fleet.ts";
import { clearLeftoverTailscaleServe, explainTailscaleFailure, tailnetListenFallback, tailscaleServe, tailscaleStatus, type TailscaleStatus } from "./tailscale.ts";
import { defaultSetupIo, SetupCancelled, type SetupIo } from "./cli-prompts.ts";
-import { HEADLESS_VERB_NAMES, usage } from "./cli-usage.ts";
+import { routeCli, usage } from "./cli-usage.ts"; import { savedSessionHeaders } from "./headless/saved-servers.ts";
import { normalizePhoneOrigin, phonePairingInstructions, runPhoneSetup } from "./cli-phone-setup.ts";
import { browserSignInLines, desktopOwnedRefusal, formatSessions, pairingBlock, RELAY_NOT_WITH_TUNNEL, relayPairingBlock, showRelayPairing } from "./cli-pairing.ts";
import { cliCommand, cliPrefix } from "./cli-invocation.ts";
@@ -255,7 +255,7 @@ let serveOwnerToken: string | undefined;
async function api(port: number, path: string, init: { method?: string; body?: string } = {}): Promise<{ status: number; body: any }> {
// x-openmausbot-cli names the tool in the activity log; on loopback it grants nothing.
- const headers: Record<string, string> = { "content-type": "application/json", "x-openmausbot-cli": "1", ...(serveOwnerToken ? { "x-openmausbot-cli-owner": serveOwnerToken } : {}) };
+ const headers: Record<string, string> = { "content-type": "application/json", "x-openmausbot-cli": "1", ...(serveOwnerToken ? { "x-openmausbot-cli-owner": serveOwnerToken } : path.startsWith("/api/auth/") ? await savedSessionHeaders(`http://127.0.0.1:${port}`) : {}) };
const res = await fetch(`http://127.0.0.1:${port}${path}`, { method: init.method, body: init.body, headers, signal: AbortSignal.timeout(3000) });
const body: unknown = await res.json().catch(() => ({}));
return { status: res.status, body };
@@ -388,7 +388,7 @@ export async function runSessions(options: CliOptions): Promise<number> {
return 1;
}
if (status !== 200) {
- console.error(`could not revoke: ${typeof body?.error === "string" ? body.error : status}`);
+ console.error(desktopOwnedRefusal(status, body) ?? `could not revoke: ${typeof body?.error === "string" ? body.error : status}`);
return 1;
}
console.log(`revoked ${options.revoke}: that device is signed out and its stream is closed`);
@@ -642,18 +642,18 @@ async function planTunnel(options: CliOptions, log: (line: string) => void, reco
account = createTunnelAccount({ dataDir: options.dataDir, version: reportableServerVersion(), recovery, log: (line) => log(`tunnel: ${line}`) });
if (account.credentials.status === "unavailable") return fail(`${account.credentials.file} exists but could not be read; fix or remove it`);
if (!describeTunnelAccount(account.credentials.read()).email) {
- return fail(`no account on this machine yet: run ${cliCommand("login")} first, then ${cliCommand("serve --tunnel")}`);
+ return fail(`no account on this machine yet: run ${cliCommand("account login")} first, then ${cliCommand("serve --tunnel")}`);
}
try {
const state = await account.service.retry();
const saved = tunnelAccess(account.credentials.read()) !== null;
- if (state.status === "signed-out") log(`tunnel: the sign-in on this machine expired; run ${cliCommand("login")} to renew it${saved ? " (serving the saved address until then)" : ""}`);
+ if (state.status === "signed-out") log(`tunnel: the sign-in on this machine expired; run ${cliCommand("account login")} to renew it${saved ? " (serving the saved address until then)" : ""}`);
else if (state.message) log(`tunnel: ${state.message}${saved ? " Serving the saved address for now." : ""}`);
} catch (error) {
log(`tunnel: control plane not reachable right now (${message(error)}); using the saved address`);
}
access = tunnelAccess(account.credentials.read());
- if (!access) return fail(`this machine has no public address; run ${cliCommand("login")} again`);
+ if (!access) return fail(`this machine has no public address; run ${cliCommand("account login")} again`);
}
let binary: string;
try {
@@ -975,7 +975,7 @@ export async function runOnboardingCommand(
export async function main(argv = process.argv.slice(2)): Promise<number> {
if (argv[0] === "sentinel") return runSentinelCli(argv.slice(1));
if (argv[0] === "config") return runConfigCli(argv.slice(1));
- if (HEADLESS_VERB_NAMES.has(argv[0] ?? "") || (argv[0] === "help" && HEADLESS_VERB_NAMES.has(argv[1] ?? ""))) return (await import("./headless/main.ts")).runHeadless(argv);
+ const routed = routeCli(argv); if (routed.headless) return (await import("./headless/main.ts")).runHeadless(routed.argv); argv = routed.argv;
const options = parseArgs(argv);
if ("error" in options) {
console.error(`${options.error}\nAll commands and options: ${cliCommand("--help")}`);
diff --git a/server/headless/args.test.ts b/server/headless/args.test.ts
index fcff173213..6def151dc1 100644
--- a/server/headless/args.test.ts
+++ b/server/headless/args.test.ts
@@ -40,10 +40,29 @@ describe("parseCommand", () => {
});
it("knows which verbs change something", () => {
- for (const verb of ["send", "run", "interrupt", "team apply", "engine set", "token create", "token revoke"]) expect(MUTATING_VERBS.has(verb), verb).toBe(true);
- for (const verb of ["doctor", "bots", "wait", "messages", "export", "events", "team export", "engine list"]) expect(MUTATING_VERBS.has(verb), verb).toBe(false);
- expect([...HEADLESS_VERBS].sort()).toEqual(["bots", "channels", "connect", "doctor", "edit", "engine", "events", "export", "interrupt", "mcp",
- "messages", "models", "new-bot", "new-channel", "run", "send", "send-channel", "set-model", "team", "token", "wait"]);
+ for (const verb of ["send", "run", "interrupt", "team apply", "engine set", "token create", "token revoke", "bots delete", "bots pause", "stop",
+ "threads clear", "threads delete", "computers start", "computers sleep"]) expect(MUTATING_VERBS.has(verb), verb).toBe(true);
+ for (const verb of ["doctor", "bots", "bots list", "bots get", "status", "whoami", "threads list", "computers list", "wait", "messages", "export", "events", "team export", "engine list"]) {
+ expect(MUTATING_VERBS.has(verb), verb).toBe(false);
+ }
+ expect([...HEADLESS_VERBS].sort()).toEqual(["bots", "channels", "computers", "connect", "doctor", "edit", "engine", "events", "export", "interrupt", "login",
+ "logout", "mcp", "messages", "models", "new-bot", "new-channel", "run", "send", "send-channel", "servers", "set-model", "status", "stop", "team",
+ "threads", "token", "use", "wait", "whoami"]);
+ });
+
+ it("keeps bare bots a list, and reads a bots, threads or computers action", () => {
+ expect(parseCommand(["bots", "--json"])).toMatchObject({ verb: "bots", flags: { json: true } });
+ expect(parseCommand(["bots", "delete", "QA 1", "QA 2", "--dry-run"])).toMatchObject({ verb: "bots delete", positionals: ["QA 1", "QA 2"], flags: { "dry-run": true } });
+ expect(parseCommand(["bots", "pause", "--team", "Support"])).toMatchObject({ verb: "bots pause", flags: { team: "Support" } });
+ expect(parseCommand(["stop", "--all", "-y"])).toMatchObject({ verb: "stop", flags: { all: true, yes: true } });
+ expect(usage(() => parseCommand(["threads"]))).toMatchObject({ exitCode: 2, message: "threads needs one of: list, clear, delete" });
+ expect(usage(() => parseCommand(["bots", "pause", "x", "--yes"]))).toMatchObject({ exitCode: 2 });
+ // no flag skips a permission or approval of any kind
+ for (const verb of ["stop", "bots delete", "threads clear", "login"]) {
+ for (const skip of ["--yolo", "--skip-permissions", "--dangerously-skip-permissions", "--token"]) {
+ expect(usage(() => parseCommand([...verb.split(" "), "x", skip])), `${verb} ${skip}`).toMatchObject({ exitCode: 2 });
+ }
+ }
});
});
diff --git a/server/headless/args.ts b/server/headless/args.ts
index c698926ee7..192bb7a62b 100644
--- a/server/headless/args.ts
+++ b/server/headless/args.ts
@@ -1,14 +1,20 @@
import { parseArgs, type ParseArgsOptionsConfig } from "node:util";
-/** What the process exits with. Scripts and CI branch on these. */
+/** What the process exits with. Scripts and CI branch on these. A refusal from the server maps the same way for every verb:
+ * needsLogin (401), notAllowed (403), conflict (409, busy) and notFound (404). `run`/`wait` keep 4 for a timeout,
+ * `team apply --check` 6 for changes and `doctor --host` 7, as they always have. */
export const EXIT = {
done: 0,
failed: 1,
usage: 2,
needsInput: 3,
timeout: 4,
+ needsLogin: 4,
unreachable: 5,
+ notAllowed: 5,
changes: 6,
+ conflict: 6,
+ notFound: 7,
/** `doctor --host`: this machine is missing something the server needs. */
hostMissing: 7,
/** `doctor --data`: the data folder has a problem left (after --fix, one it could not repair). */
@@ -57,7 +63,39 @@ const WAITING = {
strict: { type: "boolean" },
} satisfies ParseArgsOptionsConfig;
+/** Which bots a verb acts on: names or ids, a team, or every bot. */
+const SELECT = {
+ team: { type: "string" },
+ all: { type: "boolean" },
+} satisfies ParseArgsOptionsConfig;
+
+const CAREFUL = {
+ yes: { type: "boolean", short: "y" },
+ "dry-run": { type: "boolean" },
+} satisfies ParseArgsOptionsConfig;
+
+const MANY = 200;
+
const VERBS: Record<string, { options: ParseArgsOptionsConfig; positionals: number }> = {
+ login: { options: { scope: { type: "string" }, name: { type: "string" } }, positionals: 1 },
+ logout: { options: {}, positionals: 1 },
+ whoami: { options: {}, positionals: 0 },
+ use: { options: {}, positionals: 1 },
+ servers: { options: {}, positionals: 0 },
+ status: { options: {}, positionals: 0 },
+ "bots list": { options: {}, positionals: 0 },
+ "bots get": { options: {}, positionals: 1 },
+ "bots delete": { options: { ...SELECT, ...CAREFUL }, positionals: MANY },
+ "bots pause": { options: { ...SELECT, "dry-run": { type: "boolean" } }, positionals: MANY },
+ "bots resume": { options: { ...SELECT, "dry-run": { type: "boolean" } }, positionals: MANY },
+ "bots stop": { options: { ...SELECT, ...CAREFUL }, positionals: MANY },
+ stop: { options: { ...SELECT, ...CAREFUL }, positionals: MANY },
+ "threads list": { options: {}, positionals: 1 },
+ "threads clear": { options: CAREFUL, positionals: 1 },
+ "threads delete": { options: CAREFUL, positionals: MANY },
+ "computers list": { options: {}, positionals: 0 },
+ "computers start": { options: { "dry-run": { type: "boolean" } }, positionals: 1 },
+ "computers sleep": { options: { "dry-run": { type: "boolean" } }, positionals: 1 },
doctor: { options: { wait: { type: "string" }, host: { type: "boolean" }, data: { type: "boolean" }, fix: { type: "boolean" }, "data-dir": { type: "string" }, domain: { type: "string" } }, positionals: 0 },
bots: { options: {}, positionals: 0 },
channels: { options: {}, positionals: 0 },
@@ -119,6 +157,7 @@ export const HEADLESS_VERBS: ReadonlySet<string> = new Set(Object.keys(VERBS).ma
/** Verbs that change something; control-omb refuses them on a discovered server. */
export const MUTATING_VERBS: ReadonlySet<string> = new Set([
"send", "send-channel", "run", "interrupt", "new-bot", "new-channel", "set-model", "edit", "team apply", "engine set", "token create", "token revoke",
+ "bots delete", "bots pause", "bots resume", "bots stop", "stop", "threads clear", "threads delete", "computers start", "computers sleep",
]);
export type Flags = Record<string, string | boolean | string[] | undefined>;
@@ -129,7 +168,10 @@ export interface ParsedCommand {
positionals: string[];
}
-const SUBCOMMANDS = new Map([["team", ["apply", "export"]], ["engine", ["set", "list"]], ["token", ["create", "list", "revoke"]]]);
+const SUBCOMMANDS = new Map([["team", ["apply", "export"]], ["engine", ["set", "list"]], ["token", ["create", "list", "revoke"]],
+ ["threads", ["list", "clear", "delete"]], ["computers", ["list", "start", "sleep"]]]);
+/** `bots` alone still lists them, as it always has. */
+const OPTIONAL_SUBCOMMANDS = new Map([["bots", ["list", "get", "delete", "pause", "resume", "stop"]]]);
/** Strict: an unknown flag or a missing value is a usage error (exit 2). */
export function parseCommand(argv: readonly string[]): ParsedCommand {
@@ -137,6 +179,10 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
if (!head) throw usageError("name a verb", "run openmausbot help");
let verb = head;
let args = rest;
+ if (OPTIONAL_SUBCOMMANDS.get(head)?.includes(rest[0] ?? "")) {
+ verb = `${head} ${rest[0]}`;
+ args = rest.slice(1);
+ }
const actions = SUBCOMMANDS.get(head);
if (actions) {
const action = rest[0];
diff --git a/server/headless/bot-shell.ts b/server/headless/bot-shell.ts
new file mode 100644
index 0000000000..96bd7e2b08
--- /dev/null
+++ b/server/headless/bot-shell.ts
@@ -0,0 +1,15 @@
+// Inside a bot's own shell the CLI acts as that bot: it never uses the person's saved sign-in, and it signs nothing in.
+// Security: this keeps one bot from deleting or stopping the others by accident through the person's session. It is not
+// a boundary against a bot with Full access, which runs as the person and can read whatever they can.
+
+/** What OpenMausBot's server puts in the environment of the engines it starts, and so of every bot's shell: the run tag
+ * spawnCli gives each engine (engine-records.ts), the desktop app's mark on its server's children, and a turn's
+ * per-turn capability. A person's terminal has none of them. */
+const TURN_VARIABLES = ["OMB_ENGINE_TAG", "OMB_COMMS_TOKEN", "OMB_HOOK_TOKEN_FILE", "OMB_HOOK_URL", "OMB_HARNESS_URL", "OMB_BOT_ID"] as const;
+
+export function inBotShell(env: NodeJS.ProcessEnv): boolean {
+ return env.OMB_DESKTOP_PARENT === "1" || TURN_VARIABLES.some((name) => Boolean(env[name]?.trim()));
+}
+
+export const BOT_SHELL_REFUSAL = "inside a bot's shell the openmausbot command acts as that bot, so it does not sign in or use your saved sign-in";
+export const BOT_SHELL_HINT = "run this in your own terminal, or ask the person to do it";
diff --git a/server/headless/client.test.ts b/server/headless/client.test.ts
index 93c833b361..c1b1aabb69 100644
--- a/server/headless/client.test.ts
+++ b/server/headless/client.test.ts
@@ -52,14 +52,22 @@ describe("the server and the credential", () => {
describe("explain", () => {
it("turns refusals and unreachable servers into exit codes a script can branch on", async () => {
const status = (code: number, message = "nope") => Object.assign(new Error(message), { status: code });
- expect(await explain(status(401))).toMatchObject({ exitCode: 5, hint: expect.stringContaining("--token-file") });
- expect(await explain(status(403, "admin scope required"))).toMatchObject({ exitCode: 5, message: "not allowed: admin scope required" });
- expect(await explain(status(409, "stop this bot's turn first"))).toMatchObject({ exitCode: 1, message: "stop this bot's turn first" });
+ expect(await explain(status(401))).toMatchObject({ exitCode: 4, message: "this server needs you signed in", hint: "run `openmausbot login`" });
+ expect(await explain(status(401), undefined, { identity: { kind: "token" } })).toMatchObject({ exitCode: 4, message: "this server did not accept the token given" });
+ expect(await explain(status(401), undefined, { botShell: true })).toMatchObject({ exitCode: 4, hint: expect.stringContaining("your own terminal") });
+ const signedIn = { identity: { kind: "saved" as const, name: "local", label: "x", scopes: ["admin", "client"], expiresAt: 0 } };
+ expect(await explain(status(403, "admin scope required"), undefined, signedIn)).toMatchObject({ exitCode: 5, message: "not allowed: admin scope required" });
+ expect(await explain(status(403, "admin scope required"), undefined, { botShell: true })).toMatchObject({ exitCode: 5, hint: expect.stringContaining("your own terminal") });
+ expect(await explain(status(403, "OpenMausBot refused this request because the installed desktop app requires a paired session token.")))
+ .toMatchObject({ exitCode: 4, message: "not allowed: a change from a program on this computer needs you signed in", hint: expect.stringContaining("openmausbot login") });
+ expect(await explain(status(403, "admin scope required"), undefined, { identity: { kind: "saved", name: "local", label: "x", scopes: ["client"], expiresAt: 0 } }))
+ .toMatchObject({ hint: expect.stringContaining("chat only") });
+ expect(await explain(status(409, "stop this bot's turn first"))).toMatchObject({ exitCode: 6, message: "stop this bot's turn first" });
expect(await explain(status(409, 'OpenMausBot API error (409): {"error":"stop this bot\'s turn first","code":"thread_busy"}')))
- .toMatchObject({ exitCode: 1, message: "stop this bot's turn first" });
+ .toMatchObject({ exitCode: 6, message: "stop this bot's turn first" });
expect(await explain(status(403, 'OpenMausBot API error (403): {"error":"admin scope required"}'))).toMatchObject({ message: "not allowed: admin scope required" });
expect(await explain(status(502, "OpenMausBot API error (502): <html>Bad gateway</html>"))).toMatchObject({ message: "OpenMausBot API error (502): <html>Bad gateway</html>" });
- expect(await explain(status(404, 'OpenMausBot API error (404): {"error":"no such bot"}'))).toMatchObject({ exitCode: 2, message: "no such bot" });
+ expect(await explain(status(404, 'OpenMausBot API error (404): {"error":"no such bot"}'))).toMatchObject({ exitCode: 7, message: "no such bot" });
expect(await explain(status(404, "OpenMausBot API error (404): not found"))).toMatchObject({ exitCode: 1 });
expect(await explain(new TypeError("fetch failed"), "http://127.0.0.1:1")).toMatchObject({ exitCode: 5, message: "cannot reach OpenMausBot at http://127.0.0.1:1" });
expect(await explain(Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" }))).toMatchObject({ exitCode: 5 });
diff --git a/server/headless/client.ts b/server/headless/client.ts
index 1501b7252c..dd93b22b79 100644
--- a/server/headless/client.ts
+++ b/server/headless/client.ts
@@ -3,6 +3,8 @@
import { readFileSync } from "node:fs";
import { EXIT, flag, HeadlessError, usageError, type Flags } from "./args.ts";
+import { BOT_SHELL_HINT } from "./bot-shell.ts";
+import type { SavedServers } from "./saved-servers.ts";
type McpModule = typeof import("../../scripts/mcp-server.ts");
export type ToolCaller = McpModule["handleToolCall"];
@@ -15,6 +17,8 @@ export interface ClientDeps {
requireExplicitForMutations?: boolean;
callTool?: ToolCaller;
request?: Requester;
+ /** What `openmausbot login` saved; absent in a bot's shell, which never uses the person's sign-in. */
+ saved?: SavedServers;
}
const DISCOVERY_PORTS = [8799, 18799, 28799];
@@ -31,9 +35,13 @@ export async function loadMcp(): Promise<McpModule> {
}
}
+/** Who the requests go as: a token given for this command, a saved sign-in, or none (this computer, unsigned). */
+export type ClientIdentity = { kind: "token" } | { kind: "saved"; name: string; label: string; scopes: string[]; expiresAt: number } | { kind: "none" };
+
export interface HeadlessClient {
baseUrl: string;
explicit: boolean;
+ identity: ClientIdentity;
json<T = any>(path: string, init?: RequestInit): Promise<T>;
/** `stream` lifts the request timeout. */
raw(path: string, init?: RequestInit & { stream?: boolean }): Promise<Response>;
@@ -67,10 +75,14 @@ export function namedServer(flags: Flags, env: NodeJS.ProcessEnv): { url: string
export async function openClient(flags: Flags, deps: ClientDeps, mutating: boolean): Promise<HeadlessClient> {
const mcp = await loadMcp();
- const token = readToken(flags, deps.env);
+ let token = readToken(flags, deps.env);
+ let identity: ClientIdentity = token ? { kind: "token" } : { kind: "none" };
const named = namedServer(flags, deps.env);
+ const current = !named && !token ? deps.saved?.current() ?? null : null;
let baseUrl: string;
- if (named && "url" in named) {
+ if (current) {
+ baseUrl = current.url;
+ } else if (named && "url" in named) {
try {
baseUrl = mcp.validateBaseUrl(named.url);
} catch (error) {
@@ -95,7 +107,20 @@ export async function openClient(flags: Flags, deps: ClientDeps, mutating: boole
"start one with `openmausbot serve`, or name one with --url or OPENMAUSBOT_URL");
}
}
+ // A saved sign-in goes only to the exact address it was made at: the current server, or a named one that is the same.
+ const signedIn = !token ? current ?? (named ? deps.saved?.at(baseUrl) ?? null : null) : null;
+ const savedToken = signedIn ? deps.saved!.token(signedIn.name) : null;
const request = deps.request ?? mcp.request;
+ if (signedIn && savedToken) {
+ // Another server can take the same port later (the app closed, `serve` started): the sign-in is not for it.
+ const live = await request("/.well-known/openmausbot/environment", {}, baseUrl).catch(() => null) as { environmentId?: unknown } | null;
+ if (typeof live?.environmentId === "string" && live.environmentId !== signedIn.environmentId) {
+ throw new HeadlessError(`the server at ${baseUrl} is not "${signedIn.label}", the one you signed in to`, EXIT.needsLogin,
+ "sign in to it with openmausbot login, or name another server with --url");
+ }
+ token = savedToken;
+ identity = { kind: "saved", name: signedIn.name, label: signedIn.label, scopes: signedIn.scopes, expiresAt: signedIn.expiresAt };
+ }
const callTool = deps.callTool ?? mcp.handleToolCall;
const withAuth = (init: RequestInit = {}): RequestInit => {
if (!token) return init;
@@ -106,7 +131,8 @@ export async function openClient(flags: Flags, deps: ClientDeps, mutating: boole
const fetcher = (path: string, init: RequestInit = {}) => request(path, withAuth(init), baseUrl);
return {
baseUrl,
- explicit: named !== undefined,
+ explicit: named !== undefined || current !== null,
+ identity,
json: (path, init) => fetcher(path, init),
async raw(path, init = {}) {
const { stream, ...rest } = init;
@@ -129,23 +155,42 @@ export function serverWords(message: string): string {
}
}
-export async function explain(error: unknown, baseUrl?: string): Promise<HeadlessError> {
+/** What the command knew when the server refused it, for a hint that leads somewhere. */
+export interface RefusalContext {
+ botShell?: boolean;
+ identity?: ClientIdentity;
+}
+
+function signInHint(context: RefusalContext): string {
+ if (context.botShell) return BOT_SHELL_HINT;
+ if (context.identity?.kind === "token") return "the token given was not accepted, or lacks the scope: make a new one with openmausbot token create";
+ if (context.identity?.kind === "saved" && !context.identity.scopes.includes("admin")) {
+ return "this sign-in is chat only: run openmausbot login again without --scope chat";
+ }
+ return "sign in once with `openmausbot login` (the app shows a card to allow it)";
+}
+
+export async function explain(error: unknown, baseUrl?: string, context: RefusalContext = {}): Promise<HeadlessError> {
if (error instanceof HeadlessError) return error;
const mcp = await loadMcp().catch(() => undefined);
- const message = serverWords(error instanceof Error ? error.message : String(error));
+ const raw = error instanceof Error ? error.message : String(error);
+ const message = serverWords(raw);
if (mcp && error instanceof mcp.ToolInputError) return usageError(message);
const status = typeof (error as { status?: unknown })?.status === "number" ? (error as { status: number }).status : undefined;
if (status === 401) {
- return new HeadlessError("this server needs a credential and did not accept the one given", EXIT.unreachable,
- "get one with `openmausbot connect URL --out FILE`, then pass --token-file FILE or set OPENMAUSBOT_TOKEN");
+ const said = context.identity?.kind === "saved" ? "your sign-in to this server ended" : context.identity?.kind === "token" ? "this server did not accept the token given" : "this server needs you signed in";
+ return new HeadlessError(said, EXIT.needsLogin,
+ context.botShell ? BOT_SHELL_HINT : context.identity?.kind === "token" ? signInHint(context) : "run `openmausbot login`");
}
if (status === 403) {
- return new HeadlessError(`not allowed: ${message}`, EXIT.unreachable,
- "this needs a paired session with the right scope: `openmausbot connect` mints one on this computer");
+ const said = message === raw && /paired session token/.test(raw) ? "a change from a program on this computer needs you signed in" : message;
+ const unsigned = !context.botShell && (context.identity === undefined || context.identity.kind === "none");
+ return new HeadlessError(`not allowed: ${said.replace(/^forbidden: /, "")}`, unsigned ? EXIT.needsLogin : EXIT.notAllowed, signInHint(context));
}
if (status === 404 && /^no such (bot|channel|conversation|task|message)\b/i.test(message)) {
- return usageError(message, "openmausbot bots and openmausbot channels list the ids");
+ return new HeadlessError(message, EXIT.notFound, "openmausbot bots and openmausbot channels list the ids");
}
+ if (status === 409) return new HeadlessError(message, EXIT.conflict, "it is busy: stop it first (openmausbot stop BOT), or try again when it finishes");
if (/cannot report a conversation's job/.test(message)) return new HeadlessError(message, EXIT.unreachable, "update OpenMausBot on the server");
const cause = (error as { cause?: { code?: unknown } })?.cause?.code;
if ((error instanceof TypeError && /fetch failed/i.test(message)) || cause === "ECONNREFUSED" || cause === "ENOTFOUND"
diff --git a/server/headless/commands.ts b/server/headless/commands.ts
index db9137dcf7..46927a17e4 100644
--- a/server/headless/commands.ts
+++ b/server/headless/commands.ts
@@ -42,7 +42,7 @@ async function doctorOnce(ctx: VerbContext): Promise<VerbOutcome> {
if (tooOld) problems.push(`OpenMausBot ${server!.version ?? "(unknown version)"} is too old for the headless commands: it cannot report a conversation's job`);
if (isOmb && !availableCount) problems.push("no engine is available: set one up with `openmausbot engine set KIND --key-env VAR`");
if (session?.kind === "session" && typeof session.expiresAt === "number" && session.expiresAt - Date.now() < 14 * DAY) {
- warnings.push(`this session expires in ${Math.max(0, Math.floor((session.expiresAt - Date.now()) / DAY))} days: get a new one with openmausbot connect`);
+ warnings.push(`this session expires in ${Math.max(0, Math.floor((session.expiresAt - Date.now()) / DAY))} days: sign in again with openmausbot login (a script: openmausbot token create)`);
}
const browser = config?.browserEngine ?? null;
if (browser && browser.kind !== "engine") warnings.push(`bots have no built-in browser here: ${browser.reason ?? "not installed"}${browser.installable ? " (install it with `openmausbot browser install`)" : ""}`);
@@ -98,14 +98,15 @@ export async function doctor(ctx: VerbContext): Promise<VerbOutcome> {
}
export async function list(ctx: VerbContext): Promise<VerbOutcome> {
- const tool = ctx.verb === "bots" ? "list_bots" : ctx.verb === "channels" ? "list_channels" : "list_available_models";
+ const bots = ctx.verb === "bots" || ctx.verb === "bots list";
+ const tool = bots ? "list_bots" : ctx.verb === "channels" ? "list_channels" : "list_available_models";
const result = await (await ctx.client()).tool(tool, {});
- const human = ctx.verb === "bots"
+ const human = bots
? (result.bots as Rec[]).map((bot) => `${bot.name}${bot.title ? ` — ${bot.title}` : ""} · ${bot.section ? `team ${bot.section}` : "no team"}${bot.chiefOfStaff ? " · Chief of Staff" : ""} · ${bot.activity === "waiting-on-you" ? "waiting on you" : bot.busy ? "working" : bot.waitingForTeammates ? "waiting on teammates" : "idle"} · id ${bot.id}`)
: ctx.verb === "channels"
? (result.channels as Rec[]).map((room) => `${room.name} · ${room.memberIds?.length ?? 0} members · ${room.working ? "working" : "idle"} · id ${room.id}`)
: (result.instances as Rec[]).map((instance) => `${instance.instanceId} · ${instance.snapshot?.state ?? "unknown"}${instance.models?.default ? ` · default ${instance.models.default}` : ""}${Array.isArray(instance.models?.options) ? ` · ${instance.models.options.length} models` : ""}`);
- return { result, exitCode: EXIT.done, human: human.length ? human : [`No ${ctx.verb === "models" ? "engines" : ctx.verb} yet.`] };
+ return { result, exitCode: EXIT.done, human: human.length ? human : [`No ${ctx.verb === "models" ? "engines" : bots ? "bots" : ctx.verb} yet.`] };
}
export async function messages(ctx: VerbContext): Promise<VerbOutcome> {
diff --git a/server/headless/connect.ts b/server/headless/connect.ts
index 9706e6757c..15ad99f9a8 100644
--- a/server/headless/connect.ts
+++ b/server/headless/connect.ts
@@ -83,8 +83,11 @@ export async function connectVerb(ctx: VerbContext): Promise<VerbOutcome> {
if (!code) {
const minted = await call(origin, "/api/auth/pairing", { method: "POST", body: JSON.stringify({ label, ...(ctx.flags.client ? { scopes: ["client"] } : {}) }) });
if (minted.status !== 200 || typeof minted.body.code !== "string") {
+ const desktop = typeof minted.body.error === "string" && minted.body.error.includes("must come from the desktop app");
throw new HeadlessError(`this server will not mint a pairing code for a command on this computer${minted.body.error ? ` (${minted.body.error})` : ""}`,
- EXIT.unreachable, `${cliCommand("pair")} in a terminal on this computer, then pass --code CODE`);
+ EXIT.notAllowed, desktop
+ ? `the MausBot app runs this server: run ${cliCommand("login")} instead and press Allow in the app, or make a code in Settings → Phone & devices and pass --code CODE`
+ : `${cliCommand("pair")} in a terminal on this computer, then pass --code CODE`);
}
code = minted.body.code as string;
}
diff --git a/server/headless/context.ts b/server/headless/context.ts
index ac459088f8..214b499471 100644
--- a/server/headless/context.ts
+++ b/server/headless/context.ts
@@ -4,6 +4,7 @@ import { readFileSync } from "node:fs";
import { flag, oneOf, parseDuration, usageError, type Flags } from "./args.ts";
import type { HeadlessClient } from "./client.ts";
import type { HeadlessIo, Output } from "./output.ts";
+import type { SavedServers } from "./saved-servers.ts";
export interface VerbContext {
verb: string;
@@ -15,6 +16,16 @@ export interface VerbContext {
client(): Promise<HeadlessClient>;
signal: AbortSignal;
defaultWaitMs: number;
+ /** Running in a bot's own shell: it acts as that bot (bot-shell.ts). */
+ botShell: boolean;
+ /** What `openmausbot login` saved; null in a bot's shell. */
+ saved: SavedServers | null;
+ /** Someone is at a terminal to answer a question. */
+ interactive: boolean;
+ /** Asks a yes-or-no question on the terminal; only called when `interactive`. */
+ confirm(question: string): Promise<boolean>;
+ /** Opens a web page in the person's browser; false when it could not. */
+ openBrowser(url: string): Promise<boolean>;
}
export interface VerbOutcome {
diff --git a/server/headless/events-reconnect.test.ts b/server/headless/events-reconnect.test.ts
index 1250ca0e7b..3c9e6e7c23 100644
--- a/server/headless/events-reconnect.test.ts
+++ b/server/headless/events-reconnect.test.ts
@@ -15,7 +15,7 @@ function fixture(onProgress: () => void = () => undefined) {
let attempts = 0;
const io: HeadlessIo = { out: () => undefined, err: onProgress, readStdin: async () => "" };
const client: HeadlessClient = {
- baseUrl: "http://127.0.0.1:1", explicit: true,
+ baseUrl: "http://127.0.0.1:1", explicit: true, identity: { kind: "none" },
json: async <T>() => ({} as T),
tool: async () => ({}),
raw: async (_path, init) => {
@@ -28,6 +28,7 @@ function fixture(onProgress: () => void = () => undefined) {
verb: "events", flags: {}, positionals: [], env: {}, io,
output: new Output(io, {}), client: async () => client,
signal: controller.signal, defaultWaitMs: 1_000,
+ botShell: false, saved: null, interactive: false, confirm: async () => false, openBrowser: async () => false,
};
return { controller, ctx, signal: () => streamSignal!, attempts: () => attempts };
}
diff --git a/server/headless/events.test.ts b/server/headless/events.test.ts
index cc70209636..6927cadeec 100644
--- a/server/headless/events.test.ts
+++ b/server/headless/events.test.ts
@@ -106,8 +106,8 @@ describe("events against a server", () => {
answer = (_req, res) => { res.writeHead(401, { "content-type": "application/json" }); res.end(JSON.stringify({ error: "unauthorized: this session has expired or was revoked" })); };
const { io, out } = capture();
const code = await runHeadless(["events", "--json"], { io, env: { OPENMAUSBOT_URL: origin, OPENMAUSBOT_TOKEN: "omb_sess_expired" } });
- expect(code).toBe(5);
- expect(JSON.parse(out.join("\n"))).toMatchObject({ ok: false, exitCode: 5, error: "this server needs a credential and did not accept the one given" });
+ expect(code).toBe(4);
+ expect(JSON.parse(out.join("\n"))).toMatchObject({ ok: false, exitCode: 4, error: "this server did not accept the token given" });
expect(asked).toHaveLength(1);
});
diff --git a/server/headless/fleet.ts b/server/headless/fleet.ts
new file mode 100644
index 0000000000..6617a4bc95
--- /dev/null
+++ b/server/headless/fleet.ts
@@ -0,0 +1,358 @@
+// status, bots get|delete|pause|resume|stop, stop, threads and computers. Each change is the request the app makes, so
+// the server's own refusals stand: the MausBot bot is never deleted, and a busy bot or conversation answers "busy".
+import { EXIT, flag, HeadlessError, usageError } from "./args.ts";
+import { explain, type HeadlessClient } from "./client.ts";
+import type { VerbContext, VerbOutcome } from "./context.ts";
+import { shortId } from "./output.ts";
+
+type Rec = Record<string, any>;
+
+const DELETE_BATCH = 500;
+
+async function readBots(client: HeadlessClient): Promise<Rec[]> {
+ const fleet = await client.json<Rec>("/api/bots?messages=0");
+ return Array.isArray(fleet.bots) ? fleet.bots : [];
+}
+
+const lower = (value: unknown) => String(value ?? "").trim().toLowerCase();
+
+/** The one bot a name or id means; a name two bots share is refused. */
+export function findBot(bots: readonly Rec[], wanted: string): Rec {
+ const byId = bots.find((bot) => bot.id === wanted);
+ if (byId) return byId;
+ const named = bots.filter((bot) => lower(bot.name) === lower(wanted));
+ if (named.length === 1) return named[0]!;
+ if (named.length > 1) {
+ throw usageError(`"${wanted}" names ${named.length} bots: ${named.map((bot) => `${bot.name} (id ${bot.id})`).join("; ")}`, "use the id");
+ }
+ throw new HeadlessError(`no bot named "${wanted}"`, EXIT.notFound, "openmausbot status lists them");
+}
+
+export type Selection = { kind: "names"; bots: Rec[] } | { kind: "team"; team: string; bots: Rec[] } | { kind: "all"; bots: Rec[] };
+
+/** Names or ids, `--team NAME` or `--all`: exactly one of them. */
+export function selectBots(bots: readonly Rec[], ctx: Pick<VerbContext, "flags" | "positionals" | "verb">, positionals = ctx.positionals): Selection {
+ const team = flag(ctx.flags, "team")?.trim();
+ const all = ctx.flags.all === true;
+ const ways = [positionals.length > 0, team !== undefined, all].filter(Boolean).length;
+ if (ways !== 1) {
+ throw usageError(ways ? "pick bots one way: names or ids, --team NAME, or --all" : "name the bots",
+ `openmausbot ${ctx.verb} NAME…, --team NAME or --all`);
+ }
+ if (all) return { kind: "all", bots: [...bots] };
+ if (team !== undefined) {
+ const members = bots.filter((bot) => lower(bot.section) === lower(team));
+ if (!members.length) {
+ const teams = [...new Set(bots.map((bot) => bot.section).filter(Boolean))];
+ throw new HeadlessError(`no bots in a team named "${team}"`, EXIT.notFound, teams.length ? `teams here: ${teams.join(", ")}` : "no bot is in a team");
+ }
+ return { kind: "team", team: String(members[0]!.section), bots: members };
+ }
+ const picked = new Map<string, Rec>();
+ for (const wanted of positionals) {
+ const bot = findBot(bots, wanted.trim());
+ picked.set(bot.id, bot);
+ }
+ return { kind: "names", bots: [...picked.values()] };
+}
+
+/** What a person reads in the status list. */
+export function botState(bot: Rec, held: ReadonlySet<string> | null): string {
+ if (held?.has(bot.id)) return "paused";
+ if (bot.activity === "dead" || bot.activity === "no-signal") return "failed";
+ if (bot.activity === "waiting-on-you") return "waiting on you";
+ if (bot.busy || bot.activity === "working") return "working";
+ if (bot.waitingForTeammates) return "waiting on teammates";
+ return "idle";
+}
+
+export function botComputer(bot: Rec): string {
+ if (bot.computer === "off") return "none";
+ if (bot.computer === "cloud") return bot.cloudBackend === "vps" ? "cloud (VPS)" : "cloud";
+ if (bot.computer === "vm") return "local VM";
+ if (bot.computer === "local") return "this computer";
+ return bot.computer ?? "auto";
+}
+
+function table(rows: readonly string[][]): string[] {
+ const widths = rows[0]!.map((_, column) => Math.max(...rows.map((row) => row[column]!.length)));
+ return rows.map((row) => row.map((cell, column) => (column === row.length - 1 ? cell : cell.padEnd(widths[column]!))).join(" ").trimEnd());
+}
+
+async function pausedBots(client: HeadlessClient): Promise<Set<string> | null> {
+ const paused = await client.json<Rec>("/api/paused").catch(() => null);
+ return Array.isArray(paused?.heldBots) ? new Set(paused.heldBots) : null;
+}
+
+async function serverLabel(client: HeadlessClient): Promise<string> {
+ const environment = await client.json<Rec>("/.well-known/openmausbot/environment").catch(() => ({} as Rec));
+ return `${environment.label ? `"${environment.label}" ` : ""}(${client.baseUrl})`;
+}
+
+export async function statusVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const client = await ctx.client();
+ const [bots, held, environment, session] = await Promise.all([
+ readBots(client), pausedBots(client),
+ client.json<Rec>("/.well-known/openmausbot/environment").catch(() => ({} as Rec)),
+ client.json<Rec>("/api/auth/session").catch(() => null),
+ ]);
+ const rows = bots.map((bot) => ({ id: bot.id, name: bot.name, team: bot.section ?? null, state: botState(bot, held), computer: botComputer(bot),
+ working: (bot.tasks ?? []).filter((task: Rec) => task.busy).length }));
+ const counts: Record<string, number> = {};
+ for (const row of rows) counts[row.state] = (counts[row.state] ?? 0) + 1;
+ const who = session?.kind === "session" ? `signed in as "${session.label}"${session.scopes?.includes("admin") ? "" : " (chat only)"}`
+ : ctx.botShell ? "as this bot's shell" : "not signed in";
+ return {
+ result: { server: { url: client.baseUrl, label: environment.label ?? null, version: environment.version ?? null },
+ session: session ? { kind: session.kind, ...(session.kind === "session" ? { label: session.label, scopes: session.scopes, expiresAt: session.expiresAt } : { scopes: session.scopes }) } : null,
+ botShell: ctx.botShell,
+ pausedKnown: held !== null, counts, bots: rows },
+ exitCode: EXIT.done,
+ human: [
+ `${environment.label ?? "MausBot"}${environment.version ? ` · MausBot ${environment.version}` : ""} · ${client.baseUrl} · ${who}`,
+ "",
+ ...(rows.length
+ ? table([["BOT", "STATE", "COMPUTER", "TEAM", "ID"], ...rows.map((row) => [row.name, row.state, row.computer, row.team ?? "—", shortId(row.id)])])
+ : ["No bots yet."]),
+ "",
+ `${rows.length} bot${rows.length === 1 ? "" : "s"}${Object.keys(counts).length ? `: ${Object.entries(counts).map(([state, count]) => `${count} ${state}`).join(" · ")}` : ""}${held === null && rows.length ? " (paused bots show once you sign in with full control)" : ""}`,
+ ],
+ };
+}
+
+interface Step { id: string; name: string; ok: boolean; status?: number; error?: string; hint?: string; exitCode?: number; answer?: unknown }
+
+/** Runs each change in turn and keeps going past a refusal; the exit code is the first refusal's. */
+async function eachTarget(ctx: VerbContext, client: HeadlessClient, targets: readonly Rec[], change: (bot: Rec) => Promise<unknown>): Promise<{ steps: Step[]; exitCode: number }> {
+ const steps: Step[] = [];
+ for (const bot of targets) {
+ try {
+ steps.push({ id: bot.id, name: bot.name, ok: true, answer: await change(bot) });
+ } catch (error) {
+ const reported = await explain(error, client.baseUrl, { botShell: ctx.botShell, identity: client.identity });
+ steps.push({ id: bot.id, name: bot.name, ok: false, error: reported.message, exitCode: reported.exitCode, ...(reported.hint ? { hint: reported.hint } : {}),
+ ...(typeof (error as { status?: unknown }).status === "number" ? { status: (error as { status: number }).status } : {}) });
+ }
+ }
+ return { steps, exitCode: steps.find((step) => !step.ok)?.exitCode ?? EXIT.done };
+}
+
+const stepLines = (steps: readonly Step[], done: string) => {
+ const hint = steps.find((step) => step.hint)?.hint;
+ return [...steps.map((step) => ` ${step.ok ? "✓" : "✗"} ${step.name} (${shortId(step.id)})${step.ok ? ` ${done}` : `: ${step.error}`}`), ...(hint ? [`hint: ${hint}`] : [])];
+};
+
+/** Prints what a destructive verb would touch; with --dry-run that is the answer. Without --yes it asks, and only a
+ * person at a terminal can say yes: a script without --yes stops here. */
+async function confirmPlan(ctx: VerbContext, client: HeadlessClient, plan: { doing: string; note: string; lines: string[]; result: Rec }): Promise<VerbOutcome | null> {
+ const where = await serverLabel(client);
+ const header = `${plan.doing} on ${where}, ${plan.note}:`;
+ if (ctx.flags["dry-run"] === true) {
+ return { result: { ok: true, dryRun: true, server: client.baseUrl, ...plan.result }, exitCode: EXIT.done, human: [`Would ${header.charAt(0).toLowerCase()}${header.slice(1)}`, ...plan.lines, "Nothing was changed (--dry-run)."] };
+ }
+ if (!client.explicit) {
+ throw usageError("this deletes or stops things, so name the server it is for", "sign in with openmausbot login, or pass --url or --port");
+ }
+ if (ctx.flags.yes === true) return null;
+ if (!ctx.interactive) throw usageError(`this would ${plan.doing.charAt(0).toLowerCase()}${plan.doing.slice(1)} on ${where}: add --yes to go ahead`, "or --dry-run to only see the list");
+ ctx.io.err([header, ...plan.lines].join("\n"));
+ if (await ctx.confirm("Go ahead?")) return null;
+ return { result: { ok: false, cancelled: true }, exitCode: EXIT.failed, human: ["Nothing was changed."] };
+}
+
+const botLine = (bot: Rec) => ` ${bot.name} (${shortId(bot.id)})${bot.section ? `, team ${bot.section}` : ""}`;
+const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
+
+async function deleteBots(ctx: VerbContext, client: HeadlessClient, selection: Selection): Promise<VerbOutcome> {
+ const kept = selection.bots.filter((bot) => bot.defaultBot);
+ const targets = selection.bots.filter((bot) => !bot.defaultBot);
+ const keptLines = kept.map((bot) => ` (${bot.name} is kept: the MausBot bot is never deleted)`);
+ if (!targets.length) throw new HeadlessError(`${kept.map((bot) => bot.name).join(", ")} is never deleted`, EXIT.conflict, "it can be hidden in Settings → General instead");
+ const stop = await confirmPlan(ctx, client, { doing: `Delete ${plural(targets.length, "bot")}`, note: "with their conversations and files", lines: [...targets.map(botLine), ...keptLines],
+ result: { action: "delete", bots: targets.map((bot) => ({ id: bot.id, name: bot.name, team: bot.section ?? null })) } });
+ if (stop) return stop;
+ const { steps, exitCode } = await eachTarget(ctx, client, targets, (bot) => client.json(`/api/bots/${encodeURIComponent(bot.id)}`, { method: "DELETE" }));
+ const deleted = steps.filter((step) => step.ok).length;
+ return {
+ result: { ok: exitCode === EXIT.done, action: "delete", deleted, results: steps.map(({ answer: _answer, ...step }) => step) }, exitCode,
+ human: [`Deleted ${deleted} of ${plural(targets.length, "bot")}.`, ...stepLines(steps, "deleted")],
+ };
+}
+
+async function pauseBots(ctx: VerbContext, client: HeadlessClient, selection: Selection, paused: boolean): Promise<VerbOutcome> {
+ const verb = paused ? "pause" : "resume";
+ const bodies = selection.kind === "all" ? [{ kind: "all", paused }]
+ : selection.kind === "team" ? [{ kind: "department", id: selection.team, paused }]
+ : selection.bots.map((bot) => ({ kind: "bot", id: bot.id, paused }));
+ const what = selection.kind === "all" ? "every bot, the ones made later too" : selection.kind === "team" ? `the ${selection.team} team, its bots made later too` : selection.bots.map((bot) => bot.name).join(", ");
+ if (ctx.flags["dry-run"] === true) {
+ return { result: { ok: true, dryRun: true, action: verb, requests: bodies }, exitCode: EXIT.done, human: [`Would ${verb} ${what}. Nothing was changed (--dry-run).`] };
+ }
+ let stopped = 0;
+ for (const body of bodies) stopped += Number((await client.json<Rec>("/api/paused", { method: "POST", body: JSON.stringify(body) })).stopped) || 0;
+ return {
+ result: { ok: true, action: verb, requests: bodies, stopped },
+ exitCode: EXIT.done,
+ human: paused
+ ? [`Paused ${what}${stopped ? `, and stopped ${plural(stopped, "conversation")} that ${stopped === 1 ? "was" : "were"} working` : ""}. A pause lasts across restarts: openmausbot bots resume ${selection.kind === "all" ? "--all" : selection.kind === "team" ? `--team "${selection.team}"` : "NAME"} undoes it.`]
+ : [`Resumed ${what}. A bot or team paused on its own stays paused.`],
+ };
+}
+
+async function stopBots(ctx: VerbContext, client: HeadlessClient, selection: Selection): Promise<VerbOutcome> {
+ const body = selection.kind === "all" ? { all: true } : { botIds: selection.bots.map((bot) => bot.id) };
+ if (selection.kind === "all") {
+ const working = selection.bots.filter((bot) => bot.busy || bot.activity === "working");
+ const stop = await confirmPlan(ctx, client, { doing: "Stop the work of every bot", note: `${working.length} working now, nothing is paused`,
+ lines: working.length ? working.map(botLine) : [" (none is working right now)"], result: { action: "stop", all: true, working: working.map((bot) => ({ id: bot.id, name: bot.name })) } });
+ if (stop) return stop;
+ } else if (ctx.flags["dry-run"] === true) {
+ return { result: { ok: true, dryRun: true, action: "stop", bots: selection.bots.map((bot) => ({ id: bot.id, name: bot.name })) }, exitCode: EXIT.done,
+ human: [`Would stop the work of ${selection.bots.map((bot) => bot.name).join(", ")}. Nothing was changed (--dry-run).`] };
+ }
+ const answer = await client.json<Rec>("/api/turns/stop", { method: "POST", body: JSON.stringify(body) });
+ const stopped = Number(answer.stopped) || 0;
+ return {
+ result: { ok: true, action: "stop", botIds: answer.botIds ?? [], stopped },
+ exitCode: EXIT.done,
+ human: [`Stopped ${plural(stopped, "conversation")}. Nothing is paused: a new message or routine starts a bot again.`],
+ };
+}
+
+export async function botsVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const client = await ctx.client();
+ const bots = await readBots(client);
+ if (ctx.verb === "bots get") {
+ const wanted = ctx.positionals[0]?.trim();
+ if (!wanted) throw usageError("name a bot", "openmausbot bots get NAME");
+ const bot = findBot(bots, wanted);
+ const held = await pausedBots(client);
+ const tasks: Rec[] = bot.tasks ?? [];
+ return {
+ result: { ...bot, state: botState(bot, held) },
+ exitCode: EXIT.done,
+ human: [
+ `${bot.name}${bot.title ? ` — ${bot.title}` : ""}`,
+ ` id ${bot.id}`,
+ ` team ${bot.section ?? "—"}`,
+ ` state ${botState(bot, held)}`,
+ ` computer ${botComputer(bot)}`,
+ ` model ${bot.modelSelection?.instanceId ?? "?"}${bot.modelSelection?.model ? `/${bot.modelSelection.model}` : ""}`,
+ ` approvals ${bot.approvalMode ?? (bot.autoApprove ? "auto" : "ask")}`,
+ ` threads ${tasks.length}${tasks.some((task) => task.busy) ? ` (${tasks.filter((task) => task.busy).length} working)` : ""}`,
+ ],
+ };
+ }
+ const selection = selectBots(bots, ctx);
+ if (ctx.verb === "bots delete") return deleteBots(ctx, client, selection);
+ if (ctx.verb === "bots pause" || ctx.verb === "bots resume") return pauseBots(ctx, client, selection, ctx.verb === "bots pause");
+ return stopBots(ctx, client, selection);
+}
+
+export async function stopVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const client = await ctx.client();
+ return stopBots(ctx, client, selectBots(await readBots(client), ctx));
+}
+
+async function deleteThreads(ctx: VerbContext, client: HeadlessClient, bot: Rec, threads: readonly Rec[], clearing: boolean): Promise<VerbOutcome> {
+ const lines = threads.map((task) => ` ${task.title || "Untitled"} (${shortId(task.threadId)})${task.busy ? ", working now" : ""}`);
+ const stop = await confirmPlan(ctx, client, {
+ doing: `Delete ${plural(threads.length, "conversation")} of ${bot.name}`, note: clearing ? "and it starts one new, empty conversation" : "for good", lines,
+ result: { action: clearing ? "clear" : "delete", bot: { id: bot.id, name: bot.name }, threads: threads.map((task) => ({ id: task.threadId, title: task.title })) },
+ });
+ if (stop) return stop;
+ const deleted: string[] = [];
+ const refused: Rec[] = [];
+ const ids = threads.map((task) => task.threadId as string);
+ for (let at = 0; at < ids.length; at += DELETE_BATCH) {
+ const answer = await client.json<Rec>(`/api/bots/${encodeURIComponent(bot.id)}/tasks/delete`, { method: "POST", body: JSON.stringify({ threadIds: ids.slice(at, at + DELETE_BATCH) }) });
+ deleted.push(...(answer.deleted ?? []));
+ refused.push(...(answer.refused ?? []));
+ }
+ const busy = refused.filter((refusal) => refusal.reason === "busy").length;
+ return {
+ result: { ok: refused.length === 0, action: clearing ? "clear" : "delete", bot: { id: bot.id, name: bot.name }, deleted, refused },
+ exitCode: refused.length === 0 ? EXIT.done : busy ? EXIT.conflict : EXIT.notFound,
+ human: [
+ `Deleted ${plural(deleted.length, "conversation")} of ${bot.name}.`,
+ ...(refused.length ? [`Kept ${refused.length}: ${busy ? `${busy} working now (stop it first: openmausbot stop "${bot.name}")` : ""}${refused.length - busy ? `${busy ? "; " : ""}${refused.length - busy} not found` : ""}.`] : []),
+ ],
+ };
+}
+
+export async function threadsVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const [wanted, ...threadIds] = ctx.positionals.map((value) => value.trim());
+ if (!wanted) throw usageError("name a bot", `openmausbot ${ctx.verb} BOT${ctx.verb === "threads delete" ? " THREAD…" : ""}`);
+ const client = await ctx.client();
+ const bot = findBot(await readBots(client), wanted);
+ const tasks: Rec[] = bot.tasks ?? [];
+ if (ctx.verb === "threads list") {
+ return {
+ result: { bot: { id: bot.id, name: bot.name }, threads: tasks.map((task) => ({ id: task.threadId, title: task.title ?? null, busy: Boolean(task.busy), active: task.threadId === bot.threadId, createdAt: task.createdAt ?? null })) },
+ exitCode: EXIT.done,
+ human: tasks.length
+ ? table([["THREAD", "TITLE", "STATE"], ...tasks.map((task) => [task.threadId, `${task.threadId === bot.threadId ? "* " : ""}${task.title || "Untitled"}`, task.busy ? "working" : "idle"])])
+ : [`${bot.name} has no conversations.`],
+ };
+ }
+ if (ctx.verb === "threads clear") {
+ if (threadIds.length) throw usageError("threads clear takes only the bot", "threads delete BOT THREAD… deletes some");
+ if (!tasks.length) return { result: { ok: true, deleted: [] }, exitCode: EXIT.done, human: [`${bot.name} has no conversations.`] };
+ return deleteThreads(ctx, client, bot, tasks, true);
+ }
+ if (!threadIds.length) throw usageError("name the conversations to delete", "openmausbot threads list BOT shows their ids");
+ const picked = threadIds.map((id) => {
+ const task = tasks.find((candidate) => candidate.threadId === id);
+ if (!task) throw new HeadlessError(`${bot.name} has no conversation ${id}`, EXIT.notFound, `openmausbot threads list "${bot.name}" shows them`);
+ return task;
+ });
+ return deleteThreads(ctx, client, bot, [...new Map(picked.map((task) => [task.threadId, task])).values()], false);
+}
+
+async function computerChange(client: HeadlessClient, botId: string, action: "provision" | "sleep"): Promise<Rec> {
+ const response = await client.raw(`/api/bots/${encodeURIComponent(botId)}/computer/${action}`, {
+ method: "POST", headers: { "content-type": "application/json" }, body: "{}", stream: true,
+ });
+ const text = await response.text();
+ if (!response.ok) throw Object.assign(new Error(`OpenMausBot API error (${response.status}): ${text}`), { status: response.status });
+ try {
+ return JSON.parse(text) as Rec;
+ } catch {
+ return {};
+ }
+}
+
+export async function computersVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const client = await ctx.client();
+ const bots = await readBots(client);
+ if (ctx.verb === "computers list") {
+ const inventory = await client.json<Rec>("/api/computers/boxes").catch(() => null);
+ const boxes = new Map<string, Rec>((inventory?.instances ?? []).filter((box: Rec) => box.ownerBotId).map((box: Rec) => [box.ownerBotId as string, box]));
+ const rows = bots.map((bot) => ({ id: bot.id, name: bot.name, computer: botComputer(bot), cloud: boxes.get(bot.id) ? { state: boxes.get(bot.id)!.state, name: boxes.get(bot.id)!.name } : null }));
+ return {
+ result: { bots: rows, cloudKnown: inventory !== null },
+ exitCode: EXIT.done,
+ human: rows.length
+ ? table([["BOT", "WORKS ON", "CLOUD COMPUTER"], ...rows.map((row) => [row.name, row.computer, row.cloud ? row.cloud.state : row.computer.startsWith("cloud") ? (inventory ? "none yet" : "?") : "—"])])
+ : ["No bots yet."],
+ };
+ }
+ const wanted = ctx.positionals[0]?.trim();
+ if (!wanted) throw usageError("name a bot", `openmausbot ${ctx.verb} BOT`);
+ const bot = findBot(bots, wanted);
+ const starting = ctx.verb === "computers start";
+ if (ctx.flags["dry-run"] === true) {
+ return { result: { ok: true, dryRun: true, action: starting ? "start" : "sleep", bot: { id: bot.id, name: bot.name } }, exitCode: EXIT.done,
+ human: [`Would ${starting ? "start (or wake)" : "put to sleep"} ${bot.name}'s cloud computer. Nothing was changed (--dry-run).`] };
+ }
+ if (bot.computer !== "cloud") {
+ throw new HeadlessError(`${bot.name} works on ${botComputer(bot)}, not a cloud computer`, EXIT.conflict, "choose Cloud computer in the bot's settings first");
+ }
+ if (starting) ctx.io.err(`Starting ${bot.name}'s cloud computer; a new one takes a few minutes…`);
+ const answer = await computerChange(client, bot.id, starting ? "provision" : "sleep");
+ return {
+ result: { ok: true, action: starting ? "start" : "sleep", bot: { id: bot.id, name: bot.name }, computer: answer },
+ exitCode: EXIT.done,
+ human: [starting ? `${bot.name}'s cloud computer is ready.` : `${bot.name}'s cloud computer is asleep; it wakes when the bot needs it.`],
+ };
+}
diff --git a/server/headless/login.e2e.test.ts b/server/headless/login.e2e.test.ts
new file mode 100644
index 0000000000..c940b9966b
--- /dev/null
+++ b/server/headless/login.e2e.test.ts
@@ -0,0 +1,172 @@
+import { mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { randomBytes } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { launchVerificationServer, type VerificationServer } from "../../scripts/control-omb.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { runHeadless, type HeadlessOptions } from "./main.ts";
+import type { HeadlessIo } from "./output.ts";
+import type { SecurityRunner } from "./saved-servers.ts";
+
+/** macOS `security` as a map: no real keychain is touched. */
+function fakeKeychain(): SecurityRunner {
+ const items = new Map<string, string>();
+ return (args, stdin) => {
+ if (args[0] === "-i") {
+ const match = /-s "([^"]+)" -a "([^"]+)" -l "[^"]*" -w "([^"]+)"/.exec(stdin ?? "");
+ if (match) items.set(`${match[1]}/${match[2]}`, match[3]!);
+ return { status: match ? 0 : 1, stdout: "" };
+ }
+ const key = `${args[args.indexOf("-s") + 1]}/${args[args.indexOf("-a") + 1]}`;
+ if (args[0] === "find-generic-password") return items.has(key) ? { status: 0, stdout: `${items.get(key)}\n` } : { status: 44, stdout: "" };
+ return { status: items.delete(key) ? 0 : 44, stdout: "" };
+ };
+}
+
+describe("openmausbot login, then status, bots, stop and threads against the desktop app's own server", () => {
+ let fixture: VerificationServer;
+ const owner = randomBytes(32).toString("base64url");
+ const home = mkdtempSync(join(tmpdir(), "omb-cli-home-"));
+ const security = fakeKeychain();
+ const asApp = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${fixture.info.url}${path}`, {
+ method, headers: { "content-type": "application/json", "x-openmausbot-desktop-owner": owner, origin: fixture.info.url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return await response.json() as Record<string, any>;
+ };
+ const cli = async (argv: string[], options: Partial<HeadlessOptions> = {}) => {
+ const out: string[] = [], err: string[] = [];
+ const io: HeadlessIo = { out: (text) => out.push(text), err: (text) => err.push(text), readStdin: async () => "" };
+ const code = await runHeadless(argv, { io, env: { HOME: home }, platform: "darwin", security, interactive: false, openBrowser: async () => false, ...options });
+ return { code, out: out.join("\n"), err: err.join("\n") };
+ };
+
+ beforeAll(async () => {
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (input, init = {}) => realFetch(input, { ...init, headers: { ...Object.fromEntries(new Headers(init.headers)), "x-openmausbot-desktop-owner": owner } });
+ try {
+ fixture = await launchVerificationServer({ ...process.env, OMB_TEST_DESKTOP_OWNER_TOKEN: owner });
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ for (const [name, section] of [["QA Tester 1", "QA"], ["QA Tester 2", "QA"], ["Support Lead", "Support"]]) {
+ await asApp("POST", "/api/bots", { name, section, useDefaults: false, requireAvailableModel: false });
+ }
+ });
+ afterAll(async () => {
+ await fixture?.close();
+ removeTempDir(home);
+ });
+
+ it("signs in only after Allow in the app, then acts as the person; a bot's shell never uses that sign-in", async () => {
+ const before = await cli(["bots", "delete", "QA Tester 1", "--url", fixture.info.url, "--yes"]);
+ expect(before.code).toBe(4);
+ expect(before.out).toContain("hint: sign in once with `openmausbot login`");
+
+ let shown = "";
+ const approving = (async () => {
+ for (let tries = 0; tries < 100; tries++) {
+ const waiting = (await asApp("GET", "/api/auth/cli-login")).requests ?? [];
+ if (waiting.length) {
+ shown = waiting[0].code;
+ return asApp("POST", `/api/auth/cli-login/${waiting[0].id}/allow`, {});
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ throw new Error("no sign-in request arrived");
+ })();
+ const login = await cli(["login", fixture.info.url, "--json"]);
+ await approving;
+ expect(login.code).toBe(0);
+ expect(login.err).toContain(shown);
+ expect(login.err).toContain("MausBot is asking you to allow this terminal");
+ const signedIn = JSON.parse(login.out);
+ expect(signedIn).toMatchObject({ ok: true, storedIn: "keychain", session: { scopes: ["admin", "client"] } });
+ expect(login.out).not.toMatch(/omb_sess_/);
+
+ const whoami = await cli(["whoami"]);
+ expect(whoami).toMatchObject({ code: 0, out: expect.stringContaining("full control") });
+
+ const status = await cli(["status", "--json"]);
+ expect(status.code).toBe(0);
+ const statusBody = JSON.parse(status.out);
+ expect(statusBody.bots.map((bot: { name: string }) => bot.name)).toEqual(expect.arrayContaining(["QA Tester 1", "QA Tester 2", "Support Lead"]));
+ expect(statusBody.bots.every((bot: { state: string }) => bot.state === "idle")).toBe(true);
+ expect((await cli(["status"])).out).toMatch(/BOT\s+STATE\s+COMPUTER\s+TEAM\s+ID/);
+
+ const plan = await cli(["bots", "delete", "--team", "qa", "--dry-run"]);
+ expect(plan.code).toBe(0);
+ expect(plan.out).toContain("Would delete 2 bots");
+ expect(plan.out).toContain("QA Tester 1");
+ expect(plan.out).toContain("Nothing was changed (--dry-run).");
+ const unconfirmed = await cli(["bots", "delete", "--team", "QA"]);
+ expect(unconfirmed).toMatchObject({ code: 2, err: expect.stringContaining("add --yes") });
+ expect((await cli(["bots", "delete", "--team", "QA"], { interactive: true, confirm: async () => false })).code).toBe(1);
+
+ // A real turn's environment, as the engine (and so a bot's shell) got it from the server, with the person's HOME.
+ expect((await cli(["send", "Support Lead", "hello"])).code).toBe(0);
+ expect((await cli(["wait", "Support Lead", "--timeout", "60"])).code).toBe(0);
+ const turnEnv = (JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")) as { env: NodeJS.ProcessEnv }).env;
+ const botShell = { env: { ...turnEnv, HOME: home } };
+ const refused = await cli(["bots", "delete", "QA Tester 1", "--yes"], botShell);
+ expect(refused.code).toBe(5);
+ expect(refused.out).toContain("your own terminal");
+ expect((await cli(["login"], botShell)).code).toBe(5);
+ expect((await cli(["whoami"], botShell)).out).toContain("acting as the bot");
+
+ const deleted = await cli(["bots", "delete", "--team", "QA", "--yes", "--json"]);
+ expect(deleted.code).toBe(0);
+ expect(JSON.parse(deleted.out)).toMatchObject({ ok: true, deleted: 2 });
+ expect((await cli(["bots", "get", "QA Tester 1"])).code).toBe(7);
+
+ const stopAll = await cli(["stop", "--all", "--yes"]);
+ expect(stopAll).toMatchObject({ code: 0, out: expect.stringContaining("Nothing is paused") });
+
+ expect((await cli(["bots", "pause", "Support Lead"])).code).toBe(0);
+ expect(JSON.parse((await cli(["status", "--json"])).out).bots.find((bot: { name: string }) => bot.name === "Support Lead").state).toBe("paused");
+ expect((await cli(["bots", "resume", "Support Lead"])).code).toBe(0);
+
+ const threads = await cli(["threads", "list", "Support Lead", "--json"]);
+ expect(JSON.parse(threads.out).threads).toHaveLength(1);
+ const cleared = await cli(["threads", "clear", "Support Lead", "--yes", "--json"]);
+ expect(cleared.code).toBe(0);
+ expect(JSON.parse(cleared.out).deleted).toHaveLength(1);
+
+ expect((await cli(["computers", "start", "Support Lead"])).code).toBe(6);
+
+ const out = await cli(["logout"]);
+ expect(out).toMatchObject({ code: 0, out: expect.stringContaining("Signed out") });
+ expect((await cli(["bots", "delete", "Support Lead", "--url", fixture.info.url, "--yes"])).code).toBe(4);
+ });
+});
+
+describe("openmausbot login against a server started with openmausbot serve", () => {
+ let fixture: VerificationServer;
+ const home = mkdtempSync(join(tmpdir(), "omb-cli-serve-home-"));
+ const cli = async (argv: string[]) => {
+ const out: string[] = [], err: string[] = [];
+ const io: HeadlessIo = { out: (text) => out.push(text), err: (text) => err.push(text), readStdin: async () => "" };
+ const code = await runHeadless(argv, { io, env: { HOME: home }, platform: "linux", interactive: false, openBrowser: async () => false });
+ return { code, out: out.join("\n"), err: err.join("\n") };
+ };
+ beforeAll(async () => { fixture = await launchVerificationServer(); });
+ afterAll(async () => {
+ await fixture?.close();
+ removeTempDir(home);
+ });
+
+ it("signs in with no card, since a command here is that server's owner, and a chat-only sign-in cannot stop every bot", async () => {
+ const login = await cli(["login", fixture.info.url, "--scope", "chat", "--name", "box", "--json"]);
+ expect(login.code).toBe(0);
+ expect(login.err).toBe("");
+ expect(JSON.parse(login.out)).toMatchObject({ name: "box", storedIn: "file", session: { scopes: ["client"] } });
+ expect((await cli(["whoami"])).out).toContain("chat only");
+ const stop = await cli(["stop", "--all", "--yes"]);
+ expect(stop.code).toBe(5);
+ expect(stop.err).toContain("chat only");
+ expect((await cli(["servers"])).out).toContain("* box");
+ });
+});
diff --git a/server/headless/login.ts b/server/headless/login.ts
new file mode 100644
index 0000000000..a65db57cca
--- /dev/null
+++ b/server/headless/login.ts
@@ -0,0 +1,204 @@
+// login, logout, whoami, use and servers. The session goes to the Keychain (or a file only you can read) and is never
+// printed or taken on the command line; it is sent only to the exact address it was made at.
+import { createHash, randomBytes } from "node:crypto";
+import { hostname } from "node:os";
+
+import { EXIT, flag, HeadlessError, oneOf, usageError } from "./args.ts";
+import { BOT_SHELL_HINT, BOT_SHELL_REFUSAL } from "./bot-shell.ts";
+import { loadMcp, namedServer } from "./client.ts";
+import type { VerbContext, VerbOutcome } from "./context.ts";
+import type { SavedServer, SavedServers } from "./saved-servers.ts";
+
+type Rec = Record<string, any>;
+
+const DISCOVERY_PORTS = [8799, 18799, 28799];
+const LOOPBACK = /^https?:\/\/(?:127\.\d+\.\d+\.\d+|localhost|\[::1\])(?::\d+)?$/i;
+
+/** The desktop app runs this server: it shows the Allow card itself, and its local changes need a sign-in. */
+const desktopApp = (environment: Rec) => environment.capabilities?.selfUpdate === "desktop-managed";
+const day = (at: number) => new Date(at).toISOString().slice(0, 10);
+const reach = (scopes: readonly string[]) => (scopes.includes("admin") ? "full control" : "chat only");
+
+function savedOnly(ctx: VerbContext): SavedServers {
+ if (ctx.botShell || !ctx.saved) throw new HeadlessError(BOT_SHELL_REFUSAL, EXIT.notAllowed, BOT_SHELL_HINT);
+ return ctx.saved;
+}
+
+async function call(origin: string, path: string, init: RequestInit = {}, signal?: AbortSignal): Promise<{ status: number; body: Rec }> {
+ const timeout = AbortSignal.timeout(15_000);
+ const response = await fetch(`${origin}${path}`, {
+ ...init, redirect: "error", signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
+ headers: { "content-type": "application/json", ...(init.headers as Record<string, string> | undefined) },
+ });
+ return { status: response.status, body: await response.json().catch(() => ({})) as Rec };
+}
+
+/** `maus.example.com` is https, `localhost:8799` http: the address a person types, as an origin. */
+function typedOrigin(typed: string): string {
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(typed) ? typed : `${/^(?:localhost|127\.|\[::1\])/i.test(typed) ? "http" : "https"}://${typed}`;
+ return withScheme.replace(/\/+$/, "");
+}
+
+async function serverToSignInTo(ctx: VerbContext): Promise<string> {
+ const mcp = await loadMcp();
+ const valid = (url: string) => {
+ try {
+ return mcp.validateBaseUrl(url);
+ } catch (error) {
+ throw usageError(error instanceof Error ? error.message : String(error));
+ }
+ };
+ const typed = ctx.positionals[0]?.trim();
+ if (typed) return valid(typedOrigin(typed));
+ const named = namedServer(ctx.flags, ctx.env);
+ if (named) return valid("url" in named ? named.url : `http://127.0.0.1:${named.port}`);
+ try {
+ return await mcp.probeBaseUrls(DISCOVERY_PORTS.map((port) => `http://127.0.0.1:${port}`));
+ } catch {
+ throw new HeadlessError("MausBot is not running on this computer", EXIT.unreachable,
+ "open the MausBot app, or name a server: openmausbot login https://maus.example.com (an OpenMausBot account for --tunnel is openmausbot account login)");
+ }
+}
+
+/** `local` for this computer's usual port, `local-18799` for another, else the host's name. */
+export function defaultServerName(origin: string): string {
+ const url = new URL(origin);
+ if (LOOPBACK.test(origin)) return !url.port || url.port === "8799" ? "local" : `local-${url.port}`;
+ return url.hostname.replace(/[^\w.-]/g, "-").slice(0, 80);
+}
+
+/** A server run by `openmausbot serve` with owner trust makes a code for a program on its own computer, as `connect` does. */
+async function signInDirectly(origin: string, label: string, scopes: string[], signal: AbortSignal): Promise<Rec | null> {
+ const minted = await call(origin, "/api/auth/pairing", { method: "POST", body: JSON.stringify({ label, scopes }) }, signal);
+ if (minted.status !== 200 || typeof minted.body.code !== "string") return null;
+ const paired = await call(origin, "/api/auth/pair", { method: "POST", body: JSON.stringify({ code: minted.body.code, label }) }, signal);
+ return paired.status === 200 && typeof paired.body.token === "string" ? paired.body : null;
+}
+
+async function signInWithCard(ctx: VerbContext, origin: string, label: string, scope: "admin" | "client", environment: Rec): Promise<Rec> {
+ const verifier = randomBytes(32).toString("base64url");
+ const verifierHash = createHash("sha256").update(verifier).digest("base64url");
+ const started = await call(origin, "/api/auth/cli-login", { method: "POST", body: JSON.stringify({ label, scope, verifierHash }) }, ctx.signal);
+ if (started.status === 404) {
+ throw new HeadlessError("this server does not take openmausbot login yet", EXIT.failed, "update MausBot there, or use openmausbot connect URL --code CODE --out FILE");
+ }
+ if (started.status !== 201 || typeof started.body.id !== "string") {
+ throw new HeadlessError(`the server would not start a sign-in: ${started.body.error ?? started.status}`, started.status === 403 ? EXIT.notAllowed : EXIT.failed);
+ }
+ const code = String(started.body.code);
+ if (desktopApp(environment) && LOOPBACK.test(origin)) {
+ ctx.io.err(`MausBot is asking you to allow this terminal. Check the code in the app matches, then press Allow:\n\n ${code}\n`);
+ } else {
+ const opened = await ctx.openBrowser(`${origin}/`);
+ ctx.io.err(`${opened ? "Opened" : "Open"} ${origin}/ in your browser. Sign in there if it asks, check the code matches, then press Allow:\n\n ${code}\n`);
+ }
+ const until = Number(started.body.expiresAt) || Date.now() + 10 * 60_000;
+ const every = Math.min(5_000, Math.max(500, Number(started.body.intervalMs) || 1_000));
+ while (Date.now() < until) {
+ await new Promise<void>((resolve, reject) => {
+ const stop = () => { clearTimeout(timer); reject(new HeadlessError("stopped: nothing was signed in", EXIT.interrupted)); };
+ const timer = setTimeout(() => { ctx.signal.removeEventListener("abort", stop); resolve(); }, every);
+ ctx.signal.addEventListener("abort", stop, { once: true });
+ });
+ const polled = await call(origin, `/api/auth/cli-login/${encodeURIComponent(started.body.id)}`, { method: "POST", body: JSON.stringify({ verifier }) }, ctx.signal);
+ if (polled.status === 202) continue;
+ if (polled.status === 200 && typeof polled.body.token === "string") return polled.body;
+ if (polled.body.state === "denied") throw new HeadlessError("the sign-in was denied in MausBot", EXIT.notAllowed);
+ throw new HeadlessError(`the sign-in did not finish: ${polled.body.error ?? polled.status}`, polled.status === 403 ? EXIT.notAllowed : EXIT.failed,
+ "run openmausbot login again");
+ }
+ throw new HeadlessError("nobody allowed the sign-in within ten minutes", EXIT.failed, "run openmausbot login again, then press Allow in MausBot");
+}
+
+export async function loginVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const saved = savedOnly(ctx);
+ const scope = oneOf(flag(ctx.flags, "scope"), "--scope", ["all", "chat"] as const, "all") === "chat" ? "client" : "admin";
+ const origin = await serverToSignInTo(ctx);
+ const described = await call(origin, "/.well-known/openmausbot/environment", {}, ctx.signal).catch(() => null);
+ if (described?.status !== 200 || typeof described.body.environmentId !== "string") {
+ throw new HeadlessError(`no MausBot server answers at ${origin}`, EXIT.unreachable, "check the address, and that MausBot is running there");
+ }
+ const environment = described.body;
+ const name = flag(ctx.flags, "name")?.trim() || defaultServerName(origin);
+ const label = `openmausbot CLI on ${hostname().slice(0, 50)}`;
+ const scopes = scope === "admin" ? ["admin", "client"] : ["client"];
+ const direct = LOOPBACK.test(origin) && !desktopApp(environment) ? await signInDirectly(origin, label, scopes, ctx.signal) : null;
+ const answer = direct ?? await signInWithCard(ctx, origin, label, scope, environment);
+ const session = answer.session ?? {};
+ const server: Omit<SavedServer, "store"> = {
+ url: origin, environmentId: environment.environmentId, label: String(answer.environment?.label ?? environment.label ?? name),
+ sessionId: String(session.id ?? ""), scopes: Array.isArray(session.scopes) ? session.scopes : scopes, expiresAt: Number(session.expiresAt) || 0,
+ };
+ const store = saved.save(name, server, answer.token as string);
+ return {
+ result: { ok: true, name, server: { url: origin, label: server.label, environmentId: server.environmentId },
+ session: { id: server.sessionId, label: session.label ?? label, scopes: server.scopes, expiresAt: server.expiresAt }, storedIn: store },
+ exitCode: EXIT.done,
+ human: [
+ `Signed in to "${server.label}" (${origin}) with ${reach(server.scopes)}${server.expiresAt ? `, until ${day(server.expiresAt)} (it renews while you use it)` : ""}.`,
+ `Saved as "${name}" ${store === "keychain" ? "in the macOS Keychain" : "in a file only you can read"}; it is now the server every command uses.`,
+ ],
+ };
+}
+
+export async function logoutVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const saved = savedOnly(ctx);
+ const name = ctx.positionals[0]?.trim() || saved.current()?.name;
+ const server = name ? saved.get(name) : null;
+ if (!name || !server) {
+ if (ctx.positionals[0]) throw new HeadlessError(`no saved server named "${name}"`, EXIT.notFound, "openmausbot servers lists them");
+ return { result: { ok: true, signedOut: null }, exitCode: EXIT.done,
+ human: ["You are not signed in to any server. (To release a --tunnel address and sign this machine out of its OpenMausBot account: openmausbot account logout.)"] };
+ }
+ const token = saved.token(name);
+ const ended = token
+ ? await call(server.url, "/api/auth/logout", { method: "POST", body: "{}", headers: { authorization: `Bearer ${token}` } }).then((answer) => answer.status === 200, () => false)
+ : false;
+ saved.forget(name);
+ return {
+ result: { ok: true, signedOut: name, url: server.url, sessionEnded: ended },
+ exitCode: EXIT.done,
+ human: [`Signed out of "${server.label}" (${server.url}).${ended ? "" : " The server could not be reached, so its session ends on its own date; Settings → Phone & devices removes it now."}`],
+ };
+}
+
+export async function whoamiVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const client = await ctx.client();
+ const [session, environment] = await Promise.all([
+ client.json<Rec>("/api/auth/session"),
+ client.json<Rec>("/.well-known/openmausbot/environment").catch(() => ({} as Rec)),
+ ]);
+ const where = `${environment.label ? `"${environment.label}" ` : ""}(${client.baseUrl})`;
+ const who = session.kind === "session"
+ ? `"${session.label || "unnamed"}" on ${where}: ${reach(session.scopes ?? [])}${typeof session.expiresAt === "number" ? `, until ${day(session.expiresAt)}` : ""}`
+ : session.trust === "service" || desktopApp(environment)
+ ? `this computer, not signed in, on ${where}: you can look; a change needs openmausbot login`
+ : `this computer's owner on ${where}`;
+ return {
+ result: { ok: true, url: client.baseUrl, server: { label: environment.label, environmentId: environment.environmentId }, botShell: ctx.botShell,
+ identity: client.identity.kind === "saved" ? { kind: "saved", name: client.identity.name } : { kind: client.identity.kind }, session },
+ exitCode: EXIT.done,
+ human: [`${ctx.botShell ? "In this bot's shell, acting as the bot (your saved sign-in is not used): " : "You are "}${who}.`],
+ };
+}
+
+export async function useVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const saved = savedOnly(ctx);
+ const name = ctx.positionals[0]?.trim();
+ if (!name) throw usageError("name a saved server", "openmausbot servers lists them");
+ saved.use(name);
+ const server = saved.get(name)!;
+ return { result: { ok: true, current: name, url: server.url }, exitCode: EXIT.done, human: [`Every command now goes to "${server.label}" (${server.url}).`] };
+}
+
+export async function serversVerb(ctx: VerbContext): Promise<VerbOutcome> {
+ const { current, servers } = savedOnly(ctx).list();
+ const rows = servers.map(({ store: _store, sessionId: _session, ...server }) => ({ ...server, current: server.name === current }));
+ return {
+ result: { current, servers: rows },
+ exitCode: EXIT.done,
+ human: rows.length
+ ? rows.map((server) => `${server.current ? "*" : " "} ${server.name} ${server.url} "${server.label}" ${reach(server.scopes)}${server.expiresAt ? `, until ${day(server.expiresAt)}` : ""}`)
+ : ["No saved servers. Sign in with: openmausbot login [SERVER]"],
+ };
+}
diff --git a/server/headless/main.ts b/server/headless/main.ts
index 44a16988e6..ff449c0b08 100644
--- a/server/headless/main.ts
+++ b/server/headless/main.ts
@@ -1,5 +1,6 @@
import { HEADLESS_USAGE } from "../cli-usage.ts";
import { EXIT, HeadlessError, MUTATING_VERBS, parseCommand } from "./args.ts";
+import { inBotShell } from "./bot-shell.ts";
import { explain, loadMcp, openClient, type ClientDeps, type HeadlessClient } from "./client.ts";
import { doctor, edit, interrupt, list, messages, newBot, newChannel, send, setModel } from "./commands.ts";
import { connectVerb } from "./connect.ts";
@@ -9,6 +10,10 @@ import { eventsVerb } from "./events.ts";
import { exportVerb } from "./export.ts";
import { Output, processIo, type HeadlessIo } from "./output.ts";
import { runVerb, waitVerb } from "./run.ts";
+import { botsVerb, computersVerb, statusVerb, stopVerb, threadsVerb } from "./fleet.ts";
+import { loginVerb, logoutVerb, serversVerb, useVerb, whoamiVerb } from "./login.ts";
+import { askOnTerminal, openInBrowser, terminalPresent } from "./prompt.ts";
+import { SavedServers, type SecurityRunner } from "./saved-servers.ts";
import { teamApplyVerb, teamExportVerb } from "./team-apply.ts";
import { tokenVerb } from "./token.ts";
@@ -29,7 +34,48 @@ openmausbot doctor --data [--fix] [--data-dir DIR]
--fix applies the repairs that cannot lose data, only while no server uses the folder; whatever a repair changes is
copied to DIR/doctor-backups/<time>/ first. Anything else is reported with what to do.
Exit 0 fine (after --fix: fine now), 8 a problem is left.`,
- bots: "openmausbot bots\n Your bots and what each is doing.",
+ login: `openmausbot login [SERVER] [--scope chat] [--name NAME]
+ Sign this terminal in, once. On this computer MausBot shows a card with a short code: check it matches the one printed
+ here and press Allow. For a Cloud or a server elsewhere (openmausbot login https://maus.example.com) your browser opens
+ the same card. The sign-in lasts 30 days and renews while you use it; it is kept in the macOS Keychain (elsewhere in a
+ file only you can read) and never printed. --scope chat signs in for chat only. Every command then uses this server.
+ Inside a bot's own shell it refuses: there the command acts as that bot.`,
+ logout: "openmausbot logout [NAME]\n Sign out of the current server (or NAME): its session ends there and is removed here.",
+ whoami: "openmausbot whoami\n Which server the commands go to, and who you are to it.",
+ use: "openmausbot use NAME\n Send every command to another saved server (openmausbot servers lists them).",
+ servers: "openmausbot servers\n The servers you signed in to; * marks the one commands go to.",
+ status: `openmausbot status
+ Every bot at a glance: working, waiting on you, waiting on teammates, paused, failed or idle, with its computer and team.`,
+ bots: `openmausbot bots [list] your bots and what each is doing
+openmausbot bots get BOT
+openmausbot bots delete (BOT… | --team NAME | --all) [--dry-run] [--yes]
+openmausbot bots pause | resume (BOT… | --team NAME | --all) [--dry-run]
+openmausbot bots stop (BOT… | --team NAME | --all) [--dry-run] [--yes]
+ delete prints the bots it would delete and asks first; --yes skips the question (a script must pass it),
+ --dry-run only prints the list. Pausing stops their work and lasts across restarts until resume; --team pauses
+ the team itself, so bots added to it later are paused too. stop stops their work now and pauses nothing.`,
+ "bots list": "openmausbot bots list\n Your bots and what each is doing (the same as openmausbot bots).",
+ "bots get": "openmausbot bots get BOT\n One bot: its team, state, computer, model, approvals and conversations.",
+ "bots delete": "openmausbot bots delete (BOT… | --team NAME | --all) [--dry-run] [--yes]\n Delete bots with their conversations. It prints the list and asks first; MausBot itself and a busy bot are refused.",
+ "bots pause": "openmausbot bots pause (BOT… | --team NAME | --all) [--dry-run]\n Pause bots: their work stops and nothing new starts, across restarts, until bots resume.",
+ "bots resume": "openmausbot bots resume (BOT… | --team NAME | --all) [--dry-run]\n Resume paused bots.",
+ "bots stop": "openmausbot bots stop (BOT… | --team NAME | --all) [--dry-run] [--yes]\n The same as openmausbot stop.",
+ stop: `openmausbot stop (BOT… | --team NAME | --all) [--dry-run] [--yes]
+ Stop the work these bots are doing now: every conversation, routine run and hand-off. Nothing is paused, so a new
+ message or routine starts them again. --all prints the bots working now and asks first.`,
+ threads: `openmausbot threads list BOT
+openmausbot threads clear BOT [--dry-run] [--yes] delete every conversation (the bot keeps one new, empty one)
+openmausbot threads delete BOT THREAD… [--dry-run] [--yes]
+ A conversation that is working is kept: stop it first.`,
+ "threads list": "openmausbot threads list BOT\n A bot's conversations; * marks the one it has open.",
+ "threads clear": "openmausbot threads clear BOT [--dry-run] [--yes]\n Delete all of a bot's conversations; it keeps one new, empty one. Prints the list and asks first.",
+ "threads delete": "openmausbot threads delete BOT THREAD… [--dry-run] [--yes]\n Delete some of a bot's conversations, by id (threads list shows them). Prints the list and asks first.",
+ computers: `openmausbot computers list where each bot works, and its cloud computer's state
+openmausbot computers start BOT create or wake a bot's cloud computer (the bot must be set to Cloud computer)
+openmausbot computers sleep BOT put it to sleep; it wakes when the bot needs it`,
+ "computers list": "openmausbot computers list\n Where each bot works, and its cloud computer's state.",
+ "computers start": "openmausbot computers start BOT [--dry-run]\n Create or wake a bot's cloud computer, and wait until it is ready.",
+ "computers sleep": "openmausbot computers sleep BOT [--dry-run]\n Put a bot's cloud computer to sleep.",
channels: "openmausbot channels\n Your rooms (group chats) and who is in them.",
models: "openmausbot models\n The engines and the models each offers (use them as INSTANCE/MODEL).",
messages: `openmausbot messages TARGET [--limit 30]\n The latest messages of a conversation (at most 200).
@@ -86,8 +132,9 @@ openmausbot doctor --data [--fix] [--data-dir DIR]
claude: the key runs every Claude bot; --only-claude-api keeps it to "Claude (API key)" bots.`,
"engine list": "openmausbot engine list\n The engines, whether each is ready, and which keys are set (never their values).",
connect: `openmausbot connect [URL] [--code CODE] --out FILE [--label NAME] [--client] [--force]
- Get a token for a workspace you reach over the network, saved to FILE (only you can read it).
- On this computer's own server the code is made for you; elsewhere, get one from Settings → Phone & devices.
+ Get a token for a workspace you reach over the network, saved to FILE (only you can read it). For yourself at a
+ terminal, openmausbot login is simpler. On a server you started with openmausbot serve the code is made for you;
+ for the desktop app or a server elsewhere, get one from Settings → Phone & devices.
Then use it: --url URL --token-file FILE (or OPENMAUSBOT_URL and OPENMAUSBOT_TOKEN).`,
mcp: "openmausbot mcp\n Serve the OpenMausBot MCP tools on stdin and stdout, for an agent (docs/mcp-server.md).",
token: "openmausbot token create NAME --out FILE … | token list | token revoke ID (see help token create)",
@@ -109,6 +156,12 @@ export interface HeadlessOptions {
requireExplicitForMutations?: boolean;
defaultWaitMs?: number;
signal?: AbortSignal;
+ /** Tests: stand-ins for macOS `security`, the platform, the terminal and the browser. */
+ security?: SecurityRunner;
+ platform?: NodeJS.Platform;
+ interactive?: boolean;
+ confirm?: (question: string) => Promise<boolean>;
+ openBrowser?: (url: string) => Promise<boolean>;
}
const VERBS: Record<string, (ctx: VerbContext) => Promise<VerbOutcome>> = {
@@ -116,6 +169,10 @@ const VERBS: Record<string, (ctx: VerbContext) => Promise<VerbOutcome>> = {
interrupt, "new-bot": newBot, "new-channel": newChannel, "set-model": setModel, edit, export: exportVerb, events: eventsVerb,
"team apply": teamApplyVerb, "team export": teamExportVerb, "engine set": engineVerb, "engine list": engineVerb, connect: connectVerb,
"token create": tokenVerb, "token list": tokenVerb, "token revoke": tokenVerb,
+ login: loginVerb, logout: logoutVerb, whoami: whoamiVerb, use: useVerb, servers: serversVerb, status: statusVerb,
+ "bots list": list, "bots get": botsVerb, "bots delete": botsVerb, "bots pause": botsVerb, "bots resume": botsVerb, "bots stop": botsVerb,
+ stop: stopVerb, "threads list": threadsVerb, "threads clear": threadsVerb, "threads delete": threadsVerb,
+ "computers list": computersVerb, "computers start": computersVerb, "computers sleep": computersVerb,
};
async function execute(argv: readonly string[], options: HeadlessOptions, io: HeadlessIo): Promise<{ outcome: VerbOutcome; output: Output; client?: HeadlessClient }> {
@@ -131,20 +188,28 @@ async function execute(argv: readonly string[], options: HeadlessOptions, io: He
return { outcome: { result: null, exitCode: EXIT.done, human: [], printed: true }, output };
}
const env = options.env ?? process.env;
+ const botShell = inBotShell(env);
+ // control-omb drives fixtures only: a saved sign-in would point it at the person's own workspace.
+ const saved = botShell || options.requireExplicitForMutations ? null : new SavedServers({ env, ...(options.platform ? { platform: options.platform } : {}), ...(options.security ? { security: options.security } : {}) });
let client: HeadlessClient | undefined;
let opening: Promise<HeadlessClient> | undefined;
const ctx: VerbContext = {
verb: parsed.verb, flags: parsed.flags, positionals: parsed.positionals, env, io, output,
client: () => (opening ??= openClient(parsed.flags, { env, ...(options.callTool ? { callTool: options.callTool } : {}),
- ...(options.request ? { request: options.request } : {}), requireExplicitForMutations: options.requireExplicitForMutations === true },
+ ...(options.request ? { request: options.request } : {}), requireExplicitForMutations: options.requireExplicitForMutations === true,
+ ...(saved ? { saved } : {}) },
MUTATING_VERBS.has(parsed.verb)).then((opened) => (client = opened))),
signal: options.signal ?? new AbortController().signal,
defaultWaitMs: options.defaultWaitMs ?? 30 * 60_000,
+ botShell, saved,
+ interactive: options.interactive ?? terminalPresent(),
+ confirm: options.confirm ?? ((question) => askOnTerminal(question, io)),
+ openBrowser: options.openBrowser ?? openInBrowser,
};
try {
return { outcome: await VERBS[parsed.verb]!(ctx), output, ...(client ? { client } : {}) };
} catch (error) {
- throw await explain(error, client?.baseUrl);
+ throw await explain(error, client?.baseUrl, { botShell, ...(client ? { identity: client.identity } : {}) });
}
}
diff --git a/server/headless/prompt.ts b/server/headless/prompt.ts
new file mode 100644
index 0000000000..81a4d2a224
--- /dev/null
+++ b/server/headless/prompt.ts
@@ -0,0 +1,39 @@
+import { spawn } from "node:child_process";
+import { createInterface } from "node:readline/promises";
+
+import type { HeadlessIo } from "./output.ts";
+
+/** A person can answer: both ends are a terminal. A pipe, CI or another agent is not. */
+export function terminalPresent(): boolean {
+ return process.stdin.isTTY === true && process.stderr.isTTY === true;
+}
+
+/** Asks on stderr, so stdout stays the command's result; only "y" or "yes" is a yes. */
+export async function askOnTerminal(question: string, io: HeadlessIo): Promise<boolean> {
+ const lines = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
+ try {
+ const answer = await lines.question(`${question} [y/N] `);
+ return /^y(?:es)?$/i.test(answer.trim());
+ } catch {
+ io.err("");
+ return false;
+ } finally {
+ lines.close();
+ }
+}
+
+/** The person's own browser, through the platform's opener; the address is one argument, never a shell string. */
+export function openInBrowser(url: string): Promise<boolean> {
+ const [command, args] = process.platform === "darwin" ? ["open", [url]]
+ : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
+ : ["xdg-open", [url]];
+ return new Promise((resolve) => {
+ try {
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
+ child.once("error", () => resolve(false));
+ child.once("spawn", () => { child.unref(); resolve(true); });
+ } catch {
+ resolve(false);
+ }
+ });
+}
diff --git a/server/headless/run.test.ts b/server/headless/run.test.ts
index 531ed8196f..47679065ff 100644
--- a/server/headless/run.test.ts
+++ b/server/headless/run.test.ts
@@ -228,7 +228,7 @@ describe("wait", () => {
expect((await harness([waited("settled", "completed", job("completed", "v1"))], { drops: [proxy] }).run(["wait", "--thread", "t1", "--json"])).code).toBe(0);
const refused = Object.assign(new Error("OpenMausBot API error (401): {\"error\":\"unauthorized\"}"), { status: 401 });
const gone = harness([waited("settled", "completed", job("completed", "v1"))], { drops: [refused] });
- expect((await gone.run(["wait", "--thread", "t1", "--json"])).code).toBe(5);
+ expect((await gone.run(["wait", "--thread", "t1", "--json"])).code).toBe(4);
expect(gone.calls.filter((call) => call.name === "wait_for_conversation")).toHaveLength(1);
// a bug's TypeError is not a dropped connection: it fails at once
const bug = harness([waited("settled", "completed", job("completed", "v1"))], { drops: [new TypeError("Cannot read properties of undefined (reading 'job')")] });
diff --git a/server/headless/saved-servers.test.ts b/server/headless/saved-servers.test.ts
new file mode 100644
index 0000000000..bf232f910e
--- /dev/null
+++ b/server/headless/saved-servers.test.ts
@@ -0,0 +1,103 @@
+import "../testing/scrub-ambient-omb-env.ts";
+
+import { mkdtempSync, readFileSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+import { removeTempDir } from "../testing/cleanup.ts";
+import { inBotShell } from "./bot-shell.ts";
+import { openClient } from "./client.ts";
+import { cliConfigDir, SavedServers, type SecurityRunner } from "./saved-servers.ts";
+
+const home = mkdtempSync(join(tmpdir(), "omb-saved-"));
+afterAll(() => removeTempDir(home));
+
+/** A stand-in for macOS `security`: a map, so no keychain is touched. Records every argv to prove a session is never on one. */
+function fakeKeychain() {
+ const items = new Map<string, string>();
+ const argv: string[][] = [];
+ const runner: SecurityRunner = (args, stdin) => {
+ argv.push([...args]);
+ if (args[0] === "-i") {
+ const match = /^add-generic-password -U -s "([^"]+)" -a "([^"]+)" -l "[^"]*" -w "([^"]+)"\n$/.exec(stdin ?? "");
+ if (!match) return { status: 1, stdout: "" };
+ items.set(`${match[1]}/${match[2]}`, match[3]!);
+ return { status: 0, stdout: "" };
+ }
+ const service = args[args.indexOf("-s") + 1], account = args[args.indexOf("-a") + 1];
+ if (args[0] === "find-generic-password") {
+ const found = items.get(`${service}/${account}`);
+ return found ? { status: 0, stdout: `${found}\n` } : { status: 44, stdout: "" };
+ }
+ if (args[0] === "delete-generic-password") return { status: items.delete(`${service}/${account}`) ? 0 : 44, stdout: "" };
+ return { status: 1, stdout: "" };
+ };
+ return { items, argv, runner };
+}
+
+const server = { url: "http://127.0.0.1:8799", environmentId: "env-1", label: "Studio", sessionId: "s1", scopes: ["admin", "client"], expiresAt: 1 };
+
+describe("saved servers", () => {
+ it("lives under the command's own HOME or XDG_CONFIG_HOME, never the process's", () => {
+ expect(cliConfigDir({ HOME: "/h" }, "darwin")).toBe(join("/h", ".config", "openmausbot"));
+ expect(cliConfigDir({ HOME: "/h", XDG_CONFIG_HOME: "/x" }, "linux")).toBe(join("/x", "openmausbot"));
+ expect(cliConfigDir({ USERPROFILE: "C:\\u", APPDATA: "C:\\a" }, "win32")).toBe(join("C:\\a", "openmausbot"));
+ expect(cliConfigDir({}, "linux")).toBeNull();
+ });
+
+ it("keeps the session in the Keychain on a Mac, fed on stdin so it is never on a command line", () => {
+ const keychain = fakeKeychain();
+ const saved = new SavedServers({ env: { HOME: join(home, "mac") }, platform: "darwin", security: keychain.runner });
+ expect(saved.save("local", server, "omb_sess_secret_value")).toBe("keychain");
+ expect(keychain.items.get("openmausbot-cli/local")).toBe("omb_sess_secret_value");
+ expect(keychain.argv.flat().join(" ")).not.toContain("omb_sess_secret_value");
+ const file = join(home, "mac", ".config", "openmausbot", "servers.json");
+ expect(readFileSync(file, "utf8")).not.toContain("omb_sess_secret_value");
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(saved.token("local")).toBe("omb_sess_secret_value");
+ expect(saved.current()).toMatchObject({ name: "local", url: server.url, store: "keychain" });
+ saved.forget("local");
+ expect(keychain.items.size).toBe(0);
+ expect(saved.current()).toBeNull();
+ });
+
+ it.skipIf(process.platform === "win32")("falls back to a file only this user can read when there is no Keychain", () => {
+ const saved = new SavedServers({ env: { HOME: join(home, "linux") }, platform: "linux", security: () => { throw new Error("no security on Linux"); } });
+ expect(saved.save("box", { ...server, url: "https://maus.example.com" }, "omb_sess_file_value")).toBe("file");
+ const file = join(home, "linux", ".config", "openmausbot", "sessions", "box");
+ expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(saved.token("box")).toBe("omb_sess_file_value");
+ expect(saved.at("https://maus.example.com")?.name).toBe("box");
+ expect(saved.at("https://maus.example.com.evil.test")).toBeNull();
+ });
+
+ it("sends a saved session only to the exact address it was made at, and never from a bot's shell", async () => {
+ const keychain = fakeKeychain();
+ const env = { HOME: join(home, "send") };
+ const saved = new SavedServers({ env, platform: "darwin", security: keychain.runner });
+ saved.save("local", server, "omb_sess_saved");
+ const request = vi.fn(async () => ({}));
+ const headers = () => (request.mock.calls.at(-1) as unknown as [string, RequestInit, string]);
+
+ const current = await openClient({}, { env, request, saved }, true);
+ expect(current).toMatchObject({ baseUrl: server.url, explicit: true, identity: { kind: "saved", name: "local" } });
+ await current.json("/api/bots");
+ expect(new Headers(headers()[1].headers).get("authorization")).toBe("Bearer omb_sess_saved");
+
+ const elsewhere = await openClient({ url: "http://127.0.0.1:18799" }, { env, request, saved }, true);
+ await elsewhere.json("/api/bots");
+ expect(elsewhere.identity).toEqual({ kind: "none" });
+ expect(new Headers(headers()[1].headers).has("authorization")).toBe(false);
+
+ const named = await openClient({ port: "8799" }, { env, request, saved }, true);
+ expect(named.identity).toMatchObject({ kind: "saved" });
+
+ // In a bot's shell main.ts passes no saved servers at all, so the person's session is never read.
+ expect(inBotShell({ OMB_DESKTOP_PARENT: "1" })).toBe(true);
+ expect(inBotShell({ OMB_HOOK_TOKEN_FILE: "/tmp/x" })).toBe(true);
+ expect(inBotShell({ OMB_COMMS_TOKEN: "t" })).toBe(true);
+ expect(inBotShell({ OMB_ENGINE_TAG: "0123456789abcdef0123456789abcdef" })).toBe(true);
+ expect(inBotShell({ HOME: "/h", OMB_PORT: "8799", OMB_DATA_DIR: "/d" })).toBe(false);
+ });
+});
diff --git a/server/headless/saved-servers.ts b/server/headless/saved-servers.ts
new file mode 100644
index 0000000000..33af6b2d61
--- /dev/null
+++ b/server/headless/saved-servers.ts
@@ -0,0 +1,191 @@
+// The servers `openmausbot login` signed in to, like kubectl's contexts: servers.json names each server and which one is
+// current; the session itself is in the macOS Keychain, or in a file only this user can read elsewhere. Nothing here is
+// ever printed. Paths come from the environment the command runs with, never from the process's own home.
+import { spawnSync } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { HeadlessError, EXIT } from "./args.ts";
+import { inBotShell } from "./bot-shell.ts";
+
+export interface SavedServer {
+ url: string;
+ environmentId: string;
+ label: string;
+ sessionId: string;
+ scopes: string[];
+ expiresAt: number;
+ store: "keychain" | "file";
+}
+
+interface SavedFile {
+ current?: string;
+ servers: Record<string, SavedServer>;
+}
+
+/** Runs macOS `security` with `stdin` as its input; tests pass a fake so no real keychain is touched. */
+export type SecurityRunner = (args: readonly string[], stdin?: string) => { status: number | null; stdout: string };
+
+export interface SavedServersOptions {
+ env: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ security?: SecurityRunner;
+}
+
+const KEYCHAIN_SERVICE = "openmausbot-cli";
+const NAME = /^[\w.-]{1,80}$/;
+
+const runSecurity: SecurityRunner = (args, stdin) => {
+ const result = spawnSync("/usr/bin/security", [...args], { input: stdin, encoding: "utf8", timeout: 15_000 });
+ return { status: result.status, stdout: result.stdout ?? "" };
+};
+
+export function cliConfigDir(env: NodeJS.ProcessEnv, platform: NodeJS.Platform = process.platform): string | null {
+ if (env.XDG_CONFIG_HOME?.trim()) return join(env.XDG_CONFIG_HOME.trim(), "openmausbot");
+ if (platform === "win32" && env.APPDATA?.trim()) return join(env.APPDATA.trim(), "openmausbot");
+ const home = env.HOME?.trim() || env.USERPROFILE?.trim();
+ return home ? join(home, ".config", "openmausbot") : null;
+}
+
+/** `security -i` reads its command from stdin, so the session never appears in a process list. */
+const quoted = (value: string) => `"${value.replace(/["\\]/g, "\\$&")}"`;
+
+export class SavedServers {
+ readonly dir: string | null;
+ private readonly platform: NodeJS.Platform;
+ private readonly security: SecurityRunner;
+
+ constructor(options: SavedServersOptions) {
+ this.platform = options.platform ?? process.platform;
+ this.dir = cliConfigDir(options.env, this.platform);
+ this.security = options.security ?? runSecurity;
+ }
+
+ private get file(): string | null {
+ return this.dir ? join(this.dir, "servers.json") : null;
+ }
+
+ private read(): SavedFile {
+ const file = this.file;
+ if (!file || !existsSync(file)) return { servers: {} };
+ try {
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as SavedFile;
+ return { ...(typeof parsed.current === "string" ? { current: parsed.current } : {}), servers: parsed.servers && typeof parsed.servers === "object" ? parsed.servers : {} };
+ } catch {
+ throw new HeadlessError(`${file} could not be read`, EXIT.failed, "fix or remove it, then run openmausbot login again");
+ }
+ }
+
+ private write(saved: SavedFile): void {
+ const file = this.file;
+ if (!file || !this.dir) throw new HeadlessError("no home folder to keep the sign-in in", EXIT.failed, "set HOME");
+ mkdirSync(this.dir, { recursive: true, mode: 0o700 });
+ const temporary = `${file}.${process.pid}.tmp`;
+ writeFileSync(temporary, `${JSON.stringify(saved, null, 2)}\n`, { mode: 0o600 });
+ if (this.platform !== "win32") chmodSync(temporary, 0o600);
+ renameSync(temporary, file);
+ }
+
+ list(): { current: string | null; servers: Array<SavedServer & { name: string }> } {
+ const saved = this.read();
+ return { current: saved.current ?? null, servers: Object.entries(saved.servers).map(([name, server]) => ({ name, ...server })) };
+ }
+
+ get(name: string): SavedServer | null {
+ return this.read().servers[name] ?? null;
+ }
+
+ current(): (SavedServer & { name: string }) | null {
+ const saved = this.read();
+ const server = saved.current ? saved.servers[saved.current] : undefined;
+ return server && saved.current ? { name: saved.current, ...server } : null;
+ }
+
+ /** The saved server at exactly this origin, so a session goes only where it was made. */
+ at(origin: string): (SavedServer & { name: string }) | null {
+ return this.list().servers.find((server) => server.url === origin) ?? null;
+ }
+
+ use(name: string): void {
+ const saved = this.read();
+ if (!saved.servers[name]) throw new HeadlessError(`no saved server named "${name}"`, EXIT.notFound, "openmausbot servers lists them");
+ this.write({ ...saved, current: name });
+ }
+
+ /** Keeps the session and makes this server current; says where the session went. */
+ save(name: string, server: Omit<SavedServer, "store">, token: string): SavedServer["store"] {
+ if (!NAME.test(name)) throw new HeadlessError(`"${name}" is not a usable name: letters, digits, dots and dashes`, EXIT.usage);
+ const store = this.putToken(name, token);
+ const saved = this.read();
+ this.write({ current: name, servers: { ...saved.servers, [name]: { ...server, store } } });
+ return store;
+ }
+
+ forget(name: string): void {
+ const saved = this.read();
+ const server = saved.servers[name];
+ if (!server) return;
+ this.removeToken(name, server.store);
+ const { [name]: _gone, ...rest } = saved.servers;
+ this.write({ ...(saved.current && saved.current !== name ? { current: saved.current } : {}), servers: rest });
+ }
+
+ token(name: string): string | null {
+ const server = this.get(name);
+ if (!server) return null;
+ if (server.store === "keychain") {
+ const found = this.security(["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", name, "-w"]);
+ return found.status === 0 && found.stdout.trim() ? found.stdout.trim() : null;
+ }
+ const file = this.tokenFile(name);
+ try {
+ return readFileSync(file, "utf8").trim() || null;
+ } catch {
+ return null;
+ }
+ }
+
+ private tokenFile(name: string): string {
+ return join(this.dir!, "sessions", name);
+ }
+
+ private putToken(name: string, token: string): SavedServer["store"] {
+ if (this.platform === "darwin") {
+ const added = this.security(["-i"], `add-generic-password -U -s ${quoted(KEYCHAIN_SERVICE)} -a ${quoted(name)} -l ${quoted(`OpenMausBot CLI: ${name}`)} -w ${quoted(token)}\n`);
+ if (added.status === 0) return "keychain";
+ }
+ if (!this.dir) throw new HeadlessError("no home folder to keep the sign-in in", EXIT.failed, "set HOME");
+ mkdirSync(join(this.dir, "sessions"), { recursive: true, mode: 0o700 });
+ const file = this.tokenFile(name);
+ rmSync(file, { force: true });
+ writeFileSync(file, `${token}\n`, { mode: 0o600, flag: "wx" });
+ if (this.platform !== "win32") chmodSync(file, 0o600);
+ return "file";
+ }
+
+ private removeToken(name: string, store: SavedServer["store"]): void {
+ if (store === "keychain") this.security(["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", name]);
+ else if (this.dir) rmSync(this.tokenFile(name), { force: true });
+ }
+}
+
+const classicHeaders = new Map<string, Promise<Record<string, string>>>();
+
+/** For the classic commands (pair, devices): the saved sign-in for exactly this origin, while the server there is still
+ * the one it was made for; never in a bot's shell. */
+export function savedSessionHeaders(origin: string, env: NodeJS.ProcessEnv = process.env): Promise<Record<string, string>> {
+ if (inBotShell(env)) return Promise.resolve({});
+ const known = classicHeaders.get(origin);
+ if (known) return known;
+ const looked = (async (): Promise<Record<string, string>> => {
+ const saved = new SavedServers({ env });
+ const server = saved.at(origin);
+ if (!server) return {};
+ const live = await fetch(`${origin}/.well-known/openmausbot/environment`, { signal: AbortSignal.timeout(3_000) })
+ .then((response) => response.json() as Promise<{ environmentId?: unknown }>, () => null);
+ const token = live?.environmentId === server.environmentId ? saved.token(server.name) : null;
+ return token ? { authorization: `Bearer ${token}` } : {};
+ })().catch(() => ({}));
+ classicHeaders.set(origin, looked);
+ return looked;
+}
diff --git a/server/headless/team-apply.test.ts b/server/headless/team-apply.test.ts
index 4903f7aa00..6e877e2e86 100644
--- a/server/headless/team-apply.test.ts
+++ b/server/headless/team-apply.test.ts
@@ -77,7 +77,7 @@ function workspace(seed: { bots?: Rec[]; groups?: Rec[]; sections?: string[]; co
throw new Error(`no route for ${method} ${path}`);
};
const client: HeadlessClient = {
- baseUrl: "http://omb", explicit: true, json, raw: async () => { throw new Error("no raw reads here"); },
+ baseUrl: "http://omb", explicit: true, identity: { kind: "none" }, json, raw: async () => { throw new Error("no raw reads here"); },
tool: async (name, args: Rec) => {
writes.push(`tool ${name}`);
if (name === "create_channel") state.groups.push({ id: `room-${++ids}`, name: args.name, memberIds: args.member_ids, section: args.section,
@@ -321,7 +321,7 @@ describe("team export", () => {
const out = join(dir, `team.${extension}`);
const ctx = { verb: "team export", flags: { out }, positionals: [], env: {}, io: { out: () => undefined, err: () => undefined, readStdin: async () => "" },
output: new Output({ out: () => undefined, err: () => undefined, readStdin: async () => "" }, {}), client: async () => client,
- signal: new AbortController().signal, defaultWaitMs: 1_000 } as VerbContext;
+ signal: new AbortController().signal, defaultWaitMs: 1_000, botShell: false, saved: null, interactive: false, confirm: async () => false, openBrowser: async () => false } as VerbContext;
await teamExportVerb(ctx);
if (extension === "yaml") expect(readFileSync(out, "utf8")).toMatch(/^# Written by openmausbot team export/);
const back = loadTeamFile(out);
@@ -345,7 +345,7 @@ describe("team export", () => {
const out = join(dir, `team.${extension}`);
const ctx = { verb: "team export", flags: { out }, positionals: [], env: {}, io: { out: () => undefined, err: () => undefined, readStdin: async () => "" },
output: new Output({ out: () => undefined, err: () => undefined, readStdin: async () => "" }, {}), client: async () => client,
- signal: new AbortController().signal, defaultWaitMs: 1_000 } as VerbContext;
+ signal: new AbortController().signal, defaultWaitMs: 1_000, botShell: false, saved: null, interactive: false, confirm: async () => false, openBrowser: async () => false } as VerbContext;
const exported = await teamExportVerb(ctx);
expect((exported.result as Rec).redacted).toEqual(['team "Launch Room" brief', 'bot "Room Lead" soul', 'bot "Room Lead" skill launch-report']);
const written = [readFileSync(out, "utf8"), readFileSync(join(dir, "skills/room-lead/launch-report/SKILL.md"), "utf8")].join("\n");
diff --git a/server/phone-relay.ts b/server/phone-relay.ts
index 8d13ba1744..645e157fe8 100644
--- a/server/phone-relay.ts
+++ b/server/phone-relay.ts
@@ -153,7 +153,7 @@ export function tunnelHolder(env: NodeJS.ProcessEnv, dataDir: string): string |
const account = openTunnelCredentials(dataDir);
if (account.status === "unavailable") return `${account.file} could not be read, so this machine may hold a tunnel address`;
const document = account.read();
- if (describeTunnelAccount(document).address || document[MANAGED_COMPANION_ENDPOINT_FIELD]) return "this machine holds a tunnel address from `openmausbot login`";
+ if (describeTunnelAccount(document).address || document[MANAGED_COMPANION_ENDPOINT_FIELD]) return "this machine holds a tunnel address from `openmausbot account login`";
return null;
}