Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bot link: a moving bot stays listed, a moved bot's own id reaches it, the wait restarts per change, paused bots are not offered
milind-soni81a078385f17
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 8c77da3fe9..adfc9c93e8 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -26,7 +26,7 @@ import { EXCHANGE_BYTES, LINK_EXPIRES_MS, PAIR_PATH, STATE_PATH, SYNC_PATH, linkconst CLOUD = peerKey("cloud-environment"), COMPUTER = peerKey("computer-environment");const onCloud = (id: string) => linkedId(CLOUD, id), onComputer = (id: string) => linkedId(COMPUTER, id);-type Bot = { id: string; name: string; hidden?: boolean };+type Bot = { id: string; name: string; hidden?: boolean; paused?: boolean; movedTo?: { team: { id: string; name: string }; state: "moving" | "moved" } };type Run = (node: HandoffView, resumed: boolean, signal: AbortSignal) => Promise<HostTurnResult>;const until = async (what: () => boolean, label: string, ms = 8_000) => {@@ -92,14 +92,15 @@ function place(label: string, bots: Bot[], version?: number) {let openedCount = 0, port = 0, generation = 0, skew = 0, minted = 0, directoryChanges = 0;const sockets = new Set<import("node:net").Socket>();- function boot(options: { limits?: { queueMs?: number; stallMs?: number } } = {}) {+ function boot(options: { limits?: { queueMs?: number; stallMs?: number }; tell?: { afterMs: number; withinMs: number } } = {}) {rooms = createLinkedRooms({ dataDir: dir, store: roomStore as never, coordinator: () => coordinator, on: () => link.on(), linked: (peer) => link.has(peer), online: (peer) => link.online(peer), linkedBots: () => link.linked(), selfName: () => link.selfName(), wanted: () => link.wanted(),window: (threadId, reader) => createRoomTranscript({ store: roomStore as never, teammateReportContext: () => "" }).window(threadId, "Sam", undefined, reader),opener: (botId, threadId) => (routineThreads.has(threadId) ? { requester: { kind: "routine_run", runId: "run-1", botId, threadId }, origin: { kind: "routine", source: "routine", ref: "routine-1" } } : undefined),personName: () => "Sam", line: (_threadId, key, params) => `${key} ${params.bot ?? params.bots}${params.place ? ` [${params.place}]` : ""}`, follow: (_groupId, _threadId, speaker, text, hop) => { followed.push(`${speaker.name} at ${hop}: ${text}`); } });link = createBotLink({rooms, directoryChanged: () => { directoryChanges += 1; rooms.sync(); },- dataDir: dir, coordinator: () => coordinator, bots: () => bots, bot: (id) => bots.find((bot) => bot.id === id), level: () => "full",+ dataDir: dir, coordinator: () => coordinator, bots: () => bots, bot: (id) => bots.find((bot) => bot.id === id), level: () => "full", paused: (bot) => Boolean((bot as Bot).paused),+ ...(options.tell ? { tellAfterMs: options.tell.afterMs, tellWithinMs: options.tell.withinMs } : {}),openThread: (bot, title, opener, brief) => { const id = `${bot.id}-work-${++openedCount}`; threads.add(id); opened.push({ threadId: id, title, from: opener.name, brief }); return id; },hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam",sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId, ...(input.roomId ? { roomId: input.roomId } : {}) }); },@@ -230,7 +231,7 @@ afterEach(async () => {});/** A computer and a Cloud. The same id, `shared`, is a different bot in each. */-async function two(options: { paired?: boolean; limits?: { queueMs?: number; stallMs?: number } } = {}) {+async function two(options: { paired?: boolean; limits?: { queueMs?: number; stallMs?: number }; tell?: { afterMs: number; withinMs: number } } = {}) {const computer = place("computer", [{ id: "shared", name: "Scout" }, { id: "local-writer", name: "Writer" }]).boot(options);const cloud = place("cloud", [{ id: "shared", name: "Atlas" }, { id: "cloud-analyst", name: "Analyst" }]).boot(options);places.push(computer, cloud);@@ -1242,6 +1243,33 @@ describe("the link between a computer and its Cloud", () => {await until(() => computer.link.resolve("Nimbus")?.bot.id === "cloud-late", "the computer hears of the Cloud's new bot");});+ it("changes that keep coming are told once, after a pause in them", async () => {+ const { computer, cloud } = await two({ tell: { afterMs: 2_000, withinMs: 60_000 } });+ const hellos: string[][] = [];+ const receive = cloud.link.receive;+ cloud.link.receive = (peer, frames) => { for (const frame of frames as Frame[]) if (frame.t === "hello") hellos.push(frame.bots.map((bot) => bot.name)); receive(peer, frames); };+ const bot = { id: "busy", name: "Busy0" };+ computer.bots.push(bot);+ // Ten changes 300 ms apart, longer in all than the 2 s wait: the wait starts over with each, so one hello.+ for (let index = 0; index < 10; index += 1) { bot.name = `Busy${index}`; computer.link.botsChanged(); await new Promise((resolve) => setTimeout(resolve, 300)); }+ await until(() => cloud.link.resolve("Busy9") !== undefined, "the Cloud hears the last name");+ expect(hellos.filter((names) => names.some((name) => name.startsWith("Busy")))).toEqual([["Scout", "Writer", "Busy9"]]);+ });++ it("changes that never pause are still told once per ceiling", async () => {+ const { computer, cloud } = await two({ tell: { afterMs: 2_000, withinMs: 3_000 } });+ const told: string[] = [];+ const receive = cloud.link.receive;+ cloud.link.receive = (peer, frames) => { for (const frame of frames as Frame[]) if (frame.t === "hello") { const busy = frame.bots.find((one) => one.name.startsWith("Busy")); if (busy) told.push(busy.name); } receive(peer, frames); };+ const bot = { id: "busy", name: "Busy0" };+ computer.bots.push(bot);+ // Changes 300 ms apart for 6 s: heard at the 3 s ceiling, then once more after they stop.+ for (let index = 0; index < 20; index += 1) { bot.name = `Busy${index}`; computer.link.botsChanged(); await new Promise((resolve) => setTimeout(resolve, 300)); }+ await until(() => cloud.link.resolve("Busy19") !== undefined, "the Cloud hears the last name");+ expect(told).toHaveLength(2);+ expect(told.at(-1)).toBe("Busy19");+ }, 30_000);+it("a bot moved to the Cloud is found there at once, and the computer's stub of it is no longer listed or answered there", async () => {const { computer, cloud } = await two();computer.bots.push({ id: "moved-bot-1", name: "Mover" });@@ -1250,10 +1278,18 @@ describe("the link between a computer and its Cloud", () => {// The move: the bot is the Cloud's now; the computer keeps a hidden stub that says where it went.cloud.bots.push({ id: "moved-bot-1", name: "Mover" });cloud.link.botsChanged();- Object.assign(computer.bots.find((bot) => bot.id === "moved-bot-1")!, { hidden: true, movedTo: { team: { id: "my-cloud", name: "My Cloud" }, state: "moved" } });+ // While it moves it stays listed where it was, so a bot that asks for it hears that it is moving, not that it is gone.+ const moving = computer.bots.find((bot) => bot.id === "moved-bot-1")!;+ moving.movedTo = { team: { id: "my-cloud", name: "My Cloud" }, state: "moving" };+ computer.link.botsChanged();+ await new Promise((resolve) => setTimeout(resolve, 1_000));+ expect(cloud.link.resolve(onComputer("moved-bot-1"))?.bot.name).toBe("Mover");+ Object.assign(moving, { hidden: true, movedTo: { team: { id: "my-cloud", name: "My Cloud" }, state: "moved" } });computer.link.botsChanged();await until(() => computer.link.resolve("Mover")?.bot.id === "moved-bot-1" && cloud.link.resolve(onComputer("moved-bot-1")) === undefined, "both places hear of the move");expect(cloud.link.linked().some((one) => one.bot.id === "moved-bot-1")).toBe(false);+ // Named by its own id, it is the Cloud's bot, not the stub it left here.+ expect(computer.link.resolve("moved-bot-1")).toMatchObject({ peer: CLOUD, bot: { id: "moved-bot-1" } });const { receipts } = await computer.handOff("local-writer", call(["Mover"], "Answer from My Cloud"));expect(receipts[0]).toMatchObject({ botId: onCloud("moved-bot-1"), outcome: "queued" });await until(() => cloud.runs.some((run) => run.botId === "moved-bot-1"), "the moved bot works on the Cloud");@@ -1272,6 +1308,12 @@ describe("the link between a computer and its Cloud", () => {expect(answer.body.error).toContain(`Analyst on My Cloud (id ${onCloud("cloud-analyst-2")})`);expect(answer.body.error).toContain("Send it again with the id of the one you mean");expect(computer.link.reachableElsewhere()).toBe(`Through the link to My Cloud you can also reach: Atlas on My Cloud (id ${onCloud("shared")}), Analyst on My Cloud (id ${onCloud("cloud-analyst")}), Analyst on My Cloud (id ${onCloud("cloud-analyst-2")}).`);+ // A bot its place paused is not offered, and is no reason to ask which one is meant.+ cloud.bots.find((bot) => bot.id === "cloud-analyst-2")!.paused = true;+ cloud.link.botsChanged();+ await until(() => computer.link.linked().some((one) => one.bot.paused), "the computer hears of the pause");+ expect(computer.link.reachableElsewhere()).not.toContain("cloud-analyst-2");+ expect(computer.link.resolve("Analyst")?.bot.id).toBe("cloud-analyst");await computer.fetch("PUT", STATE_PATH, { on: false });expect(computer.link.reachableElsewhere()).toBe("");});diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex 0efc905bf6..995ebb0d34 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -53,6 +53,8 @@ const FILE_RETRY_MS = 5_000;const FILE_RETRY_MAX_MS = 5 * 60_000;/** This place's bots changed: the other places hear the new list once changes settle, so a burst of them is one hello. */const TELL_AFTER_MS = 250;+/** Under changes that do not stop, the other places still hear at least this often. */+const TELL_WITHIN_MS = 1_500;/** How a computer moves a file's bytes: it puts the ones it sends and gets the ones it is sent. `holds`: the Cloud already* has this file, so it is not sent again. `gone` on an error: the Cloud said it will not take it or has no such file, so@@ -158,8 +160,12 @@ export interface BotLinkDeps {revoke?(sessionId: string): void;now?: () => number;log?(line: string): void;- /** How long after a change to this place's bots the other places are told (TELL_AFTER_MS). */+ /** How long after the last change to this place's bots the other places are told (TELL_AFTER_MS), and the longest a+ * change waits while more keep coming (TELL_WITHIN_MS). */tellAfterMs?: number;+ tellWithinMs?: number;+ /** The person paused this bot, or the plan keeps it asleep: it takes no work now. */+ paused?(bot: LocalBot): boolean;}export interface CoordinateContext {@@ -199,8 +205,8 @@ export function createBotLink(deps: BotLinkDeps) {/** Hand-offs whose result came: the rest that end here (cut by restarts, refused, stopped) are stopped where they run. */const resulted = new Set<string>();let alive: NodeJS.Timeout | undefined;- /** A change to this place's bots waits here to be told. */- let telling: NodeJS.Timeout | undefined;+ /** A change to this place's bots waits here to be told, since `tellingSince`. */+ let telling: NodeJS.Timeout | undefined, tellingSince = 0;/** Hand-offs whose files are being taken in, and results whose files are being sent: one at a time each. */const accepting = new Set<string>(), resultsGoing = new Set<string>();/** What waits to be tried again because a file could not cross yet, by what it is for. */@@ -211,12 +217,14 @@ export function createBotLink(deps: BotLinkDeps) {const linkOf = (peer: string): Live => { let one = live.get(peer); if (!one) { one = { online: false, seq: 0, outbox: [], level: 1 }; live.set(peer, one); } return one; };const isOnline = (peer: string) => live.get(peer)?.online === true;const placeName = (peer: string) => state?.peers[peer]?.place.name ?? "the other place";- const directory = (): LinkedBot[] => deps.bots().filter((bot) => !bot.hidden && !bot.movedTo && /^[\w-]{1,128}$/u.test(bot.id)).map((bot) => ({+ /** A bot that moved to another place for good leaves a hidden stub here; one still moving is here and says so. */+ const movedAway = (bot: LocalBot) => (bot.movedTo as { state?: unknown } | null | undefined)?.state === "moved";+ const directory = (): LinkedBot[] => deps.bots().filter((bot) => !bot.hidden && !movedAway(bot) && /^[\w-]{1,128}$/u.test(bot.id)).map((bot) => ({id: bot.id, name: bot.name, ...(bot.title ? { title: bot.title.slice(0, 200) } : {}), ...(bot.description ? { description: bot.description.slice(0, 400) } : {}),...(deps.model?.(bot) ? { model: deps.model(bot)!.slice(0, 200) } : {}), level: deps.level(bot),...(bot.color ? { color: bot.color.slice(0, 64) } : {}), ...(bot.mascotBody ? { mascotBody: bot.mascotBody.slice(0, 64) } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor.slice(0, 64) } : {}),...(bot.mascotBodyColor ? { mascotBodyColor: bot.mascotBodyColor.slice(0, 64) } : {}), ...(bot.mascotMaterial ? { mascotMaterial: bot.mascotMaterial.slice(0, 64) } : {}),- ...(bot.chiefOfStaff ? { chief: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}),+ ...(bot.chiefOfStaff ? { chief: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}), ...(deps.paused?.(bot) ? { paused: true } : {}),})).slice(0, 500);function send(peer: string, frame: Frame): void {@@ -332,14 +340,17 @@ export function createBotLink(deps: BotLinkDeps) {* A bot's id here, in any case, or the start of one (8+ characters), stays with the local resolver, so a bot elsewhere* named after it never takes that bot's work or its files. */function resolve(raw: string): Remote | undefined {- const matches = candidates(raw);- return matches.length === 1 ? matches[0] : undefined;+ const matches = candidates(raw), awake = matches.length > 1 ? matches.filter((remote) => !remote.bot.paused) : matches;+ return awake.length === 1 ? awake[0] : undefined;}/** Every bot of another place `raw` could name, by the rules of `resolve`: one is that bot, more say nothing. */function candidates(raw: string): Remote[] {if (!state) return [];const wanted = raw.trim(), lower = wanted.toLowerCase();- const local = deps.bots();+ // A bot that moved away is named by its own id still: that is the bot of the place it moved to, never its stub here.+ const stub = deps.bots().find((bot) => movedAway(bot) && bot.id.toLowerCase() === lower);+ if (stub) return Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => bot.id === stub.id).map((bot) => ({ peer, bot })));+ const local = deps.bots().filter((bot) => !movedAway(bot));if (local.some((bot) => bot.id.toLowerCase() === lower)) return [];if (isLinkedId(wanted)) { const remote = remoteOf(wanted); return remote ? [remote] : []; }if (isIdStart(wanted) && local.some((bot) => bot.id.toLowerCase().startsWith(lower))) return [];@@ -349,7 +360,8 @@ export function createBotLink(deps: BotLinkDeps) {}/** A name more than one bot of the other places has (and no bot here): which one is meant, by its address. */function sharedName(raw: string): string | null {- const matches = candidates(raw);+ // A bot its place paused would refuse the work, so it is no choice to offer.+ const matches = candidates(raw).filter((remote) => !remote.bot.paused);if (matches.length < 2) return null;const listed = matches.slice(0, 12).map((remote) => `${remote.bot.name} on ${placeName(remote.peer)} (id ${linkedId(remote.peer, remote.bot.id)})`).join("; ");return `${matches.length} bots of the person's other places are named "${raw.trim().slice(0, 120)}", so nothing was sent: ${listed}${matches.length > 12 ? `; and ${matches.length - 12} more` : ""}. Send it again with the id of the one you mean.`;@@ -801,7 +813,7 @@ export function createBotLink(deps: BotLinkDeps) {* it can reach through the link, each by the id that reaches it. */reachableElsewhere(): string {if (!state) return "";- const far = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.map((bot) => ({ peer, bot })));+ const far = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => !bot.paused).map((bot) => ({ peer, bot })));const places = [...new Set(Object.keys(state.peers).map(placeName))].join(", ");if (!far.length) return `This place is linked to ${places}, but no bot there can be reached through the link now.`;const listed = far.slice(0, 12).map(({ peer, bot }) => `${bot.name} on ${placeName(peer)} (id ${linkedId(peer, bot.id)})`).join(", ");@@ -858,11 +870,15 @@ export function createBotLink(deps: BotLinkDeps) {},/** Housekeeping, at start and once a day: old records go, and on the Cloud a computer long gone is unlinked. */tidy(): void { prune(); expire(); sweep(); },- /** This place's bots changed (one was made, renamed, hidden, moved, deleted, its look, model or level changed): once- * changes settle, the other places hear the new list, and nothing when what they are told did not change. */+ /** This place's bots changed (one was made, renamed, hidden, moved, deleted, paused, its look, model or level changed):+ * once changes settle (or every TELL_WITHIN_MS while they do not), the other places hear the new list, and nothing when+ * what they are told did not change. */botsChanged(): void {- if (!state || telling) return;- telling = setTimeout(tellBots, deps.tellAfterMs ?? TELL_AFTER_MS);+ if (!state) return;+ const at = Date.now();+ if (!telling) tellingSince = at;+ clearTimeout(telling);+ telling = setTimeout(tellBots, Math.max(0, Math.min(deps.tellAfterMs ?? TELL_AFTER_MS, tellingSince + (deps.tellWithinMs ?? TELL_WITHIN_MS) - at)));telling.unref?.();},setOnline,diff --git a/server/bot-link/protocol.ts b/server/bot-link/protocol.tsindex e03cd24723..dc2a4fe716 100644--- a/server/bot-link/protocol.ts+++ b/server/bot-link/protocol.ts@@ -56,6 +56,8 @@ export const linkedBotSchema = z.object({id: botId, name, title: z.string().max(200).optional(), description: z.string().max(400).optional(), model: z.string().max(200).optional(), level: level.optional(),/** How it looks and where its own chat is, so the other place can draw it as it is drawn at home. */color: z.string().max(64).optional(), mascotBody: z.string().max(64).optional(), mascotFaceColor: z.string().max(64).optional(), mascotBodyColor: z.string().max(64).optional(), mascotMaterial: z.string().max(64).optional(), chief: z.boolean().optional(), threadId: botId.optional(),+ /** Paused there (by the person, or asleep on its plan): it would refuse work. A level-2 place that does not know it drops it. */+ paused: z.boolean().optional(),});export type LinkedBot = z.infer<typeof linkedBotSchema>;diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsindex 19ac3554a0..e459d2b8e4 100644--- a/server/host/bot-link-host.ts+++ b/server/host/bot-link-host.ts@@ -36,6 +36,8 @@ export interface BotLinkHostDeps {/** A work thread a far bot opened here is named from the job it handed, behind "@Sender · ". */titleHanded?(botId: string, threadId: string, brief: string, prefix: string): void;refusal(bot: BotRecord): string | null;+ /** The person paused this bot, or its plan keeps it asleep: the other places are told, so they do not offer it. */+ paused?(botId: string): boolean;language(threadId: string): string | undefined;personName(threadId: string): string | undefined;sessions: { issue(input: { label: string; scopes: Array<"admin" | "client">; email?: string; userId?: string }): { token: string; session: { id: string } }; revoke(id: string): boolean };@@ -96,6 +98,7 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {dataDir: deps.dataDir, coordinator: deps.coordinator, kick: deps.kick, log: deps.log, rooms, directoryChanged: () => { syncStandIns(); }, revoke: (sessionId) => { deps.sessions.revoke(sessionId); },bots: () => store.bots, bot: (id) => store.bot(id),refusal: (bot) => deps.refusal(bot as BotRecord),+ paused: (bot) => deps.paused?.(bot.id) ?? false,model: (bot) => (bot as BotRecord).modelSelection.model,level: (bot) => deps.level(bot as BotRecord),openThread: (bot, title, opener, brief) => {diff --git a/server/index.ts b/server/index.tsindex 7962b06c91..ffc3809c63 100644--- a/server/index.ts+++ b/server/index.ts@@ -2779,7 +2779,7 @@ const phones = createPhones({mint: (botId, turn) => mintInternalCapability({ botId, ...turn, kind: "device", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }),active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});-const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, routineThread: (botId, threadId) => { const run = activeRoutineRunForThread(threadId); return run?.botId === botId && run.target === "bot"; }, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let starterRoutineWake: StarterRoutineWake | undefined; /* made beside tieAutomationsToBots, once the routines and triggers are */ const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.+const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => { broadcast({ kind: "config", ...configStatus() }); pausesChanged(); } }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, routineThread: (botId, threadId) => { const run = activeRoutineRunForThread(threadId); return run?.botId === botId && run.target === "bot"; }, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let starterRoutineWake: StarterRoutineWake | undefined; /* made beside tieAutomationsToBots, once the routines and triggers are */ const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => { broadcast({ kind: "config", ...configStatus() }); pausesChanged(); } }); /** A bot was paused or woken: the other places of the link hear it (server/bot-link/link.ts; nothing while the link is off). */ function pausesChanged() { try { botLink.link.botsChanged(); } catch { /* the link is made further down; nothing to tell before it is */ } } let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, storage: () => withCacheCounters(perf.storage(), cacheSweeper), dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),@@ -3841,7 +3841,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });const remoteTeammates = new RemoteTeammates(); const remoteHandoff = createRemoteHandoff({ teammates: remoteTeammates, coordinator: () => coordinator, localBots: () => store.bots, botName: (id) => store.bot(id)?.name, outside: (threadId) => (outsideLineage.outsideDrivenThread(threadId) || outsideLineage.cloudGuestDriven(threadId) ? OUTSIDE_STAYS_HERE : undefined), file: join(DATA_DIR, "remote-teammate-work.json"), log: (line) => console.error(line) }); const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });-const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: beginGroupTurnOperation, finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, refusal: botMoveRefusal, language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({+const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: beginGroupTurnOperation, finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, refusal: botMoveRefusal, paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },log: line => console.error("coordinator:", line),diff --git a/server/peer-roster.ts b/server/peer-roster.tsindex 4e804f7d9c..89764e6e2d 100644--- a/server/peer-roster.ts+++ b/server/peer-roster.ts@@ -230,11 +230,15 @@ export function resolveTeammate<T extends RosterMember>(if (near.length === 1) return { id: near[0]!.id, byName: true };const apart = bots.find(bot => bot.id !== from.id && !bot.hidden && !bot.defaultBot && !wider?.hides(bot) && !sameAudience(from.visibility, bot.visibility) && (fold(bot.name) === name || loose(bot.name) === loose(wanted)));if (apart) return { error: wider?.refusal(apart) ?? reachRefusal(from, apart, lookedAfterBy)! };- const away = bots.some(bot => !wider?.hides(bot) && (fold(bot.name) === name || loose(bot.name) === loose(wanted))) ? null : elsewhere(wanted);+ // An archived bot of that name keeps the answer here; the stub a bot left when it moved away does not, since it lives on elsewhere.+ const away = bots.some(bot => !movedAway(bot) && !wider?.hides(bot) && (fold(bot.name) === name || loose(bot.name) === loose(wanted))) ? null : elsewhere(wanted);if (away && "where" in away) return { error: away.where };return { error: `No bot with id or name "${shown}" — call list_bots and copy the exact id from the result.${teammateChoices(reachable)}${away ? ` ${away.hint}` : ""} ${PEER_ACCESS_HELP}` };}+/** The hidden stub a bot leaves behind when it moved to another place for good. */+const movedAway = (bot: RosterMember) => (bot as { movedTo?: { state?: unknown } | null }).movedTo?.state === "moved";+const CHOICES_MAX = 12;export function sharedNameChoices(matches: readonly RosterMember[]): string {diff --git a/server/places-elsewhere.test.ts b/server/places-elsewhere.test.tsindex 4424e4747e..b67d6ac7a0 100644--- a/server/places-elsewhere.test.ts+++ b/server/places-elsewhere.test.ts@@ -67,6 +67,9 @@ describe("where the person's other bots live", () => {expect(resolveTeammate(bots, from, "Reviewer 2", here.explain)).toEqual({ error: expect.stringMatching(/^Reviewer 2 lives on Work laptop, the person's computer, not here\./u) });expect(resolveTeammate(bots, from, "Scout", here.explain), "a bot here of that name, archived: no such reachable bot, never elsewhere").toEqual({ error: expect.stringMatching(/^No bot with id or name "Scout"/u) });expect(resolveTeammate(bots, from, "Nobody", here.explain)).toEqual({ error: expect.not.stringContaining("Bots work together") });+ // The stub a bot left when it moved to the laptop is not an archived bot here: where it lives is said.+ const moved = [...bots, { id: "rev-2", name: "Reviewer 2", hidden: true, movedTo: { team: { id: "laptop", name: "Work laptop" }, state: "moved" } }];+ expect(resolveTeammate(moved, from, "Reviewer 2", here.explain)).toEqual({ error: expect.stringMatching(/^Reviewer 2 lives on Work laptop/u) });});});