Skip to content

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

Bots of the person's other places are records this place finds by their address (early, behind the same switch) (#6104)

Milind Soni3edc00844c4e
diff --git a/server/bot-link.e2e.test.ts b/server/bot-link.e2e.test.ts
index 8d2319a860..4c4f5221e6 100644
--- a/server/bot-link.e2e.test.ts
+++ b/server/bot-link.e2e.test.ts
@@ -62,6 +62,52 @@ it("a bot on the computer and a bot on the person's own server hand each other w
expect(backedUp).not.toMatch(/Wait for bot turns/);
await expect.poll(async () => (await computer.api("GET", "/api/bot-link")).online, { timeout: 15_000 }).toBe(true);
+ // The server's bot is a record on the computer, found by its address there and nowhere else: not listed, not saved,
+ // and it takes no turn on the computer.
+ const rows = (await computer.api("GET", "/api/bot-link/bots")).bots as any[];
+ const standIn = rows.find((row) => row.name === "Atlas");
+ expect(standIn).toMatchObject({ botId: atlas.id, home: { name: "My server", online: true }, threadId: expect.any(String) });
+ expect(standIn.id).toMatch(/^link-[0-9a-f]{8}-/);
+ expect(JSON.stringify(await computer.api("GET", `/api/bots/${standIn.id}`))).toContain("\"Atlas\"");
+ expect((await computer.api("GET", "/api/bots?messages=0")).bots.some((bot: any) => bot.id === standIn.id)).toBe(false);
+ expect(readFileSync(join(computer.dataDir, "bots.json"), "utf8")).not.toContain(standIn.id);
+ const direct = await fetch(`${computer.url}/api/bots/${standIn.id}/messages`, { method: "POST", headers: { "content-type": "application/json", origin: computer.url }, body: JSON.stringify({ text: "Are you here?" }) });
+ const refused = JSON.stringify(await direct.json());
+ expect(direct.status, refused).toBeGreaterThanOrEqual(400);
+ expect(refused).toContain("lives on My server");
+ await home.api("GET", "/api/bot-link/bots", undefined, { token: owner, status: 403 });
+
+ // A stand-in is read-only on the computer. Every route that changes a bot is found in the server's own source and
+ // asked for the stand-in, with each changing method: each answers where the bot lives, and nothing on the computer changes.
+ expect(JSON.stringify(await computer.api("GET", `/api/bots/${standIn.id}`))).not.toContain("\"home\"");
+ const source = [join(import.meta.dirname, "index.ts"), ...readdirSync(join(import.meta.dirname, "routes")).filter((name) => name.endsWith(".ts") && !name.includes(".test.")).map((name) => join(import.meta.dirname, "routes", name))]
+ .map((file) => readFileSync(file, "utf8")).join("\n");
+ const botRoutes = new Set([""]);
+ for (const found of source.matchAll(/\\\/api\\\/bots\\\/\([^)]*\)((?:\\\/[a-z][\w-]*)*)/gu)) botRoutes.add(found[1]!.replaceAll("\\/", "/"));
+ for (const found of source.matchAll(/["`]\/api\/bots\/\$\{[^}]*\}((?:\/[a-z][\w-]*)*)/gu)) botRoutes.add(found[1]!);
+ expect(botRoutes.size, [...botRoutes].join(" ")).toBeGreaterThan(15);
+ const before = { bots: readFileSync(join(computer.dataDir, "bots.json"), "utf8"), groups: existsSync(join(computer.dataDir, "groups.json")) ? readFileSync(join(computer.dataDir, "groups.json"), "utf8") : "", list: JSON.stringify((await computer.api("GET", "/api/bots?messages=0")).bots.map((bot: any) => [bot.id, bot.chiefOfStaff ?? false, bot.tasks?.length ?? 0])) };
+ const asked = async (method: string, path: string, body: unknown) => {
+ const response = await fetch(`${computer.url}${path}`, { method, headers: { "content-type": "application/json", origin: computer.url }, body: JSON.stringify(body), signal: AbortSignal.timeout(10_000) });
+ return { status: response.status, text: await response.text() };
+ };
+ for (const route of botRoutes) for (const method of ["POST", "PUT", "PATCH", "DELETE"]) {
+ const answer = await asked(method, `/api/bots/${standIn.id}${route}`, { chiefOfStaff: true, name: "Renamed", title: "New thread", text: "hello" });
+ expect([answer.status, answer.text], `${method} /api/bots/<stand-in>${route}`).toEqual([409, expect.stringContaining("lives on My server")]);
+ }
+ // Named in a body: not a room member, and no automation of its own, each with the same plain reason.
+ for (const [path, body] of [["/api/groups", { name: "Mixed", memberIds: [writer.id, standIn.id] }], ["/api/routines", { name: "Daily", prompt: "Count the orders.", botId: standIn.id, schedule: { kind: "daily", time: "09:00" } }]] as const) {
+ const answer = await asked("POST", path, body);
+ expect(answer.status, `${path}: ${answer.text}`).toBeGreaterThanOrEqual(400);
+ expect(answer.text, path).toContain("lives on My server");
+ }
+ expect((await asked("POST", "/api/webhooks", { name: "Orders", botId: standIn.id, prompt: "Read the order." })).status).toBeGreaterThanOrEqual(400);
+ expect((await computer.api("GET", "/api/routines")).routines.some((routine: any) => routine.botId === standIn.id)).toBe(false);
+ expect(readFileSync(join(computer.dataDir, "bots.json"), "utf8")).toBe(before.bots);
+ expect(existsSync(join(computer.dataDir, "groups.json")) ? readFileSync(join(computer.dataDir, "groups.json"), "utf8") : "").toBe(before.groups);
+ expect(JSON.stringify((await computer.api("GET", "/api/bots?messages=0")).bots.map((bot: any) => [bot.id, bot.chiefOfStaff ?? false, bot.tasks?.length ?? 0]))).toBe(before.list);
+ expect(JSON.stringify(await computer.api("GET", `/api/bots/${standIn.id}`))).toContain("\"Atlas\"");
+
// The computer's bot hands work to the server's bot by name, and is resumed with its result.
home.plan(atlas.id, { reply: "Atlas counted 42 orders." });
computer.plan(writer.id,
@@ -129,6 +175,8 @@ it("a bot on the computer and a bot on the person's own server hand each other w
// Off on the computer: the server is told, and neither keeps the link.
expect(await computer.api("PUT", "/api/bot-link", { on: false })).toEqual({ on: false });
await expect.poll(() => existsSync(join(home.dataDir, "bot-link.json")), { timeout: 10_000 }).toBe(false);
+ await computer.api("GET", `/api/bots/${standIn.id}`, undefined, { status: 404 });
+ expect((await computer.api("GET", "/api/bot-link/bots")).bots).toEqual([]);
await home.api("POST", "/api/bot-link/sync", { ack: 0, frames: [], wait: 0 }, { token: paired.token, status: 401 });
} finally {
await Promise.all(fixtures.map((fixture) => fixture.close()));
diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.ts
index 2d2315d679..361e41f18e 100644
--- a/server/bot-link/dial.ts
+++ b/server/bot-link/dial.ts
@@ -11,7 +11,7 @@ import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import type { BotLink, EndedLink, FileTransfer } from "./link.ts";
-import { FILE_PATH, HOLD_MS, SYNC_PATH, syncAnswer, type FileWay, type Frame } from "./protocol.ts";
+import { FILE_PATH, HOLD_MS, LEVEL_HEADER, PROTOCOL_LEVEL, SYNC_PATH, levelOf, syncAnswer, type FileWay, type Frame } from "./protocol.ts";
const FIRST_RETRY_MS = 1_000;
const MAX_RETRY_MS = 60_000;
@@ -27,9 +27,11 @@ export interface DialerOptions {
log?(line: string): void;
holdMs?: number;
firstRetryMs?: number;
+ /** What this computer says its version reads; a test stands in for an older app with it. */
+ level?: number;
}
-export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS }: DialerOptions) {
+export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS, level = PROTOCOL_LEVEL }: DialerOptions) {
let running = false, stopped = true, asleep = false, needsPairing = false;
let session = "", ack = 0, fresh = true, retryMs = firstRetryMs;
let held: AbortController | null = null;
@@ -95,7 +97,7 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h
try {
response = await fetchImpl(`${target.origin}${SYNC_PATH}`, {
method: "POST", redirect: "error", cache: "no-store", signal: controller.signal,
- headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${target.token}`, origin: target.origin,
+ headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${target.token}`, origin: target.origin, [LEVEL_HEADER]: String(level),
...(carriesWork(sending) ? {} : { [BACKGROUND_HEADER]: "1" }) },
body: JSON.stringify({ fresh, ack, frames: sending.map((entry) => entry.frame), wait }),
});
@@ -130,6 +132,7 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h
}
fresh = false; retryMs = firstRetryMs;
link.setOnline(peer, true);
+ link.setLevel(peer, levelOf(response.headers.get(LEVEL_HEADER)));
const news = answer.data.frames.filter((entry) => entry.seq > ack);
link.receive(peer, news.map((entry) => entry.frame));
ack = Math.max(ack, ...news.map((entry) => entry.seq));
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.ts
index a94b379517..0e5b5b3689 100644
--- a/server/bot-link/link.test.ts
+++ b/server/bot-link/link.test.ts
@@ -36,7 +36,7 @@ const call = (botIds: string[], message: string, more: Partial<CoordinateBotsCal
({ botIds, message, rework: false, thread: "standing", reply: "resume", consult: false, ...more });
/** One place. `boot()` again over the same folder is that place's server restarted. */
-function place(label: string, bots: Bot[]) {
+function place(label: string, bots: Bot[], version?: number) {
const dir = mkdtempSync(join(tmpdir(), `bot-link-${label}-`));
const threads = new Set<string>();
const runs: Array<{ botId: string; threadId: string; text: string; resumed: boolean; requester: string; origin: unknown }> = [];
@@ -57,7 +57,7 @@ function place(label: string, bots: Bot[]) {
const failing: Array<{ match: RegExp; status: number }> = [];
let run: Run = async (node) => ({ ok: true, text: `${node.botId} did: ${node.text}` });
let coordinator!: Coordinator, link!: BotLink, dialer!: ReturnType<typeof createDialer>, ticker: NodeJS.Timeout | undefined, http: Server | undefined;
- let opened = 0, port = 0, generation = 0, skew = 0, minted = 0;
+ let opened = 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 } } = {}) {
@@ -70,6 +70,7 @@ function place(label: string, bots: Bot[]) {
kick: () => { queueMicrotask(() => { try { coordinator.tick(); } catch { /* closed */ } }); },
revoke: (sessionId) => { for (const [token, id] of issued) if (id === sessionId) issued.delete(token); },
now: () => Date.now() + skew,
+ directoryChanged: () => { directoryChanges += 1; },
files: {
carried: (id, way) => ledger.get(`${id}:${way}`)?.files ?? [],
crossed: (id, way, from, files) => { if (!ledger.has(`${id}:${way}`)) ledger.set(`${id}:${way}`, { from, files: [...files] }); },
@@ -86,7 +87,7 @@ function place(label: string, bots: Bot[]) {
},
};
coordinator = createCoordinator({ dataDir: dir, host: link.host(inner), log: () => {}, ...(options.limits ? { runtimeLimits: options.limits } : {}) });
- dialer = createDialer({ link, holdMs: 400, firstRetryMs: 20 });
+ dialer = createDialer({ link, holdMs: 400, firstRetryMs: 20, ...(version ? { level: version } : {}) });
ticker = setInterval(() => coordinator.tick(), 15);
return api;
}
@@ -100,7 +101,7 @@ function place(label: string, bots: Bot[]) {
async function listen(at = 0): Promise<string> {
const routes = routesOf({
- link, dialer, environmentId: `${label}-environment`, seenMs: 900, power: () => null,
+ link, dialer, environmentId: `${label}-environment`, seenMs: 900, power: () => null, ...(version ? { level: version } : {}),
local: (who) => who.kind === "loopback", owner: (who) => who.kind === "session" && who.session.id === "owner-session",
issue: () => { const token = `link-token-${++minted}-0123456789`; issued.set(token, `link-session-${minted}`); return { token, sessionId: issued.get(token)! }; },
revoke: (sessionId) => { for (const [token, id] of issued) if (id === sessionId) issued.delete(token); },
@@ -158,6 +159,7 @@ function place(label: string, bots: Bot[]) {
/** Time passes for this place's link. */
later(ms: number) { skew += ms; },
sessions: () => [...issued.values()],
+ directoryChanges: () => directoryChanges,
async fetch(method: string, path: string, body?: unknown, bearer?: string) {
const response = await fetch(`http://127.0.0.1:${port}${path}`, { method, headers: { "content-type": "application/json", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },
...(body === undefined ? {} : { body: JSON.stringify(body) }) });
@@ -692,6 +694,58 @@ describe("the link between a computer and its Cloud", () => {
expect(cloud.runs.filter((run) => run.botId === "cloud-analyst")).toHaveLength(1);
});
+ it("each place keeps the other's bots with their address, place and look, and hears when they change or the link ends", async () => {
+ const { computer, cloud } = await two();
+ expect(computer.link.linked().map((one) => [one.id, one.place.name, one.online, one.bot.name])).toEqual([[onCloud("shared"), "My Cloud", true, "Atlas"], [onCloud("cloud-analyst"), "My Cloud", true, "Analyst"]]);
+ expect(cloud.link.linked().map((one) => one.id)).toEqual([onComputer("shared"), onComputer("local-writer")]);
+ const before = cloud.directoryChanges();
+ computer.bots.push({ id: "new", name: "Newcomer" });
+ computer.link.botsChanged();
+ await until(() => cloud.link.linked().some((one) => one.bot.name === "Newcomer"), "the Cloud hears of the new bot");
+ expect(cloud.directoryChanges()).toBeGreaterThan(before);
+ const heard = computer.directoryChanges();
+ await computer.fetch("PUT", STATE_PATH, { on: false });
+ expect(computer.link.linked()).toEqual([]);
+ expect(computer.directoryChanges()).toBeGreaterThan(heard);
+ await until(() => cloud.link.linked().length === 0, "the Cloud drops the computer's bots");
+ });
+
+ it("a place on the first version is sent only what that version reads, and a place on this one the bots' looks too", async () => {
+ const looks = (bots: Bot[]) => bots.map((bot) => ({ ...bot, color: "green", mascotBody: "classic", threadId: `${bot.id}-chat` }));
+ const meet = async (computerVersion?: number, cloudVersion?: number) => {
+ const computer = place("computer", looks([{ id: "shared", name: "Scout" }]), computerVersion).boot(), cloud = place("cloud", looks([{ id: "shared", name: "Atlas" }]), cloudVersion).boot();
+ places.push(computer, cloud);
+ const origin = await cloud.listen();
+ await computer.listen();
+ await pair(computer, cloud, origin);
+ return { computer, cloud };
+ };
+ const seen = (side: ReturnType<typeof place>) => side.link.linked().map((one) => Object.keys(one.bot).sort().join());
+ const older = await meet(undefined, 1);
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(seen(older.cloud), "an older Cloud is sent no field it would refuse").toEqual(["id,level,name"]);
+ const olderApp = await meet(1, undefined);
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(seen(olderApp.computer), "an older app is sent no field it would refuse").toEqual(["id,level,name"]);
+ const both = await meet();
+ await until(() => seen(both.cloud)[0] === "color,id,level,mascotBody,name,threadId" && seen(both.computer)[0] === "color,id,level,mascotBody,name,threadId", "both on this version: each learns the other's looks, the computer after its first answer");
+ // Work crosses a mixed pair as it always did.
+ const { receipts } = await older.computer.handOff("shared", call(["Atlas"], "Count the orders"));
+ await until(() => older.cloud.runs.some((run) => run.botId === "shared"), "the older Cloud's bot gets the work");
+ expect(receipts[0]?.outcome).toBe("queued");
+ });
+
+ it("a hello whose bot id could not be a bot's own id is dropped whole, and such a bot of this place is never told", async () => {
+ const { computer, cloud } = await two();
+ const known = cloud.link.linked().map((one) => one.id);
+ for (const id of ["../../etc", "a/b", "a\\b", "a b", ".", "x".repeat(129), ""]) cloud.link.receive(COMPUTER, [{ t: "hello", place: { id: "computer-environment", name: "Sam's Mac" }, bots: [{ id, name: "Evil" }, { id: "fine", name: "Fine" }] }]);
+ expect(cloud.link.linked().map((one) => one.id)).toEqual(known);
+ computer.bots.push({ id: "../up", name: "Odd" }, { id: "plain_id-2", name: "Plain" });
+ computer.link.botsChanged();
+ await until(() => cloud.link.linked().some((one) => one.bot.name === "Plain"), "the Cloud hears of the bot with an ordinary id");
+ expect(cloud.link.linked().some((one) => one.bot.name === "Odd")).toBe(false);
+ });
+
it("the link's sign-in reaches the link's own routes and nothing else", () => {
const linked = { userId: "bot-link:computer-environment" };
expect(linkSessionRefusal(linked, "POST", SYNC_PATH)).toBeNull();
diff --git a/server/bot-link/link.ts b/server/bot-link/link.ts
index 553c8626de..4749917f15 100644
--- a/server/bot-link/link.ts
+++ b/server/bot-link/link.ts
@@ -102,7 +102,8 @@ const endedSchema = z.array(z.object({ origin: z.string(), token: z.string(), at
/** A link that was turned off while its Cloud could not be told: the Cloud is told when it can next be reached. */
export type EndedLink = z.infer<typeof endedSchema>[number];
-interface LocalBot { id: string; name: string; color?: string; hidden?: boolean; title?: string; description?: string; movedTo?: unknown }
+interface LocalBot { id: string; name: string; color?: string; hidden?: boolean; title?: string; description?: string; movedTo?: unknown;
+ mascotBody?: string | null; mascotFaceColor?: string | null; chiefOfStaff?: boolean; threadId?: string }
export interface BotLinkDeps {
dataDir: string;
@@ -133,6 +134,8 @@ export interface BotLinkDeps {
resultRow(parent: HandoffView, child: HandoffView, name: string): void;
/** The coordinator should look again: a place came back, or went. */
kick(): void;
+ /** The other places' bots changed: one came, went or changed, or a place was linked or unlinked. */
+ directoryChanged?(): void;
/** On the Cloud: ends the session a computer's link used. */
revoke?(sessionId: string): void;
now?: () => number;
@@ -152,7 +155,8 @@ export interface CoordinateContext {
}
type CoordinateResult = { status: number; body: Record<string, unknown> };
type Remote = { peer: string; bot: LinkedBot };
-type Live = { online: boolean; seq: number; outbox: Numbered[] };
+/** `level`: what that place's version reads (protocol.ts), 1 until it says more. `told`: the level its last hello was made for. */
+type Live = { online: boolean; seq: number; outbox: Numbered[]; level: number; told?: number };
export type BotLink = ReturnType<typeof createBotLink>;
@@ -183,12 +187,14 @@ export function createBotLink(deps: BotLinkDeps) {
let transfer: FileTransfer | null = null;
const save = () => { if (state) writeFileAtomic(file, JSON.stringify(state), { mode: 0o600 }); };
- const linkOf = (peer: string): Live => { let one = live.get(peer); if (!one) { one = { online: false, seq: 0, outbox: [] }; live.set(peer, one); } return one; };
+ 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).map((bot) => ({
+ const directory = (): LinkedBot[] => deps.bots().filter((bot) => !bot.hidden && !bot.movedTo && /^[\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.chiefOfStaff ? { chief: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}),
})).slice(0, 500);
function send(peer: string, frame: Frame): void {
@@ -197,7 +203,15 @@ export function createBotLink(deps: BotLinkDeps) {
one.outbox.push({ seq: ++one.seq, frame });
for (const listener of outboundListeners) listener(peer);
}
- const hello = (peer: string) => { if (state) { const bots = directory(); toldBots = JSON.stringify(bots); send(peer, { t: "hello", place: state.self, bots }); } };
+ /** A place on the first version takes a hello only with the fields that version knows. */
+ const basic = ({ id, name, title, description, model, level }: LinkedBot): LinkedBot => ({ id, name, ...(title ? { title } : {}), ...(description ? { description } : {}), ...(model ? { model } : {}), ...(level ? { level } : {}) });
+ const hello = (peer: string) => {
+ if (!state) return;
+ const bots = directory(), one = linkOf(peer);
+ toldBots = JSON.stringify(bots);
+ one.told = one.level;
+ send(peer, { t: "hello", place: state.self, bots: one.level >= 2 ? bots : bots.map(basic) });
+ };
const spoolRoot = join(deps.dataDir, SPOOL);
const spoolOf = (peer: string, id: string) => join(spoolRoot, createHash("sha256").update(`${peer}\0${id}`).digest("hex").slice(0, 32));
@@ -458,7 +472,7 @@ export function createBotLink(deps: BotLinkDeps) {
const known = state.peers[peer]!;
// A computer is the place it paired as: its name may change, its identity may not.
if (frame.place.id !== known.place.id) { log("bot link: a hello from another place than the one paired was dropped"); return; }
- if (JSON.stringify([frame.place, frame.bots]) !== JSON.stringify([known.place, known.bots])) { known.place = frame.place; known.bots = frame.bots; save(); deps.kick(); }
+ if (JSON.stringify([frame.place, frame.bots]) !== JSON.stringify([known.place, known.bots])) { known.place = frame.place; known.bots = frame.bots; save(); deps.kick(); deps.directoryChanged?.(); }
return;
}
case "handoff": return accept(peer, frame);
@@ -554,6 +568,7 @@ export function createBotLink(deps: BotLinkDeps) {
failPending(peer, reason);
if (Object.keys(state.peers).length === 0) { off(true); return; }
save();
+ deps.directoryChanged?.();
for (const listener of outboundListeners) listener(peer);
deps.kick();
}
@@ -583,6 +598,7 @@ export function createBotLink(deps: BotLinkDeps) {
failPending(null, "The link between this place and the person's other place was turned off before the work came back.");
for (const peer of peers) for (const listener of outboundListeners) listener(peer);
deps.kick();
+ deps.directoryChanged?.();
}
function receipt(remote: Remote, outcome: PeerDeliveryReceipt["outcome"], detail: string, more: Partial<PeerDeliveryReceipt> = {}): PeerDeliveryReceipt {
@@ -722,6 +738,8 @@ export function createBotLink(deps: BotLinkDeps) {
peers: Object.entries(state.peers).map(([peer, known]) => ({ ...known.place, online: isOnline(peer), bots: known.bots.length })),
bots: Object.values(state.peers).reduce((sum, known) => sum + known.bots.length, 0), waiting: pending.size }
: (() => { const ended = [...new Set(readEnded().map((one) => one.origin))]; return { on: false as const, ...(ended.length ? { ended } : {}) }; })()),
+ /** Every bot of every linked place, with its address here. */
+ linked: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), peer, place: known.place, online: isOnline(peer), bot }))),
/** Other places' bots as list_bots names them. */
agents: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), name: bot.name, section: "", model: bot.model ?? "", busy: false,
status: isOnline(peer) ? "linked" : "offline", statusText: isOnline(peer) ? `on ${known.place.name}` : `on ${known.place.name}, offline now: work for it waits until it is back`,
@@ -735,6 +753,7 @@ export function createBotLink(deps: BotLinkDeps) {
peers: { [key]: { place: input.peer, bots: kept?.peers[key]?.bots ?? [], seenAt: now() } }, threads: kept?.threads ?? {}, work: kept?.work ?? {} };
save();
deps.kick();
+ deps.directoryChanged?.();
},
/** On the Cloud: one computer is paired. The session its link used before is returned, for the caller to end; other
* computers' links are left as they are. Null when no more computers fit. */
@@ -747,6 +766,7 @@ export function createBotLink(deps: BotLinkDeps) {
state.peers[key] = { place: input.computer, bots: known?.place.id === input.computer.id ? known.bots : [], sessionId: input.sessionId, seenAt: now() };
save();
deps.kick();
+ deps.directoryChanged?.();
return { peer: key, ...(known?.sessionId ? { replaced: known.sessionId } : {}) };
},
/** On the Cloud: one computer's link ends (all of them when none is named). */
@@ -774,6 +794,14 @@ export function createBotLink(deps: BotLinkDeps) {
/** This place's bots changed: connected places hear the new list. */
botsChanged(): void { if (state && JSON.stringify(directory()) !== toldBots) for (const [peer, one] of live) if (one.online) hello(peer); },
setOnline,
+ /** What that place's version reads, as its last exchange said. One that turns out to read more than its last hello
+ * was made for is told again, in full. */
+ setLevel(peer: string, level: number): void {
+ if (!state?.peers[peer]) return;
+ const one = linkOf(peer);
+ one.level = level;
+ if (one.told !== undefined && level > one.told) hello(peer);
+ },
/** A computer's way to move a file's bytes, while it has one. */
setTransfer(next: FileTransfer | null): void { transfer = next; },
/** On the Cloud: whether a file a computer is about to put is one it need not send: the Cloud has its bytes, or the
diff --git a/server/bot-link/protocol.ts b/server/bot-link/protocol.ts
index cff3355b88..4db18005da 100644
--- a/server/bot-link/protocol.ts
+++ b/server/bot-link/protocol.ts
@@ -18,6 +18,8 @@ export const handoffOfRoot = (rootId: string): string => rootId.slice(LINK_PREFI
export const SYNC_PATH = "/api/bot-link/sync";
export const PAIR_PATH = "/api/bot-link/pair";
export const STATE_PATH = "/api/bot-link";
+/** The other places' bots, for the app on this computer to list beside this place's own. */
+export const BOTS_PATH = "/api/bot-link/bots";
/** One file of a hand-off or of its result, as bytes: the computer puts the ones it sends and gets the ones it is sent. */
export const FILE_PATH = "/api/bot-link/file";
/** As many as one assignment may carry in all (server/host/handoff-files.ts). */
@@ -36,14 +38,25 @@ export const BRIEF_MAX = 12_000;
const RESULT_MAX = 200_000;
const id = z.string().min(1).max(200);
+/** A bot's own id, in the characters every place gives its bots. A stand-in's address is made from it, and nothing with
+ * a path separator, a dot or a space can ever be one: a hello that carries such an id is dropped whole. */
+const botId = z.string().regex(/^[\w-]{1,128}$/u);
+/** What each side can read, said in a header on every exchange (older versions ignore a header they do not know). A side
+ * sends the other only what its level reads. 1: the first version, whose hello takes a bot's id, name, title,
+ * description, model and level and nothing else. 2: a bot's look, Chief mark and own thread too. */
+export const LEVEL_HEADER = "x-omb-bot-link";
+export const PROTOCOL_LEVEL = 2;
+export const levelOf = (header: string | string[] | null | undefined): number => { const said = Number(Array.isArray(header) ? header[0] : header); return Number.isInteger(said) && said >= 1 ? Math.min(said, PROTOCOL_LEVEL) : 1; };
const name = z.string().trim().min(1).max(120);
export const placeSchema = z.object({ id, name }).strict();
export type Place = z.infer<typeof placeSchema>;
const level = z.enum(["ask", "edits", "auto", "full", "custom"]);
export const linkedBotSchema = z.object({
- id, name, title: z.string().max(200).optional(), description: z.string().max(400).optional(), model: z.string().max(200).optional(), level: level.optional(),
-}).strict();
+ 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(), chief: z.boolean().optional(), threadId: botId.optional(),
+});
export type LinkedBot = z.infer<typeof linkedBotSchema>;
export const fileMeta = z.object({ name: z.string().min(1).max(255), mime: z.string().max(200), kind: z.enum(["image", "file"]), bytes: z.number().int().nonnegative() }).strict();
diff --git a/server/bot-moves.test.ts b/server/bot-moves.test.ts
index 2ab2a7a14a..f7d38b00e2 100644
--- a/server/bot-moves.test.ts
+++ b/server/bot-moves.test.ts
@@ -145,3 +145,10 @@ describe("a bot moving from this computer to My Cloud", () => {
expect("refused" in moves.back("pip")).toBe(true);
});
});
+
+it("a bot that lives in another of the person's places takes no turn here, and says where it lives", () => {
+ const standIn = { name: "Atlas", home: { place: "ab12cd34", placeName: "My Cloud", botId: "b1" } };
+ expect(botMoveRefusal(standIn)).toBe("Atlas lives on My Cloud: its turns run there, not here.");
+ expect(() => assertBotHere(standIn)).toThrow(/lives on My Cloud/);
+ expect(botMoveRefusal({ name: "Scout" })).toBeNull();
+});
diff --git a/server/bot-moves.ts b/server/bot-moves.ts
index 3416159d6d..9eae457e86 100644
--- a/server/bot-moves.ts
+++ b/server/bot-moves.ts
@@ -31,14 +31,15 @@ type Team = BotMovedTo["team"];
type Held = BotMovedTo & { held?: string[] };
/** Why this bot takes no turn here, or null. */
-export function botMoveRefusal(bot: Pick<BotRecord, "name"> & { movedTo?: BotMovedTo } | null | undefined): string | null {
+export function botMoveRefusal(bot: Pick<BotRecord, "name"> & { movedTo?: BotMovedTo; home?: BotRecord["home"] } | null | undefined): string | null {
+ if (bot?.home) return `${bot.name} lives on ${bot.home.placeName}: its turns run there, not here.`;
const moved = bot?.movedTo;
if (!moved) return null;
return moved.state === "moved" ? `${bot!.name} lives in ${moved.team.name} now.` : `${bot!.name} is moving to ${moved.team.name}. It's ready there in a moment.`;
}
/** A turn of this bot starts here only while it is not moving or moved. */
-export function assertBotHere(bot: Pick<BotRecord, "name"> & { movedTo?: BotMovedTo } | null | undefined): void {
+export function assertBotHere(bot: Pick<BotRecord, "name"> & { movedTo?: BotMovedTo; home?: BotRecord["home"] } | null | undefined): void {
const said = botMoveRefusal(bot);
if (said) throw Object.assign(new Error(said), { status: 409, code: "moved" });
}
diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.ts
index fc5fa202c0..011888a841 100644
--- a/server/host/bot-link-host.ts
+++ b/server/host/bot-link-host.ts
@@ -9,6 +9,7 @@ import type { Coordinator, HandoffView } from "../coordinator.ts";
import { redactSecretsInText } from "../redact.ts";
import type { RequestAuth } from "../request-auth.ts";
import { createBotLinkRoutes, linkSessionUser } from "../routes/bot-link.ts";
+import { isLinkedId } from "../bot-link/protocol.ts";
import type { Level } from "../runtime/types.ts";
import type { BotRecord, Store } from "../store.ts";
import type { HandoffFiles, PassedFile } from "./handoff-files.ts";
@@ -17,7 +18,7 @@ import { sentRow, teammateResultRow } from "./handoff-sent.ts";
export interface BotLinkHostDeps {
dataDir: string;
environmentId: string;
- store: Pick<Store, "bots" | "bot" | "createTask" | "taskByThread" | "appendMessage" | "patchTask" | "onChange" | "group" | "groupTaskByThread" | "markGroupThreadUnread">;
+ store: Pick<Store, "bots" | "bot" | "standIns" | "createTask" | "taskByThread" | "appendMessage" | "patchTask" | "onChange" | "group" | "groupTaskByThread" | "markGroupThreadUnread">;
coordinator(): Coordinator;
kick(): void;
level(bot: BotRecord): Level;
@@ -36,8 +37,20 @@ export interface BotLinkHostDeps {
export function createBotLinkHost(deps: BotLinkHostDeps) {
const { store } = deps;
+ /** Each bot of each linked place as a record this place finds by its address: its name and look, and where it lives.
+ * It has no conversation, model or tools here, and takes no turn here. */
+ const syncStandIns = () => {
+ const next = new Map<string, BotRecord>();
+ for (const { id, peer, place, bot } of link.linked()) {
+ next.set(id, { id, name: bot.name, color: bot.color ?? "blue", threadId: "", tasks: [], resumeCursors: {}, modelSelection: { instanceId: "", model: bot.model ?? "" },
+ home: { place: peer, placeName: place.name, botId: bot.id }, ...(bot.title ? { title: bot.title } : {}), ...(bot.description ? { description: bot.description } : {}),
+ ...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}) } as unknown as BotRecord);
+ }
+ store.standIns.clear();
+ for (const [id, record] of next) if (isLinkedId(id)) store.standIns.set(id, record);
+ };
const link = createBotLink({
- dataDir: deps.dataDir, coordinator: deps.coordinator, kick: deps.kick, log: deps.log, revoke: (sessionId) => { deps.sessions.revoke(sessionId); },
+ dataDir: deps.dataDir, coordinator: deps.coordinator, kick: deps.kick, log: deps.log, directoryChanged: () => syncStandIns(), revoke: (sessionId) => { deps.sessions.revoke(sessionId); },
bots: () => store.bots, bot: (id) => store.bot(id),
refusal: (bot) => deps.refusal(bot as BotRecord),
model: (bot) => (bot as BotRecord).modelSelection.model,
@@ -94,6 +107,7 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {
/** Once the server is up. Off: nothing. On, on the computer: it starts asking the Cloud. */
start(): void {
if (!link.on()) return;
+ syncStandIns();
watch();
link.tidy();
if (link.role() === "dialer") dialer.start({ gentle: true });
diff --git a/server/host/stand-in-guard.ts b/server/host/stand-in-guard.ts
new file mode 100644
index 0000000000..a159be273b
--- /dev/null
+++ b/server/host/stand-in-guard.ts
@@ -0,0 +1,43 @@
+// A stand-in (server/host/bot-link-host.ts) is the record of a bot that lives in another of the person's places. On this
+// place it is read-only: nothing here changes it, deletes it, or gives it a thread, a room or an automation of its own.
+// The store's write methods look only among this place's own bots; this is the same rule at the door, so a request that
+// names a stand-in where a bot is changed is answered with where that bot lives instead of half-doing something.
+import { botMoveRefusal } from "../bot-moves.ts";
+
+type StandIn = { name: string; home?: { place: string; placeName: string; botId: string } };
+
+const READS = new Set(["GET", "HEAD", "OPTIONS"]);
+const decoded = (value: string): string => { try { return decodeURIComponent(value); } catch { return value; } };
+
+/** The stand-in a request that changes something names in its path or its query, if any. With no stand-in on this place
+ * (the link is off) this looks at nothing. The link's own routes are not bot routes and are left to the link. */
+export function standInNamed(standIns: ReadonlyMap<string, StandIn>, method: string, url: URL): StandIn | null {
+ if (standIns.size === 0 || READS.has(method)) return null;
+ const path = url.pathname;
+ if (!path.startsWith("/api/") || path === "/api/bot-link" || path.startsWith("/api/bot-link/")) return null;
+ for (const segment of path.split("/")) {
+ const named = segment ? standIns.get(decoded(segment)) : undefined;
+ if (named) return named;
+ }
+ for (const value of url.searchParams.values()) {
+ const named = standIns.get(value);
+ if (named) return named;
+ }
+ return null;
+}
+
+/** The answer such a request gets: where the bot lives, in the words a turn for it is refused with. */
+export function standInWriteRefusal(standIns: ReadonlyMap<string, StandIn>, method: string, url: URL): { error: string; code: "moved" } | null {
+ const named = standInNamed(standIns, method, url);
+ return named ? { error: botMoveRefusal(named) ?? `${named.name} lives in another place.`, code: "moved" } : null;
+}
+
+/** The first stand-in among ids a request's body names (a room's members, an automation's bot), or null. */
+export function standInAmong(standIns: ReadonlyMap<string, StandIn>, ids: readonly unknown[]): { error: string } | null {
+ if (standIns.size === 0) return null;
+ for (const id of ids) {
+ const named = typeof id === "string" ? standIns.get(id) : undefined;
+ if (named) return { error: botMoveRefusal(named) ?? `${named.name} lives in another place.` };
+ }
+ return null;
+}
diff --git a/server/index.ts b/server/index.ts
index 1d7b932a44..b3f3998d2d 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -584,7 +584,7 @@ import { PhoneSecretBridge, PhoneSecretSubmissionRegistry } from "./phone-secret
// Keep these two last, so loading the route table leaves module start-up order as is.
import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";
import { holdBodyDeadline } from "./body-deadline.ts";
-import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createBotLinkHost } from "./host/bot-link-host.ts"; import { isBotLinkHeldPath, linkSessionRefusal } from "./routes/bot-link.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
+import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createBotLinkHost } from "./host/bot-link-host.ts"; import { standInAmong, standInWriteRefusal } from "./host/stand-in-guard.ts"; import { isBotLinkHeldPath, linkSessionRefusal } from "./routes/bot-link.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";
import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerStore, workspaceBannerSummary } from "./routes/workspace-banner.ts";
import { createBotMemoryRoutes } from "./routes/bot-memory.ts";
@@ -2242,7 +2242,7 @@ function canAdmitDirectTurn(botId: string, threadId: string): boolean {
}
function unattendedDispatchState(botId: string): "ready" | "busy" | "missing" {
- const bot = store.bot(botId);
+ const found = store.bot(botId), bot = found?.home ? null : found; // A stand-in takes no automation here: its bot lives in another place.
const decision = admit("unattended", {}, {
botPresent: Boolean(bot),
atCapacity: Boolean(bot) && botAtThreadCapacity(botId),
@@ -2780,7 +2780,7 @@ function checkedMemberIds(value: unknown): { ok: true; memberIds: string[] } | {
if (invalidIndex !== -1) {
return { ok: false, error: `unknown channel member: ${String(value[invalidIndex])}` };
}
- const memberIds = [...new Set(value as string[])];
+ const memberIds = [...new Set(value as string[])]; const elsewhere = standInAmong(store.standIns, memberIds); if (elsewhere) return { ok: false, error: elsewhere.error };
if (!memberIds.length) return { ok: false, error: "a channel needs at least one bot" };
if (memberIds.every((id) => store.bot(id)?.hidden)) {
return {
@@ -2922,7 +2922,7 @@ const wireTask = (task: TaskRecord, botModel: ModelSelection, awaiting = threads
/** Strips provider session ids (resumeCursors) here, not at call sites, so no broadcast or paired phone ever gets them. */
const wireBot = (bot: BotRecord, onlyThreadId?: string): WireBot => {
- const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, ...rest } = bot;
+ const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, home: _home, ...rest } = bot;
// Clients see Ask while an elevated grant awaits the desktop's confirmation, never a grant that may still roll back.
const visible = approvalGrant && !approvalGrant.threadOnly
? { ...rest, approvalMode: "ask" as const, autoApprove: false }
@@ -2942,7 +2942,7 @@ function toolScopeForTurn(botId: string) {
}
const wireTrustedApprovalBot = (bot: NonNullable<ReturnType<typeof store.bot>>) => {
- const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, ...rest } = bot;
+ const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, home: _home, ...rest } = bot;
const awaiting = threadsAwaitingTeammates();
return { ...rest, approvalMode: approvalModeFor(rest), mainThreadId: botMainThread(bot.id), avatarUrl: rest.avatarUrl ?? null, ...(tasks ? { tasks: tasks.map((task) => wireTask(task, bot.modelSelection, awaiting)) } : {}) };
};
@@ -7207,7 +7207,7 @@ class DirectSendRefused extends Error {
}
}
-function directSendRefusal(botId: string, threadId: string): DirectSendRefused | null {
+function directSendRefusal(botId: string, threadId: string): DirectSendRefused | null { const standIn = store.standIns.get(botId); if (standIn) return new DirectSendRefused(409, { error: botMoveRefusal(standIn)!, code: "moved" });
try {
assertWithinBudget(cfg, DATA_DIR);
} catch (error) {
@@ -9017,7 +9017,7 @@ const memberOwnBot = createMemberOwnBot({ store: () => store, routines: () => ro
async function deleteBotWithLifecycle(botId: string, revalidate: () => void = () => {}, setupRequest?: TeamSetupRequest) {
const deletionResponse = (status: number, body: { error?: string; ok?: boolean; notice?: string }) => ({ status, body });
revalidate();
- const bot = store.bot(botId);
+ const bot = store.bot(botId); if (bot?.home) return deletionResponse(409, { error: botMoveRefusal(bot)! });
if (!bot) return deletionResponse( 404, { error: "no such bot" }); if (bot.defaultBot) return deletionResponse(409, { error: defaultBotRefusal(bot.name) });
const heldRefusal = sharedVm.deletionRefusal(bot.id); if (heldRefusal) return deletionResponse(409, { error: heldRefusal });
if (computerProviderConfigTransitions.size > 0) {
@@ -12708,7 +12708,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
// Route modules are tried here, behind the gate; do not add route `if`s below.
- if (await dispatchRoutes(ROUTES, { req, res, url, path, method, auth, json, readBody })) return;
+ const standInRefused = standInWriteRefusal(store.standIns, method, url); if (standInRefused) { req.resume(); return json(res, 409, standInRefused); } if (await dispatchRoutes(ROUTES, { req, res, url, path, method, auth, json, readBody })) return;
if (method === "GET" && path === "/api/auth/session") {
return json(
@@ -14519,7 +14519,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
});
}
const routineBodyRefusal = (body: unknown, existing?: Routine): { status: number; error: string } | null => {
- const hidden = hiddenRoutineTarget(body, visible), notYours = teamRoutines.bodyRefusal(auth, body);
+ const hidden = hiddenRoutineTarget(body, visible), notYours = teamRoutines.bodyRefusal(auth, body), elsewhere = standInAmong(store.standIns, [(body as { botId?: unknown } | null)?.botId]); if (elsewhere) return { status: 409, error: elsewhere.error };
return hidden ? { status: 404, error: hidden } : notYours ?? routineModelRefusal(body, routineModelChecks, existing);
};
if (path === "/api/routines" && method === "POST") {
diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.ts
index e858a477d4..06c9938ca5 100644
--- a/server/routes/bot-link.ts
+++ b/server/routes/bot-link.ts
@@ -18,7 +18,7 @@ import { z } from "zod";
import type { createDialer } from "../bot-link/dial.ts";
import type { BotLink } from "../bot-link/link.ts";
-import { FILE_PATH, PAIR_PATH, SEEN_MS, STATE_PATH, SYNC_PATH, fileWay, placeSchema, syncRequest } from "../bot-link/protocol.ts";
+import { BOTS_PATH, FILE_PATH, LEVEL_HEADER, PAIR_PATH, PROTOCOL_LEVEL, SEEN_MS, STATE_PATH, SYNC_PATH, fileWay, levelOf, placeSchema, syncRequest } from "../bot-link/protocol.ts";
import { FILE_MAX_BYTES } from "../../shared/upload-limits.ts";
import { answerAsleep } from "../cloud-power.ts";
import type { RequestAuth } from "../request-auth.ts";
@@ -64,6 +64,8 @@ export interface BotLinkRouteDeps {
/** The link was turned on here. */
turnedOn?(): void;
seenMs?: number;
+ /** What this place says its version reads; a test stands in for an older Cloud with it. */
+ level?: number;
}
export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {
@@ -91,9 +93,19 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {
const state = () => ({ ...link.status(), ...(link.role() === "dialer" ? dialer.state() : {}) });
return async ({ req, res, url, path, method, auth, json, readBody }) => {
- if (path !== STATE_PATH && path !== PAIR_PATH && path !== SYNC_PATH && path !== FILE_PATH) return PASS;
+ if (path !== STATE_PATH && path !== PAIR_PATH && path !== SYNC_PATH && path !== FILE_PATH && path !== BOTS_PATH) return PASS;
res.setHeader("cache-control", "no-store");
+ if (path === BOTS_PATH) {
+ req.resume();
+ if (!deps.local(auth)) return json(res, 403, { error: "Only the app on this computer lists its other places' bots." });
+ if (method !== "GET") return json(res, 405, { error: "method not allowed" });
+ // Names and looks only, as each place told this one: no message, address or sign-in.
+ return json(res, 200, { bots: link.linked().map(({ id, place, online, bot }) => ({ id, home: { id: place.id, name: place.name, online }, botId: bot.id, name: bot.name,
+ ...(bot.title ? { title: bot.title } : {}), ...(bot.color ? { color: bot.color } : {}), ...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}),
+ ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}), ...(bot.chief ? { chiefOfStaff: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}) })) });
+ }
+
if (path === STATE_PATH) {
if (!deps.local(auth)) { req.resume(); return json(res, 403, { error: "Only the app on this computer can turn the link to the Cloud on or off." }); }
if (method === "GET") return json(res, 200, state());
@@ -178,6 +190,9 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {
const power = deps.power();
if (power?.sleeping()) return answerAsleep(res, json);
seen(peer);
+ // Each side says what its version reads; a computer on the first version says nothing and is sent only what that reads.
+ link.setLevel(peer, levelOf(req.headers[LEVEL_HEADER]));
+ if ((deps.level ?? PROTOCOL_LEVEL) > 1) res.setHeader(LEVEL_HEADER, String(deps.level ?? PROTOCOL_LEVEL));
if (body.data.fresh) link.sessionStarted(peer);
link.receive(peer, body.data.frames);
const linked = () => auth.kind === "session" && link.peerOfSession(auth.session.id) === peer;
diff --git a/server/store.test.ts b/server/store.test.ts
index 9932b19a94..84dc18ecad 100644
--- a/server/store.test.ts
+++ b/server/store.test.ts
@@ -199,6 +199,31 @@ describe("Store", () => {
.toEqual(JSON.parse(before).find((g: { id: string }) => g.id === room.id).memberIds);
});
+ it("a stand-in is read-only: no write method finds it, so naming one changes nothing of this place's own", () => {
+ const store = new Store(selection);
+ const chief = store.createBot({ section: "Delivery" });
+ store.setChiefOfStaff(chief.id);
+ store.patchBot(chief.id, { managedSections: ["Office"] });
+ const room = store.createGroup("Room", [chief.id], false, "Delivery");
+ const id = "link-0a1b2c3d-atlas";
+ store.standIns.set(id, { id, name: "Atlas", color: "blue", threadId: "", tasks: [], resumeCursors: {}, modelSelection: { instanceId: "", model: "" }, section: "Delivery", home: { place: "0a1b2c3d", placeName: "My Cloud", botId: "atlas" } } as unknown as BotRecord);
+ const bots = readFileSync(join(DATA_DIR, "bots.json"), "utf8"), groups = readFileSync(join(DATA_DIR, "groups.json"), "utf8");
+ const changes: string[] = [];
+ store.onChange((change) => { changes.push(change.type); });
+ expect(store.bot(id)?.name).toBe("Atlas");
+ expect(store.setChiefOfStaff(id)).toBeNull();
+ expect(store.bot(chief.id)).toMatchObject({ chiefOfStaff: true, managedSections: ["Office"] });
+ expect(store.deleteBot(id)).toBe(false);
+ expect(store.patchBot(id, { name: "Renamed" })).toBeNull();
+ expect(store.createTask(id, "A thread")).toBeFalsy();
+ expect(store.tasks(id)).toEqual([]);
+ expect(store.standIns.get(id)).toMatchObject({ name: "Atlas", tasks: [] });
+ expect(store.group(room.id)?.memberIds).toEqual([chief.id]);
+ expect(changes).toEqual([]);
+ expect(readFileSync(join(DATA_DIR, "bots.json"), "utf8")).toBe(bots);
+ expect(readFileSync(join(DATA_DIR, "groups.json"), "utf8")).toBe(groups);
+ });
+
it("renames populated teams without changing members, conversations, grants or computer identity", () => {
const store = new Store(selection);
const chief = store.createBot({ section: "Delivery" });
diff --git a/server/store.ts b/server/store.ts
index f9d8fa6f89..1f58ac134c 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -156,7 +156,7 @@ export function titleFromLlm(raw: string): string | null {
export interface BotRecord extends Omit<WireBot, "avatarUrl" | "tasks"> {
tasks?: TaskRecord[];
avatarUrl?: string;
- resumeCursors: Record<string, unknown>; mainThreadChoice?: string; // mainThreadChoice ("Set as main thread") is host-only; clients get mainThreadId.
+ resumeCursors: Record<string, unknown>; /** Set on a stand-in: the place this bot lives in, and its id there. */ home?: { place: string; placeName: string; botId: string }; mainThreadChoice?: string; // mainThreadChoice ("Set as main thread") is host-only; clients get mainThreadId.
/** Elevation journal: Full/Custom runs as Ask until Electron confirms the prepared reply; a marker surviving a restart is revoked on load. */
approvalGrant?: {
requestId: string;
@@ -173,7 +173,7 @@ export interface BotRecord extends Omit<WireBot, "avatarUrl" | "tasks"> {
assignedSkills?: string[];
}
-export type BotWirePrivateKeys = "resumeCursors" | "mainThreadChoice" | "tasks" | "avatarUrl" | "approvalGrant" | "lastProfileRequestId" | "lastTeamSetupReceipt" | "packageBase" | "assignedSkills";
+export type BotWirePrivateKeys = "resumeCursors" | "home" | "mainThreadChoice" | "tasks" | "avatarUrl" | "approvalGrant" | "lastProfileRequestId" | "lastTeamSetupReceipt" | "packageBase" | "assignedSkills";
export type BotWireProjection = Pick<BotRecord, Exclude<keyof BotRecord, BotWirePrivateKeys>>;
export type BotWireProjectionIsExact = AssertExact<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection> & AssertSameKeys<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection>;
export const botWireProjectionIsExact: BotWireProjectionIsExact = true;
@@ -273,7 +273,7 @@ function taskCountsAsBotUnread(task: { unread?: boolean; routineRunId?: string }
}
export class Store {
- bots: BotRecord[] = [];
+ bots: BotRecord[] = []; /** Bots that live in another of the person's places (server/bot-link/), by their address here: found by id, never listed, counted, saved, moved or backed up. */ standIns = new Map<string, BotRecord>();
groups: GroupRecord[] = []; /** Told before a delete of these conversations is tried; "thread.deleted" follows only for those that went. Must not throw. */ threadsGoing: (threadIds: readonly string[]) => void = () => {};
private threads = new ThreadCache(() => this.busyThreadIds());
private defaultSelection: () => ModelSelection;
@@ -1279,7 +1279,7 @@ export class Store {
}
bot(id: string) {
- return this.bots.find((b) => b.id === id) ?? null;
+ return this.bots.find((b) => b.id === id) ?? this.standIns.get(id) ?? null; } /** One of this place's own bots. Every method that changes a bot looks here and never among the stand-ins: a record with `home` is read-only on this place. */ private own(id: string) { return this.bots.find((b) => b.id === id) ?? null;
}
botByThread(threadId: string) {
@@ -1356,7 +1356,7 @@ export class Store {
}
applyTeamSetup(request: TeamSetupRequest): TeamSetupResult {
- const chief = this.bot(request.botId);
+ const chief = this.own(request.botId);
if (!chief) throw new Error("The requesting Chief no longer exists");
if (chief.lastTeamSetupReceipt?.requestId === request.requestId) return chief.lastTeamSetupReceipt.result;
const managedSections = [...new Set([...(chief.managedSections ?? []), ...request.newTeams])];
@@ -1436,7 +1436,7 @@ export class Store {
}
applyModelDefault(id: string, modelSelection: ModelSelection): BotRecord | null {
- const previous = this.bot(id);
+ const previous = this.own(id);
if (!previous) return null;
const next: BotRecord = { ...previous, modelSelection: structuredClone(modelSelection), tasks: this.withDefaultModel(previous, modelSelection) };
this.saveBots(this.bots.map((candidate) => candidate.id === id ? next : candidate));
@@ -1446,12 +1446,12 @@ export class Store {
}
deleteBot(id: string, setupRequest?: TeamSetupRequest): boolean {
- const bot = this.bot(id);
+ const bot = this.own(id);
if (!bot) return false;
if (bot.defaultBot) throw Object.assign(new Error(defaultBotRefusal(bot.name)), { status: 409 });
let nextBots = this.bots.filter((b) => b.id !== id); this.threadsGoing([bot.threadId, ...(bot.tasks ?? []).map((t) => t.threadId)]);
if (setupRequest) {
- const chief = this.bot(setupRequest.botId);
+ const chief = this.own(setupRequest.botId);
if (!chief || chief.id === id || setupRequest.deletion?.botId !== id) throw new Error("The reviewed deletion no longer has a valid owner");
const lastTeamSetupReceipt: NonNullable<BotRecord["lastTeamSetupReceipt"]> = { requestId: setupRequest.requestId, result: { state: "applied", newTeams: [], bots: [
{ id: bot.id, name: bot.name, action: "deleted" },
@@ -1492,7 +1492,7 @@ export class Store {
}
patchBot(id: string, patch: Partial<BotRecord>): BotRecord | null {
- const bot = this.bot(id);
+ const bot = this.own(id);
if (!bot) return null; patch = reshowWhenMoved(bot, patch);
if (patch.connectorTools !== undefined) {
const parsed = parseConnectorTools(patch.connectorTools);
@@ -1547,7 +1547,7 @@ export class Store {
}
patchBotProfile(id: string, patch: BotProfilePatch & Partial<Pick<BotRecord, "cwd" | "browserProfile" | "lastProfileRequestId">>): BotRecord | null {
- const bot = this.bot(id);
+ const bot = this.own(id);
if (!bot) return null;
const next = { ...bot, ...reshowWhenMoved(bot, patch) };
if (patch.soul !== undefined) {
@@ -1574,7 +1574,7 @@ export class Store {
section: string,
): { ok: true; bots: BotRecord[] } | { ok: false; reason: "unavailable" | "chief-conflict" } {
const ids = [...new Set(botIds)];
- const targets = ids.map((id) => this.bot(id));
+ const targets = ids.map((id) => this.own(id));
if (targets.some((bot) => !bot || bot.hidden)) return { ok: false, reason: "unavailable" };
const targetSection = sectionKey(section);
@@ -1602,7 +1602,7 @@ export class Store {
for (const botId of changedIds) this.emit({ type: "bot", botId });
}
this.rememberSections([targetSection]);
- return { ok: true, bots: ids.map((id) => this.bot(id)!) };
+ return { ok: true, bots: ids.map((id) => this.own(id)!) };
}
updateTeamMembers(section: string, addIds: string[], removeIds: string[]):
@@ -1612,7 +1612,7 @@ export class Store {
const adds = new Set(addIds), removes = new Set(removeIds);
const ids = new Set([...adds, ...removes]);
for (const id of ids) {
- const bot = this.bot(id);
+ const bot = this.own(id);
if (!bot || bot.hidden) return { ok: false, reason: "unavailable" };
if (adds.has(id) && removes.has(id)) return { ok: false, reason: "membership-changed" };
if (removes.has(id) && sectionKey(bot.section) !== key) return { ok: false, reason: "membership-changed" };
@@ -1629,7 +1629,7 @@ export class Store {
}
setActivity(botId: string, activity: BotActivity): BotRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot) return null;
if ((this.legacyActivities.get(botId) ?? "idle") === activity) return bot;
this.legacyActivities.set(botId, activity);
@@ -1639,7 +1639,7 @@ export class Store {
}
setTaskActivity(botId: string, threadId: string, activity: BotActivity, noTurnRunning = false): BotRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
const busy = ACTIVITY_BUSY.has(activity) && !noTurnRunning;
@@ -1668,7 +1668,7 @@ export class Store {
/** Makes `id` its scope's one Chief (its owner's on a Team Cloud, else its department's), or with no `id` leaves
* `section` without one. */
setChiefOfStaff(id: string | null, section?: string | null): BotRecord[] | null {
- const selected = id ? this.bot(id) : null;
+ const selected = id ? this.own(id) : null;
if (id && !selected) return null;
const scope = selected ? chiefScope(selected) : chiefScope({ section: section ?? undefined });
const changed: BotRecord[] = [];
@@ -1807,7 +1807,7 @@ export class Store {
}
setResumeCursor(botId: string, instanceId: string, cursor: unknown, threadId?: string) {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot) return;
const task = threadId ? this.taskByThread(botId, threadId) : this.activeTask(botId), mirrored = !threadId || bot.threadId === threadId;
if (isDeepStrictEqual(task?.resumeCursors[instanceId], cursor) && (!mirrored || isDeepStrictEqual(bot.resumeCursors[instanceId], cursor))) return;
@@ -1881,7 +1881,7 @@ export class Store {
}
pinTaskCwd(botId: string, threadId: string, fallbackCwd?: string, opts: { none?: boolean; privateOnly?: boolean } = {}): string | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = bot ? this.taskByThread(botId, threadId) : undefined;
if (!bot || !task) return null;
if (opts.privateOnly && task.cwd === undefined) {
@@ -1928,11 +1928,11 @@ export class Store {
}
project(botId: string, projectId: string): BotProjectRecord | undefined {
- return this.bot(botId)?.projects?.find((project) => project.id === projectId);
+ return this.own(botId)?.projects?.find((project) => project.id === projectId);
}
createProject(botId: string, name: string, emoji?: string | null): BotProjectRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot || !name.trim() || (emoji != null && !isProjectEmoji(emoji))) return null;
const project: BotProjectRecord = {
id: newId(), name: name.trim().slice(0, 80),
@@ -1956,7 +1956,7 @@ export class Store {
}
reorderProjects(botId: string, projectIds: string[]): BotProjectRecord[] | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const projects = bot?.projects ?? [];
if (!bot || projectIds.length !== projects.length || new Set(projectIds).size !== projects.length) return null;
const byId = new Map(projects.map((project) => [project.id, project]));
@@ -1982,7 +1982,7 @@ export class Store {
}
deleteProject(botId: string, projectId: string): BotRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot || !this.project(botId, projectId)) return null;
bot.projects = bot.projects!.filter((project) => project.id !== projectId);
for (const task of bot.tasks ?? []) {
@@ -1999,16 +1999,16 @@ export class Store {
}
tasks(botId: string): TaskRecord[] {
- return this.bot(botId)?.tasks ?? [];
+ return this.own(botId)?.tasks ?? [];
}
activeTask(botId: string): TaskRecord | undefined {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
return bot?.tasks?.find((t) => t.threadId === bot.threadId);
}
taskByThread(botId: string, threadId: string): TaskRecord | undefined {
- return this.bot(botId)?.tasks?.find((t) => t.threadId === threadId);
+ return this.own(botId)?.tasks?.find((t) => t.threadId === threadId);
}
workThread(botId: string, fromBotId: string, fromThreadId: string, roomLane = false, also: (task: TaskRecord) => boolean = () => true): TaskRecord | undefined {
@@ -2017,7 +2017,7 @@ export class Store {
}
projectBotForTask(botId: string, threadId: string): BotRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
return {
@@ -2036,7 +2036,7 @@ export class Store {
}
patchTask(botId: string, threadId: string, patch: TaskPatch, options: { turnEnd?: true } = {}): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
if (patch.projectId !== undefined && !this.project(botId, patch.projectId)) return null;
@@ -2066,7 +2066,7 @@ export class Store {
}
clearAutoSurfacePins(botId: string, destination: Destination): number {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const stale = bot?.tasks?.filter((task) => task.surface !== undefined && task.surfaceSource === "auto" && task.surface !== destination) ?? [];
if (!bot || !stale.length) return 0;
this.commitBotChange(bot, "the threads' destinations", () => {
@@ -2082,7 +2082,7 @@ export class Store {
/** One write: never publish a new provider before its approval downgrade. */
switchTaskModel(botId: string, threadId: string, selection: ModelSelection,
updateBotDefault: boolean, resetApprovalToAsk: boolean, taskPatch: TaskPatch = {}): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
const approval = resetApprovalToAsk ? structuredClone(ASK_NOW) : {};
@@ -2101,7 +2101,7 @@ export class Store {
followBotModel(botId: string, threadIds: readonly string[],
reset: (from: ModelSelection, to: ModelSelection) => Partial<TaskRecord> = () => ({})): string[] {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot?.tasks) return [];
const listed = new Set(threadIds);
const patches = bot.tasks.map((task): Partial<TaskRecord> | null => !listed.has(task.threadId) || task.modelSelection === undefined ? null : {
@@ -2121,7 +2121,7 @@ export class Store {
}
setAllThreadApprovalMode(botId: string, mode: Exclude<ApprovalMode, "custom">): BotRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot) return null;
const patch = { approvalMode: mode, autoApprove: mode === "auto" }; // saved grants stay through Full access, unused there, so a later Ask keeps them
const tasks = (bot.tasks ?? []).map(task => ({ ...task, ...patch }));
@@ -2135,7 +2135,7 @@ export class Store {
/** Rewrites the bot's own "Always allow" list and each of its threads' in one save (always-allow.ts). */
rewriteGrants(botId: string, rewrite: GrantRewrite, removal = false): boolean {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot || !rewriteGrantLists(bot, rewrite, () => this.saveBots(), removal)) return false;
this.emit({ type: "bot", botId });
return true;
@@ -2143,7 +2143,7 @@ export class Store {
/** An uncommitted grant is ignored, so a refresh cannot copy the temporary Ask mask. */
refreshTaskPermissions(botId: string, threadId: string): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
const mode = approvalModeFor({ ...bot, approvalGrant: undefined });
@@ -2163,7 +2163,7 @@ export class Store {
createTask(botId: string, title?: string, activate = true, projectId?: string, openedBy?: TaskOpenedBy, approvalMode?: "ask" | "full",
modelSelection?: ModelSelection, cwd?: string, beforeShown?: (task: TaskRecord) => void): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot) return null;
if (projectId !== undefined && !this.project(botId, projectId)) return null;
const task = buildTask(bot, title, projectId, openedBy, approvalMode, modelSelection, cwd);
@@ -2176,7 +2176,7 @@ export class Store {
}
forkTask(botId: string, sourceThreadId: string, messageId: string): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const source = this.taskByThread(botId, sourceThreadId);
if (!bot || !source) return null;
const sourceView = this.projectBotForTask(botId, sourceThreadId)!;
@@ -2188,7 +2188,7 @@ export class Store {
}
setTaskOpenedBy(botId: string, threadId: string, openedBy: TaskOpenedBy): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
this.commitBotChange(bot, "who opened the thread", () => { task.openedBy = structuredClone(openedBy); });
@@ -2206,7 +2206,7 @@ export class Store {
}
setTaskClosedBy(botId: string, threadId: string, closedBy: TaskClosedBy | null): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = this.taskByThread(botId, threadId);
if (!bot || !task) return null;
if (!closedBy && !task.closedBy) return task;
@@ -2219,7 +2219,7 @@ export class Store {
}
switchTask(botId: string, threadId: string): BotRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = bot?.tasks?.find((t) => t.threadId === threadId);
if (!bot || !task) return null;
this.commitBotChange(bot, "the thread switch", () => this.mirrorActiveTask(bot, task));
@@ -2232,7 +2232,7 @@ export class Store {
}
titleTaskFromFirstMessage(botId: string, text: string, threadId?: string): TaskRecord | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
const task = threadId ? this.taskByThread(botId, threadId) : this.activeTask(botId);
if (!bot || !task || task.titleFromFirstMessage || (task.title !== UNTITLED_TASK && task.title !== UNTITLED_THREAD)) return null;
this.commitBotChange(bot, "the thread's title", () => {
@@ -2256,7 +2256,7 @@ export class Store {
/** Transcript rows and bots.json commit together, so either failing leaves every task, log file and subscriber untouched. */
deleteTasks(botId: string, threadIds: string[]): { bot: BotRecord; deleted: string[]; missing: string[] } | null {
- const bot = this.bot(botId);
+ const bot = this.own(botId);
if (!bot?.tasks) return null;
const present = new Set(bot.tasks.map((t) => t.threadId));
const unique = [...new Set(threadIds)];