Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(skill-burger): scope cached decisions to the recorded run

Afloat4d6dabcb0dba
diff --git a/server/skill-burger/routes.test.ts b/server/skill-burger/routes.test.ts
index 79921bbf2f..1871038161 100644
--- a/server/skill-burger/routes.test.ts
+++ b/server/skill-burger/routes.test.ts
@@ -10,6 +10,8 @@ import { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";
import { dispatchRoutes } from "../routes/table.ts";
import { createSkillBurgerRoutes, type SkillBurgerRouteDeps } from "./routes.ts";
+import { createExecutors } from "./executors.ts";
+import { startRun } from "./runner.ts";
const servers: Server[] = [];
afterEach(async () => {
@@ -48,7 +50,7 @@ async function serve(extra: Partial<SkillBurgerRouteDeps> = {}, scopes: readonly
const res = await fetch(`${base}${path}`, init);
return { status: res.status, body: await res.json() as Record<string, any> };
};
- return { api, bot };
+ return { api, bot, root };
}
const send = (method: string, body: unknown): RequestInit => ({ method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
@@ -94,6 +96,50 @@ it("names a finished run with the bot's small text model, and says nothing when
expect((await plain.api("/api/skill-burger-summary", send("POST", { botId: plain.bot, threadId: "t1" }))).body).toEqual({ summary: null });
});
+it.each(["unavailable", "not requested"])("does not apply an earlier run's decisions when the next summary is %s", async (summary) => {
+ let messages: RunMessage[] = [...thread, { id: "reply-1", role: "bot", kind: "text", text: "I sent the email only because invoices were found." }];
+ let answering = true;
+ const { api, bot, root } = await serve({
+ messages: () => messages,
+ summarize: async (_botId, prompt) => !answering ? null : prompt.startsWith("A run was saved")
+ ? '{"conditions":[{"step":"s2","when":{"$step":"s1","path":"messages.0","op":"exists"}}]}'
+ : "Send the invoice",
+ });
+ const request = { botId: bot, threadId: "t1" };
+ await api("/api/skill-burger-summary", send("POST", request));
+ const prior = await api("/api/skill-burgers", send("POST", { ...request, name: "conditional-invoice", summary: "A custom title" }));
+ expect(prior.status).toBe(201);
+ const previous = (await api("/api/skill-burgers/conditional-invoice")).body.workflow;
+ expect(previous.steps[1].when).toEqual({ $step: "s1", path: "messages.0", op: "exists" });
+
+ messages = [...messages, ...thread.map((message) => ({ ...message, id: `${message.id}-next` })),
+ { id: "reply-2", role: "bot", kind: "text", text: "I sent the status email whether or not there were invoices." }];
+ answering = false;
+ if (summary === "unavailable") expect((await api("/api/skill-burger-summary", send("POST", request))).body).toEqual({ summary: null });
+ const saved = await api("/api/skill-burgers", send("POST", { ...request, name: "unconditional-invoice" }));
+ expect(saved.status).toBe(201);
+ const workflow = (await api("/api/skill-burgers/unconditional-invoice")).body.workflow;
+ const sent: Array<{ tool_slug: string; arguments: Record<string, unknown> }> = [];
+ const exec = createExecutors({
+ botId: bot, cwd: root,
+ async internal(kind, path, body) {
+ expect(kind).toBe("connectors");
+ expect(path).toBe("/api/internal/connectors/mcp");
+ const tool = (body as { params: { arguments: { tools: typeof sent } } }).params.arguments.tools[0]!;
+ sent.push(tool);
+ const data = tool.tool_slug === "GMAIL_FETCH_EMAILS" ? { messages: [] } : { messageId: "fixture-email" };
+ return { ok: true, body: { result: { content: [{ type: "text", text: JSON.stringify({ data: { results: [{ tool_slug: tool.tool_slug, response: { successful: true, data } }] } }) }] } } };
+ },
+ });
+ const ran = await startRun({ name: saved.body.skill.name, botId: bot, threadId: "fresh", sha256: saved.body.skill.sha256, workflow }, {
+ exec, events: { started() {}, ended() {} }, save() { throw new Error("this workflow should finish without a pause"); },
+ });
+ expect(ran).toMatchObject({ ok: true, status: "ok" });
+ expect(sent.map((tool) => tool.tool_slug)).toEqual(["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]);
+ expect(sent[1]!.arguments).toMatchObject({ recipient_email: "[email protected]" });
+ expect(workflow.steps[1]).not.toHaveProperty("when");
+});
+
it("lets a Team member who can chat with the bot add a burger for everyone, and only them or an admin change it", async () => {
let access: "none" | "view" | "chat" | "edit" = "chat";
diff --git a/server/skill-burger/routes.ts b/server/skill-burger/routes.ts
index a9e4775a65..6ee85fae9c 100644
--- a/server/skill-burger/routes.ts
+++ b/server/skill-burger/routes.ts
@@ -2,6 +2,7 @@
// every bot, built here from the stored messages (their full inputs and outputs, already scrubbed of held secrets); GET
// lists every saved one; PATCH renames one or undoes a change to its steps; DELETE with the sha256 it was saved with is its
// Undo. Whoever can chat with the bot that made a run may add it; only whoever saved it, or an admin, changes it.
+import { createHash } from "node:crypto";
import { z } from "zod";
import { draftFromLayers, draftWorkflow } from "../../shared/skill-burger/draft.ts";
@@ -98,17 +99,23 @@ function outputOf(layer: { output?: string } | undefined): unknown {
try { return JSON.parse(layer.output); } catch { return layer.output.slice(0, 40); }
}
+function decisionRunKey(threadId: string, messages: readonly RunMessage[]): string {
+ const start = messages.findLastIndex((message) => message.role === "user" && message.kind === "text" && message.text?.trim());
+ const run = messages.slice(Math.max(0, start)).map(({ id, role, kind, text, tool }) => ({ id, role, kind, text, tool }));
+ return `${threadId}:${createHash("sha256").update(JSON.stringify(run)).digest("hex")}`;
+}
+
/** Decisions the summary pass read in a run, kept until it is saved; a run whose steps changed since finds none. */
function createDecisionCache(limit = 200) {
const kept = new Map<string, Decisions>();
- const key = (threadId: string, workflow: Workflow) => `${threadId}:${workflow.steps.map((step) => `${step.id}=${step.label}`).join("|")}`;
+ const key = (run: string, workflow: Workflow) => `${run}:${workflow.steps.map((step) => `${step.id}=${step.label}`).join("|")}`;
return {
- remember(threadId: string, workflow: Workflow, decisions: Decisions) {
- kept.delete(key(threadId, workflow));
- kept.set(key(threadId, workflow), decisions);
+ remember(run: string, workflow: Workflow, decisions: Decisions) {
+ kept.delete(key(run, workflow));
+ kept.set(key(run, workflow), decisions);
while (kept.size > limit) kept.delete(kept.keys().next().value!);
},
- find: (threadId: string, workflow: Workflow) => kept.get(key(threadId, workflow)) ?? null,
+ find: (run: string, workflow: Workflow) => kept.get(key(run, workflow)) ?? null,
};
}
@@ -148,13 +155,14 @@ export function createSkillBurgerRoutes(deps: SkillBurgerRouteDeps): RouteHandle
const ask = askOf(messages);
if (!burgerWorthy(layers) || !ask || !deps.summarize) return json(res, 200, { summary: null });
const draft = drafted(messages);
+ const run = decisionRunKey(threadId, messages);
const words = botWords(messages);
const [reply, decided] = await Promise.all([
deps.summarize(botId, summaryPrompt(ask, layers)).catch(() => null),
draft && words ? deps.summarize(botId, decisionsPrompt(ask, draft.workflow.steps.map((step, index) => ({ id: step.id, label: step.label, output: outputOf(draft.layers[index]) })), words)).catch(() => null) : null,
]);
const decisions = parseDecisions(decided);
- if (draft && decisions) decisionsFor.remember(threadId, draft.workflow, decisions);
+ if (draft && decisions) decisionsFor.remember(run, draft.workflow, decisions);
return json(res, 200, { summary: cleanSummary(reply) });
}
if (path !== SKILL_BURGERS_PATH && !path.startsWith(`${SKILL_BURGERS_PATH}/`)) return PASS;
@@ -175,9 +183,10 @@ export function createSkillBurgerRoutes(deps: SkillBurgerRouteDeps): RouteHandle
const { botId, threadId, summary, name, skip, inputs } = body.data;
if (!deps.owns(botId, threadId) || !deps.sees(auth, threadId)) return json(res, 404, { error: "No such conversation." });
if (!mayAdd(auth, botId)) return json(res, 403, { error: CANT_ADD });
- const draft = drafted(deps.messages(threadId), summary);
+ const messages = deps.messages(threadId);
+ const draft = drafted(messages, summary);
if (!draft) return json(res, 422, { error: "This run has nothing to save yet." });
- const chosen = applyChoices(applyDecisions(draft.workflow, decisionsFor.find(threadId, draft.workflow)), { ...(skip ? { skip } : {}), ...(inputs ? { inputs } : {}) });
+ const chosen = applyChoices(applyDecisions(draft.workflow, decisionsFor.find(decisionRunKey(threadId, messages), draft.workflow)), { ...(skip ? { skip } : {}), ...(inputs ? { inputs } : {}) });
if ("error" in chosen) return json(res, 422, { error: chosen.error });
saved = saveWorkflowSkill({ workflow: chosen, name, origin: botId, savedBy, botIds, root: deps.root });
}