Skip to content

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

fix(pi): book pi's priced cost and cached tokens on turn.completed (#4090)

Aditya Umale95d60df4ee93
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.ts
index 29b5d3c6fd..224d511209 100644
--- a/scripts/testing/file-size-ratchet.test.ts
+++ b/scripts/testing/file-size-ratchet.test.ts
@@ -38,7 +38,7 @@ const LINES: Record<string, number> = {
"server/vps-computer.ts": 1369,
"scripts/mcp-server.ts": 1414,
"server/boat.ts": 1258,
- "server/drivers/pi.ts": 1047,
+ "server/drivers/pi.ts": 1036,
"server/container-computer.ts": 1225,
"src/components/ModelPicker.tsx": 1050,
"src/components/PhoneSetupFlow.tsx": 1146,
diff --git a/server/drivers/pi-rpc.ts b/server/drivers/pi-rpc.ts
index 23b15d24ea..14d2744182 100644
--- a/server/drivers/pi-rpc.ts
+++ b/server/drivers/pi-rpc.ts
@@ -1,3 +1,6 @@
+import { readFileSync } from "node:fs";
+import type { SendTurnInput, TurnImageInput } from "../contracts.ts";
+
/** omp's RPC v2 splits a frame over 1 MiB into base64 `rpc_chunk` pieces (`chunkId`/`count`/
* `byteLength` per frame, sequential `index`, `data` per piece). Any inconsistency drops the sequence. */
export class PiRpcChunks {
@@ -110,3 +113,18 @@ export function piLineReader(onLine: (line: string) => boolean | void): (chunk:
}
};
}
+
+type PiPromptImage = {
+ type: "image";
+ data: string;
+ mimeType: TurnImageInput["mime"];
+};
+
+/** pi's prompt frame carries each attached image as base64. */
+export function readPiPromptImages(turn: SendTurnInput): PiPromptImage[] {
+ return (turn.images ?? []).map((image) => ({
+ type: "image",
+ data: readFileSync(image.path).toString("base64"),
+ mimeType: image.mime,
+ }));
+}
diff --git a/server/drivers/pi-usage.ts b/server/drivers/pi-usage.ts
new file mode 100644
index 0000000000..951912facf
--- /dev/null
+++ b/server/drivers/pi-usage.ts
@@ -0,0 +1,37 @@
+/** pi-ai's per-message usage: `input` excludes cached prompt tokens, and `cost` is pi's own priced USD. */
+export type PiUsage = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; cost?: { total?: number } };
+export type TurnUsage = { input: number; output: number; cachedInput?: number };
+
+const usageCount = (value: unknown): number | undefined =>
+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
+
+/** One pi run's tokens and priced cost, in the app's shape where input includes cached tokens like the other drivers. */
+export class PiRunUsage {
+ usage: TurnUsage | undefined;
+ /** pi's priced USD. A zero is pi's default for a model without prices, so it stays unknown rather than booked as free. */
+ cost: number | undefined;
+ // pi sends a model call's usage on its assistant message_end, before any tool runs, and again on turn_end.
+ private counted = false;
+
+ /** Counts the current model call's usage once, so a stop while a tool runs still books it. */
+ add(usage: PiUsage | undefined): void {
+ if (!usage || this.counted) return;
+ this.counted = true;
+ const total = this.usage;
+ const cacheRead = usageCount(usage.cacheRead);
+ const cachedInput = cacheRead === undefined ? total?.cachedInput : (total?.cachedInput ?? 0) + cacheRead;
+ this.usage = {
+ input: (total?.input ?? 0) + (usageCount(usage.input) ?? 0) + (cacheRead ?? 0) + (usageCount(usage.cacheWrite) ?? 0),
+ output: (total?.output ?? 0) + (usageCount(usage.output) ?? 0),
+ ...(cachedInput === undefined ? {} : { cachedInput }),
+ };
+ const cost = usageCount(usage.cost?.total);
+ if (cost) this.cost = (this.cost ?? 0) + cost;
+ }
+
+ /** turn_end closes a model call; the next call is counted again. */
+ endTurn(usage: PiUsage | undefined): void {
+ this.add(usage);
+ this.counted = false;
+ }
+}
diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.ts
index 7d38cc57e0..8ed4113353 100644
--- a/server/drivers/pi.test.ts
+++ b/server/drivers/pi.test.ts
@@ -862,6 +862,28 @@ describe("PiDriver turns (fake CLI)", () => {
expect(servers.composio).toMatchObject({ command: "node", args: ["connector-proxy.js"], env: { COMPOSIO_KEY: "ck" } });
});
+ it("reports pi's priced cost and cached tokens summed over the whole run", async () => {
+ await create("priced");
+ await instance.adapter.sendTurn({ threadId: "t-priced", text: "run it", model: "synthetic/hf:moonshotai/Kimi-K3" });
+ const done = await recorder.until((e) => e.type === "turn.completed");
+
+ expect(done).toMatchObject({ ok: true });
+ // input counts every prompt token, cached ones included, as the other drivers do.
+ expect((done as { usage: unknown }).usage).toEqual({ input: 257, output: 3, cachedInput: 220 });
+ expect((done as { cost: number }).cost).toBeCloseTo(0.0025, 10);
+ });
+
+ it("books a model call's cost when the turn is stopped while its tool runs", async () => {
+ await create("priced-stop");
+ await instance.adapter.sendTurn({ threadId: "t-priced-stop", text: "run it", model: "synthetic/hf:moonshotai/Kimi-K3" });
+ await recorder.until((e) => e.type === "item.started");
+ await instance.adapter.interruptTurn("t-priced-stop");
+ const done = await recorder.until((e) => e.type === "turn.completed");
+
+ expect(done).toMatchObject({ ok: true, stopReason: "cancelled", usage: { input: 125, output: 1, cachedInput: 100 } });
+ expect((done as { cost: number }).cost).toBeCloseTo(0.0021, 10);
+ });
+
it("rides the toolUse auto-continue and only settles on the final end_turn", async () => {
await create("tooluse");
await instance.adapter.sendTurn({ threadId: "t-tool", text: "run it" });
diff --git a/server/drivers/pi.ts b/server/drivers/pi.ts
index 3606df43c3..a80b39fbfa 100644
--- a/server/drivers/pi.ts
+++ b/server/drivers/pi.ts
@@ -31,7 +31,6 @@ import type {
RuntimeEventListener,
SendTurnInput,
SteerOutcome,
- TurnImageInput,
} from "../contracts.ts";
import { EFFORT_LEVELS } from "../../shared/wire.ts";
import { newEventId, newId } from "../contracts.ts";
@@ -47,7 +46,8 @@ import { appendNative } from "./native.ts";
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { buildMcpServers } from "./pi-mcp-servers.ts";
-import { decodePiFrame, PiRpcChunks, piLineReader } from "./pi-rpc.ts";
+import { decodePiFrame, PiRpcChunks, piLineReader, readPiPromptImages } from "./pi-rpc.ts";
+import { PiRunUsage, type PiUsage, type TurnUsage } from "./pi-usage.ts";
export { decodePiFrame, PiRpcChunks, piLineReader } from "./pi-rpc.ts";
const DRIVER_KIND = "piAgent";
@@ -67,20 +67,6 @@ const PI_SESSION_SLOW = "Pi is taking longer than usual to start this conversati
/** pi answered success:false: an explicit refusal from a live runtime, not a transport failure. */
class PiRpcRefusalError extends Error {}
-type PiPromptImage = {
- type: "image";
- data: string;
- mimeType: TurnImageInput["mime"];
-};
-
-function readPiPromptImages(turn: SendTurnInput): PiPromptImage[] {
- return (turn.images ?? []).map((image) => ({
- type: "image",
- data: readFileSync(image.path).toString("base64"),
- mimeType: image.mime,
- }));
-}
-
/** Native logs go into bug reports: keep the RPC shape and size, never image bytes. */
function piNativeLogMessage(message: Record<string, unknown>): Record<string, unknown> {
if (!Array.isArray(message.images)) return message;
@@ -357,8 +343,8 @@ interface PiEvent {
args?: unknown;
result?: unknown;
isError?: boolean;
- message?: { stopReason?: string; errorMessage?: string; usage?: { input?: number; output?: number } };
- usage?: { input?: number; output?: number };
+ message?: { role?: string; stopReason?: string; errorMessage?: string; usage?: PiUsage };
+ usage?: PiUsage;
isTerminal?: boolean;
willRetry?: boolean;
id?: string;
@@ -467,8 +453,8 @@ export const PiDriver: ProviderDriver<PiConfig> = {
let settled = false;
let completion: Promise<void> | null = null;
let endStopReason: string | undefined;
- let endUsage: { input?: number; output?: number } | undefined;
- let completionOutcome: { ok: boolean; stopReason: string; usage?: { input: number; output: number } } | null = null;
+ const runUsage = new PiRunUsage();
+ let completionOutcome: { ok: boolean; stopReason: string; cost?: number; usage?: TurnUsage } | null = null;
let endErrorMessage: string | undefined;
let agentEndTimer: ReturnType<typeof setTimeout> | null = null;
const images = readPiPromptImages(turn);
@@ -550,11 +536,12 @@ export const PiDriver: ProviderDriver<PiConfig> = {
emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_text", text });
};
- const settle = (ok: boolean, stopReason?: string | null, usage = endUsage): Promise<void> => {
+ const settle = (ok: boolean, stopReason?: string | null, usage = runUsage.usage): Promise<void> => {
if (completion) return completion;
const outcome = completionOutcome ??= {
ok, stopReason: stopReason ?? (ok ? "end_turn" : "failed"),
- ...(usage ? { usage: { input: usage.input ?? 0, output: usage.output ?? 0 } } : {}),
+ ...(usage ? { usage } : {}),
+ ...(runUsage.cost === undefined ? {} : { cost: runUsage.cost }),
};
settled = true;
if (agentEndTimer) {
@@ -597,10 +584,10 @@ export const PiDriver: ProviderDriver<PiConfig> = {
type: "runtime.error",
message: String(endErrorMessage ?? "pi turn failed").slice(0, 2_000),
});
- settle(false, "failed", endUsage);
+ settle(false, "failed", runUsage.usage);
return;
}
- settle(true, sr === "cancelled" || sr === "aborted" ? "cancelled" : "end_turn", endUsage);
+ settle(true, sr === "cancelled" || sr === "aborted" ? "cancelled" : "end_turn", runUsage.usage);
};
const stop = () => {
@@ -753,6 +740,9 @@ export const PiDriver: ProviderDriver<PiConfig> = {
}
return;
}
+ case "message_end":
+ if (evt.message?.role === "assistant") runUsage.add(evt.message.usage);
+ return;
case "turn_end":
{
// A killed child can still flush one buffered frame after the turn settled.
@@ -760,8 +750,7 @@ 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) };
+ runUsage.endTurn(evt.usage ?? evt.message?.usage);
// 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;
diff --git a/server/testing/fake-pi-cli.ts b/server/testing/fake-pi-cli.ts
index d2a99cbffd..eba26843ab 100755
--- a/server/testing/fake-pi-cli.ts
+++ b/server/testing/fake-pi-cli.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env node
// Fake of the pi coding agent's `--mode rpc --no-session` stdio surface for pi.ts tests. Env knobs:
-// FAKE_PI_MODE happy (default) | tooluse | permission | interleave | question-select | question-input
+// FAKE_PI_MODE happy (default) | tooluse | priced | priced-stop | permission | interleave | question-select | question-input
// | turn-error | no-models | exit-early | compaction | compaction-recovery
// | compaction-recovery-upstream | prompt-reject | omp-chunk
// | session-slow (answers new_session after FAKE_PI_SESSION_DELAY_MS, default 800, and dumps {sessionReplied})
@@ -189,6 +189,30 @@ const streamToolTurn = () => {
send({ type: "agent_end" });
};
+// pi's real Usage shape (pi-ai): cached tokens and the priced cost ride on message.usage, not a top-level usage.
+const piUsage = (input: number, output: number, cacheRead: number, cacheWrite: number, total: number) =>
+ ({ input, output, cacheRead, cacheWrite, totalTokens: input + output + cacheRead + cacheWrite,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total } });
+
+// Like pi, the assistant message_end carries the call's usage before its tool runs; turn_end repeats it.
+const startPricedToolTurn = () => {
+ send({ type: "agent_start" });
+ send({ type: "turn_start" });
+ send({ type: "message_end", message: { role: "assistant", stopReason: "toolUse", usage: piUsage(5, 1, 100, 20, 0.0021) } });
+ send({ type: "tool_execution_start", toolCallId: "call_1", toolName: "bash", args: { command: "echo hi" } });
+};
+
+const streamPricedTurn = () => {
+ startPricedToolTurn();
+ send({ type: "tool_execution_end", toolCallId: "call_1", toolName: "bash", isError: false, result: { content: [{ type: "text", text: "hi" }] } });
+ send({ type: "turn_end", message: { stopReason: "toolUse", usage: piUsage(5, 1, 100, 20, 0.0021) } });
+ send({ type: "turn_start" });
+ send({ type: "message_update", assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "done" } });
+ send({ type: "message_end", message: { role: "assistant", stopReason: "stop", usage: piUsage(12, 2, 120, 0, 0.0004) } });
+ send({ type: "turn_end", message: { stopReason: "stop", usage: piUsage(12, 2, 120, 0, 0.0004) } });
+ send({ type: "agent_end" });
+};
+
const streamPermissionTurn = () => {
send({ type: "agent_start" });
send({ type: "turn_start" });
@@ -345,6 +369,8 @@ function handle(cmd: any) {
}
send({ type: "response", command: "prompt", success: true });
if (mode === "tooluse") streamToolTurn();
+ else if (mode === "priced") streamPricedTurn();
+ else if (mode === "priced-stop") startPricedToolTurn();
else if (mode === "permission") streamPermissionTurn();
else if (mode === "question-select") streamQuestionSelectTurn();
else if (mode === "question-input") streamQuestionInputTurn();