Skip to content

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

Pi: report each assistant message's prompt size, so context.compactAt can fold

MaxWang0076a27c61de6c1
diff --git a/server/drivers/pi-usage.ts b/server/drivers/pi-usage.ts
index 951912facf..baf275f20b 100644
--- a/server/drivers/pi-usage.ts
+++ b/server/drivers/pi-usage.ts
@@ -5,6 +5,29 @@ 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;
+export interface PiMessageUsage {
+ input: number;
+ output: number;
+ cachedInput?: number;
+ contextTokens: number;
+}
+
+/** One assistant message, not the run total: `input` counts cache reads, and `contextTokens` is that call's whole prompt. */
+export function piMessageUsage(usage: PiUsage | undefined): PiMessageUsage | undefined {
+ if (!usage) return undefined;
+ const fresh = usageCount(usage.input);
+ const cacheRead = usageCount(usage.cacheRead);
+ const cacheWrite = usageCount(usage.cacheWrite);
+ const output = usageCount(usage.output);
+ if (fresh === undefined && cacheRead === undefined && cacheWrite === undefined && output === undefined) return undefined;
+ return {
+ input: (fresh ?? 0) + (cacheRead ?? 0),
+ output: output ?? 0,
+ ...(cacheRead === undefined ? {} : { cachedInput: cacheRead }),
+ contextTokens: (fresh ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0),
+ };
+}
+
/** 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;
diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.ts
index f396a74370..d3a5f24eda 100644
--- a/server/drivers/pi.test.ts
+++ b/server/drivers/pi.test.ts
@@ -70,6 +70,16 @@ describe("parsePiCatalog", () => {
).toEqual({ default: "", options: [] });
});
+ it("keeps a listed model's context window and drops a non-positive one", () => {
+ const line =
+ '{"type":"response","command":"get_available_models","success":true,"data":{"models":[' +
+ '{"provider":"ollama-cloud","id":"glm-5.2","name":"glm-5.2","contextWindow":131072},' +
+ '{"provider":"openai","id":"gpt-4o","name":"GPT-4o","contextWindow":0}]}}\n';
+ const catalog = parsePiCatalog(line);
+ expect(catalog.options[0]).toMatchObject({ id: "ollama-cloud/glm-5.2", contextWindow: 131072 });
+ expect(catalog.options[1]).not.toHaveProperty("contextWindow");
+ });
+
it("ignores non-response lines (pi emits TUI bookkeeping on stdout too)", () => {
const stdout =
'{"type":"extension_ui_request","id":"x","method":"setStatus","statusKey":"loops"}\n' + MODELS_LINE + "\n";
@@ -959,6 +969,19 @@ describe("PiDriver turns (fake CLI)", () => {
expect(servers.composio).toMatchObject({ command: "node", args: ["connector-proxy.js"], env: { COMPOSIO_KEY: "ck" } });
});
+ it("reports each assistant call's prompt size, not the run's summed usage", async () => {
+ await create("priced", { FAKE_PI_CONTEXT_WINDOW: "200000" });
+ await instance.adapter.sendTurn({ threadId: "t-context", text: "run it", model: "ollama-cloud/glm-5.2" });
+ await recorder.until((e) => e.type === "turn.completed");
+
+ const updates = recorder.events.filter((event) => event.type === "thread.token-usage.updated");
+ expect(updates).toEqual([
+ expect.objectContaining({ input: 105, output: 1, cachedInput: 100, contextTokens: 125, contextWindow: 200_000 }),
+ expect.objectContaining({ input: 132, output: 2, cachedInput: 120, contextTokens: 132, contextWindow: 200_000 }),
+ ]);
+ expect(recorder.events.at(-1)).toMatchObject({ usage: { input: 257, output: 3, cachedInput: 220 } });
+ });
+
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" });
diff --git a/server/drivers/pi.ts b/server/drivers/pi.ts
index 6cef845b36..3c050ea147 100644
--- a/server/drivers/pi.ts
+++ b/server/drivers/pi.ts
@@ -53,7 +53,7 @@ import { piAgentDir, readPiDefaultModel, withOwnPiAgentDir } from "./pi-agent-di
import { noticeFailure } from "../chat-notices.ts";
import { decodePiFrame, PiRpcChunks, piLineReader, piNativeLogMessage, readPiPromptImages } from "./pi-rpc.ts";
-import { PiRunUsage, type PiUsage, type TurnUsage } from "./pi-usage.ts";
+import { piMessageUsage, PiRunUsage, type PiUsage, type TurnUsage } from "./pi-usage.ts";
export { decodePiFrame, PiRpcChunks, piLineReader } from "./pi-rpc.ts";
const DRIVER_KIND = "piAgent";
@@ -80,6 +80,7 @@ interface PiModelEntry {
provider: string;
id: string;
name?: string;
+ contextWindow?: number;
}
interface PiModelsResponse {
@@ -92,11 +93,15 @@ interface PiModelsResponse {
function piCatalogFromFrame(frame: unknown, fallbackDefault: string): ModelCatalog | null {
const res = frame as PiModelsResponse;
if (res?.type !== "response" || res.command !== "get_available_models" || !res.success) return null;
- const options: Array<{ id: string; label: string; custom: true; provider: string }> = [];
+ const options: Array<{ id: string; label: string; custom: true; provider: string; contextWindow?: number }> = [];
for (const m of res.data?.models ?? []) {
if (!m?.provider || !m?.id) continue;
const id = `${m.provider}/${m.id}`;
- options.push({ id, label: m.name ?? m.id, custom: true, provider: m.provider });
+ const contextWindow = m.contextWindow;
+ options.push({
+ id, label: m.name ?? m.id, custom: true, provider: m.provider,
+ ...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0 ? { contextWindow } : {}),
+ });
}
return { default: fallbackDefault || (options[0]?.id ?? ""), options };
}
@@ -710,9 +715,23 @@ export const PiDriver: ProviderDriver<PiConfig> = {
if (evt.type.endsWith("compaction_end") && typeof (evt as { result?: { summary?: unknown } }).result?.summary === "string" && /\S/.test((evt as { result: { summary: string } }).result.summary) && !(evt as { aborted?: boolean }).aborted && !(evt as { errorMessage?: string }).errorMessage) { flushAssistantText(); emit({ ...base(threadId, turnId), type: "context.compacted" }); }
return;
}
- case "message_end":
- if (evt.message?.role === "assistant") runUsage.add(evt.message.usage);
+ case "message_end": {
+ if (evt.message?.role !== "assistant") return;
+ runUsage.add(evt.message.usage);
+ const call = piMessageUsage(evt.message.usage);
+ if (!call) return;
+ const contextWindow = models.options.find((option) => option.id === turn.model)?.contextWindow;
+ emit({
+ ...base(threadId, turnId),
+ type: "thread.token-usage.updated",
+ input: call.input,
+ output: call.output,
+ ...(call.cachedInput === undefined ? {} : { cachedInput: call.cachedInput }),
+ contextTokens: call.contextTokens,
+ ...(typeof contextWindow === "number" && contextWindow > 0 ? { contextWindow } : {}),
+ });
return;
+ }
case "turn_end":
{
// A killed child can still flush one buffered frame after the turn settled.
diff --git a/server/testing/fake-pi-cli.ts b/server/testing/fake-pi-cli.ts
index 95807db534..48f63513d8 100755
--- a/server/testing/fake-pi-cli.ts
+++ b/server/testing/fake-pi-cli.ts
@@ -12,18 +12,21 @@
// FAKE_PI_PERSIST_SESSION persist prompts to disk and load them on switch_session
// FAKE_PI_STEER_REFUSE answer a steer with an explicit success:false
// FAKE_PI_STEER_OUT_OF_ORDER hold the first steer until a second arrives, then refuse the first and accept the second
+// FAKE_PI_CONTEXT_WINDOW positive token count attached to every listed model
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { playStreamScript, streamScript, type StreamScript } from "./stream-script.ts";
const mode = process.env.FAKE_PI_MODE ?? "happy";
+const listedWindow = Number(process.env.FAKE_PI_CONTEXT_WINDOW);
+const modelWindow = Number.isFinite(listedWindow) && listedWindow > 0 ? { contextWindow: listedWindow } : {};
const modelPairs = (process.env.FAKE_PI_MODELS ?? "ollama-cloud/glm-5.2,openai/gpt-4o")
.split(",")
.filter(Boolean)
.map((pair) => {
const [provider, id] = pair.split("/");
- return { provider: provider ?? "x", id: id ?? "m", name: id ?? "m" };
+ return { provider: provider ?? "x", id: id ?? "m", name: id ?? "m", ...modelWindow };
});
const argv = process.argv.slice(2);