Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Hand work to teammates on other servers in coordinate_bots (#7014 step 2)
Bugfixer 2b1bb504a35f0
diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex 1cce865621..1a4c28bf55 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -20,7 +20,7 @@ import { z } from "zod";import { writeFileAtomic } from "../atomic.ts";import type { CoordinateBotsCall, Coordinator, CoordinatorHost, HandoffView, HostTurnResult } from "../coordinator.ts";import type { PassedFile } from "../host/handoff-files.ts";-import type { PeerDeliveryReceipt } from "../peer-delivery.ts";+import { foldName, withTargetsHere, type CoordinateResult, type PeerDeliveryReceipt } from "../peer-delivery.ts";import { isIdStart } from "../peer-roster.ts";import type { Level } from "../runtime/types.ts";import { BRIEF_MAX, EXCHANGE_BYTES, FILES_MAX, LINK_EXPIRES_MS, PEERS_MAX, frameSchema, handoffOfRoot, isLinkedId, linkRoot, linkedBotSchema, linkedId, parseLinked, peerKey, placeSchema,@@ -169,7 +169,6 @@ export interface CoordinateContext {problem?: string;handed(nodeId: string): void;}-type CoordinateResult = { status: number; body: Record<string, unknown> };type Remote = { peer: string; bot: LinkedBot };/** `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 };@@ -312,7 +311,6 @@ export function createBotLink(deps: BotLinkDeps) {const address = parseLinked(linked), bot = address ? state?.peers[address.peer]?.bots.find((one) => one.id === address.botId) : undefined;return address && bot ? { peer: address.peer, bot } : undefined;};- const fold = (value: string) => value.replace(/^@/u, "").replace(/[-_]+/gu, " ").replace(/\s+/gu, " ").trim().toLowerCase();/** The bot of another place `raw` names: by its address here, or by a name no bot here has and only one bot elsewhere has.* 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. */@@ -323,9 +321,9 @@ export function createBotLink(deps: BotLinkDeps) {if (local.some((bot) => bot.id.toLowerCase() === lower)) return undefined;if (isLinkedId(wanted)) return remoteOf(wanted);if (isIdStart(wanted) && local.some((bot) => bot.id.toLowerCase().startsWith(lower))) return undefined;- const named = fold(wanted);- if (!named || local.some((bot) => !bot.hidden && fold(bot.name) === named)) return undefined;- const matches = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => fold(bot.name) === named).map((bot) => ({ peer, bot })));+ const named = foldName(wanted);+ if (!named || local.some((bot) => !bot.hidden && foldName(bot.name) === named)) return undefined;+ const matches = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => foldName(bot.name) === named).map((bot) => ({ peer, bot })));return matches.length === 1 ? matches[0] : undefined;}@@ -671,20 +669,7 @@ export function createBotLink(deps: BotLinkDeps) {receipts.push(receipt(remote, "failed", said));}}- const sent = refused.length < receipts.length;- const mine = sent ? `Handed to the person's other place. ${call.reply === "none" ? "Nothing comes back from a one-way notice." : "Finish your turn now: the result resumes you when it is back."}` : "";- if (here.length === 0) return { status: sent ? 200 : 409, body: { receipts, ...(sent ? { message: mine } : { error: refused.join("; ") }) } };- const rest = await local({ ...call, botIds: here });- const theirs = Array.isArray(rest.body.receipts) ? rest.body.receipts as PeerDeliveryReceipt[] : [];- const ok = sent || rest.status === 200;- const errors = [...refused, ...(typeof rest.body.error === "string" ? [rest.body.error] : [])];- // Instruction-only is the whole call's verdict: nothing was delivered anywhere and no refusal of another place is a- // real failure. One genuine refusal, or a delivery, keeps this a failed call however the local part answered.- const { instructionOnly: localInstructionOnly, ...restBody } = rest.body;- const instructionOnly = !ok && refused.length === 0 && localInstructionOnly === true;- return { status: ok ? 200 : rest.status, body: { ...restBody, receipts: [...receipts, ...theirs],- ...(ok ? { message: [mine, rest.body.message].filter(Boolean).join(" "), ...(errors.length ? { notSent: errors.join("; ") } : {}) } : { error: errors.join("; ") }),- ...(instructionOnly ? { instructionOnly: true } : {}) } };+ return withTargetsHere(call, here, { receipts, refused, message: `Handed to the person's other place. ${call.reply === "none" ? "Nothing comes back from a one-way notice." : "Finish your turn now: the result resumes you when it is back."}` }, local);}/** Why this call cannot go to another place at all, or null. */function unsupportedHere(call: CoordinateBotsCall, context: CoordinateContext, place: string): string | null {diff --git a/server/host/remote-teammate-handoff.test.ts b/server/host/remote-teammate-handoff.test.tsnew file mode 100644index 0000000000..14a13a7110--- /dev/null+++ b/server/host/remote-teammate-handoff.test.ts@@ -0,0 +1,272 @@+import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createCoordinator, type Coordinator, type CoordinateBotsCall, type CoordinatorHost, type HandoffView } from "../coordinator.ts";+import type { RemoteResult, RemoteTeammate } from "../remote-teammates.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { createRemoteHandoff, remoteBotId, type RemoteHandoffContext, type RemoteHandoffDeps } from "./remote-teammate-handoff.ts";++const ADA: RemoteTeammate = { id: "6f1c1a52-9d55-4b8e-9d0e-6c1f0b0f2a11", name: "Ada", base: "https://bots.example.test", botId: "ada-bot", key: "bak_testkeytestkeytestkey", createdAt: 1 };+const REMOTE = remoteBotId(ADA.id);++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) removeTempDir(dir); });++function innerHost(): CoordinatorHost {+ return {+ validate: vi.fn(() => undefined),+ busy: vi.fn(() => false),+ run: vi.fn(async () => ({ ok: true, text: "local done" })),+ report: vi.fn(),+ changed: vi.fn(),+ names: vi.fn(() => ({ requester: "Chief", assignee: "Local" })),+ park: vi.fn(),+ levelOf: vi.fn(() => ({ level: "ask" as const })),+ chiefOf: vi.fn(() => false),+ };+}++function setup(more: Partial<RemoteHandoffDeps> = {}) {+ const dir = mkdtempSync(join(tmpdir(), "remote-handoff-"));+ dirs.push(dir);+ const teammates = [ADA];+ let coordinator: Coordinator | undefined;+ const progress = vi.fn();+ const deps: RemoteHandoffDeps = {+ teammates: { list: () => teammates.map(({ key: _key, ...view }) => view), get: (id) => teammates.find((one) => one.id === id) },+ coordinator: () => coordinator!,+ localBots: () => [{ id: "chief-id", name: "Chief" }, { id: "local-ada-twin", name: "Builder" }],+ botName: (id) => (id === "chief-id" ? "Chief" : undefined),+ outside: () => undefined,+ file: join(dir, "remote-teammate-work.json"),+ wait: vi.fn(async () => {}),+ log: () => {},+ ...more,+ };+ const remote = createRemoteHandoff(deps);+ const inner = innerHost();+ const host = remote.host(inner);+ coordinator = createCoordinator({ dataDir: dir, host, log: () => {} });+ const realProgress = coordinator.progress.bind(coordinator);+ coordinator.progress = (threadId) => { progress(threadId); realProgress(threadId); };+ coordinator.beginTurn({ id: "gen-1", address: { botId: "chief-id", threadId: "chief-chat" }, brief: "Ask Ada", level: "full", origin: { kind: "user", request: "Ask Ada" } });+ const context: RemoteHandoffContext = { sender: { id: "chief-id", name: "Chief" }, address: { threadId: "chief-chat", botId: "chief-id" }, generation: "gen-1", external: false, handed: vi.fn() };+ return { dir, deps, remote, inner, host, coordinator, context, progress, teammates };+}++const call = (botIds: string[], more: Partial<CoordinateBotsCall> = {}): CoordinateBotsCall => ({ botIds, message: "Check the staging site", rework: false, thread: "standing", reply: "resume", consult: false, ...more });+const local = vi.fn(async (sent: CoordinateBotsCall) => ({ status: 200, body: { receipts: sent.botIds.map((botId) => ({ botId, outcome: "queued", detail: "sent here" })), message: "Local sent." } }));+const reply = (text: string, thread = "t-1"): RemoteResult => ({ ok: true, answer: { reply: text, thread } });+const working = (status: "working" | "needs_approval" = "working", thread = "t-1"): RemoteResult => ({ ok: true, answer: { thread, status } });++/** Hands Ada the work and returns her node, as the coordinator would run it. */+function handed(s: ReturnType<typeof setup>, more: Partial<CoordinateBotsCall> = {}) {+ const { node } = s.coordinator.enqueue(s.context.address, "gen-1", undefined, { botId: REMOTE, threadId: `${REMOTE}:chief-chat` }, "Check the staging site",+ { mode: more.consult ? "consult" : more.reply === "none" ? "notify" : "work", reply: more.reply === "none" ? "none" : "resume" });+ return node;+}+const run = (s: ReturnType<typeof setup>, node: HandoffView, signal = new AbortController().signal) =>+ s.host.run(node, false, signal, { text: node.text, note: "", restartNote: "", turn: "first" });++describe("remote teammate hand-off: list_bots and coordinate_bots", () => {+ it("lists each teammate on another server by its address here, with no key", () => {+ const { remote } = setup();+ const agents = remote.agents();+ expect(agents).toEqual([{ id: REMOTE, name: "Ada", section: "", model: "", busy: false, status: "remote", statusText: "on another server (bots.example.test)" }]);+ expect(JSON.stringify(agents)).not.toContain("bak_");+ });++ it("queues work for a teammate named by its address or its name, and hands the rest to this server's bots", async () => {+ const s = setup();+ local.mockClear();+ const result = await s.remote.coordinate(call([REMOTE, "Builder"]), s.context, local);+ expect(result.status).toBe(200);+ expect(local).toHaveBeenCalledWith(expect.objectContaining({ botIds: ["Builder"] }));+ const receipts = result.body.receipts as Array<{ botId: string; outcome: string; requestId?: string; detail: string }>;+ expect(receipts[0]).toMatchObject({ botId: REMOTE, outcome: "queued", detail: expect.stringContaining("sent to Ada on another server") });+ expect(s.coordinator.node(receipts[0]!.requestId!)).toMatchObject({ botId: REMOTE, parentId: "gen-1", status: "queued", mode: "work", reply: "resume" });+ expect(s.context.handed).toHaveBeenCalledWith(receipts[0]!.requestId);++ const byName = await s.remote.coordinate(call(["ada"], { consult: true }), s.context, local);+ expect((byName.body.receipts as Array<{ botId: string }>)[0]!.botId).toBe(REMOTE);+ });++ it("leaves a name one of this server's bots answers to, and calls from outside this server's turns, to this server", async () => {+ const s = setup();+ s.teammates.push({ ...ADA, id: "0d7e2f43-1b2c-4c8d-8e9f-0a1b2c3d4e5f", name: "Chief" });+ local.mockClear();+ await s.remote.coordinate(call(["Chief"]), s.context, local);+ expect(local).toHaveBeenCalledWith(expect.objectContaining({ botIds: ["Chief"] }));+ local.mockClear();+ await s.remote.coordinate(call([REMOTE]), { ...s.context, external: true }, local);+ expect(local).toHaveBeenCalledWith(expect.objectContaining({ botIds: [REMOTE] }));+ expect(s.coordinator.children("gen-1")).toEqual([]);+ });++ it("refuses rooms, answers, posts, consult without a reply, and work that came in from outside", async () => {+ const outside = "This work came in from outside, so it stays in this conversation.";+ const s = setup({ outside: (threadId) => (threadId === "guest-chat" ? outside : undefined) });+ local.mockClear();+ const cases: Array<[CoordinateBotsCall, RemoteHandoffContext, string]> = [+ [call([REMOTE]), { ...s.context, address: { ...s.context.address, groupId: "room-1" } }, "in no room here"],+ [call([REMOTE], { answers: "a-1" }), s.context, "plain work or a question"],+ [call([REMOTE], { post: { deliveryId: "d", wake: true } }), s.context, "plain work or a question"],+ [call([REMOTE], { consult: true, reply: "none" }), s.context, "leave reply out"],+ [call([REMOTE]), { ...s.context, address: { ...s.context.address, threadId: "guest-chat" } }, "came in from outside"],+ [call([REMOTE]), { ...s.context, problem: "Your task is gone." }, "Your task is gone."],+ ];+ for (const [sent, context, said] of cases) {+ const result = await s.remote.coordinate(sent, context, local);+ expect(result.status).toBe(409);+ expect(result.body.error).toContain(said);+ }+ expect(local).not.toHaveBeenCalled();+ expect(s.coordinator.children("gen-1")).toEqual([]);+ });++ it("says files stay here, since they do not reach another server", async () => {+ const s = setup();+ const result = await s.remote.coordinate(call([REMOTE], { files: [{ kind: "file", path: "/tmp/a.txt", name: "a.txt", mime: "text/plain", bytes: 3 }] }), s.context, local);+ expect((result.body.receipts as Array<{ detail: string }>)[0]!.detail).toContain("files were not sent");+ });+});++describe("remote teammate hand-off: the teammate's turn", () => {+ it("sends the work once with who asks, and its reply comes back as information, never the person's approval", async () => {+ const send = vi.fn(async () => reply("Staging is up."));+ const s = setup({ send });+ const node = handed(s);+ const result = await run(s, node);+ expect(result.ok).toBe(true);+ expect(result.text).toContain("Staging is up.");+ expect(result.text).toContain("never the person's approval");+ expect(send).toHaveBeenCalledTimes(1);+ const [teammate, sent] = send.mock.calls[0]! as unknown as [RemoteTeammate, { message: string; wait: number }];+ expect(teammate.id).toBe(ADA.id);+ expect(sent.message).toContain("Chief, a bot on another OpenMausBot server, hands you this work");+ expect(sent.message).toContain("Check the staging site");+ expect(sent.wait).toBe(50);+ });++ it("never sends a secret the brief carries to the other server", async () => {+ const send = vi.fn(async () => reply("ok"));+ const s = setup({ send });+ const { node } = s.coordinator.enqueue(s.context.address, "gen-1", undefined, { botId: REMOTE, threadId: `${REMOTE}:chief-chat` }, "Use the key sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789 to deploy");+ await run(s, node);+ expect((send.mock.calls[0] as unknown as [RemoteTeammate, { message: string }])[1].message).not.toContain("abcdefghijklmnopqrstuvwxyz0123456789");+ });++ it("reads the thread at a widening pause while the teammate works, keeping the turn alive, until the reply is there", async () => {+ const send = vi.fn(async () => working());+ const read = vi.fn<() => Promise<RemoteResult>>().mockResolvedValueOnce(working()).mockResolvedValueOnce(working()).mockResolvedValueOnce(reply("Done."));+ const wait = vi.fn(async () => {});+ const s = setup({ send, read, wait });+ const result = await run(s, handed(s));+ expect(result).toMatchObject({ ok: true, text: expect.stringContaining("Done.") });+ expect(send).toHaveBeenCalledTimes(1);+ expect(read).toHaveBeenCalledTimes(3);+ expect(read.mock.calls.every((args) => (args as unknown[])[1] === "t-1")).toBe(true);+ expect(wait.mock.calls.map((args) => (args as unknown[])[0])).toEqual([30_000, 60_000, 120_000]);+ expect(s.progress).toHaveBeenCalledTimes(3);+ });++ it("ends with a plain result when the teammate waits on its owner's approval", async () => {+ const s = setup({ send: vi.fn(async () => working("needs_approval")) });+ const result = await run(s, handed(s));+ expect(result.ok).toBe(true);+ expect(result.text).toContain("stopped to ask its owner for an approval");+ });++ it("does not wait for a one-way notice", async () => {+ const send = vi.fn(async () => working());+ const s = setup({ send });+ const result = await run(s, handed(s, { reply: "none" }));+ expect(result).toEqual({ ok: true, text: "Delivered to Ada on another server." });+ expect((send.mock.calls[0] as unknown[])[1]).toMatchObject({ wait: 0 });+ });++ it("waits the other server's retry-after when it is busy or rate limited, then sends", async () => {+ const send = vi.fn<() => Promise<RemoteResult>>()+ .mockResolvedValueOnce({ ok: false, problem: "rate_limited", status: 429, retryAfterSeconds: 42 })+ .mockResolvedValueOnce({ ok: false, problem: "busy", status: 409 })+ .mockResolvedValueOnce(reply("ok"));+ const wait = vi.fn(async () => {});+ const s = setup({ send, wait });+ expect((await run(s, handed(s))).ok).toBe(true);+ expect(wait.mock.calls.map((args) => (args as unknown[])[0])).toEqual([42_000, 30_000]);+ });++ it("never sends again after a send that may have arrived, and fails plainly on a refused key", async () => {+ const unreachable = vi.fn(async (): Promise<RemoteResult> => ({ ok: false, problem: "unreachable", detail: "no answer in time" }));+ const s = setup({ send: unreachable });+ const first = await run(s, handed(s));+ expect(first).toMatchObject({ ok: false, failure: { text: expect.stringContaining("could not be reached") } });+ expect(unreachable).toHaveBeenCalledTimes(1);++ const wrongKey = vi.fn(async (): Promise<RemoteResult> => ({ ok: false, problem: "wrong_key", status: 401 }));+ const t = setup({ send: wrongKey });+ const second = await run(t, handed(t));+ expect(second).toMatchObject({ ok: false, text: expect.stringContaining("no longer takes the saved key") });+ expect(second.text).not.toContain("bak_");+ expect(wrongKey).toHaveBeenCalledTimes(1);+ });++ it("gives up on a thread it cannot read after five misses in a row", async () => {+ const read = vi.fn(async (): Promise<RemoteResult> => ({ ok: false, problem: "unreachable" }));+ const s = setup({ send: vi.fn(async () => working()), read });+ const result = await run(s, handed(s));+ expect(result.ok).toBe(false);+ expect(read).toHaveBeenCalledTimes(6);+ });++ it("after a restart reads the thread it already sent instead of sending the work again, and forgets it once reported", async () => {+ const s = setup({ send: vi.fn(async () => working()), read: vi.fn(async () => { throw new Error("stop here"); }) });+ const node = handed(s);+ await expect(run(s, node)).rejects.toThrow("stop here");+ const kept = JSON.parse(readFileSync(s.deps.file, "utf8"));+ expect(kept.work[node.id]).toMatchObject({ teammate: ADA.id, thread: "t-1" });+ expect(statSync(s.deps.file).mode & 0o777).toBe(0o600);++ const send = vi.fn(async () => reply("never"));+ const read = vi.fn(async () => reply("Read after the restart."));+ const again = createRemoteHandoff({ ...s.deps, send, read }).host(innerHost());+ const result = await again.run(node, true, new AbortController().signal, { text: "", note: "", restartNote: "", turn: "rerun" });+ expect(result.text).toContain("Read after the restart.");+ expect(send).not.toHaveBeenCalled();+ again.report({ ...node, status: "completed" }, s.coordinator.node("gen-1"));+ expect(JSON.parse(readFileSync(s.deps.file, "utf8")).work[node.id]).toBeUndefined();+ });++ it("stops at once when the turn is stopped while it waits", async () => {+ const controller = new AbortController();+ const wait = vi.fn(async (_ms: number, signal: AbortSignal) => { controller.abort(); signal.throwIfAborted(); });+ const s = setup({ send: vi.fn(async () => working()), wait });+ const result = await run(s, handed(s), controller.signal);+ expect(result).toEqual({ ok: false, text: "Stopped before Ada's reply came back." });+ });++ it("refuses a teammate removed since, and leaves this server's own nodes to the host it wraps", async () => {+ const s = setup();+ const node = handed(s);+ expect(s.host.names(node, s.coordinator.node("gen-1"))).toEqual({ requester: "Chief", assignee: "Ada (another server)" });+ s.teammates.splice(0);+ expect(s.host.validate(node, s.coordinator.node("gen-1"))).toContain("was removed");+ const own = { ...node, botId: "chief-id" };+ expect(s.host.validate(own)).toBeUndefined();+ expect(s.inner.validate).toHaveBeenCalledWith(own, undefined);+ expect(await run(s, own)).toEqual({ ok: true, text: "local done" });+ expect(s.host.levelOf({ botId: REMOTE, threadId: "x" })).toEqual({ level: "full" });+ });++ it("ignores an unreadable record of sent work instead of failing to start", () => {+ const dir = mkdtempSync(join(tmpdir(), "remote-handoff-"));+ dirs.push(dir);+ const file = join(dir, "remote-teammate-work.json");+ writeFileSync(file, "{not json");+ const log = vi.fn();+ expect(() => createRemoteHandoff({ ...setup().deps, file, log })).not.toThrow();+ expect(log).toHaveBeenCalledWith(expect.stringContaining("ignoring unreadable"));+ });+});diff --git a/server/host/remote-teammate-handoff.ts b/server/host/remote-teammate-handoff.tsnew file mode 100644index 0000000000..033e74d27b--- /dev/null+++ b/server/host/remote-teammate-handoff.ts@@ -0,0 +1,223 @@+// Hand-offs to teammates on other servers (server/remote-teammates.ts): list_bots names them, coordinate_bots queues work+// for them as for any teammate, and their turn is a Bot API call to the other server whose reply comes back as the+// result. Everything else (rooms, answers, posts, files) stays with this server's own bots.+import { readFileSync } from "node:fs";+import { setTimeout as delay } from "node:timers/promises";+import { z } from "zod";++import { writeFileAtomic } from "../atomic.ts";+import type { CoordinateBotsCall, Coordinator, CoordinatorHost, HandoffView, HostTurnResult } from "../coordinator.ts";+import { foldName, withTargetsHere, type CoordinateResult, type PeerDeliveryReceipt } from "../peer-delivery.ts";+import { readRemote, sendToRemote, type RemoteResult, type RemoteTeammate, type RemoteTeammates } from "../remote-teammates.ts";+import { redactSecretsInText } from "../redact.ts";+import { parseJson } from "../schema.ts";+import { clip } from "./text-clip.ts";++/** A teammate on another server is addressed here as `remote-<its id in remote-teammates.json>`. */+export const REMOTE_PREFIX = "remote-";+export const remoteBotId = (id: string): string => `${REMOTE_PREFIX}${id}`;+export const isRemoteBotId = (botId: string | undefined): boolean => typeof botId === "string" && botId.startsWith(REMOTE_PREFIX);++/** The Bot API allows ten calls a minute for a key: reads start at this pause and double up to the next. */+const FIRST_READ_MS = 30_000;+const LONGEST_READ_MS = 120_000;+/** The other server's own retry-after is waited for, up to this. */+const LONGEST_RETRY_MS = 300_000;+/** Answers in a row that were no answer (unreachable, rate limited, busy) before the hand-off fails. */+const MAX_MISSES = 5;+const SEND_WAIT_S = 50;+const REPLY_CHARS = 20_000;+const BRIEF_CHARS = 200_000;+/** A sent hand-off's thread is kept this long, so a restart reads its reply instead of sending the work again. */+const KEEP_MS = 30 * 24 * 60 * 60_000;++const workSchema = z.object({ version: z.literal(1), work: z.record(z.string(), z.object({ teammate: z.string(), thread: z.string(), at: z.number() })) });+type Sent = z.output<typeof workSchema>["work"][string];++export interface RemoteHandoffContext {+ sender: { id: string; name: string };+ address: { groupId?: string; threadId: string; botId: string };+ generation: string;+ parentId?: string;+ /** The caller is not one of this server's own turns. */+ external: boolean;+ /** Why this conversation may not hand work on at all, as for any hand-off. */+ problem?: string;+ handed(nodeId: string): void;+}++export interface RemoteHandoffDeps {+ teammates: Pick<RemoteTeammates, "list" | "get">;+ coordinator(): Coordinator;+ /** This server's own bots: a name or id one of them answers to never goes to another server. */+ localBots(): ReadonlyArray<{ id: string; name: string }>;+ botName(id: string): string | undefined;+ /** Why this conversation may not reach another server with the owner's key: work in it came in from outside, or a guest drives it. */+ outside(threadId: string): string | undefined;+ /** Where a sent hand-off's thread on the other server is kept (mode 600). */+ file: string;+ send?: typeof sendToRemote;+ read?: typeof readRemote;+ wait?: (ms: number, signal: AbortSignal) => Promise<void>;+ now?: () => number;+ log(line: string): void;+}++export function createRemoteHandoff(deps: RemoteHandoffDeps) {+ const send = deps.send ?? sendToRemote, read = deps.read ?? readRemote;+ const wait = deps.wait ?? ((ms: number, signal: AbortSignal) => delay(ms, undefined, { signal }));+ const now = deps.now ?? Date.now;+ const teammateOf = (botId: string): RemoteTeammate | undefined => (isRemoteBotId(botId) ? deps.teammates.get(botId.slice(REMOTE_PREFIX.length)) : undefined);+ const nameOf = (botId: string) => teammateOf(botId)?.name ?? "Teammate";++ let sent: Record<string, Sent> = {};+ try {+ const parsed = workSchema.safeParse(parseJson(readFileSync(deps.file, "utf8")));+ if (parsed.success) sent = parsed.data.work;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") deps.log(`remote teammates: ignoring unreadable ${deps.file}`);+ }+ const save = () => {+ try { writeFileAtomic(deps.file, JSON.stringify({ version: 1, work: sent }), { mode: 0o600 }); } catch (error) { deps.log(`remote teammates: could not save sent work: ${error instanceof Error ? error.message : String(error)}`); }+ };+ const forget = (id: string) => {+ const cutoff = now() - KEEP_MS;+ let changed = false;+ for (const [key, entry] of Object.entries(sent)) if (key === id || entry.at < cutoff) { delete sent[key]; changed = true; }+ if (changed) save();+ };++ /** The teammate on another server a coordinate_bots target names, unless one of this server's bots answers to it. */+ function resolve(raw: string): RemoteTeammate | undefined {+ const wanted = raw.trim();+ if (isRemoteBotId(wanted)) return teammateOf(wanted);+ const named = foldName(wanted), lower = wanted.toLowerCase();+ if (!named || deps.localBots().some((bot) => bot.id.toLowerCase().startsWith(lower) || foldName(bot.name) === named)) return undefined;+ const matches = deps.teammates.list().filter((teammate) => foldName(teammate.name) === named);+ return matches.length === 1 ? deps.teammates.get(matches[0]!.id) : undefined;+ }++ function unsupported(call: CoordinateBotsCall, context: RemoteHandoffContext): string | null {+ return context.problem ? context.problem+ : deps.outside(context.address.threadId) ?? (call.groupId || context.address.groupId ? "Teammates on other servers are in no room here: hand it to them from your own conversation"+ : call.answers || call.post || call.ownThread ? "That does not reach another server: send the bot plain work or a question instead"+ : call.consult && call.reply === "none" ? "consult asks a question whose answer comes back to you; leave reply out" : null);+ }++ /** coordinate_bots for teammates on other servers; every other target goes on as before (`local`). */+ async function coordinate(call: CoordinateBotsCall, context: RemoteHandoffContext, local: (call: CoordinateBotsCall) => Promise<CoordinateResult>): Promise<CoordinateResult> {+ if (context.external) return local(call);+ const away = new Map<string, RemoteTeammate>();+ for (const raw of call.botIds) { const teammate = resolve(raw); if (teammate) away.set(raw, teammate); }+ if (away.size === 0) return local(call);+ const here = call.botIds.filter((raw) => !away.has(raw));+ const receipts: PeerDeliveryReceipt[] = [], refused: string[] = [];+ const mode = call.consult ? "consult" as const : call.reply === "none" ? "notify" as const : "work" as const;+ const coordinator = deps.coordinator();+ for (const teammate of new Map([...away.values()].map((one) => [one.id, one])).values()) {+ const botId = remoteBotId(teammate.id);+ const receipt = (outcome: PeerDeliveryReceipt["outcome"], detail: string, more: Partial<PeerDeliveryReceipt> = {}): PeerDeliveryReceipt => ({ botId, botName: teammate.name, outcome, detail: clip(detail, 400), ...more });+ const problem = unsupported(call, context);+ if (problem) { refused.push(problem); receipts.push(receipt("failed", problem)); continue; }+ const threadId = `${botId}:${call.thread === "new" ? `${context.generation}:${receipts.length}` : context.address.threadId}`;+ try {+ const { node, duplicate } = coordinator.enqueue(context.address, context.generation, context.parentId, { botId, threadId }, call.message, {+ mode, reply: call.reply === "none" ? "none" : "resume", thread: call.thread === "new" ? "new" : "standing", rework: call.rework, ...(call.doneWhen ? { doneWhen: call.doneWhen } : {}) });+ const returns = mode === "notify" ? "nothing comes back from it" : "its reply will resume you";+ const files = call.files?.length ? " Its files were not sent: files do not reach other servers, so put what it needs in the message." : "";+ receipts.push(receipt(duplicate && node.status !== "queued" ? "injected" : "queued",+ duplicate ? `already sent to ${teammate.name} on another server: ${returns}` : `sent to ${teammate.name} on another server; ${returns}.${files}`, { requestId: node.id }));+ if (!duplicate) context.handed(node.id);+ } catch (error) {+ const said = error instanceof Error ? error.message : String(error);+ refused.push(said);+ receipts.push(receipt("failed", said));+ }+ }+ return withTargetsHere(call, here, { receipts, refused, message: `Handed to a teammate on another server. ${call.reply === "none" ? "Nothing comes back from a one-way notice." : "Finish your turn now: its reply resumes you when it is back."}` }, local);+ }++ /** What the other bot reads: who hands it what, and when it is done. */+ function brief(node: HandoffView): string {+ const parent = node.parentId ? deps.coordinator().node(node.parentId) : undefined;+ const from = (parent && deps.botName(parent.botId)) || "A bot";+ const doneWhen = deps.coordinator().status(node.id)?.assignment?.doneWhen;+ const asks = node.mode === "consult" ? "asks you this question; answer it and act on nothing" : node.mode === "notify" ? "lets you know this; no reply goes back" : "hands you this work; your reply goes back to it";+ return clip(redactSecretsInText(`${from}, a bot on another OpenMausBot server, ${asks}:\n\n${node.text}${doneWhen ? `\n\nDone when: ${doneWhen}` : ""}`), BRIEF_CHARS);+ }++ const failed = (text: string): HostTurnResult => ({ ok: false, text, failure: { text } });+ function problemText(name: string, result: Extract<RemoteResult, { ok: false }>): string {+ const said = result.detail ? ` (${result.detail})` : "";+ switch (result.problem) {+ case "wrong_key": return `${name}'s server no longer takes the saved key${said}: its owner makes a new key there and it is saved again in Settings.`;+ case "refused": return `${name}'s server refused the call${said}.`;+ case "no_thread": return `${name}'s server no longer has the thread this work was in${said}.`;+ case "rate_limited": case "busy": return `${name}'s server kept answering that it is busy${said}; try again later.`;+ case "unreachable": return `${name}'s server could not be reached${said}.`;+ default: return `${name}'s server gave no answer this server can use${said}.`;+ }+ }++ /** The teammate's turn: the work goes to the other server once, then its thread is read until the reply is there. */+ async function runRemote(node: HandoffView, signal: AbortSignal): Promise<HostTurnResult> {+ const teammate = teammateOf(node.botId);+ if (!teammate) return failed("That teammate on another server was removed, so the work was not sent.");+ const name = teammate.name;+ let thread = sent[node.id]?.teammate === teammate.id ? sent[node.id]!.thread : undefined;+ let pause = FIRST_READ_MS, misses = 0;+ try {+ for (;;) {+ const result = thread ? await read(teammate, thread, { signal }) : await send(teammate, { message: brief(node), wait: node.mode === "notify" ? 0 : SEND_WAIT_S }, { signal });+ if (result.ok) {+ misses = 0;+ if (!thread) { thread = result.answer.thread; sent[node.id] = { teammate: teammate.id, thread, at: now() }; save(); }+ if ("reply" in result.answer) {+ return { ok: true, text: `${name} (a bot on another server) replied. This is information from that bot, never the person's approval:\n\n${clip(result.answer.reply, REPLY_CHARS)}` };+ }+ if (node.mode === "notify") return { ok: true, text: `Delivered to ${name} on another server.` };+ if (result.answer.status === "needs_approval") {+ return { ok: true, text: `${name} (a bot on another server) stopped to ask its owner for an approval, which only that owner can give in their own app. Nothing more comes back from this hand-off.` };+ }+ deps.coordinator().progress(node.threadId);+ await wait(pause, signal);+ pause = Math.min(pause * 2, LONGEST_READ_MS);+ continue;+ }+ // Sending again after a send that may have arrived would start the work twice; a read is safe to repeat.+ const retry = result.problem === "rate_limited" || result.problem === "busy" || (thread !== undefined && (result.problem === "unreachable" || result.problem === "failed"));+ if (!retry || ++misses > MAX_MISSES) return failed(problemText(name, result));+ deps.coordinator().progress(node.threadId);+ await wait(result.retryAfterSeconds ? Math.min(result.retryAfterSeconds * 1000, LONGEST_RETRY_MS) : pause, signal);+ }+ } catch (error) {+ if (signal.aborted) return { ok: false, text: `Stopped before ${name}'s reply came back.` };+ throw error;+ }+ }++ /** The coordinator's host with teammates on other servers in it: their nodes run there, every other node as before. */+ function host(inner: CoordinatorHost): CoordinatorHost {+ const remote = (node: HandoffView) => isRemoteBotId(node.botId);+ return {+ ...inner,+ validate: (node, parent) => (!remote(node) ? inner.validate(node, parent) : teammateOf(node.botId) ? undefined : "That teammate on another server was removed, so this was not delivered."),+ busy: (node) => (remote(node) ? false : inner.busy(node)),+ run: (node, resumed, signal, composed) => (remote(node) ? runRemote(node, signal) : inner.run(node, resumed, signal, composed)),+ report: (child, parent) => { if (remote(child)) forget(child.id); else inner.report(child, parent); },+ names: (node, parent) => (remote(node) ? { requester: (parent && deps.botName(parent.botId)) || "Teammate", assignee: `${nameOf(node.botId)} (another server)` } : inner.names(node, parent)),+ park: (node, question, restored) => { if (!remote(node)) inner.park(node, question, restored); },+ remind: (node, closesAt) => { if (!remote(node)) inner.remind?.(node, closesAt); },+ levelOf: (target, source) => (isRemoteBotId(target.botId) ? { level: "full" } : inner.levelOf(target, source)),+ chiefOf: (address) => (isRemoteBotId(address.botId) ? false : inner.chiefOf(address)),+ outward: (node) => (remote(node) ? [] : inner.outward?.(node) ?? []),+ shareAnswer: (first, joiner) => (remote(first) || remote(joiner) ? false : inner.shareAnswer?.(first, joiner) ?? false),+ };+ }++ /** Teammates on other servers as list_bots names them. */+ const agents = () => deps.teammates.list().map((teammate) => ({ id: remoteBotId(teammate.id), name: teammate.name, section: "", model: "", busy: false,+ status: "remote", statusText: `on another server (${new URL(teammate.base).host})` }));++ return { coordinate, host, agents, resolve };+}diff --git a/server/index.ts b/server/index.tsindex 4ade981ff1..8f5dfc6d23 100644--- a/server/index.ts+++ b/server/index.ts@@ -639,7 +639,7 @@ import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwnersimport { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";import { createThreadRoutes } from "./routes/threads.ts";-import { createWebhookRoutes } from "./routes/webhooks.ts"; import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts"; import { RemoteTeammates } from "./remote-teammates.ts";+import { createWebhookRoutes } from "./routes/webhooks.ts"; import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts"; import { RemoteTeammates } from "./remote-teammates.ts"; import { createRemoteHandoff } from "./host/remote-teammate-handoff.ts";import { withScopeHint } from "./connector-scope-hint.ts"; import { accountsByApp, withAccountHint } from "./connector-account-hint.ts";import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";import { createConnectorCards } from "./host/connector-cards.ts";@@ -3836,7 +3836,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:answerLive: async (threadId, requestId, text) => await answerRequest(threadId, botForThread(store.botByThread(threadId)?.id ?? "", threadId)?.modelSelection.instanceId ?? "", requestId, "answer", text) === "answered", settleSignIns: (node) => signInSettle.answeredElsewhere(node),keptPrivate: (node, requester) => keptPrivate({ child: teamHost.privateTo(node.threadId), parent: teamHost.privateTo(requester.threadId) }),steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });-const reworkCap = createReworkCap(); 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),+const reworkCap = createReworkCap(); 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 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), 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({dataDir: DATA_DIR,@@ -3846,7 +3846,7 @@ const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLstandingThreadOf: botId => botMainThread(botId) ?? store.bot(botId)?.threadId,botOfThread: threadId => store.botByThread(threadId)?.id,},- host: botLink.link.host({ holdReason: (node) => queuedStatus(node), statusReply: (requester, prompt, signal) => sideJobs.text("status-reply", requester)?.generateText(prompt, { signal, timeoutMs: STATUS_REPLY_TIMEOUT_MS }) ?? Promise.resolve(undefined),+ host: remoteHandoff.host(botLink.link.host({ holdReason: (node) => queuedStatus(node), statusReply: (requester, prompt, signal) => sideJobs.text("status-reply", requester)?.generateText(prompt, { signal, timeoutMs: STATUS_REPLY_TIMEOUT_MS }) ?? Promise.resolve(undefined),validate: (node, parent) => node.mode === "notify" && node.status !== "queued" ? undefined: !node.parentId && node.groupId ? roomRootProblem(node): roomHandoffProblem(node, parent),@@ -4032,7 +4032,7 @@ const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverL},shareAnswer: createShareAnswer({ askedFrom: (node) => (node.parentId ? coordinator.node(node.parentId)?.threadId : undefined), audienceOf: teamHost.audienceOf, pinned: (botId, threadId) => store.taskByThread(botId, threadId)?.cwd, botFolder: (botId) => store.bot(botId)?.cwd, privateFolders: TASK_WORKSPACES_DIR }),joined: (node) => { store.appendMessage(node.threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${serverLine(threadLanguage(node.threadId), "server.teammates.sameRequest")}`, ok: true } }); },- }),+ })),});threadsAwaitingTeammates = () => new Set([...coordinator.awaitingTeammateThreads(), ...checkWork.threads()]);const groupUsageReader = new GroupUsageReader(DATA_DIR); const chiefRooms = createChiefRooms({ store, updateRoom: updateChannel, published: (group) => broadcast({ kind: "group", group: publicGroupState(group) }) });@@ -9384,7 +9384,7 @@ const webhookIngressStatus = () => ({baseUrl: webhookIngress?.baseUrl ?? `http://127.0.0.1:${WEBHOOK_PORT}`,...(webhookIngressError ? { error: webhookIngressError } : {}),});-ROUTES.push(createTeamFilesRoutes({ files: teamFilesHost.files, actor: (auth) => auth.kind === "session" && auth.session.email ? { person: personKey(auth.session), admin: auth.scopes.includes("admin") } : null, personName: (person) => teamHost.personName(person), botName: (botId) => store.bot(botId)?.name })); ROUTES.push(createWebhookRoutes({ webhooks, ingress: webhookIngressStatus, visible: (auth) => visibleTo(viewerFor(auth)) }), botApi.routes, createRemoteTeammateRoutes({ teammates: new RemoteTeammates() }));+ROUTES.push(createTeamFilesRoutes({ files: teamFilesHost.files, actor: (auth) => auth.kind === "session" && auth.session.email ? { person: personKey(auth.session), admin: auth.scopes.includes("admin") } : null, personName: (person) => teamHost.personName(person), botName: (botId) => store.bot(botId)?.name })); ROUTES.push(createWebhookRoutes({ webhooks, ingress: webhookIngressStatus, visible: (auth) => visibleTo(viewerFor(auth)) }), botApi.routes, createRemoteTeammateRoutes({ teammates: remoteTeammates }));const RUNTIME_KEEP_MS = 30 * 24 * 60 * 60_000;let runtimePrunedAt = 0;@@ -13026,7 +13026,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {description: b.description || undefined,};});- return json(res, 200, { bots: [...bots, ...botLink.link.agents()] });+ return json(res, 200, { bots: [...bots, ...botLink.link.agents(), ...remoteHandoff.agents()] });}if (await dispatchRoutes([createInternalThreadRoutes({store, coordinator, from: internalSender, fromThreadId: internalCapability.threadId,@@ -13626,7 +13626,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const message = coordinateResultMessage(reply, answeredOnly);return { status: sent ? 200 : 409, body: { receipts, ...(sent ? { message: lead ? `${lead} ${message}` : message } : { error: refused.join("; "), ...(refusalsOnlyInstructions(refused, receipts) ? { instructionOnly: true } : {}) }),...(EXTERNAL && sent ? { rootId: generation } : {}) } };- }, coordinateBots = (call: CoordinateBotsCall) => botLink.link.coordinate(call, { sender: internalSender, address: { groupId: store.groupByThread(internalCapability.threadId)?.id, threadId: internalCapability.threadId, botId: internalSender.id }, generation: internalCapability.generation, parentId: internalCapability.roomHandoffId, external: EXTERNAL, handed: delegatedThisTurn, problem: linkSourceProblem(internalSender.id, internalCapability.threadId) }, coordinateHere);+ }, handoffContext = { sender: internalSender, address: { groupId: store.groupByThread(internalCapability.threadId)?.id, threadId: internalCapability.threadId, botId: internalSender.id }, generation: internalCapability.generation, parentId: internalCapability.roomHandoffId, external: EXTERNAL, handed: delegatedThisTurn, problem: linkSourceProblem(internalSender.id, internalCapability.threadId) }, coordinateBots = (call: CoordinateBotsCall) => remoteHandoff.coordinate(call, handoffContext, (rest) => botLink.link.coordinate(rest, handoffContext, coordinateHere));if (method === "GET" && path === "/api/internal/assignment-status") {const id = url.searchParams.get("id")?.trim() ?? "";const fromThreadId = internalCapability.threadId;diff --git a/server/peer-delivery.ts b/server/peer-delivery.tsindex 277bbdcd7f..973cb10068 100644--- a/server/peer-delivery.ts+++ b/server/peer-delivery.ts@@ -48,6 +48,33 @@ export function refusalsOnlyInstructions(refused: readonly string[], receipts: rreturn refused.length > 0 && refused.every((said) => instructed.includes(said));}+/** A bot's name as a coordinate_bots target is matched: no leading @, dashes and underscores as spaces, any case. */+export const foldName = (value: string): string => value.replace(/^@/u, "").replace(/[-_]+/gu, " ").replace(/\s+/gu, " ").trim().toLowerCase();++export type CoordinateResult = { status: number; body: Record<string, unknown> };++/** A coordinate_bots call that sent some of its targets elsewhere (another place, another server) answers once for all:+ * what went elsewhere, then the targets still `here` handed on as before (`local`). `message` is what a delivery+ * elsewhere tells the bot. */+export async function withTargetsHere<Call extends { botIds: string[] }>(call: Call, here: readonly string[], sent: { receipts: PeerDeliveryReceipt[]; refused: string[]; message: string },+ local: (call: Call) => Promise<CoordinateResult>): Promise<CoordinateResult> {+ const { receipts, refused } = sent;+ const delivered = refused.length < receipts.length;+ const mine = delivered ? sent.message : "";+ if (here.length === 0) return { status: delivered ? 200 : 409, body: { receipts, ...(delivered ? { message: mine } : { error: refused.join("; ") }) } };+ const rest = await local({ ...call, botIds: [...here] });+ const theirs = Array.isArray(rest.body.receipts) ? rest.body.receipts as PeerDeliveryReceipt[] : [];+ const ok = delivered || rest.status === 200;+ const errors = [...refused, ...(typeof rest.body.error === "string" ? [rest.body.error] : [])];+ // Instruction-only is the whole call's verdict: nothing was delivered anywhere and no refusal elsewhere is a real+ // failure. One genuine refusal, or a delivery, keeps this a failed call however the local part answered.+ const { instructionOnly: localInstructionOnly, ...restBody } = rest.body;+ const instructionOnly = !ok && refused.length === 0 && localInstructionOnly === true;+ return { status: ok ? 200 : rest.status, body: { ...restBody, receipts: [...receipts, ...theirs],+ ...(ok ? { message: [mine, rest.body.message].filter(Boolean).join(" "), ...(errors.length ? { notSent: errors.join("; ") } : {}) } : { error: errors.join("; ") }),+ ...(instructionOnly ? { instructionOnly: true } : {}) } };+}+export function renderPeerDeliveryReceipts(receipts: readonly PeerDeliveryReceipt[]): string {if (!receipts.length) return "";const line = (receipt: PeerDeliveryReceipt) => `${named(receipt)}: ${receipt.outcome} — ${receipt.detail}`;diff --git a/server/places-elsewhere.ts b/server/places-elsewhere.tsindex bf5c5290da..49fb4abd73 100644--- a/server/places-elsewhere.ts+++ b/server/places-elsewhere.ts@@ -10,6 +10,7 @@ import { join } from "node:path";import { z } from "zod";import { writeFileAtomic } from "./atomic.ts";+import { foldName } from "./peer-delivery.ts";import { mentionedBots } from "./store.ts";const FILE = "places-elsewhere.json";@@ -31,7 +32,6 @@ export type Explained = { where: string } | { hint: string } | null;export const ONE_PLACE = "Bots work together only within one place, so a bot on another computer or server can't be reached from here. "+ "To bring them together, the person can make one place their bots' home: in the app, right-click their own server's icon on the left of the app and choose \"Make … my home\".";-const fold = (value: string) => value.replace(/^@/u, "").replace(/[-_]+/gu, " ").replace(/\s+/gu, " ").trim().toLowerCase();/** How the person brings these two places' bots together, told to a bot (to offer it) or to the person: on the place that* can be home (a server of theirs, or My Cloud) with the one tap the app offers for it, or by hand when neither place is@@ -66,8 +66,8 @@ export function livesElsewhere(bot: string, place: Place, self: Elsewhere["self"/** The bots of the person's other places that `text` @mentions, none named like a bot here. */function mentionsOf(known: Elsewhere, text: string, here: ReadonlyArray<{ name: string }>): Array<{ bot: string; place: Place }> {if (!text.includes("@")) return [];- const local = new Set(here.map((bot) => fold(bot.name)));- const names = known.places.flatMap((place) => place.bots.filter((bot) => !local.has(fold(bot))).map((bot) => ({ name: bot, place })));+ const local = new Set(here.map((bot) => foldName(bot.name)));+ const names = known.places.flatMap((place) => place.bots.filter((bot) => !local.has(foldName(bot))).map((bot) => ({ name: bot, place })));return mentionedBots(text, names).map(({ name: bot, place }) => ({ bot, place }));}@@ -84,10 +84,10 @@ export function createPlacesElsewhere({ dataDir, now = Date.now }: { dataDir: st};/** The place another of the person's places names `bot` in, with the name it has there. */const where = (bot: string): { bot: string; place: Place } | null => {- const wanted = fold(bot);+ const wanted = foldName(bot);if (!wanted) return null;for (const place of read()?.places ?? []) {- const found = place.bots.find((candidate) => fold(candidate) === wanted);+ const found = place.bots.find((candidate) => foldName(candidate) === wanted);if (found) return { bot: found, place };}return null;