Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Context: ask Claude Code for its own per-category count of a conversation's window
luishron123f42c2ce0db69
diff --git a/server/context-breakdown.e2e.test.ts b/server/context-breakdown.e2e.test.tsnew file mode 100644index 0000000000..5a9c040fe7--- /dev/null+++ b/server/context-breakdown.e2e.test.ts@@ -0,0 +1,69 @@+import { existsSync } from "node:fs";+import { expect, it } from "vitest";++import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";+import { request } from "../scripts/mcp-server.ts";+import type { ContextBreakdown } from "../shared/context-breakdown.ts";++const answer = {+ categories: [+ { id: "system_prompt", name: "System prompt", tokens: 1900, color: "promptBorder", kind: "used" },+ { id: "mcp_tools_deferred", name: "MCP tools (deferred)", tokens: 700, color: "inactive", isDeferred: true, kind: "deferred" },+ { id: "messages", name: "Messages", tokens: 4100, color: "purple", kind: "used" },+ { id: "free_space", name: "Free space", tokens: 194000, color: "promptBorder", kind: "free" },+ ],+ totalTokens: 6000, maxTokens: 200000, isAutoCompactEnabled: false,+ messageBreakdown: { toolCallTokens: 100, toolResultTokens: 3000, attachmentTokens: 0, assistantMessageTokens: 600, userMessageTokens: 400 },+};++async function setup(extraEnv: NodeJS.ProcessEnv) {+ const fixture = await launchVerificationServer({ ...process.env, ...extraEnv }, undefined, undefined, undefined, undefined, undefined, ["codex"]);+ const control = async (...args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;+ const bot = (await control("new-bot", "--name", "Context probe")).bot;+ const thread: string = bot.activeTaskId;+ const post = (action: string) => request(`/api/bots/${bot.id}/${action}`, { method: "POST", body: JSON.stringify({ threadId: thread }) }, fixture.info.url);+ const context = () => post("context") as Promise<{ threadId: string; breakdown: ContextBreakdown | null }>;+ const send = async (text: string) => {+ await control("send", "--bot", bot.id, "--task", thread, "--text", text);+ expect((await control("wait", "--bot", bot.id, "--task", thread, "--timeout", "30")).status).toBe("settled");+ };+ const close = async () => { try { await fixture.close(); } finally { expect(existsSync(fixture.info.dataDir)).toBe(false); } };+ return { thread, post, context, send, close };+}++it("answers with the engine's own count while its process holds the conversation, and with nothing otherwise", async () => {+ const f = await setup({ FAKE_CLAUDE_CONTEXT_USAGE: JSON.stringify(answer) });+ try {+ expect(await f.context()).toEqual({ threadId: f.thread, breakdown: null });++ await f.send("hello");+ expect(await f.context()).toEqual({+ threadId: f.thread,+ breakdown: {+ tokens: 6000, window: 200000,+ categories: [+ { id: "system_prompt", kind: "used", tokens: 1900 },+ { id: "messages", kind: "used", tokens: 4100 },+ { id: "free_space", kind: "free", tokens: 194000 },+ ],+ messages: { toolCalls: 100, toolResults: 3000, attachments: 0, assistant: 600, user: 400 },+ autoCompact: false,+ },+ });++ await f.post("start-fresh");+ expect(await f.context()).toEqual({ threadId: f.thread, breakdown: null });+ } finally {+ await f.close();+ }+}, 60_000);++it("has no breakdown from an engine that does not count its window by category", async () => {+ const f = await setup({});+ try {+ await f.send("hello");+ expect(await f.context()).toEqual({ threadId: f.thread, breakdown: null });+ } finally {+ await f.close();+ }+}, 60_000);diff --git a/server/contracts.ts b/server/contracts.tsindex a32afc7435..3ba9c92c12 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -8,6 +8,7 @@ import type {} from "../shared/runtime-events.ts";import type { LocalModelFacts, OllamaProblem } from "../shared/local-model.ts";import type { ProviderIcon } from "../shared/provider-icon.ts";+import type { ContextBreakdown } from "../shared/context-breakdown.ts";export type { CloudBackend, EffortLevel, ModelSelection } from "../shared/wire.ts";export type {@@ -330,6 +331,9 @@ export interface ProviderAdapter {hold(threadId: ThreadId, until: number | null): boolean;compact?(threadId: ThreadId, options: { instructions: string; session?: string; signal?: AbortSignal }): Promise<IdleCompactResult>;};+ /** The engine's own count, by category, of what fills this thread's context window. null when the thread has no live+ * engine process to ask or the engine gave no answer; never an estimate. */+ contextBreakdown?(threadId: ThreadId, options?: { signal?: AbortSignal }): Promise<ContextBreakdown | null>;}/** Tokens are the ping's own; `costUsd` is notional on a subscription. `busy`: a turn was running and nothing was sent;diff --git a/server/drivers/claude-context-usage.test.ts b/server/drivers/claude-context-usage.test.tsnew file mode 100644index 0000000000..9a89a87564--- /dev/null+++ b/server/drivers/claude-context-usage.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from "vitest";+import { claudeContextBreakdown, claudeContextUsage } from "./claude-context-usage.ts";++// The answer Claude Code 2.1.325 gives to get_context_usage, without the fields this module does not read.+const answer = {+ categories: [+ { id: "system_prompt", name: "System prompt", tokens: 1929, color: "promptBorder", kind: "used" },+ { id: "system_tools", name: "System tools", tokens: 8165, color: "inactive", kind: "used" },+ { id: "system_tools_deferred", name: "System tools (deferred)", tokens: 13263, color: "inactive", isDeferred: true, kind: "deferred" },+ { id: "memory_files", name: "Memory files", tokens: 640, color: "claude", kind: "used" },+ { id: "skills", name: "Skills", tokens: 2064, color: "warning", kind: "used" },+ { id: "messages", name: "Messages", tokens: 5200, color: "purple", kind: "used" },+ { id: "autocompact_buffer", name: "Autocompact buffer", tokens: 33000, color: "inactive", kind: "buffer" },+ { id: "free_space", name: "Free space", tokens: 949002, color: "promptBorder", kind: "free" },+ ],+ totalTokens: 17998, maxTokens: 1000000, rawMaxTokens: 1000000, percentage: 2, model: "claude-opus-5-5",+ autoCompactThreshold: 967000, isAutoCompactEnabled: true,+ messageBreakdown: {+ toolCallTokens: 900, toolResultTokens: 3100, attachmentTokens: 0, assistantMessageTokens: 700, userMessageTokens: 500,+ redirectedContextTokens: 0, unattributedTokens: 0, toolCallsByType: [], attachmentsByType: [],+ },+ apiUsage: null,+};+const breakdown = {+ tokens: 17998, window: 1000000,+ categories: [+ { id: "system_prompt", kind: "used", tokens: 1929 },+ { id: "system_tools", kind: "used", tokens: 8165 },+ { id: "memory_files", kind: "used", tokens: 640 },+ { id: "skills", kind: "used", tokens: 2064 },+ { id: "messages", kind: "used", tokens: 5200 },+ { id: "autocompact_buffer", kind: "buffer", tokens: 33000 },+ { id: "free_space", kind: "free", tokens: 949002 },+ ],+ messages: { toolCalls: 900, toolResults: 3100, attachments: 0, assistant: 700, user: 500 },+ autoCompact: true, autoCompactAt: 967000,+};++function harness(delivered = true) {+ const written: any[] = [];+ const context = claudeContextUsage(async (frame) => { written.push(frame); return delivered; });+ const answered = (response: Record<string, unknown>) =>+ context.frame({ type: "control_response", response: { request_id: written.at(-1).request_id, ...response } });+ return { context, written, answered };+}++describe("claudeContextBreakdown", () => {+ it("keeps the engine's rows and leaves out the tool schemas held outside the window", () => {+ expect(claudeContextBreakdown(answer)).toEqual(breakdown);+ });++ it("reports no compaction threshold when the engine does not compact by itself", () => {+ const { messageBreakdown: _parts, ...rest } = answer;+ expect(claudeContextBreakdown({ ...rest, isAutoCompactEnabled: false })).toEqual({+ tokens: breakdown.tokens, window: breakdown.window, categories: breakdown.categories, autoCompact: false,+ });+ });++ it("gives nothing rather than a partial count", () => {+ expect(claudeContextBreakdown(null)).toBeNull();+ expect(claudeContextBreakdown({ ...answer, maxTokens: 0 })).toBeNull();+ expect(claudeContextBreakdown({ ...answer, categories: [{ name: "Messages", tokens: 5200, kind: "used" }] })).toBeNull();+ expect(claudeContextBreakdown({ ...answer, categories: [{ id: "messages", tokens: "many", kind: "used" }] })).toBeNull();+ expect(claudeContextBreakdown({ ...answer, categories: [answer.categories[2]] })).toBeNull();+ });+});++describe("claudeContextUsage", () => {+ it("asks for the summary count and resolves with the CLI's answer", async () => {+ const { context, written, answered } = harness();+ const reading = context.read();+ expect(written).toEqual([{ type: "control_request", request_id: "context-usage-1", request: { subtype: "get_context_usage", detail: "summary" } }]);+ expect(answered({ subtype: "success", response: answer })).toBe(true);+ await expect(reading).resolves.toEqual(breakdown);+ expect(answered({ subtype: "success", response: answer })).toBe(false);+ });++ it("leaves every frame that is not its own answer to the driver", () => {+ const { context } = harness();+ void context.read();+ expect(context.frame({ type: "control_response", response: { subtype: "success", request_id: "other", response: answer } })).toBe(false);+ expect(context.frame({ type: "control_request", request_id: "context-usage-1", request: { subtype: "elicitation" } })).toBe(false);+ expect(context.frame({ type: "assistant" })).toBe(false);+ });++ it("has no breakdown from a CLI that does not know the request", async () => {+ const { context, answered } = harness();+ const reading = context.read();+ answered({ subtype: "error", error: "Unsupported control request subtype: get_context_usage", error_code: "unsupported_request" });+ await expect(reading).resolves.toBeNull();+ });++ it("has no breakdown when the request never reached the CLI, the CLI closed, or the caller stopped waiting", async () => {+ await expect(harness(false).context.read()).resolves.toBeNull();++ const closing = harness();+ const open = closing.context.read();+ closing.context.close();+ await expect(open).resolves.toBeNull();++ const waiting = harness();+ const stop = new AbortController();+ const abandoned = waiting.context.read(stop.signal);+ stop.abort();+ await expect(abandoned).resolves.toBeNull();+ expect(waiting.answered({ subtype: "success", response: answer })).toBe(false);+ await expect(waiting.context.read(stop.signal)).resolves.toBeNull();+ expect(waiting.written).toHaveLength(1);+ });+});diff --git a/server/drivers/claude-context-usage.ts b/server/drivers/claude-context-usage.tsnew file mode 100644index 0000000000..e28016ecbb--- /dev/null+++ b/server/drivers/claude-context-usage.ts@@ -0,0 +1,70 @@+// Claude Code counts its own context window by category: {type:"control_request", request:{subtype:"get_context_usage"}}+// on stdin is answered by a control_response (2.1.325). With detail "summary" it answers from the last response's usage+// and local estimates and makes no token-count call. A CLI that does not know the request answers subtype "error".+import type { ContextBreakdown } from "../../shared/context-breakdown.ts";++const ID_PREFIX = "context-usage-";+const tokens = (value: unknown): number | null =>+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : null;++/** Rows marked deferred are tool schemas kept out of the window, so they are left out. */+export function claudeContextBreakdown(response: any): ContextBreakdown | null {+ const used = tokens(response?.totalTokens);+ const window = tokens(response?.maxTokens);+ if (used === null || !window || !Array.isArray(response.categories)) return null;+ const categories: ContextBreakdown["categories"] = [];+ for (const row of response.categories) {+ const count = tokens(row?.tokens);+ if (row?.kind === "deferred" || row?.isDeferred === true) continue;+ if (typeof row?.id !== "string" || count === null || (row.kind !== "used" && row.kind !== "buffer" && row.kind !== "free")) return null;+ categories.push({ id: row.id, kind: row.kind, tokens: count });+ }+ if (!categories.length) return null;+ const parts = response.messageBreakdown;+ const messages = parts && typeof parts === "object" ? {+ toolCalls: tokens(parts.toolCallTokens), toolResults: tokens(parts.toolResultTokens), attachments: tokens(parts.attachmentTokens),+ assistant: tokens(parts.assistantMessageTokens), user: tokens(parts.userMessageTokens),+ } : null;+ const autoCompactAt = tokens(response.autoCompactThreshold);+ return {+ tokens: used, window, categories,+ ...(messages && Object.values(messages).every((value) => value !== null) ? { messages: messages as ContextBreakdown["messages"] } : {}),+ ...(typeof response.isAutoCompactEnabled === "boolean" ? { autoCompact: response.isAutoCompactEnabled } : {}),+ ...(response.isAutoCompactEnabled === true && autoCompactAt ? { autoCompactAt } : {}),+ };+}++/** `write` settles true once the frame reached the CLI's stdin, false when it could not be sent. */+export function claudeContextUsage(write: (frame: unknown) => Promise<boolean>) {+ const pending = new Map<string, (breakdown: ContextBreakdown | null) => void>();+ let sent = 0;+ const settle = (id: string, breakdown: ContextBreakdown | null) => {+ const resolve = pending.get(id);+ pending.delete(id);+ resolve?.(breakdown);+ };+ return {+ /** Consumes the answer to one of its own requests; false for every other frame. */+ frame(o: any): boolean {+ const id = o?.type === "control_response" ? o.response?.request_id : undefined;+ if (typeof id !== "string" || !pending.has(id)) return false;+ settle(id, o.response.subtype === "success" ? claudeContextBreakdown(o.response.response) : null);+ return true;+ },+ /** null when the CLI has no answer: it does not know the request, it exited, or `signal` gave up waiting. */+ read(signal?: AbortSignal): Promise<ContextBreakdown | null> {+ if (signal?.aborted) return Promise.resolve(null);+ const id = `${ID_PREFIX}${++sent}`;+ return new Promise((resolve) => {+ const giveUp = () => settle(id, null);+ pending.set(id, (breakdown) => { signal?.removeEventListener("abort", giveUp); resolve(breakdown); });+ signal?.addEventListener("abort", giveUp, { once: true });+ void write({ type: "control_request", request_id: id, request: { subtype: "get_context_usage", detail: "summary" } })+ .then((delivered) => { if (!delivered) settle(id, null); });+ });+ },+ close(): void {+ for (const id of pending.keys()) settle(id, null);+ },+ };+}diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex ecd034448e..979f0ad6f2 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -19,6 +19,7 @@ import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./claude-auth-recovery.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.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 { claudeContextUsage } from "./claude-context-usage.ts";import { claudeElicitations } from "./claude-elicitation.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts";import { readCostHistory, recordCostState } from "./claude-cost-history.ts";import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";@@ -835,6 +836,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {child: ReturnType<typeof spawnCli>;broker?: Awaited<ReturnType<typeof createPermissionBroker>>;elicit: ReturnType<typeof claudeElicitations>;+ context: ReturnType<typeof claudeContextUsage>;mcpConfigPath: string | null;systemPromptPath: string | null;argsKey: string; /** the CLI version whose --help chose the args, and whether they include --autocompact */ cliVersion: string | null; passedAutocompact: boolean;@@ -896,6 +898,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {/** Forgets a CLI that died mid-turn and removes its files, so the retry starts a clean session. */const discardSession = (threadId: string, session: Session) => {session.elicit.close();+ session.context.close();if (session.mcpConfigPath) {try {rmSync(dirname(session.mcpConfigPath), { recursive: true, force: true });@@ -920,6 +923,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {s.broker = undefined;broker?.close();s.elicit.close();+ s.context.close();appendNative(threadId, { dir: "out", source: "claude.session", msg: { close: why, ...(contractChanged?.length ? { contractChanged } : {}) } });// stdin EOF is the CLI's exit signal; give it a moment, then insisttry {@@ -1353,17 +1357,18 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {});}let markClosed!: () => void;+ // A CLI that already exited needs no answer: the write is skipped, like writeUser's.+ const writeControl = (frame: unknown) => new Promise<boolean>((resolve) => {+ const { stdin } = session.child;+ if (!stdin.writable || stdin.destroyed) return resolve(false);+ try { stdin.write(`${JSON.stringify(frame)}\n`, (err) => resolve(!err)); } catch { resolve(false); }+ });const session: Session = {closed: new Promise<void>((resolve) => { markClosed = resolve; }),child,broker,- // A CLI that already exited needs no answer: the write is skipped, like writeUser's.- elicit: claudeElicitations((frame) => new Promise<boolean>((resolve) => {- const { stdin } = session.child;- if (!stdin.writable || stdin.destroyed) return resolve(false);- try { stdin.write(`${JSON.stringify(frame)}\n`, (err) => resolve(!err)); } catch { resolve(false); }- }),- (event) => emit({ ...base(threadId, session.turn?.turnId ?? turnId), ...event })),+ elicit: claudeElicitations(writeControl, (event) => emit({ ...base(threadId, session.turn?.turnId ?? turnId), ...event })),+ context: claudeContextUsage(writeControl),mcpConfigPath,systemPromptPath,argsKey, cliVersion: cliHelpVersion, passedAutocompact,@@ -1451,7 +1456,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {authRecovery.frame(threadId, o, session.costTotal);// A replayed stdin message carries its images again: keep their bytes out of the log.appendNative(threadId, { dir: "in", source: "claude.sdk.message", msg: o?.type === "user" && o.isReplay === true && o.message ? diagnosticClaudeUserMessage(o) : o });- if (session.elicit.frame(o)) return;+ if (session.elicit.frame(o) || session.context.frame(o)) return;if (session.turn?.continuationSilence && !(o.type === "system" && o.subtype === "init") && !(o.type === "user" && o.isReplay === true)) {clearTimeout(session.turn.continuationSilence);session.turn.continuationSilence = null;@@ -1846,6 +1851,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {if (session.idleTimer) clearTimeout(session.idleTimer);session.broker?.close();session.elicit.close();+ session.context.close();if (session.mcpConfigPath) {try {rmSync(dirname(session.mcpConfigPath), { recursive: true, force: true });@@ -2060,6 +2066,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {hasSession: (threadId) => active.has(threadId),enginePid: (threadId) => (active.has(threadId) ? sessions.get(threadId)?.child.pid : undefined),cacheKeepWarm: forks.adapter,+ contextBreakdown: async (threadId, options) => {+ const session = sessions.get(threadId);+ return session && !session.closing && session.child.exitCode === null ? session.context.read(options?.signal) : null;+ },stopAll: async () => {for (const { stop } of active.values()) stop();for (const threadId of Array.from(sessions.keys())) closeSession(threadId, "stopAll");diff --git a/server/request-auth.ts b/server/request-auth.tsindex c137ab9d23..986656d00f 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -358,6 +358,7 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/active-branch$/ },{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/compact$/ },{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/start-fresh$/ },+ { methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/context$/ },{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/helper-followup$/ }, // MausBot's own person only: see mayFollowUp{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/interrupt$/ },{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/read$/ },diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 579a5959c3..8a982e4db6 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -164,6 +164,8 @@ const guardedSendSchema = z.object({}).strict().refine((who) => Boolean(who.email || who.name)).optional(),}).strict().refine((send) => (send.text === undefined) !== (send.reaction === undefined));+const CONTEXT_BREAKDOWN_WAIT_MS = 5_000;+export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler {const {store, registry, handoffs, liveTurn, phoneSecretSubmissions, directTurnDispatchClaims, groupSpeakers,@@ -494,6 +496,20 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerreturn json(res, 200, { ok: true, message: startFresh(store, bot.id, bot.threadId), threadId: bot.threadId });}+ m = path.match(/^\/api\/bots\/([\w-]+)\/context$/);+ if (m && method === "POST") {+ const body = await readBody(req);+ requirePinnedClientThread(m[1], body?.threadId);+ const bot = requestedTaskBot(m[1], body?.threadId);+ const notYours = cloudThreadRefusal(auth, bot.threadId);+ if (notYours) return json(res, 403, { error: notYours });+ // After Start fresh the engine process still holds the conversation the person left, until the next turn replaces it.+ const stale = store.taskByThread(bot.id, bot.threadId)?.rewound === true;+ const breakdown = stale ? null : await registry.get(bot.modelSelection.instanceId)?.adapter+ .contextBreakdown?.(bot.threadId, { signal: AbortSignal.timeout(CONTEXT_BREAKDOWN_WAIT_MS) }) ?? null;+ return json(res, 200, { threadId: bot.threadId, breakdown });+ }+m = path.match(/^\/api\/bots\/([\w-]+)\/messages\/([\w-]+)\/edit$/);if (m && method === "POST") {const messageId = m[2];diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.tsindex 74410254a3..919bbf97c2 100755--- a/server/testing/fake-claude-cli.ts+++ b/server/testing/fake-claude-cli.ts@@ -15,6 +15,8 @@// FAKE_CLAUDE_DUMP path for the latest turn's {argv, env, cwd, prompt, systemPrompt, mcpConfig}// FAKE_CLAUDE_ELICIT JSON request body: a "hang" turn (or a failing FAKE_CLAUDE_TRANSIENTS launch) first asks it// as control_request "elicit-1"+// FAKE_CLAUDE_CONTEXT_USAGE JSON answered to a get_context_usage control_request; unset, the request is refused as+// unsupported, like any other control_request// FAKE_CLAUDE_CONTROL_LOG JSON-lines file every control_response the host writes is appended to// FAKE_CLAUDE_EXIT_AFTER_TURN 1: exit once the turn is answered, so later turns relaunch with --resume// FAKE_CLAUDE_AUTH_AFTER_TURN 1: from the second turn, answer as not-logged-in; FAKE_CLAUDE_AUTH_AFTER_WORK 1: not-logged-in@@ -1337,6 +1339,14 @@ process.stdin.on("data", (c) => {if (process.env.FAKE_CLAUDE_CONTROL_LOG) appendFileSync(process.env.FAKE_CLAUDE_CONTROL_LOG, `${line}\n`);continue;}+ const control = prompt as { type?: unknown; request_id?: unknown; request?: { subtype?: unknown } } | null;+ if (control?.type === "control_request") {+ const usage = control.request?.subtype === "get_context_usage" ? process.env.FAKE_CLAUDE_CONTEXT_USAGE : undefined;+ out({ type: "control_response", response: usage+ ? { subtype: "success", request_id: control.request_id, response: JSON.parse(usage) }+ : { subtype: "error", request_id: control.request_id, error: `Unsupported control request subtype: ${String(control.request?.subtype)}`, error_code: "unsupported_request" } });+ continue;+ }if (turnRunning || lateTurnWaiting) {if (process.env.FAKE_CLAUDE_LATE_STEER_GATE) lateSteers.push(prompt);else {diff --git a/shared/context-breakdown.ts b/shared/context-breakdown.tsnew file mode 100644index 0000000000..a2c9a07146--- /dev/null+++ b/shared/context-breakdown.ts@@ -0,0 +1,16 @@+/** An engine's own count of what fills a conversation's context window. Absent wherever the engine does not report one:+ * the harness never estimates a category. */+export interface ContextBreakdown {+ /** Tokens in the window now. */+ tokens: number;+ window: number;+ /** `used` rows are in the window, `buffer` is what the engine holds back for its own compaction and `free` is the+ * rest. `id` is the engine's key for the row; Claude Code's are system_prompt, system_tools, mcp_tools,+ * mcp_instructions, custom_agents, memory_files, skills, messages, autocompact_buffer, compact_buffer and free_space. */+ categories: Array<{ id: string; kind: "used" | "buffer" | "free"; tokens: number }>;+ /** What the `messages` row is made of. */+ messages?: { toolCalls: number; toolResults: number; attachments: number; assistant: number; user: number };+ /** The engine compacts the conversation by itself, at `autoCompactAt` tokens when it says where. */+ autoCompact?: boolean;+ autoCompactAt?: number;+}