Skip to content

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

Mistral (Vibe): sign-in through the engine's own browser flow

JoaoPec4fa959e76318
diff --git a/server/contracts.ts b/server/contracts.ts
index 8d2bd42008..ff7daece56 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -567,8 +567,7 @@ export interface ProviderInstance {
/** Optional first-party runtime installation and account setup. */
readonly installRuntime?: () => Promise<void>;
readonly startAuthentication?: () => Promise<ProviderAuthenticationStart>;
- readonly authenticationMethod?: "browser-pkce";
- readonly getAuthentication?: (flowId: string) => Promise<ProviderAuthenticationStatus>;
+ readonly authenticationMethod?: "browser-pkce" | "browser"; readonly getAuthentication?: (flowId: string) => Promise<ProviderAuthenticationStatus>;
readonly completeAuthentication?: (flowId: string, callbackUrl: string) => Promise<void>;
readonly cancelAuthentication?: () => Promise<void>;
/** Remove the provider CLI's stored sign-in on this server; never touches another instance's home. */
diff --git a/server/drivers/acp/browser-auth.test.ts b/server/drivers/acp/browser-auth.test.ts
new file mode 100644
index 0000000000..99ce9d04ed
--- /dev/null
+++ b/server/drivers/acp/browser-auth.test.ts
@@ -0,0 +1,144 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import { AcpBrowserAuth, type AcpBrowserSignInSpec } from "./browser-auth.ts";
+
+const fakeCli = join(import.meta.dirname, "../../testing/fake-vibe-acp-signin.mjs");
+
+function tempHome(): string {
+ return mkdtempSync(join(tmpdir(), "acp-browser-auth-"));
+}
+
+function spec(overrides: Partial<AcpBrowserSignInSpec> = {}): AcpBrowserSignInSpec {
+ return {
+ product: "Mistral",
+ methodId: (methods) => methods.some((method) => method.id === "browser-auth") ? "browser-auth" : null,
+ failure: (stage, detail) => `${stage}${detail ? ` (${detail})` : ""}`,
+ ...overrides,
+ };
+}
+
+const homes: string[] = [];
+afterAll(() => {
+ for (const home of homes) rmSync(home, { recursive: true, force: true });
+});
+
+const soon = { timeout: 10_000, interval: 100 };
+
+function makeAuth(home: string, ready: string, mode?: string): AcpBrowserAuth {
+ return new AcpBrowserAuth(spec({ args: [fakeCli] }), {
+ cli: process.execPath,
+ environment: () => ({ ...process.env, HOME: home, FAKE_VIBE_READY: ready, ...(mode ? { FAKE_VIBE_MODE: mode } : {}) }),
+ startupTimeoutMs: 30_000,
+ });
+}
+
+describe.skipIf(process.platform === "win32")("AcpBrowserAuth", () => {
+ it("holds authenticate open and succeeds once the readiness probe says signed in", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const ready = join(home, "ready");
+ const auth = makeAuth(home, ready);
+ const started = await auth.start();
+ expect(started).toMatchObject({ phase: "waiting", authorizationUrl: null });
+ const status = await auth.get(started.flowId!);
+ expect(status.phase).toBe("waiting");
+ writeFileSync(ready, "signed-in");
+ await expect.poll(async () => (await auth.get(started.flowId!)).phase, soon).toBe("succeeded");
+ await auth.dispose();
+ });
+
+ it("cancel ends the held flow without success", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const auth = makeAuth(home, join(home, "ready"));
+ const started = await auth.start();
+ await auth.cancel();
+ await expect(auth.get(started.flowId!)).resolves.toMatchObject({ phase: "cancelled" });
+ await auth.dispose();
+ });
+
+ it("fails with the processEnded stage when the engine exits before answering", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const auth = makeAuth(home, join(home, "ready"), "exit-after-init");
+ const started = await auth.start();
+ await expect.poll(async () => (await auth.get(started.flowId!)).phase, soon).toBe("failed");
+ await auth.dispose();
+ });
+
+ it("fails at the start stage when the engine offers no authentication methods", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const auth = makeAuth(home, join(home, "ready"), "no-methods");
+ const started = await auth.start();
+ await expect.poll(async () => (await auth.get(started.flowId!)).phase, soon).toBe("failed");
+ await auth.dispose();
+ });
+
+ it("never leaks the engine's own refusal words — the stage decides the message", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const auth = makeAuth(home, join(home, "ready"), "refused");
+ const started = await auth.start();
+ await expect.poll(async () => (await auth.get(started.flowId!)).phase, soon).toBe("failed");
+ const status = await auth.get(started.flowId!);
+ expect(JSON.stringify(status)).not.toContain("secret-token-do-not-leak");
+ await auth.dispose();
+ });
+
+ it("refuses an unknown flow id", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const auth = makeAuth(home, join(home, "ready"));
+ await expect(auth.get("no-such-flow")).rejects.toThrow();
+ await auth.dispose();
+ });
+
+ it("signOut runs the spec's removeCredentials", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const removed: string[] = [];
+ const auth = new AcpBrowserAuth(spec({ removeCredentials: (env) => { removed.push(env.HOME!); } }), {
+ cli: process.execPath,
+ environment: () => ({ ...process.env, HOME: home }),
+ });
+ await auth.signOut();
+ expect(removed).toEqual([home]);
+ await auth.dispose();
+ });
+
+ it("appends the server hint when the cli path is missing (ENOENT)", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const auth = new AcpBrowserAuth(
+ spec({ serverHint: "this sign-in happens on the computer running OpenMausBot" }),
+ { cli: join(home, "missing-cli"), environment: () => ({ ...process.env, HOME: home }) },
+ );
+ // A missing cli reports ENOENT asynchronously, after start has already resolved as waiting.
+ const started = await auth.start();
+ await expect.poll(async () => (await auth.get(started.flowId!)).phase, soon).toBe("failed");
+ const status = await auth.get(started.flowId!);
+ expect(status.message).toContain("computer running OpenMausBot");
+ await auth.dispose();
+ });
+
+ it("reports authenticated through onAuthenticated", async () => {
+ const home = tempHome();
+ homes.push(home);
+ const ready = join(home, "ready");
+ let notified: string | null = null;
+ const auth = new AcpBrowserAuth(spec({ args: [fakeCli] }), {
+ cli: process.execPath,
+ environment: () => ({ ...process.env, HOME: home, FAKE_VIBE_READY: ready }),
+ startupTimeoutMs: 30_000,
+ onAuthenticated: async () => { notified = "yes"; },
+ });
+ const started = await auth.start();
+ writeFileSync(ready, "signed-in");
+ await expect.poll(async () => (await auth.get(started.flowId!)).phase, soon).toBe("succeeded");
+ expect(notified).toBe("yes");
+ await auth.dispose();
+ });
+});
diff --git a/server/drivers/acp/browser-auth.ts b/server/drivers/acp/browser-auth.ts
new file mode 100644
index 0000000000..e9397e2550
--- /dev/null
+++ b/server/drivers/acp/browser-auth.ts
@@ -0,0 +1,277 @@
+//Browser sign-in through the engine's own ACP `authenticate`: the app starts a one-shot session much like a turn's
+// spawn, initializes it, and sends `authenticate`; the engine then opens the person's browser itself and holds that
+// request until the person finishes there. `start` resolves as soon as the engine holds the sign-in open (the
+// browser pops behind it); `get` reports the flow until the authenticate response, a readiness probe, expiry or a
+// cancel decides it; nothing leaves a session running on a failure path. This mirrors DeviceAuthController
+// (see device-auth.ts); the wire follows what a discovery session speaks (see custom-model-catalog.ts).
+import type { ChildProcess } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "../../contracts.ts";
+import { killCliTree, spawnCli } from "../../procs.ts";
+
+type Env = Record<string, string | undefined>;
+
+const MAX_LINE_BYTES = 1024 * 1024;
+const MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
+/** initialize is the only quick request; the long one is `authenticate`, under the flow's own expiry. */
+const INIT_TIMEOUT_MS = 30_000;
+
+/** Where a failure came from, seen by the app; the message is decided by stage, never by the CLI's own words. */
+export type AcpBrowserAuthStage = "start" | "initialize" | "authenticate" | "processEnded" | "expired";
+
+export interface AcpBrowserSignInSpec {
+ product: string;
+ /** Extra spawn arguments for the sign-in session, ahead of the engine's own session args. */
+ args?: readonly (string | ((env: Env) => string | undefined))[];
+ /** initialize's authMethods → the methodId the authenticate carries; null means no sign-in is offered. */
+ methodId(authMethods: Array<{ id?: string }>, env: Env): string | null;
+ /** Checked while the engine still holds `authenticate`: once the sign-in is there where a turn reads it, the flow
+ * ends well even if the engine never answers. */
+ signedIn?(env: Env): boolean;
+ /** On a server the engine's browser cannot reach the person's screen: one sentence of guidance. */
+ serverHint?: string;
+ /** One safe sentence for a failed sign-in, per stage; `detail` is the app's own observation. */
+ failure(stage: AcpBrowserAuthStage, detail?: string): string;
+ /** Remove the engine's own stored sign-in (its cache files, its keychain entry); the person's pasted
+ * provider key in Connections is not this engine's to remove. */
+ removeCredentials?(env: Env): void | Promise<void>;
+}
+
+export interface AcpBrowserAuthOptions {
+ cli: string;
+ /** The engine's own session spawn args, so the sign-in runs with a turn's environment. */
+ sessionArgs?: (env: Env) => readonly string[];
+ cwd?: string;
+ environment: () => Env;
+ onAuthenticated?: () => Promise<void>;
+ startupTimeoutMs?: number;
+ lifetimeMs?: number;
+ terminateTimeoutMs?: number;
+}
+
+type Flow = {
+ id: string;
+ status: ProviderAuthenticationStatus;
+ child: ChildProcess | null;
+ ready: boolean;
+ resolve: ((value: ProviderAuthenticationStart) => void) | null;
+ startupTimer: NodeJS.Timeout;
+ expiryTimer: NodeJS.Timeout;
+ stopping?: Promise<boolean>;
+};
+
+/** The instance surface an ACP driver exposes for its browser sign-in: start/get/cancel, plus `signOut` when the spec
+ * can remove the stored sign-in. Marked `browser` so the registry separates it from a device-code flow. Lives beside
+ * the controller so the instance wiring stays one line in each driver, like deviceAuthInstanceSurface (see
+ * device-auth.ts). */
+export function acpBrowserAuthInstanceSurface(auth: AcpBrowserAuth, spec: AcpBrowserSignInSpec) {
+ return {
+ authenticationMethod: "browser" as const,
+ startAuthentication: () => auth.start(),
+ getAuthentication: (flowId: string) => auth.get(flowId),
+ cancelAuthentication: () => auth.cancel(),
+ ...(spec.removeCredentials ? { signOut: () => auth.signOut() } : {}),
+ };
+}
+
+export class AcpBrowserAuth {
+ private flow: Flow | null = null;
+ /** A finished flow's status stays findable by its flowId until the next start replaces it, so a status poll never
+ * races a finishing sign-in. */
+ private finished: { flowId: string; status: ProviderAuthenticationStatus } | null = null;
+ private disposed = false;
+ private readonly spec: AcpBrowserSignInSpec;
+ private readonly options: AcpBrowserAuthOptions;
+
+ constructor(spec: AcpBrowserSignInSpec, options: AcpBrowserAuthOptions) {
+ this.spec = spec;
+ this.options = options;
+ }
+
+ async start(): Promise<ProviderAuthenticationStart> {
+ if (this.disposed) throw new Error("This provider was removed. Refresh Settings before signing in.");
+ if (this.flow) await this.flow.stopping;
+ if (this.flow) throw new Error(`A ${this.spec.product} sign-in is already in progress. Finish or cancel it first.`);
+ if (this.disposed) throw new Error("This provider was removed. Refresh Settings before signing in.");
+ return new Promise<ProviderAuthenticationStart>((resolveStart, rejectStart) => {
+ const env = this.options.environment();
+ const lifetimeMs = this.options.lifetimeMs ?? 15 * 60_000;
+ const flow: Flow = {
+ id: randomUUID(),
+ status: {
+ phase: "waiting", flowId: null, authorizationUrl: null,
+ expiresAt: new Date(Date.now() + lifetimeMs).toISOString(),
+ },
+ child: null, ready: false, resolve: null,
+ startupTimer: setTimeout(() => this.finish(flow, "failed", this.spec.failure("start")), this.options.startupTimeoutMs ?? 30_000),
+ expiryTimer: setTimeout(() => this.finish(flow, "expired", this.spec.failure("expired")), lifetimeMs),
+ };
+ flow.startupTimer.unref();
+ flow.expiryTimer.unref();
+ this.flow = flow;
+ this.finished = null;
+
+ const failFlow = (stage: AcpBrowserAuthStage, detail?: string) =>
+ this.finish(flow, "failed", this.spec.failure(stage, detail));
+ const spawnFail = (detail?: string) => {
+ const message = this.spec.failure("start", detail);
+ const reported = detail === "ENOENT" && this.spec.serverHint ? `${message} ${this.spec.serverHint}` : message;
+ this.finish(flow, "failed", reported);
+ rejectStart(new Error(message));
+ };
+
+ let child: ReturnType<typeof spawnCli>;
+ try {
+ const extra = (this.spec.args ?? []).map((arg) => typeof arg === "function" ? arg(env) : arg).filter((arg): arg is string => arg !== undefined);
+ const sessionArgs = this.options.sessionArgs ? this.options.sessionArgs(env) : [];
+ const argv = [this.options.cli, ...extra, ...sessionArgs];
+ child = spawnCli(argv[0], argv.slice(1), { cwd: this.options.cwd, env, stdio: ["pipe", "pipe", "pipe"] }, "bot");
+ } catch (error) {
+ spawnFail(error instanceof Error && typeof (error as { code?: unknown }).code === "string"
+ ? String((error as { code?: unknown }).code) : undefined);
+ return;
+ }
+ flow.child = child;
+ child.once("error", (error) => {
+ if (flow.ready || this.flow !== flow) return;
+ const code = error instanceof Error ? (error as { code?: unknown }).code : undefined;
+ if (code === "ENOENT") spawnFail("ENOENT");
+ else failFlow("processEnded", typeof code === "string" ? code : undefined);
+ });
+ child.once("close", (code) => {
+ if (flow.ready || this.flow !== flow) return;
+ failFlow("processEnded", code !== null ? `exit ${code}` : undefined);
+ });
+
+ const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
+ let requestSeq = 1;
+ let buffer = "";
+ child.stdout!.on("data", (chunk: Buffer) => {
+ buffer += chunk.toString("utf8");
+ if (buffer.length > MAX_OUTPUT_BYTES) { failFlow("processEnded", "overflow"); return; }
+ let newline: number;
+ while ((newline = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, newline);
+ buffer = buffer.slice(newline + 1);
+ if (line.length > MAX_LINE_BYTES) { failFlow("processEnded", "overflow"); return; }
+ this.receive(flow, pending, line);
+ }
+ });
+ child.stderr!.on("data", () => {});
+
+ const request = (method: string, params: unknown, timeoutMs: number) => new Promise<unknown>((resolve, rejectRequest) => { const id = requestSeq++;
+ const timer = setTimeout(() => {
+ pending.delete(id);
+ rejectRequest(new Error(`${method} was not answered in time`));
+ }, timeoutMs);
+ timer.unref?.();
+ pending.set(id, {
+ resolve: (value) => { clearTimeout(timer); resolve(value); },
+ reject: (error) => { clearTimeout(timer); rejectRequest(error); },
+ });
+ if (child.stdin.writable) child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
+ else rejectRequest(new Error("the sign-in process ended early"));
+ });
+
+ // The engine holds `authenticate` open until the browser step ends, and its answer IS that step's end; every
+ // request the engine itself raises is refused: this session grants nothing and decides nothing.
+ request("initialize", {
+ protocolVersion: 1,
+ clientInfo: { name: "openmausbot", version: "0.0.0" },
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
+ }, INIT_TIMEOUT_MS).then((raw) => {
+ if (this.flow !== flow) return;
+ const methods = Array.isArray((raw as { authMethods?: unknown })?.authMethods)
+ ? (raw as { authMethods: Array<{ id?: string }> }).authMethods : [];
+ const methodId = this.spec.methodId(methods, env);
+ if (!methodId) { failFlow("start"); return; }
+ request("authenticate", { methodId }, lifetimeMs).then(
+ () => this.finish(flow, "succeeded"),
+ () => failFlow("authenticate"),
+ );
+ }, () => failFlow("initialize"));
+
+ // The browser opens behind this; the person's progress shows up on the status endpoint.
+ resolveStart({ phase: "waiting", flowId: flow.id, authorizationUrl: null, expiresAt: flow.status.expiresAt });
+ });
+ }
+
+ async get(flowId: string): Promise<ProviderAuthenticationStatus> {
+ if (this.finished?.flowId === flowId) return { ...this.finished.status };
+ if (!flowId || this.flow?.id !== flowId) throw new Error("This sign-in is no longer available. Start sign-in again.");
+ const flow = this.flow;
+ if (!flow.ready && this.spec.signedIn && this.spec.signedIn(this.options.environment())) this.finish(flow, "succeeded");
+ return { ...(this.flow === flow ? flow.status : this.finished?.status ?? flow.status) };
+ }
+
+ async cancel(): Promise<void> {
+ const flow = this.flow;
+ if (flow) this.finish(flow, "cancelled", `${this.spec.product} sign-in was cancelled.`);
+ await flow?.stopping;
+ }
+
+ async dispose(): Promise<void> {
+ this.disposed = true;
+ await this.cancel();
+ this.flow = null;
+ }
+
+ /** Removes the engine's own stored sign-in; refuses while a sign-in is in progress. */
+ async signOut(): Promise<void> {
+ if (!this.spec.removeCredentials) throw new Error(`Signing out of ${this.spec.product} is not available from here.`);
+ if (this.flow) throw new Error(`Finish or cancel the ${this.spec.product} sign-in in progress before signing out.`);
+ await this.spec.removeCredentials(this.options.environment());
+ }
+
+ /** Every request the engine raises is refused; a reply to this app's requests resolves or rejects its pending. */
+ private receive(flow: Flow, pending: Map<number, { resolve(value: unknown): void; reject(error: Error): void }>, line: string) {
+ let parsed: unknown;
+ try { parsed = JSON.parse(line) as unknown; } catch { return; }
+ const message = (parsed ?? {}) as { id?: unknown; method?: unknown; error?: unknown; result?: unknown };
+ if (typeof message.method === "string" && message.id !== undefined && typeof message.id === "number") {
+ const stdin = flow.child?.stdin;
+ if (stdin?.writable) {
+ stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Not available during sign-in." } })}\n`);
+ }
+ return;
+ }
+ if (typeof message.id !== "number") return;
+ const entry = pending.get(message.id);
+ if (!entry) return;
+ pending.delete(message.id);
+ if (message.error !== undefined && message.error !== null && typeof message.error === "object"
+ && typeof (message.error as { message?: unknown }).message === "string") {
+ // The CLI's own words never travel — the stage decides the message the person reads.
+ entry.reject(new Error("a sign-in request was refused"));
+ } else entry.resolve(message.result);
+ }
+
+ private finish(flow: Flow, phase: "failed" | "succeeded" | "expired" | "cancelled", message?: string): void {
+ if (this.flow !== flow) return;
+ this.flow = null;
+ clearTimeout(flow.startupTimer);
+ clearTimeout(flow.expiryTimer);
+ flow.ready = true;
+ const status: ProviderAuthenticationStatus = {
+ ...flow.status, phase,
+ authorizationUrl: null, expiresAt: null,
+ ...(message ? { message } : {}),
+ };
+ this.finished = { flowId: flow.id, status };
+ if (phase === "succeeded") void this.options.onAuthenticated?.().catch(() => {});
+ // A start promise still open (a spawn failure before the early resolve) only ever rejects; finish's resolve was
+ // consumed by start() right after the spawn, so this is for that window alone.
+ flow.resolve?.({ phase: phase === "succeeded" ? "succeeded" : "waiting", flowId: flow.id, authorizationUrl: null, expiresAt: null });
+ flow.resolve = null;
+ const child = flow.child;
+ flow.child = null;
+ if (child) flow.stopping = this.stopChild(child);
+ }
+
+ private async stopChild(child: ChildProcess): Promise<boolean> {
+ const stopped = await killCliTree(child, this.options.terminateTimeoutMs ?? 2_000).catch(() => false);
+ if (stopped || child.exitCode !== null || child.signalCode !== null) return true;
+ child.kill("SIGKILL");
+ return false;
+ }
+}
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index f349569f4f..25a310763a 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -15,6 +15,7 @@ import { openStartupModelCatalog } from "../../startup-model-catalog.ts";
import { acpModelCatalog } from "./model-catalog.ts";
import { decodeInjectId } from "../local-inject.ts";
import { DeviceAuthController, deviceAuthInstanceSurface, type DeviceSignIn } from "../device-auth.ts";
+import { AcpBrowserAuth, acpBrowserAuthInstanceSurface, type AcpBrowserSignInSpec } from "./browser-auth.ts";
import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";
import type { PromptSplitReceipt } from "../prompt-split.ts";
import { describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts";
@@ -131,6 +132,10 @@ export interface AcpSupport {
/** The CLI's own device-code login (`grok login --device-auth`), run with the turns' binary and
* environment and confirmed by isAuthenticated. */
deviceSignIn?: DeviceSignIn;
+ /** The agent's own ACP `authenticate` as a sign-in from the app: it spawns one sign-in session, sends
+ * initialize + authenticate, and the engine itself opens the person's browser and blocks the request until
+ * the person finishes there. The spec holds only this CLI's differences. */
+ browserSignIn?: AcpBrowserSignInSpec;
/** CLI argv AFTER the binary name to enter ACP stdio mode. */
spawnArgs(config: AcpConfig, turn: SendTurnInput): string[];
/** Provider credential variables this ACP child is allowed to inherit. */
@@ -368,6 +373,13 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const deviceSignIn = support.deviceSignIn
? new DeviceAuthController(support.deviceSignIn, { cli: config.cli, environment: () => childEnv(), onAuthenticated: refreshModels })
: null;
+ const browserSignIn = support.browserSignIn
+ ? new AcpBrowserAuth(support.browserSignIn, {
+ cli: config.cli,
+ environment: () => childEnv(),
+ onAuthenticated: refreshModels,
+ })
+ : null;
const listeners = new Set<RuntimeEventListener>();
let disposing = false;
const requireRunning = () => {
@@ -1639,6 +1651,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
refreshModels: support.resolveModels ? () => refreshModels(true) : undefined,
...(startupModelRefresh ? { startupModelRefresh } : {}),
...(support.deviceSignIn && deviceSignIn ? deviceAuthInstanceSurface(deviceSignIn, support.deviceSignIn) : {}),
+ ...(support.browserSignIn && browserSignIn ? acpBrowserAuthInstanceSurface(browserSignIn, support.browserSignIn) : {}),
snapshot,
adapter: {
provider: DRIVER_KIND,
@@ -1686,6 +1699,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
dispose: async () => {
disposing = true;
await deviceSignIn?.dispose();
+ await browserSignIn?.dispose();
const disposingSessions = Array.from(sessions);
for (const { stop } of active.values()) stop();
for (const [threadId, session] of disposingSessions) {
diff --git a/server/drivers/acp/mistral-vibe.ts b/server/drivers/acp/mistral-vibe.ts
index 011ca34376..8583b315fa 100644
--- a/server/drivers/acp/mistral-vibe.ts
+++ b/server/drivers/acp/mistral-vibe.ts
@@ -15,7 +15,8 @@
// `model`, and `thinking` (off | high). `thinking` follows the chosen model's own default;
// item-specific thought levels prove nothing here, so variants stay off.
// - `vibe-acp --version` prints "vibe-acp 3.1.1".
-import { existsSync, readFileSync } from "node:fs";
+import { execFile } from "node:child_process";
+import { existsSync, readFileSync, rmSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
@@ -68,8 +69,19 @@ function offeredModels(sessionConfig: unknown): { values: string[]; current?: st
};
}
-/** Discovers models in a temporary session, so a refresh leaves no record in the person's Vibe history. */
-export async function resolveMistralVibeModels(
+/** Sign-out removes what the engine's own browser sign-in wrote: the whoami cache everywhere, and the
+ * macOS keychain entry it stores the token in. A pasted plan key in Connections is not touched. */
+export async function removeMistralVibeSignIn(env: Record<string, string | undefined>): Promise<void> {
+ const home = vibeHome(env);
+ try { rmSync(join(home, "whoami_cache.json"), { force: true }); } catch {}
+ if (process.platform !== "darwin") return;
+ await new Promise<void>((resolve) => {
+ execFile("security", ["delete-generic-password", "-s", "ai.mistral.vibe"], { timeout: 5_000, windowsHide: true }, () => resolve());
+ });
+}
+
+
+/** Discovers models in a temporary session, so a refresh leaves no record in the person's Vibe history. */export async function resolveMistralVibeModels(
env: Record<string, string | undefined>,
config: Pick<AcpConfig, "cli">,
): Promise<ModelCatalog> {
@@ -104,6 +116,27 @@ export const mistralVibeSupport: AcpSupport = {
},
spawnArgs: () => [],
credentialEnv: ["MISTRAL_API_KEY"],
+ // The app signs in through the engine's own authenticate step: the child opens the browser itself and
+ // holds the request until the person finishes there (see header).
+ browserSignIn: {
+ product: "Mistral",
+ methodId: (methods) => (methods.some((method) => method.id === "browser-auth") ? "browser-auth" : null),
+ signedIn: (env) => vibeSignedIn(env),
+ serverHint:
+ "OpenMausBot cannot reach a browser on this server. Sign in from a machine that runs OpenMausBot, or paste a Mistral API key under Settings → Connections → Model providers.",
+ failure(stage, detail) {
+ switch (stage) {
+ case "start": return detail === "ENOENT"
+ ? "Mistral Vibe isn't installed where OpenMausBot runs. Install it on this card, then try again."
+ : "Mistral Vibe did not start a sign-in in time. Update the CLI on this card, then try again.";
+ case "initialize": return "Mistral Vibe did not answer its sign-in handshake in time. Update the CLI on this card, then try again.";
+ case "authenticate": return "The Mistral sign-in did not finish. It may have been cancelled in the browser; start it again to retry.";
+ case "processEnded": return "The Mistral sign-in ended before finishing. Update the CLI on this card, then try again.";
+ case "expired": return "The Mistral sign-in window expired. Start it again to retry.";
+ }
+ },
+ removeCredentials: removeMistralVibeSignIn,
+ },
// Model is a session config option (see header); ids pass through unchanged.
selectModel: { configId: "model" },
resolveModels: resolveMistralVibeModels,
diff --git a/server/drivers/acp/probe-errors.test.ts b/server/drivers/acp/probe-errors.test.ts
index a2a2cf9709..0c2cdc6879 100644
--- a/server/drivers/acp/probe-errors.test.ts
+++ b/server/drivers/acp/probe-errors.test.ts
@@ -9,7 +9,7 @@ import { KimiAgentDriver } from "./kimi.ts";
afterEach(() => vi.restoreAllMocks());
it.each([
- [{ code: "ENOENT" }, "isn't installed, or isn't on this app's PATH"],
+ [{ code: "ENOENT" }, "isn't installed where the app runs"],
[{ code: "EACCES" }, "isn't executable"],
[{ killed: true, signal: "SIGTERM" }, "timed out"],
[{ code: 1 }, "version check failed"],
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index 03a6f75948..f1366920c4 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -357,7 +357,11 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
const instance = registry.get(instanceId);
if (!instance) return json(res, 404, { error: "unknown instance" });
// The official local OAuth callback terminates on this machine, not a phone or a remote browser.
- if (instance.authenticationMethod === "browser-pkce" && (isProxied(req) || !isLoopbackHost(req.socket.remoteAddress))) {
+ if ((instance.authenticationMethod === "browser-pkce" || instance.authenticationMethod === "browser")
+ && (isProxied(req) || !isLoopbackHost(req.socket.remoteAddress))) {
+ if (instance.authenticationMethod === "browser") {
+ return json(res, 403, { error: "This sign-in happens in a browser on the computer running OpenMausBot. Open OpenMausBot there to sign in." });
+ }
return json(res, 403, { error: "Continue with ChatGPT on the computer running OpenMausBot. Hosted Pro sign-in requires OpenAI's hosted-app approval." });
}
const started = await providerAuthSessions.start(instance, owner);
diff --git a/server/testing/fake-vibe-acp-signin.mjs b/server/testing/fake-vibe-acp-signin.mjs
new file mode 100644
index 0000000000..7fe49c0c7f
--- /dev/null
+++ b/server/testing/fake-vibe-acp-signin.mjs
@@ -0,0 +1,34 @@
+#!/usr/bin/env node
+// Offline stand-in for an ACP engine during its own browser sign-in: on `authenticate` it holds the request open
+// the way Mistral Vibe does, until the FAKE_VIBE_READY file appears (the person finished in their browser) or the
+// process is killed. Modes: ok (answers authenticate once the ready file appears) | never (never answers) |
+// exit-after-init (closes before answering) | no-methods (initialize offers none) | refused (answers authenticate
+// with an error carrying a token, which must never reach the person). No network, no real credential.
+import { existsSync } from "node:fs";
+import { createInterface } from "node:readline";
+
+const mode = process.env.FAKE_VIBE_MODE || "ok";
+const ready = () => process.env.FAKE_VIBE_READY;
+const replyOk = (id, result) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
+
+createInterface({ input: process.stdin }).on("line", (line) => {
+ let message;
+ try { message = JSON.parse(line); } catch { return; }
+ if (message.method === "initialize") {
+ const methods = mode === "no-methods" ? [] : [{ id: "browser-auth", name: "Sign in" }];
+ replyOk(message.id, { protocolVersion: 1, authMethods: methods });
+ if (mode === "exit-after-init") setImmediate(() => process.exit(3));
+ return;
+ }
+ if (message.method !== "authenticate") return;
+ if (mode === "refused") {
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -1, message: "sign-in failed: secret-token-do-not-leak" } })}\n`);
+ return;
+ }
+ const hold = setInterval(() => {
+ if (mode === "ok" && existsSync(ready())) {
+ clearInterval(hold);
+ replyOk(message.id, {});
+ }
+ }, 50);
+});
diff --git a/src/components/EngineBrowserSignIn.tsx b/src/components/EngineBrowserSignIn.tsx
new file mode 100644
index 0000000000..d102a9f219
--- /dev/null
+++ b/src/components/EngineBrowserSignIn.tsx
@@ -0,0 +1,153 @@
+//A sign-in whose engine opens the person's browser itself (Mistral Vibe's ACP authenticate): the app starts the
+// flow, then only polls until the engine reports it done — there is no link or code to show.
+import { useEffect, useRef, useState } from "react";
+import { Loader2, LogIn } from "lucide-react";
+import { api, useStore } from "@/state/store";
+import { intlLocale, t } from "@/lib/i18n";
+import { engineSignedIn } from "@/lib/product-events";
+import { deviceFlowUnavailable, type DeviceSignInStatus } from "./DeviceSignIn";
+
+function ended(phase: "failed" | "expired"): DeviceSignInStatus {
+ return {
+ phase, flowId: null, authorizationUrl: null, expiresAt: null,
+ ...(phase === "failed" ? { message: t("engineSetup.engineBrowser.failed") } : {}),
+ };
+}
+
+/** A start button, a spinner while the person finishes in their browser, and the outcome. */
+export function EngineBrowserSignIn({ instanceId, autoStart = false, onDone }: {
+ instanceId: string;
+ autoStart?: boolean;
+ onDone?: (signedIn: boolean) => void;
+}) {
+ const { refreshInstances, refreshModels } = useStore();
+ const [auth, setAuth] = useState<DeviceSignInStatus | null>(null);
+ const [busy, setBusy] = useState(autoStart);
+ const started = useRef(false);
+ const [error, setError] = useState<string | null>(null);
+ const base = `/api/instances/${encodeURIComponent(instanceId)}/auth`;
+ const failed = t("engineSetup.engineBrowser.failed");
+
+ // The sign-in already succeeded: a failed catalog refresh must not read as a failed sign-in.
+ const refresh = async () => {
+ engineSignedIn("mistral_vibe", "browser");
+ try { await refreshInstances(); } catch {}
+ try { await refreshModels(instanceId); } catch {}
+ onDone?.(true);
+ };
+
+ useEffect(() => {
+ if (busy || auth?.phase !== "waiting" || !auth.flowId) return;
+ const controller = new AbortController();
+ const remaining = auth.expiresAt ? Date.parse(auth.expiresAt) - Date.now() : Number.NaN;
+ const expiryTimer = Number.isFinite(remaining)
+ ? window.setTimeout(() => { controller.abort(); setAuth(ended("expired")); setError(null); }, Math.max(0, remaining))
+ : null;
+ const timer = window.setTimeout(() => {
+ void api(`${base}/status?flowId=${encodeURIComponent(auth.flowId!)}`, { signal: controller.signal })
+ .then(async ({ auth: next }: { auth: DeviceSignInStatus }) => {
+ if (controller.signal.aborted) return;
+ setAuth(next);
+ setError(null);
+ if (next.phase === "succeeded") await refresh();
+ })
+ .catch((cause: unknown) => {
+ if (controller.signal.aborted) return;
+ if (deviceFlowUnavailable(cause)) {
+ setAuth(ended("failed"));
+ setError(null);
+ return;
+ }
+ setError(cause instanceof Error ? cause.message : failed);
+ setAuth({ ...auth });
+ });
+ }, 2000);
+ return () => {
+ window.clearTimeout(timer);
+ if (expiryTimer !== null) window.clearTimeout(expiryTimer);
+ controller.abort();
+ };
+ }, [auth, base, busy, failed, instanceId, refreshInstances, refreshModels, onDone]);
+
+ const start = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const { auth: next }: { auth: DeviceSignInStatus } = await api(`${base}/start`, { method: "POST" });
+ setAuth(next);
+ if (next.phase === "succeeded") await refresh();
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : failed);
+ } finally { setBusy(false); }
+ };
+
+ const cancel = async () => {
+ if (!auth?.flowId) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await api(`${base}/cancel`, { method: "POST", body: JSON.stringify({ flowId: auth.flowId }) });
+ setAuth({ phase: "cancelled", flowId: null, authorizationUrl: null, expiresAt: null });
+ onDone?.(false);
+ } catch (cause) {
+ if (deviceFlowUnavailable(cause)) setAuth(ended("failed"));
+ else setError(cause instanceof Error ? cause.message : failed);
+ } finally { setBusy(false); }
+ };
+
+ useEffect(() => {
+ if (!autoStart || started.current) return;
+ started.current = true;
+ void start();
+ }, [autoStart]);
+
+ const startLabel = busy ? t("engineSetup.engineBrowser.starting")
+ : auth || error ? t("engineSetup.device.tryAgain")
+ : t("engineSetup.engineBrowser.start");
+
+ if (auth && auth.phase !== "waiting") {
+ const label = auth.phase === "succeeded" ? t("engineSetup.engineBrowser.connected")
+ : auth.phase === "cancelled" ? t("engineSetup.engineBrowser.cancelled")
+ : auth.phase === "expired" ? t("engineSetup.engineBrowser.expired")
+ : auth.message || failed;
+ return (
+ <div data-engine-browser-sign-in className="mt-3 space-y-2">
+ <p role="status" className={auth.phase === "succeeded" ? "text-[12px] text-success" : "text-[12px] text-ink-secondary"}>{label}</p>
+ {auth.phase !== "succeeded" && (
+ <button type="button" disabled={busy} onClick={() => void start()}
+ className="flex w-full items-center justify-center gap-2 rounded-lg bg-accent px-3 py-2 text-[13px] font-semibold text-white hover:brightness-110 disabled:opacity-50">
+ <LogIn size={14} />
+ {startLabel}
+ </button>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="mt-3 space-y-2" data-engine-browser-sign-in>
+ {auth?.phase !== "succeeded" && (
+ <button type="button" disabled={busy} onClick={() => void start()}
+ className="flex w-full items-center justify-center gap-2 rounded-lg bg-accent px-3 py-2 text-[13px] font-semibold text-white hover:brightness-110 disabled:opacity-50">
+ {busy ? <Loader2 size={14} className="animate-spin" /> : <LogIn size={14} />}
+ {startLabel}
+ </button>
+ )}
+ {auth?.phase === "waiting" && (
+ <div className="space-y-2 rounded-lg border border-hairline/50 bg-app p-3">
+ <p role="status" className="flex items-center gap-1.5 text-[12px] text-ink-secondary">
+ <Loader2 size={12} className="animate-spin" /> {t("engineSetup.engineBrowser.waiting")}
+ </p>
+ {auth.expiresAt && Number.isFinite(Date.parse(auth.expiresAt)) && (
+ <p className="text-[11px] text-ink-secondary">{t("engineSetup.engineBrowser.expires", { time: new Date(auth.expiresAt).toLocaleTimeString(intlLocale(), { hour: "2-digit", minute: "2-digit" }) })}</p>
+ )}
+ <button type="button" disabled={busy} onClick={() => void cancel()}
+ className="w-full rounded-lg bg-control px-3 py-2 text-[12px] font-medium text-ink disabled:opacity-50">
+ {busy ? t("engineSetup.device.cancelling") : t("engineSetup.device.cancel")}
+ </button>
+ </div>
+ )}
+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/components/EngineSetup.tsx b/src/components/EngineSetup.tsx
index 1e35bf727b..e9c8356b16 100644
--- a/src/components/EngineSetup.tsx
+++ b/src/components/EngineSetup.tsx
@@ -6,6 +6,7 @@ import { t } from "@/lib/i18n";
import { engineDisplayName } from "@/lib/engine-name";
import { copyText } from "@/lib/copy-text";
import { DEVICE_SIGN_IN_COPY, DeviceSignIn, deviceSignInProvider } from "./DeviceSignIn";
+import { EngineBrowserSignIn } from "./EngineBrowserSignIn";
import { ClaudeSignIn } from "./ClaudeSignIn";
import { RefreshEngines } from "./EngineLibrary";
import { AppCopyNotice, AppCopySetup } from "./EngineAppCopy";
@@ -549,6 +550,7 @@ export function EngineSetup({
/** A Cloud's "not installed" reason only says to install it in a terminal or use Set CLI; the card says what to do instead. */
const cloudReasonHidden = cloudCantInstall || (cloudHome && !signInOnly && Boolean(install?.server) && instance.snapshot.notEngineCli !== true);
const deviceSignIn = signInOnly && instance.authentication?.method === "device-code";
+ const engineBrowserSignIn = signInOnly && instance.authentication?.method === "browser";
const browserSignIn = signInOnly && instance.authentication?.method === "browser-pkce";
const pasteSignIn = signInOnly && instance.authentication?.method === "paste-code";
const provider = deviceSignInProvider(instance.driverKind);
@@ -557,7 +559,9 @@ export function EngineSetup({
? t("engineSetup.signInTitle", { name: engineDisplayName(instance) })
: t("engineSetup.setupTitle", { name: engineDisplayName(instance) });
const description = descriptionOverride ?? (signInOnly
- ? browserSignIn
+ ? engineBrowserSignIn
+ ? t("engineSetup.engineBrowser.description")
+ : browserSignIn
? t("engineSetup.chatgpt.description")
: deviceSignIn
? t(DEVICE_SIGN_IN_COPY[provider].description)
@@ -608,7 +612,7 @@ export function EngineSetup({
}
// The app's own copy is out of reach of the person's terminal, so its sign-in is finished here.
- if (signInOnly && install.appCopy && !deviceSignIn && !browserSignIn && !pasteSignIn) {
+ if (signInOnly && install.appCopy && !deviceSignIn && !engineBrowserSignIn && !pasteSignIn) {
return <AppCopySetup instance={instance} className={className} unframed={unframed} />;
}
@@ -635,7 +639,9 @@ export function EngineSetup({
</p>
))}
- {deviceSignIn || browserSignIn ? (
+ {engineBrowserSignIn ? (
+ <EngineBrowserSignIn key={instance.instanceId} instanceId={instance.instanceId} />
+ ) : deviceSignIn || browserSignIn ? (
<>
<DeviceSignIn key={instance.instanceId} instanceId={instance.instanceId} browserPkce={browserSignIn} provider={provider} />
{deviceSignIn && provider !== "codex" && signInCommand && serverTerminal(cloudHome) && (
diff --git a/src/lib/analytics-allowlist.ts b/src/lib/analytics-allowlist.ts
index e6fe6d0414..5b9b8f98d0 100644
--- a/src/lib/analytics-allowlist.ts
+++ b/src/lib/analytics-allowlist.ts
@@ -68,7 +68,7 @@ export const KEY_VIA = ["settings", "computer_panel", "chat_request", "apps", "m
export type KeyVia = (typeof KEY_VIA)[number];
export const KEY_RESULT = ["ok", "rejected", "unverified", "error"] as const;
export type KeyResult = (typeof KEY_RESULT)[number];
-export const SIGN_IN_ENGINE = ["claude", "codex", "grok", "kimi", "cursor"] as const;
+export const SIGN_IN_ENGINE = ["claude", "codex", "grok", "kimi", "cursor", "mistral_vibe"] as const;
export const SIGN_IN_METHOD = ["code", "device_code", "browser"] as const;
export type SignInMethod = (typeof SIGN_IN_METHOD)[number];
export const BOT_SOURCE = ["blank", "template", "preset"] as const;
diff --git a/src/locales/en.json b/src/locales/en.json
index 93c5e67a71..1e8a739851 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -6053,8 +6053,16 @@
"engineSetup.chatgpt.manageUsage": "Manage usage",
"engineSetup.chatgpt.welcome": "You’re using your ChatGPT plan",
"engineSetup.chatgpt.welcomeBody": "Eligible AI requests in {app} use your ChatGPT plan. Manage usage and access in ChatGPT settings. Your ChatGPT plan is separate from MausBot Cloud.",
- "engineSetup.device.start": "Connect ChatGPT",
- "engineSetup.device.starting": "Getting your sign-in code…",
+ "engineSetup.engineBrowser.description": "Sign in to {name} in the browser that just opened. OpenMausBot keeps the sign-in open until you finish there.",
+ "engineSetup.engineBrowser.start": "Sign in to Mistral",
+ "engineSetup.engineBrowser.starting": "Opening the Mistral sign-in…",
+ "engineSetup.engineBrowser.waiting": "Finish the sign-in in the browser that opened…",
+ "engineSetup.engineBrowser.expires": "The sign-in window closes at {time}.",
+ "engineSetup.engineBrowser.connected": "Connected to Mistral. Your models are being refreshed.",
+ "engineSetup.engineBrowser.failed": "The Mistral sign-in did not finish. Start it again to retry.",
+ "engineSetup.engineBrowser.cancelled": "Sign-in cancelled.",
+ "engineSetup.engineBrowser.expired": "The Mistral sign-in window expired. Start it again to retry.",
+ "engineSetup.device.start": "Connect ChatGPT", "engineSetup.device.starting": "Getting your sign-in code…",
"engineSetup.device.enterCode": "Enter this one-time code on OpenAI's sign-in page:",
"engineSetup.device.copyCode": "Copy sign-in code",
"engineSetup.device.openChatGPT": "Open ChatGPT sign-in",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index b1de15c1f0..14c6b9b554 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -5731,6 +5731,15 @@
"engineSetup.chatgpt.manageUsage": "Gerenciar uso",
"engineSetup.chatgpt.welcome": "Você está usando seu plano do ChatGPT",
"engineSetup.chatgpt.welcomeBody": "No app {app}, os pedidos de IA cobertos pelo seu plano do ChatGPT usam esse plano. Gerencie o uso e o acesso nas configurações do ChatGPT. Seu plano do ChatGPT é separado do MausBot Cloud.",
+ "engineSetup.engineBrowser.description": "Entre no {name} pelo navegador que acabou de abrir. O OpenMausBot mantém o login aberto até você terminar lá.",
+ "engineSetup.engineBrowser.start": "Entrar no Mistral",
+ "engineSetup.engineBrowser.starting": "Abrindo o login do Mistral…",
+ "engineSetup.engineBrowser.waiting": "Termine o login no navegador que foi aberto…",
+ "engineSetup.engineBrowser.expires": "A janela de login se encerra às {time}.",
+ "engineSetup.engineBrowser.connected": "Conectado ao Mistral. Os seus modelos estão sendo atualizados.",
+ "engineSetup.engineBrowser.failed": "O login do Mistral não foi concluído. Comece de novo para tentar outra vez.",
+ "engineSetup.engineBrowser.cancelled": "Login cancelado.",
+ "engineSetup.engineBrowser.expired": "A janela de login do Mistral expirou. Comece de novo para tentar outra vez.",
"engineSetup.device.start": "Conectar o ChatGPT",
"engineSetup.device.starting": "Obtendo seu código de login…",
"engineSetup.device.enterCode": "Digite este código de uso único na página de login da OpenAI:",