xonecas.io
64875
Mc

mini-coder / commit acbd1e9

chore: code cleanup and small improvements

xonecas2026-09-25 acbd1e9a0f360bda9147a0c6675db53eebef243b parent 210098a

15 files changed

src/agent.ts+30−37
@@ -13,7 +13,6 @@ import {
1313 } from "@earendil-works/pi-ai";
1414 import type { Session } from "./session.ts";
1515 import { acceptsImages, executeTool, type ToolDetails, type ToolResult } from "./tools/index.ts";
16-import type { ToolName } from "./config.ts";
1716
1817 export type Phase = "preparing" | "waitingModel" | "streaming" | "runningTool" | "pausing" | "idle";
1918
@@ -21,15 +20,15 @@ export type AgentEvent =
2120 | { type: "phase"; phase: Phase; detail?: string }
2221 | { type: "text"; delta: string }
2322 | { type: "reasoning"; delta: string }
24- | { type: "toolCall"; name: string; callId: string; arguments: JsonObject }
25- | { type: "toolOutput"; name: string; callId: string; chunk: string }
26- | { type: "toolResult"; name: string; callId: string; text: string; isError: boolean }
23+ | { type: "toolCall"; name: string; arguments: JsonObject }
24+ | { type: "toolOutput"; chunk: string }
25+ | { type: "toolResult"; name: string; text: string; isError: boolean }
2726 | { type: "message"; message: AssistantMessage }
2827 | { type: "error"; message: string }
2928 | { type: "cancelled" }
3029 | { type: "complete" };
3130
32-export interface Interaction {
31+interface Interaction {
3332 isPauseRequested(): boolean;
3433 clearPause(): void;
3534 requestSteering(): Promise<string>;
@@ -47,12 +46,11 @@ export interface AgentOptions {
4746 model: Model<Api>;
4847 systemPrompt: string;
4948 tools: Tool[];
50- toolNames: ToolName[];
5149 thinkingEffort: ModelThinkingLevel;
5250 session: Session;
5351 }
5452
55-export interface AgentRun extends AgentOptions {
53+interface AgentRun extends AgentOptions {
5654 messages: Message[];
5755 signal: AbortSignal;
5856 interaction: Interaction;
@@ -63,9 +61,8 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
6361 const { messages, session, signal, interaction, onEvent } = run;
6462
6563 /** Appends a user message the model reads at the next step boundary. */
66- const steer = (texts: string[]): void => {
67- const content = texts.filter((text) => text.length > 0).join("\n");
68- if (content.length === 0) return;
64+ const steer = (content: string): void => {
65+ if (content === "") return;
6966 const message: UserMessage = { role: "user", content, timestamp: Date.now() };
7067 messages.push(message);
7168 session.appendMessage(message);
@@ -74,28 +71,29 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
7471 /**
7572 * Returns the steering typed while paused, or ""; the caller decides where
7673 * it lands, because a user message between an assistant turn and its tool
77- * results is rejected by the provider.
74+ * results is rejected by the provider. Null once the turn has been aborted;
75+ * every step boundary is a cancellation point.
7876 */
79- const pause = async (): Promise<string> => {
80- if (!interaction.isPauseRequested()) return "";
81- interaction.clearPause();
82- onEvent({ type: "phase", phase: "pausing" });
83- const steering = await interaction.requestSteering();
84- onEvent({ type: "phase", phase: "idle" });
85- return steering;
77+ const pauseStep = async (): Promise<string | null> => {
78+ if (signal.aborted) return null;
79+ if (interaction.isPauseRequested()) {
80+ interaction.clearPause();
81+ onEvent({ type: "phase", phase: "pausing" });
82+ const steering = await interaction.requestSteering();
83+ onEvent({ type: "phase", phase: "idle" });
84+ if (signal.aborted) return null;
85+ return steering;
86+ }
87+ return "";
8688 };
8789
8890 for (;;) {
89- if (signal.aborted) {
90- onEvent({ type: "cancelled" });
91- return;
92- }
93- const steering = await pause();
94- if (signal.aborted) {
91+ const steering = await pauseStep();
92+ if (steering === null) {
9593 onEvent({ type: "cancelled" });
9694 return;
9795 }
98- steer([steering]);
96+ steer(steering);
9997
10098 onEvent({ type: "phase", phase: "preparing" });
10199 session.appendRequest({
@@ -130,7 +128,6 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
130128 onEvent({
131129 type: "toolCall",
132130 name: event.toolCall.name,
133- callId: event.toolCall.id,
134131 arguments: event.toolCall.arguments,
135132 });
136133 }
@@ -165,28 +162,24 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
165162 // tool results.
166163 const held: string[] = [];
167164 for (const call of toolCalls) {
168- if (signal.aborted) {
169- onEvent({ type: "cancelled" });
170- return;
171- }
172- const steering = await pause();
173- if (signal.aborted) {
165+ const steering = await pauseStep();
166+ if (steering === null) {
174167 onEvent({ type: "cancelled" });
175168 return;
176169 }
177170 if (steering !== "") held.push(steering);
178171 onEvent({ type: "phase", phase: "runningTool", detail: call.name });
179172
180- const tool = run.toolNames.find((name) => name === call.name);
173+ const tool = run.tools.find((candidate) => candidate.name === call.name);
181174 let result: ToolResult;
182175 if (tool === undefined) {
183176 result = { text: `unknown tool: ${call.name}`, isError: true };
184177 } else {
185178 try {
186- result = await executeTool(tool, call, {
179+ result = await executeTool(call, {
187180 signal,
188181 supportsImages: acceptsImages(run.model),
189- onOutput: (chunk) => onEvent({ type: "toolOutput", name: call.name, callId: call.id, chunk }),
182+ onOutput: (chunk) => onEvent({ type: "toolOutput", chunk }),
190183 });
191184 } catch (error) {
192185 result = { text: (error as Error).message, isError: true };
@@ -204,8 +197,8 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
204197 };
205198 messages.push(toolMessage);
206199 session.appendMessage(toolMessage);
207- onEvent({ type: "toolResult", name: call.name, callId: call.id, text: result.text, isError: result.isError });
200+ onEvent({ type: "toolResult", name: call.name, text: result.text, isError: result.isError });
208201 }
209- steer(held);
202+ steer(held.join("\n"));
210203 }
211204 }
src/cli.ts+5−13
@@ -10,18 +10,11 @@ import { runTui } from "./tui/tui.ts";
1010 function parseArgs(argv: string[]): { print: string | null } {
1111 let print: string | null = null;
1212 for (let i = 0; i < argv.length; i++) {
13- const arg = argv[i];
14- if (arg === "-p" || arg === "--print") {
15- const value = argv[++i];
16- if (value === undefined) throw new Error(`${arg} requires a prompt`);
17- print = value;
18- } else if (arg.startsWith("--print=")) {
19- print = arg.slice("--print=".length);
20- } else if (arg.startsWith("-p=")) {
21- print = arg.slice("-p=".length);
22- } else {
23- throw new Error(`unknown argument: ${arg}`);
24- }
13+ const match = /^(?:-p|--print)(?:=(.*))?$/.exec(argv[i]);
14+ if (match === null) throw new Error(`unknown argument: ${argv[i]}`);
15+ const value = match[1] ?? argv[++i];
16+ if (value === undefined) throw new Error(`${argv[i - 1]} requires a prompt`);
17+ print = value;
2518 }
2619 return { print };
2720 }
@@ -87,7 +80,6 @@ async function main(): Promise<void> {
8780 model,
8881 systemPrompt: buildSystemPrompt(config),
8982 tools: toolSchemas(config.tools, acceptsImages(model)),
90- toolNames: config.tools,
9183 thinkingEffort: clampThinkingLevel(model, config.thinkingEffort),
9284 session,
9385 };
src/config.ts+4−3
@@ -108,16 +108,17 @@ const API_FACTORY: Record<CustomApi, () => ReturnType<typeof openAICompletionsAp
108108 export function resolveModel(config: Config): { models: MutableModels; model: Model<Api> } {
109109 const models = builtinModels();
110110 for (const provider of config.customProviders) {
111+ const name = provider.name ?? provider.id;
111112 models.setProvider(
112113 createProvider({
113114 id: provider.id,
114- name: provider.name ?? provider.id,
115+ name,
115116 baseUrl: provider.baseUrl,
116117 headers: provider.headers,
117118 auth: {
118119 apiKey: provider.envKeys?.length
119- ? envApiKeyAuth(provider.name ?? provider.id, provider.envKeys)
120- : { name: provider.name ?? provider.id, resolve: async () => ({ auth: { apiKey: "unused" } }) },
120+ ? envApiKeyAuth(name, provider.envKeys)
121+ : { name, resolve: async () => ({ auth: { apiKey: "unused" } }) },
121122 },
122123 api: API_FACTORY[provider.api](),
123124 models: provider.models.map((id) => ({
src/session.ts+4−5
@@ -73,10 +73,9 @@ function titleFor(message: Message): string {
7373 }
7474
7575 export class Session {
76- readonly sessionsDir: string;
77- readonly cwd: string;
76+ private readonly sessionsDir: string;
77+ private readonly cwd: string;
7878 id: string | null = null;
79- logPath: string | null = null;
8079 private fd: number | null = null;
8180 private closed = false;
8281
@@ -123,8 +122,8 @@ export class Session {
123122 throw error;
124123 }
125124 this.id = name;
126- this.logPath = join(dir, "session.jsonl");
127- this.fd = openSync(this.logPath, "a");
125+ const logPath = join(dir, "session.jsonl");
126+ this.fd = openSync(logPath, "a");
128127 const header: SessionHeader = {
129128 type: "session",
130129 version: 1,
src/tools/bash.ts+1−1
@@ -6,7 +6,7 @@ export const BASH_PARAMS = Type.Object(
66 { command: Type.String({ description: "Command to run" }) },
77 { additionalProperties: false },
88 );
9-export type BashArgs = Static<typeof BASH_PARAMS>;
9+type BashArgs = Static<typeof BASH_PARAMS>;
1010
1111 const MAX_HEAD = 10_000;
1212 const MAX_TAIL = 6_000;
src/tools/edit.ts+1−1
@@ -11,7 +11,7 @@ export const EDIT_PARAMS = Type.Object(
1111 },
1212 { additionalProperties: false },
1313 );
14-export type EditArgs = Static<typeof EDIT_PARAMS>;
14+type EditArgs = Static<typeof EDIT_PARAMS>;
1515
1616 export function edit(args: EditArgs, signal: AbortSignal): ToolResult {
1717 const { path, oldText, newText } = args;
src/tools/index.ts+3−3
@@ -40,8 +40,8 @@ export function toolSchemas(names: ToolName[], withImages: boolean): Tool[] {
4040 return names.map((name) => tools[name]);
4141 }
4242
43-export async function executeTool(name: ToolName, call: ToolCall, ctx: ToolContext): Promise<ToolResult> {
44- if (name === "edit") return edit(parseArgs(EDIT_PARAMS, call.arguments), ctx.signal);
45- if (name === "read") return read(parseArgs(READ_PARAMS, call.arguments), ctx);
43+export async function executeTool(call: ToolCall, ctx: ToolContext): Promise<ToolResult> {
44+ if (call.name === "edit") return edit(parseArgs(EDIT_PARAMS, call.arguments), ctx.signal);
45+ if (call.name === "read") return read(parseArgs(READ_PARAMS, call.arguments), ctx);
4646 return bash(parseArgs(BASH_PARAMS, call.arguments), ctx);
4747 }
src/tools/read.ts+1−1
@@ -7,7 +7,7 @@ export const READ_PARAMS = Type.Object(
77 { path: Type.String({ description: "File path" }) },
88 { additionalProperties: false },
99 );
10-export type ReadArgs = Static<typeof READ_PARAMS>;
10+type ReadArgs = Static<typeof READ_PARAMS>;
1111
1212 const IMAGE_MIME: Record<string, string> = {
1313 png: "image/png",
src/tui/commands.ts+2−2
@@ -5,7 +5,7 @@ export interface CommandContext {
55 write(lines: string[]): void;
66 }
77
8-export interface Command {
8+interface Command {
99 name: string; // no leading slash, lowercase
1010 description: string; // one line, shown by /help
1111 run(ctx: CommandContext, args: string): void;
@@ -35,7 +35,7 @@ const help: Command = {
3535 },
3636 };
3737
38-export const COMMANDS: Command[] = [help];
38+const COMMANDS: Command[] = [help];
3939
4040 /** `/name args` for a known `name`, else null; unknown slash text stays a message. */
4141 export function findCommand(text: string): { command: Command; args: string } | null {
src/tui/editor.ts+1−1
@@ -27,7 +27,7 @@ function wordEnd(cps: string[], col: number): number {
2727 return i;
2828 }
2929
30-export interface EditorRender {
30+interface EditorRender {
3131 rows: string[];
3232 cursorRow: number;
3333 cursorCol: number;
src/tui/stream.ts+2−6
@@ -9,11 +9,6 @@ export interface BodyLine {
99 bg?: string;
1010 }
1111
12-/** The text after the last newline: what is still incomplete. */
13-function tail(text: string): string {
14- return text.slice(text.lastIndexOf("\n") + 1);
15-}
16-
1712 /**
1813 * A text stream projected onto display lines. `feed` and `flush` return the
1914 * lines that became final; `pending` returns what is still in flight.
@@ -127,7 +122,8 @@ export class TailStream implements StreamRenderer {
127122 private rest = "";
128123
129124 feed(delta: string): BodyLine[] {
130- this.rest = tail(this.rest + delta);
125+ const text = this.rest + delta;
126+ this.rest = text.slice(text.lastIndexOf("\n") + 1);
131127 return [];
132128 }
133129
src/tui/term.ts+16−25
@@ -1,7 +1,6 @@
11 const COMBINING = /\p{M}/u;
22
33 function charWidth(code: number): number {
4- if (code === 0) return 0;
54 if (code < 32 || (code >= 0x7f && code < 0xa0)) return 0;
65 if (code === 0x200b || code === 0x200c || code === 0x200d || code === 0xfeff) return 0;
76 if (code >= 0xfe00 && code <= 0xfe0f) return 0;
@@ -210,20 +209,15 @@ function lookup(code: number, mods: number): Key | null {
210209 return KEYS[`${code}:${mods}`] ?? null;
211210 }
212211
213-/** A legacy control byte, as the chord the same key arrives as elsewhere. */
214-function controlChord(code: number): Chord {
215- if (code === 0x08) return { code: CODE.backspace, mods: 0 };
216- if (code === 0x09) return { code: CODE.tab, mods: 0 };
217- if (code === 0x0d) return { code: CODE.enter, mods: 0 };
218- return { code: code + 0x60, mods: CTRL };
219-}
220-
221212 /** Control bytes are never text: they resolve through the table or vanish. */
222213 function mapPoint(code: number): Key | null {
223214 if (code === 0x7f) return lookup(CODE.backspace, 0);
224215 if (code < 0x20) {
225- const { code: point, mods } = controlChord(code);
226- return lookup(point, mods);
216+ // A legacy control byte, as the chord the same key arrives as elsewhere.
217+ if (code === 0x08) return lookup(CODE.backspace, 0);
218+ if (code === 0x09) return lookup(CODE.tab, 0);
219+ if (code === 0x0d) return lookup(CODE.enter, 0);
220+ return lookup(code + 0x60, CTRL);
227221 }
228222 return { type: "text", text: String.fromCodePoint(code) };
229223 }
@@ -253,12 +247,15 @@ function normalizePaste(text: string): string {
253247 return text.replace(/\r\n?/g, "\n");
254248 }
255249
256-export class KeyParser {
250+class KeyParser {
257251 private buffer = "";
258252 private pasting = false;
259253
260- pendingEscape(): boolean {
261- return !this.pasting && this.buffer === "\x1b";
254+ /** What the buffer may still complete: a lone ESC, a partial sequence, or nothing. */
255+ pending(): "escape" | "sequence" | null {
256+ if (this.pasting) return null;
257+ if (this.buffer === "\x1b") return "escape";
258+ return this.buffer.length > 1 ? "sequence" : null;
262259 }
263260
264261 flushEscape(): Key[] {
@@ -267,11 +264,6 @@ export class KeyParser {
267264 return [{ type: "escape" }];
268265 }
269266
270- /** True while the buffer holds a sequence that may still complete. */
271- pendingSequence(): boolean {
272- return !this.pasting && this.buffer.length > 1;
273- }
274-
275267 flushSequence(): void {
276268 this.buffer = "";
277269 }
@@ -363,7 +355,7 @@ export class KeyParser {
363355 }
364356 }
365357
366-export interface TerminalHandlers {
358+interface TerminalHandlers {
367359 onKey: (key: Key) => void;
368360 onResize: () => void;
369361 }
@@ -426,12 +418,13 @@ export class Terminal {
426418 // incomplete sequence never wedges the buffer.
427419 this.clearTimers();
428420 for (const key of this.parser.feed(chunk)) this.handlers.onKey(key);
429- if (this.parser.pendingEscape()) {
421+ const pending = this.parser.pending();
422+ if (pending === "escape") {
430423 this.escapeTimer = setTimeout(() => {
431424 this.escapeTimer = undefined;
432425 for (const key of this.parser.flushEscape()) this.handlers.onKey(key);
433426 }, 30);
434- } else if (this.parser.pendingSequence()) {
427+ } else if (pending === "sequence") {
435428 this.sequenceTimer = setTimeout(() => {
436429 this.sequenceTimer = undefined;
437430 this.parser.flushSequence();
@@ -439,7 +432,5 @@ export class Terminal {
439432 }
440433 };
441434
442- private onResize = (): void => {
443- this.handlers.onResize();
444- };
435+ private onResize = (): void => this.handlers.onResize();
445436 }
src/tui/theme.ts+5−18
@@ -1,38 +1,25 @@
11 /**
2- * The one palette: TokyoNight `night`, transcribed from `folke/tokyonight.nvim`
3- * (`lua/tokyonight/colors/night.lua` and its generated highlight groups). Every
4- * colour the TUI writes comes from here, foreground and background alike, so no
5- * row can fall back to the terminal's own colours. Truecolor only.
2+ * The one palette: the TokyoNight `night` slots the TUI uses, from
3+ * `folke/tokyonight.nvim` (`lua/tokyonight/colors/night.lua` and its generated
4+ * highlight groups). Every colour the TUI writes comes from here, foreground and
5+ * background alike, so no row can fall back to the terminal's own colours.
6+ * Truecolor only.
67 */
78 export const PALETTE = {
89 bg: "#1a1b26",
9- bg_dark: "#16161e",
10- bg_dark1: "#0c0e14",
11- bg_highlight: "#292e42",
1210 fg: "#c0caf5",
1311 fg_dark: "#a9b1d6",
14- fg_gutter: "#3b4261",
1512 comment: "#565f89",
16- dark3: "#545c7e",
17- dark5: "#737aa2",
1813 terminal_black: "#414868",
1914 blue: "#7aa2f7",
20- blue0: "#3d59a1",
2115 blue1: "#2ac3de",
22- blue2: "#0db9d7",
2316 blue5: "#89ddff",
24- blue6: "#b4f9f8",
25- blue7: "#394b70",
26- cyan: "#7dcfff",
2717 green: "#9ece6a",
2818 green1: "#73daca",
29- green2: "#41a6b5",
3019 magenta: "#bb9af7",
31- magenta2: "#ff007c",
3220 orange: "#ff9e64",
3321 purple: "#9d7cd8",
3422 red: "#f7768e",
35- red1: "#db4b4b",
3623 teal: "#1abc9c",
3724 yellow: "#e0af68",
3825 } as const;
src/tui/tui.ts+9−25
@@ -29,8 +29,7 @@ const EDIT_HEADER = /^(Index: |={3,}$|--- |\+\+\+ )/;
2929
3030 function callSummary(name: string, args: JsonObject): string {
3131 if (name === "bash" && typeof args.command === "string") return args.command.replace(/\s*\n\s*/g, " ");
32- if (name === "edit" && typeof args.path === "string") return args.path;
33- if (name === "read" && typeof args.path === "string") return args.path;
32+ if ((name === "edit" || name === "read") && typeof args.path === "string") return args.path;
3433 return JSON.stringify(args);
3534 }
3635
@@ -187,7 +186,6 @@ class Tui {
187186 private steeringResolve: ((text: string) => void) | null = null;
188187 private abort: AbortController | null = null;
189188 private renderScheduled = false;
190- private reanchor = false;
191189 private closed = false;
192190
193191 // Scrollback: lines accumulate here and are written above the live region.
@@ -209,7 +207,10 @@ class Tui {
209207 this.opts = opts;
210208 this.term = new Terminal({
211209 onKey: (key) => this.handleKey(key),
212- onResize: () => this.handleResize(),
210+ // A reflow moves the region but leaves the cursor on the line it was on,
211+ // so the region's top is still `cursorUp` rows above it. Redraw over the
212+ // old region instead of dropping the anchor, which would leave it behind.
213+ onResize: () => this.render(),
213214 });
214215 this.done = new Promise((resolve) => {
215216 this.resolveExit = resolve;
@@ -226,16 +227,7 @@ class Tui {
226227 this.render();
227228 }
228229
229- private onSignal = (): void => {
230- this.exit();
231- };
232-
233- private handleResize(): void {
234- // A reflow moves the region but leaves the cursor on the line it was on, so
235- // the region's top is still `cursorUp` rows above it. Redraw over the old
236- // region instead of dropping the anchor, which would leave it behind.
237- this.render();
238- }
230+ private onSignal = (): void => this.exit();
239231
240232 private handleKey(key: Key): void {
241233 if (key.type === "eof") {
@@ -314,15 +306,9 @@ class Tui {
314306 private async runTurn(): Promise<void> {
315307 try {
316308 await runAgentTurn({
317- models: this.opts.models,
318- model: this.opts.model,
319- systemPrompt: this.opts.systemPrompt,
320- tools: this.opts.tools,
321- toolNames: this.opts.toolNames,
309+ ...this.opts,
322310 messages: this.messages,
323- session: this.opts.session,
324311 signal: this.abort!.signal,
325- thinkingEffort: this.opts.thinkingEffort,
326312 interaction: {
327313 isPauseRequested: () => this.pauseRequested,
328314 clearPause: () => {
@@ -563,12 +549,10 @@ class Tui {
563549 // terminal; the re-anchor newline goes after the scrollback, not before the
564550 // erase, because `clear()` measures from the previous frame's cursor and
565551 // moving the cursor down first lands the erase one row below the region.
566- if (this.scroll !== "" && this.live.height >= this.term.height - 1) this.reanchor = true;
567552 const scroll = this.scroll;
568553 this.scroll = "";
569- const prefix = this.reanchor ? "\r\n" : "";
570- this.reanchor = false;
571- this.term.write(this.live.draw(lines, cursorRow, editor.cursorCol, scroll + prefix));
554+ const reanchor = scroll !== "" && this.live.height >= this.term.height - 1;
555+ this.term.write(this.live.draw(lines, cursorRow, editor.cursorCol, scroll + (reanchor ? "\r\n" : "")));
572556 }
573557
574558 private exit(): void {
src/tui/usage.ts+5−11
@@ -1,4 +1,4 @@
1-import type { Api, AssistantMessage, ImageContent, Message, Model, TextContent, Tool } from "@earendil-works/pi-ai";
1+import type { Api, AssistantMessage, Message, Model, Tool } from "@earendil-works/pi-ai";
22 import { dim, red, yellow } from "./styles.ts";
33
44 /** ~1 token per 4 characters, the heuristic pi-ai uses. */
@@ -6,18 +6,12 @@ function estimateText(text: string): number {
66 return Math.ceil(text.length / 4);
77 }
88
9-function contentChars(content: string | Array<TextContent | ImageContent>): number {
10- if (typeof content === "string") return content.length;
11- let chars = 0;
12- for (const block of content) if (block.type === "text") chars += block.text.length;
13- return chars;
14-}
15-
169 /** Characters one message contributes. Image and thinking blocks are ignored: an undercount. */
1710 function messageChars(message: Message): number {
18- if (message.role !== "assistant") return contentChars(message.content);
11+ const content = message.content;
12+ if (typeof content === "string") return content.length;
1913 let chars = 0;
20- for (const block of message.content) {
14+ for (const block of content) {
2115 if (block.type === "text") chars += block.text.length;
2216 else if (block.type === "toolCall") chars += block.name.length + JSON.stringify(block.arguments).length;
2317 }
@@ -53,7 +47,7 @@ export function estimateContextTokens(messages: Message[], systemPrompt: string,
5347 }
5448
5549 /** `812`, `12.3k`, `1.24M` — trailing zeros trimmed. */
56-export function formatTokens(n: number): string {
50+function formatTokens(n: number): string {
5751 if (n < 1000) return String(n);
5852 const scaled = n < 1_000_000 ? n / 1000 : n / 1_000_000;
5953 const unit = n < 1_000_000 ? "k" : "M";