xonecas.io
64875
Mc

mini-coder / commit 262db76

feat: task tool

xonecas2026-04-24 262db7660a2ecfef24732551572427002aa0e491 parent e9dde6a

11 files changed

AGENTS.md+1−1
@@ -2,7 +2,7 @@
22
33 A new version of mini-coder, written from the ground up as library first, plugins.
44 Version `mini-coder@0.5.x` is currently stable and mostly complete, that's our reference implementation.
5-Benchmarking from the start, keep the agent dumb, build the plugin-library-first architecture, then
5+Benchmarking from the start, keep the agent dumb, build the library-first architecture, then
66 run an automated benchmarking loop to shape/hone the harness.
77
88 ## Dog-fooding
TODO.md+1−1
@@ -7,4 +7,4 @@
77 - `src/tui.ts:248` tool timing is still cumulative for later tool calls\*\*
88 The new duration is computed from `msg.timestamp`, which is set when the tool call is first shown, not when that specific tool
99 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.
10+ that includes time spent waiting on earlier tools, so the displayed `Took ...` is inaccurate.
src/agent.ts+26−13
@@ -13,17 +13,28 @@ import {
1313 import { parseSkillFrontmatter } from "./shared";
1414 import type { CliOptions, ToolAndRunner } from "./types";
1515
16-export const TASK_PROMPT = `# You are "mini-coder", an elite coding agent.
16+const IDENTITY_PROMPT = `# You are "mini-coder", an elite coding agent.
1717
1818 Behaviour guidelines:
1919
20+- Tone: use a jovial but motivated colleague persona. Be less verbose and more concise. You are working with software engineers, act appropriately, no fluff, only direct talk.`;
21+
22+export const MAIN_PROMPT = `${IDENTITY_PROMPT}
2023 - Answer all user questions without guessing, or assuming.
2124 - Use recent online information, the current environment, and your training data combined for a complete answer.
25+- Once you've gathered enough information to complete the request, stop exploring and complete it.
26+- Use the \`task()\` tool to complete your work. Define a plan with the user, break it down into tasks, and use the tool.
27+- Be careful with overlapping work when using \`task()\` in parallel.
28+- Be careful with existing changes and destructive commands, they could harm your user's changes.
29+`;
30+
31+export const TASK_PROMPT = `${IDENTITY_PROMPT}
32+- Use recent online information, the current environment, and your training data combined for a complete answer.
2233 - Once you've gathered enough information to complete the request, stop exploring and complete the task.
2334 - When completing a task, ensure that you fulfill the contract **exactly**.
35+- Always verify your changes using compilation, testing, and manual verification when possible.
2436 - Use temp directory for temp files, scripts or anything that doesn't match the requested output.
2537 - Be careful with existing changes and destructive commands, they could harm your user's changes.
26-- Tone: use a jovial but motivated colleague persona. Be less verbose and more concise. You are working with software engineers, act appropriately, no fluff, only direct talk.
2738 `;
2839
2940 // `AGENTS.md` support: find it in current folder (./AGENTS.md) and a global one. (`.agents/AGENTS.md`)
@@ -123,8 +134,8 @@ export async function streamAgent(
123134 messages: Message[],
124135 options: CliOptions,
125136 abortController?: AbortController,
126- streamFn?: (ev: AssistantMessageEvent) => void,
127- toolsFn?: (tool: ToolResultMessage) => void,
137+ streamFn?: (ev: AssistantMessageEvent, context: Context) => void,
138+ toolsFn?: (tool: ToolResultMessage, context: Context) => void,
128139 completeFn?: (msg: AssistantMessage, context: Context) => void,
129140 ) {
130141 const context: Context = {
@@ -133,21 +144,23 @@ export async function streamAgent(
133144 tools: tools.map((t) => t.tool),
134145 };
135146
136- let controller: AbortController
137- const onAbort = () => { controller?.abort(); }
147+ let controller: AbortController;
148+ const onAbort = () => {
149+ controller?.abort();
150+ };
138151 // Wire the global abort signal to each turn http requests
139- abortController?.signal.addEventListener('abort', onAbort)
152+ abortController?.signal.addEventListener("abort", onAbort);
140153
141154 while (true) {
142- controller = new AbortController()
155+ controller = new AbortController();
143156 const s = streamSimple(options.model, context, {
144157 apiKey,
145158 reasoning: options.effort,
146- signal: controller.signal
159+ signal: controller.signal,
147160 });
148161
149162 for await (const ev of s) {
150- streamFn?.(ev);
163+ streamFn?.(ev, context);
151164 }
152165
153166 const finalMessage = await s.result();
@@ -155,7 +168,7 @@ export async function streamAgent(
155168
156169 if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
157170 completeFn?.(finalMessage, context);
158- abortController?.signal.removeEventListener('abort', onAbort)
171+ abortController?.signal.removeEventListener("abort", onAbort);
159172 return;
160173 }
161174
@@ -175,7 +188,7 @@ export async function streamAgent(
175188 timestamp: Date.now(),
176189 };
177190 context.messages.push(msg);
178- toolsFn?.(msg);
191+ toolsFn?.(msg, context);
179192 }
180193
181194 if (toolCalls.length > 0) {
@@ -183,7 +196,7 @@ export async function streamAgent(
183196 // we add { apiKey } in this call. And how does it work without it?
184197 const cont = await completeSimple(options.model, context, {
185198 reasoning: options.effort,
186- signal: controller.signal
199+ signal: controller.signal,
187200 });
188201 context.messages.push(cont);
189202 }
src/index.ts+0−4
@@ -16,9 +16,6 @@ export async function main(): Promise<void> {
1616 process.exit(0);
1717 }
1818
19-
20- const abortController = new AbortController();
21-
2219 const state: TUIState = {
2320 options,
2421 prompt: "",
@@ -27,7 +24,6 @@ export async function main(): Promise<void> {
2724 streaming: false,
2825 stickToBottom: true,
2926 scrollOffset: 0,
30- abortController
3127 };
3228
3329 initTUI(state, leave);
src/tool-bash.ts+2−3
@@ -27,11 +27,10 @@ Current working directory: ${process.cwd()}
2727
2828 export const bash: Tool = {
2929 name: "bash",
30- description:
31- "This is your command line, run commands in your user's environment.",
30+ description,
3231 parameters: Type.Object({
3332 command: Type.String({
34- description,
33+ description: "The command you want to run on the user's environment.",
3534 }),
3635 }),
3736 };
src/tool-task.ts+83−0
@@ -0,0 +1,83 @@
1+import {
2+ type AssistantMessage,
3+ type Message,
4+ type ThinkingLevel,
5+ type Tool,
6+ Type,
7+} from "@mariozechner/pi-ai";
8+import { streamAgent, TASK_PROMPT } from "./agent";
9+import { getApiKey } from "./oauth";
10+import { bash, runBashTool } from "./tool-bash";
11+import { edit, runEditTool } from "./tool-edit";
12+import type { CliOptions, ToolAndRunner } from "./types";
13+
14+const description = `## Task tool
15+
16+Best practices using this tool:
17+
18+- Use detailed prompts, be specific about the expected output and guardrails.
19+- Task tool doesn't know your context, make sure include all relevant details.
20+- Break your work down into small tasks, one small job for each task call.
21+- Always prefer using this tool before any other specific tool.
22+- Use this tool to explore directories, codebases and the web.
23+- Use this tool to perform edits, run verifications, and review changes.
24+- When describing edits, include detailed descriptions and validation requirements.`;
25+
26+export const task: Tool = {
27+ name: "task",
28+ description,
29+ parameters: Type.Object({
30+ prompt: Type.String({
31+ description: "The detailed description of the task you want complete.",
32+ }),
33+ }),
34+};
35+
36+export async function runTaskTool(
37+ options: CliOptions & { abortController?: AbortController },
38+ args: Record<string, any>,
39+) {
40+ const apiKey = await getApiKey(options);
41+ const tools: ToolAndRunner[] = [
42+ { tool: bash, runner: runBashTool },
43+ { tool: edit, runner: runEditTool },
44+ ];
45+ const messages: Message[] = [
46+ { role: "user", content: args.prompt, timestamp: Date.now() },
47+ ];
48+
49+ // For custom effort for speed and less suprises. Consider even using a `taskModel` config value.
50+ // Also remove the piggy backed abortController.
51+ const taskOptions = {
52+ ...options,
53+ effort: "low" as ThinkingLevel,
54+ abortController: undefined,
55+ };
56+
57+ let output = "";
58+ const onComplete = (ev: AssistantMessage) => {
59+ output = ev.content
60+ .filter((b) => b.type === "text")
61+ .map((b) => b.text)
62+ .join("\n");
63+
64+ if (["stop", "error", "aborted"].includes(ev.stopReason)) {
65+ if (ev.errorMessage)
66+ output += `\n\nStopped: ${ev.stopReason}, message:\n${ev.errorMessage}`;
67+ }
68+ };
69+
70+ await streamAgent(
71+ apiKey,
72+ tools,
73+ TASK_PROMPT,
74+ messages,
75+ taskOptions,
76+ options.abortController,
77+ undefined,
78+ undefined,
79+ onComplete,
80+ );
81+
82+ return output.trim();
83+}
src/tui-components.ts+6−6
@@ -1,6 +1,6 @@
11 import { type Color, HStack, Text } from "@cel-tui/core";
22 import { onceEvery } from "./shared";
3-import { TUIState } from "./types";
3+import type { TUIState } from "./types";
44
55 export const theme = {
66 black: "color00" as Color,
@@ -94,11 +94,11 @@ export function ActivityPill(state: TUIState, spinnerFrame: string) {
9494 let label = state.activeState.replaceAll("_", " ");
9595 const fg = state.streaming ? theme.bblack : theme.bwhite;
9696 const bg = state.streaming ? theme.bwhite : theme.bblack;
97- const frame = state.streaming ? spinnerFrame : ""
98-
97+ const frame = state.streaming ? spinnerFrame : "";
98+
9999 if (frame) {
100- label += ` ${frame}`
100+ label += ` ${frame}`;
101101 }
102102
103- return TextPill(label, fg, bg)
104-}
103+ return TextPill(label, fg, bg);
104+}
src/tui-conversation.ts+1−1
@@ -53,7 +53,7 @@ function toolMessageNode(msg: TUIMessage): Node {
5353 memoizedSyntaxHighlight(
5454 msg.id ?? String(msg.timestamp),
5555 msg.header ?? "",
56- "bash",
56+ msg.label === "bash" ? "bash" : "markdown",
5757 ),
5858 Text(msg.content, { wrap: "word", fgColor: theme.bblack }),
5959 ]);
src/tui-state.ts+8−0
@@ -43,6 +43,14 @@ export function createTUIToolMessage(
4343 : source.arguments.command;
4444 }
4545
46+ // Task tool call
47+ if ("arguments" in source && "prompt" in source.arguments) {
48+ args =
49+ source.arguments?.prompt?.length > argsMaxLength
50+ ? source.arguments.prompt.substring(0, argsMaxLength)
51+ : source.arguments.prompt;
52+ }
53+
4654 // Edit tool call
4755 if ("arguments" in source && "path" in source.arguments) {
4856 const before = source.arguments.oldText;
src/tui.ts+37−26
@@ -1,11 +1,10 @@
11 import { basename } from "node:path";
2-import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
2+import { cel, HStack, ProcessTerminal, VStack } from "@cel-tui/core";
33 import type { Message } from "@mariozechner/pi-ai";
4-import { streamAgent, TASK_PROMPT } from "./agent";
4+import { MAIN_PROMPT, streamAgent } from "./agent";
55 import { getApiKey } from "./oauth";
66 import { estimateTokens, secureRandomString } from "./shared";
7-import { bash, runBashTool } from "./tool-bash";
8-import { edit, runEditTool } from "./tool-edit";
7+import { runTaskTool, task } from "./tool-task";
98 import { ActivityPill, Spinner, TextPill, theme } from "./tui-components";
109 import { Conversation } from "./tui-conversation";
1110 import { Editor } from "./tui-editor";
@@ -15,28 +14,28 @@ import type { ToolAndRunner, TUIMessage, TUIState } from "./types";
1514 function clearOrAbort(state: TUIState) {
1615 // Are we mid stream? Abort it.
1716 if (state.streaming) {
18- state.abortController.abort()
17+ state.abortController?.abort();
1918 state.abortController = new AbortController();
2019 }
2120
2221 // Is the user clearing a state prompt?
2322 if (state.prompt?.length) {
24- state.prompt = ""
23+ state.prompt = "";
2524 }
2625 }
2726
2827 function ContextPill(state: TUIState) {
29- let text = ""
28+ let text = "";
3029 if (!state.context) {
31- text = "0%"
30+ text = "0%";
3231 } else {
33- const current = estimateTokens(JSON.stringify(state.context))
34- const max = state.options.model.maxTokens
35- const percent = Math.round((current/max)*100)
36- text = `~${percent}%`
32+ const current = estimateTokens(JSON.stringify(state.context));
33+ const max = state.options.model.contextWindow;
34+ const percent = Math.round((current / max) * 100);
35+ text = `~${percent}%`;
3736 }
3837
39- return TextPill(text, theme.bblack, theme.bwhite)
38+ return TextPill(text, theme.bblack, theme.bwhite);
4039 }
4140
4241 export function initTUI(state: TUIState, leave: (s: string) => void) {
@@ -68,9 +67,9 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
6867 clearInterval(baseFramerateIntervalId);
6968 cel.stop();
7069 leave("Done.");
71- } else if (key === 'escape') {
70+ } else if (key === "escape") {
7271 // Abort or clear prompt
73- clearOrAbort(state)
72+ clearOrAbort(state);
7473 }
7574 },
7675 },
@@ -95,10 +94,11 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
9594 (key: string) => {
9695 // onKeyPress
9796 if (key === "enter") {
98- if (state.prompt === ':q') {
99- clearInterval(baseFramerateIntervalId)
100- cel.stop()
101- leave("Done. I like vim too.")
97+ if (state.prompt === ":q") {
98+ clearInterval(baseFramerateIntervalId);
99+ cel.stop();
100+ leave("Done. I like vim too.");
101+ return false;
102102 }
103103 const submit = async () => {
104104 await streamTUI(state);
@@ -117,11 +117,18 @@ export async function streamTUI(state: TUIState) {
117117 if (state.streaming) return;
118118 state.streaming = true;
119119
120+ const abortController = new AbortController();
121+ state.abortController = abortController;
122+
120123 const lastTs = Date.now();
121124 const apiKey = await getApiKey(state.options);
122125 const tools: ToolAndRunner[] = [
123- { tool: bash, runner: runBashTool },
124- { tool: edit, runner: runEditTool },
126+ {
127+ tool: task,
128+ runner: async (args: Record<string, any>) => {
129+ return runTaskTool({...state.options, abortController}, args);
130+ },
131+ },
125132 ];
126133 const userPrompt = {
127134 role: "user",
@@ -140,11 +147,13 @@ export async function streamTUI(state: TUIState) {
140147 await streamAgent(
141148 apiKey,
142149 tools,
143- TASK_PROMPT,
150+ MAIN_PROMPT,
144151 messages,
145152 state.options,
146153 state.abortController,
147- (ev) => {
154+ (ev, context) => {
155+ state.context = context;
156+
148157 switch (ev.type) {
149158 case "text_start":
150159 state.activeState = "answering";
@@ -182,7 +191,7 @@ export async function streamTUI(state: TUIState) {
182191 }
183192
184193 case "toolcall_end": {
185- state.activeState = "idle";
194+ state.activeState = "waiting";
186195
187196 // Collect tool calls state
188197 const finishedToolCalls = ev.partial.content.filter(
@@ -209,7 +218,7 @@ export async function streamTUI(state: TUIState) {
209218 }
210219
211220 case "done":
212- state.activeState = "idle";
221+ state.activeState = "waiting";
213222 cel.render();
214223 break;
215224
@@ -219,7 +228,7 @@ export async function streamTUI(state: TUIState) {
219228 }
220229 },
221230
222- (tool) => {
231+ (tool, context) => {
223232 // Append the output to the existing TUI messages
224233 state.messages = state.messages.map((msg) => {
225234 if (tool.toolCallId === msg.id) {
@@ -230,6 +239,7 @@ export async function streamTUI(state: TUIState) {
230239 }
231240 return msg;
232241 });
242+ state.context = context;
233243 cel.render();
234244 },
235245
@@ -259,6 +269,7 @@ export async function streamTUI(state: TUIState) {
259269 }
260270
261271 state.streaming = false;
272+ state.activeState = "idle";
262273 state.context = context;
263274 cel.render();
264275 },
src/types.ts+7−2
@@ -8,7 +8,12 @@ export type CliOptions = {
88 jsonOutput?: boolean;
99 };
1010
11-export type TUIActiveState = "idle" | "thinking" | "answering" | "calling_tool";
11+export type TUIActiveState =
12+ | "idle"
13+ | "waiting"
14+ | "thinking"
15+ | "answering"
16+ | "calling_tool";
1217
1318 export type TUIMessage = {
1419 content: string;
@@ -29,7 +34,7 @@ export type TUIState = {
2934 streaming: boolean;
3035 stickToBottom: boolean;
3136 scrollOffset: number;
32- abortController: AbortController;
37+ abortController?: AbortController;
3338 };
3439
3540 export type SavedOAuthAuth = OAuthCredentials & {