Skip to content

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

fix(pi): accumulate usage across tool rounds and continuations

Sebastian B97d7c6df3769
diff --git a/server/drivers/pi-lifecycle.test.ts b/server/drivers/pi-lifecycle.test.ts
index 706f38db2a..2abbc66073 100644
--- a/server/drivers/pi-lifecycle.test.ts
+++ b/server/drivers/pi-lifecycle.test.ts
@@ -1,4 +1,4 @@
-import { chmodSync, mkdtempSync, readFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -13,7 +13,6 @@ const CLI = fileURLToPath(new URL("../testing/fake-pi-lifecycle.mjs", import.met
let dir: string;
let instance: ProviderInstance;
let events: EventRecorder;
-let ownedPid: number | undefined;
beforeEach(async () => {
ensureDirs();
@@ -27,13 +26,16 @@ beforeEach(async () => {
environment: { FAKE_PI_LIFECYCLE_DUMP: join(dir, "rpc.jsonl") },
});
events = recordEvents(instance.adapter);
- ownedPid = undefined;
});
afterEach(async () => {
await instance.dispose();
- if (ownedPid) {
- try { process.kill(ownedPid, "SIGKILL"); } catch {}
+ const dump = join(dir, "rpc.jsonl");
+ if (existsSync(dump)) {
+ const rows = readFileSync(dump, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { pid?: number });
+ for (const { pid } of rows) {
+ if (pid) { try { process.kill(pid, "SIGKILL"); } catch {} }
+ }
}
events.stop();
await removeTempDir(dir);
@@ -43,7 +45,6 @@ it.each(["interrupt", "stopAll", "dispose"])("keeps ownership through %s until t
await instance.adapter.sendTurn({ threadId: "cancel", text: "wait" });
await events.until((event) => event.type === "item.started");
const { pid } = JSON.parse(readFileSync(join(dir, "rpc.jsonl"), "utf8").trim()) as { pid: number };
- ownedPid = pid;
let runningAtCompletion = false;
instance.adapter.onEvent((event) => {
if (event.type !== "turn.completed") return;
@@ -81,7 +82,7 @@ it.each([
expect(events.events.find((event) => event.type === "session.started")).toMatchObject({ model: confirmed });
});
-it.each(["retry", "nonterminal", "compaction_start", "auto_compaction_start"])(
+it.each(["retry", "nonterminal", "compaction_start", "auto_compaction_start", "agent_start"])(
"keeps a turn running beyond the completion grace after %s",
async (kind) => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
@@ -110,3 +111,19 @@ it("retains the completion fallback when no continuation or maintenance arrives"
}
expect(await events.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true, stopReason: "end_turn" });
});
+
+it.each(["toolUse", "tool_use", "tool_calls"])("accumulates usage across %s rounds without counting duplicate fields", async (reason) => {
+ await instance.adapter.sendTurn({ threadId: "usage", text: `usage:${reason}` });
+ expect(await events.until((event) => event.type === "turn.completed")).toMatchObject({
+ ok: true, usage: { input: 17, output: 3 },
+ });
+});
+
+it("keeps usage already consumed when Stop cancels a continuation", async () => {
+ await instance.adapter.sendTurn({ threadId: "usage-stop", text: "usage:hold" });
+ await events.until((event) => event.type === "content.delta" && event.delta === "usage-ready");
+ await instance.adapter.interruptTurn("usage-stop");
+ expect(await events.until((event) => event.type === "turn.completed")).toMatchObject({
+ ok: true, stopReason: "cancelled", usage: { input: 5, output: 1 },
+ });
+});
diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.ts
index 5f6dc566a0..7d38cc57e0 100644
--- a/server/drivers/pi.test.ts
+++ b/server/drivers/pi.test.ts
@@ -874,7 +874,7 @@ describe("PiDriver turns (fake CLI)", () => {
expect(JSON.stringify(recorder.events)).not.toContain("pi-input-secret");
expect(JSON.stringify(recorder.events)).not.toContain("pi-output-secret");
expect(done).toMatchObject({ ok: true, stopReason: "end_turn" });
- expect((done as { usage: { input: number; output: number } }).usage).toEqual({ input: 12, output: 2 });
+ expect((done as { usage: { input: number; output: number } }).usage).toEqual({ input: 17, output: 3 });
const text = recorder.events.find(
(e) => e.type === "item.completed" && (e as { itemType: string }).itemType === "assistant_text",
) as { text: string } | undefined;
diff --git a/server/drivers/pi.ts b/server/drivers/pi.ts
index 16708ecc1f..b93a87a835 100644
--- a/server/drivers/pi.ts
+++ b/server/drivers/pi.ts
@@ -543,7 +543,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_text", text });
};
- const settle = (ok: boolean, stopReason?: string | null, usage?: { input?: number; output?: number }): Promise<void> => {
+ const settle = (ok: boolean, stopReason?: string | null, usage = endUsage): Promise<void> => {
if (completion) return completion;
settled = true;
if (agentEndTimer) {
@@ -750,10 +750,11 @@ export const PiDriver: ProviderDriver<PiConfig> = {
if (agentEndTimer) clearTimeout(agentEndTimer);
agentEndTimer = null;
const sr = evt.message?.stopReason;
+ const usage = evt.usage ?? evt.message?.usage;
+ if (usage) endUsage = { input: (endUsage?.input ?? 0) + (usage.input ?? 0), output: (endUsage?.output ?? 0) + (usage.output ?? 0) };
// toolUse: pi ran a tool and auto-continues; the next turn_end carries the outcome.
if (sr === "toolUse" || sr === "tool_use" || sr === "tool_calls") return;
endStopReason = sr;
- endUsage = evt.usage ?? evt.message?.usage;
endErrorMessage = evt.message?.errorMessage;
// pi can schedule maintenance (overflow-recovery compaction) after the final turn_end;
// only agent_end proves the session is done rewriting itself.
diff --git a/server/testing/fake-pi-lifecycle.mjs b/server/testing/fake-pi-lifecycle.mjs
index c4c7dd0dbc..d87f1ddddd 100755
--- a/server/testing/fake-pi-lifecycle.mjs
+++ b/server/testing/fake-pi-lifecycle.mjs
@@ -14,9 +14,10 @@ createInterface({ input: process.stdin }).on("line", (line) => {
if (cmd.type === "get_available_models") {
process.stdout.write(JSON.stringify({ type: "response", command: cmd.type, success: true, data: { models: [model] } }) + "\n", () => process.exit(0));
}
- if (["get_state", "new_session", "switch_session"].includes(cmd.type)) {
+ if (cmd.type === "get_state") {
reply(cmd.type, { sessionFile: "fixture-session.jsonl", model });
}
+ if (["new_session", "switch_session"].includes(cmd.type)) reply(cmd.type, { cancelled: false });
if (cmd.type === "set_model") {
dump({ setModel: cmd.modelId });
if (cmd.modelId === "refused") send({ type: "response", command: cmd.type, success: false, error: "Model unavailable" });
@@ -26,6 +27,19 @@ createInterface({ input: process.stdin }).on("line", (line) => {
dump({ prompt: cmd.message, pid: process.pid });
reply(cmd.type);
send({ type: "tool_execution_start", toolCallId: "ready", toolName: "fixture" });
+ if (cmd.message.startsWith("usage:")) {
+ const stopReason = cmd.message === "usage:hold" ? "toolUse" : cmd.message.slice("usage:".length);
+ send({ type: "turn_end", message: { stopReason, usage: { input: 5, output: 1 } }, usage: { input: 5, output: 1 } });
+ if (cmd.message === "usage:hold") {
+ send({ type: "message_update", assistantMessageEvent: { type: "text_delta", delta: "usage-ready" } });
+ return;
+ }
+ send({ type: "turn_start" });
+ send({ type: "turn_end", message: { stopReason: "end_turn", usage: { input: 12, output: 2 } } });
+ send({ type: "agent_end", isTerminal: true });
+ send({ type: "agent_settled" });
+ return;
+ }
if (cmd.message.startsWith("maintenance:")) {
send({ type: "turn_end", message: { stopReason: "end_turn" } });
const kind = cmd.message.slice("maintenance:".length);