Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(skill-burger): resume only unsent delegation requests
Afloat33f62ba94c74
diff --git a/server/skill-burger/delegate-step.ts b/server/skill-burger/delegate-step.tsindex 07ae488edc..c5da643314 100644--- a/server/skill-burger/delegate-step.ts+++ b/server/skill-burger/delegate-step.ts@@ -17,13 +17,17 @@ export interface DelegationState {who: Record<string, { id: string; name: string } | null>;requests: Array<{ part: string; botId: string; name: string; requestId: string }>;replies: Record<string, { name: string; ok: boolean; text: string; round: number }>;+ /** A round still being sent; its requests already accepted work, and only the remaining parts may be sent. */+ pendingSend?: { fixes?: Record<string, string> };}+type DelegateReceipt = { botId: string; name: string; requestId: string };+export interface DelegateExecutors {/** The teammates this bot can hand work to now. */teammates(signal: AbortSignal): Promise<Teammate[]>;/** One coordinate_bots call as this turn: its receipts, or why it was refused. */- delegate(input: { botIds: string[]; message: string; doneWhen?: string; rework?: boolean; consult?: boolean; signal: AbortSignal }): Promise<{ ok: true; receipts: Array<{ botId: string; name: string; requestId: string }> } | { ok: false; error: string }>;+ delegate(input: { botIds: string[]; message: string; doneWhen?: string; rework?: boolean; consult?: boolean; signal: AbortSignal }): Promise<{ ok: true; receipts: DelegateReceipt[] } | { ok: false; error: string; receipts?: DelegateReceipt[] }>;/** A hand-off's status and result, once it can be read. */assignment(id: string, signal: AbortSignal): Promise<Settled | null>;}@@ -85,11 +89,11 @@ export function missingPrompt(missing: DelegateStep["tasks"]): string {/** Sends the round's work: each part's message to whoever does it now, one call per distinct message (at most four* teammates a call). Returns the hand-offs, or why a call was refused. */export async function sendRound(step: DelegateStep, state: DelegationState, fill: (ref: WorkflowRef) => unknown, exec: DelegateExecutors, signal: AbortSignal,- fixes?: Record<string, string>): Promise<{ ok: true; requests: DelegationState["requests"] } | { ok: false; error: string }> {+ fixes?: Record<string, string>, accepted: DelegationState["requests"] = []): Promise<{ ok: true; requests: DelegationState["requests"] } | { ok: false; error: string; requests: DelegationState["requests"] }> {const calls = new Map<string, { parts: string[]; botIds: string[]; message: string; doneWhen?: string }>();for (const task of step.tasks) {const to = state.who[task.bot.name];- if (!to || (fixes && !(task.bot.name in fixes))) continue;+ if (!to || (fixes && !(task.bot.name in fixes)) || accepted.some((request) => request.part === task.bot.name)) continue;const base = textOf(task.message, fill);const message = fixes ? `${fixes[task.bot.name]}\n\nThe work, as first asked:\n${base}` : base;const key = `${message}\u0000${task.doneWhen ?? ""}`;@@ -97,19 +101,19 @@ export async function sendRound(step: DelegateStep, state: DelegationState, fillif (!call.botIds.includes(to.id)) { call.parts.push(task.bot.name); call.botIds.push(to.id); }calls.set(key, call);}- const requests: DelegationState["requests"] = [];+ const requests: DelegationState["requests"] = [...accepted];for (const call of calls.values()) {for (let at = 0; at < call.botIds.length; at += 4) {const botIds = call.botIds.slice(at, at + 4);const sent = await exec.delegate({ botIds, message: call.message, ...(call.doneWhen ? { doneWhen: call.doneWhen } : {}), ...(fixes ? { rework: true } : {}), ...(step.consult ? { consult: true } : {}), signal });- if (!sent.ok) return sent;for (const [index, botId] of botIds.entries()) {- const receipt = sent.receipts.find((one) => one.botId === botId);+ const receipt = sent.receipts?.find((one) => one.botId === botId);if (receipt?.requestId) requests.push({ part: call.parts[at + index]!, botId, name: receipt.name, requestId: receipt.requestId });}+ if (!sent.ok) return { ok: false, error: sent.error, requests };}}- return requests.length ? { ok: true, requests } : { ok: false, error: "no teammate took the work" };+ return requests.length ? { ok: true, requests } : { ok: false, error: "no teammate took the work", requests };}/** The replies, once every hand-off of the round has settled; the names still working while some haven't. */diff --git a/server/skill-burger/executors.ts b/server/skill-burger/executors.tsindex 8118d15a7a..8d84eb668a 100644--- a/server/skill-burger/executors.ts+++ b/server/skill-burger/executors.ts@@ -145,10 +145,10 @@ export function createExecutors(context: ExecutorContext): StepExecutors {botIds: input.botIds, message: input.message, ...(input.doneWhen ? { done_when: input.doneWhen } : {}), ...(input.rework ? { rework: true } : {}), ...(input.consult ? { consult: true } : {}),}, input.signal);const receipts = (Array.isArray(answer.body.receipts) ? answer.body.receipts : []).map(record).flatMap((receipt) => (- receipt && typeof receipt.botId === "string" && typeof receipt.requestId === "string" ? [{ botId: receipt.botId, name: String(receipt.botName ?? receipt.botId), requestId: receipt.requestId }] : []));- if (!answer.ok || !receipts.length) {- const refusedOne = (Array.isArray(answer.body.receipts) ? answer.body.receipts : []).map(record).find((receipt) => receipt?.detail);- return { ok: false, error: String(answer.body.error ?? refusedOne?.detail ?? "the hand-off was refused") };+ receipt && receipt.outcome !== "failed" && typeof receipt.botId === "string" && typeof receipt.requestId === "string" ? [{ botId: receipt.botId, name: String(receipt.botName ?? receipt.botId), requestId: receipt.requestId }] : []));+ if (!answer.ok || !receipts.length || input.botIds.some((botId) => !receipts.some((receipt) => receipt.botId === botId))) {+ const refusedOne = (Array.isArray(answer.body.receipts) ? answer.body.receipts : []).map(record).find((receipt) => receipt?.detail && !receipts.some((one) => one.botId === receipt.botId));+ return { ok: false, error: String(answer.body.error ?? refusedOne?.detail ?? "the hand-off was refused"), receipts };}return { ok: true, receipts };},diff --git a/server/skill-burger/partial-delegation.test.ts b/server/skill-burger/partial-delegation.test.tsnew file mode 100644index 0000000000..aa5101de5f--- /dev/null+++ b/server/skill-burger/partial-delegation.test.ts@@ -0,0 +1,147 @@+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, it } from "vitest";++import { workflowSchema } from "../../shared/skill-burger/format.ts";+import { peerDeliveryReceipt, withTargetsHere } from "../peer-delivery.ts";+import { RuntimeCoordinator } from "../runtime-coordinator.ts";+import { createExecutors } from "./executors.ts";+import { createRunStates } from "./run-state.ts";+import { resumeRun, startRun, type RunDeps, type RunEnvelope, type RunState } from "./runner.ts";++const roots: string[] = [];+const coordinators: RuntimeCoordinator[] = [];+afterEach(() => {+ coordinators.splice(0).forEach((coordinator) => coordinator.close());+ roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }));+});++async function team(phase: "initial" | "review", batched: boolean) {+ const root = mkdtempSync(join(tmpdir(), "burger-partial-delegation-"));+ roots.push(root);+ const stateDir = join(root, "states");+ const roster = [{ id: "kiwi", name: "Kiwi" }, { id: "rio", name: "Rio" }];+ const calls: Array<{ botIds: string[]; message: string; rework?: boolean }> = [];+ const accepted: Array<{ botId: string; requestId: string; rework: boolean }> = [];+ const completed = new Map<string, () => void>();+ let refuse = true;+ let reviewing = false;+ const coordinator = new RuntimeCoordinator({+ dataDir: ":memory:", log() {},+ handoffLimit: { refusal: (botId) => refuse && botId === "rio" && (phase === "initial" || reviewing) ? "Rio is at its hand-off limit" : null },+ host: {+ validate: () => undefined, busy: () => false, changed() {}, park() {},+ names: (node) => ({ requester: "Lead", assignee: node.botId }),+ levelOf: () => ({ level: "ask" }), chiefOf: () => false,+ run: async (node) => ({ ok: true, text: `${roster.find((bot) => bot.id === node.botId)!.name}: ${accepted.find((one) => one.requestId === node.id)!.rework ? "corrected" : "initial"} report (${node.id})` }),+ report: (child) => completed.get(child.id)?.(),+ },+ });+ coordinators.push(coordinator);+ const source = { botId: "lead", threadId: "t" };+ coordinator.beginTurn({ id: "gen-1", address: source, brief: "Collect reports", level: "ask", origin: { kind: "user", request: "Collect reports" } });+ const exec = createExecutors({+ botId: "lead", cwd: root,+ async internal(kind, path, body) {+ expect(kind).toBe("agents");+ if (path.startsWith("/api/internal/agents?")) return { ok: true, body: { bots: roster } };+ if (path.startsWith("/api/internal/assignment-status?")) {+ const id = new URL(path, "http://localhost").searchParams.get("id")!;+ const node = coordinator.node(id);+ expect(node).toBeDefined();+ return { ok: true, body: { assignment: { status: node!.status, result: node!.result } } };+ }+ expect(path).toBe("/api/internal/coordinate-bots");+ const call = body as { botIds: string[]; message: string; rework?: boolean };+ calls.push(call);+ reviewing ||= call.rework === true;+ const settling: Promise<void>[] = [];+ const receipts = call.botIds.map((botId) => {+ const bot = roster.find((one) => one.id === botId)!;+ try {+ const { node, duplicate } = coordinator.enqueue(source, "gen-1", undefined, { botId, threadId: `${botId}-work` }, call.message, { rework: call.rework });+ if (!duplicate) {+ accepted.push({ botId, requestId: node.id, rework: call.rework === true });+ settling.push(new Promise<void>((resolve) => completed.set(node.id, resolve)));+ }+ return peerDeliveryReceipt({+ botId, botName: bot.name, requestId: node.id,+ outcome: duplicate && node.status === "completed" ? "failed" : "queued",+ detail: duplicate && node.status === "completed" ? "not sent again: it already finished and its result stands; send it with rework=true to run it again" : "sent",+ });+ } catch (error) {+ return peerDeliveryReceipt({ botId, botName: bot.name, outcome: "failed", detail: (error as Error).message });+ }+ });+ coordinator.tick();+ await Promise.all(settling);+ const reply = await withTargetsHere(call, [], {+ receipts, refused: receipts.filter((one) => one.outcome === "failed").map((one) => one.detail), message: "Work sent",+ }, async () => { throw new Error("all target replies are already supplied"); });+ return { ok: reply.status === 200, status: reply.status, body: reply.body };+ },+ });+ const deps: RunDeps = { exec, events: { started() {}, ended() {} }, save: (state) => createRunStates(stateDir).save(state) };+ const workflow = workflowSchema.parse({+ version: 1, summary: "Collect reports", args: {}, steps: [+ {+ id: "s1", kind: "delegate", label: "Ask teammates", ...(phase === "review" ? { review: { rounds: 1 } } : {}),+ tasks: roster.map((bot) => ({ bot, message: batched ? "Inspect the report" : `Inspect ${bot.name}'s part` })),+ },+ { id: "s2", kind: "file", label: "Write final report", path: "report.txt", content: { $step: "s1", path: "text" } },+ ],+ });+ const resume = async (envelope: RunEnvelope, response: string) => {+ const token = envelope.error?.resumeToken ?? envelope.requiresInput?.resumeToken;+ expect(token).toBeTruthy();+ const state = createRunStates(stateDir).take(token!, "lead");+ expect(state).not.toBeNull();+ return resumeRun(state!, response, deps);+ };+ let stopped = await startRun({ name: "reports", botId: "lead", threadId: "t", sha256: "x", workflow }, deps);+ if (phase === "review") {+ const review = await resume(stopped, "back");+ expect(review).toMatchObject({ requiresInput: { type: "review" } });+ stopped = await resume(review, '{"redo":{"Kiwi":"Check the source","Rio":"Check the source"}}');+ }+ const saved = JSON.parse(readFileSync(join(stateDir, `${stopped.run}.json`), "utf8")) as RunState;+ return { stopped, saved, resume, exec, calls, accepted, allow: () => { refuse = false; }, report: join(root, "report.txt") };+}++it.each([+ ["initial", false], ["initial", true], ["review", false], ["review", true],+] as const)("resumes a partially accepted %s round without resending accepted requests (batched: %s)", async (phase, batched) => {+ const h = await team(phase, batched);+ const acceptedKiwi = h.accepted.filter((one) => one.botId === "kiwi").at(-1)!;+ expect(existsSync(h.report)).toBe(false);+ const acceptedBefore = h.accepted.length;+ const stillRefused = await h.resume(h.stopped, "try again");+ expect(existsSync(h.report)).toBe(false);+ expect(h.accepted).toHaveLength(acceptedBefore);+ expect(stillRefused).toMatchObject({ ok: false, error: { step: "s1" } });+ const callsBefore = h.calls.length;+ h.allow();+ const resumed = await h.resume(stillRefused, "go on");+ const done = resumed.requiresInput?.type === "teammates" ? await h.resume(resumed, "back") : resumed;+ const rounds = phase === "review" ? 2 : 1;+ expect(h.accepted.filter((one) => one.botId === "kiwi")).toHaveLength(rounds);+ expect(h.accepted.filter((one) => one.botId === "rio")).toHaveLength(rounds);+ expect(h.calls.slice(callsBefore)).toEqual([expect.objectContaining({ botIds: ["rio"], ...(phase === "review" ? { rework: true } : {}) })]);+ if (phase === "review") expect(h.calls.at(-1)!.message).toContain("Check the source");+ expect(h.stopped).toMatchObject({ ok: false, error: { step: "s1", message: expect.stringContaining("Rio is at its hand-off limit") } });+ expect(h.saved.delegation).toMatchObject({ round: rounds, requests: [{ part: "Kiwi", requestId: acceptedKiwi.requestId }] });+ expect(done).toMatchObject({ ok: true, status: "ok" });+ const report = readFileSync(h.report, "utf8");+ expect(report).toContain(`Kiwi: ${phase === "review" ? "corrected" : "initial"} report (${acceptedKiwi.requestId})`);+ expect(report).toContain(`Rio: ${phase === "review" ? "corrected" : "initial"} report`);+});++it("does not accept a refused completed-duplicate receipt carrying an old request id", async () => {+ const h = await team("initial", true);+ h.allow();+ const result = await h.exec.delegate!({ botIds: ["kiwi", "rio"], message: "Inspect the report", signal: new AbortController().signal });+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining("not sent again: it already finished") });+ expect(result).toHaveProperty("receipts", [{ botId: "rio", name: "Rio", requestId: h.accepted.find((one) => one.botId === "rio")!.requestId }]);+ expect(h.accepted.filter((one) => one.botId === "kiwi")).toHaveLength(1);+});diff --git a/server/skill-burger/runner.ts b/server/skill-burger/runner.tsindex d29e8f7825..4bfea8fa97 100644--- a/server/skill-burger/runner.ts+++ b/server/skill-burger/runner.ts@@ -253,13 +253,19 @@ export async function runFrom(state: Omit<RunState, "waiting" | "createdAt"> & {const signal = deps.signal ?? new AbortController().signal;const roster = await exec.teammates(signal).catch(() => []);const { who, missing } = matchTeammates(step, roster, chosen);- const delegation: NonNullable<RunState["delegation"]> = { step: step.id, round: 1, who, requests: [], replies: {} };+ const delegation: NonNullable<RunState["delegation"]> = state.delegation?.step === step.id && state.delegation.pendingSend+ ? { ...state.delegation, who }+ : { step: step.id, round: 1, who, requests: [], replies: {}, pendingSend: {} };if (missing.length) return hand(step, "missing_bot", undefined, { prompt: missingPrompt(missing), delegation });- const sent = await sendRound(step, delegation, (ref) => resolve(ref, args, results), exec as DelegateExecutors, signal);- if (!sent.ok) return fail(step, "step_failed", clip(redactSecretsInText(sent.error), ERROR_MAX));+ const sent = await sendRound(step, delegation, (ref) => resolve(ref, args, results), exec as DelegateExecutors, signal, delegation.pendingSend?.fixes, delegation.requests);delegation.requests = sent.requests;+ if (!sent.ok) {+ state.delegation = delegation;+ return fail(step, "step_failed", clip(redactSecretsInText(sent.error), ERROR_MAX));+ }+ delete delegation.pendingSend;const names = [...new Set(sent.requests.map((request) => request.name))];- results[step.id] = { state: "handed", detail: { waitingOn: names, rounds: 1 } };+ results[step.id] = { state: "handed", detail: { waitingOn: names, rounds: delegation.round } };return hand(step, "teammates", undefined, { prompt: TEAMMATES_PROMPT(teammateNames(names.map((one) => ({ bot: { name: one } })), false), id), delegation });};@@ -424,14 +430,16 @@ export async function resumeRun(state: RunState, response: string, deps: RunDepsconst parts = Object.keys(redo);if (!parts.length) return finish();if (delegation.round - 1 >= (step.review?.rounds ?? 0)) return finish(parts);- const sent = await sendRound(step, delegation, fill, exec, signal, redo);+ const next: NonNullable<RunState["delegation"]> = { ...delegation, round: delegation.round + 1, requests: [], pendingSend: { fixes: redo } };+ const sent = await sendRound(step, next, fill, exec, signal, redo);+ next.requests = sent.requests;if (!sent.ok) {results[step.id] = { state: "failed", error: clip(sent.error, ERROR_MAX) };deps.events.ended(state.id, state.name, step, results[step.id]!);- deps.save({ ...state, results, waiting: { step: step.id, type: "failed" }, createdAt: Date.now() });+ deps.save({ ...state, results, delegation: next, waiting: { step: step.id, type: "failed" }, createdAt: Date.now() });return { protocolVersion: 1, ok: false, run: state.id, steps: [], error: { type: "step_failed", message: `"${step.label}" couldn't send the work back: ${clip(sent.error, ERROR_MAX)}`, step: step.id, resumeToken: state.id } };}- const next = { ...delegation, round: delegation.round + 1, requests: sent.requests };+ delete next.pendingSend;const names = [...new Set(sent.requests.map((request) => request.name))];results[step.id] = { state: "handed", detail: { waitingOn: names, rounds: next.round } };return ask("teammates", TEAMMATES_PROMPT(names.join(", "), state.id), { delegation: next });