xonecas.io
64875
Mc

mini-coder / commit 37bef45

fix: better agent core api/shape and events

xonecas2026-04-27 37bef454d3d6a486b99aedbbd405a05f0c52ea00 parent 4d8d166

8 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

src/agent.ts+124−400
@@ -1,386 +1,19 @@
1-import { readdir } from "node:fs/promises";
2-import { homedir, platform } from "node:os";
3-import { join } from "node:path";
41 import {
52 type AssistantMessage,
63 type Context,
7- type Message,
84 streamSimple,
5+ type TextContent,
96 type ToolCall,
10- type ToolResultMessage,
117 } from "@mariozechner/pi-ai";
12-import { type StatusResult, simpleGit } from "simple-git";
138 import { getApiKey } from "./oauth";
14-import { parseSkillFrontmatter } from "./shared";
159 import type {
16- AgentStreamEvent,
17- CliOptions,
10+ AgentContex,
11+ AgentEvent,
12+ AgentToolEvent,
1813 ToolAndRunner,
19- ToolRunnerEvent,
2014 } from "./types";
2115
22-const IDENTITY_PROMPT = `# You are "mini-coder", an efficient, elite coding agent.
23-
24-## Behaviour rules:
25-
26-**IMPORTANT**: This is your default behaviour, breaking these rules is unacceptable.
27-
28-- Answer all user requests without guessing, or assuming.
29-- Use recent online information, the current environment, and your training data combined for a complete answer.
30-- Be defensive with existing changes and destructive commands, they could harm your user's changes.
31-- Be efficient, don't get lost with tangents or satisfying your curiosity, root yourself on the user request.
32-- Narrate your edits with small commentary messages during long tasks.
33-- Do not over-scope your work, or add more scope during implementation.
34-- Avoid over-enginnering, hacks or creative solutions. The boring, simple and repliable is always preffered.
35-- Focus on the user's request requirements to answer accurately and efficiently.
36-- Once you've gathered enough information to complete the request, stop exploring and complete it.
37-- Ensure that you fulfill the user's expectation, requirements and contract **exactly**.
38-- Use temp directory for temp files, scripts, plan files, or anything that doesn't match the requested output.
39-- Always verify your changes using compilation, testing, and manual verification when possible.
40-- Do not overstate what changed or what was verified. Never make unverified claims.
41-- Summaries must match the diff.
42-- 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.`;
43-
44-export const MAIN_PROMPT = `${IDENTITY_PROMPT}
45-
46-## Workflow:
47-
48-- Use this if the user did not specify a workflow.
49-
50-1. Read the user's message, understand the request.
51-2. Gather context from the local environment, local code, docs and online related references to the request as needed.
52-3. Plan your changes by breaking down the request into small tasks, resolve open questions with the user to complete your plan with accuracy and detail.
53-4. Use the appropriate tools to execute the plan. Keep the plan up to date and follow it accurately.
54-5. Validate your changes without adding more scope to your work.
55-6. Summarize your changes and completed plan in your final message.
56-
57-## Tool selection heuristic:
58-
59-**Always** follow this logic when deciding your tool usage:
60-
61-- You have limitted context size, the task tool compresses tool loops for you, keeping your context pressure low.
62-- Before **every tool call** consider if you are doing too much in your context window, and favor using the task tool.
63-- If the user's request requires **less** than 3 to 4 shell/edit/read tool calls, use them and complete the request.
64-- Else, the request requires **more** than 4 shell/edit tool calls, use the \`task()\` tool.
65-- This is not optional, if you fill your context with exploration, excessive tool calls, then you have none left to help the user. This is unacceptable.
66-
67-**IMPORTANT: Always make sure you are not falling into a shell tool calling loop!**
68-
69-- This is a clear sign you should be using the task tool. Stop the loop and use the task tool.
70-`;
71-
72-export const TASK_PROMPT = `${IDENTITY_PROMPT}
73-
74-## Workflow:
75-
76-1. Read the user message, understand the request. Gather context as needed to complete the request.
77-2. Plan your changes by breaking down the request into smaller tasks as needed.
78-3. Execute your plan with the appropriate tools.
79-4. Validate your changes without adding scope, and ensuring the user's request is met **exactly** with no deviations.
80-5. Your final message should include a summary of your actions and any diffs from your edits.
81-`;
82-
83-async function getEnvPrompt() {
84- // TODO: What else do the agents always check before answering every time?
85- let gitStatus: StatusResult | { nogit: string };
86- try {
87- gitStatus = await simpleGit().status();
88- } catch (_) {
89- gitStatus = { nogit: "No git repo in this folder." };
90- }
91- const envStatus = JSON.stringify(
92- {
93- cwd: process.cwd(),
94- os: platform(),
95- git: gitStatus,
96- },
97- null,
98- 4,
99- );
100-
101- const text = `### Environment status and information
102-
103-\`\`\`json
104- ${envStatus}
105-\`\`\`
106-`;
107-
108- return text;
109-}
110-
111-// `AGENTS.md` support: find it in current folder (./AGENTS.md) and a global one. (`.agents/AGENTS.md`)
112-export async function getAGENTSFiles() {
113- const content: string[] = [];
114-
115- const globalPath = join(homedir(), ".agents/AGENTS.md");
116- const globalFile = Bun.file(globalPath);
117-
118- if (await globalFile.exists()) {
119- content.push(await globalFile.text());
120- }
121-
122- const localPath = join(process.cwd(), "AGENTS.md");
123- const localFile = Bun.file(localPath);
124-
125- if (await localFile.exists()) {
126- content.push(await localFile.text());
127- }
128-
129- return content.join("\n\n").trim();
130-}
131-
132-// `SKILLS.md` discovery from [~|.]/agents/skills/*/SKILL.md
133-export async function getSkills(): Promise<string> {
134- let skillsBlock: string = "";
135- const skillRoots = [
136- join(homedir(), ".agents", "skills"),
137- join(process.cwd(), ".agents", "skills"),
138- ];
139-
140- for (const root of skillRoots) {
141- let entries: string[];
142-
143- try {
144- entries = await readdir(root);
145- } catch {
146- continue;
147- }
148-
149- for (const entry of entries) {
150- const path = join(root, entry, "SKILL.md");
151- const file = Bun.file(path);
152-
153- if (!(await file.exists())) {
154- continue;
155- }
156-
157- const parsed = parseSkillFrontmatter(await file.text());
158-
159- if (!parsed) {
160- continue;
161- }
162-
163- skillsBlock += `## ${parsed.name}
164-
165-> Absolute file path to read: ${path}
166-
167-${parsed.description}
168-
169-`;
170- }
171- }
172-
173- if (!skillsBlock.length) return "";
174-
175- const skills = `# Skills
176-
177-- The following skills provide specialized instructions for specific tasks.
178-- Use the shell tool to read a skill's file when the task matches its description.
179-- Use the skill provided absolute file path instead of guessing or constructing one.
180-- Skills can be global (in ~/.agents/skills) or locat to the directory (./agents/skills)
181-
182-${skillsBlock}`;
183-
184- return skills.trim();
185-}
186-
187-export async function buildSystemPrompt(systemPrompt: string) {
188- const agentsContent = await getAGENTSFiles();
189- const skillsContent = await getSkills();
190- const envStatus = await getEnvPrompt();
191- let complete = systemPrompt + envStatus;
192-
193- if (skillsContent) {
194- complete += `\n${skillsContent}`;
195- }
196-
197- if (agentsContent) {
198- complete += `\n${agentsContent}`;
199- }
200-
201- return complete;
202-}
203-
204-export function insertToolUsageReminder(
205- messages: Message[],
206- toolMessage: ToolResultMessage,
207-) {
208- // check for the last 5 tool call assistant messages
209- // if they are non-`task` tool calls insert the reminder
210- // as a prefix.
211- let output = toolMessage.content
212- .filter((b) => b.type === "text")
213- .map((b) => b.text)
214- .join("\n");
215-
216- const budget = 5;
217- const toolCalls: ToolCall[] = [];
218- messages.forEach((m) => {
219- if (m.role === "assistant") {
220- const toolCallsBlocks = m.content.filter((b) => b.type === "toolCall");
221- toolCalls.push(...toolCallsBlocks);
222- }
223- });
224- const recentToolCalls = toolCalls.slice(-budget);
225- const taskSeen = recentToolCalls.some((call) => call.name === "task");
226-
227- if (toolCalls.length >= budget && !taskSeen) {
228- output = `# System reminder:
229-
230-> You are in a shell or edit tool calling loop poluting your context.
231-
232-- Remember your tool choice heuristic.
233-- Plan your next actions, and use the task tool to continue.
234-- If you have completed the user request, complete your answer.
235-
236----
237-
238-${output}
239-`;
240- }
241-
242- toolMessage.content = [{ type: "text", text: output }];
243-
244- return toolMessage;
245-}
246-
24716 export async function* streamAgent(
248- apiKey: string,
249- tools: ToolAndRunner[],
250- systemPrompt: string,
251- messages: Message[],
252- options: CliOptions,
253- abortController?: AbortController,
254-): AsyncGenerator<AgentStreamEvent> {
255- const context: Context = {
256- systemPrompt: await buildSystemPrompt(systemPrompt),
257- messages,
258- tools: tools.map((t) => t.tool),
259- };
260-
261- while (true) {
262- const s = streamSimple(options.model, context, {
263- apiKey,
264- reasoning: options.effort,
265- signal: abortController?.signal,
266- });
267-
268- for await (const ev of s) {
269- yield { type: "assistant", event: ev, context };
270- }
271-
272- const finalMessage = await s.result();
273- context.messages.push(finalMessage);
274-
275- // Check if the agent is done, or an error/abort happened before moving
276- // on towards tool calling.
277- if (finalMessage.stopReason !== "toolUse") {
278- // Agent is done, send the final message, and current context.
279- yield { type: "complete", message: finalMessage, context };
280- break;
281- }
282-
283- // TODO: Extract into it's own function
284- // Call tolls and per tool result callback.
285- const toolCalls = finalMessage.content.filter(
286- (msg) => msg.type === "toolCall",
287- );
288-
289- for (const call of toolCalls) {
290- let output = "";
291- let isError = false;
292-
293- const toolDef = tools.find((item) => item.tool.name === call.name);
294- let msg: ToolResultMessage = {
295- role: "toolResult",
296- toolCallId: call.id,
297- toolName: call.name,
298- content: [{ type: "text", text: output }],
299- isError,
300- timestamp: Date.now(),
301- };
302-
303- if (!toolDef) {
304- output = `Unknown tool: ${call.name}`;
305- isError = true;
306- } else {
307- try {
308- for await (const event of toolDef.runner(call.arguments)) {
309- switch (event.type) {
310- case "output":
311- output += event.text;
312- msg = {
313- ...msg,
314- content: [{ type: "text", text: event.text }],
315- };
316- yield {
317- type: "tool_output",
318- message: msg,
319- context,
320- };
321- break;
322-
323- case "result":
324- output = event.text;
325- break;
326- }
327- }
328- } catch (err) {
329- const error = err instanceof Error ? err.message : "Unknown error";
330- output = `Tool call failed: ${error}`;
331- isError = true;
332- }
333- }
334-
335- msg = {
336- role: "toolResult",
337- toolCallId: call.id,
338- toolName: call.name,
339- content: [{ type: "text", text: output }],
340- isError,
341- timestamp: Date.now(),
342- };
343-
344- // Update with tool results. let the user make changes if they want
345- context.messages.push(msg);
346-
347- yield {
348- type: "tool_result",
349- message: msg,
350- context,
351- };
352- }
353- }
354-}
355-
356-// CONTINUE: exploring a cleaner api for the core. It's a mess of bugs between this and the consumers: task, tui and headless, they all do things slighty different :/ my bad. this will bring some consistency.
357-type AgentContex = {
358- systemPrompt: string;
359- tools: ToolAndRunner[];
360- messages: Message[];
361- options: CliOptions;
362- signal: AbortSignal | undefined;
363-};
364-
365-type AgentEvent =
366- | {
367- type: "message_start" | "message_update";
368- partial: AssistantMessage;
369- }
370- | {
371- type: "message_end";
372- message: AssistantMessage;
373- }
374- | {
375- type: "tool_message_start" | "tool_message_update";
376- partial: ToolResultMessage;
377- }
378- | {
379- type: "tool_message_end";
380- message: ToolResultMessage;
381- };
382-
383-export async function* _streamAgent(
38417 agentCtx: AgentContex,
38518 ): AsyncGenerator<AgentEvent> {
38619 const llmCtx: Context = {
@@ -395,6 +28,7 @@ export async function* _streamAgent(
39528 // Main agent loop, continues until llm sends a response other than toolCall or has no tool calls.
39629 while (true) {
39730 const s = streamSimple(agentCtx.options.model, llmCtx, {
31+ reasoning: agentCtx.options.effort,
39832 signal: agentCtx.signal,
39933 apiKey,
40034 });
@@ -427,7 +61,6 @@ export async function* _streamAgent(
42761 }
42862 break;
42963
430- case "done":
43164 case "error": {
43265 const finalMessage = await s.result();
43366 if (added) {
@@ -450,50 +83,141 @@ export async function* _streamAgent(
45083 llmCtx.messages.push(message);
45184 yield { type: "message_start", partial: { ...message } };
45285 }
86+ yield { type: "message_end", message };
45387
45488 const toolCalls = message.content.filter((c) => c.type === "toolCall");
45589
45690 // Stop on errors or no tools to call.
45791 if (message.stopReason !== "toolUse" || toolCalls.length === 0) {
458- yield { type: "message_end", message };
45992 break;
46093 }
46194
462- const toolMessagesMap = new Map<string, ToolResultMessage>()
95+ const seenToolIds = new Map<string, number>();
46396 if (toolCalls.length > 0) {
464- const ts = toolRunner(toolCalls, agentCtx.tools)
465-
466- // Append toolResultMessges
467- for await (const toolMsg of ts) {
468- if (toolMessagesMap.has(toolMsg.toolCallId)) {
469- // Already seen, just update
470- toolMessagesMap.set(toolMsg.toolCallId, toolMsg);
471- llmCtx.messages = llmCtx.messages.map(m => {
472- if (m.role === 'toolResult' && m.toolCallId === toolMsg.toolCallId) {
473- return toolMsg
97+ const ts = toolRunner(toolCalls, agentCtx.tools, agentCtx.signal);
98+
99+ for await (const e of ts) {
100+ if (e.type === "tool_update") {
101+ // Update contex with update or add new.
102+ const existing = seenToolIds.get(e.partial.toolCallId);
103+ if (existing && existing >= 0) {
104+ const m = llmCtx.messages[existing];
105+ if (m.role === "toolResult") {
106+ llmCtx.messages[existing] = {
107+ ...m,
108+ content: [...m.content, ...e.partial.content],
109+ isError: e.partial.isError,
110+ };
474111 }
475- return m
476- })
477- yield { type: "tool_message_update", partial: toolMsg }
478- } else {
479- // New, add to context and map.
480- toolMessagesMap.set(toolMsg.toolCallId, toolMsg);
481- llmCtx.messages.push(toolMsg)
482- yield { type: "tool_message_start", partial: toolMsg }
483- }
484- }
485112
486- // Updates done, yield final tool results
487- for (const item of toolMessagesMap.values()) {
488- yield { type: "tool_message_end", message: item }
113+ yield {
114+ type: "tool_message_update",
115+ partial: e.partial,
116+ };
117+ } else {
118+ llmCtx.messages.push(e.partial);
119+ seenToolIds.set(e.partial.toolCallId, llmCtx.messages.length - 1);
120+
121+ yield {
122+ type: "tool_message_start",
123+ partial: e.partial,
124+ };
125+ }
126+ } else if (e.type === "tool_result") {
127+ // Update context with full message and yield
128+ const idx = llmCtx.messages.findIndex(
129+ (m) =>
130+ m.role === "toolResult" && m.toolCallId === e.message.toolCallId,
131+ );
132+ if (idx >= 0) {
133+ llmCtx.messages[idx] = e.message;
134+ } else {
135+ llmCtx.messages.push(e.message);
136+ }
137+
138+ yield {
139+ type: "tool_message_end",
140+ message: e.message,
141+ };
142+ }
489143 }
490144 }
491145 }
492146 }
493147
148+// This should stay stateless, don't accumulate anything at this layer, just proxy
149+// wrapped runners events.
494150 async function* toolRunner(
495- toolCall: ToolCall[],
151+ toolCalls: ToolCall[],
496152 tools: ToolAndRunner[],
497-): AsyncGenerator<ToolResultMessage> {
498- return;
153+ signal?: AbortSignal,
154+): AsyncGenerator<AgentToolEvent> {
155+ for (const call of toolCalls) {
156+ const timestamp = Date.now();
157+ const tool = tools.find((t) => t.tool.name === call.name);
158+
159+ if (!tool) {
160+ yield {
161+ type: "tool_result",
162+ message: {
163+ role: "toolResult",
164+ toolCallId: call.id,
165+ toolName: call.name,
166+ content: [{ type: "text", text: "Error: Tool not found" }],
167+ isError: true,
168+ timestamp,
169+ },
170+ };
171+ continue;
172+ }
173+
174+ try {
175+ for await (const e of tool.runner(call.arguments, signal)) {
176+ // yield deltas for output, full output on result.
177+ const content: TextContent = { type: "text", text: e.text };
178+
179+ if (e.type === "output") {
180+ // handle deltas
181+ yield {
182+ type: "tool_update",
183+ partial: {
184+ role: "toolResult",
185+ toolCallId: call.id,
186+ toolName: call.name,
187+ content: [content],
188+ isError: false,
189+ timestamp,
190+ },
191+ };
192+ } else if (e.type === "result") {
193+ // handle final message
194+ yield {
195+ type: "tool_result",
196+ message: {
197+ role: "toolResult",
198+ toolCallId: call.id,
199+ toolName: call.name,
200+ content: [content],
201+ isError: false,
202+ timestamp,
203+ },
204+ };
205+ }
206+ }
207+ } catch (err) {
208+ // We don't validate arguments, so it's better to show the errors.
209+ const error = err instanceof Error ? err.message : "Unknown error";
210+ yield {
211+ type: "tool_result",
212+ message: {
213+ role: "toolResult",
214+ toolCallId: call.id,
215+ toolName: call.name,
216+ content: [{ type: "text", text: `Error: ${error}` }],
217+ isError: true,
218+ timestamp,
219+ },
220+ };
221+ }
222+ }
499223 }
src/args.ts+0−7
@@ -111,7 +111,6 @@ export async function handleArgv(argv: string[]): Promise<CliOptions> {
111111 let modelId = settingsModelId;
112112 let effort = settingsEffort;
113113 let prompt: string | undefined;
114- let jsonOutput: boolean | undefined;
115114 let providerChanged = false;
116115 let explicitModel = false;
117116
@@ -146,11 +145,6 @@ export async function handleArgv(argv: string[]): Promise<CliOptions> {
146145 continue;
147146 }
148147
149- if (flag === "--json" || flag === "-j") {
150- jsonOutput = true;
151- continue;
152- }
153-
154148 if (flag === "--login" || flag === "-l") {
155149 await loginOAuth(requireValue(argv, i, flag));
156150 i++;
@@ -166,7 +160,6 @@ export async function handleArgv(argv: string[]): Promise<CliOptions> {
166160 model,
167161 effort,
168162 prompt,
169- jsonOutput,
170163 };
171164 const nextSettings: Settings = {
172165 provider,
src/headless.ts+20−101
@@ -1,126 +1,45 @@
1-import type {
2- AssistantMessage,
3- AssistantMessageEvent,
4- Message,
5- ToolResultMessage,
6-} from "@mariozechner/pi-ai";
7-import { MAIN_PROMPT, streamAgent } from "./agent";
8-import { getApiKey } from "./oauth";
1+import type { Message } from "@mariozechner/pi-ai";
2+import { streamAgent } from "./agent";
3+import { buildSystemPrompt, MAIN_PROMPT } from "./prompt";
94 import { bash, runBashTool } from "./tool-bash";
105 import { edit, runEditTool } from "./tool-edit";
116 import { runTaskTool, task } from "./tool-task";
12-import type { CliOptions, ToolAndRunner } from "./types";
7+import type { AgentContex, CliOptions, ToolAndRunner } from "./types";
138
149 export async function streamHeadless(
1510 options: CliOptions,
1611 leave: (s?: string) => void,
1712 ) {
18- const lastTs = Date.now();
19- const apiKey = await getApiKey(options);
2013 const tools: ToolAndRunner[] = [
2114 { tool: bash, runner: runBashTool },
2215 { tool: edit, runner: runEditTool },
23- { tool: task, runner: (args) => runTaskTool(options, args) },
16+ {
17+ tool: task,
18+ runner: (args) => runTaskTool(options, args),
19+ },
2420 ];
2521 const messages: Message[] = [
2622 { role: "user", content: options.prompt || "", timestamp: Date.now() },
2723 ];
24+ console.log(JSON.stringify(messages[0]));
2825
29- function log(args: { msg?: string; json?: string }) {
30- if ("json" in args && options.jsonOutput) console.log(args.json);
31- if ("msg" in args && !options.jsonOutput) console.log(args.msg);
32- }
33-
34- const onStream = (ev: AssistantMessageEvent) => {
35- switch (ev.type) {
36- case "text_end":
37- log({ msg: `> ${ev.content}` });
38- break;
39- case "thinking_start":
40- log({ msg: "> Thinking..." });
41- break;
42- case "toolcall_end":
43- // TODO: other tools output
44- log({
45- msg: `> ${ev.toolCall.name}: ${JSON.stringify(ev.toolCall.arguments)}`,
46- });
47- break;
48- case "error":
49- log({ msg: `> Error ${ev.reason}\n${ev.error.content}` });
50- break;
51- }
52-
53- // Log all non-delta events:
54- if (!ev.type.includes("delta")) {
55- log({ json: JSON.stringify(ev) });
56- }
57- };
58-
59- const onTool = (tool: ToolResultMessage) => {
60- let text = tool.content
61- .filter((c) => c.type === "text")
62- .map((c) => c.text)
63- .join("\n")
64- .slice(-400);
65-
66- if (text.length === 400) {
67- text = `...${text}`;
68- }
69-
70- log({
71- msg: `> ${tool.toolName} output:\n---\n${text}\n---`,
72- json: JSON.stringify(tool),
73- });
74-
75- return tool;
76- };
77-
78- const onComplete = (msg: AssistantMessage) => {
79- log({
80- msg: `\nTotal tokens: ${msg.usage.input} in, ${msg.usage.output} out`,
81- });
82- log({ msg: `Cost: $${msg.usage.cost.total.toFixed(4)}\n` });
83-
84- if (["stop", "error", "aborted"].includes(msg.stopReason)) {
85- log({ msg: `Reason for stopping: "${msg.stopReason}"` });
86- leave(
87- !options.jsonOutput
88- ? `Done. Took ${(Date.now() - lastTs) / 1000}s`
89- : undefined,
90- );
91- }
92- };
93-
94- log({ msg: "mini-coder headless" });
95- log({ msg: "-------------------" });
96-
97- for await (const event of streamAgent(
98- apiKey,
26+ const systemPrompt = await buildSystemPrompt(MAIN_PROMPT);
27+ const ctx: AgentContex = {
28+ systemPrompt,
9929 tools,
100- MAIN_PROMPT,
10130 messages,
10231 options,
103- undefined,
104- )) {
105- switch (event.type) {
106- case "assistant":
107- onStream(event.event);
108- break;
109-
110- case "tool_output":
111- // TODO:
112- // onToolOutput(event);
113- break;
114-
115- case "tool_result":
116- onTool(event.message);
117- break;
32+ };
11833
119- case "complete":
120- onComplete(event.message);
34+ const agent = streamAgent(ctx);
35+ for await (const ev of agent) {
36+ switch (ev.type) {
37+ case "message_end":
38+ case "tool_message_end":
39+ console.log(JSON.stringify(ev.message));
12140 break;
12241 }
12342 }
12443
125- leave("Done.");
44+ leave();
12645 }
src/prompt.ts+231−0
@@ -0,0 +1,231 @@
1+import { readdir } from "node:fs/promises";
2+import { homedir, platform } from "node:os";
3+import { join } from "node:path";
4+import type { Message, ToolCall, ToolResultMessage } from "@mariozechner/pi-ai";
5+import simpleGit, { type StatusResult } from "simple-git";
6+import { parseSkillFrontmatter } from "./shared";
7+
8+const IDENTITY_PROMPT = `# You are "mini-coder", an efficient, elite coding agent.
9+
10+## Behaviour rules:
11+
12+**IMPORTANT**: This is your default behaviour, breaking these rules is unacceptable.
13+
14+- Answer all user requests without guessing, or assuming.
15+- Use recent online information, the current environment, and your training data combined for a complete answer.
16+- Be defensive with existing changes and destructive commands, they could harm your user's changes.
17+- Be efficient, don't get lost with tangents or satisfying your curiosity, root yourself on the user request.
18+- Narrate your edits with small commentary messages during long tasks.
19+- Do not over-scope your work, or add more scope during implementation.
20+- Avoid over-enginnering, hacks or creative solutions. The boring, simple and repliable is always preffered.
21+- Focus on the user's request requirements to answer accurately and efficiently.
22+- Once you've gathered enough information to complete the request, stop exploring and complete it.
23+- Ensure that you fulfill the user's expectation, requirements and contract **exactly**.
24+- Use temp directory for temp files, scripts, plan files, or anything that doesn't match the requested output.
25+- Always verify your changes using compilation, testing, and manual verification when possible.
26+- Do not overstate what changed or what was verified. Never make unverified claims.
27+- Summaries must match the diff.
28+- 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.`;
29+
30+export const MAIN_PROMPT = `${IDENTITY_PROMPT}
31+
32+## Workflow:
33+
34+- Use this if the user did not specify a workflow.
35+
36+1. Read the user's message, understand the request.
37+2. Gather context from the local environment, local code, docs and online related references to the request as needed.
38+3. Plan your changes by breaking down the request into small tasks, resolve open questions with the user to complete your plan with accuracy and detail.
39+4. Use the appropriate tools to execute the plan. Keep the plan up to date and follow it accurately.
40+5. Validate your changes without adding more scope to your work.
41+6. Summarize your changes and completed plan in your final message.
42+
43+## Tool selection heuristic:
44+
45+**Always** follow this logic when deciding your tool usage:
46+
47+- You have limitted context size, the task tool compresses tool loops for you, keeping your context pressure low.
48+- Before **every tool call** consider if you are doing too much in your context window, and favor using the task tool.
49+- If the user's request requires **less** than 3 to 4 shell/edit/read tool calls, use them and complete the request.
50+- Else, the request requires **more** than 4 shell/edit tool calls, use the \`task()\` tool.
51+- This is not optional, if you fill your context with exploration, excessive tool calls, then you have none left to help the user. This is unacceptable.
52+
53+**IMPORTANT: Always make sure you are not falling into a shell tool calling loop!**
54+
55+- This is a clear sign you should be using the task tool. Stop the loop and use the task tool.
56+`;
57+
58+export const TASK_PROMPT = `${IDENTITY_PROMPT}
59+
60+## Workflow:
61+
62+1. Read the user message, understand the request. Gather context as needed to complete the request.
63+2. Plan your changes by breaking down the request into smaller tasks as needed.
64+3. Execute your plan with the appropriate tools.
65+4. Validate your changes without adding scope, and ensuring the user's request is met **exactly** with no deviations.
66+5. Your final message should include a summary of your actions and any diffs from your edits.
67+`;
68+
69+async function getEnvPrompt() {
70+ // TODO: What else do the agents always check before answering every time?
71+ let gitStatus: StatusResult | { nogit: string };
72+ try {
73+ gitStatus = await simpleGit().status();
74+ } catch (_) {
75+ gitStatus = { nogit: "No git repo in this folder." };
76+ }
77+ const envStatus = JSON.stringify(
78+ {
79+ cwd: process.cwd(),
80+ os: platform(),
81+ git: gitStatus,
82+ },
83+ null,
84+ 4,
85+ );
86+
87+ const text = `### Environment status and information
88+
89+\`\`\`json
90+ ${envStatus}
91+\`\`\`
92+`;
93+
94+ return text;
95+}
96+
97+// `AGENTS.md` support: find it in current folder (./AGENTS.md) and a global one. (`.agents/AGENTS.md`)
98+export async function getAGENTSFiles() {
99+ const content: string[] = [];
100+
101+ const globalPath = join(homedir(), ".agents/AGENTS.md");
102+ const globalFile = Bun.file(globalPath);
103+
104+ if (await globalFile.exists()) {
105+ content.push(await globalFile.text());
106+ }
107+
108+ const localPath = join(process.cwd(), "AGENTS.md");
109+ const localFile = Bun.file(localPath);
110+
111+ if (await localFile.exists()) {
112+ content.push(await localFile.text());
113+ }
114+
115+ return content.join("\n\n").trim();
116+}
117+
118+// `SKILLS.md` discovery from [~|.]/agents/skills/*/SKILL.md
119+export async function getSkills(): Promise<string> {
120+ let skillsBlock: string = "";
121+ const skillRoots = [
122+ join(homedir(), ".agents", "skills"),
123+ join(process.cwd(), ".agents", "skills"),
124+ ];
125+
126+ for (const root of skillRoots) {
127+ let entries: string[];
128+
129+ try {
130+ entries = await readdir(root);
131+ } catch {
132+ continue;
133+ }
134+
135+ for (const entry of entries) {
136+ const path = join(root, entry, "SKILL.md");
137+ const file = Bun.file(path);
138+
139+ if (!(await file.exists())) {
140+ continue;
141+ }
142+
143+ const parsed = parseSkillFrontmatter(await file.text());
144+
145+ if (!parsed) {
146+ continue;
147+ }
148+
149+ skillsBlock += `## ${parsed.name}
150+
151+> Absolute file path to read: ${path}
152+
153+${parsed.description}
154+
155+`;
156+ }
157+ }
158+
159+ if (!skillsBlock.length) return "";
160+
161+ const skills = `# Skills
162+
163+- The following skills provide specialized instructions for specific tasks.
164+- Use the shell tool to read a skill's file when the task matches its description.
165+- Use the skill provided absolute file path instead of guessing or constructing one.
166+- Skills can be global (in ~/.agents/skills) or locat to the directory (./agents/skills)
167+
168+${skillsBlock}`;
169+
170+ return skills.trim();
171+}
172+
173+export async function buildSystemPrompt(systemPrompt: string) {
174+ const agentsContent = await getAGENTSFiles();
175+ const skillsContent = await getSkills();
176+ const envStatus = await getEnvPrompt();
177+ let complete = systemPrompt + envStatus;
178+
179+ if (skillsContent) {
180+ complete += `\n${skillsContent}`;
181+ }
182+
183+ if (agentsContent) {
184+ complete += `\n${agentsContent}`;
185+ }
186+
187+ return complete;
188+}
189+
190+export function insertToolUsageReminder(
191+ messages: Message[],
192+ toolMessage: ToolResultMessage,
193+) {
194+ // check for the last 5 tool call assistant messages
195+ // if they are non-`task` tool calls insert the reminder
196+ // as a prefix.
197+ let output = toolMessage.content
198+ .filter((b) => b.type === "text")
199+ .map((b) => b.text)
200+ .join("\n");
201+
202+ const budget = 5;
203+ const toolCalls: ToolCall[] = [];
204+ messages.forEach((m) => {
205+ if (m.role === "assistant") {
206+ const toolCallsBlocks = m.content.filter((b) => b.type === "toolCall");
207+ toolCalls.push(...toolCallsBlocks);
208+ }
209+ });
210+ const recentToolCalls = toolCalls.slice(-budget);
211+ const taskSeen = recentToolCalls.some((call) => call.name === "task");
212+
213+ if (toolCalls.length >= budget && !taskSeen) {
214+ output = `# System reminder:
215+
216+> You are in a shell or edit tool calling loop poluting your context.
217+
218+- Remember your tool choice heuristic.
219+- Plan your next actions, and use the task tool to continue.
220+- If you have completed the user request, complete your answer.
221+
222+---
223+
224+${output}
225+`;
226+ }
227+
228+ toolMessage.content = [{ type: "text", text: output }];
229+
230+ return toolMessage;
231+}
src/shared.ts+9−0
@@ -106,3 +106,12 @@ export function parseSkillFrontmatter(content: string) {
106106
107107 return { name, description };
108108 }
109+
110+export function formatTimestamp(timestampMs: number): string {
111+ return new Date(timestampMs).toLocaleTimeString("en-GB", {
112+ hour: "2-digit",
113+ minute: "2-digit",
114+ second: "2-digit",
115+ hour12: false,
116+ });
117+}
src/tool-task.ts+66−74
@@ -1,15 +1,15 @@
1-import {
2- type Message,
Cut short: this commit's diff is over 1000 lines.
src/tui.ts+61−132
Cut short: this commit's diff is over 1000 lines.
src/types.ts+33−20
Cut short: this commit's diff is over 1000 lines.