xonecas.io
64875
Mc

mini-coder / commit 1ae754c

chore: drop dead code and collapse duplicated plumbing

- one AgentOptions for the TUI, --print and AgentRun, instead of three
  copies of the same eight fields
- one endTurn() for the three terminal agent events
- one resolveSteering() for the four copies of steering resolution
- executeTool: its try/catch was unreachable, agent.ts already catches
- messageChars: three identical branches for the non-assistant roles
- remove MessageRecord, ResolvedModel, the ToolContext re-export, the
  session record exports, and timestamp()'s unused width

xonecas2026-09-23 1ae754c011f827d7b30c414fd8baf3664785dbd1 parent a23c8d8

7 files changed

src/agent.ts+7−3
@@ -41,17 +41,21 @@ export const NO_INTERACTION: Interaction = {
4141 requestSteering: async () => "",
4242 };
4343
44-export interface AgentRun {
44+/** What one turn needs, shared by both projections: the TUI and `--print`. */
45+export interface AgentOptions {
4546 models: Models;
4647 model: Model<Api>;
4748 systemPrompt: string;
4849 tools: Tool[];
4950 toolNames: ToolName[];
50- messages: Message[];
51+ thinkingEffort: ThinkingLevel;
5152 session: Session;
53+}
54+
55+export interface AgentRun extends AgentOptions {
56+ messages: Message[];
5257 signal: AbortSignal;
5358 interaction: Interaction;
54- thinkingEffort: ThinkingLevel;
5559 onEvent: (event: AgentEvent) => void;
5660 }
5761
src/cli.ts+5−24
@@ -1,31 +1,12 @@
11 import process from "node:process";
2-import type {
3- Api,
4- AssistantMessage,
5- Message,
6- Model,
7- Models,
8- ThinkingLevel,
9- Tool,
10- UserMessage,
11-} from "@earendil-works/pi-ai";
12-import { loadConfig, resolveModel, type ToolName } from "./config.ts";
2+import type { AssistantMessage, Message, UserMessage } from "@earendil-works/pi-ai";
3+import { loadConfig, resolveModel } from "./config.ts";
134 import { buildSystemPrompt } from "./prompt.ts";
145 import { acceptsImages, toolSchemas } from "./tools/index.ts";
156 import { Session } from "./session.ts";
16-import { NO_INTERACTION, runAgentTurn } from "./agent.ts";
7+import { NO_INTERACTION, runAgentTurn, type AgentOptions } from "./agent.ts";
178 import { runTui } from "./tui/tui.ts";
189
19-interface RunContext {
20- models: Models;
21- model: Model<Api>;
22- systemPrompt: string;
23- tools: Tool[];
24- toolNames: ToolName[];
25- thinkingEffort: ThinkingLevel;
26- session: Session;
27-}
28-
2910 function parseArgs(argv: string[]): { print: string | null } {
3011 let print: string | null = null;
3112 for (let i = 0; i < argv.length; i++) {
@@ -45,7 +26,7 @@ function parseArgs(argv: string[]): { print: string | null } {
4526 return { print };
4627 }
4728
48-async function runPrint(prompt: string, ctx: RunContext): Promise<number> {
29+async function runPrint(prompt: string, ctx: AgentOptions): Promise<number> {
4930 const messages: Message[] = [];
5031 const user: UserMessage = { role: "user", content: prompt, timestamp: Date.now() };
5132 messages.push(user);
@@ -101,7 +82,7 @@ async function main(): Promise<void> {
10182 const config = loadConfig();
10283 const { models, model } = resolveModel(config);
10384 const session = new Session(config.sessionsDir, process.cwd());
104- const ctx: RunContext = {
85+ const ctx: AgentOptions = {
10586 models,
10687 model,
10788 systemPrompt: buildSystemPrompt(config),
src/config.ts+1−6
@@ -105,12 +105,7 @@ const API_FACTORY: Record<CustomApi, () => ReturnType<typeof openAICompletionsAp
105105 "google-generative-ai": googleGenerativeAIApi,
106106 };
107107
108-export interface ResolvedModel {
109- models: MutableModels;
110- model: Model<Api>;
111-}
112-
113-export function resolveModel(config: Config): ResolvedModel {
108+export function resolveModel(config: Config): { models: MutableModels; model: Model<Api> } {
114109 const models = builtinModels();
115110 for (const provider of config.customProviders) {
116111 models.setProvider(
src/session.ts+5−5
@@ -9,7 +9,7 @@ import { randomBytes } from "node:crypto";
99 import { join } from "node:path";
1010 import type { Message, Tool } from "@earendil-works/pi-ai";
1111
12-export interface SessionHeader {
12+interface SessionHeader {
1313 type: "session";
1414 version: 1;
1515 id: string;
@@ -18,7 +18,7 @@ export interface SessionHeader {
1818 title: string;
1919 }
2020
21-export interface RequestRecord {
21+interface RequestRecord {
2222 type: "request";
2323 at: string;
2424 provider: string;
@@ -29,13 +29,13 @@ export interface RequestRecord {
2929 tools: Tool[];
3030 }
3131
32-export interface MessageRecord {
32+interface MessageRecord {
3333 type: "message";
3434 at: string;
3535 message: Message;
3636 }
3737
38-export type SessionRecord = SessionHeader | RequestRecord | MessageRecord;
38+type SessionRecord = SessionHeader | RequestRecord | MessageRecord;
3939
4040 function slugify(text: string): string {
4141 const slug = text
@@ -57,7 +57,7 @@ function shortId(): string {
5757 }
5858
5959 function timestamp(date: Date): string {
60- const p = (n: number, width = 2) => String(n).padStart(width, "0");
60+ const p = (n: number) => String(n).padStart(2, "0");
6161 return (
6262 `${date.getUTCFullYear()}${p(date.getUTCMonth() + 1)}${p(date.getUTCDate())}` +
6363 `-${p(date.getUTCHours())}${p(date.getUTCMinutes())}${p(date.getUTCSeconds())}`
src/tools/index.ts+5−9
@@ -5,7 +5,7 @@ import { BASH_PARAMS, bash } from "./bash.ts";
55 import { EDIT_PARAMS, edit } from "./edit.ts";
66 import { READ_PARAMS, read } from "./read.ts";
77
8-export type { ToolContext, ToolDetails, ToolResult } from "./common.ts";
8+export type { ToolDetails, ToolResult } from "./common.ts";
99
1010 /** Whether a model accepts image input. Drives `read`'s description and results. */
1111 export function acceptsImages(model: Model<Api>): boolean {
@@ -40,12 +40,8 @@ export function toolSchemas(names: ToolName[], withImages: boolean): Tool[] {
4040 return names.map((name) => tools[name]);
4141 }
4242
43-export function executeTool(name: ToolName, call: ToolCall, ctx: ToolContext): Promise<ToolResult> {
44- try {
45- if (name === "edit") return Promise.resolve(edit(parseArgs(EDIT_PARAMS, call.arguments), ctx.signal));
46- if (name === "read") return Promise.resolve(read(parseArgs(READ_PARAMS, call.arguments), ctx));
47- return bash(parseArgs(BASH_PARAMS, call.arguments), ctx);
48- } catch (error) {
49- return Promise.resolve({ text: (error as Error).message, isError: true });
50- }
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);
46+ return bash(parseArgs(BASH_PARAMS, call.arguments), ctx);
5147 }
src/tui/tui.ts+28−65
@@ -1,34 +1,12 @@
11 import process from "node:process";
2-import type {
3- Api,
4- AssistantMessage,
5- JsonObject,
6- Message,
7- Model,
8- Models,
9- ThinkingLevel,
10- Tool,
11- UserMessage,
12-} from "@earendil-works/pi-ai";
13-import { runAgentTurn, type AgentEvent, type Phase } from "../agent.ts";
14-import type { Session } from "../session.ts";
15-import type { ToolName } from "../config.ts";
2+import type { AssistantMessage, JsonObject, Message, UserMessage } from "@earendil-works/pi-ai";
3+import { runAgentTurn, type AgentEvent, type AgentOptions, type Phase } from "../agent.ts";
164 import { Terminal, expandTabs, wrapLine, type Key } from "./term.ts";
175 import { Editor } from "./editor.ts";
186 import { MarkdownStream, TailStream, type BodyLine, type StreamRenderer } from "./stream.ts";
197 import { cyan, dim, green, red } from "./styles.ts";
208 import { contextUsageLine, estimateContextTokens } from "./usage.ts";
219
22-export interface TuiOptions {
23- models: Models;
24- model: Model<Api>;
25- systemPrompt: string;
26- tools: Tool[];
27- toolNames: ToolName[];
28- thinkingEffort: ThinkingLevel;
29- session: Session;
30-}
31-
3210 /** Status-row spinner frames; the only animation in the TUI. */
3311 const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
3412 const SPINNER_MS = 120;
@@ -158,7 +136,7 @@ class LiveRegion {
158136 }
159137
160138 class Tui {
161- private readonly opts: TuiOptions;
139+ private readonly opts: AgentOptions;
162140 private readonly term: Terminal;
163141 private readonly editor = new Editor();
164142 private readonly live = new LiveRegion();
@@ -192,7 +170,7 @@ class Tui {
192170 private frame = 0;
193171 private spinner: NodeJS.Timeout | undefined;
194172
195- constructor(opts: TuiOptions) {
173+ constructor(opts: AgentOptions) {
196174 this.opts = opts;
197175 this.term = new Terminal({
198176 onKey: (key) => this.handleKey(key),
@@ -258,13 +236,10 @@ class Tui {
258236 private submit(): void {
259237 const text = this.editor.text();
260238 if (this.active) {
261- if (this.paused && this.steeringResolve) {
239+ if (this.paused && this.steeringResolve !== null) {
262240 this.editor.clear();
263241 if (text.length > 0) this.commitUser(text);
264- const resolve = this.steeringResolve;
265- this.steeringResolve = null;
266- this.paused = false;
267- resolve(text);
242+ this.resolveSteering(text);
268243 }
269244 return;
270245 }
@@ -312,11 +287,7 @@ class Tui {
312287 requestSteering: () =>
313288 new Promise<string>((resolve) => {
314289 this.paused = true;
315- this.steeringResolve = (text) => {
316- this.paused = false;
317- this.steeringResolve = null;
318- resolve(text);
319- };
290+ this.steeringResolve = resolve;
320291 this.render();
321292 }),
322293 },
@@ -329,11 +300,7 @@ class Tui {
329300 this.active = false;
330301 this.abort = null;
331302 this.pauseRequested = false;
332- if (this.steeringResolve) {
333- const resolve = this.steeringResolve;
334- this.steeringResolve = null;
335- resolve("");
336- }
303+ this.resolveSteering("");
337304 this.paused = false;
338305 if (this.spinner) clearInterval(this.spinner);
339306 this.spinner = undefined;
@@ -342,16 +309,20 @@ class Tui {
342309 }
343310
344311 private cancel(): void {
345- if (this.steeringResolve) {
346- const resolve = this.steeringResolve;
347- this.steeringResolve = null;
348- this.paused = false;
349- resolve("");
350- }
312+ this.resolveSteering("");
351313 this.abort?.abort();
352314 this.render();
353315 }
354316
317+ /** Answers a pending steering prompt; "" leaves the turn ending. */
318+ private resolveSteering(text: string): void {
319+ const resolve = this.steeringResolve;
320+ if (resolve === null) return;
321+ this.steeringResolve = null;
322+ this.paused = false;
323+ resolve(text);
324+ }
325+
355326 private handleAgentEvent(event: AgentEvent): void {
356327 if (this.closed) return;
357328 switch (event.type) {
@@ -387,36 +358,28 @@ class Tui {
387358 this.commitToolResult(event.name, event.text, event.isError);
388359 break;
389360 case "error":
390- this.finishTurn();
391- this.commitLines(this.reply.flush());
392- this.flushCalls();
393- this.separator = true;
394- this.push(`! ${event.message}`);
361+ this.endTurn(`! ${event.message}`);
395362 break;
396363 case "cancelled":
397- this.finishTurn();
398- this.commitLines(this.reply.flush());
399- this.flushCalls();
400- this.separator = true;
401- this.push("! cancelled");
364+ this.endTurn("! cancelled");
402365 break;
403366 case "complete":
404- this.finishTurn();
405- this.commitLines(this.reply.flush());
406- this.flushCalls();
407- this.separator = true;
408- this.push(dim(`[complete · ${this.elapsed()}s]`));
367+ this.endTurn(dim(`[complete · ${this.elapsed()}s]`));
409368 break;
410369 }
411370 this.render();
412371 }
413372
414- /** Terminal states clear the status row and any in-flight preview. */
415- private finishTurn(): void {
373+ /** A terminal state: clears the status row and any in-flight preview, then commits. */
374+ private endTurn(line: string): void {
416375 this.phase = "idle";
417376 this.detail = undefined;
418377 this.paused = false;
419378 this.activity.reset();
379+ this.commitLines(this.reply.flush());
380+ this.flushCalls();
381+ this.separator = true;
382+ this.push(line);
420383 }
421384
422385 private elapsed(): number {
@@ -578,7 +541,7 @@ class Tui {
578541 }
579542 }
580543
581-export async function runTui(opts: TuiOptions): Promise<void> {
544+export async function runTui(opts: AgentOptions): Promise<void> {
582545 const tui = new Tui(opts);
583546 tui.start();
584547 return tui.done;
src/tui/usage.ts+1−3
@@ -15,9 +15,7 @@ function contentChars(content: string | Array<TextContent | ImageContent>): numb
1515
1616 /** Characters one message contributes. Image and thinking blocks are ignored: an undercount. */
1717 function messageChars(message: Message): number {
18- if (message.role === "system") return contentChars(message.content);
19- if (message.role === "user") return contentChars(message.content);
20- if (message.role === "toolResult") return contentChars(message.content);
18+ if (message.role !== "assistant") return contentChars(message.content);
2119 let chars = 0;
2220 for (const block of message.content) {
2321 if (block.type === "text") chars += block.text.length;