@@ -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 }