Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Hand-offs: one quiet line in the receiving bot's main chat that opens the hand-off thread
milind-sonif14966e7faca
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 56731800a9..cd54a26f9d 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -46,6 +46,8 @@ function place(label: string, bots: Bot[], version?: number) {const threads = new Set<string>();/** Each work thread this place opened for a far bot: the job it was opened with names it. */const opened: Array<{ threadId: string; title: string; from: string; brief: string }> = [];+ /** Each hand-off from the far place this place's bot took, as its main chat is told of it. */+ const handed: Array<{ botId: string; threadId: string; from: string; text: string }> = [];const runs: Array<{ botId: string; threadId: string; text: string; resumed: boolean; requester: string; origin: unknown }> = [];const sent: Array<{ recipient: string; threadId: string; roomId?: string }> = [];const results: Array<{ thread: string; name: string; status: string; result: string }> = [];@@ -107,7 +109,7 @@ function place(label: string, bots: Bot[], version?: number) {dataDir: dir, coordinator: () => coordinator, bots: () => bots, bot: (id) => bots.find((bot) => bot.id === id), level: () => "full", paused: (bot) => Boolean((bot as Bot).paused), acceptRefusal: (bot) => (bot as Bot).farWorkRefused ?? null,...(options.tell ? { tellAfterMs: options.tell.afterMs, tellWithinMs: options.tell.withinMs } : {}),openThread: (bot, title, opener, brief) => { const id = `${bot.id}-work-${++openedCount}`; threads.add(id); opened.push({ threadId: id, title, from: opener.name, brief }); return id; },- hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam",+ hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam", handed: (input) => { handed.push(input); },sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId, ...(input.roomId ? { roomId: input.roomId } : {}) }); },resultRow: (parent, child, name) => { results.push({ thread: parent.threadId, name, status: child.status, result: child.result }); for (const listener of resultListeners) listener(); },kick: () => { queueMicrotask(() => { try { coordinator.tick(); } catch { /* closed */ } }); },@@ -194,7 +196,7 @@ function place(label: string, bots: Bot[], version?: number) {}const api = {- dir, bots, runs, sent, results, requests, opened, boot, listen, unplug, shutdown, handOff, keep, ledger,+ dir, bots, runs, sent, results, requests, opened, handed, boot, listen, unplug, shutdown, handOff, keep, ledger,nextResult(): Promise<void> {return new Promise((resolve) => {const listener = () => { resultListeners.delete(listener); resolve(); };@@ -404,6 +406,12 @@ describe("the link between a computer and its Cloud", () => {await until(() => computer.results.length === 2, "the second result is back");expect(cloud.runs.filter((run) => run.botId === "cloud-analyst").map((run) => run.threadId)).toEqual(["cloud-analyst-work-1", "cloud-analyst-work-1"]);expect(cloud.opened).toEqual([{ threadId: "cloud-analyst-work-1", title: "@Writer · work", from: "Writer", brief: "Count the orders" }]);+ // One line per hand-off in the Cloud bot's main chat, each pointing at the thread its work ran in.+ expect(cloud.handed).toEqual([+ { botId: "cloud-analyst", threadId: "cloud-analyst-work-1", from: "Writer", text: "Count the orders" },+ { botId: "cloud-analyst", threadId: "cloud-analyst-work-1", from: "Writer", text: "Now the refunds" },+ ]);+ expect(computer.handed).toEqual([]);});it("a call that got one instruction-only local refusal and one real refusal from the other place fails, and says why", async () => {diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex af3c0af3fe..ffdc18dabf 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -133,6 +133,8 @@ export interface BotLinkDeps {/** Opens the thread another place's work runs in, and returns its id. */openThread(bot: LocalBot, title: string, opener: { botId: string; name: string; threadId: string }, brief: string): string | undefined;hasThread(botId: string, threadId: string): boolean;+ /** Work from the other place reached `botId`'s thread `threadId`: its main chat may say so (server/host/handed-line.ts). */+ handed?(input: { botId: string; threadId: string; from: string; text: string }): void;personName(threadId: string): string | undefined;/** "Sent to …" in the requester's conversation. */sentRow(input: { sender: LocalBot; threadId: string; recipient: { id: string; name: string }; workThreadId: string; nodeId: string; reason?: string; doneWhen?: string;@@ -535,6 +537,7 @@ export function createBotLink(deps: BotLinkDeps) {if (files.length) deps.files?.crossed(node.id, "sent", { botId: address.botId, name: frame.from.name }, files);work.child = node.id;state.work[frame.id] = work;+ deps.handed?.({ botId: bot.id, threadId, from: frame.from.name, text: frame.text });save();coordinator.endTurn(root, { ok: true, text: "" });if (frame.mode === "notify") recordResult(frame.id, { ok: true, text: "" });diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.tsindex 74d82fe25d..6025ce44ab 100644--- a/server/direct-coordination.e2e.test.ts+++ b/server/direct-coordination.e2e.test.ts@@ -18,6 +18,10 @@ const told = (turn: any): string => {return `${turn.system}\n${typeof content === "string" ? content : JSON.stringify(content ?? "")}`;};+/** A helper's main chat after a hand-off: what it held before, and one quiet line that opens the thread the work ran in. */+const withHandedLine = (before: any[], botId: string, threadId: string) => [...before,+ expect.objectContaining({ role: "bot", kind: "activity", threadRef: expect.objectContaining({ botId, threadId }), tool: expect.objectContaining({ nameCode: "chat.notice.askedMe" }) })];+/** With OMB_TEST_DESKTOP_OWNER_TOKEN it runs as the desktop app runs it, every change carrying the app's owner capability. */async function fixture(test: (f: any) => Promise<void>, fakeEnv: NodeJS.ProcessEnv = {}) {const desktopOwner = fakeEnv.OMB_TEST_DESKTOP_OWNER_TOKEN;@@ -191,8 +195,9 @@ it("coordinates a lead and its specialist from ordinary chat, returns to Clive,expect(f.evidence().map((turn: any) => turn.botId)).toEqual([f.chief.id, f.lead.id, f.specialist.id, f.lead.id, f.chief.id]);expect(f.nodes().every((node: any) => !node.groupId && node.status === "completed")).toBe(true);expect((await f.api("/api/bots")).groups).toEqual([]);- expect(await f.messages(f.lead.activeTaskId)).toEqual(originalLead);- expect(await f.messages(f.specialist.activeTaskId)).toEqual(originalSpecialist);+ const workThread = (botId: string) => f.nodes().find((node: any) => node.botId === botId).threadId;+ expect(await f.messages(f.lead.activeTaskId)).toEqual(withHandedLine(originalLead, f.lead.id, workThread(f.lead.id)));+ expect(await f.messages(f.specialist.activeTaskId)).toEqual(withHandedLine(originalSpecialist, f.specialist.id, workThread(f.specialist.id)));const receipt = (await f.messages(f.chief.activeTaskId)).find((message: any) => message.tool?.name === "Sent to Engineering lead");expect(receipt.threadRef).toMatchObject({ botId: f.lead.id, threadId: f.nodes().find((node: any) => node.botId === f.lead.id).threadId });expect(receipt.threadRef.threadId).not.toBe(f.lead.activeTaskId);@@ -368,7 +373,7 @@ it("opens a fresh thread on a teammate with coordinate_bots thread \"new\" and gconst lead = (await f.api("/api/bots")).bots.find((bot: any) => bot.id === f.lead.id);expect(lead.tasks.find((task: any) => task.threadId === child.threadId)).toMatchObject({ title: "NEW_THREAD_BRIEF verify the CSV export yourself", openedBy: { botId: f.chief.id, name: "Clive" } });expect(child.threadId).not.toBe(f.lead.activeTaskId);- expect(await f.messages(f.lead.activeTaskId)).toEqual(originalLead);+ expect(await f.messages(f.lead.activeTaskId)).toEqual(withHandedLine(originalLead, f.lead.id, child.threadId));expect(f.evidence().map((turn: any) => turn.botId)).toEqual([f.chief.id, f.lead.id, f.chief.id]);expect((await f.messages(f.chief.activeTaskId)).some((message: any) => message.tool?.name === "Engineering lead replied" && message.tool.output === "NEW_THREAD_RESULT verified")).toBe(true);}), 45_000);@@ -410,6 +415,35 @@ it("closes a thread \"new\" opened once its result is back, and opens it again fexpect((await leadTask(child.threadId)).archivedAt).toBeGreaterThan(closed.archivedAt);}), 90_000);+it("leaves one quiet line in the teammate's main chat for a hand-off, which opens its thread and is no turn and no context", () => fixture(async f => {+ f.plan[f.chief.id] = { turns: [+ { steps: [{ arguments: { bot_ids: [f.lead.id], message: "OCTOPUS_BRIEF find three octopus facts", thread: "new", title: "Octopus facts" } }], reply: "Asked the lead" },+ { reply: "The lead reported back" },+ ] };+ f.plan[f.lead.id] = { turns: [{ reply: "OCTOPUS_RESULT three facts" }, { reply: "MAIN_CHAT_REPLY hello" }] };+ await f.start();+ expect((await f.wait()).status).toBe("settled");+ const [child] = f.nodes().filter((node: any) => node.botId === f.lead.id);+ expect(child.threadId).not.toBe(f.lead.activeTaskId);+ const lines = (await f.messages(f.lead.activeTaskId)).filter((message: any) => message.threadRef?.threadId === child.threadId);+ expect(lines).toHaveLength(1);+ expect(lines[0]).toMatchObject({ role: "bot", kind: "activity", threadRef: { botId: f.lead.id, threadId: child.threadId, title: "Octopus facts" },+ tool: { name: "Clive asked me: Octopus facts", ok: true, nameCode: "chat.notice.askedMe", nameParams: { bot: "Clive", title: "Octopus facts" } } });+ expect(lines[0].tool).not.toHaveProperty("itemId");+ const leadBot = (await f.api("/api/bots")).bots.find((bot: any) => bot.id === f.lead.id);+ expect(leadBot.tasks.find((task: any) => task.threadId === f.lead.activeTaskId).unread).toBe(true);+ // The hand-off ran in its own thread; the main chat took no turn for the line.+ expect(f.evidence().filter((turn: any) => turn.botId === f.lead.id).map((turn: any) => turn.threadId)).toEqual([child.threadId]);++ await f.cli("send", "--bot", f.lead.id, "--task", f.lead.activeTaskId, "--text", "Hello there");+ expect((await f.cli("wait", "--bot", f.lead.id, "--task", f.lead.activeTaskId, "--timeout", "30")).status).toBe("settled");+ const mainTurn = f.evidence().filter((turn: any) => turn.botId === f.lead.id).at(-1);+ expect(mainTurn.threadId).toBe(f.lead.activeTaskId);+ expect(told(mainTurn)).toContain("Hello there");+ // The line itself never reaches the model (the thread's title may, through the bot's own recent-work notes).+ expect(told(mainTurn)).not.toContain("asked me");+}), 60_000);+it("reruns an identical brief with rework=true in the archived thread \"new\" opened, which leaves the archive while it runs", () => fixture(async f => {const brief = "REWORK_BRIEF run the export check";const gate = join(f.session.info.dataDir, "rework.gate");@@ -432,6 +466,8 @@ it("reruns an identical brief with rework=true in the archived thread \"new\" opf.save();await f.cli("send", "--bot", f.chief.id, "--task", f.chief.activeTaskId, "--text", "Have them run it once more in that thread.");await expect.poll(() => f.nodes().filter((node: any) => node.botId === f.lead.id).at(-1)?.status, { timeout: 15_000 }).toBe("running");+ // The sender's turn records its call once that turn is written down, which can land just after the work starts.+ await expect.poll(() => f.evidence().filter((turn: any) => turn.botId === f.chief.id).at(-1)?.evidence?.some((entry: any) => entry.step?.arguments?.rework === true), { timeout: 15_000 }).toBe(true);const [sent] = f.evidence().filter((turn: any) => turn.botId === f.chief.id).at(-1).evidence.filter((entry: any) => entry.step).map((entry: any) => entry.response.result);expect(sent.isError).toBeFalsy();expect(JSON.parse(sent.content[0].text).receipts[0]).toMatchObject({ outcome: "queued", threadId: child.threadId });diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsindex c044f1d644..2689619773 100644--- a/server/host/bot-link-host.ts+++ b/server/host/bot-link-host.ts@@ -35,6 +35,8 @@ export interface BotLinkHostDeps {level(bot: BotRecord): Level;/** A work thread a far bot opened here is named from the job it handed, behind "@Sender · ". */titleHanded?(botId: string, threadId: string, brief: string, prefix: string): void;+ /** One line in the receiving bot's main chat for each hand-off the other place sends it (server/host/handed-line.ts). */+ handedLine?(input: { botId: string; threadId: string; from: string; text: string }): void;refusal(bot: BotRecord): string | null;/** Why this bot cannot take work from the other place now (server/bot-link/far-side.ts), or null. */acceptRefusal?(bot: BotRecord): string | null;@@ -110,6 +112,7 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {return threadId;},hasThread: (botId, threadId) => Boolean(store.taskByThread(botId, threadId)),+ ...(deps.handedLine ? { handed: deps.handedLine } : {}),personName: deps.personName,files: {carried: deps.files.carried, crossed: deps.files.crossed,diff --git a/server/host/handed-line.test.ts b/server/host/handed-line.test.tsnew file mode 100644index 0000000000..412ad106f6--- /dev/null+++ b/server/host/handed-line.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from "vitest";++import { replayToolCalls } from "../context-rebuild.ts";+import { isContextMessage } from "../delta-context.ts";+import type { Message } from "../store.ts";+import { handedLine, handedSummary, postHandedLine, type HandedLineDeps } from "./handed-line.ts";++function fakeStore(threads: Record<string, { title: string; unread?: boolean }>) {+ const appended: Array<{ threadId: string; message: Omit<Message, "id" | "at"> }> = [];+ const patched: Array<{ botId: string; threadId: string; patch: Record<string, unknown> }> = [];+ const store = {+ taskByThread: (_botId: string, threadId: string) => threads[threadId] ? { threadId, ...threads[threadId] } : null,+ appendMessage: (threadId: string, message: Omit<Message, "id" | "at">) => { appended.push({ threadId, message }); return { ...message, id: `m${appended.length}`, at: 1 }; },+ patchTask: (botId: string, threadId: string, patch: Record<string, unknown>) => { patched.push({ botId, threadId, patch }); return null; },+ } as unknown as HandedLineDeps["store"];+ return { store, appended, patched };+}++describe("the hand-off line in a helper's main chat", () => {+ it("says who asked and for what, opens the hand-off thread, and marks the main chat unread", () => {+ const { store, appended, patched } = fakeStore({ main: { title: "Garden" }, work: { title: "Octopus facts" } });+ const id = postHandedLine({ store, mainThread: () => "main", language: () => undefined },+ { botId: "sage", threadId: "work", from: "Mochi", text: "Find three octopus facts", title: "Octopus facts" });+ expect(id).toBe("m1");+ expect(appended).toEqual([{ threadId: "main", message: {+ role: "bot", kind: "activity",+ tool: { name: "Mochi asked me: Octopus facts", ok: true, nameCode: "chat.notice.askedMe", nameParams: { bot: "Mochi", title: "Octopus facts" } },+ threadRef: { botId: "sage", threadId: "work", title: "Octopus facts" },+ } }]);+ expect(patched).toEqual([{ botId: "sage", threadId: "main", patch: { unread: true } }]);+ });++ it("writes the line in the main chat's language", () => {+ const { store } = fakeStore({ main: { title: "Garden" }, work: { title: "Octopus facts" } });+ const asked: string[] = [];+ postHandedLine({ store, mainThread: () => "main", language: (threadId) => { asked.push(threadId); return undefined; } },+ { botId: "sage", threadId: "work", from: "Mochi", text: "Octopus facts" });+ expect(asked).toEqual(["main"]);+ });++ it("leaves nothing when the work runs in the main chat itself, or either thread is gone", () => {+ const { store, appended, patched } = fakeStore({ main: { title: "Garden" }, work: { title: "Work" } });+ const deps = { store, mainThread: () => "main", language: () => undefined };+ expect(postHandedLine(deps, { botId: "sage", threadId: "main", from: "Mochi", text: "x" })).toBeUndefined();+ expect(postHandedLine(deps, { botId: "sage", threadId: "gone", from: "Mochi", text: "x" })).toBeUndefined();+ expect(postHandedLine({ ...deps, mainThread: () => undefined }, { botId: "sage", threadId: "work", from: "Mochi", text: "x" })).toBeUndefined();+ expect(postHandedLine({ ...deps, mainThread: () => "missing" }, { botId: "sage", threadId: "work", from: "Mochi", text: "x" })).toBeUndefined();+ expect(appended).toEqual([]);+ expect(patched).toEqual([]);+ });++ it("says the request on one line, cut short, when the sender gave no title", () => {+ expect(handedSummary(" Find three\n\noctopus facts ")).toBe("Find three octopus facts");+ const long = handedSummary("word ".repeat(40));+ expect([...long].length).toBeLessThanOrEqual(60);+ expect(long.endsWith("…")).toBe(true);+ expect(handedSummary("ignored", " Octopus facts ")).toBe("Octopus facts");+ });++ it("is never context for the bot's model: not a message, not a replayed tool call", () => {+ const line = { ...handedLine({ from: "Mochi", summary: "Octopus facts", botId: "sage", threadId: "work", threadTitle: "Octopus facts" }), id: "line", at: 2 } as Message;+ expect(isContextMessage(line)).toBe(false);+ const before = { id: "a", at: 1, role: "user", kind: "text", text: "Hello" } as Message;+ const after = { id: "b", at: 3, role: "bot", kind: "text", text: "Hi" } as Message;+ expect(replayToolCalls([before, line, after], { replayToolHistory: true }, {})).toEqual([]);+ });+});diff --git a/server/host/handed-line.ts b/server/host/handed-line.tsnew file mode 100644index 0000000000..12c17c9497--- /dev/null+++ b/server/host/handed-line.ts@@ -0,0 +1,50 @@+// A bot a teammate hands work to does it in a thread of its own, which closes once the result is back. So that opening+// the bot shows the work happened, its main chat gets one quiet line per hand-off ("Mochi asked me: Octopus facts"),+// which opens that thread, and the main chat is marked unread like any other news. The line is an activity row with no+// tool item: it is never context for the bot's model (delta-context.ts isContextMessage, context-rebuild.ts+// replayToolCalls) and it starts no turn. Nothing else is sent: no notification, no card, nothing to answer.+import { serverLine } from "../server-lines.ts";+import type { Message, Store } from "../store.ts";++/** The words the app shows in the viewer's language; `tool.name` keeps them in the main chat's language. */+export const HANDED_LINE_CODE = "chat.notice.askedMe";+const SUMMARY_MAX = 60;++/** What was asked, as the line says it: the title the sender gave, else the start of its message on one line. */+export function handedSummary(text: string, title?: string): string {+ const named = title?.replace(/\s+/g, " ").trim();+ if (named) return named;+ const words = text.replace(/\s+/g, " ").trim();+ const characters = [...words];+ return characters.length <= SUMMARY_MAX ? words : `${characters.slice(0, SUMMARY_MAX - 1).join("").trimEnd()}…`;+}++export function handedLine(input: { from: string; summary: string; botId: string; threadId: string; threadTitle: string; language?: string }): Omit<Message, "id" | "at"> {+ const params = { bot: input.from, title: input.summary };+ return {+ role: "bot", kind: "activity",+ tool: { name: serverLine(input.language, "server.teammates.askedMe", params), ok: true, nameCode: HANDED_LINE_CODE, nameParams: params },+ threadRef: { botId: input.botId, threadId: input.threadId, title: input.threadTitle },+ };+}++export type HandedLineDeps = {+ store: Pick<Store, "appendMessage" | "patchTask" | "taskByThread">;+ /** The bot's main chat with the person. */+ mainThread(botId: string): string | undefined;+ language(threadId: string): string | undefined;+};++/** Leaves the line for one hand-off to `botId`, worked in `threadId`, in the bot's main chat, and marks that chat unread.+ * Nothing when the work runs in the main chat itself. Returns the line's id. */+export function postHandedLine(deps: HandedLineDeps, input: { botId: string; threadId: string; from: string; text: string; title?: string }): string | undefined {+ const main = deps.mainThread(input.botId);+ if (!main || main === input.threadId) return undefined;+ const work = deps.store.taskByThread(input.botId, input.threadId);+ if (!work || !deps.store.taskByThread(input.botId, main)) return undefined;+ const line = handedLine({ from: input.from, summary: handedSummary(input.text, input.title), botId: input.botId, threadId: input.threadId,+ threadTitle: work.title, language: deps.language(main) });+ const { id } = deps.store.appendMessage(main, line);+ deps.store.patchTask(input.botId, main, { unread: true });+ return id;+}diff --git a/server/index.ts b/server/index.tsindex d293fccc02..185b6b6314 100644--- a/server/index.ts+++ b/server/index.ts@@ -332,7 +332,7 @@ import { buildRecoveryText, buildTurnContext, replaysNatively } from "./turn-conimport { Handoffs, isContextMessage, recordHanded, renderUnseen, sessionStart, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";import { extractReplayImages, extractTurnImages, nativeClips, turnMedia, videoFramesWithin } from "./turn-images.ts";import { callTitleExcerpt } from "./thread-title.ts";-import { generateThreadTitle } from "./thread-title-generate.ts"; import { createHandedThreadTitle } from "./host/handed-thread-title.ts";+import { generateThreadTitle } from "./thread-title-generate.ts"; import { createHandedThreadTitle } from "./host/handed-thread-title.ts"; import { postHandedLine, type HandedLineDeps } from "./host/handed-line.ts";import { engineCommandCpuMs, engineProcessExited, engineProcessGone, ENGINE_EXIT_STALL_MS, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts"; import { createDispatchClaims } from "./host/dispatch-claims.ts";import { TurnResources, type TurnOwner } from "./turn-resources.ts";import { createPhoneHold } from "./phone-screen/hold.ts"; import { createPhoneGate } from "./routes/phone-gate.ts";@@ -3841,7 +3841,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });const remoteTeammates = new RemoteTeammates(); const remoteHandoff = createRemoteHandoff({ teammates: remoteTeammates, coordinator: () => coordinator, localBots: () => store.bots, botName: (id) => store.bot(id)?.name, outside: (threadId) => (outsideLineage.outsideDrivenThread(threadId) || outsideLineage.cloudGuestDriven(threadId) ? OUTSIDE_STAYS_HERE : undefined), file: join(DATA_DIR, "remote-teammate-work.json"), log: (line) => console.error(line) }); const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });-const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), 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 linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({+const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => botMainThread(botId) ?? store.bot(botId)?.threadId, language: (threadId) => threadLanguage(threadId) }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), 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 linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },log: line => console.error("coordinator:", line),@@ -13599,7 +13599,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {...(via === "room" ? {} : { threadId: node.threadId }),}));if (!duplicate) {- if (!EXTERNAL) delegatedThisTurn(node.id);+ if (!EXTERNAL) delegatedThisTurn(node.id); if (handedLines && via === "direct" && !post && !call.answers && recipient.id !== internalSender.id) postHandedLine(handedLines, { botId: recipient.id, threadId: node.threadId, from: internalSender.name, text: call.message, ...(call.title ? { title: call.title } : {}) });const sentRowId = post ? undefined : store.appendMessage(address.threadId, sentRow({ sender: internalSender, recipient, threadId: node.threadId, room: addressedRoom, via, language: threadLanguage(address.threadId),reason: call.reason, doneWhen: call.doneWhen ? redactSecretsInText(call.doneWhen) : undefined, title: store.taskByThread(recipient.id, node.threadId)?.title, ...handoffFiles.sentWith(node.id) })).id; if (sentRowId && via !== "room") handoffStatus.track(node.id, address.threadId, sentRowId);}diff --git a/src/locales/en.json b/src/locales/en.jsonindex f0010a77c7..b3058fa2ed 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -439,6 +439,7 @@"server.rooms.compactedRequested": "compacted {bot}'s context ({percent}% full): fresh session with the room's recent messages","server.rooms.compactedThreshold": "{bot}'s context was {percent}% full: compacted to a fresh session with the room's recent messages","server.teammates.sent": "Sent to {bot}",+ "server.teammates.askedMe": "{bot} asked me: {title}","server.checkBack.pending": "Will check back {when}","server.checkBack.started": "Checked back {when}","server.checkBack.cancelled": "Check-back cancelled",@@ -10299,6 +10300,7 @@"chat.notice.waitingApprovalElsewhere": "Waiting on your approval in @{name}","chat.notice.waitingAnswerElsewhere": "Waiting on your answer in @{name}","chat.notice.teammateNeedsInput": "{name} needs your input: {question}",+ "chat.notice.askedMe": "{bot} asked me: {title}","chat.notice.waitingPasswordElsewhere": "Waiting on your {label} in @{name}","chat.notice.waitingSignInElsewhere": "Waiting on you to sign in to {label} in @{name}","chat.notice.waitingConnectElsewhere": "Waiting on you to connect {label} in @{name}",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 7a43dfc41f..a95f6f59f1 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -420,6 +420,7 @@"server.rooms.compactedRequested": "Compactamos o contexto de {bot} ({percent}% ocupado): nova sessão com as mensagens recentes do grupo","server.rooms.compactedThreshold": "Compactamos o contexto de {bot}, que estava {percent}% ocupado: nova sessão com as mensagens recentes do grupo","server.teammates.sent": "Enviado para {bot}",+ "server.teammates.askedMe": "{bot} me pediu: {title}","server.checkBack.pending": "Vai verificar de novo: {when}","server.checkBack.started": "Verificou de novo: {when}","server.checkBack.cancelled": "Verificação cancelada",@@ -10219,6 +10220,7 @@"chat.notice.waitingApprovalElsewhere": "Esperando sua aprovação em @{name}","chat.notice.waitingAnswerElsewhere": "Esperando sua resposta em @{name}","chat.notice.teammateNeedsInput": "{name} precisa da sua resposta: {question}",+ "chat.notice.askedMe": "{bot} me pediu: {title}","chat.notice.waitingPasswordElsewhere": "Esperando você em @{name}: {label}","chat.notice.waitingSignInElsewhere": "Esperando você entrar em {label} em @{name}","chat.notice.waitingConnectElsewhere": "Esperando você conectar {label} em @{name}",