xonecas.io
64875
Mc

mini-coder / commit 4d5d11c

fix:context tracking

xonecas2026-02-20 4d5d11c7f738188c88f4020d3a48b254c132ff54 parent 8a8ff87

9 files changed

TODO.md+3−24
@@ -1,23 +1,3 @@
1-# `cwd` leaks into tool schemas
2-
3-All file tools expose `cwd` in their Zod schema, so the LLM sees it as a callable parameter. It's always injected by `withCwdDefault()` and should be hidden from the model.
4-
5-Causes confusion
6-
7-```
8-▶ create a readme file and introduce yourself
9- ✎ create README.md
10- ✖ EACCES: permission denied, mkdir '/root/src/mini-coder'
11- ✎ create README.md
12- ✖ EACCES: permission denied, mkdir '/home/sandbox'
13- $ $ pwd
14- ✔ 0
15- │ /home/xonecas/src/mini-coder
16- ✎ create README.md
17-```
18-
19----
20-
211 # Fix implementation error
222
233 1. The DB only saves text — agent.ts:412–429 strips tool parts before writing to SQLite. That's the right design for persistence, but coreHistory in memory is never trimmed.
@@ -45,11 +25,10 @@ Besides undoing the conversation turn, it should restore some snapshot, using gi
4525
4626 ---
4727
48-# Fix tools not saved to db.
28+# Tools output
4929
50-- We are breaking existing sessions on resume, update the db and code to store the full session messages.
51-
52----
30+Insert/read/edit/write/grep all were changed with the hashline feature, outputs needs
31+to be re-done to match our style of nice formatted data.
5332
5433 Subagent needs visibity on the ui somehow... that accounts for multiple in parallel... Needs planning, maybe a tree view showing the subagent's tool calls before the output.
5534
src/agent/agent.ts+5−6
@@ -14,7 +14,7 @@ import {
1414 restoreTerminal,
1515 writeln,
1616 } from "../cli/output.ts";
17-import { resolveModel } from "../llm-api/providers.ts";
17+import { getContextWindow, resolveModel } from "../llm-api/providers.ts";
1818 import { type CoreMessage, runTurn } from "../llm-api/turn.ts";
1919 import type { Message, ToolDef } from "../llm-api/types.ts";
2020 import { connectMcpServer } from "../mcp/client.ts";
@@ -409,10 +409,8 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
409409 signal: abortController.signal,
410410 });
411411
412- const { inputTokens, outputTokens, newMessages } = await renderTurn(
413- events,
414- spinner,
415- );
412+ const { inputTokens, outputTokens, contextTokens, newMessages } =
413+ await renderTurn(events, spinner);
416414 process.removeListener("SIGINT", onSigInt);
417415
418416 // newMessages are raw ModelMessage objects — push directly into coreHistory
@@ -460,7 +458,8 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
460458 gitBranch: branch,
461459 inputTokens,
462460 outputTokens,
463- contextPercent: null,
461+ contextTokens,
462+ contextWindow: getContextWindow(currentModel),
464463 });
465464 }
466465 }
src/cli/output.ts+22−5
@@ -389,11 +389,13 @@ export async function renderTurn(
389389 ): Promise<{
390390 inputTokens: number;
391391 outputTokens: number;
392+ contextTokens: number;
392393 newMessages: import("../llm-api/turn.ts").CoreMessage[];
393394 }> {
394395 let inText = false;
395396 let inputTokens = 0;
396397 let outputTokens = 0;
398+ let contextTokens = 0;
397399 let newMessages: import("../llm-api/turn.ts").CoreMessage[] = [];
398400
399401 for await (const event of events) {
@@ -434,6 +436,7 @@ export async function renderTurn(
434436 spinner.stop();
435437 inputTokens = event.inputTokens;
436438 outputTokens = event.outputTokens;
439+ contextTokens = event.contextTokens;
437440 newMessages = event.messages;
438441 break;
439442 }
@@ -451,7 +454,7 @@ export async function renderTurn(
451454 }
452455 }
453456
454- return { inputTokens, outputTokens, newMessages };
457+ return { inputTokens, outputTokens, contextTokens, newMessages };
455458 }
456459
457460 // ─── Status bar ───────────────────────────────────────────────────────────────
@@ -465,7 +468,8 @@ export function renderStatusBar(opts: {
465468 gitBranch: string | null;
466469 inputTokens: number;
467470 outputTokens: number;
468- contextPercent: number | null;
471+ contextTokens: number;
472+ contextWindow: number | null;
469473 }): void {
470474 const cols = (process.stderr as NodeJS.WriteStream).columns ?? 80;
471475
@@ -479,9 +483,22 @@ export function renderStatusBar(opts: {
479483 c.dim(`↑${fmtTokens(opts.inputTokens)} ↓${fmtTokens(opts.outputTokens)}`),
480484 );
481485 }
482- if (opts.contextPercent !== null) {
483- const pct = `${opts.contextPercent}%`;
484- right.push(opts.contextPercent > 80 ? c.red(pct) : c.dim(pct));
486+ if (opts.contextTokens > 0) {
487+ const ctxRaw = fmtTokens(opts.contextTokens);
488+ if (opts.contextWindow !== null) {
489+ const pct = Math.round((opts.contextTokens / opts.contextWindow) * 100);
490+ const ctxMax = fmtTokens(opts.contextWindow);
491+ const pctStr = `${pct}%`;
492+ const colored =
493+ pct >= 90
494+ ? c.red(pctStr)
495+ : pct >= 75
496+ ? c.yellow(pctStr)
497+ : c.dim(pctStr);
498+ right.push(c.dim(`ctx ${ctxRaw}/${ctxMax} `) + colored);
499+ } else {
500+ right.push(c.dim(`ctx ${ctxRaw}`));
501+ }
485502 }
486503 if (opts.gitBranch) right.push(c.dim(`⎇ ${opts.gitBranch}`));
487504
src/llm-api/providers.ts+39−0
@@ -129,6 +129,45 @@ function directGoogle() {
129129 return _directGoogle;
130130 }
131131
132+// ─── Context window table ─────────────────────────────────────────────────────
133+// Maps model ID substrings (matched in order) to token limits.
134+// Covers all Zen models plus common direct-provider model families.
135+// When a model isn't matched, callers fall back to showing raw token counts.
136+
137+const CONTEXT_WINDOW_TABLE: Array<[pattern: RegExp, tokens: number]> = [
138+ // Claude — all modern models are 200k
139+ [/^claude-/, 200_000],
140+ // Gemini — all Gemini 3.x are 1M
141+ [/^gemini-/, 1_000_000],
142+ // GPT-5 series — 128k
143+ [/^gpt-5/, 128_000],
144+ // GPT-4o / GPT-4 series — 128k
145+ [/^gpt-4/, 128_000],
146+ // Kimi K2 / K2.5 — 262k
147+ [/^kimi-k2/, 262_000],
148+ // MiniMax M2 — 196k
149+ [/^minimax-m2/, 196_000],
150+ // GLM 5 / 4.x — 128k
151+ [/^glm-/, 128_000],
152+ // Qwen3 Coder — 131k (Qwen3 standard)
153+ [/^qwen3-/, 131_000],
154+];
155+
156+/**
157+ * Return the known context window size (in tokens) for a model string.
158+ * Accepts either a bare model ID or a "provider/model-id" string.
159+ * Returns null when the model is unknown.
160+ */
161+export function getContextWindow(modelString: string): number | null {
162+ const modelId = modelString.includes("/")
163+ ? modelString.slice(modelString.indexOf("/") + 1)
164+ : modelString;
165+ for (const [pattern, tokens] of CONTEXT_WINDOW_TABLE) {
166+ if (pattern.test(modelId)) return tokens;
167+ }
168+ return null;
169+}
170+
132171 // ─── Public API ───────────────────────────────────────────────────────────────
133172
134173 /**
src/llm-api/turn.ts+6−0
@@ -68,6 +68,10 @@ export async function* runTurn(options: {
6868
6969 let inputTokens = 0;
7070 let outputTokens = 0;
71+ // Overwritten each step — after all steps this holds the last step's input
72+ // token count, which approximates context window usage (each step re-sends
73+ // the full conversation history, so later steps have larger prompts).
74+ let contextTokens = 0;
7175
7276 try {
7377 const streamOpts: StreamTextOptions = {
@@ -78,6 +82,7 @@ export async function* runTurn(options: {
7882 onStepFinish: (step: StepResult<ToolSet>) => {
7983 inputTokens += step.usage?.inputTokens ?? 0;
8084 outputTokens += step.usage?.outputTokens ?? 0;
85+ contextTokens = step.usage?.inputTokens ?? contextTokens;
8186 },
8287 ...(systemPrompt ? { system: systemPrompt } : {}),
8388 ...(signal ? { abortSignal: signal } : {}),
@@ -162,6 +167,7 @@ export async function* runTurn(options: {
162167 type: "turn-complete",
163168 inputTokens,
164169 outputTokens,
170+ contextTokens,
165171 // Pass raw ModelMessage objects — no conversion; they are fed back to
166172 // streamText on the next turn and must stay in their original shape.
167173 messages: newMessages,
src/llm-api/types.ts+2−0
@@ -70,6 +70,8 @@ export interface TurnCompleteEvent {
7070 type: "turn-complete";
7171 inputTokens: number;
7272 outputTokens: number;
73+ /** Input tokens of the final step — equals the actual context window usage. */
74+ contextTokens: number;
7375 /**
7476 * Raw AI SDK ModelMessage objects generated this turn.
7577 * These are passed directly back to streamText on subsequent turns —
src/tools/edit.ts+108−108
@@ -5,128 +5,128 @@ import { generateDiff } from "./diff.ts";
55 import { findLineByHash } from "./hashline.ts";
66
77 const EditSchema = z.object({
8- path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9- startAnchor: z
10- .string()
11- .describe('Start anchor from a prior read/grep, e.g. "11:a3"'),
12- endAnchor: z
13- .string()
14- .optional()
15- .describe(
16- 'End anchor (inclusive), e.g. "33:0e". Omit to target only the startAnchor line.',
17- ),
18- newContent: z
19- .string()
20- .optional()
21- .describe(
22- "Replacement text. Omit or pass empty string to delete the range.",
23- ),
8+ path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9+ startAnchor: z
10+ .string()
11+ .describe('Start anchor from a prior read/grep, e.g. "11:a3"'),
12+ endAnchor: z
13+ .string()
14+ .optional()
15+ .describe(
16+ 'End anchor (inclusive), e.g. "33:0e". Omit to target only the startAnchor line.',
17+ ),
18+ newContent: z
19+ .string()
20+ .optional()
21+ .describe(
22+ "Replacement text. Omit or pass empty string to delete the range.",
23+ ),
2424 });
2525
2626 type EditInput = z.infer<typeof EditSchema> & { cwd?: string };
2727
2828 export interface EditOutput {
29- path: string;
30- diff: string;
29+ path: string;
30+ diff: string;
3131 }
3232
3333 const HASH_NOT_FOUND_ERROR =
34- "Hash not found. Re-read the file to get current anchors.";
34+ "Hash not found. Re-read the file to get current anchors.";
3535
3636 export const editTool: ToolDef<EditInput, EditOutput> = {
37- name: "edit",
38- description:
39- "Replace or delete a range of lines in an existing file using hashline anchors. " +
40- 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
41- "Provide startAnchor alone to target a single line, or add endAnchor for a range. " +
42- "Set newContent to the replacement text, or omit it to delete the range. " +
43- "To create a file use `write`. To insert without replacing any lines use `insert`.",
44- schema: EditSchema,
45- execute: async (input) => {
46- const cwd = input.cwd ?? process.cwd();
47- const filePath = input.path.startsWith("/")
48- ? input.path
49- : join(cwd, input.path);
50-
51- const relPath = relative(cwd, filePath);
52-
53- const file = Bun.file(filePath);
54- if (!(await file.exists())) {
55- throw new Error(
56- `File not found: "${relPath}". To create a new file use the \`write\` tool.`,
57- );
58- }
59-
60- const start = parseAnchor(input.startAnchor, "startAnchor");
61- const end = input.endAnchor
62- ? parseAnchor(input.endAnchor, "endAnchor")
63- : null;
64-
65- if (end && end.line < start.line) {
66- throw new Error(
67- "endAnchor line number must be >= startAnchor line number.",
68- );
69- }
70-
71- const original = await file.text();
72- const lines = original.split("\n");
73-
74- const startLine = findLineByHash(lines, start.hash, start.line);
75- if (!startLine) throw new Error(HASH_NOT_FOUND_ERROR);
76-
77- let endLine = startLine;
78- if (end) {
79- const resolvedEnd = findLineByHash(lines, end.hash, end.line);
80- if (!resolvedEnd) throw new Error(HASH_NOT_FOUND_ERROR);
81- endLine = resolvedEnd;
82- }
83- if (endLine < startLine) {
84- throw new Error("endAnchor resolves before startAnchor.");
85- }
86-
87- const replacement =
88- input.newContent === undefined || input.newContent === ""
89- ? []
90- : input.newContent.split("\n");
91-
92- const updatedLines = [
93- ...lines.slice(0, startLine - 1),
94- ...replacement,
95- ...lines.slice(endLine),
96- ];
97-
98- const updated = updatedLines.join("\n");
99- await Bun.write(filePath, updated);
100-
101- const diff = generateDiff(relPath, original, updated);
102- return { path: relPath, diff };
103- },
37+ name: "edit",
38+ description:
39+ "Replace or delete a range of lines in an existing file using hashline anchors. " +
40+ 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
41+ "Provide startAnchor alone to target a single line, or add endAnchor for a range. " +
42+ "Set newContent to the replacement text, or omit it to delete the range. " +
43+ "To create a file use `write`. To insert without replacing any lines use `insert`.",
44+ schema: EditSchema,
45+ execute: async (input) => {
46+ const cwd = input.cwd ?? process.cwd();
47+ const filePath = input.path.startsWith("/")
48+ ? input.path
49+ : join(cwd, input.path);
50+
51+ const relPath = relative(cwd, filePath);
52+
53+ const file = Bun.file(filePath);
54+ if (!(await file.exists())) {
55+ throw new Error(
56+ `File not found: "${relPath}". To create a new file use the \`write\` tool.`,
57+ );
58+ }
59+
60+ const start = parseAnchor(input.startAnchor, "startAnchor");
61+ const end = input.endAnchor
62+ ? parseAnchor(input.endAnchor, "endAnchor")
63+ : null;
64+
65+ if (end && end.line < start.line) {
66+ throw new Error(
67+ "endAnchor line number must be >= startAnchor line number.",
68+ );
69+ }
70+
71+ const original = await file.text();
72+ const lines = original.split("\n");
73+
74+ const startLine = findLineByHash(lines, start.hash, start.line);
75+ if (!startLine) throw new Error(HASH_NOT_FOUND_ERROR);
76+
77+ let endLine = startLine;
78+ if (end) {
79+ const resolvedEnd = findLineByHash(lines, end.hash, end.line);
80+ if (!resolvedEnd) throw new Error(HASH_NOT_FOUND_ERROR);
81+ endLine = resolvedEnd;
82+ }
83+ if (endLine < startLine) {
84+ throw new Error("endAnchor resolves before startAnchor.");
85+ }
86+
87+ const replacement =
88+ input.newContent === undefined || input.newContent === ""
89+ ? []
90+ : input.newContent.split("\n");
91+
92+ const updatedLines = [
93+ ...lines.slice(0, startLine - 1),
94+ ...replacement,
95+ ...lines.slice(endLine),
96+ ];
97+
98+ const updated = updatedLines.join("\n");
99+ await Bun.write(filePath, updated);
100+
101+ const diff = generateDiff(relPath, original, updated);
102+ return { path: relPath, diff };
103+ },
104104 };
105105
106106 interface ParsedAnchor {
107- line: number;
108- hash: string;
107+ line: number;
108+ hash: string;
109109 }
110110
111111 function parseAnchor(value: string, name: string): ParsedAnchor {
112- const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
113- if (!match) {
114- throw new Error(
115- `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
116- );
117- }
118-
119- const line = Number(match[1]);
120- if (!Number.isInteger(line) || line < 1) {
121- throw new Error(`Invalid ${name} line number.`);
122- }
123-
124- const hash = match[2];
125- if (!hash) {
126- throw new Error(
127- `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
128- );
129- }
130-
131- return { line, hash: hash.toLowerCase() };
112+ const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
113+ if (!match) {
114+ throw new Error(
115+ `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
116+ );
117+ }
118+
119+ const line = Number(match[1]);
120+ if (!Number.isInteger(line) || line < 1) {
121+ throw new Error(`Invalid ${name} line number.`);
122+ }
123+
124+ const hash = match[2];
125+ if (!hash) {
126+ throw new Error(
127+ `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
128+ );
129+ }
130+
131+ return { line, hash: hash.toLowerCase() };
132132 }
src/tools/insert.ts+78−78
@@ -5,98 +5,98 @@ import { generateDiff } from "./diff.ts";
55 import { findLineByHash } from "./hashline.ts";
66
77 const InsertSchema = z.object({
8- path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9- anchor: z
10- .string()
11- .describe('Anchor line from a prior read/grep, e.g. "11:a3"'),
12- position: z
13- .enum(["before", "after"])
14- .describe('Insert the content "before" or "after" the anchor line'),
15- content: z.string().describe("Text to insert"),
8+ path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9+ anchor: z
10+ .string()
11+ .describe('Anchor line from a prior read/grep, e.g. "11:a3"'),
12+ position: z
13+ .enum(["before", "after"])
14+ .describe('Insert the content "before" or "after" the anchor line'),
15+ content: z.string().describe("Text to insert"),
1616 });
1717
1818 type InsertInput = z.infer<typeof InsertSchema> & { cwd?: string };
1919
2020 export interface InsertOutput {
21- path: string;
22- diff: string;
21+ path: string;
22+ diff: string;
2323 }
2424
2525 const HASH_NOT_FOUND_ERROR =
26- "Hash not found. Re-read the file to get current anchors.";
26+ "Hash not found. Re-read the file to get current anchors.";
2727
2828 export const insertTool: ToolDef<InsertInput, InsertOutput> = {
29- name: "insert",
30- description:
31- "Insert new lines before or after an anchor line in an existing file. " +
32- "The anchor line itself is not modified. " +
33- 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
34- "To replace or delete lines use `edit`. To create a file use `write`.",
35- schema: InsertSchema,
36- execute: async (input) => {
37- const cwd = input.cwd ?? process.cwd();
38- const filePath = input.path.startsWith("/")
39- ? input.path
40- : join(cwd, input.path);
41-
42- const relPath = relative(cwd, filePath);
43-
44- const file = Bun.file(filePath);
45- if (!(await file.exists())) {
46- throw new Error(
47- `File not found: "${relPath}". To create a new file use the \`write\` tool.`,
48- );
49- }
50-
51- const parsed = parseAnchor(input.anchor);
52-
53- const original = await file.text();
54- const lines = original.split("\n");
55-
56- const anchorLine = findLineByHash(lines, parsed.hash, parsed.line);
57- if (!anchorLine) throw new Error(HASH_NOT_FOUND_ERROR);
58-
59- const insertAt = input.position === "before" ? anchorLine - 1 : anchorLine;
60- const insertLines = input.content.split("\n");
61-
62- const updatedLines = [
63- ...lines.slice(0, insertAt),
64- ...insertLines,
65- ...lines.slice(insertAt),
66- ];
67-
68- const updated = updatedLines.join("\n");
69- await Bun.write(filePath, updated);
70-
71- const diff = generateDiff(relPath, original, updated);
72- return { path: relPath, diff };
73- },
29+ name: "insert",
30+ description:
31+ "Insert new lines before or after an anchor line in an existing file. " +
32+ "The anchor line itself is not modified. " +
33+ 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
34+ "To replace or delete lines use `edit`. To create a file use `write`.",
35+ schema: InsertSchema,
36+ execute: async (input) => {
37+ const cwd = input.cwd ?? process.cwd();
38+ const filePath = input.path.startsWith("/")
39+ ? input.path
40+ : join(cwd, input.path);
41+
42+ const relPath = relative(cwd, filePath);
43+
44+ const file = Bun.file(filePath);
45+ if (!(await file.exists())) {
46+ throw new Error(
47+ `File not found: "${relPath}". To create a new file use the \`write\` tool.`,
48+ );
49+ }
50+
51+ const parsed = parseAnchor(input.anchor);
52+
53+ const original = await file.text();
54+ const lines = original.split("\n");
55+
56+ const anchorLine = findLineByHash(lines, parsed.hash, parsed.line);
57+ if (!anchorLine) throw new Error(HASH_NOT_FOUND_ERROR);
58+
59+ const insertAt = input.position === "before" ? anchorLine - 1 : anchorLine;
60+ const insertLines = input.content.split("\n");
61+
62+ const updatedLines = [
63+ ...lines.slice(0, insertAt),
64+ ...insertLines,
65+ ...lines.slice(insertAt),
66+ ];
67+
68+ const updated = updatedLines.join("\n");
69+ await Bun.write(filePath, updated);
70+
71+ const diff = generateDiff(relPath, original, updated);
72+ return { path: relPath, diff };
73+ },
7474 };
7575
7676 interface ParsedAnchor {
77- line: number;
78- hash: string;
77+ line: number;
78+ hash: string;
7979 }
8080
8181 function parseAnchor(value: string): ParsedAnchor {
82- const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
83- if (!match) {
84- throw new Error(
85- `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
86- );
87- }
88-
89- const line = Number(match[1]);
90- if (!Number.isInteger(line) || line < 1) {
91- throw new Error("Invalid anchor line number.");
92- }
93-
94- const hash = match[2];
95- if (!hash) {
96- throw new Error(
97- `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
98- );
99- }
100-
101- return { line, hash: hash.toLowerCase() };
82+ const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
83+ if (!match) {
84+ throw new Error(
85+ `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
86+ );
87+ }
88+
89+ const line = Number(match[1]);
90+ if (!Number.isInteger(line) || line < 1) {
91+ throw new Error("Invalid anchor line number.");
92+ }
93+
94+ const hash = match[2];
95+ if (!hash) {
96+ throw new Error(
97+ `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
98+ );
99+ }
100+
101+ return { line, hash: hash.toLowerCase() };
102102 }
src/tools/write.ts+31−31
@@ -5,43 +5,43 @@ import type { ToolDef } from "../llm-api/types.ts";
55 import { generateDiff } from "./diff.ts";
66
77 const WriteSchema = z.object({
8- path: z.string().describe("File path to write (absolute or relative to cwd)"),
9- content: z.string().describe("Full content to write to the file"),
8+ path: z.string().describe("File path to write (absolute or relative to cwd)"),
9+ content: z.string().describe("Full content to write to the file"),
1010 });
1111
1212 type WriteInput = z.infer<typeof WriteSchema> & { cwd?: string };
1313
1414 export interface WriteOutput {
15- path: string;
16- diff: string;
17- created: boolean;
15+ path: string;
16+ diff: string;
17+ created: boolean;
1818 }
1919
2020 export const writeTool: ToolDef<WriteInput, WriteOutput> = {
21- name: "write",
22- description:
23- "Create a new file or fully overwrite an existing file with the given content. " +
24- "Use this only for new files. " +
25- "For targeted line edits on existing files, **use `edit` or `insert` instead**.",
26- schema: WriteSchema,
27- execute: async (input) => {
28- const cwd = input.cwd ?? process.cwd();
29- const filePath = input.path.startsWith("/")
30- ? input.path
31- : join(cwd, input.path);
32-
33- const relPath = relative(cwd, filePath);
34-
35- const dir = dirname(filePath);
36- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
37-
38- const file = Bun.file(filePath);
39- const created = !(await file.exists());
40- const before = created ? "" : await file.text();
41-
42- await Bun.write(filePath, input.content);
43-
44- const diff = generateDiff(relPath, before, input.content);
45- return { path: relPath, diff, created };
46- },
21+ name: "write",
22+ description:
23+ "Create a new file or fully overwrite an existing file with the given content. " +
24+ "Use this only for new files. " +
25+ "For targeted line edits on existing files, **use `edit` or `insert` instead**.",
26+ schema: WriteSchema,
27+ execute: async (input) => {
28+ const cwd = input.cwd ?? process.cwd();
29+ const filePath = input.path.startsWith("/")
30+ ? input.path
31+ : join(cwd, input.path);
32+
33+ const relPath = relative(cwd, filePath);
34+
35+ const dir = dirname(filePath);
36+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
37+
38+ const file = Bun.file(filePath);
39+ const created = !(await file.exists());
40+ const before = created ? "" : await file.text();
41+
42+ await Bun.write(filePath, input.content);
43+
44+ const diff = generateDiff(relPath, before, input.content);
45+ return { path: relPath, diff, created };
46+ },
4747 };