Skip to content

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

fix: charge Claude session forks for their own usage

jonathanwxh-cella9d483545948
diff --git a/server/drivers/claude-cost-history.ts b/server/drivers/claude-cost-history.ts
index f79dde8887..4d1c791e59 100644
--- a/server/drivers/claude-cost-history.ts
+++ b/server/drivers/claude-cost-history.ts
@@ -3,7 +3,6 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { DATA_DIR } from "../config.ts";
import { writeFileAtomic } from "../atomic.ts";
-import type { ClaudeCostSnapshot } from "./claude.ts";
const COST_HISTORY_FILE = join(DATA_DIR, "claude-cost-history.json");
const COST_HISTORY_SESSIONS = 100;
@@ -37,3 +36,57 @@ export function recordCostState(sessionId: string, state: ClaudeCostSnapshot): v
writeFileAtomic(COST_HISTORY_FILE, JSON.stringify(history), { mode: 0o600, durable: false });
} catch {}
}
+
+/** A turn's cost from total_cost_usd, which is the process's running total (2.1.282): the growth
+ * since `previous`, or the whole figure when the start is unknown or the total went down. */
+export function turnCostFromRunningTotal(total: number | null, previous: number | null): number | null {
+ if (total === null) return null;
+ if (previous === null || total < previous) return total;
+ return Number((total - previous).toFixed(10));
+}
+
+/** total_cost_usd and per-model modelUsage [input, cache read, cache write, output] from a
+ * `result`; both cover the whole session, including what --resume restored. */
+export interface ClaudeCostSnapshot {
+ total: number;
+ models: Record<string, [number, number, number, number]>;
+}
+
+export function claudeCostSnapshot(total: unknown, modelUsage: unknown): ClaudeCostSnapshot | null {
+ if (typeof total !== "number" || !Number.isFinite(total)) return null;
+ const count = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
+ const models: ClaudeCostSnapshot["models"] = {};
+ if (modelUsage && typeof modelUsage === "object" && !Array.isArray(modelUsage)) {
+ for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) {
+ if (!raw || typeof raw !== "object") continue;
+ const u = raw as Record<string, unknown>;
+ models[model] = [count(u.inputTokens), count(u.cacheReadInputTokens), count(u.cacheCreationInputTokens), count(u.outputTokens)];
+ }
+ }
+ return { total, models };
+}
+
+/** The running total a resumed session carried before this process's first turn. On --resume the
+ * CLI (2.1.282) restores cost from an earlier state, not always the latest one seen. */
+export function restoredCostBase(
+ earlier: readonly ClaudeCostSnapshot[],
+ current: ClaudeCostSnapshot,
+ usage: { input: number; cacheRead: number; cacheWrite: number; output: number },
+): number {
+ const turn = [usage.input, usage.cacheRead, usage.cacheWrite, usage.output];
+ const nothing: ClaudeCostSnapshot = { total: 0, models: {} };
+ let exact: number | null = null;
+ let inside = 0;
+ for (const state of [nothing, ...earlier]) {
+ const within = Object.entries(state.models).every(([model, counts]) =>
+ counts.every((n, i) => n <= (current.models[model]?.[i] ?? 0)));
+ if (!within) continue;
+ inside = state.total;
+ const growth = Object.entries(current.models).map(([model, counts]) =>
+ counts.map((n, i) => n - (state.models[model]?.[i] ?? 0)));
+ const isTurn = (counts: number[]) => counts.every((n, i) => n === turn[i]);
+ const summed = turn.map((_, i) => growth.reduce((sum, counts) => sum + counts[i]!, 0));
+ if (growth.some(isTurn) || isTurn(summed)) exact = state.total;
+ }
+ return exact ?? inside;
+}
diff --git a/server/drivers/claude-keepwarm.ts b/server/drivers/claude-keepwarm.ts
index 47ebf2f91c..aad8f28a10 100644
--- a/server/drivers/claude-keepwarm.ts
+++ b/server/drivers/claude-keepwarm.ts
@@ -14,6 +14,7 @@
// The CLI starts every command server in its MCP config as it launches, before any tool call, and the bot's own servers
// are in that config (the tool list is part of the prefix). So a fork runs where the bot's turns run: in the bot box
// where that is on, with the same plan a turn gets (forkSpawnOptions).
+import { claudeCostSnapshot, readCostHistory, restoredCostBase, turnCostFromRunningTotal, type ClaudeCostSnapshot } from "./claude-cost-history.ts";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -82,7 +83,22 @@ export const KEEP_WARM_DENY_HOOK = `process.stdout.write(JSON.stringify({ hookSp
const count = (value: unknown): number => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
-export function parseKeepWarmResult(stdout: string, stderr: string, code: number | null): CacheWarmPingResult {
+export function forkUsage(frame: Record<string, unknown>, earlier: readonly ClaudeCostSnapshot[]) {
+ const usage = (frame.usage ?? {}) as Record<string, unknown>;
+ const models = frame.modelUsage && typeof frame.modelUsage === "object" && !Array.isArray(frame.modelUsage)
+ ? Object.keys(frame.modelUsage) : [];
+ const tokens = {
+ input: count(usage.input_tokens),
+ cacheRead: count(usage.cache_read_input_tokens),
+ cacheWrite: count(usage.cache_creation_input_tokens),
+ output: count(usage.output_tokens),
+ };
+ const state = claudeCostSnapshot(frame.total_cost_usd, frame.modelUsage);
+ const costUsd = state ? turnCostFromRunningTotal(state.total, restoredCostBase(earlier, state, tokens)) : null;
+ return { ...tokens, costUsd, model: models[0] ?? null };
+}
+
+export function parseKeepWarmResult(stdout: string, stderr: string, code: number | null, earlier: readonly ClaudeCostSnapshot[] = []): CacheWarmPingResult {
let frame: Record<string, unknown> | null = null;
try {
const parsed = JSON.parse(stdout.trim());
@@ -99,18 +115,7 @@ export function parseKeepWarmResult(stdout: string, stderr: string, code: number
const limit = frame.api_error === "usage_limit_reached" || USAGE_LIMIT.test(text);
return { ok: false, reason: limit ? "the account's usage limit refused the ping" : `the ping failed: ${text.slice(0, 300) || "API error"}`, ...(limit ? { limit: true } : {}) };
}
- const usage = (frame.usage ?? {}) as Record<string, unknown>;
- const models = frame.modelUsage && typeof frame.modelUsage === "object" && !Array.isArray(frame.modelUsage)
- ? Object.keys(frame.modelUsage) : [];
- return {
- ok: true,
- input: count(usage.input_tokens),
- cacheRead: count(usage.cache_read_input_tokens),
- cacheWrite: count(usage.cache_creation_input_tokens),
- output: count(usage.output_tokens),
- costUsd: typeof frame.total_cost_usd === "number" && Number.isFinite(frame.total_cost_usd) ? frame.total_cost_usd : null,
- model: models[0] ?? null,
- };
+ return { ok: true, ...forkUsage(frame, earlier) };
}
/** How a fork is started: in the conversation's engine home and, where turns are boxed, in a box like its turns'
@@ -129,8 +134,9 @@ export function runKeepWarmPing(opts: {
signal?: AbortSignal;
timeoutMs?: number;
}): Promise<CacheWarmPingResult> {
+ const earlier = readCostHistory()[opts.sessionId] ?? [];
return runForkedPrompt({ ...opts, what: "ping", prompt: KEEP_WARM_PROMPT, persist: false, timeoutMs: opts.timeoutMs ?? KEEP_WARM_TIMEOUT_MS,
- parse: parseKeepWarmResult, failed: (reason) => ({ ok: false, reason }) });
+ parse: (stdout, stderr, code) => parseKeepWarmResult(stdout, stderr, code, earlier), failed: (reason) => ({ ok: false, reason }) });
}
/** One prompt on a fork of a live session, with that session's exact launch contract so its cached prompt start is read
diff --git a/server/drivers/claude-warm-summary.test.ts b/server/drivers/claude-warm-summary.test.ts
index a5490a4bd4..3996d15545 100644
--- a/server/drivers/claude-warm-summary.test.ts
+++ b/server/drivers/claude-warm-summary.test.ts
@@ -9,6 +9,7 @@ import type { ProviderInstance } from "../contracts.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { ClaudeDriver } from "./claude.ts";
+import { readCostHistory, recordCostState } from "./claude-cost-history.ts";
import type { KeepWarmContract } from "./claude-keepwarm.ts";
import { claudeForks, PARKED_FORK_MS, parseWarmSummaryResult, warmSummaryPrompt, type WarmSummaryRun } from "./claude-warm-summary.ts";
@@ -127,6 +128,30 @@ describe("ClaudeDriver warm summary (fake CLI)", () => {
await removeTempDir(scratch);
});
+ it("bills repeated pings and an in-place summary against the state the fork restored", async () => {
+ const session = "cbd80c4c-d57c-4fd5-914b-4869f9c69d9e";
+ const frame = JSON.stringify({
+ type: "result", session_id: session, total_cost_usd: 11.452,
+ usage: { input_tokens: 2, cache_read_input_tokens: 30, output_tokens: 4 },
+ modelUsage: { opus: { inputTokens: 52, cacheReadInputTokens: 230, cacheCreationInputTokens: 4, outputTokens: 13 } },
+ });
+ vi.stubEnv("FAKE_CLAUDE_PING_RESULT", frame);
+ vi.stubEnv("FAKE_CLAUDE_COMPACT_RESULT", frame);
+ try {
+ await instance.adapter.sendTurn({ threadId: "t-cost", text: "hi", resumeCursor: session });
+ await recorder.until((e) => e.type === "turn.completed");
+ recordCostState(session, { total: 11.44, models: { opus: [50, 200, 4, 9] } });
+ recordCostState(session, { total: 12, models: { opus: [80, 300, 5, 15] } });
+ const forks = instance.adapter.cacheKeepWarm!;
+ for (let i = 0; i < 2; i++) expect(await forks.ping("t-cost")).toMatchObject({ ok: true, costUsd: 0.012 });
+ expect(readCostHistory()[session]?.at(-1)?.total).toBe(12);
+ expect(await forks.compact!("t-cost", { instructions: "", session })).toMatchObject({ ok: true, session, costUsd: 0.012 });
+ expect(readCostHistory()[session]?.at(-1)?.total).toBe(11.452);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
it("summarizes on a persisted fork of the live session with its launch contract, and the next turn resumes the fork", async () => {
await instance.adapter.sendTurn({ threadId: "t-sum", botId: "b1", text: "hi", model: "claude-sonnet-5", system: "You are Editor." });
await recorder.until((e) => e.type === "turn.completed");
diff --git a/server/drivers/claude-warm-summary.ts b/server/drivers/claude-warm-summary.ts
index 5dcf40c052..ec500466ce 100644
--- a/server/drivers/claude-warm-summary.ts
+++ b/server/drivers/claude-warm-summary.ts
@@ -7,7 +7,8 @@
// only when no turn started meanwhile, so a person who writes during a summary is not held up by it (the host may still
// choose to wait for one when the turn would summarize anyway: server/warm-summary.ts).
import type { CacheWarmPingResult, IdleCompactResult } from "../contracts.ts";
-import { type KeepWarmContract, runForkedPrompt, runKeepWarmPing } from "./claude-keepwarm.ts";
+import { readCostHistory, type ClaudeCostSnapshot } from "./claude-cost-history.ts";
+import { forkUsage, type KeepWarmContract, runForkedPrompt, runKeepWarmPing } from "./claude-keepwarm.ts";
import { USAGE_LIMIT } from "./retry.ts";
/** Writing the summary is most of it: thousands of output tokens, 35 to 60 s on Opus for a 160k conversation. */
@@ -23,12 +24,10 @@ export function warmSummaryPrompt(instructions: string): string {
return line ? `/compact ${line}` : "/compact";
}
-const count = (value: unknown): number => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
-
/** The fork's session and usage, plus its running cost for the driver's cost history. */
export type WarmSummaryRun = IdleCompactResult & { costTotal?: number; modelUsage?: unknown };
-export function parseWarmSummaryResult(stdout: string, stderr: string, code: number | null, sessionBefore: string): WarmSummaryRun {
+export function parseWarmSummaryResult(stdout: string, stderr: string, code: number | null, sessionBefore: string, earlier: readonly ClaudeCostSnapshot[] = []): WarmSummaryRun {
let frame: Record<string, unknown> | null = null;
try {
const parsed = JSON.parse(stdout.trim());
@@ -47,18 +46,11 @@ export function parseWarmSummaryResult(stdout: string, stderr: string, code: num
}
const session = typeof frame.session_id === "string" && frame.session_id.trim() ? frame.session_id : null;
if (!session) return { ok: false, reason: "the summary did not say which session it wrote" };
- const usage = (frame.usage ?? {}) as Record<string, unknown>;
- const models = frame.modelUsage && typeof frame.modelUsage === "object" && !Array.isArray(frame.modelUsage) ? Object.keys(frame.modelUsage) : [];
return {
ok: true,
session,
sessionBefore,
- input: count(usage.input_tokens),
- cacheRead: count(usage.cache_read_input_tokens),
- cacheWrite: count(usage.cache_creation_input_tokens),
- output: count(usage.output_tokens),
- costUsd: typeof frame.total_cost_usd === "number" && Number.isFinite(frame.total_cost_usd) ? frame.total_cost_usd : null,
- model: models[0] ?? null,
+ ...forkUsage(frame, earlier),
...(typeof frame.total_cost_usd === "number" ? { costTotal: frame.total_cost_usd } : {}),
...(frame.modelUsage !== undefined ? { modelUsage: frame.modelUsage } : {}),
};
@@ -67,10 +59,11 @@ export function parseWarmSummaryResult(stdout: string, stderr: string, code: num
export function runWarmSummary(opts: {
cli: string; contract: KeepWarmContract; sessionId: string; instructions: string; signal?: AbortSignal; timeoutMs?: number;
}): Promise<WarmSummaryRun> {
+ const earlier = readCostHistory()[opts.sessionId] ?? [];
return runForkedPrompt<WarmSummaryRun>({
cli: opts.cli, contract: opts.contract, sessionId: opts.sessionId, what: "summary", prompt: warmSummaryPrompt(opts.instructions),
persist: true, timeoutMs: opts.timeoutMs ?? WARM_SUMMARY_TIMEOUT_MS, signal: opts.signal,
- parse: (stdout, stderr, code) => parseWarmSummaryResult(stdout, stderr, code, opts.sessionId),
+ parse: (stdout, stderr, code) => parseWarmSummaryResult(stdout, stderr, code, opts.sessionId, earlier),
failed: (reason) => ({ ok: false, reason }),
});
}
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index d5c44e6c3b..975c4e37ae 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -20,7 +20,8 @@ import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./cla
import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.ts";
import { claudeOwnMcpOverHttp, withLoopbackNoProxy } from "./own-mcp-http.ts"; import { claudeAgentsMount, claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";
import { claudeElicitations } from "./claude-elicitation.ts"; import { claudePrestartTools, type ClaudePrestartTools } from "./claude-prestart.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts"; import { claudeContextUsage, liveContextBreakdown, writeControlFrame } from "./claude-context-usage.ts";
-import { readCostHistory, recordCostState } from "./claude-cost-history.ts";
+import { claudeCostSnapshot, readCostHistory, recordCostState, restoredCostBase, turnCostFromRunningTotal } from "./claude-cost-history.ts";
+export { claudeCostSnapshot, restoredCostBase, turnCostFromRunningTotal, type ClaudeCostSnapshot } from "./claude-cost-history.ts";
import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";
import { ClaudeLoginController } from "./claude-login-auth.ts";
@@ -639,60 +640,6 @@ function firstText(content: unknown): string {
return Array.isArray(content) ? content.filter((b) => b?.type === "text" && b.text).map((b) => b.text).join("") : "";
}
-/** A turn's cost from total_cost_usd, which is the process's running total (2.1.282): the growth
- * since `previous`, or the whole figure when the start is unknown or the total went down. */
-export function turnCostFromRunningTotal(total: number | null, previous: number | null): number | null {
- if (total === null) return null;
- if (previous === null || total < previous) return total;
- return Number((total - previous).toFixed(10));
-}
-
-/** total_cost_usd and per-model modelUsage [input, cache read, cache write, output] from a
- * `result`; both cover the whole session, including what --resume restored. */
-export interface ClaudeCostSnapshot {
- total: number;
- models: Record<string, [number, number, number, number]>;
-}
-
-export function claudeCostSnapshot(total: unknown, modelUsage: unknown): ClaudeCostSnapshot | null {
- if (typeof total !== "number" || !Number.isFinite(total)) return null;
- const count = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
- const models: ClaudeCostSnapshot["models"] = {};
- if (modelUsage && typeof modelUsage === "object" && !Array.isArray(modelUsage)) {
- for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) {
- if (!raw || typeof raw !== "object") continue;
- const u = raw as Record<string, unknown>;
- models[model] = [count(u.inputTokens), count(u.cacheReadInputTokens), count(u.cacheCreationInputTokens), count(u.outputTokens)];
- }
- }
- return { total, models };
-}
-
-/** The running total a resumed session carried before this process's first turn. On --resume the
- * CLI (2.1.282) restores cost from an earlier state, not always the latest one seen. */
-export function restoredCostBase(
- earlier: readonly ClaudeCostSnapshot[],
- current: ClaudeCostSnapshot,
- usage: { input: number; cacheRead: number; cacheWrite: number; output: number },
-): number {
- const turn = [usage.input, usage.cacheRead, usage.cacheWrite, usage.output];
- const nothing: ClaudeCostSnapshot = { total: 0, models: {} };
- let exact: number | null = null;
- let inside = 0;
- for (const state of [nothing, ...earlier]) {
- const within = Object.entries(state.models).every(([model, counts]) =>
- counts.every((n, i) => n <= (current.models[model]?.[i] ?? 0)));
- if (!within) continue;
- inside = state.total;
- const growth = Object.entries(current.models).map(([model, counts]) =>
- counts.map((n, i) => n - (state.models[model]?.[i] ?? 0)));
- const isTurn = (counts: number[]) => counts.every((n, i) => n === turn[i]);
- const summed = turn.map((_, i) => growth.reduce((sum, counts) => sum + counts[i]!, 0));
- if (growth.some(isTurn) || isTurn(summed)) exact = state.total;
- }
- return exact ?? inside;
-}
-
type ClaudeImage = NonNullable<SendTurnInput["images"]>[number];
type ClaudeUserContent =
| { type: "image"; source: { type: "base64"; media_type: ClaudeImage["mime"]; data: string } }