Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(cards): give the engine the person's own words, and close a card only once the engine took it
luishron1232254664d78e4
diff --git a/server/host/ask-cards.test.ts b/server/host/ask-cards.test.tsindex 6abf5f4645..288f5c8b33 100644--- a/server/host/ask-cards.test.ts+++ b/server/host/ask-cards.test.ts@@ -4,7 +4,7 @@ import type { HandoffView } from "../coordinator.ts";import type { Notification } from "../notify.ts";import type { RequestAuth } from "../request-auth.ts";import type { BotRecord, Message } from "../store.ts";-import { askToolName, createAskCards, withoutTypedNote, type AskCardsDeps } from "./ask-cards.ts";+import { askToolName, closeCard, createAskCards, type AskCardsDeps } from "./ask-cards.ts";const AUTH = { kind: "session", scopes: ["client"], session: { id: "s", email: "[email protected]" } } as unknown as RequestAuth;const QUESTION = "What wording should the new footer text use?";@@ -44,10 +44,11 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?const nodes = new Map<string, HandoffView>();const answered: Array<{ id: string; text: string }> = [];const notified: Notification[] = [];- const answers: Array<{ threadId: string; requestId: string; message?: string; engineMessage?: string; behavior?: "close" }> = [];+ const answers: Array<{ threadId: string; requestId: string; message?: string; behavior?: "close" }> = [];const live = new Set(options.live ?? []);const written: unknown[] = [];let refuse: { status: number; error: string } | null = null;+ let afterAnswer: (() => void) | null = null;const deps: AskCardsDeps = {store: store as unknown as AskCardsDeps["store"],node: (id) => nodes.get(id),@@ -59,8 +60,9 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?answerCard: vi.fn(async (input) => {if (refuse) return { ok: false as const, ...refuse };answers.push({ threadId: input.threadId, requestId: input.requestId, ...(input.behavior === "close" ? { behavior: "close" as const }- : { message: input.message, ...(input.engineMessage ? { engineMessage: input.engineMessage } : {}) }) });+ : { message: input.message }) });live.delete(input.requestId);+ afterAnswer?.();return { ok: true as const };}),answeredIn: (threadId, requestId) => (threadId === "inbox" && requestId.startsWith("req") ? "work" : threadId),@@ -84,7 +86,7 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?nodes.set("root", { id: "root", rootId: "root", threadId: "inbox", botId: "scout" } as HandoffView);const say = (threadId: string, text: string) => store.appendMessage(threadId, { role: "bot", kind: "text", text });return { cards, store, rows, notified, answers, answered, node, say, deps, written, open: (requestId: string) => live.add(requestId),- refuse: (value: typeof refuse) => { refuse = value; } };+ refuse: (value: typeof refuse) => { refuse = value; }, afterAnswer: (value: typeof afterAnswer) => { afterAnswer = value; } };}describe("a teammate's NEEDS INPUT question", () => {@@ -353,29 +355,19 @@ describe("a typed line answers a question card", () => {expect(fixed.answers).toEqual([]);});- const NOTE = "[The person typed this in the chat instead of picking an option. Reply to it, and ask again if you still need an answer.]";-- it("answers the card its turn waits on in the bot's own chat, telling only the engine the words were typed, not picked", async () => {+ it("answers the card its turn waits on in the bot's own chat with exactly the person's words", async () => {const w = world({ live: ["req-1"] });const asked = question(w, "chat");const result = await w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-3" });- expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "What time is it?", engineMessage: `${NOTE} What time is it?` }]);+ expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "What time is it?" }]);expect(result).toMatchObject({ status: 202, message: { role: "user", text: "What time is it?", replyToId: asked.id, sendId: "send-3" } });- expect(JSON.stringify(w.written), "nothing the conversation writes carries the note").not.toContain("The person typed this");- expect(JSON.stringify(w.rows("chat"))).not.toContain("The person typed this");});- it("files the note under a structured question's text for the engine, and the plain words for the card", async () => {+ it("files a structured question's answer under its text, as an answer typed on the card would be", async () => {const w = world({ live: ["req-1"] });question(w, "chat", { questionRequest: { version: 1, questions: [{ question: "Should I?", options: [{ label: "Yes" }, { label: "No" }] }] } });await w.cards.typed(AUTH, "chat", "Not yet", undefined, {});- expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "The user answered your questions.\n\nQ: Should I?\nA: Not yet",- engineMessage: `The user answered your questions.\n\nQ: Should I?\nA: ${NOTE} Not yet` }]);- });-- it("keeps the note out of a tool's output that repeats the answer back", () => {- expect(withoutTypedNote(`The user answered your questions.\n\nQ: Should I?\nA: ${NOTE} Not yet`)).toBe("The user answered your questions.\n\nQ: Should I?\nA: Not yet");- expect(withoutTypedNote("ok")).toBe("ok");+ expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "The user answered your questions.\n\nQ: Should I?\nA: Not yet" }]);});it("closes a card that takes no words in the bot's own chat and leaves the line to be sent as the next message", async () => {@@ -421,6 +413,29 @@ describe("a typed line answers a question card", () => {expect(w.answers).toHaveLength(1);});+ it("closes one card when the same send arrives twice at once and a new card opens before its line is written", async () => {+ const w = world({ live: ["req-1"] });+ question(w, "chat", { fixedOptions: true });+ w.afterAnswer(() => {+ w.afterAnswer(null);+ question(w, "chat", { requestId: "req-2", fixedOptions: true });+ w.open("req-2");+ });+ const tries = await Promise.all([1, 2].map(() => w.cards.typed(AUTH, "chat", "Something else first", undefined, { sendId: "send-6" })));+ expect(tries).toEqual([null, null]);+ expect(w.answers.map((answer) => answer.requestId)).toEqual(["req-1"]);+ });++ it("lets a send whose close was refused try again", async () => {+ const w = world({ live: ["req-1"] });+ question(w, "chat", { fixedOptions: true });+ w.refuse({ status: 409, error: "The request is no longer open." });+ expect(await w.cards.typed(AUTH, "chat", "Something else first", undefined, { sendId: "send-7" })).toBeNull();+ w.refuse(null);+ expect(await w.cards.typed(AUTH, "chat", "Something else first", undefined, { sendId: "send-7" })).toBeNull();+ expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", behavior: "close" }]);+ });+it("leaves a line in the bot's own chat to the usual send while two question cards wait there", async () => {for (const second of [{}, { fixedOptions: true }]) {const w = world({ live: ["req-1", "req-2"] });@@ -549,6 +564,44 @@ describe("the chip in the conversation that handed the work on", () => {});});+describe("closing a card the person moved past", () => {+ const setup = () => {+ const card = { id: "m1", at: 1, role: "bot", kind: "options", card: { requestId: "req-1", requestType: "question", options: [], fixedOptions: true } } as unknown as Message;+ const patches: Array<Partial<Message>> = [];+ const live = new Map([["chat:req-1", "m1"]]);+ const store = { patchMessage: (_threadId: string, _id: string, patch: Partial<Message>) => { patches.push(patch); return { ...card, ...patch }; } };+ return { card, patches, live, close: (decline: () => Promise<"rejected" | "unavailable">) =>+ closeCard({ threadId: "chat", requestId: "req-1", card, live, store: store as never, decline }) };+ };++ it("reads closed without an answer once the engine took the decline, and is no longer live while it was on its way", async () => {+ const w = setup();+ let liveWhileDeclining = true;+ expect(await w.close(async () => { liveWhileDeclining = w.live.has("chat:req-1"); return "rejected"; })).toBe("rejected");+ expect(liveWhileDeclining, "the engine settling the request leaves the card to this close").toBe(false);+ expect(w.patches).toEqual([{ card: { ...w.card.card, answered: "unavailable", dismissed: true } }]);+ expect(w.live.has("chat:req-1")).toBe(false);+ });++ it("stays open and live for a tap when the engine did not take the decline, or delivering it failed", async () => {+ for (const decline of [async () => "unavailable" as const, async (): Promise<"rejected"> => { throw new Error("broker gone"); }]) {+ const w = setup();+ expect(await w.close(decline)).toBe("unavailable");+ expect(w.patches).toEqual([]);+ expect(w.live.get("chat:req-1")).toBe("m1");+ }+ });++ it("delivers nothing for a card no turn waits on", async () => {+ const w = setup();+ w.live.clear();+ const decline = vi.fn(async () => "rejected" as const);+ expect(await w.close(decline)).toBe("unavailable");+ expect(decline).not.toHaveBeenCalled();+ expect(w.patches).toEqual([]);+ });+});+describe("askToolName", () => {const bot = (toolScope?: BotRecord["toolScope"]) => ({ modelSelection: { instanceId: "claude", model: "m" }, toolScope }) as BotRecord;const claude = () => ({ kind: "mcp" as const, server: "ogb", name: "ask_user" });diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.tsindex c5dc961307..a811ae18cc 100644--- a/server/host/ask-cards.ts+++ b/server/host/ask-cards.ts@@ -10,7 +10,7 @@ import { allowsTool, type ToolIdentity } from "../../shared/tool-scope.ts";import type { PersonWait } from "../../shared/person-wait.ts";import type { OptionCardData } from "../../shared/wire.ts";import { noticeTool, type ChatNoticeKey } from "../chat-notices.ts";-import type { RuntimeEvent } from "../contracts.ts";+import type { RequestOutcome, RuntimeEvent } from "../contracts.ts";import type { HandoffView } from "../coordinator.ts";import { buildNotification, type Notification } from "../notify.ts";import type { RequestAuth } from "../request-auth.ts";@@ -24,11 +24,9 @@ import { settledWaitingChip } from "../waiting-on-person.ts";const OPEN_QUESTION = "needs-input-";const DAY_MS = 24 * 60 * 60_000;const NEEDS_INPUT_LINE = /^needs input:/i;-const TYPED_IN_CHAT = "[The person typed this in the chat instead of picking an option. Reply to it, and ask again if you still need an answer.]";const hasAttachment = (text: string): boolean => text.includes("<attached-image") || text.includes("<attached-file");-/** Only the engine reads the typed-line note: a tool's output that repeats the answer back shows the person's words alone. */-const CLOSED_BY_TYPING = "The person typed in the chat instead of picking an option; their line comes next.";-export const withoutTypedNote = (text: string): string => text.replaceAll(`${TYPED_IN_CHAT} `, "");+/** How long a send that answered or closed a card keeps it from touching another, while its line is not yet written. */+const SPENT_SEND_MS = 60_000;type Typed = { status: number; message?: Message; error?: string } | null;export interface AskCardsDeps {@@ -47,7 +45,7 @@ export interface AskCardsDeps {/** The parked node's next turn carries the person's answer. */answerNode(id: string, text: string): boolean;/** Answers a card as a tap on it would, with the same checks on who may answer, through an inbox copy too. */- answerCard(input: { auth: RequestAuth; threadId: string; requestId: string; behavior: "answer" | "close"; message?: string; engineMessage?: string }): Promise<{ ok: true } | { ok: false; status: number; error: string }>;+ answerCard(input: { auth: RequestAuth; threadId: string; requestId: string; behavior: "answer" | "close"; message?: string }): Promise<{ ok: true } | { ok: false; status: number; error: string }>;/** The conversation a card in `threadId` was asked in: an inbox copy's original. */answeredIn(threadId: string, requestId: string): string;now?: () => number;@@ -73,6 +71,20 @@ const typedAnswer = (card: OptionCardData, text: string): string => {return questions ? formatQuestionAnswers(questions, [[text]]) : text;};+/** Closes a question card the person moved past without an answer, once the engine takes the decline. While it is on+ * its way the card is not live, so the engine settling the request leaves the card alone; one that did not land leaves+ * the card open and live, for a tap. */+export async function closeCard(input: { threadId: string; requestId: string; card: Message | undefined; live: Map<string, string>;+ store: Pick<Store, "patchMessage">; decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {+ const key = `${input.threadId}:${input.requestId}`, messageId = input.live.get(key);+ if (!messageId || !input.card?.card) return "unavailable";+ input.live.delete(key);+ const outcome = await input.decline().catch((): RequestOutcome => "unavailable");+ if (outcome === "unavailable") input.live.set(key, messageId);+ else input.store.patchMessage(input.threadId, input.card.id, { card: { ...input.card.card, answered: "unavailable", dismissed: true } });+ return outcome;+}+/** The reply up to its NEEDS INPUT line; empty when the line is the whole reply. */function beforeQuestion(text: string): string {const lines = text.split(/\r?\n/);@@ -308,8 +320,9 @@ export function createAskCards(deps: AskCardsDeps) {/** A person's line answers an inbox copy it replies to, or the question card the bot's turn waits on, as a tap would.* In the bot's own chat that is the one question card a turn waits on there, and one that takes no words closes* instead, the line going on as the next message. Null leaves the line to be sent (steered or queued) as usual. Tries- * of one send run one after another. */+ * of one send run one after another, and one that answered or closed a card touches no other. */const typing = new Map<string, Promise<Typed>>();+ const spent = new Map<string, number>();function typed(auth: RequestAuth, threadId: string, text: string, target: Message | undefined,line: { sendId?: string; sender?: Message["sender"] }): Promise<Typed> {if (!line.sendId) return typedOnce(auth, threadId, text, target, line);@@ -327,6 +340,9 @@ export function createAskCards(deps: AskCardsDeps) {// A send tried again touches no card: the same line that answered one is its receipt; anything else goes on to the// usual send, which matches the line it wrote or refuses other words under the same id.const again = line.sendId ? thread.find((message) => message.sendId === line.sendId) : undefined;+ const key = line.sendId ? `${threadId}:${line.sendId}` : "";+ for (const [send, at] of spent) if ((again && send === key) || now() - at > SPENT_SEND_MS) spent.delete(send);+ if (spent.has(key)) return null;if (again) {const answeredCard = again.text === text && (!target || target.id === again.replyToId)&& thread.some((message) => message.id === again.replyToId && message.card?.requestId);@@ -338,10 +354,9 @@ export function createAskCards(deps: AskCardsDeps) {const only = waiting.length === 1 ? waiting[0]! : undefined;const ownChat = !handedOn && !hasAttachment(text) && Boolean(only) && (!target || target.id === only!.id);if (ownChat && !answerableInWords(only!.card)) {- const closed = await deps.answerCard({ auth, threadId, requestId: only!.card!.requestId!, behavior: "close", engineMessage: CLOSED_BY_TYPING });- // Refused (the session ended, the person may not answer it, it is no longer open): the card stays as it is and the- // line is sent as before, steered into the waiting turn or queued behind it.- if (!closed.ok) return null;+ // Closed or not, the line goes on as the next message, steered into the waiting turn or queued behind it.+ if (key) spent.set(key, now());+ if (!(await deps.answerCard({ auth, threadId, requestId: only!.card!.requestId!, behavior: "close" })).ok) spent.delete(key);return null;}const asked = target@@ -352,9 +367,12 @@ export function createAskCards(deps: AskCardsDeps) {const requestId = asked.card.requestId;const origin = deps.answeredIn(threadId, requestId);if (origin === threadId && !((handedOn || ownChat) && deps.live(threadId, requestId))) return null;- const note = ownChat && origin === threadId ? { engineMessage: typedAnswer(asked.card, `${TYPED_IN_CHAT} ${text}`) } : {};- const answered = await deps.answerCard({ auth, threadId, requestId, behavior: "answer", message: typedAnswer(asked.card, text), ...note });- if (!answered.ok) return { status: answered.status, error: answered.error };+ if (key) spent.set(key, now());+ const answered = await deps.answerCard({ auth, threadId, requestId, behavior: "answer", message: typedAnswer(asked.card, text) });+ if (!answered.ok) {+ spent.delete(key);+ return { status: answered.status, error: answered.error };+ }const posted = store.appendMessage(threadId, { role: "user", kind: "text", text, replyToId: asked.id,...(line.sendId ? { sendId: line.sendId } : {}), ...(line.sender ? { sender: line.sender } : {}) });return { status: 202, message: posted };diff --git a/server/index.ts b/server/index.tsindex 1f753eaebb..f2cf9a946f 100644--- a/server/index.ts+++ b/server/index.ts@@ -26,7 +26,7 @@ import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";import { SharedComputerControl } from "./shared-computer-control.ts";import { STATUS_REPLY_TIMEOUT_MS } from "./runtime/status-reply.ts"; import { createCoordinator, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";import { queuedBehindPersonText, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";-import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards, withoutTypedNote } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";+import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, closeCard, createAskCards } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";import { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";@@ -4747,7 +4747,7 @@ async function answerRequest(message?: string,decidedFor?: { id: string; name: string },always?: boolean,- rememberCommand?: boolean, engineMessage = message,+ rememberCommand?: boolean,): Promise<RequestOutcome> {// Snapshot the card BEFORE delivering: delivery synchronously consumes the askMessageByRequest entry.const thread = store.messagesFor(threadId);@@ -4757,14 +4757,15 @@ async function answerRequest(: thread.find((m) => m.card?.requestId === requestId);const card = cardMessage?.card;const remembered = rememberCommand ? pendingCommandRules.get(`${threadId}:${requestId}`) : undefined;- // The live turn owns this question, as it owns Stop and steer. A card closed without an answer says so before the engine's decline settles it, and records no denial.+ // The live turn owns this question, as it owns Stop and steer. A card closed without an answer records no denial.const instance = runningTurnEngines.get(threadId) ?? registry.get(instanceId);- if (behavior === "close" && card) store.patchMessage(threadId, cardMessage!.id, { card: { ...card, answered: "unavailable", dismissed: true } });+ if (behavior === "close") return closeCard({ threadId, requestId, card: cardMessage, live: askMessageByRequest, store,+ decline: async () => instance ? instance.adapter.respondToRequest(threadId, requestId, { behavior: "deny" }) : "unavailable" });let outcome: RequestOutcome = "unavailable";if (instance) {try {// Only a card that offered "Allow for this session" can keep one: never a guest's turn, a sandbox widening or the person's own computer.- outcome = await instance.adapter.respondToRequest(threadId, requestId, { behavior: behavior === "close" ? "deny" : behavior, message: engineMessage, always: always && behavior === "allow" && card?.allowSession === true });+ outcome = await instance.adapter.respondToRequest(threadId, requestId, { behavior, message, always: always && behavior === "allow" && card?.allowSession === true });} catch {outcome = "unavailable";}@@ -4784,7 +4785,7 @@ async function answerRequest(if (settled) store.patchMessage(threadId, cardMessage.id, { card: { ...settled, answeredText: message } });}// Record only verdicts that reached the engine; a question's answer is not a decision.- if (outcome !== "unavailable" && behavior !== "answer" && behavior !== "close") {+ if (outcome !== "unavailable" && behavior !== "answer") {appendDecision(DATA_DIR, {threadId,requestId,@@ -4824,11 +4825,10 @@ async function respondToCard(input: {requestId: string;behavior: "allow" | "deny" | "answer" | "close";message?: string;- /** What the engine reads instead of `message`; the card and every copy of it keep `message`. */ engineMessage?: string;callId?: string;via?: DecisionVia;}): Promise<CardRespondResult> {- const { auth, requestId, behavior, message, engineMessage, callId, via } = input, threadId = automationReports.answeredIn(teamMessages.inbox.answeredIn(input.threadId, requestId), requestId);+ const { auth, requestId, behavior, message, callId, via } = input, threadId = automationReports.answeredIn(teamMessages.inbox.answeredIn(input.threadId, requestId), requestId);// A call outlives the request that started it: the session must still be valid.if (auth.kind === "session" && !sessions.isLive(auth.session.id)) {return { ok: false, status: 401, error: "The session that started this call has ended." };@@ -4845,7 +4845,7 @@ async function respondToCard(input: {await answeringCardAs(auth, threadId, requestId, async () => {const outcome = await answerRequest(threadId, botForThread(bot.id, threadId)?.modelSelection.instanceId ?? "", requestId, behavior, message,- { id: bot.id, name: bot.name }, undefined, undefined, engineMessage,+ { id: bot.id, name: bot.name },);if (outcome === "unavailable" && isPersistentQuestionCard(card) && behavior === "answer" && cardMessage) {const answer = message?.trim() ?? "";@@ -6409,7 +6409,7 @@ bus.subscribe((event: RuntimeEvent) => {const existing = store.messagesFor(event.threadId).find((m) => m.id === messageId)?.tool;toolName = existing?.name ?? "tool";store.patchMessage(event.threadId, messageId, {- tool: { ...existing, name: toolName, ok: event.ok, output: event.output === undefined ? undefined : scrubHeldSecrets(withoutTypedNote(event.output)), ...mcpToolProblem(toolName, event.ok, event.output, Object.keys(cfg.mcpServers ?? {}), threadLanguage(event.threadId)) },+ tool: { ...existing, name: toolName, ok: event.ok, output: event.output === undefined ? undefined : scrubHeldSecrets(event.output), ...mcpToolProblem(toolName, event.ok, event.output, Object.keys(cfg.mcpServers ?? {}), threadLanguage(event.threadId)) },}); void connectionHealth.toolStep({ threadId: event.threadId, generation: activeInternalGenerationByThread.get(event.threadId), tool: toolName, ok: event.ok, output: event.output }).catch(() => {});toolMessageByItem.delete(itemKey);}