Skip to content

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

fix(hooks): an ended turn's late output needs that turn's own bearer, counts only once saved, and survives a turn that ends mid-request or before it is bound

Absterrg07f2a50d084ea
diff --git a/server/host/late-tool-results.test.ts b/server/host/late-tool-results.test.ts
index 8d4136b072..cb8ed1acc2 100644
--- a/server/host/late-tool-results.test.ts
+++ b/server/host/late-tool-results.test.ts
@@ -3,25 +3,37 @@ import { describe, expect, it } from "vitest";
import { createLateToolResults, LATE_TOOL_RESULT_MS } from "./late-tool-results.ts";
const turn = { threadId: "t1", botId: "b1", turnId: "turn-1", token: "secret", toolUseIds: new Set(["tool-a", "tool-b"]) };
+const bearer = "Bearer secret";
describe("late tool results", () => {
- it("lets an ended turn's bearer save each of its own tool calls once", () => {
+ it("lets an ended turn's bearer save each of its own tool calls once, counting only a save that happened", () => {
const late = createLateToolResults(() => 0);
late.turnEnded(turn);
- expect(late.holder("Bearer secret")).toEqual({ botId: "b1", threadId: "t1" });
- expect(late.claim("t1", "b1", "tool-a")).toBe("turn-1");
- expect(late.claim("t1", "b1", "tool-a")).toBeNull();
- expect(late.claim("t1", "b1", "tool-b")).toBe("turn-1");
- expect(late.holder("Bearer secret")).toBeNull();
+ expect(late.holder(bearer)).toEqual({ botId: "b1", threadId: "t1" });
+ expect(late.turnFor(bearer, "t1", "b1", "tool-a")).toBe("turn-1");
+ expect(late.turnFor(bearer, "t1", "b1", "tool-a")).toBe("turn-1");
+ late.saved("t1", "turn-1", "tool-a");
+ expect(late.turnFor(bearer, "t1", "b1", "tool-a")).toBeNull();
+ late.saved("t1", "turn-1", "tool-b");
+ expect(late.holder(bearer)).toBeNull();
});
it("knows no other bearer, conversation, bot or tool call", () => {
const late = createLateToolResults(() => 0);
late.turnEnded(turn);
- for (const header of ["Bearer secreT", "Bearer secret ", "secret", undefined, ["Bearer secret"]]) expect(late.holder(header)).toBeNull();
- expect(late.claim("t2", "b1", "tool-a")).toBeNull();
- expect(late.claim("t1", "b2", "tool-a")).toBeNull();
- expect(late.claim("t1", "b1", "tool-c")).toBeNull();
+ for (const header of ["Bearer secreT", "Bearer secret ", "secret", undefined, [bearer]]) expect(late.holder(header)).toBeNull();
+ expect(late.turnFor(bearer, "t2", "b1", "tool-a")).toBeNull();
+ expect(late.turnFor(bearer, "t1", "b2", "tool-a")).toBeNull();
+ expect(late.turnFor(bearer, "t1", "b1", "tool-c")).toBeNull();
+ });
+
+ it("gives one ended turn's bearer nothing of another turn's tool calls in the same conversation", () => {
+ const late = createLateToolResults(() => 0);
+ late.turnEnded(turn);
+ late.turnEnded({ ...turn, turnId: "turn-2", token: "other", toolUseIds: new Set(["tool-z"]) });
+ expect(late.turnFor(bearer, "t1", "b1", "tool-z")).toBeNull();
+ expect(late.turnFor("Bearer other", "t1", "b1", "tool-a")).toBeNull();
+ expect(late.turnFor("Bearer other", "t1", "b1", "tool-z")).toBe("turn-2");
});
it("ends with its window, when the conversation's bearers are revoked, or when nothing was left to save", () => {
@@ -29,14 +41,14 @@ describe("late tool results", () => {
const late = createLateToolResults(() => now);
late.turnEnded(turn);
now = LATE_TOOL_RESULT_MS;
- expect(late.holder("Bearer secret")).toBeNull();
- expect(late.claim("t1", "b1", "tool-a")).toBeNull();
+ expect(late.holder(bearer)).toBeNull();
+ expect(late.turnFor(bearer, "t1", "b1", "tool-a")).toBeNull();
late.turnEnded(turn);
late.forgetThread("t1");
- expect(late.claim("t1", "b1", "tool-a")).toBeNull();
+ expect(late.turnFor(bearer, "t1", "b1", "tool-a")).toBeNull();
late.turnEnded({ ...turn, toolUseIds: new Set() });
- expect(late.holder("Bearer secret")).toBeNull();
+ expect(late.holder(bearer)).toBeNull();
});
});
diff --git a/server/host/late-tool-results.ts b/server/host/late-tool-results.ts
index dd9709c29c..f9d0499521 100644
--- a/server/host/late-tool-results.ts
+++ b/server/host/late-tool-results.ts
@@ -22,25 +22,26 @@ export function createLateToolResults(now: () => number = Date.now) {
for (let i = ended.length - 1; i >= 0; i--) if (ended[i]!.until <= at || ended[i]!.toolUseIds.size === 0) ended.splice(i, 1);
return ended;
};
+ const presents = (header: string | string[] | undefined, token: string) => {
+ const got = Buffer.from(Array.isArray(header) ? "" : (header ?? ""));
+ const expected = Buffer.from(`Bearer ${token}`);
+ return got.length === expected.length && timingSafeEqual(got, expected);
+ };
return {
turnEnded(turn: EndedHookTurn): void {
if (turn.toolUseIds.size) ended.push({ ...turn, toolUseIds: new Set(turn.toolUseIds), until: now() + LATE_TOOL_RESULT_MS });
},
- /** The bot and conversation an ended turn's bearer belongs to, compared in constant time. */
+ /** The bot and conversation an ended turn's bearer belongs to. */
holder(header: string | string[] | undefined): { botId: string; threadId: string } | null {
- const got = Buffer.from(Array.isArray(header) ? "" : (header ?? ""));
- for (const turn of live()) {
- const expected = Buffer.from(`Bearer ${turn.token}`);
- if (got.length === expected.length && timingSafeEqual(got, expected)) return { botId: turn.botId, threadId: turn.threadId };
- }
- return null;
+ const turn = live().find((candidate) => presents(header, candidate.token));
+ return turn ? { botId: turn.botId, threadId: turn.threadId } : null;
+ },
+ /** The ended turn whose bearer this is, if that turn's tool call still waits for its full output. */
+ turnFor(header: string | string[] | undefined, threadId: string, botId: string, toolUseId: string): string | null {
+ return live().find((turn) => turn.threadId === threadId && turn.botId === botId && turn.toolUseIds.has(toolUseId) && presents(header, turn.token))?.turnId ?? null;
},
- /** The ended turn a tool call of this conversation belongs to, if its output may still be saved; claims it. */
- claim(threadId: string, botId: string, toolUseId: string): string | null {
- const turn = live().find((candidate) => candidate.threadId === threadId && candidate.botId === botId && candidate.toolUseIds.has(toolUseId));
- if (!turn) return null;
- turn.toolUseIds.delete(toolUseId);
- return turn.turnId;
+ saved(threadId: string, turnId: string, toolUseId: string): void {
+ for (const turn of ended) if (turn.threadId === threadId && turn.turnId === turnId) turn.toolUseIds.delete(toolUseId);
},
forgetThread(threadId: string): void {
for (let i = ended.length - 1; i >= 0; i--) if (ended[i]!.threadId === threadId) ended.splice(i, 1);
diff --git a/server/index.ts b/server/index.ts
index 1d739d548d..a896835700 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -1759,6 +1759,7 @@ function revokeAllInternalCapabilities(): void {
function bindInternalCapabilityToProviderTurn(threadId: string, generation: string, turnId?: string): void {
if (turnId && !internalGenerationByProviderTurn.bind(threadId, generation, turnId)) {
+ rememberLateToolResults(threadId, generation, turnId);
revokeInternalCapabilityGeneration(threadId, generation);
}
}
@@ -1767,12 +1768,16 @@ function revokeInternalCapabilityForProviderEvent(event: RuntimeEvent): void {
if (!event.turnId) return;
const owner = internalGenerationByProviderTurn.complete(event.threadId, event.turnId);
if (!owner) return;
- const hooks = [...internalCapabilities].find(([, capability]) => capability.kind === "hooks" && capability.threadId === owner.threadId && capability.generation === owner.generation);
- if (hooks) lateToolResults.turnEnded({ threadId: owner.threadId, botId: hooks[1].botId, turnId: event.turnId, token: hooks[0], toolUseIds: new Set(store.activePath(owner.threadId)
- .flatMap((m) => m.kind === "activity" && m.turnId === event.turnId && m.tool?.itemId && m.tool.fullResult === undefined ? [m.tool.itemId] : [])) });
+ rememberLateToolResults(owner.threadId, owner.generation, event.turnId);
revokeInternalCapabilityGeneration(owner.threadId, owner.generation);
}
+function rememberLateToolResults(threadId: string, generation: string, turnId: string): void {
+ const hooks = [...internalCapabilities].find(([, capability]) => capability.kind === "hooks" && capability.threadId === threadId && capability.generation === generation);
+ if (hooks) lateToolResults.turnEnded({ threadId, botId: hooks[1].botId, turnId, token: hooks[0], toolUseIds: new Set(store.activePath(threadId)
+ .flatMap((m) => m.kind === "activity" && m.turnId === turnId && m.tool?.itemId && m.tool.fullResult === undefined ? [m.tool.itemId] : [])) });
+}
+
/** Constant-time comparisons, so the check does not leak a matching prefix length. */
function authorizedInternalCapability(header: string | string[] | undefined): InternalCapability | null {
const got = Buffer.from(Array.isArray(header) ? "" : (header ?? ""));
@@ -5419,7 +5424,7 @@ const TOOL_RESULTS_DIR = join(DATA_DIR, "tool-results");
const TOOL_RESULT_SPILL_MAX = 512 * 1024;
const DIGESTS_AFTER_COMPACTION = 2;
-function ingestEngineHook(capability: Pick<InternalCapability, "botId" | "threadId">, body: unknown, turnEnded = false): { ok: boolean; ignored?: string; context?: string; hookSpecificOutput?: unknown } {
+function ingestEngineHook(capability: Pick<InternalCapability, "botId" | "threadId">, body: unknown, bearer: string | string[] | undefined, turnEnded = false): { ok: boolean; ignored?: string; context?: string; hookSpecificOutput?: unknown } {
const event = body && typeof body === "object" ? (body as { event?: unknown; payload?: unknown }) : {};
const name = typeof event.event === "string" ? event.event : "";
const payload = event.payload && typeof event.payload === "object" ? (event.payload as Record<string, unknown>) : {};
@@ -5450,7 +5455,8 @@ function ingestEngineHook(capability: Pick<InternalCapability, "botId" | "thread
const text = typeof response === "string" ? response : JSON.stringify(response ?? null, null, 2);
const rows = store.activePath(threadId), toolRow = (turn: string | null | undefined) => turn ? rows.findLast((m) => m.kind === "activity" && m.turnId === turn && m.tool?.itemId === toolUseId) : undefined;
let turnId: string | null | undefined = turnEnded ? undefined : liveTurnByThread.get(threadId), row = toolRow(turnId);
- if (!row) row = toolRow(turnId = lateToolResults.claim(threadId, capability.botId, toolUseId));
+ const late = row ? null : lateToolResults.turnFor(bearer, threadId, capability.botId, toolUseId);
+ if (late) row = toolRow(turnId = late);
if (!turnId || !row?.tool) return { ok: true, ignored: "tool not observed in this turn" };
const key = `${threadId}:${turnId}:${toolUseId}`;
if (!commandReceipt("hook.ingest", key)) {
@@ -5459,6 +5465,7 @@ function ingestEngineHook(capability: Pick<InternalCapability, "botId" | "thread
const fullResult = spillToolResult(dir, key, redacted, TOOL_RESULT_SPILL_MAX);
store.patchMessage(threadId, row.id, { tool: { ...row.tool, fullResult } }, { kind: "hook.ingest", key });
}
+ if (late) lateToolResults.saved(threadId, late, toolUseId);
return { ok: true };
}
@@ -12837,7 +12844,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const internalCapability = authorizedInternalCapability(req.headers.authorization);
if (!internalCapability) {
const ended = method === "POST" && path === "/api/internal/hook" ? lateToolResults.holder(req.headers.authorization) : null;
- return ended ? json(res, 200, ingestEngineHook(ended, await readBody(req), true)) : json(res, 401, { error: "unauthorized" });
+ return ended ? json(res, 200, ingestEngineHook(ended, await readBody(req), req.headers.authorization, true)) : json(res, 401, { error: "unauthorized" });
}
const internalSender = store.bot(internalCapability.botId);
if (!internalSender) {
@@ -12948,8 +12955,9 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
message: `End this turn now without using the previous computer tools. OpenMausBot will continue the original request on ${option.label} with a fresh tool connection.` });
}
if (method === "POST" && path === "/api/internal/hook") {
- const body = await readInternalBody();
- return json(res, 200, ingestEngineHook(internalCapability, body));
+ const body = await readBody(req), turnEnded = !internalCapabilityIsActive(internalCapability);
+ if (turnEnded && !lateToolResults.holder(req.headers.authorization)) return json(res, 401, { error: TURN_ENDED_REFUSAL });
+ return json(res, 200, ingestEngineHook(internalCapability, body, req.headers.authorization, turnEnded));
}
if (method === "POST" && path === "/api/internal/tool-result") {
const body = await readInternalBody();
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index 11c9f762b7..48805f28d1 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -259,9 +259,16 @@ const settingsHooks: Record<string, Array<{ matcher?: string; hooks?: Array<{ ty
})();
const hooksAfterTurnMs = Number(process.env.FAKE_CLAUDE_HOOKS_AFTER_TURN_MS);
const hooksAfterTurn: Array<() => unknown> = [];
+let hookBatchesWaiting = 0;
const runHooksAfterTurn = () => {
const due = hooksAfterTurn.splice(0);
- if (due.length) setTimeout(() => { for (const run of due) run(); }, hooksAfterTurnMs);
+ if (!due.length) return;
+ hookBatchesWaiting += 1;
+ setTimeout(() => {
+ for (const run of due) run();
+ hookBatchesWaiting -= 1;
+ finishIfDone();
+ }, hooksAfterTurnMs);
};
function runHooks(event: FakeHookEvent, payload: Record<string, unknown>): string {
let stdout = "";
@@ -643,6 +650,7 @@ const startLateTurn = (): boolean => {
const finishIfDone = () => {
if (turnRunning) return;
if (startLateTurn()) return;
+ if (hookBatchesWaiting > 0) return;
if (stdinEnded) process.exit(0);
if (process.env.FAKE_CLAUDE_EXIT_AFTER_TURN === "1") process.stdout.write("", () => process.exit(0));
const gone = process.env.FAKE_CLAUDE_GONE_AFTER_TURN;
@@ -1309,6 +1317,7 @@ const playTurn = (prompt: JsonValue, late = false) => {
out({ type: "assistant", message: { content: [{ type: "text", text: `reply to: ${promptText(prompt)}${tail}` }] } });
if (!lateContinuation && finishGate && readFileSync(finishGate, "utf8").trim() === "fail") {
out({ type: "result", is_error: true, stop_reason: "error", result: "fixture turn failed" });
+ runHooksAfterTurn();
turnRunning = false;
finishIfDone();
return;