Skip to content

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

Remote hand-off: one conversation per work thread, no second send (review on #7113)

Bugfixer 2b01badcaaeb5
diff --git a/server/host/remote-teammate-handoff.test.ts b/server/host/remote-teammate-handoff.test.ts
index 84f0624750..7abfeeba32 100644
--- a/server/host/remote-teammate-handoff.test.ts
+++ b/server/host/remote-teammate-handoff.test.ts
@@ -105,6 +105,17 @@ describe("remote teammate hand-off: list_bots and coordinate_bots", () => {
expect(s.coordinator.children("gen-1")).toEqual([]);
});
+ it("takes a short name as an id start of this server's bots only at 8 characters, as anywhere else", async () => {
+ const s = setup();
+ s.teammates.push({ ...ADA, id: "0d7e2f43-1b2c-4c8d-8e9f-0a1b2c3d4e5f", name: "Loc" });
+ local.mockClear();
+ await s.remote.coordinate(call(["Loc"]), s.context, local);
+ expect(local).not.toHaveBeenCalled();
+ expect(s.coordinator.children("gen-1")).toHaveLength(1);
+ expect(s.remote.resolve("local-ad")).toBeUndefined();
+ expect(s.remote.resolve("LOCAL-ADA-TWIN")).toBeUndefined();
+ });
+
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) });
@@ -239,6 +250,59 @@ describe("remote teammate hand-off: the teammate's turn", () => {
expect(JSON.parse(readFileSync(s.deps.file, "utf8")).work[node.id]).toBeUndefined();
});
+ it("goes on in the same conversation there for standing work, and starts a new one for a new thread", async () => {
+ const send = vi.fn(async (_teammate: RemoteTeammate, sent: { thread?: string }) => reply("Done.", sent.thread ?? `t-${send.mock.calls.length}`));
+ const s = setup({ send });
+ const enqueue = (text: string, threadId = `${REMOTE}:chief-chat`) => s.coordinator.enqueue(s.context.address, "gen-1", undefined, { botId: REMOTE, threadId }, text).node;
+ await run(s, enqueue("First"));
+ await run(s, enqueue("Follow up on that"));
+ const threads = () => send.mock.calls.map(([, sent]) => (sent as { thread?: string }).thread);
+ expect(threads()).toEqual([undefined, "t-1"]);
+ // A restart keeps the conversation.
+ const again = createRemoteHandoff({ ...s.deps, send }).host(innerHost());
+ await again.run(enqueue("And again"), false, new AbortController().signal, { text: "", note: "", restartNote: "", turn: "first" });
+ expect(threads()).toEqual([undefined, "t-1", "t-1"]);
+
+ await s.remote.coordinate(call([REMOTE], { thread: "new", message: "Something else" }), s.context, local);
+ const fresh = s.coordinator.children("gen-1").find((node) => node.text === "Something else")!;
+ await run(s, fresh);
+ expect(threads()).toEqual([undefined, "t-1", "t-1", undefined]);
+ });
+
+ it("starts a new conversation there when the other server no longer has the standing one", async () => {
+ const send = vi.fn(async (_teammate: RemoteTeammate, sent: { thread?: string }): Promise<RemoteResult> =>
+ (sent.thread === "t-1" && send.mock.calls.length > 1 ? { ok: false, problem: "no_thread", status: 404 } : reply("Done.", sent.thread ?? `t-${send.mock.calls.length}`)));
+ const s = setup({ send });
+ const enqueue = (text: string) => s.coordinator.enqueue(s.context.address, "gen-1", undefined, { botId: REMOTE, threadId: `${REMOTE}:chief-chat` }, text).node;
+ await run(s, enqueue("First"));
+ expect(await run(s, enqueue("Follow up"))).toMatchObject({ ok: true, text: expect.stringContaining("Done.") });
+ expect(send.mock.calls.map(([, sent]) => (sent as { thread?: string }).thread)).toEqual([undefined, "t-1", undefined]);
+ expect(JSON.parse(readFileSync(s.deps.file, "utf8")).conversations[`${REMOTE}:chief-chat`]).toMatchObject({ thread: "t-3" });
+ });
+
+ it("never sends the work again after a restart in the middle of sending it", async () => {
+ const s = setup({ send: vi.fn(async () => { throw new Error("stopped while sending"); }) });
+ const node = handed(s);
+ await expect(run(s, node)).rejects.toThrow("stopped while sending");
+ const send = vi.fn(async () => reply("twice"));
+ const again = createRemoteHandoff({ ...s.deps, send }).host(innerHost());
+ const result = await again.run(node, true, new AbortController().signal, { text: "", note: "", restartNote: "", turn: "rerun" });
+ expect(result).toMatchObject({ ok: false, text: expect.stringContaining("may have arrived there; it was not sent again") });
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it("gives a teammate's result on another server to the bot that handed it alone", () => {
+ const s = setup();
+ const node = handed(s);
+ const parent = s.coordinator.node("gen-1");
+ expect(s.remote.reportName(node, parent)).toBe("Ada (another server)");
+ expect(s.remote.reportName(node, parent, "chief-id")).toBe("Ada (another server)");
+ expect(s.remote.reportName(node, parent, "local-ada-twin")).toBeUndefined();
+ expect(s.remote.reportName(node, undefined)).toBeUndefined();
+ expect(s.remote.reportName(node, { botId: "gone-bot" })).toBeUndefined();
+ expect(s.remote.reportName({ botId: "chief-id" }, parent)).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(); });
diff --git a/server/host/remote-teammate-handoff.ts b/server/host/remote-teammate-handoff.ts
index 033e74d27b..06ce947557 100644
--- a/server/host/remote-teammate-handoff.ts
+++ b/server/host/remote-teammate-handoff.ts
@@ -8,6 +8,7 @@ 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 { isIdStart } from "../peer-roster.ts";
import { readRemote, sendToRemote, type RemoteResult, type RemoteTeammate, type RemoteTeammates } from "../remote-teammates.ts";
import { redactSecretsInText } from "../redact.ts";
import { parseJson } from "../schema.ts";
@@ -30,9 +31,19 @@ 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;
+/** The work thread of a hand-off with `thread: "new"` starts with this, after the teammate's address: it never goes on in an earlier conversation. */
+const NEW_THREAD = "new:";
-const workSchema = z.object({ version: z.literal(1), work: z.record(z.string(), z.object({ teammate: z.string(), thread: z.string(), at: z.number() })) });
+const conversationSchema = z.object({ teammate: z.string(), thread: z.string(), at: z.number() });
+const workSchema = z.object({
+ version: z.literal(1),
+ /** By hand-off: the other server's thread, or none yet while the work is being sent. */
+ work: z.record(z.string(), conversationSchema.extend({ thread: z.string().optional() })),
+ /** By standing work thread here: the other server's thread a later hand-off goes on in. */
+ conversations: z.record(z.string(), conversationSchema).default({}),
+});
type Sent = z.output<typeof workSchema>["work"][string];
+type Conversation = z.output<typeof conversationSchema>;
export interface RemoteHandoffContext {
sender: { id: string; name: string };
@@ -71,19 +82,21 @@ export function createRemoteHandoff(deps: RemoteHandoffDeps) {
const nameOf = (botId: string) => teammateOf(botId)?.name ?? "Teammate";
let sent: Record<string, Sent> = {};
+ let conversations: Record<string, Conversation> = {};
try {
const parsed = workSchema.safeParse(parseJson(readFileSync(deps.file, "utf8")));
- if (parsed.success) sent = parsed.data.work;
+ if (parsed.success) ({ work: sent, conversations } = parsed.data);
} 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)}`); }
+ try { writeFileAtomic(deps.file, JSON.stringify({ version: 1, work: sent, conversations }), { 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; }
+ for (const [key, entry] of Object.entries(conversations)) if (entry.at < cutoff) { delete conversations[key]; changed = true; }
if (changed) save();
};
@@ -92,7 +105,9 @@ export function createRemoteHandoff(deps: RemoteHandoffDeps) {
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;
+ // An id start names a bot here only as it would anywhere else: 8 characters or more, so "Ad" is no prefix of "ada-…".
+ const ownId = (id: string) => id.toLowerCase() === lower || (isIdStart(wanted) && id.toLowerCase().startsWith(lower));
+ if (!named || deps.localBots().some((bot) => ownId(bot.id) || 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;
}
@@ -119,7 +134,7 @@ export function createRemoteHandoff(deps: RemoteHandoffDeps) {
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}`;
+ const threadId = `${botId}:${call.thread === "new" ? `${NEW_THREAD}${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 } : {}) });
@@ -164,14 +179,29 @@ export function createRemoteHandoff(deps: RemoteHandoffDeps) {
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;
+ const earlier = sent[node.id]?.teammate === teammate.id ? sent[node.id] : undefined;
+ // Marked before the call: a restart while the other server may have taken the work must not send it again.
+ if (earlier && earlier.thread === undefined) {
+ return failed(`This server stopped while sending the work to ${name}, so it may have arrived there; it was not sent again. Ask ${name} what it got before handing it on again.`);
+ }
+ let thread = earlier?.thread;
+ // Standing work goes on in the conversation the last hand-off in this thread had there, so a follow-up has its context.
+ const standing = !node.threadId.startsWith(`${node.botId}:${NEW_THREAD}`);
+ let goOn = standing && conversations[node.threadId]?.teammate === teammate.id ? conversations[node.threadId]!.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 (!thread && !sent[node.id]) { sent[node.id] = { teammate: teammate.id, at: now() }; save(); }
+ const result = thread ? await read(teammate, thread, { signal })
+ : await send(teammate, { message: brief(node), ...(goOn ? { thread: goOn } : {}), 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 (!thread) {
+ thread = result.answer.thread;
+ sent[node.id] = { teammate: teammate.id, thread, at: now() };
+ if (standing) conversations[node.threadId] = { 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)}` };
}
@@ -184,6 +214,8 @@ export function createRemoteHandoff(deps: RemoteHandoffDeps) {
pause = Math.min(pause * 2, LONGEST_READ_MS);
continue;
}
+ // The other server no longer has that conversation, and took nothing: the work starts a new one there.
+ if (!thread && goOn && result.problem === "no_thread") { goOn = undefined; delete conversations[node.threadId]; save(); 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));
@@ -219,5 +251,12 @@ export function createRemoteHandoff(deps: RemoteHandoffDeps) {
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 };
+ /** A teammate on another server is no bot here, so the room checks can't place it: its result is the requester's alone,
+ * while that bot is still here. Its name for the result, or undefined when `readerBotId` may not read it. */
+ function reportName(node: Pick<HandoffView, "botId">, parent: Pick<HandoffView, "botId"> | undefined, readerBotId?: string): string | undefined {
+ if (!isRemoteBotId(node.botId) || !parent || (readerBotId !== undefined && readerBotId !== parent.botId) || !deps.botName(parent.botId)) return undefined;
+ return `${nameOf(node.botId)} (another server)`;
+ }
+
+ return { coordinate, host, agents, resolve, reportName };
}
diff --git a/server/index.ts b/server/index.ts
index 8f5dfc6d23..b8dc0e6504 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -639,7 +639,7 @@ import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners
import { 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 { createRemoteHandoff } from "./host/remote-teammate-handoff.ts";
+import { createWebhookRoutes } from "./routes/webhooks.ts"; import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts"; import { RemoteTeammates } from "./remote-teammates.ts"; import { createRemoteHandoff, isRemoteBotId } 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";
@@ -9435,8 +9435,10 @@ function teammateReportContext(requestId: string, readerBotId?: string): string
const node = coordinator.node(requestId);
const parent = node?.parentId ? coordinator.node(node.parentId) : undefined;
const reader = parent && readerBotId ? { ...parent, botId: readerBotId } : parent;
- if (!node || !reader || roomHandoffProblem(node, reader)) return "[Teammate result withheld or no longer retained]";
- const bot = store.bot(node.botId)?.name;
+ const remote = node && isRemoteBotId(node.botId);
+ const remoteName = remote ? remoteHandoff.reportName(node, parent, readerBotId) : undefined;
+ if (!node || !reader || (remote ? !remoteName : roomHandoffProblem(node, reader))) return "[Teammate result withheld or no longer retained]";
+ const bot = remote ? remoteName : store.bot(node.botId)?.name;
return `${reportNote(bot ?? "Teammate")}\n${JSON.stringify({ bot, task: escapeNotes(node.text), status: node.status, result: escapeNotes(node.result) })}`;
}