Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chief answers for the person: review follow-ups from #4120
Doğukaan Kılıçarslan4537ce86ff38
diff --git a/docs/verification/question-cards.md b/docs/verification/question-cards.mdindex dae332e13f..6d9df8f357 100644--- a/docs/verification/question-cards.md+++ b/docs/verification/question-cards.md@@ -72,7 +72,7 @@ Staff, hands Mira work. Expected:question). As her Chief, Clive sends the answer with that thread id: it answers the card for the person (receipt`injected`), her turn carries on with `@Clive answered for the person: …`, the card says Clive answered, and no work ishanded out. When Clive is not her Chief, the same thread id is refused as above and the question stays the person's.- So it is when a webhook starts Clive's turn: it does not list the question either. The person can still change Clive's+ When a webhook starts Clive's turn, the question is not listed either. The person can still change Clive'sanswer on the card, and Mira gets a new turn with it.Unit tests for the relay's rules (which thread, which sender, sign-ins, work handed out this turn, an engine that cannotdiff --git a/server/host/question-routing.ts b/server/host/question-routing.tsindex 7b53081e73..b9bba243be 100644--- a/server/host/question-routing.ts+++ b/server/host/question-routing.ts@@ -147,9 +147,9 @@ export function createQuestionRouting(deps: QuestionRoutingDeps) {/** What the Chief's turns list: the questions `teammates` (those it manages) wait on the person for, in threads the Chief* did not open on them and it may read (`readable`); at most ten. */- function waitingForPerson(chief: BotRecord, teammates: readonly BotRecord[], readable: (threadId: string) => boolean = () => true): Array<{ bot: string; threadId: string; thread: string; question: string; since: number }> {+ function waitingForPerson(chief: BotRecord, teammates: readonly BotRecord[], readable: (threadId: string, botId: string) => boolean = () => true): Array<{ bot: string; threadId: string; thread: string; question: string; since: number }> {return teammates.flatMap((teammate) => store.tasks(teammate.id)- .filter((task) => task.activity === "waiting-on-you" && task.archivedAt === undefined && task.openedBy?.botId !== chief.id && readable(task.threadId))+ .filter((task) => task.activity === "waiting-on-you" && task.archivedAt === undefined && task.openedBy?.botId !== chief.id && readable(task.threadId, teammate.id)).flatMap((task) => {const asked = forPerson(teammate.id, task.threadId);return asked ? [{ bot: teammate.name, threadId: task.threadId, thread: task.title, question: asked.question, since: asked.row.at }] : [];diff --git a/server/host/teammate-prompts.test.ts b/server/host/teammate-prompts.test.tsindex 523b3b075b..3427cf221f 100644--- a/server/host/teammate-prompts.test.ts+++ b/server/host/teammate-prompts.test.ts@@ -11,17 +11,20 @@ const teammate = { id: "mira", name: "Mira" } as BotRecord;const NOW = 10 * 24 * 60 * 60_000;-function questions(fullAccess: boolean, since = NOW - 60_000, now = NOW): string {+function questions(fullAccess: boolean, since = NOW - 60_000, now = NOW, over: Partial<TeammatePromptDeps> = {}): string {const deps = {now: () => now,store: { bots: [chief, teammate], bot: () => teammate },isUnattended: () => false,startedOutside: () => false,+ asksActingPerson: () => () => true,guestDriven: () => false,confined: () => false,fullAccess: () => fullAccess,readableFrom: () => () => true,- waitingForPerson: () => [{ bot: "Mira", threadId: "t1", thread: "Pricing", question: "Keep the old page?", since }],+ waitingForPerson: (_chief: BotRecord, _teammates: readonly BotRecord[], readable: (threadId: string, botId: string) => boolean) =>+ readable("t1", "mira") ? [{ bot: "Mira", threadId: "t1", thread: "Pricing", question: "Keep the old page?", since }] : [],+ ...over,} as unknown as TeammatePromptDeps;return createTeammatePrompts(deps).questions(chief, "job");}@@ -57,6 +60,14 @@ describe("what a Chief is told about its teammates' questions", () => {}});+ it("on a team, lists only the questions for the person the Chief's turn acts for", () => {+ const asked: Array<[string, string, string]> = [];+ const forOther = questions(true, NOW - 60_000, NOW, { asksActingPerson: (chiefThread) => (threadId, botId) => { asked.push([chiefThread, threadId, botId]); return false; } });+ expect(forOther).toBe("");+ expect(asked).toEqual([["job", "t1", "mira"]]);+ expect(questions(true)).toContain("Keep the old page?");+ });+it("a teammate's words stay in the JSON list, never loose in the sentence that tells the Chief what to do", () => {const told = questions(true, NOW - 2 * LONG_WAIT_MS);expect(told.split("Keep the old page?")).toHaveLength(2);diff --git a/server/host/teammate-prompts.ts b/server/host/teammate-prompts.tsindex 72db0fbd77..0044ab32f2 100644--- a/server/host/teammate-prompts.ts+++ b/server/host/teammate-prompts.ts@@ -18,10 +18,12 @@ export interface TeammatePromptDeps {fullAccess(botId: string, threadId: string): boolean;/** The work in this thread was started by an outside event. */startedOutside(threadId: string): boolean;+ /** Whether the person the turn in `chiefThreadId` acts for is the one a question in `threadId` of `botId` waits on. */+ asksActingPerson(chiefThreadId: string): (threadId: string, botId: string) => boolean;guestDriven(threadId: string): boolean;confined(threadId: string): boolean;readableFrom(threadId: string): (other: string) => boolean;- waitingForPerson(chief: BotRecord, teammates: readonly BotRecord[], readable: (threadId: string) => boolean): WaitingQuestion[];+ waitingForPerson(chief: BotRecord, teammates: readonly BotRecord[], readable: (threadId: string, botId: string) => boolean): WaitingQuestion[];now?(): number;}@@ -57,7 +59,8 @@ export function createTeammatePrompts(deps: TeammatePromptDeps) {if (!actsForPerson(bot, threadId)) return "";const teammates = store.bots.filter((teammate) => teammate.id !== bot.id && !teammate.hidden && canManage(bot, teammate));const now = deps.now?.() ?? waitNow();- const waiting = deps.waitingForPerson(bot, teammates, deps.readableFrom(threadId))+ const readable = deps.readableFrom(threadId), asked = deps.asksActingPerson(threadId);+ const waiting = deps.waitingForPerson(bot, teammates, (other, botId) => readable(other) && asked(other, botId)).map(({ since, ...one }) => ({ ...one, thread: escapeNotes(one.thread).slice(0, 120), question: escapeNotes(one.question).slice(0, 400),...(waitedLong(since, now) ? { waited: waitedWords(since, now) } : {}) }));if (!waiting.length) return "";diff --git a/server/index.ts b/server/index.tsindex 8104d276fa..23104166bf 100644--- a/server/index.ts+++ b/server/index.ts@@ -3843,7 +3843,13 @@ const threadReadableFrom = (threadId: string) => (other: string): boolean => !prconst queuedStatus = createQueuedReason({ botName: (id) => store.bot(id)?.name, threadBusy, groupTurn: (id) => Boolean(activeGroupTurnForBot(id)), behindPerson: queuedBehindPerson,waitsForComputer: (node) => { const seat = parkedSeats.get(node.id); return Boolean(seat && !turnResources.free(seat)); },slots: (id) => ({ busy: store.tasks(id).filter((task) => threadBusy(id, task.threadId)).map(({ threadId, title }) => ({ threadId, title })), limit: maxConcurrentChildThreads(cfg, botThreadsHost(cloudPlanTier.starter())) }) });-const teammatePrompts = createTeammatePrompts({ store, outstandingDirect: (threadId) => coordinator.outstandingDirect(threadId), openPersonCard, queuedStatus, isUnattended, fullAccess: fullAccessForSource, startedOutside: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "outside" || coordinator.active().some((node) => node.threadId === threadId && node.origin?.kind === "outside"), guestDriven: cloudGuestDriven, confined: (threadId) => proactive.fence.confines(threadId), readableFrom: threadReadableFrom, waitingForPerson: (chief, teammates, readable) => questionRouting.waitingForPerson(chief, teammates, readable) });+/** Security invariant: on a team a Chief answers a teammate's question only for the person it is for, and only in a turn that person drives. */+function asksActingPerson(chiefThreadId: string): (threadId: string, botId: string) => boolean {+ if (!CLOUD_TEAM) return () => true;+ const person = actingPeople.requester(chiefThreadId);+ return (threadId, botId) => person !== null && teamOwners.routing.askedPerson(botId, threadId) === person;+}+const teammatePrompts = createTeammatePrompts({ store, asksActingPerson, outstandingDirect: (threadId) => coordinator.outstandingDirect(threadId), openPersonCard, queuedStatus, isUnattended, fullAccess: fullAccessForSource, startedOutside: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "outside" || coordinator.active().some((node) => node.threadId === threadId && node.origin?.kind === "outside"), guestDriven: cloudGuestDriven, confined: (threadId) => proactive.fence.confines(threadId), readableFrom: threadReadableFrom, waitingForPerson: (chief, teammates, readable) => questionRouting.waitingForPerson(chief, teammates, readable) });function queuedBehindPerson(node: HandoffView): { threadId: string; kind: "approval" | "question" | "review"; title: string } | undefined {if (node.groupId || node.status !== "queued" || threadBusy(node.botId, node.threadId) || !botAtThreadCapacity(node.botId, undefined, true)) return undefined;@@ -13948,6 +13954,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const inRoom = targets.filter(target => target.groupId).length, lanes = inRoom > 0 && roomJobs.useLanes(destination!, roomThreadId!, inRoom, mode);const receipts: PeerDeliveryReceipt[] = [];const refused: string[] = [];+ const answeredForPerson = new Set<PeerDeliveryReceipt>();for (const target of targets) {let createdThread: string | undefined;const room = target.groupId ? destination : undefined;@@ -13958,8 +13965,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {// Work a person's request hands on opens in the receiving bot's chat with them when it may use their own apps.const opener = (room ? null : handOnFor) ?? openerFrom(address.threadId);// A Chief answers, for the person, the question a teammate it manages waits on in a thread the Chief did not open.- const forPerson = EXTERNAL || room || fresh || call.answers || mode !== "work" || call.thread === "standing" || !teammatePrompts.actsForPerson(internalSender, internalCapability.threadId) || !canManage(internalSender, recipient) || !threadReadableFrom(internalCapability.threadId)(call.thread) ? undefined : await questionRouting.answerForPerson({ sender: internalSender, senderThreadId: address.threadId, target: recipient, threadId: call.thread, message: call.message });- if (forPerson) { if (forPerson.outcome === "failed") refused.push(forPerson.detail); receipts.push(forPerson); continue; }+ const forPerson = EXTERNAL || room || fresh || call.answers || mode !== "work" || call.thread === "standing" || !teammatePrompts.actsForPerson(internalSender, internalCapability.threadId) || !canManage(internalSender, recipient) || !threadReadableFrom(internalCapability.threadId)(call.thread) || !asksActingPerson(internalCapability.threadId)(call.thread, recipient.id) ? undefined : await questionRouting.answerForPerson({ sender: internalSender, senderThreadId: address.threadId, target: recipient, threadId: call.thread, message: call.message });+ if (forPerson) { if (forPerson.outcome === "failed") refused.push(forPerson.detail); else answeredForPerson.add(forPerson); receipts.push(forPerson); continue; }const continued = room || fresh ? undefined : workThreadFor(store, { botId: target.botId, botName: recipient.name, fromBotId: internalSender.id, fromThreadId: address.threadId, thread: call.thread, notice: mode === "notify",answering: coordinator.answersTo(internalCapability.roomHandoffId ?? generation), also: (task) => !CLOUD_TEAM || threadStarters.get(task.threadId) === opener });const relayed = EXTERNAL || (!call.answers && (room || fresh || mode === "consult")) ? undefined : await questionRouting.relay({ sender: internalSender, senderThreadId: address.threadId,@@ -14028,11 +14035,14 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}}const sent = refused.length < receipts.length;+ const answeredOnly = answeredForPerson.size > 0 && receipts.every((receipt) => receipt.outcome === "failed" || answeredForPerson.has(receipt));const lead = destination && sent ? roomJobs.describeRoomJobs(destination, roomThreadId!, receipts,{ senderId: internalSender.id, returns, lanes, awaited: reply !== "none" }) : "";if (EXTERNAL) coordinator.endTurn(generation, { ok: sent, text: sent ? "" : refused.join("; ") });const message = reply === "none"? "Sent one way. Nothing comes back and nothing resumes you; continue your turn."+ : answeredOnly+ ? "Answered for the person. Nothing comes back and nothing resumes you; continue your turn and tell the person what you answered.": reply === "poll"? "Handed to the coordinator. Read each result with assignment_status (id: a receipt's requestId, or rootId for the whole call), long-polling with wait_ms.": "End your turn after sending all work. These actual teammates will reply and resume you automatically. Do not poll or wait.";diff --git a/server/teammate-follow-ups.e2e.test.ts b/server/teammate-follow-ups.e2e.test.tsindex 3745f5ca2f..aa033a29a5 100644--- a/server/teammate-follow-ups.e2e.test.ts+++ b/server/teammate-follow-ups.e2e.test.ts@@ -261,6 +261,7 @@ it("P1 lets Clive, as Mira's Chief, answer for the person the question she asksexpect(f.given("C-ANSWER")).toContain(PERSON_QUESTION);const [sent] = f.replies("C-ANSWER");expect(sent.receipts).toEqual([expect.objectContaining({ outcome: "injected", threadId: chat, detail: expect.stringContaining(`answered its question "${PERSON_QUESTION}" for the person`) })]);+ expect(sent.message, "an answer alone hands no work out, so Clive continues and tells the person").toContain("Answered for the person. Nothing comes back and nothing resumes you");await expect.poll(async () => (await f.messages(chat)).some((message: any) => message.role === "bot" && String(message.text).startsWith("P1-RESULT")), { timeout: 30_000 }).toBe(true);const result = (await f.messages(chat)).find((message: any) => String(message.text).startsWith("P1-RESULT")).text as string;expect(result).toContain("@Clive answered for the person");@@ -328,6 +329,24 @@ it("P4 keeps Mira's question from a Clive turn a webhook started: it is not listexpect(f.children()).toEqual([]);}), hostTimeout(90_000));+it("P7 keeps Mira's question from a Clive turn a scheduled routine started: it is not listed, the thread is refused, and it stays the person's", () => scenario(async (f) => {+ await f.askMeFirst();+ const chat = f.mira.activeTaskId as string;+ askThePerson(f, "P7");+ f.script(f.clive.id, { key: "C-ROUTINE", match: ["P7-ROUTINE"], steps: [{ arguments: { bot_ids: [f.mira.id], message: "Keep it", thread: chat }, expectError: true }], reply: "C-ROUTINE: refused." });+ await f.say(f.mira.id, chat, "P7: redo the pricing page.");+ await expect.poll(async () => (await asking(f, chat)) !== undefined, { timeout: 30_000 }).toBe(true);++ const routine = await f.api("POST", "/api/routines", { name: "P7", prompt: "P7-ROUTINE: tell Mira to keep it.", botId: f.clive.id, schedule: { type: "daily", time: "09:00", weekdays: [1] } });+ expect(routine.status, JSON.stringify(routine.body)).toBe(201);+ expect((await f.api("POST", `/api/routines/${routine.body.routine.id}/run`)).status).toBe(201);+ await expect.poll(() => f.keys(f.clive.id), { timeout: 30_000 }).toEqual(["C-ROUTINE"]);+ expect(f.given("C-ROUTINE")).not.toContain("Teammates you manage wait on the person's answer");+ expect(f.replies("C-ROUTINE")).toEqual([`"${chat}" is not a thread you opened on Mira: use a threadId one of your coordinate_bots receipts gave, or one list_threads shows on them`]);+ expect((await asking(f, chat))?.answered).toBeUndefined();+ expect(f.children()).toEqual([]);+}), hostTimeout(90_000));+it("P5 does not take a message that names other work as the answer to Mira's question to the person", () => scenario(async (f) => {await f.askMeFirst();const chat = f.mira.activeTaskId as string;diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex e99002faec..56be898d30 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -281,7 +281,7 @@"server.teammates.backWithResultsRestart": "Wznowiono po restarcie z wynikami przekazanej pracy, trwa przegląd","server.teammates.handedWork": "przekazana praca","server.teammates.answerPassed": "Odpowiedź przekazana do czekającej pracy",- "server.teammates.answeredForPerson": "Odpowiedziano za tę osobę na pytanie: {name}",+ "server.teammates.answeredForPerson": "Odpowiedziano za tę osobę na pytanie od {name}","server.teammates.personReplied": "{name} odpowiedział","server.teammates.personAssistantAnswered": "Asystent {name} odpowiedział","server.teammates.told": "Powiadomiono: {name}",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 36f21208ea..f645c44681 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -281,7 +281,7 @@"server.teammates.backWithResultsRestart": "После перезапуска продолжено с результатами переданной работы, идёт проверка","server.teammates.handedWork": "переданная работа","server.teammates.answerPassed": "Ответ передан ожидающей работе",- "server.teammates.answeredForPerson": "Дан ответ за человека на вопрос: {name}",+ "server.teammates.answeredForPerson": "Дан ответ за человека на вопрос от {name}","server.teammates.personReplied": "{name} ответил","server.teammates.personAssistantAnswered": "Ассистент {name} ответил","server.teammates.told": "Сообщено: {name}",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 14c34fd934..9b293ed94c 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -228,7 +228,7 @@"server.teammates.backWithResultsRestart": "Після перезапуску повернувся з переданою роботою, триває перевірка","server.teammates.handedWork": "передана робота","server.teammates.answerPassed": "Відповідь передано роботі, що чекала",- "server.teammates.answeredForPerson": "Дано відповідь за людину на запитання: {name}",+ "server.teammates.answeredForPerson": "Дано відповідь за людину на запитання від {name}","server.teammates.personReplied": "{name} відповів","server.teammates.personAssistantAnswered": "Асистент {name} відповів","server.teammates.told": "Повідомлено: {name}",