Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Let a one-on-one goal step hand work to teammates (#4370)
Aditya Umaleee98c5149b07
diff --git a/server/host/message-pages.ts b/server/host/message-pages.tsindex dbfecce86b..892604d2f1 100644--- a/server/host/message-pages.ts+++ b/server/host/message-pages.ts@@ -1,4 +1,4 @@-import type { Message } from "../store.ts";+import type { Message, Store } from "../store.ts";import { toolResultPrefix } from "../tool-results.ts";const MESSAGE_PAGE_MAX = 200;@@ -31,3 +31,37 @@ export function pageMessage(message: Message): Message | Record<string, unknown>if (output === undefined || output.length <= TOOL_OUTPUT_PREVIEW) return slim;return { ...slim, tool: { ...tool, output: toolResultPrefix(output, TOOL_OUTPUT_PREVIEW), clipped: true } };}++/** A conversation's messages one page at a time (newest first when `before` is absent), and the page around one message. */+export function messagePages(store: Pick<Store, "messagesFor" | "messagesTail" | "activeLeaf">) {+ function messagePage(threadId: string, limit: number | undefined, before?: string | null) {+ if (limit === undefined) {+ return { messages: store.messagesFor(threadId), activeLeafId: store.activeLeaf(threadId) };+ }+ if (!before) {+ const tail = store.messagesTail(threadId, limit);+ return { messages: tail.messages.map(pageMessage), hasMore: tail.hasMore, activeLeafId: tail.activeLeafId };+ }+ const all = store.messagesFor(threadId);+ const end = all.findIndex((msg) => msg.id === before);+ const stop = end === -1 ? all.length : end;+ const start = Math.max(0, stop - limit);+ return {+ messages: all.slice(start, stop).map(pageMessage),+ hasMore: start > 0,+ activeLeafId: store.activeLeaf(threadId),+ };+ }++ function messageWindow(threadId: string, messageId: string, limit: number) {+ const all = store.messagesFor(threadId);+ const index = all.findIndex((message) => message.id === messageId);+ if (index < 0) return null;+ const before = Math.floor((limit - 1) / 2);+ const start = Math.max(0, Math.min(index - before, all.length - limit));+ const stop = Math.min(all.length, start + limit);+ return { messages: all.slice(start, stop).map(pageMessage), hasMore: start > 0 };+ }++ return { messagePage, messageWindow };+}diff --git a/server/host/one-on-one-goals.ts b/server/host/one-on-one-goals.tsindex d91bdb4b29..10c558e178 100644--- a/server/host/one-on-one-goals.ts+++ b/server/host/one-on-one-goals.ts@@ -21,6 +21,8 @@ export interface OneOnOneGoalDeps {requestMessageId: string;origin: WorkOrigin;unattended: boolean;+ /** The goal run this step belongs to: the step is its own turn, so it can hand work to teammates. */+ goalRunId: string;onSettled: (outcome: HostTurnResult) => void;}): Promise<unknown>;isUnattended(botId: string, threadId: string): boolean;@@ -115,6 +117,7 @@ export function createOneOnOneGoals(deps: OneOnOneGoalDeps) {requestMessageId: request.id,origin: request.origin,unattended: deps.isUnattended(bot.id, threadId),+ goalRunId: run.runId,onSettled: settle,});} catch (error) {@@ -209,7 +212,12 @@ export function createOneOnOneGoals(deps: OneOnOneGoalDeps) {return true;}- return { start, stop };+ function isLive(threadId: string, runId: string): boolean {+ const goal = live.get(threadId);+ return Boolean(goal && !goal.cancelled && goal.run.runId === runId);+ }++ return { start, stop, isLive };}export type OneOnOneGoals = ReturnType<typeof createOneOnOneGoals>;diff --git a/server/index.ts b/server/index.tsindex e31156b78c..e3a1b4419b 100644--- a/server/index.ts+++ b/server/index.ts@@ -293,7 +293,7 @@ import { createDelegatedLevel } from "./host/delegated-level.ts";import { createLiveApprovalMode } from "./host/live-approval.ts";import { CONSENT_RULE, escapeNotes, labelledLine, OUTSIDE, peerLineText, peerProvenanceNote, reportNote, requestWorkOrigin, type WorkOrigin } from "./peer-provenance.ts"; import { lineNote, PROVENANCE_PROMPT } from "./provenance-label.ts"; import { openRoomThread } from "./host/room-new-thread.ts"; import { createLineLabels } from "./host/line-labels.ts";import { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";-import { pageMessage, pageSize, slimMessage } from "./host/message-pages.ts";+import { messagePages, pageSize, slimMessage } from "./host/message-pages.ts";import { createTeammatePrompts } from "./host/teammate-prompts.ts";import { createQueuedReason } from "./host/queued-reason.ts";import { ReplayBuffer } from "./host/sse-replay.ts";@@ -2050,7 +2050,10 @@ function settleDirectCoordination(generation: string | undefined, outcome: DirecdirectCoordinationSettlers.delete(generation);const node = coordinator.node(settler?.nodeId ?? generation);const result = hostTurnResult(node, generation, outcome);- if (settler) { settler.settle(result); return; }+ if (settler) {+ settler.settle(result);+ if (settler.nodeId !== generation || !node?.goalRunId) return;+ }if (node && !node.parentId && (node.status === "source" || node.status === "running")) coordinator.endTurn(generation, result);}@@ -2842,6 +2845,7 @@ const store = new Store(() => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale,() => sharedMembership() ? undefined : cfg.profile?.name,);+const { messagePage, messageWindow } = messagePages(store);const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusal, cloudThreadStarters, cloudLendingView, cloudReportFromOthers, roomTurnStarted, roomTurnEnded, roomRun } = createCloudLendingTurns({store, cloudHome: CLOUD_HOME !== null, team: CLOUD_TEAM?.name ?? null, directRequest: (threadId) => directRequestOwners.get(threadId), threadStarter: (threadId) => threadStarters.get(threadId),ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),@@ -3885,6 +3889,9 @@ function runRoomRootTurn(node: HandoffView, group: GroupRecord, bot: BotRecord,}function runRootTurn(node: HandoffView, bot: BotRecord, signal: AbortSignal, composed: ComposedTurn): Promise<HostTurnResult> {+ if (composed.turn === "rerun" && node.goalRunId && !oneOnOneGoals.isLive(node.threadId, node.goalRunId)) {+ return Promise.resolve({ ok: false, text: "The goal run this step belonged to ended with the restart." });+ }if (composed.turn === "rerun") store.appendMessage(node.threadId, { role: "bot", kind: "activity", tool: { name: "Resuming after a restart", ok: true } });parkedSeats.delete(node.id);const owner = directRequestOwners.get(node.threadId);@@ -4602,25 +4609,6 @@ store.onChange((change) => {const DEFAULT_PAGE = 50;-function messagePage(threadId: string, limit: number | undefined, before?: string | null) {- if (limit === undefined) {- return { messages: store.messagesFor(threadId), activeLeafId: store.activeLeaf(threadId) };- }- if (!before) {- const tail = store.messagesTail(threadId, limit);- return { messages: tail.messages.map(pageMessage), hasMore: tail.hasMore, activeLeafId: tail.activeLeafId };- }- const all = store.messagesFor(threadId);- const end = all.findIndex((msg) => msg.id === before);- const stop = end === -1 ? all.length : end;- const start = Math.max(0, stop - limit);- return {- messages: all.slice(start, stop).map(pageMessage),- hasMore: start > 0,- activeLeafId: store.activeLeaf(threadId),- };-}-function guardedRequestSnapshot(botId: string, threadId: string, sendId: string) {if (!store.taskByThread(botId, threadId)) throw requestConflict("No such conversation for this bot");const activeLeafId = store.activeLeaf(threadId);@@ -4670,16 +4658,6 @@ function settleTrackedRequest(threadId: string, incoming: ReadonlySet<string> =store.patchMessage(threadId, source.id, { requestPending: false }); savedSteps.requestSettled({ botId: bot.id, threadId, request: source, reply: terminal, after: messages, generations: owner.generations, automated: !personRequest(owner) });}-function messageWindow(threadId: string, messageId: string, limit: number) {- const all = store.messagesFor(threadId);- const index = all.findIndex((message) => message.id === messageId);- if (index < 0) return null;- const before = Math.floor((limit - 1) / 2);- const start = Math.max(0, Math.min(index - before, all.length - limit));- const stop = Math.min(all.length, start + limit);- return { messages: all.slice(start, stop).map(pageMessage), hasMore: start > 0 };-}-interface SseClient {res: ServerResponse;admin: boolean;@@ -7672,6 +7650,8 @@ async function beginTurn(onTurnSettled?: () => void;/** The turn's outcome, for a caller that runs it outside any coordinated work. */onSettled?: (outcome: HostTurnResult) => void;+ /** A one-on-one goal step: a card continuation that is still its own turn, as a room goal step is. */+ goalRunId?: string;coordination?: { id: string; resumed: boolean; settle: (outcome: HostTurnResult) => void };/** A person's own send: it may run beside a room turn on another thread. */ allowRoomTurnElsewhere?: boolean;},@@ -7871,10 +7851,11 @@ async function beginTurn(directTurnDispatchClaims.set(threadId, { id: dispatchClaimId, botId, threadId, phase: "setup" }); liveTurns.dispatchStarted(threadId);directTurnBots.set(threadId, bot);beginInternalCapabilityGeneration(threadId, dispatchClaimId);- if (!opts?.coordination && !opts?.compactOnly && !opts?.cardContinuation) {+ if (!opts?.coordination && !opts?.compactOnly && (!opts?.cardContinuation || opts.goalRunId)) {const opener = handoffOpener({ botId: bot.id, threadId }, threadId);coordinator.beginTurn({ id: dispatchClaimId, address: { botId: bot.id, threadId }, brief: resolvedImages.text,- level: approvalModeForTurn(bot, commsDepth > 0, threadId), ...(opener ? { opener } : {}), origin: requestOrigin });+ level: approvalModeForTurn(bot, commsDepth > 0, threadId), ...(opener ? { opener } : {}), origin: requestOrigin,+ ...(opts?.goalRunId ? { goalRunId: opts.goalRunId } : {}) });}if (!opts?.computerSelectionContinuation && !opts?.cardContinuation && !opts?.automationSource && !opts?.unattended &&!opts?.commsDepth && !opts?.coordination && !inheritedTeamComputer(bot) && bot.computer !== "off" && agentsMounted) {@@ -8708,8 +8689,11 @@ async function beginTurn(});const rows = takeoverScope ? limitTakeover.carriedOn(current, threadId, current.modelSelection, checked.selection, { scope: takeoverScope, ...(e instanceof TurnUsageLimitRefusedError && e.resetsAt ? { resetsAt: e.resetsAt } : {}) }): [{ name: `recovery: Automatic recovery: ${instance.displayName || instance.driverKind} could not start. Trying ${target.displayName || target.driverKind} · ${checked.selection.model} once in this thread.`, ok: true }]; for (const tool of rows) store.appendMessage(threadId, { role: "bot", kind: "activity", tool });- if (opts?.coordination || opts?.onSettled) directCoordinationSettlers.delete(dispatchClaimId);- else settleDirectCoordination(dispatchClaimId, { ok: false, text: message });+ if (opts?.coordination || opts?.onSettled) {+ directCoordinationSettlers.delete(dispatchClaimId);+ // The backup begins a new root for a goal step; this attempt's root ends here.+ if (opts.goalRunId) coordinator.endTurn(dispatchClaimId, { ok: false, text: message });+ } else settleDirectCoordination(dispatchClaimId, { ok: false, text: message });await startTurn(bot.id, text, { ...opts, threadId, userMessage, editedMessageId: undefined,automaticRecoveryAttempted: true, automaticRecoveryIndex: nextIndex + 1 });// The backup now owns these callbacks: publish no failed result and release no queued receipt in between.diff --git a/server/room-roots.e2e.test.ts b/server/room-roots.e2e.test.tsindex d2ec285067..0986685cf8 100644--- a/server/room-roots.e2e.test.ts+++ b/server/room-roots.e2e.test.ts@@ -565,3 +565,68 @@ it("R8 runs a chained @mention as a root of its own, with the hop recorded", ()expect(nothingLive(f)).toEqual([]);expect((await f.roomView(room.id))).toMatchObject({ working: false, busyBotId: null });}), hostTimeout(60_000));++const goalDone = (detail: string) => `<openmaus-goal>${JSON.stringify({ status: "completed", detail })}</openmaus-goal>`;+const sendGoal = (f: any, bot: { id: string; threadId: string }, text: string) =>+ f.api("POST", `/api/bots/${bot.id}/messages`, { text, mode: "goal", threadId: bot.threadId });++it("R9 a one-on-one goal step hands work to a teammate from its own root, and the root ends with the step", () => scenario(async (f) => {+ const mira = await f.bot("Mira", "Leadership");+ const clive = (await f.bots()).find((bot: any) => bot.id === f.clive.id);+ f.script(f.clive.id,+ { key: "C-STEP", match: ["R9-GOAL"], steps: [{ arguments: { bot_ids: [mira.id], message: "R9-BRIEF: check the export numbers." } }],+ reply: `R9-SENT: Mira is on it.\n${goalDone("Mira is checking the numbers.")}` },+ { key: "C1", match: ["R9-RESULT"], reply: "R9-FINAL: confirmed, 42." });+ f.script(mira.id, { key: "M0", match: ["R9-BRIEF"], reply: "R9-RESULT: the numbers add up." });+ expect((await sendGoal(f, clive, "R9-GOAL: have Mira check the export numbers.")).status).toBe(202);+ await expect.poll(() => f.db().assignments.find((row: any) => row.parentId)?.status, { timeout: 30_000 }).toBe("completed");+ const card = (await f.messages(clive.threadId)).find((message: any) => message.kind === "goal.run");+ const root = f.db().assignments.find((row: any) => !row.parentId);+ const child = f.db().assignments.find((row: any) => row.parentId);+ expect(root).toMatchObject({ goalRunId: card.goalRun.runId, assignee: { botId: f.clive.id, destination: { threadId: clive.threadId } } });+ expect(child).toMatchObject({ parentId: root.id, rootId: root.id, status: "completed", result: "R9-RESULT: the numbers add up.",+ assignee: { botId: mira.id }, requester: { kind: "bot_turn", botId: f.clive.id, threadId: clive.threadId } });+ await expect.poll(async () => (await f.messages(clive.threadId)).find((message: any) => message.kind === "goal.run")?.goalRun?.status, { timeout: 15_000 }).toBe("completed");+ await f.final(clive.threadId, "R9-FINAL", 45_000);+ await expect.poll(() => nothingLive(f), { timeout: 15_000 }).toEqual([]);+ expect(f.turns().map((record: any) => record.planKey)).toEqual(["C-STEP", "M0", "C1"]);+}), hostTimeout(120_000));++it("R9 does not rerun a one-on-one goal step after a restart: its goal run ended with the restart", () => scenario(async (f) => {+ const clive = (await f.bots()).find((bot: any) => bot.id === f.clive.id);+ f.script(f.clive.id, { key: "C-STEP", match: ["R9R-GOAL"], readyFile: f.ready("step"), gateFile: f.gate("step"), reply: "never" });+ expect((await sendGoal(f, clive, "R9R-GOAL: publish the export page.")).status).toBe(202);+ await expect.poll(() => existsSync(f.ready("step")), { timeout: 30_000 }).toBe(true);+ const card = (await f.messages(clive.threadId)).find((message: any) => message.kind === "goal.run");+ await expect.poll(() => f.db().assignments.find((row: any) => !row.parentId)?.status, { timeout: 15_000 }).toBe("running");+ const step = f.db().assignments.find((row: any) => !row.parentId);+ expect(step).toMatchObject({ goalRunId: card.goalRun.runId, executions: 1 });+ await f.restart("SIGTERM");+ f.open("step");+ await expect.poll(() => f.db().assignments.find((row: any) => row.id === step.id)?.status, { timeout: 30_000 }).toBe("failed");+ expect(f.db().assignments.find((row: any) => row.id === step.id)).toMatchObject({ restarts: 1, result: GOAL_RUN_ENDED });+ await f.settle(1_500);+ expect(f.turns(f.clive.id).map((record: any) => record.planKey)).toEqual([]);+ expect(await f.chips(clive.threadId, RERUN_CHIP)).toHaveLength(0);+ await expect.poll(() => nothingLive(f), { timeout: 15_000 }).toEqual([]);+}), hostTimeout(90_000));++it("R9 a one-on-one goal step still asks the person first when the bot must ask before contacting other bots", () => scenario(async (f) => {+ const mira = await f.bot("Mira", "Leadership");+ const clive = (await f.bots()).find((bot: any) => bot.id === f.clive.id);+ expect((await f.api("PATCH", `/api/bots/${clive.id}`, { approvePeerComms: true, approvalMode: "ask" })).status).toBe(200);+ f.script(clive.id,+ { key: "C-STEP", match: ["R9A-GOAL"], steps: [{ arguments: { bot_ids: [mira.id], message: "R9A-BRIEF: check the export numbers." }, expectError: true }],+ reply: `R9A-ASKED: I asked before contacting Mira.\n${goalDone("Asked first.")}` });+ expect((await sendGoal(f, clive, "R9A-GOAL: have Mira check the export numbers.")).status).toBe(202);+ const asked = async () => (await f.messages(clive.threadId)).find((message: any) => message.card?.tool === "delegate_bot");+ await expect.poll(async () => Boolean(await asked()), { timeout: 30_000 }).toBe(true);+ expect(f.db().assignments.filter((row: any) => row.parentId)).toEqual([]);+ const card = await asked();+ expect((await f.api("POST", `/api/bots/${clive.id}/respond`, { threadId: clive.threadId, requestId: card.card.requestId, behavior: "deny" })).status).toBe(200);+ await expect.poll(async () => (await f.messages(clive.threadId)).find((message: any) => message.kind === "goal.run")?.goalRun?.status, { timeout: 30_000 }).toBe("completed");+ await f.settle(1_000);+ expect(f.db().assignments.filter((row: any) => row.parentId)).toEqual([]);+ expect(f.turns(mira.id)).toEqual([]);+ await expect.poll(() => nothingLive(f), { timeout: 15_000 }).toEqual([]);+}), hostTimeout(90_000));