xonecas.io
64875
Mc

mini-coder / commit 2b99259

feat: `edit()` tool is back!

xonecas2026-04-23 2b99259ebc375f60ad42a3aa30ea3ab6142f29c9 parent 6f18835

7 files changed

TODO.md+10−0
@@ -0,0 +1,10 @@
1+# Human's TODO list.
2+
3+> This file is managed by the user, only edit if asked to.
4+
5+- [ ] Use this `https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts#L326`
6+
7+- `src/tui.ts:248` tool timing is still cumulative for later tool calls\*\*
8+ The new duration is computed from `msg.timestamp`, which is set when the tool call is first shown, not when that specific tool
9+ runner starts. Since `streamAgent` executes tool calls serially, the second/third tool in one assistant turn will show a duration
10+ that includes time spent waiting on earlier tools, so the displayed `Took ...` is inaccurate.
src/agent.ts+6−11
@@ -26,15 +26,10 @@ export async function streamAgent(
2626 systemPrompt: string,
2727 messages: Message[],
2828 options: CliOptions,
29- streamFn?: (ev: AssistantMessageEvent, dur: number) => void,
30- toolsFn?: (tool: ToolResultMessage, dur: number) => void,
31- completeFn?: (
32- msg: AssistantMessage,
33- context: Context,
34- duration: number,
35- ) => void,
29+ streamFn?: (ev: AssistantMessageEvent) => void,
30+ toolsFn?: (tool: ToolResultMessage) => void,
31+ completeFn?: (msg: AssistantMessage, context: Context) => void,
3632 ) {
37- const startTs = Date.now();
3833 const context: Context = {
3934 systemPrompt,
4035 messages,
@@ -48,7 +43,7 @@ export async function streamAgent(
4843 });
4944
5045 for await (const ev of s) {
51- streamFn?.(ev, Date.now() - startTs);
46+ streamFn?.(ev);
5247 }
5348
5449 const finalMessage = await s.result();
@@ -69,7 +64,7 @@ export async function streamAgent(
6964 timestamp: Date.now(),
7065 };
7166 context.messages.push(msg);
72- toolsFn?.(msg, Date.now() - startTs);
67+ toolsFn?.(msg);
7368 }
7469
7570 if (toolCalls.length > 0) {
@@ -82,7 +77,7 @@ export async function streamAgent(
8277 }
8378
8479 if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
85- completeFn?.(finalMessage, context, Date.now() - startTs);
80+ completeFn?.(finalMessage, context);
8681 return;
8782 }
8883 }
src/headless.ts+8−3
@@ -2,14 +2,19 @@ import type { Message } from "@mariozechner/pi-ai";
22 import { streamAgent, TASK_PROMPT } from "./agent";
33 import { getApiKey } from "./oauth";
44 import { bash, runBashTool } from "./tool-bash";
5+import { edit, runEditTool } from "./tool-edit";
56 import type { CliOptions, ToolAndRunner } from "./types";
67
78 export async function streamHeadless(
89 options: CliOptions,
910 leave: (s: string) => void,
1011 ) {
12+ const lastTs = Date.now();
1113 const apiKey = await getApiKey(options);
12- const tools: ToolAndRunner[] = [{ tool: bash, runner: runBashTool }];
14+ const tools: ToolAndRunner[] = [
15+ { tool: bash, runner: runBashTool },
16+ { tool: edit, runner: runEditTool },
17+ ];
1318 const messages: Message[] = [
1419 { role: "user", content: options.prompt || "", timestamp: Date.now() },
1520 ];
@@ -45,7 +50,7 @@ export async function streamHeadless(
4550 }
4651 },
4752 undefined,
48- (msg, _, dur) => {
53+ (msg) => {
4954 const text = msg.content
5055 .filter((c) => c.type === "text")
5156 .map((c) => c.text)
@@ -58,7 +63,7 @@ export async function streamHeadless(
5863
5964 if (["stop", "error", "aborted"].includes(msg.stopReason)) {
6065 console.log(`Reason for stopping: "${msg.stopReason}"`);
61- leave(`Done. Took ${dur / 1000}s`);
66+ leave(`Done. Took ${(Date.now() - lastTs) / 1000}s`);
6267 }
6368 },
6469 );
src/tool-bash.ts+14−4
@@ -42,10 +42,20 @@ export async function runBashTool(args: Record<string, any>) {
4242 await proc.exited;
4343 const stdout = (await proc.stdout.text()).trim();
4444 const stderr = (await proc.stderr?.text())?.trim();
45- let out =
46- proc.exitCode === 0
47- ? (stdout ?? "Exit 0")
48- : stderr || stdout || `Exit ${proc.exitCode}`;
45+
46+ let out = `# EXIT CODE: ${proc.exitCode}`;
47+ if (stderr.length) {
48+ out += `
49+# STDERR:
50+
51+${stderr}`;
52+ }
53+ if (stdout.length) {
54+ out += `
55+# STDOUT:
56+
57+${stdout}`;
58+ }
4959
5060 // If `out` is too big, more than ~10KB, write it to a temp file
5161 // And add that to the truncation label for the agent to be able
src/tool-edit.ts+76−0
@@ -0,0 +1,76 @@
1+import { isAbsolute, join } from "node:path";
2+import { type Tool, Type } from "@mariozechner/pi-ai";
3+
4+export const edit: Tool = {
5+ name: `edit`,
6+ description:
7+ "This is your edit tool, use it to create or edit files safely. Always prefer this tool over bash editting methods.",
8+ parameters: Type.Object({
9+ path: Type.String({
10+ description: "File path (absolute or relative to cwd)",
11+ }),
12+ oldText: Type.String({
13+ description:
14+ 'Exact text to find and replace. Empty string means "create new file".',
15+ }),
16+ newText: Type.String({
17+ description: "Replacement text (or full content for new files)",
18+ }),
19+ }),
20+};
21+
22+function findAllIndexes(text: string, sub: string): number[] {
23+ if (sub.length === 0) return [];
24+
25+ const indexes: number[] = [];
26+
27+ let pos = text.indexOf(sub, 0);
28+ while (pos !== -1) {
29+ indexes.push(pos);
30+ pos += sub.length; // use pos += 1 if you want overlapping matches
31+ pos = text.indexOf(sub, pos);
32+ }
33+
34+ return indexes;
35+}
36+
37+export async function runEditTool(args: Record<string, any>) {
38+ const filePath = isAbsolute(args.path)
39+ ? args.path
40+ : join(process.cwd(), args.path);
41+ const file = Bun.file(filePath);
42+ const exists = await file.exists();
43+
44+ if (args.oldText === "") {
45+ if (exists) {
46+ return `File already exists: ${filePath}`;
47+ }
48+
49+ await Bun.write(file, args.newText);
50+ return `File written: ${filePath}`;
51+ }
52+
53+ if (!exists) {
54+ return `File not found: ${filePath}`;
55+ }
56+
57+ const content = await file.text();
58+ const matches = findAllIndexes(content, args.oldText);
59+
60+ if (matches.length === 0) {
61+ return `Old text not found in: ${filePath}`;
62+ }
63+
64+ if (matches.length > 1) {
65+ return `Multiple matches found in ${filePath}: ${matches.length} matches`;
66+ }
67+
68+ const idx = matches[0];
69+ const updated =
70+ content.slice(0, idx) +
71+ args.newText +
72+ content.slice(idx + args.oldText.length);
73+
74+ await file.write(updated);
75+ return `Edited: ${filePath}`;
76+}
src/tui-conversation.ts+2−1
@@ -43,6 +43,7 @@ function toolMessageNode(msg: TUIMessage) {
4343 export function Conversation(state: TUIState) {
4444 // TODO: use scroll callbacks to make the conversation a virtual list,
4545 // only showing a 12 messages window based the scroll position.
46+ // currently we just don't show earlier messages :(
4647 return VStack(
4748 {
4849 flex: 1,
@@ -56,7 +57,7 @@ export function Conversation(state: TUIState) {
5657 },
5758 },
5859 [
59- ...state.messages.map((msg) => {
60+ ...state.messages.slice(-12).map((msg) => {
6061 const dur = msg.durationMs
6162 ? `Took ${elapsedTime(msg.durationMs / 1000)}`
6263 : "-";
src/tui.ts+19−13
@@ -5,6 +5,7 @@ import { streamAgent, TASK_PROMPT } from "./agent";
55 import { getApiKey } from "./oauth";
66 import { onceEvery, secureRandomString, takeTail } from "./shared";
77 import { bash, runBashTool } from "./tool-bash";
8+import { edit, runEditTool } from "./tool-edit";
89 import { TextPill, theme } from "./tui-components";
910 import { Conversation } from "./tui-conversation";
1011 import { Editor } from "./tui-editor";
@@ -54,10 +55,10 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
5455 TextPill(state.options.model.name, theme.bblack, theme.bwhite),
5556 TextPill(`../${cwd}`, theme.bwhite, theme.bblack),
5657 VStack({ flex: 1 }, []),
58+ TextPill(state.activeState, theme.bwhite, theme.bblack),
5759 state.streaming
5860 ? TextPill(currentSpinner(), theme.bblack, theme.bwhite)
5961 : TextPill(currentSpinner(), theme.bwhite, theme.bblack),
60- TextPill(state.activeState, theme.bwhite, theme.bblack),
6162 ]),
6263
6364 Editor(
@@ -141,8 +142,12 @@ export async function streamTUI(state: TUIState) {
141142 if (state.streaming) return;
142143 state.streaming = true;
143144
145+ const lastTs = Date.now();
144146 const apiKey = await getApiKey(state.options);
145- const tools: ToolAndRunner[] = [{ tool: bash, runner: runBashTool }];
147+ const tools: ToolAndRunner[] = [
148+ { tool: bash, runner: runBashTool },
149+ { tool: edit, runner: runEditTool },
150+ ];
146151 const userPrompt = {
147152 role: "user",
148153 content: state.prompt || "",
@@ -163,7 +168,7 @@ export async function streamTUI(state: TUIState) {
163168 TASK_PROMPT,
164169 messages,
165170 state.options,
166- (ev, dur) => {
171+ (ev) => {
167172 switch (ev.type) {
168173 case "text_start":
169174 state.activeState = "answering";
@@ -184,9 +189,7 @@ export async function streamTUI(state: TUIState) {
184189 );
185190
186191 for (const call of newToolCalls) {
187- const toolMessage = createTUIToolMessage(call, {
188- durationMs: dur,
189- });
192+ const toolMessage = createTUIToolMessage(call);
190193 let found = false;
191194 state.messages = state.messages.map((msg) => {
192195 if (call.id === msg.id) {
@@ -216,14 +219,12 @@ export async function streamTUI(state: TUIState) {
216219 state.messages = state.messages.map((msg) => {
217220 if (call.id === msg.id) {
218221 updated = true;
219- return createTUIToolMessage(call, { ...msg, durationMs: dur });
222+ return createTUIToolMessage(call, msg);
220223 }
221224 return msg;
222225 });
223226 if (!updated) {
224- state.messages.push(
225- createTUIToolMessage(call, { durationMs: dur }),
226- );
227+ state.messages.push(createTUIToolMessage(call));
227228 }
228229 }
229230
@@ -242,18 +243,23 @@ export async function streamTUI(state: TUIState) {
242243 }
243244 },
244245
245- (tool, dur) => {
246+ (tool) => {
246247 // Append the output to the existing TUI messages
247248 state.messages = state.messages.map((msg) => {
248249 if (tool.toolCallId === msg.id) {
249- return createTUIToolMessage(tool, { ...msg, durationMs: dur });
250+ return createTUIToolMessage(tool, {
251+ ...msg,
252+ durationMs: Date.now() - msg.timestamp,
253+ });
250254 }
251255 return msg;
252256 });
253257 cel.render();
254258 },
255259
256- (msg, context, dur) => {
260+ (msg, context) => {
261+ const dur = Date.now() - lastTs;
262+
257263 if (msg.errorMessage) {
258264 state.messages.push({
259265 id: secureRandomString(8),