xonecas.io
64875
Mc

mini-coder / commit cedf815

chore: another garneding pass, this time after commands were added.

xonecas2026-09-26 cedf8158714c1b493c7101790b6acad97453e271 parent 653abfc

11 files changed

src/agent.ts+11−24
@@ -10,10 +10,11 @@ import {
1010 type ToolCall,
1111 type ToolResultMessage,
1212 type UserMessage,
13+ validateToolCall,
1314 } from "@earendil-works/pi-ai";
1415 import type { Session } from "./session.ts";
1516 import type { ToolName } from "./config.ts";
16-import { acceptsImages, executeTool, type ToolDetails, type ToolResult } from "./tools/index.ts";
17+import { acceptsImages, executeTool, type ToolResult } from "./tools/index.ts";
1718
1819 export type Phase = "preparing" | "waitingModel" | "streaming" | "runningTool" | "pausing" | "idle";
1920
@@ -61,14 +62,6 @@ interface AgentRun extends AgentOptions {
6162 onEvent: (event: AgentEvent) => void;
6263 }
6364
64-/** The concatenated text blocks of an assistant message, ignoring the rest. */
65-export function assistantText(message: AssistantMessage): string {
66- return message.content
67- .filter((block) => block.type === "text")
68- .map((block) => block.text)
69- .join("");
70-}
71-
7265 export async function runAgentTurn(run: AgentRun): Promise<void> {
7366 const { messages, session, signal, interaction, onEvent } = run;
7467
@@ -189,28 +182,22 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
189182 if (steering !== "") held.push(steering);
190183 onEvent({ type: "phase", phase: "runningTool", detail: call.name });
191184
192- const tool = run.tools.find((candidate) => candidate.name === call.name);
193185 let result: ToolResult;
194- if (tool === undefined) {
195- result = { text: `unknown tool: ${call.name}`, isError: true };
196- } else {
197- try {
198- result = await executeTool(call, {
199- signal,
200- supportsImages: acceptsImages(run.model),
201- onOutput: (chunk) => onEvent({ type: "toolOutput", chunk }),
202- });
203- } catch (error) {
204- result = { text: (error as Error).message, isError: true };
205- }
186+ try {
187+ result = await executeTool(call.name, validateToolCall(run.tools, call), {
188+ signal,
189+ supportsImages: acceptsImages(run.model),
190+ onOutput: (chunk) => onEvent({ type: "toolOutput", chunk }),
191+ });
192+ } catch (error) {
193+ result = { text: (error as Error).message, isError: true };
206194 }
207195
208- const toolMessage: ToolResultMessage<ToolDetails> = {
196+ const toolMessage: ToolResultMessage = {
209197 role: "toolResult",
210198 toolCallId: call.id,
211199 toolName: call.name,
212200 content: [{ type: "text", text: result.text }, ...(result.images ?? [])],
213- details: result.details,
214201 isError: result.isError,
215202 timestamp: Date.now(),
216203 };
src/cli.ts+3−3
@@ -1,10 +1,10 @@
11 import process from "node:process";
2-import { clampThinkingLevel, type AssistantMessage, type Message, type UserMessage } from "@earendil-works/pi-ai";
2+import { clampThinkingLevel, contentText, type AssistantMessage, type Message, type UserMessage } from "@earendil-works/pi-ai";
33 import { loadConfig, resolveModel } from "./config.ts";
44 import { buildSystemPrompt } from "./prompt.ts";
55 import { acceptsImages, toolSchemas } from "./tools/index.ts";
66 import { Session } from "./session.ts";
7-import { NO_INTERACTION, assistantText, runAgentTurn, type AgentOptions } from "./agent.ts";
7+import { NO_INTERACTION, runAgentTurn, type AgentOptions } from "./agent.ts";
88 import { runTui } from "./tui/tui.ts";
99
1010 function parseArgs(argv: string[]): { print: string | null } {
@@ -61,7 +61,7 @@ async function runPrint(prompt: string, ctx: AgentOptions): Promise<number> {
6161
6262 const last = messages.filter((message): message is AssistantMessage => message.role === "assistant").at(-1);
6363 if (!failed && !cancelled && last !== undefined) {
64- const text = assistantText(last);
64+ const text = contentText(last.content, "");
6565 if (text !== "") process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
6666 }
6767 return failed || cancelled ? 1 : 0;
src/session.ts+2−5
@@ -7,7 +7,7 @@ import {
77 } from "node:fs";
88 import { randomBytes } from "node:crypto";
99 import { join } from "node:path";
10-import type { Message, Tool } from "@earendil-works/pi-ai";
10+import { contentText, type Message, type Tool } from "@earendil-works/pi-ai";
1111
1212 interface SessionHeader {
1313 type: "session";
@@ -66,10 +66,7 @@ function timestamp(date: Date): string {
6666
6767 function titleFor(message: Message): string {
6868 if (message.role !== "user") return "session";
69- const text = typeof message.content === "string"
70- ? message.content
71- : message.content.map((block) => (block.type === "text" ? block.text : "")).join(" ");
72- return slugify(text);
69+ return slugify(contentText(message.content, " "));
7370 }
7471
7572 export class Session {
src/tools/bash.ts+4−11
@@ -6,7 +6,7 @@ export const BASH_PARAMS = Type.Object(
66 { command: Type.String({ description: "Command to run" }) },
77 { additionalProperties: false },
88 );
9-type BashArgs = Static<typeof BASH_PARAMS>;
9+export type BashArgs = Static<typeof BASH_PARAMS>;
1010
1111 const MAX_HEAD = 10_000;
1212 const MAX_TAIL = 6_000;
@@ -22,7 +22,7 @@ export function bash(args: BashArgs, ctx: ToolContext): Promise<ToolResult> {
2222
2323 let head = "";
2424 let tail = "";
25- let omitted = 0;
25+ let truncated = false;
2626 const append = (chunk: Buffer) => {
2727 let text = chunk.toString();
2828 ctx.onOutput?.(text);
@@ -34,7 +34,7 @@ export function bash(args: BashArgs, ctx: ToolContext): Promise<ToolResult> {
3434 if (text === "") return;
3535 tail += text;
3636 if (tail.length > MAX_TAIL) {
37- omitted += tail.length - MAX_TAIL;
37+ truncated = true;
3838 tail = tail.slice(tail.length - MAX_TAIL);
3939 }
4040 };
@@ -48,16 +48,9 @@ export function bash(args: BashArgs, ctx: ToolContext): Promise<ToolResult> {
4848 ctx.signal.removeEventListener("abort", onAbort);
4949 clearTimeout(killTimer);
5050 const exit = code ?? (ctx.signal.aborted ? "aborted" : "unknown");
51- const truncated = omitted > 0;
5251 const body = truncated ? head + TRUNCATED + tail : head + tail;
5352 const text = body + (body.endsWith("\n") || body === "" ? "" : "\n") + `exit code: ${exit}`;
54- resolve({
55- text,
56- isError: code !== 0,
57- details: truncated
58- ? { truncated: true, omittedChars: omitted, totalChars: head.length + tail.length + omitted }
59- : undefined,
60- });
53+ resolve({ text, isError: code !== 0 });
6154 };
6255
6356 let killTimer: NodeJS.Timeout | undefined;
src/tools/common.ts+1−18
@@ -1,5 +1,4 @@
1-import type { ImageContent, Static, TSchema } from "@earendil-works/pi-ai";
2-import { Value } from "typebox/value";
1+import type { ImageContent } from "@earendil-works/pi-ai";
32
43 export interface ToolContext {
54 signal: AbortSignal;
@@ -8,25 +7,9 @@ export interface ToolContext {
87 onOutput?: (chunk: string) => void;
98 }
109
11-export interface ToolDetails {
12- truncated: boolean;
13- omittedChars: number;
14- totalChars: number;
15-}
16-
1710 export interface ToolResult {
1811 text: string;
1912 isError: boolean;
20- details?: ToolDetails;
2113 /** Image blocks appended to the tool result, after `text`. */
2214 images?: ImageContent[];
2315 }
24-
25-export function parseArgs<T extends TSchema>(schema: T, value: unknown): Static<T> {
26- try {
27- return Value.Parse(schema, value);
28- } catch {
29- const first = [...Value.Errors(schema, value)][0];
30- throw new Error(first ? `${first.instancePath || "/"} ${first.message}` : "invalid arguments");
31- }
32-}
src/tools/edit.ts+1−1
@@ -11,7 +11,7 @@ export const EDIT_PARAMS = Type.Object(
1111 },
1212 { additionalProperties: false },
1313 );
14-type EditArgs = Static<typeof EDIT_PARAMS>;
14+export 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+10−10
@@ -1,11 +1,11 @@
1-import type { Api, Model, Tool, ToolCall } from "@earendil-works/pi-ai";
1+import type { Api, Model, Tool } from "@earendil-works/pi-ai";
22 import type { ToolName } from "../config.ts";
3-import { parseArgs, type ToolContext, type ToolResult } from "./common.ts";
4-import { BASH_PARAMS, bash } from "./bash.ts";
5-import { EDIT_PARAMS, edit } from "./edit.ts";
6-import { READ_PARAMS, read } from "./read.ts";
3+import type { ToolContext, ToolResult } from "./common.ts";
4+import { BASH_PARAMS, bash, type BashArgs } from "./bash.ts";
5+import { EDIT_PARAMS, edit, type EditArgs } from "./edit.ts";
6+import { READ_PARAMS, read, type ReadArgs } from "./read.ts";
77
8-export type { ToolDetails, ToolResult } from "./common.ts";
8+export type { 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,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(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);
46- return bash(parseArgs(BASH_PARAMS, call.arguments), ctx);
43+export async function executeTool(name: string, args: unknown, ctx: ToolContext): Promise<ToolResult> {
44+ if (name === "edit") return edit(args as EditArgs, ctx.signal);
45+ if (name === "read") return read(args as ReadArgs, ctx);
46+ return bash(args as BashArgs, 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-type ReadArgs = Static<typeof READ_PARAMS>;
10+export type ReadArgs = Static<typeof READ_PARAMS>;
1111
1212 const IMAGE_MIME: Record<string, string> = {
1313 png: "image/png",
src/tui/commands.ts+17−23
@@ -114,6 +114,21 @@ const login: Command = {
114114 },
115115 };
116116
117+/** Prompts for one of `models`, persists the choice, and switches to it. */
118+async function chooseModel(ctx: CommandContext, providerId: string, models: readonly Model<Api>[]): Promise<void> {
119+ if (models.length === 0) throw new Error(`no models for provider "${providerId}"`);
120+ const name = ctx.models.getProvider(providerId)?.name ?? providerId;
121+ const modelId = await ctx.prompt({
122+ type: "select",
123+ message: `Select a model for ${name}`,
124+ options: models.map((m) => ({ id: m.id, label: m.name ?? m.id })),
125+ });
126+ const chosen = models.find((m) => m.id === modelId);
127+ if (chosen === undefined) throw new Error(`unknown model: ${modelId}`);
128+ saveConfig({ provider: providerId, model: modelId });
129+ ctx.select(chosen);
130+}
131+
117132 const provider: Command = {
118133 name: "provider",
119134 description: "choose the provider and model",
@@ -126,18 +141,7 @@ const provider: Command = {
126141 message: "Select a provider",
127142 options: ids.map((id) => ({ id, label: ctx.models.getProvider(id)?.name ?? id })),
128143 });
129- const models = available.filter((m) => m.provider === providerId);
130- if (models.length === 0) throw new Error(`no models for provider "${providerId}"`);
131- const name = ctx.models.getProvider(providerId)?.name ?? providerId;
132- const modelId = await ctx.prompt({
133- type: "select",
134- message: `Select a model for ${name}`,
135- options: models.map((m) => ({ id: m.id, label: m.name ?? m.id })),
136- });
137- const chosen = models.find((m) => m.id === modelId);
138- if (chosen === undefined) throw new Error(`unknown model: ${modelId}`);
139- saveConfig({ provider: providerId, model: modelId });
140- ctx.select(chosen);
144+ await chooseModel(ctx, providerId, available.filter((m) => m.provider === providerId));
141145 },
142146 };
143147
@@ -162,17 +166,7 @@ const model: Command = {
162166 async run(ctx): Promise<void> {
163167 const providerId = ctx.model.provider;
164168 const models = await ctx.models.getAvailable(providerId, { signal: ctx.signal });
165- if (models.length === 0) throw new Error(`no models for provider "${providerId}"`);
166- const name = ctx.models.getProvider(providerId)?.name ?? providerId;
167- const modelId = await ctx.prompt({
168- type: "select",
169- message: `Select a model for ${name}`,
170- options: models.map((m) => ({ id: m.id, label: m.name ?? m.id })),
171- });
172- const chosen = models.find((m) => m.id === modelId);
173- if (chosen === undefined) throw new Error(`unknown model: ${modelId}`);
174- saveConfig({ provider: providerId, model: modelId });
175- ctx.select(chosen);
169+ await chooseModel(ctx, providerId, models);
176170 },
177171 };
178172
src/tui/tui.ts+3−2
@@ -1,6 +1,7 @@
11 import process from "node:process";
22 import {
33 clampThinkingLevel,
4+ contentText,
45 type Api,
56 type AssistantMessage,
67 type AuthEvent,
@@ -11,7 +12,7 @@ import {
1112 type ModelThinkingLevel,
1213 type UserMessage,
1314 } from "@earendil-works/pi-ai";
14-import { assistantText, runAgentTurn, type AgentEvent, type AgentOptions, type Phase } from "../agent.ts";
15+import { runAgentTurn, type AgentEvent, type AgentOptions, type Phase } from "../agent.ts";
1516 import { acceptsImages, toolSchemas } from "../tools/index.ts";
1617 import { Terminal, expandTabs, sanitize, wrapLine, type Key } from "./term.ts";
1718 import { Editor } from "./editor.ts";
@@ -606,7 +607,7 @@ class Tui {
606607 private commitMessage(message: AssistantMessage): void {
607608 this.activity.reset();
608609 this.commitLines(this.reply.flush());
609- const text = assistantText(message);
610+ const text = contentText(message.content, "");
610611 if (text.trim() !== "" && !this.streamed.includes(text)) {
611612 this.commitLines([...this.reply.feed(text.trimEnd()), ...this.reply.flush()]);
612613 }
src/tui/usage.ts+8−40
@@ -1,49 +1,17 @@
1-import type { Api, AssistantMessage, Message, Model, Tool } from "@earendil-works/pi-ai";
1+import type { Api, Message, Model, Tool } from "@earendil-works/pi-ai";
2+import { estimateContextTokens as estimate, estimateTextTokens } from "@earendil-works/pi-ai/utils/estimate";
23 import { dim, red, yellow } from "./styles.ts";
34
4-/** ~1 token per 4 characters, the heuristic pi-ai uses. */
5-function estimateText(text: string): number {
6- return Math.ceil(text.length / 4);
7-}
8-
9-/** Characters one message contributes. Image and thinking blocks are ignored: an undercount. */
10-function messageChars(message: Message): number {
11- const content = message.content;
12- if (typeof content === "string") return content.length;
13- let chars = 0;
14- for (const block of content) {
15- if (block.type === "text") chars += block.text.length;
16- else if (block.type === "toolCall") chars += block.name.length + JSON.stringify(block.arguments).length;
17- }
18- return chars;
19-}
20-
215 /**
226 * Rough token count for the context the next request would send, used only for
23- * display. Anchors on the last provider-reported usage — `totalTokens - output`
24- * is the input side of that request — and estimates the messages at and after
25- * it; without a usable anchor, estimates system prompt, tools and messages.
26- * Anchors with `totalTokens === 0` (aborted or errored) are skipped.
7+ * display. Delegates to `pi-ai`'s estimator, which anchors on the last
8+ * provider-reported usage and estimates the messages after it. Before any usage
9+ * exists there is no anchor, so the system prompt and tools are added explicitly.
2710 */
2811 export function estimateContextTokens(messages: Message[], systemPrompt: string, tools: Tool[]): number {
29- let anchor: AssistantMessage | undefined;
30- let anchorIndex = -1;
31- for (let i = messages.length - 1; i >= 0; i--) {
32- const message = messages[i];
33- if (message.role === "assistant" && message.usage.totalTokens > 0) {
34- anchor = message;
35- anchorIndex = i;
36- break;
37- }
38- }
39- if (anchor !== undefined) {
40- let tail = 0;
41- for (let i = anchorIndex; i < messages.length; i++) tail += messageChars(messages[i]);
42- return anchor.usage.totalTokens - anchor.usage.output + Math.ceil(tail / 4);
43- }
44- let total = estimateText(systemPrompt) + estimateText(JSON.stringify(tools));
45- for (const message of messages) total += Math.ceil(messageChars(message) / 4);
46- return total;
12+ const tokens = estimate(messages);
13+ if (tokens.lastUsageIndex !== null) return tokens.tokens;
14+ return tokens.tokens + estimateTextTokens(systemPrompt) + estimateTextTokens(JSON.stringify(tools));
4715 }
4816
4917 /** `812`, `12.3k`, `1.24M` — trailing zeros trimmed. */