Skip to content

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

Move back: lapse only on My Cloud's leaving hold; first arrivals made held

milind-sonia756921593f8
diff --git a/server/bot-moves.test.ts b/server/bot-moves.test.ts
index fdaf89184d..4d027e409e 100644
--- a/server/bot-moves.test.ts
+++ b/server/bot-moves.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { assertBotHere, botMoveRefusal, COMPUTER_TEAM_PREFIX, createBotMoves, MY_CLOUD_TEAM, personalTeam } from "./bot-moves.ts";
+import { arrivalMark, assertBotHere, botMoveRefusal, COMPUTER_TEAM_PREFIX, createBotMoves, MY_CLOUD_TEAM, personalTeam } from "./bot-moves.ts";
import { arrivalsFile } from "./move-back.ts";
import type { BotRecord } from "./store.ts";
import { WaitManager } from "./waits.ts";
@@ -160,13 +160,15 @@ describe("a bot coming back from My Cloud to this computer, and going there agai
const MINUTE = 60_000;
/** One place's server: a stub of Scout (or Scout live), its routines, webhook and app event, the MCP servers it has. */
- function place({ computer = true, scout = "stub" as "stub" | "live" | "none", createdAt = 0, busy = false } = {}) {
+ function place({ computer = true, scout = "stub" as "stub" | "live" | "arriving" | "none", createdAt = 0, busy = false } = {}) {
const dir = mkdtempSync(join(tmpdir(), "omb-move-back-"));
dirs.push(dir);
let clock = 10 * MINUTE;
const bots = new Map<string, Record<string, unknown>>();
if (scout === "stub") bots.set("scout", { id: "scout", name: "Scout", createdAt, hidden: true, mcpServers: ["notes"], movedTo: { team: computer ? MY_CLOUD : LAPTOP, state: "moved", at: 1, held: ["routine:brief"] } });
if (scout === "live") bots.set("scout", { id: "scout", name: "Scout", createdAt, mcpServers: ["notes"] });
+ // Made by the move, already held (POST /api/bots `arriving`).
+ if (scout === "arriving") bots.set("scout", { id: "scout", name: "Scout", createdAt, hidden: true, mcpServers: ["notes"], movedTo: arrivalMark(computer ? MY_CLOUD : LAPTOP, clock) });
bots.set("pip", { id: "pip", name: "Pip", createdAt: 0 });
const routines = [{ id: "brief", name: "Morning brief", botId: "scout", enabled: false }, { id: "weekly", name: "Weekly", botId: "scout", enabled: false }];
const hooks = [{ id: "orders", name: "Orders", botId: "scout", enabled: false }];
@@ -203,15 +205,15 @@ describe("a bot coming back from My Cloud to this computer, and going there agai
expect(routines.every((routine) => !routine.enabled), "the bot lives on My Cloud: nothing of it runs here").toBe(true);
});
- it("refuses a live bot with the same id, and only takes a bot the move just made as its first arrival", async () => {
- const here = place({ scout: "live", createdAt: 0 });
- here.tick(60 * MINUTE);
+ it("refuses a live bot with the same id, however new; a first arrival is made held, and stays held or a line however long a try takes", async () => {
+ const here = place({ scout: "live", createdAt: 10 * MINUTE });
expect(await here.moves.hold("scout", MY_CLOUD, { back: true })).toEqual({ refused: "Scout is already here.", here: true });
- expect(await here.moves.hold("scout", MY_CLOUD, { back: true, arrival: true }), "an older bot is the person's own").toEqual({ refused: "Scout is already here.", here: true });
- expect(live(scoutOf(here.bots))).toBe(true);
- const fresh = place({ scout: "live", createdAt: 9 * MINUTE });
- expect(await fresh.moves.hold("scout", MY_CLOUD, { back: true, arrival: true })).toMatchObject({ movedTo: { back: true, arrival: true, had: { mcp: [] } } });
- expect(scoutOf(fresh.bots).hidden).toBe(true);
+ expect(live(scoutOf(here.bots)), "the person's own bot is never hidden").toBe(true);
+ const fresh = place({ scout: "arriving" });
+ expect(live(scoutOf(fresh.bots)), "never live here, not even before the move holds it").toBe(false);
+ fresh.tick(3 * 60 * MINUTE);
+ expect(await fresh.moves.hold("scout", MY_CLOUD, { back: true }), "the app quit after making it: a later try takes it").toMatchObject({ movedTo: { back: true, arrival: true, had: { mcp: [] } } });
+ expect(await fresh.moves.sweep(), "never lapses").toEqual([]);
// Stopped, a first arrival is the line of where it lives, never deleted and never live here.
expect(await fresh.moves.release("scout")).toEqual({ released: true });
expect(scoutOf(fresh.bots)).toMatchObject({ hidden: true, movedTo: { team: MY_CLOUD, state: "moved" } });
@@ -258,9 +260,8 @@ describe("a bot coming back from My Cloud to this computer, and going there agai
await stub.moves.hold("scout", MY_CLOUD, { back: true });
expect((await stub.moves.arrived("scout", MY_CLOUD, []) as { arrived: { offHere: { mcpServers: string[] } } }).arrived.offHere.mcpServers).toEqual([]);
expect(scoutOf(stub.bots).mcpServers).toBeUndefined();
- const fresh = place({ scout: "live", createdAt: 10 * MINUTE });
+ const fresh = place({ scout: "arriving" });
delete scoutOf(fresh.bots).mcpServers;
- await fresh.moves.hold("scout", MY_CLOUD, { back: true, arrival: true });
expect((await fresh.moves.arrived("scout", MY_CLOUD, []) as { arrived: { offHere: { mcpServers: string[] } } }).arrived.offHere.mcpServers).toEqual(["notes", "shell"]);
expect(scoutOf(fresh.bots).mcpServers).toEqual(["docs"]);
});
@@ -309,11 +310,36 @@ describe("a bot coming back from My Cloud to this computer, and going there agai
expect(await moved.moves.sweep()).toEqual([]);
expect(scoutOf(moved.bots).movedTo.state).toBe("moved");
+ });
+
+ it("only My Cloud's hold of a bot leaving it lapses: a computer's hold and a returning hold never do, so a late switch never finds two copies or none", async () => {
+ // Second trip to My Cloud: the laptop holds its bot, My Cloud makes it live, then the lid closes for an hour.
+ const laptop = place({ scout: "live" });
+ laptop.routines[0]!.enabled = true;
+ expect((await laptop.moves.hold("scout", MY_CLOUD, { lapse: true }) as { movedTo: object }).movedTo).not.toHaveProperty("lapseAt");
+ laptop.tick(60 * MINUTE);
+ expect([await laptop.moves.sweep(), laptop.routines[0]!.enabled, live(scoutOf(laptop.bots))]).toEqual([[], false, false]);
+ expect(laptop.moves.moved("scout", MY_CLOUD), "the late switch still lands").toMatchObject({ movedTo: { state: "moved" } });
+ // Way back: My Cloud switched, then the lid closed before this computer's arrival.
const back = place();
- await back.moves.hold("scout", MY_CLOUD, { back: true, lapse: true });
- back.tick(31 * MINUTE);
- expect(await back.moves.sweep()).toEqual(["scout"]);
- expect(scoutOf(back.bots)).toMatchObject({ hidden: true, movedTo: { state: "moved" } });
+ expect((await back.moves.hold("scout", MY_CLOUD, { back: true, lapse: true }) as { movedTo: object }).movedTo).not.toHaveProperty("lapseAt");
+ back.tick(60 * MINUTE);
+ expect(await back.moves.sweep()).toEqual([]);
+ expect(await back.moves.arrived("scout", MY_CLOUD, []), "the arrival still lands").toMatchObject({ arrived: { place: "computer" } });
+ expect(live(scoutOf(back.bots))).toBe(true);
+ });
+
+ it("when My Cloud ends after a stopped try to bring the bot back, the line comes back without command servers it did not use here", async () => {
+ const { moves, bots } = place();
+ await moves.hold("scout", MY_CLOUD, { back: true });
+ scoutOf(bots).mcpServers = ["notes", "shell", "docs"];
+ await moves.release("scout");
+ expect(moves.back("scout")).toEqual({ released: true });
+ expect(scoutOf(bots)).toMatchObject({ hidden: false, mcpServers: ["notes", "docs"] });
+ expect(scoutOf(bots).movedTo).toBeUndefined();
+ const plain = place();
+ expect(plain.moves.back("scout")).toEqual({ released: true });
+ expect(scoutOf(plain.bots).mcpServers, "a line no try touched comes back as it went").toEqual(["notes"]);
});
it("remembers what the stub used here across a stopped try, so command servers new here still arrive off after an undo", async () => {
@@ -323,14 +349,13 @@ describe("a bot coming back from My Cloud to this computer, and going there agai
await moves.release("scout");
expect((await moves.hold("scout", MY_CLOUD, { back: true }) as { movedTo: object }).movedTo).toMatchObject({ had: { mcp: ["notes"] } });
expect((await moves.arrived("scout", MY_CLOUD, []) as { arrived: { offHere: { mcpServers: string[] } } }).arrived.offHere.mcpServers).toEqual(["shell"]);
- const fresh = place({ scout: "live", createdAt: 10 * MINUTE });
- await fresh.moves.hold("scout", MY_CLOUD, { back: true, arrival: true });
+ const fresh = place({ scout: "arriving" });
scoutOf(fresh.bots).mcpServers = ["shell"];
await fresh.moves.release("scout");
expect((await fresh.moves.hold("scout", MY_CLOUD, { back: true }) as { movedTo: object }).movedTo, "a first arrival had none here").toMatchObject({ had: { mcp: [] } });
});
- it("a hold past its time no longer holds before the sweep has run: no switch, no arrival, and holding again is a new hold", async () => {
+ it("a hold past its time no longer holds before the sweep has run: no switch, and holding again is a new hold", async () => {
const cloud = place({ computer: false, scout: "live" });
cloud.routines[0]!.enabled = true;
const first = await cloud.moves.hold("scout", LAPTOP, { lapse: true }) as { movedTo: { at: number; lapseAt: number } };
@@ -341,11 +366,6 @@ describe("a bot coming back from My Cloud to this computer, and going there agai
const again = await cloud.moves.hold("scout", LAPTOP, { lapse: true }) as { movedTo: { at: number } };
expect(again.movedTo.at, "a new hold, so the move copies again what the bot did meanwhile").toBe(41 * MINUTE);
expect(cloud.routines[0]!.enabled, "switched back on and off again by the new hold").toBe(false);
- const here = place();
- await here.moves.hold("scout", MY_CLOUD, { back: true, lapse: true });
- here.tick(31 * MINUTE);
- expect(await here.moves.arrived("scout", MY_CLOUD, [])).toEqual({ refused: "This bot is not coming here from there." });
- expect(live(scoutOf(here.bots))).toBe(false);
expect(place().moves.nextLapseAt()).toBeNull();
});
@@ -355,6 +375,69 @@ describe("a bot coming back from My Cloud to this computer, and going there agai
expect(scoutOf(cloud.bots).movedTo).toBeUndefined();
});
+ // The invariant (bot-moves.ts, top): in any order of the steps a move runs, lapses, crashes and stopped tries, the bot is
+ // never live in two places; it is live in none only while a move holds it (paused for the move, never between moves);
+ // and a try after all of it ends with it live where it went. The move is played as slice B will run it, both ways.
+ it("the invariant: one live copy at every point of any sequence of steps, lapses, crashes and stopped tries, both ways", async () => {
+ const random = (seed: number) => () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t ^= t + Math.imul(t ^ (t >>> 7), 61 | t); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
+ for (let seed = 1; seed <= 150; seed++) {
+ const next = random(seed);
+ const cloud = place({ computer: false, scout: "live" }), laptop = place({ scout: "stub" });
+ cloud.routines[0]!.enabled = true;
+ let onCloud = cloud.moves, onLaptop = laptop.moves;
+ const journal = { toLaptop: true, phase: "begin" as "begin" | "freeze" | "copy" | "check" | "switch1" | "switch2", at: 0, on: [] as string[], trips: 0 };
+ const sides = () => journal.toLaptop
+ ? { from: onCloud, to: onLaptop, fromTeam: LAPTOP, toTeam: MY_CLOUD, fromBots: cloud.bots, toBots: laptop.bots }
+ : { from: onLaptop, to: onCloud, fromTeam: MY_CLOUD, toTeam: LAPTOP, fromBots: laptop.bots, toBots: cloud.bots };
+ const holdFrom = async () => {
+ const answer = await sides().from.hold("scout", sides().fromTeam, { lapse: true }) as { movedTo: { at: number; held?: string[] } };
+ expect(answer.movedTo, `seed ${seed}`).toBeTruthy();
+ const fresh = answer.movedTo.at !== journal.at;
+ Object.assign(journal, { at: answer.movedTo.at, on: answer.movedTo.held ?? [] });
+ return fresh;
+ };
+ const step = async () => {
+ const { from, to, fromTeam, toTeam, fromBots, toBots } = sides();
+ if (journal.phase === "begin") { expect(await to.hold("scout", toTeam, { back: true }), `seed ${seed}`).toHaveProperty("movedTo"); journal.phase = "freeze"; }
+ else if (journal.phase === "freeze") { await holdFrom(); journal.phase = "copy"; }
+ else if (journal.phase === "copy") { scoutOf(toBots).title = `copied ${String(scoutOf(fromBots).title ?? "")}`; journal.phase = "check"; }
+ // The renewal a move makes before it switches: a new `at` means the bot worked meanwhile, so it copies again.
+ else if (journal.phase === "check") journal.phase = await holdFrom() ? "copy" : "switch1";
+ else if (journal.phase === "switch1") {
+ // To a computer My Cloud lets go first; to My Cloud, My Cloud takes it first.
+ const first = journal.toLaptop ? from.moved("scout", fromTeam) : await to.arrived("scout", toTeam, journal.on);
+ if ("refused" in first) { expect(journal.toLaptop && !from.state("scout")!.holding, `seed ${seed}: ${first.refused}`).toBe(true); journal.phase = "freeze"; }
+ else journal.phase = "switch2";
+ } else {
+ const second = journal.toLaptop ? await to.arrived("scout", toTeam, journal.on) : from.moved("scout", fromTeam);
+ expect(second, `seed ${seed}`).not.toHaveProperty("refused");
+ Object.assign(journal, { toLaptop: !journal.toLaptop, phase: "begin", at: 0, on: [], trips: journal.trips + 1 });
+ }
+ };
+ const check = (event: string) => {
+ const count = [cloud.bots, laptop.bots].filter((bots) => live(scoutOf(bots))).length;
+ // Never two; none only while a move holds it (paused for the move), never between moves.
+ expect(count <= 1 && (count === 1 || journal.phase !== "begin"), `seed ${seed} after ${event}: ${count} live, ${JSON.stringify(journal)}`).toBe(true);
+ };
+ for (let event = 0; event < 40; event++) {
+ const roll = next();
+ if (roll < 0.6) { await step(); check("a step"); }
+ else if (roll < 0.75) { cloud.tick(31 * MINUTE); laptop.tick(31 * MINUTE); await onCloud.sweep(); await onLaptop.sweep(); check("a lapse"); }
+ else if (roll < 0.87) { onCloud = cloud.again(); onLaptop = laptop.again(); check("a crash"); }
+ else if (!["switch1", "switch2"].includes(journal.phase)) {
+ // A try that stops before the switch lets go of both holds and begins again.
+ await sides().from.release("scout"); await sides().to.release("scout");
+ journal.phase = "begin"; check("a stopped try");
+ }
+ }
+ // Whatever happened, the next try finishes: the bot is live where it was going, and only there.
+ const trips = journal.trips, goingToLaptop = journal.toLaptop;
+ for (let guard = 0; journal.trips === trips && guard < 12; guard++) { await step(); check("the last try"); }
+ expect(journal.trips, `seed ${seed}`).toBe(trips + 1);
+ expect([live(scoutOf(cloud.bots)), live(scoutOf(laptop.bots))], `seed ${seed}`).toEqual(goingToLaptop ? [false, true] : [true, false]);
+ }
+ });
+
it("a computer team is a place of the person's own; a team's own id never is", () => {
expect([personalTeam(MY_CLOUD_TEAM), personalTeam("computer-inst-1"), personalTeam("computer-"), personalTeam("0b6f8e52-9d6c-4f0e-8f43-2f0c3cf8c1d2")]).toEqual([true, true, false, false]);
});
diff --git a/server/bot-moves.ts b/server/bot-moves.ts
index 6b7934877d..156e62c02b 100644
--- a/server/bot-moves.ts
+++ b/server/bot-moves.ts
@@ -12,7 +12,15 @@
// (move-back.ts keeps what was done, to be told). A bot is never live in two places and nothing of it is deleted.
//
// A hold that asks to lapse (`lapse`) lets the bot go on by itself unless it is held again within HOLD_LAPSE_MS: the
-// computer that runs a move may sleep half-way, and the bot then goes on working where it is.
+// computer that runs a move may sleep half-way, and the bot then goes on working where it is. Only My Cloud's own hold of
+// a bot leaving it lapses: My Cloud is the side that switches first on the way to a computer, so before its switch the bot
+// is live there and nowhere else. A computer's hold, and a returning hold anywhere, never lapses: by the time it would,
+// the other side may already have switched, and letting go then would make two live copies, or none.
+//
+// The invariant, at every point of any order of holds, copies, switches, arrivals, lapses, crashes and retries the two
+// sides can see: the bot is never live in two places. It is live in none only while a move holds it: paused at its place
+// until the move goes on or (My Cloud's hold) lapses, or between the two switch steps, from where the move only goes
+// forward. Between moves it is live in exactly one, and a try always finishes (bot-moves.test.ts, "the invariant").
import type { BotMovedTo } from "../shared/wire.ts";
import type { AppTriggerManager } from "./app-triggers.ts";
import type { Arrivals, ArrivedFacts, MovedAutomation, StaysOnCloud } from "./move-back.ts";
@@ -30,8 +38,6 @@ export const COMPUTER_TEAM_PREFIX = "computer-";
export const personalTeam = (id: string) => id === MY_CLOUD_TEAM || (id.startsWith(COMPUTER_TEAM_PREFIX) && id.length > COMPUTER_TEAM_PREFIX.length);
/** How long a hold that asked to lapse holds without being asked again. */
export const HOLD_LAPSE_MS = 30 * 60_000;
-/** A first arrival is held as one only while it is this new: the move made it moments before. */
-export const ARRIVAL_WINDOW_MS = 10 * 60_000;
export interface BotMovesDeps {
store: { bot(id: string): BotRecord | null | undefined; patchBot(id: string, patch: Partial<BotRecord>): BotRecord | null;
@@ -66,13 +72,17 @@ type Held = BotMovedTo & {
lapseAt?: number;
/** The bot is coming back here: hidden, no turns, compared by the move. */
back?: true;
- /** A first arrival this move made here: stopped, it is the line of where it lives. */
+ /** A first arrival, made here already held (arrivalMark): stopped, it is the line of where it lives. */
arrival?: true;
/** What this place had of it before it came back: the MCP servers it used here (null: every one). */
had?: { mcp: string[] | null };
/** The archived switch the move sent while it came back, set once it arrived. */
archived?: boolean;
};
+/** A first arrival's hold, set as the move makes the bot here (POST /api/bots `arriving`): hidden and held from its first
+ * write, with nothing here before it. */
+export function arrivalMark(team: Team, at: number): Held { return { team, state: "moving", at, back: true, arrival: true, had: { mcp: [] } }; }
+
type HoldAnswer = { movedTo: Held } | { busy: string } | { refused: string; here?: true };
/** Why this bot takes no turn here, or null. */
@@ -126,49 +136,46 @@ export function createBotMoves(deps: BotMovesDeps) {
};
/** The bot comes back here: its line is held as returning; a bot live here with this id is not taken over. */
- function holdReturning(bot: BotRecord, held: Held | undefined, team: Team, lapse: boolean, arrival: boolean): HoldAnswer {
- if (held?.back) {
- if (held.team.id !== team.id) return { refused: botMoveRefusal(bot)! };
- const { lapseAt: _lapse, ...kept } = held;
- const next: Held = { ...kept, ...lapsing(lapse) };
- set(bot.id, next);
- return { movedTo: next };
- }
+ function holdReturning(bot: BotRecord, held: Held | undefined, team: Team): HoldAnswer {
+ if (held?.back) return held.team.id === team.id ? { movedTo: held } : { refused: botMoveRefusal(bot)! };
if (held?.state === "moved") {
if (held.team.id !== team.id) return { refused: botMoveRefusal(bot)! };
const { lapseAt: _lapse, ...kept } = held;
- const next: Held = { ...kept, state: "moving", at: now(), back: true, had: held.had ?? { mcp: bot.mcpServers ? [...bot.mcpServers] : null }, ...lapsing(lapse) };
+ const next: Held = { ...kept, state: "moving", at: now(), back: true, had: held.had ?? { mcp: bot.mcpServers ? [...bot.mcpServers] : null } };
set(bot.id, next, { hidden: true });
return { movedTo: next };
}
if (held) return { refused: botMoveRefusal(bot)! };
- // Security: only a bot the move made here moments ago is taken as its arrival; any other bot with this id is the
- // person's own, which the move never hides.
- const fresh = arrival && Number.isFinite(bot.createdAt) && now() - bot.createdAt >= 0 && now() - bot.createdAt <= ARRIVAL_WINDOW_MS;
- if (!fresh) return { refused: `${bot.name} is already here.`, here: true };
- const next: Held = { team, state: "moving", at: now(), back: true, arrival: true, had: { mcp: [] }, ...lapsing(lapse) };
- set(bot.id, next, { hidden: true });
- cancelWaits(bot.id);
- return { movedTo: next };
+ // A bot live here with this id is the person's own: the move never hides it. A first arrival is made already held
+ // (arrivalMark, by POST /api/bots over the move's own caller), so it is never live here first.
+ return { refused: `${bot.name} is already here.`, here: true };
}
/** The automations of this bot, of one kind, by id and name. */
const named = (list: ReadonlyArray<{ id: string; name: string; botId: string }> | undefined, botId: string, keys: Set<string>, kind: string): MovedAutomation[] =>
(list ?? []).filter((entry) => entry.botId === botId && keys.has(`${kind}:${entry.id}`)).map((entry) => ({ id: entry.id, name: entry.name }));
+ /** The command MCP servers the bot would use here that it did not use here before (`had`; none known: none new). */
+ function newCommandServers(bot: BotRecord, had: Held["had"]): string[] {
+ if (!deps.mcp || !had) return [];
+ const here = deps.mcp(bot.id);
+ const uses = (list: readonly string[] | null) => (list === null ? here.command : here.command.filter((name) => list.includes(name)));
+ const before = new Set(uses(had.mcp));
+ return uses(bot.mcpServers ?? null).filter((name) => !before.has(name));
+ }
+ const switchOffServers = (bot: BotRecord, off: readonly string[]) => {
+ if (!off.length) return;
+ const gone = new Set(off);
+ deps.store.patchBot(bot.id, { mcpServers: (bot.mcpServers ?? deps.mcp?.(bot.id).all ?? []).filter((name) => !gone.has(name)) });
+ };
+
/** What arriving does here, decided once and kept before any of it is done. */
function arrivalFacts(bot: BotRecord, held: Held, on: readonly string[]): ArrivedFacts {
const keys = new Set(on);
const routines = named(deps.routines()?.listRoutines(), bot.id, keys, "routine");
const webhooks = named(deps.webhooks()?.list(), bot.id, keys, "webhook");
const appEvents = named(deps.appEvents()?.list(), bot.id, keys, "app-event");
- let mcpServers: string[] = [];
- if (deps.computer && deps.mcp) {
- const here = deps.mcp(bot.id);
- const uses = (list: readonly string[] | null) => (list === null ? here.command : here.command.filter((name) => list.includes(name)));
- const before = new Set(uses(held.had?.mcp ?? null));
- mcpServers = uses(bot.mcpServers ?? null).filter((name) => !before.has(name));
- }
+ const mcpServers = deps.computer ? newCommandServers(bot, held.had) : [];
const computer = deps.computer === true;
return { v: 1, from: held.team, hold: held.at, at: now(), place: computer ? "computer" : "cloud",
on: { routines, webhooks: computer ? [] : webhooks, appEvents: computer ? [] : appEvents },
@@ -179,14 +186,19 @@ export function createBotMoves(deps: BotMovesDeps) {
/** The bot stops here for the move: no turns, its automations off and its waits cancelled. Busy while it answers; a
* bot already moved stays moved. Holding it again keeps what the first hold switched off, and renews a lapsing hold.
* `back`: it is coming back here instead (holdReturning). */
- async hold(botId: string, team: Team, { lapse = false, back = false, arrival = false }: { lapse?: boolean; back?: boolean; arrival?: boolean } = {}): Promise<HoldAnswer> {
+ //
+ // For the engine that runs a move (slice B): holding again after a lapse is not a renewal but a new hold, with a new
+ // `at`, and the bot may have worked in between; whenever the `at` it gets back changes, the move copies again before
+ // it switches. `lapse` is honoured only on My Cloud's hold of a bot leaving it (see the top of this file).
+ async hold(botId: string, team: Team, { lapse = false, back = false }: { lapse?: boolean; back?: boolean } = {}): Promise<HoldAnswer> {
const bot = deps.store.bot(botId);
if (!bot) return { refused: "This bot is no longer here." };
if (bot.defaultBot) return { refused: `${bot.name} stays here: everyone on a team gets their own.` };
// Past its time, a hold is let go of first: holding again is a new hold, with a new `at`.
if (lapsed(movedOf(bot)) && ready(movedOf(bot)!.held ?? [])) await moves.release(botId);
const held = movedOf(deps.store.bot(botId) ?? bot);
- if (back) return holdReturning(deps.store.bot(botId) ?? bot, held, team, lapse, arrival);
+ if (back) return holdReturning(deps.store.bot(botId) ?? bot, held, team);
+ lapse &&= !deps.computer;
if (held?.back) return { refused: botMoveRefusal(bot)! };
if (held?.state === "moved") return held.team.id === team.id ? { movedTo: held } : { refused: botMoveRefusal(bot)! };
if (held && held.team.id !== team.id) return { refused: botMoveRefusal(bot)! };
@@ -249,10 +261,7 @@ export function createBotMoves(deps: BotMovesDeps) {
// Kept before anything is done: a server stopped half-way does the rest, the same way, when asked again.
const facts = kept && kept.from.id === team.id && kept.hold === held.at ? kept : arrivalFacts(bot, held, on);
if (facts !== kept) deps.arrivals?.put(botId, facts);
- if (facts.offHere.mcpServers.length) {
- const off = new Set(facts.offHere.mcpServers);
- deps.store.patchBot(botId, { mcpServers: (bot.mcpServers ?? deps.mcp?.(botId).all ?? []).filter((name) => !off.has(name)) });
- }
+ switchOffServers(bot, facts.offHere.mcpServers);
for (const routine of facts.on.routines) await switchTo(`routine:${routine.id}`, true);
for (const hook of facts.on.webhooks) await switchTo(`webhook:${hook.id}`, true);
for (const trigger of facts.on.appEvents) await switchTo(`app-event:${trigger.id}`, true);
@@ -265,6 +274,9 @@ export function createBotMoves(deps: BotMovesDeps) {
const held = movedOf(bot);
if (!bot || !held) return { released: true };
if (!personalTeam(held.team.id)) return { refused: botMoveRefusal(bot)! };
+ // A try to bring it back that stopped left the newer side's fields on its line: command servers it did not use here
+ // before stay off.
+ if (deps.computer) switchOffServers(bot, newCommandServers(bot, held.had));
set(botId, undefined, { hidden: false });
return { released: true };
},
diff --git a/server/index.ts b/server/index.ts
index c60e02c974..fe1018f18e 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -11975,7 +11975,7 @@ ROUTES.push(createBotCreateRoutes({
hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED, newBotComputer: (selection) => newBotWorksOn({ desktopApp: DESKTOP_MANAGED && !CLOUD_HOME && !HOSTED_WORKSPACE && desktopComputer.connection() !== null, platform: process.platform, providerSupportsLocal: registry.get(selection.instanceId)?.adapter.capabilities.localComputerMcp === true }),
maxWorkspaceBots: MAX_WORKSPACE_BOTS, paused: (botId) => starterAwake.isPaused(botId), cloudOwnerKey: CLOUD_OWNER_KEY,
hostedModels, cloudRoutineAuthors,
- routines: () => routines,
+ routines: () => routines, movesIn: (auth) => Boolean(botMoves) && !teamMoveIn && Boolean(cloudSendOwner(auth)),
storedAvatarExists, defaultSelection, checkedModelSelection, cloudOwnerSession, wireBot, team: CLOUD_TEAM && teamOwners.people ? { name: CLOUD_TEAM.name, people: teamOwners.people } : null,
personaliseSetupCard: (bot) => setupSuggestions.personalise(bot.id), chiefChanged: (changed) => chiefRooms.moved(changed),
}), createTeamOwnerRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, presence: teamPresence.of, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), sees: (auth, botId) => visibleTo(viewerFor(auth)).bot(botId), publicBot,
diff --git a/server/move-back.e2e.test.ts b/server/move-back.e2e.test.ts
index 3b9465134a..8ae41547ad 100644
--- a/server/move-back.e2e.test.ts
+++ b/server/move-back.e2e.test.ts
@@ -171,7 +171,9 @@ it("goes to My Cloud a second time: its line there comes back to life instead of
await expect.poll(async () => !(await botOn(fx.local, rover.id) as Bot & { busy?: boolean })?.busy, { timeout: 60_000, interval: 100 }).toBe(true);
expect(await move(fx.onCloud, rover.id, { state: "returning", team: LAPTOP })).toMatchObject({ status: 200, body: { movedTo: { back: true } } });
expect(parseSendSummary((await fx.onCloud("GET", "/api/cloud-send?move=1")).body)?.items.find((item) => item.key === `bot:${rover.id}`)).toMatchObject({ returning: true });
+ // This computer's hold never lapses: My Cloud takes the bot first on this way, so letting go here later would make two.
const held = await move(fx.local, rover.id, { state: "moving", team: MY_CLOUD, lapse: true });
+ expect(held.body.movedTo, "a lapse asked for here is not taken").not.toHaveProperty("lapseAt");
expect(held.status, JSON.stringify(held.body)).toBe(200);
const on = held.body.movedTo.held as string[];
const arrived = await move(fx.onCloud, rover.id, { state: "arrived", team: LAPTOP, on });
@@ -187,15 +189,22 @@ it("a bot born on My Cloud arrives here held from its first write; a stopped fir
const mine = (await fx.local("POST", "/api/bots", { name: "Mine", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot as Bot;
expect(await move(fx.local, mine.id, { state: "returning", team: MY_CLOUD }), "a live bot of the same id here").toMatchObject({ status: 409, body: { here: true } });
expect(live(await botOn(fx.local, mine.id))).toBe(true);
- const made = await fx.local("POST", "/api/bots", { id: nova.id, threadId: nova.threadId, name: "Nova", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } });
+ const creation = { id: nova.id, threadId: nova.threadId, name: "Nova", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" }, arriving: { team: MY_CLOUD } };
+ const page = await fetch(`${fx.desktopBase}/api/bots`, { method: "POST", body: JSON.stringify(creation), headers: { "content-type": "application/json",
+ "x-openmausbot-desktop-owner": fx.ownerCapability, origin: fx.desktopBase, "sec-fetch-site": "same-origin", "sec-fetch-dest": "empty" } });
+ expect(page.status, "only the move's own caller makes an arriving bot").toBe(403);
+ expect(await botOn(fx.local, nova.id)).toBeUndefined();
+ // Made already held: never live here, not even if the app quits before the move holds it.
+ const made = await fx.local("POST", "/api/bots", creation);
expect(made.status, JSON.stringify(made.body)).toBe(201);
- const arriving = await move(fx.local, nova.id, { state: "returning", team: MY_CLOUD, arrival: true });
- expect(arriving.status, JSON.stringify(arriving.body)).toBe(200);
expect(await botOn(fx.local, nova.id)).toMatchObject({ hidden: true, movedTo: { back: true, arrival: true } });
await liveOnlyOn(nova.id, "cloud");
+ await fx.relaunch({ kill: true });
+ expect(await move(fx.local, nova.id, { state: "returning", team: MY_CLOUD }), "a later try takes it").toMatchObject({ status: 200, body: { movedTo: { arrival: true } } });
+ await liveOnlyOn(nova.id, "cloud");
expect((await fx.local("DELETE", `/api/bot-moves/${nova.id}`)).status).toBe(200);
expect(await botOn(fx.local, nova.id), "kept, as the line of where it lives").toMatchObject({ hidden: true, movedTo: { state: "moved", team: MY_CLOUD } });
await liveOnlyOn(nova.id, "cloud");
expect(await move(fx.local, nova.id, { state: "returning", team: MY_CLOUD }), "the next try takes that line").toMatchObject({ status: 200, body: { movedTo: { back: true } } });
expect((await fx.local("DELETE", `/api/bot-moves/${nova.id}`)).status).toBe(200);
-}, hostTimeout(60_000));
+}, hostTimeout(120_000));
diff --git a/server/routes/bot-moves.ts b/server/routes/bot-moves.ts
index 112590880e..243f94d301 100644
--- a/server/routes/bot-moves.ts
+++ b/server/routes/bot-moves.ts
@@ -12,7 +12,7 @@ const team = z.object({ id: z.string().regex(/^[\w-]{1,128}$/u), name: z.string(
// New states, not new fields on old ones: an older server answers 400 rather than holding the bot the old way.
const bodySchema = z.discriminatedUnion("state", [
z.object({ v: z.literal(1), state: z.literal("moving"), team, lapse: z.boolean().optional() }),
- z.object({ v: z.literal(1), state: z.literal("returning"), team, lapse: z.boolean().optional(), arrival: z.boolean().optional() }),
+ z.object({ v: z.literal(1), state: z.literal("returning"), team }),
z.object({ v: z.literal(1), state: z.literal("moved"), team }),
z.object({ v: z.literal(1), state: z.literal("arrived"), team, on: z.array(z.string().regex(/^(?:routine|call|webhook|app-event):[\w-]{1,128}$/u)).max(2_000) }),
z.object({ v: z.literal(1), state: z.literal("back"), team }),
@@ -49,7 +49,7 @@ export function createBotMoveRoutes({ moves, enabled }: { moves: BotMoves | null
const moved = moves.moved(bot, body.team);
return "refused" in moved ? json(res, 409, { error: moved.refused, ...notHeld() }) : json(res, 200, { v: 1, ...moved });
}
- const answer = await moves.hold(bot, body.team, { lapse: body.lapse === true, back: body.state === "returning", arrival: body.state === "returning" && body.arrival === true });
+ const answer = await moves.hold(bot, body.team, body.state === "returning" ? { back: true } : { lapse: body.lapse === true });
if ("busy" in answer) return json(res, 409, { error: `${answer.busy} is answering. The move goes on once it is done.`, busy: answer.busy });
if ("refused" in answer) return json(res, 409, { error: answer.refused, ...(answer.here ? { here: true } : {}) });
return json(res, 200, { v: 1, movedTo: answer.movedTo });
diff --git a/server/routes/bots-create.ts b/server/routes/bots-create.ts
index 39c817a2cc..28cd6c4e37 100644
--- a/server/routes/bots-create.ts
+++ b/server/routes/bots-create.ts
@@ -1,3 +1,5 @@
+import { z } from "zod";
+
import type { BotCreateResponse, WireBot } from "../../shared/wire.ts";
import { freshLook } from "../bot-look.ts";
import { LINK_PREFIX } from "../bot-link/protocol.ts";
@@ -21,6 +23,7 @@ import { writeMemoryFile, writeMemoryTopic } from "../workspace.ts";
import { refusalBody, userError } from "../user-errors.ts";
import type { ServerErrorBody } from "../../shared/server-text.ts";
import { botLimitRefusal } from "../bot-limit.ts";
+import { arrivalMark, personalTeam } from "../bot-moves.ts";
import { PASS, type RouteHandler } from "./table.ts";
export type ModelSelectionCheck = { ok: true; selection: ModelSelection } | ({ ok: false; status: number } & ServerErrorBody);
@@ -55,8 +58,13 @@ export interface BotCreateRouteDeps {
personaliseSetupCard?(bot: BotRecord): void;
/** The Chief of Staff of a scope changed: these bots' flags did. */
chiefChanged?(changed: readonly BotRecord[]): void;
+ /** The request may make a bot that arrives by a move (`arriving`): the app's own main process on this computer, or My
+ * Cloud's owner on My Cloud (index.ts cloudSendOwner); never on a team's Cloud. */
+ movesIn?(auth: RequestAuth): boolean;
}
+const arrivingSchema = z.object({ team: z.object({ id: z.string().regex(/^[\w-]{1,128}$/u).refine(personalTeam), name: z.string().trim().min(1).max(80) }) }).strict();
+
const OWN_ID = /^[\w-]{8,128}$/;
/** A bot sent from the person's other computer keeps its id and its conversation's, so later sends and Bring newer
@@ -105,6 +113,19 @@ export function createBotCreateRoutes(deps: BotCreateRouteDeps): RouteHandler {
if (!body || typeof body !== "object" || Array.isArray(body)) {
return json(res, 400, { error: "bot must be a JSON object" });
}
+ // A bot arriving by a move (bot-moves.ts) is made held, hidden and taking no turn, so it is never live here beside
+ // the place it comes from, not even until the move holds it.
+ const { arriving: askedArrival, ...unmarked } = body as Record<string, unknown>;
+ body = unmarked;
+ let arriving: z.infer<typeof arrivingSchema> | null = null;
+ if (askedArrival !== undefined) {
+ if (!deps.movesIn?.(auth)) return json(res, 403, { error: "forbidden: only a move makes a bot that arrives" });
+ const parsed = arrivingSchema.safeParse(askedArrival);
+ if (!parsed.success || typeof unmarked.id !== "string") return json(res, 400, { error: "send arriving: { team: { id, name } } with the bot's own id" });
+ arriving = parsed.data;
+ // It brings its own settings; nothing of this place's New bot defaults (a routine, say) is added to it.
+ body = { ...unmarked, useDefaults: false };
+ }
if (req.headers["x-openmausbot-companion"] === "1") {
const field = adminOnlyBotSetting(askedSettings(body));
if (field) {
@@ -225,7 +246,8 @@ export function createBotCreateRoutes(deps: BotCreateRouteDeps): RouteHandler {
browserProfile: ordinary.browserProfile || undefined,
voiceNoteEveryReply: ordinary.voiceNoteEveryReply ?? undefined,
autoApprove: ordinary.approvalMode === "auto",
- });
+ ...(arriving ? { movedTo: arrivalMark(arriving.team, Date.now()), hidden: true } : {}),
+ } as Partial<BotRecord>);
} });
const createdRoutines: Array<{ id: string; enabled: boolean }> = [];
try {