mini-coder 0.5.13 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +25 -108
  2. package/bin/mc.ts +8 -11
  3. package/bun.lock +79 -269
  4. package/package.json +17 -22
  5. package/src/agent.ts +242 -915
  6. package/src/args.ts +289 -0
  7. package/src/headless.ts +43 -385
  8. package/src/index.ts +29 -836
  9. package/src/oauth.ts +117 -0
  10. package/src/prompt.ts +227 -276
  11. package/src/session.ts +57 -961
  12. package/src/shared.ts +117 -38
  13. package/src/tool-bash.ts +110 -0
  14. package/src/tool-edit.ts +133 -0
  15. package/src/tool-task.ts +114 -0
  16. package/src/tui-components.ts +150 -0
  17. package/src/tui-conversation.ts +262 -0
  18. package/src/tui-editor.ts +29 -0
  19. package/src/tui-overlay.ts +403 -0
  20. package/src/tui.ts +236 -0
  21. package/src/types.ts +160 -0
  22. package/tsconfig.json +17 -0
  23. package/BENCHMARK.md +0 -107
  24. package/LICENSE +0 -9
  25. package/PROGRESS.md +0 -4
  26. package/assets/icon-1-minimal.svg +0 -31
  27. package/assets/icon-2-dark-terminal.svg +0 -48
  28. package/assets/icon-3-gradient-modern.svg +0 -45
  29. package/assets/icon-4-filled-bold.svg +0 -54
  30. package/assets/icon-5-community-badge.svg +0 -63
  31. package/assets/mc-claude-smart.png +0 -0
  32. package/assets/mc-gpt-smart.png +0 -0
  33. package/assets/preview-0-5-0.png +0 -0
  34. package/assets/preview.gif +0 -0
  35. package/benchmark-baseline.sh +0 -15
  36. package/benchmark-loop.sh +0 -19
  37. package/skills-lock.json +0 -15
  38. package/src/cli.ts +0 -134
  39. package/src/errors.ts +0 -15
  40. package/src/git.ts +0 -247
  41. package/src/input.ts +0 -168
  42. package/src/mcp.ts +0 -609
  43. package/src/paths.ts +0 -37
  44. package/src/session-message.ts +0 -393
  45. package/src/settings.ts +0 -449
  46. package/src/skills.ts +0 -271
  47. package/src/submit.ts +0 -371
  48. package/src/text.ts +0 -71
  49. package/src/theme.ts +0 -330
  50. package/src/tool-common.ts +0 -93
  51. package/src/tool-grep.ts +0 -606
  52. package/src/tool-read.ts +0 -313
  53. package/src/tool-shell.ts +0 -1001
  54. package/src/tools.ts +0 -854
  55. package/src/ui/agent.ts +0 -317
  56. package/src/ui/commands.test.ts +0 -913
  57. package/src/ui/commands.ts +0 -834
  58. package/src/ui/conversation.test.ts +0 -585
  59. package/src/ui/conversation.ts +0 -1836
  60. package/src/ui/help.ts +0 -158
  61. package/src/ui/input.test.ts +0 -64
  62. package/src/ui/input.ts +0 -138
  63. package/src/ui/overlay.ts +0 -59
  64. package/src/ui/runtime.ts +0 -69
  65. package/src/ui/status.ts +0 -220
  66. package/src/ui.ts +0 -1190
  67. package/src/version.ts +0 -48
package/src/oauth.ts ADDED
@@ -0,0 +1,117 @@
1
+ import readline from "node:readline";
2
+
3
+ import { getEnvApiKey, getProviders } from "@mariozechner/pi-ai";
4
+ import {
5
+ getOAuthApiKey,
6
+ getOAuthProvider,
7
+ getOAuthProviders,
8
+ type OAuthProviderId,
9
+ } from "@mariozechner/pi-ai/oauth";
10
+ import { AUTH_PATH as AUTH_FILE } from "./shared";
11
+ import type { CliOptions, SavedOAuthCreds } from "./types";
12
+
13
+ export function isOAuthProvider(provider: string): boolean {
14
+ return getOAuthProviders().some(
15
+ (oauthProvider) => oauthProvider.id === provider,
16
+ );
17
+ }
18
+
19
+ export async function getAvailableProviders(): Promise<string[]> {
20
+ const auth = await readCreds();
21
+ const loggedInOAuthProviders = getOAuthProviders()
22
+ .map((provider) => provider.id)
23
+ .filter((provider) => auth[provider]);
24
+ const envKeyProviders = getProviders().filter(
25
+ (provider) => !!getEnvApiKey(provider),
26
+ );
27
+ const providers: string[] = [];
28
+ const providerIds = new Set<string>();
29
+
30
+ for (const provider of [...loggedInOAuthProviders, ...envKeyProviders]) {
31
+ if (providerIds.has(provider)) continue;
32
+
33
+ providers.push(provider);
34
+ providerIds.add(provider);
35
+ }
36
+
37
+ return providers;
38
+ }
39
+
40
+ export async function loginOAuth(provider: OAuthProviderId) {
41
+ const oauthProvider = getOAuthProvider(provider);
42
+ if (!oauthProvider) throw new Error(`Unknown OAuth provider: ${provider}`);
43
+
44
+ const rl = readline.createInterface({
45
+ input: process.stdin,
46
+ output: process.stdout,
47
+ });
48
+
49
+ try {
50
+ const creds = await oauthProvider.login({
51
+ onAuth: ({ url, instructions }) => {
52
+ console.log(`Open: ${url}`);
53
+ if (instructions) console.log(instructions);
54
+ },
55
+ onPrompt: async (prompt) => {
56
+ let answer: string = "";
57
+ await rl.question(prompt.message, (a) => (answer = a));
58
+ return answer;
59
+ },
60
+ onProgress: (message) => console.log(message),
61
+ });
62
+
63
+ await writeCreds({ [provider]: { type: "oauth", ...creds } });
64
+ } finally {
65
+ rl.close();
66
+ }
67
+
68
+ return await readCreds();
69
+ }
70
+
71
+ export async function getApiKey(options: CliOptions) {
72
+ const provider = options.model.provider;
73
+ const auth = await readCreds();
74
+
75
+ if (isOAuthProvider(provider)) {
76
+ const result = await getOAuthApiKey(provider, auth);
77
+ if (result) {
78
+ auth[provider] = { type: "oauth", ...result.newCredentials };
79
+ await writeCreds(auth);
80
+
81
+ return result.apiKey;
82
+ }
83
+ }
84
+
85
+ const envApiKey = getEnvApiKey(provider);
86
+ if (envApiKey) return envApiKey;
87
+
88
+ const knownProviders = getProviders() as string[];
89
+ if (!knownProviders.includes(provider)) {
90
+ if (options.model.api === "openai-completions") {
91
+ // pi-ai requires a truthy apiKey for OpenAI-compatible local providers like Ollama.
92
+ return "dummy";
93
+ }
94
+
95
+ return undefined;
96
+ }
97
+
98
+ throw new Error("Not logged in");
99
+ }
100
+
101
+ export async function readCreds(): Promise<SavedOAuthCreds> {
102
+ const file = Bun.file(AUTH_FILE);
103
+ if (await file.exists()) {
104
+ return JSON.parse(await file.text());
105
+ }
106
+
107
+ return {};
108
+ }
109
+
110
+ async function writeCreds(creds: SavedOAuthCreds) {
111
+ await Bun.write(AUTH_FILE, JSON.stringify(await mergeCreds(creds)));
112
+ }
113
+
114
+ async function mergeCreds(newCreds: SavedOAuthCreds) {
115
+ const oldCreds = await readCreds();
116
+ return { ...oldCreds, ...newCreds };
117
+ }
package/src/prompt.ts CHANGED
@@ -1,314 +1,265 @@
1
- /**
2
- * System prompt construction.
3
- *
4
- * Assembles the full system prompt from the core prompt template plus
5
- * dynamic context: AGENTS.md files, the skill catalog, and the current
6
- * environment block.
7
- *
8
- * @module
9
- */
10
-
11
- import { existsSync, readFileSync } from "node:fs";
12
- import { dirname, join, relative } from "node:path";
13
- import type { GitState } from "./git.ts";
14
- import { canonicalizePath } from "./paths.ts";
15
- import { buildSkillCatalog, type Skill } from "./skills.ts";
16
-
17
- // ---------------------------------------------------------------------------
18
- // Types
19
- // ---------------------------------------------------------------------------
20
-
21
- /** A discovered AGENTS.md file with its content. */
22
- export interface AgentsMdFile {
23
- /** Absolute path to the file. */
24
- path: string;
25
- /** Raw file content. */
26
- content: string;
27
- }
28
-
29
- /** Options for building the system prompt. */
30
- interface BuildSystemPromptOpts {
31
- /** Current working directory. */
32
- cwd: string;
33
- /** Active provider/model identifier. */
34
- modelLabel: string;
35
- /** Normalized host OS label (`linux`, `mac`, or `docker`). */
36
- os: string;
37
- /** Active shell name (for example `bash` or `zsh`). */
38
- shell: string;
39
- /** Whether the active model supports image input. */
40
- supportsImages?: boolean;
41
- /** Git repository state, or `null`/`undefined` if not in a repo. */
42
- git?: GitState | null;
43
- /** Discovered AGENTS.md files, ordered root-to-leaf. */
44
- agentsMd?: AgentsMdFile[];
45
- /** Discovered agent skills. */
46
- skills?: Skill[];
1
+ import { promises } from "node:fs";
2
+ import { readdir } from "node:fs/promises";
3
+ import { homedir, platform } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { Message, ToolCall, ToolResultMessage } from "@mariozechner/pi-ai";
6
+ import simpleGit, { type StatusResult } from "simple-git";
7
+ import { parseSkillFrontmatter } from "./shared";
8
+
9
+ const safetyPrompt = `
10
+ # Safety rules
11
+
12
+ - Answer all user requests without guessing, or assuming. Verify your answers and claims before making them.
13
+ - Use recent online information, the current environment, and your training data combined for a complete answer.
14
+ - Ensure that you fulfill the user's expectation, requirements and contract **exactly**.
15
+ - Be defensive with existing changes and destructive commands, they could harm your user's changes.
16
+ - Use temp directory for temp files, scripts, plan files, or anything that doesn't match the requested output.
17
+ - Do not over-scope your work, or add more scope during implementation.
18
+ - Avoid over-enginnering, hacks or creative solutions. The boring, simple and repliable is always preferred.
19
+ - Do not overstate what changed or what was verified. Summaries must match the diff.
20
+ `;
21
+
22
+ export const MAIN_PROMPT = `# You are "mini-coder", a coding agent.
23
+
24
+ IMPORTANT: Be defensive with existing changes and destructive commands.
25
+ IMPORTANT: Do not overstate what changed or what was verified. Summaries must match the diff.
26
+
27
+ ## Role
28
+ User messages and Tool results may include <system-reminder> tags. These contain system-generated reminders and bear no direct relation to the specific tool result in which they appear.
29
+
30
+ You help users by reading files, executing commands, editing code, and writing new files. Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without unnecessary superlatives, praise, or emotional validation.
31
+
32
+ ## Tool Usage
33
+ - The **task** tool is the preferred way to work. Use it for multi-step research, exploration, or implementation tasks.
34
+ - Use **bash**, **edit**, and other tools only for single, immediate actions.
35
+ - **Do NOT** chain multiple bash/edit calls for multi-step work. Use **task** instead.
36
+ - If a job needs more than one tool call, use the **task** tool instead of chaining individual calls.
37
+
38
+ <example>
39
+ When referencing specific functions or pieces of code, include the pattern \`file_path:line_number\`.
40
+ For example: "Clients are handled in the \`connectToServer\` function in src/services/process.ts:712."
41
+ </example>
42
+
43
+ ## Workflow
44
+ - Stay rooted on the user's request. Don't wander into tangents or explore out of curiosity.
45
+ - Gather only the information needed to fulfill the request, then stop exploring and complete it.
46
+ - Narrate your edits with brief commentary during long tasks so the user can follow progress.
47
+ - Verify your changes via compilation, tests, or manual checks whenever possible.
48
+
49
+ ## Tone
50
+ - Be concise. Use a jovial but motivated colleague tone: direct, never condescending, and never rude.
51
+
52
+ ## Error Handling
53
+ - If a tool call fails or is denied, do NOT re-attempt the exact same call. Analyze why it failed and adjust your approach.
54
+
55
+ IMPORTANT: Never guess or assume. Verify claims before making them.
56
+ IMPORTANT: Do not over-scope work or add scope during implementation.
57
+
58
+ ${safetyPrompt}
59
+ `;
60
+
61
+ export const TASK_PROMPT = `# You are an efficient, elite-level task Agent
62
+
63
+ ## Role
64
+ Execute the assigned task precisely and efficiently. Prioritize correctness over speed. Focus on facts and objective technical details.
65
+
66
+ ## Output Requirements
67
+ - Your final response must include all actions taken and exact diffs of any changes made.
68
+ - Provide a concise report of what was done, what was verified, and any decisions made.
69
+
70
+ ${safetyPrompt}
71
+ `;
72
+
73
+ async function getDir() {
74
+ const ignoreFile = Bun.file(".gitignore");
75
+ let ignoreContent = "";
76
+ if (await ignoreFile.exists()) {
77
+ ignoreContent = await ignoreFile.text();
78
+ }
79
+ const ignored = ignoreContent.split("\n");
80
+ const dir = [];
81
+ const glob = promises.glob(["*", "*/*"], { exclude: ignored });
82
+ for await (const file of glob) {
83
+ dir.push(file);
84
+ }
85
+ return dir;
47
86
  }
48
87
 
49
- // ---------------------------------------------------------------------------
50
- // AGENTS.md discovery
51
- // ---------------------------------------------------------------------------
52
-
53
- /** File name to look for during the AGENTS.md walk. */
54
- const AGENT_FILENAME = "AGENTS.md";
55
-
56
- /** Resolve the AGENTS.md scan root from git/home/env inputs. */
57
- export function resolveAgentsScanRoot(
58
- _cwd: string,
59
- gitRoot: string | null,
60
- homeDir: string,
61
- agentsRootEnv = process.env.MC_AGENTS_ROOT,
62
- ): string {
63
- if (gitRoot) {
64
- return canonicalizePath(gitRoot);
88
+ async function getEnvPrompt() {
89
+ // TODO: What else do the agents always check before answering every time?
90
+ let gitStatus: StatusResult | { nogit: string };
91
+ try {
92
+ gitStatus = await simpleGit().status();
93
+ } catch (_) {
94
+ gitStatus = { nogit: "No git repo in this folder." };
65
95
  }
66
- if (agentsRootEnv === "/") {
67
- return canonicalizePath("/");
96
+ const envKeys = ["PATH", "USER", "LANG", "HOME", "SHELL", "BUN_INSTALL"];
97
+ const env: Record<string, string> = {};
98
+ for (const key of envKeys) {
99
+ const v = Bun.env[key];
100
+
101
+ if (v !== undefined) {
102
+ env[key] = v;
103
+ }
68
104
  }
69
- return canonicalizePath(homeDir);
70
- }
71
105
 
72
- function isWithinScanRoot(path: string, scanRoot: string): boolean {
73
- const relativePath = relative(scanRoot, path);
74
- return (
75
- relativePath === "" ||
76
- (!relativePath.startsWith("..") && relativePath !== "..")
106
+ const envStatus = JSON.stringify(
107
+ {
108
+ os: platform(),
109
+ env,
110
+ cwd: process.cwd(),
111
+ dir: await getDir(),
112
+ git: gitStatus,
113
+ },
114
+ null,
115
+ 4,
77
116
  );
78
- }
79
117
 
80
- function collectAgentsSearchDirs(start: string, root: string): string[] {
81
- if (!isWithinScanRoot(start, root)) {
82
- return [start];
83
- }
118
+ const text = `### Environment status and information
84
119
 
85
- const dirs: string[] = [];
86
- let current = start;
87
- while (true) {
88
- dirs.push(current);
89
- if (current === root) {
90
- return dirs.reverse();
91
- }
120
+ \`\`\`json
121
+ ${envStatus}
122
+ \`\`\`
123
+ `;
92
124
 
93
- const parent = dirname(current);
94
- if (parent === current) {
95
- return dirs.reverse();
96
- }
97
- current = parent;
98
- }
125
+ return text;
99
126
  }
100
127
 
101
- function readAgentsMdFile(dir: string): AgentsMdFile | null {
102
- const filePath = join(dir, AGENT_FILENAME);
103
- if (!existsSync(filePath)) {
104
- return null;
128
+ // `AGENTS.md` support: find it in current folder (./AGENTS.md) and a global one. (`.agents/AGENTS.md`)
129
+ export async function getAGENTSFiles() {
130
+ const content: string[] = [];
131
+
132
+ const globalPath = join(homedir(), ".agents/AGENTS.md");
133
+ const globalFile = Bun.file(globalPath);
134
+
135
+ if (await globalFile.exists()) {
136
+ content.push(await globalFile.text());
105
137
  }
106
138
 
107
- try {
108
- return {
109
- path: filePath,
110
- content: readFileSync(filePath, "utf-8"),
111
- };
112
- } catch {
113
- return null;
139
+ const localPath = join(process.cwd(), "AGENTS.md");
140
+ const localFile = Bun.file(localPath);
141
+
142
+ if (await localFile.exists()) {
143
+ content.push(await localFile.text());
114
144
  }
145
+
146
+ return content.join("\n\n").trim();
115
147
  }
116
148
 
117
- /**
118
- * Walk from `cwd` up to `scanRoot`, collecting AGENTS.md files.
119
- *
120
- * Also checks `globalAgentsDir` for global agent instructions when provided.
121
- * Results are ordered root-to-leaf (general → specific), with global
122
- * instructions first when present.
123
- *
124
- * @param cwd - Starting directory for the walk.
125
- * @param scanRoot - Uppermost directory to include in the walk.
126
- * @param globalAgentsDir - Optional directory for global agent instructions (e.g. `~/.agents/`).
127
- * @returns Array of {@link AgentsMdFile} records, ordered general → specific.
128
- */
129
- export function discoverAgentsMd(
130
- cwd: string,
131
- scanRoot: string,
132
- globalAgentsDir?: string,
133
- ): AgentsMdFile[] {
134
- const root = canonicalizePath(scanRoot);
135
- const start = canonicalizePath(cwd);
136
- const files: AgentsMdFile[] = [];
137
-
138
- if (globalAgentsDir) {
139
- const globalFile = readAgentsMdFile(globalAgentsDir);
140
- if (globalFile) {
141
- files.push(globalFile);
149
+ // `SKILLS.md` discovery from [~|.]/agents/skills/*/SKILL.md
150
+ export async function getSkills(): Promise<string> {
151
+ let skillsBlock: string = "";
152
+ const skillRoots = [
153
+ join(homedir(), ".agents", "skills"),
154
+ join(process.cwd(), ".agents", "skills"),
155
+ ];
156
+
157
+ for (const root of skillRoots) {
158
+ let entries: string[];
159
+
160
+ try {
161
+ entries = await readdir(root);
162
+ } catch {
163
+ continue;
142
164
  }
143
- }
144
165
 
145
- for (const dir of collectAgentsSearchDirs(start, root)) {
146
- const agentsFile = readAgentsMdFile(dir);
147
- if (agentsFile) {
148
- files.push(agentsFile);
166
+ for (const entry of entries) {
167
+ const path = join(root, entry, "SKILL.md");
168
+ const file = Bun.file(path);
169
+
170
+ if (!(await file.exists())) {
171
+ continue;
172
+ }
173
+
174
+ const parsed = parseSkillFrontmatter(await file.text());
175
+
176
+ if (!parsed) {
177
+ continue;
178
+ }
179
+
180
+ skillsBlock += `## ${parsed.name}
181
+
182
+ > Absolute file path to read: ${path}
183
+
184
+ ${parsed.description}
185
+
186
+ `;
149
187
  }
150
188
  }
151
189
 
152
- return files;
153
- }
190
+ if (!skillsBlock.length) return "";
154
191
 
155
- // ---------------------------------------------------------------------------
156
- // Git line formatting
157
- // ---------------------------------------------------------------------------
158
-
159
- /**
160
- * Format a git state snapshot into a single-line string for the environment block.
161
- *
162
- * Fields are omitted when their values are zero. The git line format:
163
- * `Git: branch main | 3 staged, 1 modified, 2 untracked | +5 −2 vs origin/main`
164
- * where the trailing upstream label reflects the repository's actual tracking ref.
165
- *
166
- * @param state - The git state to format.
167
- * @returns Formatted git status line.
168
- */
169
- export function formatGitLine(state: GitState): string {
170
- const parts: string[] = [`Git: branch ${state.branch}`];
171
-
172
- // Working tree counts
173
- const counts: string[] = [];
174
- if (state.staged > 0) counts.push(`${state.staged} staged`);
175
- if (state.modified > 0) counts.push(`${state.modified} modified`);
176
- if (state.untracked > 0) counts.push(`${state.untracked} untracked`);
177
- if (counts.length > 0) parts.push(counts.join(", "));
178
-
179
- // Ahead/behind
180
- if (state.ahead > 0 || state.behind > 0) {
181
- const ab: string[] = [];
182
- if (state.ahead > 0) ab.push(`+${state.ahead}`);
183
- if (state.behind > 0) ab.push(`\u2212${state.behind}`);
184
- const upstream = state.upstream ? ` vs ${state.upstream}` : "";
185
- parts.push(`${ab.join(" ")}${upstream}`);
186
- }
192
+ const skills = `# Skills
193
+
194
+ - The following skills provide specialized instructions for specific tasks.
195
+ - Use the bash tool to read a skill's file when the task matches its description.
196
+ - Use the skill provided absolute file path instead of guessing or constructing one.
197
+ - Skills can be global (in ~/.agents/skills) or local to the directory (./agents/skills)
187
198
 
188
- return parts.join(" | ");
199
+ ${skillsBlock}`;
200
+
201
+ return skills.trim();
189
202
  }
190
203
 
191
- // ---------------------------------------------------------------------------
192
- // Core prompt template
193
- // ---------------------------------------------------------------------------
194
-
195
- function buildCorePrompt(opts: BuildSystemPromptOpts): string {
196
- const lines = [
197
- "You are mini-coder, the best software engineering assistant in the world.",
198
- "",
199
- "The current environment is:",
200
- `- LLM in use: ${opts.modelLabel}`,
201
- `- OS: ${opts.os}`,
202
- `- Current working directory: ${opts.cwd}`,
203
- ];
204
+ export async function buildSystemPrompt(systemPrompt: string) {
205
+ const agentsContent = await getAGENTSFiles();
206
+ const skillsContent = await getSkills();
207
+ let complete = systemPrompt;
204
208
 
205
- if (opts.git) {
206
- lines.push(`- ${formatGitLine(opts.git)}`);
209
+ if (skillsContent) {
210
+ complete += `\n${skillsContent}`;
207
211
  }
208
212
 
209
- lines.push(
210
- `- Shell: ${opts.shell}. Use \`command -v <name>\` to check what is available to you; do not assume environment support.`,
211
- "- Read: Read a text file from disk with offset/limit support.",
212
- "- Grep: Search file contents with ripgrep-style options and structured results.",
213
- "- Edit: Safe exact-text replacement in a single file.",
214
- );
215
-
216
- if (opts.supportsImages) {
217
- lines.push("- Read Image: Read an image from disk.");
213
+ if (agentsContent) {
214
+ complete += `\n${agentsContent}`;
218
215
  }
219
216
 
220
- lines.push(
221
- "",
222
- "## Core working style:",
223
- "",
224
- "- Be concise, direct, and useful.",
225
- "- Use a casual, solution-oriented technical tone. Avoid fluff and performative apologies.",
226
- "- When the user gives a clear command, do it without adding extra work they did not ask for.",
227
- "- Prefer the minimal implementation that satisfies the request exactly.",
228
- "- Use YAGNI. Avoid speculative abstractions, future-proofing, and unnecessary compatibility shims.",
229
- "- Preserve working behavior where possible. Prefer targeted fixes over rewrites.",
230
- "- Be thorough, use fresh eyes and internal analysis before taking action.",
231
- "- Make informed decisions based on the available information and best practices.",
232
- "- Always verify the result of your actions.",
233
- "",
234
- "### Using the shell tool:",
235
- "",
236
- "- Always execute shell commands in non-interactive mode.",
237
- "- Use the appropriate commands and package managers for the specified operating system.",
238
- "- Don't assume the environment supports all commands; check before using them.",
239
- "- Avoid destructive commands that can discard changes or override edits.",
240
- "",
241
- "### Choosing tools:",
242
- "",
243
- "- Prefer `read` for reading file contents instead of `cat`, `sed`, `head`, or `tail`.",
244
- "- Prefer `grep` for content search instead of raw `grep` / `rg`.",
245
- "- Use shell `ls` and `fd` for lightweight exploration when you just need to inspect directories or discover candidate files.",
246
- "",
247
- "### Working with code:",
248
- "",
249
- "- Describe changes before implementing them",
250
- "- Prefer boring dependable solutions over clever ones",
251
- "- Avoid creating extra files, systems or documentation outside of what was asked.",
252
- "- Check requirements, and plan your changes before editing code.",
253
- "- Implement the necessary changes, following good practices and proper error handling.",
254
- "- Always verify your changes using compilation, testing, and manual verification when possible.",
255
- "- When verifying with build or test commands, avoid leaving generated binaries or scratch artifacts in the requested output location; use temporary paths or remove them before finishing.",
256
- "- Do not leave helpers, tests, or any other form of temporary files; clean up after yourself and leave no trace.",
257
- "- Ensure you match the requested output exactly. This applies to file names, directory structure, number of files, output formats, and all other details.",
258
- '- "Polish" is not optional; it counts just as much as solving the task.',
259
- "",
260
- "### Task management",
261
- "",
262
- "- Use `todoWrite` proactively for multi-step or non-trivial tasks.",
263
- "- Capture new requirements in the todo list as soon as you understand them.",
264
- "- Use `todoRead` when you need to inspect the current list before updating it or when the user asks for the current plan/status.",
265
- "- Keep the todo list up-to-date above all; mark tasks `in_progress` before starting them and `completed` as soon as verification succeeds.",
266
- "- A todo item is only complete if the requested work is actually finished and verified to the degree the task requires.",
267
- "- Use `cancelled` to remove tasks that are no longer relevant.",
268
- "- Skip todo tools for single trivial tasks and purely conversational/informational requests.",
269
- '- You have the option to delegate tasks to copies of yourself with `mc -p "subtask prompt"` in the shell.',
270
- "- Delegate when you are orchestrating a large to-do/plan execution.",
271
- "",
272
- );
217
+ return complete;
218
+ }
273
219
 
274
- return lines.join("\n");
220
+ export async function injectEnvReminder(): Promise<string> {
221
+ const envStatus = await getEnvPrompt();
222
+ return `<system-reminder>\n${envStatus}\n</system-reminder>`;
275
223
  }
276
224
 
277
- // ---------------------------------------------------------------------------
278
- // System prompt assembly
279
- // ---------------------------------------------------------------------------
280
-
281
- /**
282
- * Build the full system prompt.
283
- *
284
- * Assembly order:
285
- * 1. Core prompt template (including the current environment block)
286
- * 2. AGENTS.md content (project-specific)
287
- * 3. Skills catalog (XML)
288
- *
289
- * @param opts - Prompt construction options.
290
- * @returns The assembled system prompt string.
291
- */
292
- export function buildSystemPrompt(opts: BuildSystemPromptOpts): string {
293
- const sections: string[] = [buildCorePrompt(opts)];
294
-
295
- // 2. AGENTS.md content
296
- if (opts.agentsMd && opts.agentsMd.length > 0) {
297
- const agentsSection = [];
298
- for (const file of opts.agentsMd) {
299
- agentsSection.push(`## ${file.path}`);
300
- agentsSection.push("");
301
- agentsSection.push(file.content);
302
- agentsSection.push("");
225
+ export function insertToolUsageReminder(
226
+ messages: Message[],
227
+ toolMessage: ToolResultMessage,
228
+ ) {
229
+ // check for the last 5 tool call assistant messages
230
+ // if they are non-`task` tool calls insert the reminder
231
+ // as a prefix.
232
+ let output = toolMessage.content
233
+ .filter((b) => b.type === "text")
234
+ .map((b) => b.text)
235
+ .join("\n");
236
+
237
+ const budget = 3;
238
+ const toolCalls: ToolCall[] = [];
239
+ const lastUserMessageIndex = messages.findLastIndex((m) => m.role === "user");
240
+ const messagesSinceLastUser = messages.slice(lastUserMessageIndex + 1);
241
+
242
+ messagesSinceLastUser.forEach((m) => {
243
+ if (m.role === "assistant") {
244
+ const toolCallsBlocks = m.content.filter((b) => b.type === "toolCall");
245
+ toolCalls.push(...toolCallsBlocks);
303
246
  }
304
- sections.push(agentsSection.join("\n").trimEnd());
305
- }
247
+ });
248
+ const recentToolCalls = toolCalls.slice(-budget);
249
+ const taskSeen = recentToolCalls.some((call) => call.name === "task");
250
+
251
+ if (toolCalls.length >= budget && !taskSeen) {
252
+ output = `<system-reminder>
253
+ You are currently making repeated individual tool calls. This fragments context and reduces efficiency.
306
254
 
307
- // 3. Skills catalog
308
- if (opts.skills && opts.skills.length > 0) {
309
- const catalog = buildSkillCatalog(opts.skills);
310
- if (catalog) sections.push(catalog);
255
+ - Stop and plan: consolidate remaining steps into a single **task** tool call.
256
+ - If the user request is fully completed, stop calling tools and provide your final answer.
257
+ </system-reminder>
258
+
259
+ ${output}`;
311
260
  }
312
261
 
313
- return sections.join("\n\n");
262
+ toolMessage.content = [{ type: "text", text: output }];
263
+
264
+ return toolMessage;
314
265
  }