Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(coordinate-bots): a run queued for its retry keeps its refusal
Flex Builder1d55de7af95f
diff --git a/server/host/refused-handoffs.test.ts b/server/host/refused-handoffs.test.tsindex 2307a8a5f3..07f25c365a 100644--- a/server/host/refused-handoffs.test.ts+++ b/server/host/refused-handoffs.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import type { RosterMember } from "../peer-roster.ts";+import type { RoutineRunStatus } from "../../shared/routines.ts";import { createRefusedHandoffs } from "./refused-handoffs.ts";import type { Delivery } from "./person-inbox.ts";@@ -13,13 +14,14 @@ const mausbot: RosterMember = { id: "maus", name: "MausBot", visibility: { peoplconst bots = [rooms, hours, books, ledger, mausbot];const SAID = "Rooms couldn't hand this to Bookkeeping, because they're shared with different people. Nothing was sent.";+const LEDGER_SAID = "Rooms couldn't hand this to Ledger, because they're shared with different people. Nothing was sent.";const r1 = { id: "run_1", routineId: "r1", botId: "rooms" }, r2 = { id: "run_2", routineId: "r2", botId: "rooms" };-function fixture(over: { writer?: string; asked?: string | null; run?: boolean; own?: boolean } = {}) {+function fixture(over: { writer?: string; asked?: string | null; run?: boolean; own?: boolean; status?: (id: string) => RoutineRunStatus | undefined } = {}) {const lines: Array<{ to: string; delivery: Delivery }> = [];let current: typeof r1 | undefined = over.run === false ? undefined : r1;const refused = createRefusedHandoffs({- bots: () => bots, runOf: () => current, writerOf: () => over.writer,+ bots: () => bots, runOf: () => current, statusOf: (id) => over.status?.(id) ?? "running", writerOf: () => over.writer,askedPerson: () => over.asked ?? null, theirOwn: () => over.own === true, inbox: () => ({ deliver: (to, delivery) => { lines.push({ to, delivery }); } }), language: () => undefined,});return { refused, lines, now: (run: typeof r1 | undefined) => { current = run; } };@@ -73,17 +75,49 @@ describe("a routine's refused hand-off", () => {expect(refused.take("t"), "the run that started since never made that call").toBeNull();});- it("keeps nothing for a run that recorded a refusal and never took it, once another run holds the conversation", () => {- const { refused, now } = fixture({ writer: "p_olive", asked: "p_mara" });- refused.settled("t", rooms, ["Ledger"], 403, r1);+ it("keeps a queued run's refusal when another run uses the conversation meanwhile and ends without taking", () => {+ const status = new Map<string, RoutineRunStatus>([["run_1", "queued"], ["run_2", "running"]]);+ const { refused, lines, now } = fixture({ writer: "p_olive", asked: "p_mara", status: (id) => status.get(id) });+ refused.settled("t", rooms, ["Bookkeeping"], 403, r1); // its first start failed: it keeps its id and conversation to start againnow(r2);- refused.settled("t", rooms, ["Bookkeeping"], 403, r2);+ refused.settled("t", rooms, ["Ledger"], 403, r2);+ status.set("run_2", "cancelled"); // cancelled without taking: nothing of its own is ever said+ status.set("run_1", "running");+ now(r1);+ expect(refused.take("t"), "the run still to finish says what it was refused").toBe(SAID);+ expect(lines.map((line) => line.to), "and its writer hears it, once").toEqual(["p_olive"]);+ expect(refused.take("t")).toBeNull();+ });++ it("says the ending run's refusal and leaves a run still queued its own for when it resumes", () => {+ const status = new Map<string, RoutineRunStatus>([["run_1", "running"], ["run_2", "queued"]]);+ const { refused, now } = fixture({ writer: "p_olive", asked: "p_mara", status: (id) => status.get(id) });+ refused.settled("t", rooms, ["Bookkeeping"], 403, r1);+ now(r2);+ refused.settled("t", rooms, ["Ledger"], 403, r2);now(r1);- expect(refused.take("t"), "the run that failed or was cancelled before saying it kept nothing to say").toBeNull();+ expect(refused.take("t"), "the run ending here says only its own").toBe(SAID);+ status.set("run_2", "running");+ now(r2);+ expect(refused.take("t"), "the run that was queued still says its own with the conversation back").toBe(LEDGER_SAID);+ });++ it("drops a finished run's refusal and never says it", () => {+ const status = new Map<string, RoutineRunStatus>([["run_1", "failed"]]);+ const { refused, lines, now } = fixture({ writer: "p_olive", asked: "p_mara", status: (id) => status.get(id) });+ refused.settled("t", rooms, ["Bookkeeping"], 403, r1);+ now(r2);+ status.set("run_2", "running");+ refused.settled("t", rooms, ["Ledger"], 403, r2);+ status.set("run_1", "running");+ now(r1);+ expect(refused.take("t"), "the run that finished before saying it kept nothing to say").toBeNull();+ expect(lines).toEqual([]);});it("says only the refusal of the run that holds the conversation after an abandoned run's is dropped", () => {- const { refused, lines, now } = fixture({ writer: "p_olive", asked: "p_mara" });+ const status = new Map<string, RoutineRunStatus>([["run_1", "failed"], ["run_2", "running"]]);+ const { refused, lines, now } = fixture({ writer: "p_olive", asked: "p_mara", status: (id) => status.get(id) });refused.settled("t", rooms, ["Ledger"], 403, r1);now(r2);refused.settled("t", rooms, ["Bookkeeping"], 403, r2);diff --git a/server/host/refused-handoffs.ts b/server/host/refused-handoffs.tsindex adb8a9b92b..c89c72f3d2 100644--- a/server/host/refused-handoffs.ts+++ b/server/host/refused-handoffs.ts@@ -3,6 +3,7 @@// nothing arrived. The person who wrote the routine reads it in their inbox, whoever else the bot's failures reach.import { namesTeammate, unreachableTeammate, type RosterMember } from "../peer-roster.ts";import { serverLine } from "../server-lines.ts";+import type { RoutineRunStatus } from "../../shared/routines.ts";import type { Delivery } from "./person-inbox.ts";/** The run that made a call, as it was before the call went out: a call can outlive it. */@@ -10,6 +11,11 @@ type Run = { id: string; routineId: string; botId: string };type Refused = { target: RosterMember; from: RosterMember };/** Who each run was refused by, per run and per bot: another run's late answer is never this run's. */type Refusals = Map<string, Map<string, Refused>>;+/** The statuses a run still to finish has: the repo's own set of unfinished rows (routine-run-history.ts, routine-due.ts).+ * Every other status ends the run, and a run that has ended never calls `take()` again. */+const NOT_FINISHED: ReadonlySet<RoutineRunStatus> = new Set<RoutineRunStatus>(["queued", "running", "waiting"]);+/** Whether the run with this status can still say a refusal: it has a row the manager would hand `take()`, and has not ended. */+const canSpeak = (status: RoutineRunStatus | undefined): boolean => status !== undefined && NOT_FINISHED.has(status);export interface RefusedHandoffDeps {bots(): readonly RosterMember[];@@ -17,6 +23,9 @@ export interface RefusedHandoffDeps {hides?(from: RosterMember, target: RosterMember): boolean;/** The run this conversation is, when it is one. */runOf(threadId: string): Run | undefined;+ /** Where the run with this id stands: `queued`, `running` or `waiting` while it can still say something, a finished+ * status or nothing at all (its row left the history) once it cannot. */+ statusOf(runId: string): RoutineRunStatus | undefined;/** The person key of who wrote this routine; absent off a Cloud and for a routine nobody wrote. */writerOf(routineId: string): string | undefined;/** Who this bot's failures in this conversation are for. */@@ -46,8 +55,9 @@ export function createRefusedHandoffs(deps: RefusedHandoffDeps) {// The run must still hold this conversation: another run's answer is not this one's.if (deps.runOf(threadId)?.id !== run.id) return;const byRun = refused.get(threadId) ?? new Map<string, Map<string, Refused>>();- // No other run can ever say a refusal here, so none of theirs is worth keeping once one is recorded.- for (const id of byRun.keys()) if (id !== run.id) byRun.delete(id);+ // A run that has ended can never say its refusal, so it keeps none; one still queued for its second start keeps its+ // id and conversation and can, so it does. The run that made this call keeps its own either way.+ for (const id of byRun.keys()) if (id !== run.id && !canSpeak(deps.statusOf(id))) byRun.delete(id);const mine = byRun.get(run.id) ?? new Map<string, Refused>();for (const raw of named) {const target = status >= 400 ? unreachableTeammate(deps.bots(), from, raw, (bot) => deps.hides?.(from, bot) === true) : null;@@ -62,10 +72,14 @@ export function createRefusedHandoffs(deps: RefusedHandoffDeps) {/** The run in this conversation is ending well: what it must say instead, once; null when nothing was refused, or another run was. */take(threadId: string): string | null {const run = deps.runOf(threadId), byRun = refused.get(threadId);- if (byRun) for (const id of byRun.keys()) if (id !== run?.id) byRun.delete(id);const seen = [...(run ? byRun?.get(run.id)?.values() ?? [] : [])];- // Another run's records here belong to a run that no longer holds the thread, so they can never be said.- refused.delete(threadId);+ if (byRun) {+ // Said now or never: the run ending here keeps nothing, nor does one that has ended since. A run still queued for+ // its second start, or running, may yet say its own, so its records stay.+ for (const id of byRun.keys()) if (id === run?.id || !canSpeak(deps.statusOf(id))) byRun.delete(id);+ if (byRun.size) refused.set(threadId, byRun);+ else refused.delete(threadId);+ }if (!seen.length) return null;const said = words(threadId, seen);const writer = run && deps.writerOf(run.routineId);diff --git a/server/index.ts b/server/index.tsindex 954b81ad1e..c3102aaa28 100644--- a/server/index.ts+++ b/server/index.ts@@ -2789,7 +2789,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersconst imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,log: line => console.warn(line) });