xonecas.io
64875
Mc

mini-coder / commit 9c643a8

Update tools for hashline anchors

xonecas2026-02-20 9c643a8512d907138d07d93d7154c44a7483a139 parent 6ce965c

6 files changed

TODO.md+20−0
@@ -1,3 +1,23 @@
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+---
6+
7+# Fix implementation error
8+
9+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.
10+
11+- Refactor sessions table to include content, tool call pairs and everything we need to remake
12+the history on resume. This breaks the schema, this is ok, we generate a new one.
13+- Ensure we don't break message format expected by the sdks.
14+
15+---
16+
17+src/tools/subagent.ts -- It should not include a model choice
18+
19+---
20+
121 # Undo needs to restore working directory
222
323 Besides undoing the conversation turn, it should restore some snapshot, using git?
src/cli/output.ts+14−8
@@ -144,14 +144,18 @@ function toolCallLine(name: string, args: unknown): string {
144144 return `${G.search} ${c.dim("grep")} ${c.bold(pattern)}${flags ? c.dim(` ${flags}`) : ""}`;
145145 }
146146 if (name === "read") {
147+ const line = Number.isFinite(a.line as number) ? Number(a.line) : null;
148+ const count = Number.isFinite(a.count as number) ? Number(a.count) : null;
147149 const range =
148- a.startLine || a.endLine
149- ? c.dim(`:${a.startLine ?? ""}–${a.endLine ?? ""}`)
150- : "";
150+ line || count ? c.dim(`:${line ?? 1}${count ? `+${count}` : ""}`) : "";
151151 return `${G.read} ${c.dim("read")} ${String(a.path ?? "")}${range}`;
152152 }
153153 if (name === "edit") {
154- const verb = !a.oldString || a.oldString === "" ? "create" : "edit";
154+ const verb = !a.startAnchor
155+ ? "create"
156+ : a.insertPosition
157+ ? "insert"
158+ : "edit";
155159 return `${G.write} ${c.dim(verb)} ${c.bold(String(a.path ?? ""))}`;
156160 }
157161 if (name === "shell") {
@@ -257,15 +261,17 @@ export function renderToolResult(
257261 if (toolName === "read") {
258262 const r = result as {
259263 path: string;
260- startLine: number;
261- endLine: number;
264+ line: number;
262265 totalLines: number;
263266 truncated: boolean;
267+ content?: string;
264268 };
269+ const linesReturned = r.content ? r.content.split("\n").length : 0;
270+ const endLine = linesReturned > 0 ? r.line + linesReturned - 1 : r.line;
265271 const range =
266- r.startLine === 1 && r.endLine === r.totalLines
272+ r.line === 1 && endLine === r.totalLines
267273 ? `${r.totalLines} lines`
268- : `lines ${r.startLine}–${r.endLine} of ${r.totalLines}`;
274+ : `lines ${r.line}–${endLine} of ${r.totalLines}`;
269275 writeln(
270276 ` ${G.info} ${c.dim(`${r.path} ${range}${r.truncated ? " (truncated)" : ""}`)}`,
271277 );
src/tools/edit.ts+108−31
@@ -2,20 +2,23 @@ import { existsSync, mkdirSync } from "node:fs";
22 import { dirname, join, relative } from "node:path";
33 import { z } from "zod";
44 import type { ToolDef } from "../llm-api/types.ts";
5+import { findLineByHash } from "./hashline.ts";
56
67 const EditInput = z.object({
78 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
8- oldString: z
9+ startAnchor: z.string().optional().describe('Start anchor, e.g. "11:a3"'),
10+ endAnchor: z
911 .string()
10- .describe(
11- "Exact string to find and replace. Must match exactly including whitespace and indentation. " +
12- "Must be unique in the file. To create a new file, pass an empty string.",
13- ),
14- newString: z
12+ .optional()
13+ .describe('End anchor (inclusive), e.g. "33:0e"'),
14+ newContent: z
1515 .string()
16- .describe(
17- "String to replace oldString with. Pass empty string to delete oldString.",
18- ),
16+ .optional()
17+ .describe("Replacement text. Omit or pass empty string to delete a range."),
18+ insertPosition: z
19+ .enum(["before", "after"])
20+ .optional()
21+ .describe("Insert-only position relative to startAnchor"),
1922 cwd: z
2023 .string()
2124 .optional()
@@ -32,14 +35,15 @@ export interface EditOutput {
3235 created: boolean;
3336 }
3437
38+const HASH_NOT_FOUND_ERROR =
39+ "Hash not found. Re-read the file to get current anchors.";
40+
3541 export const editTool: ToolDef<EditInput, EditOutput> = {
3642 name: "edit",
3743 description:
38- "Edit a file by replacing an exact string with a new string. " +
39- "The oldString must match exactly (including whitespace). " +
40- "To create a new file, pass oldString as empty string. " +
41- "To delete text, pass newString as empty string. " +
42- "Prefer small, focused edits over replacing large blocks.",
44+ "Edit a file using hashline anchors. Provide startAnchor (and optional endAnchor) " +
45+ "to replace or delete a range. Use insertPosition with startAnchor to insert text. " +
46+ "To create a new file, omit startAnchor and provide newContent.",
4347 schema: EditInput,
4448 execute: async (input) => {
4549 const cwd = input.cwd ?? process.cwd();
@@ -51,21 +55,30 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
5155 let created = false;
5256
5357 // ── Creating a new file ──────────────────────────────────────────────────
54- if (input.oldString === "") {
58+ if (!input.startAnchor) {
59+ if (input.endAnchor || input.insertPosition) {
60+ throw new Error(
61+ "startAnchor is required for edits. Omit it only to create a new file.",
62+ );
63+ }
64+ if (input.newContent === undefined) {
65+ throw new Error("newContent is required to create a new file.");
66+ }
67+
5568 const dir = dirname(filePath);
5669 if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
5770
5871 const existing = await Bun.file(filePath).exists();
5972 if (existing) {
6073 throw new Error(
61- `File "${relPath}" already exists. Provide oldString to edit an existing file.`,
74+ `File "${relPath}" already exists. Provide startAnchor to edit an existing file.`,
6275 );
6376 }
6477
65- await Bun.write(filePath, input.newString);
78+ await Bun.write(filePath, input.newContent);
6679 created = true;
6780
68- const diff = generateDiff(relPath, "", input.newString);
81+ const diff = generateDiff(relPath, "", input.newContent);
6982 return { path: relPath, success: true, diff, created };
7083 }
7184
@@ -74,27 +87,67 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
7487 const exists = await file.exists();
7588 if (!exists) {
7689 throw new Error(
77- `File not found: "${relPath}". To create a new file, pass oldString as empty string.`,
90+ `File not found: "${relPath}". To create a new file, omit startAnchor.`,
7891 );
7992 }
8093
81- const original = await file.text();
82-
83- // Check uniqueness
84- const firstIdx = original.indexOf(input.oldString);
85- if (firstIdx === -1) {
94+ const start = parseAnchor(input.startAnchor, "startAnchor");
95+ const end = input.endAnchor
96+ ? parseAnchor(input.endAnchor, "endAnchor")
97+ : null;
98+ if (end && end.line < start.line) {
8699 throw new Error(
87- `oldString not found in "${relPath}". Make sure it matches exactly including whitespace and indentation.`,
100+ "endAnchor line number must be >= startAnchor line number.",
88101 );
89102 }
90- const secondIdx = original.indexOf(input.oldString, firstIdx + 1);
91- if (secondIdx !== -1) {
92- throw new Error(
93- `oldString matches multiple locations in "${relPath}". Provide more surrounding context to make it unique.`,
94- );
103+ if (input.insertPosition && input.endAnchor) {
104+ throw new Error("insertPosition cannot be used with endAnchor.");
105+ }
106+ if (input.insertPosition && input.newContent === undefined) {
107+ throw new Error("newContent is required for insert operations.");
108+ }
109+
110+ const original = await file.text();
111+ const lines = original.split("\n");
112+
113+ const startLine = findLineByHash(lines, start.hash, start.line);
114+ if (!startLine) throw new Error(HASH_NOT_FOUND_ERROR);
115+
116+ let endLine = startLine;
117+ if (end) {
118+ const resolvedEnd = findLineByHash(lines, end.hash, end.line);
119+ if (!resolvedEnd) throw new Error(HASH_NOT_FOUND_ERROR);
120+ endLine = resolvedEnd;
121+ }
122+ if (endLine < startLine) {
123+ throw new Error("endAnchor resolves before startAnchor.");
95124 }
96125
97- const updated = original.replace(input.oldString, input.newString);
126+ let updatedLines: string[];
127+ if (input.insertPosition) {
128+ const insertLines = (input.newContent ?? "").split("\n");
129+ const insertAt =
130+ input.insertPosition === "before" ? startLine - 1 : startLine;
131+ updatedLines = [
132+ ...lines.slice(0, insertAt),
133+ ...insertLines,
134+ ...lines.slice(insertAt),
135+ ];
136+ } else {
137+ const replacement =
138+ input.newContent === undefined || input.newContent === ""
139+ ? []
140+ : input.newContent.split("\n");
141+ const startIdx = startLine - 1;
142+ const endIdx = (end ? endLine : startLine) - 1;
143+ updatedLines = [
144+ ...lines.slice(0, startIdx),
145+ ...replacement,
146+ ...lines.slice(endIdx + 1),
147+ ];
148+ }
149+
150+ const updated = updatedLines.join("\n");
98151 await Bun.write(filePath, updated);
99152
100153 const diff = generateDiff(relPath, original, updated);
@@ -102,6 +155,30 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
102155 },
103156 };
104157
158+interface ParsedAnchor {
159+ line: number;
160+ hash: string;
161+}
162+
163+function parseAnchor(value: string, name: string): ParsedAnchor {
164+ const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
165+ if (!match) {
166+ throw new Error(`Invalid ${name}. Expected "line:hh".`);
167+ }
168+
169+ const line = Number(match[1]);
170+ if (!Number.isInteger(line) || line < 1) {
171+ throw new Error(`Invalid ${name} line number.`);
172+ }
173+
174+ const hash = match[2];
175+ if (!hash) {
176+ throw new Error(`Invalid ${name}. Expected "line:hh".`);
177+ }
178+
179+ return { line, hash: hash.toLowerCase() };
180+}
181+
105182 // ─── Simple unified diff generator ───────────────────────────────────────────
106183
107184 function generateDiff(filePath: string, before: string, after: string): string {
src/tools/grep.ts+120−119
@@ -1,139 +1,140 @@
11 import { join } from "node:path";
22 import { z } from "zod";
33 import type { ToolDef } from "../llm-api/types.ts";
4+import { formatHashLine } from "./hashline.ts";
45
56 const GrepInput = z.object({
6- pattern: z.string().describe("Regular expression to search for"),
7- include: z
8- .string()
9- .optional()
10- .describe("Glob pattern to filter files, e.g. '*.ts' or '*.{ts,tsx}'"),
11- cwd: z
12- .string()
13- .optional()
14- .describe("Directory to search in (defaults to process.cwd())"),
15- contextLines: z
16- .number()
17- .int()
18- .min(0)
19- .max(10)
20- .optional()
21- .default(2)
22- .describe("Lines of context to include around each match"),
23- caseSensitive: z.boolean().optional().default(true),
24- maxResults: z.number().int().min(1).max(200).optional().default(50),
7+ pattern: z.string().describe("Regular expression to search for"),
8+ include: z
9+ .string()
10+ .optional()
11+ .describe("Glob pattern to filter files, e.g. '*.ts' or '*.{ts,tsx}'"),
12+ cwd: z
13+ .string()
14+ .optional()
15+ .describe("Directory to search in (defaults to process.cwd())"),
16+ contextLines: z
17+ .number()
18+ .int()
19+ .min(0)
20+ .max(10)
21+ .optional()
22+ .default(2)
23+ .describe("Lines of context to include around each match"),
24+ caseSensitive: z.boolean().optional().default(true),
25+ maxResults: z.number().int().min(1).max(200).optional().default(50),
2526 });
2627
2728 type GrepInput = z.infer<typeof GrepInput>;
2829
2930 export interface GrepMatch {
30- file: string;
31- line: number;
32- column: number;
33- text: string;
34- context: Array<{ line: number; text: string; isMatch: boolean }>;
31+ file: string;
32+ line: number;
33+ column: number;
34+ text: string;
35+ context: Array<{ line: number; text: string; isMatch: boolean }>;
3536 }
3637
3738 export interface GrepOutput {
38- matches: GrepMatch[];
39- totalMatches: number;
40- truncated: boolean;
39+ matches: GrepMatch[];
40+ totalMatches: number;
41+ truncated: boolean;
4142 }
4243
4344 const DEFAULT_IGNORE = [
44- "node_modules",
45- ".git",
46- "dist",
47- "*.db",
48- "*.db-shm",
49- "*.db-wal",
50- "bun.lock",
45+ "node_modules",
46+ ".git",
47+ "dist",
48+ "*.db",
49+ "*.db-shm",
50+ "*.db-wal",
51+ "bun.lock",
5152 ];
5253
5354 export const grepTool: ToolDef<GrepInput, GrepOutput> = {
54- name: "grep",
55- description:
56- "Search for a regex pattern across files. Returns file paths, line numbers, and context. " +
57- "Use this to find code patterns, function definitions, or specific text.",
58- schema: GrepInput,
59- execute: async (input) => {
60- const cwd = input.cwd ?? process.cwd();
61- const flags = input.caseSensitive ? "" : "i";
62- const regex = new RegExp(input.pattern, flags);
63- const maxResults = input.maxResults ?? 50;
64- const contextLines = input.contextLines ?? 2;
65- const include = input.include ?? "**/*";
66-
67- const fileGlob = new Bun.Glob(include);
68- const ignoreGlob = DEFAULT_IGNORE.map((p) => new Bun.Glob(p));
69-
70- const allMatches: GrepMatch[] = [];
71- let truncated = false;
72-
73- outer: for await (const relPath of fileGlob.scan({
74- cwd,
75- onlyFiles: true,
76- })) {
77- // Skip ignored
78- if (
79- ignoreGlob.some(
80- (g) => g.match(relPath) || g.match(relPath.split("/")[0] ?? ""),
81- )
82- ) {
83- continue;
84- }
85-
86- const fullPath = join(cwd, relPath);
87- let text: string;
88- try {
89- text = await Bun.file(fullPath).text();
90- } catch {
91- continue;
92- }
93-
94- // Skip binary-ish files
95- if (text.includes("\0")) continue;
96-
97- const lines = text.split("\n");
98-
99- for (let i = 0; i < lines.length; i++) {
100- const line = lines[i] ?? "";
101- const match = regex.exec(line);
102- if (!match) continue;
103-
104- // Gather context
105- const ctxStart = Math.max(0, i - contextLines);
106- const ctxEnd = Math.min(lines.length - 1, i + contextLines);
107- const context: GrepMatch["context"] = [];
108- for (let c = ctxStart; c <= ctxEnd; c++) {
109- context.push({
110- line: c + 1,
111- text: lines[c] ?? "",
112- isMatch: c === i,
113- });
114- }
115-
116- allMatches.push({
117- file: relPath,
118- line: i + 1,
119- column: match.index + 1,
120- text: line,
121- context,
122- });
123-
124- if (allMatches.length >= maxResults + 1) {
125- truncated = true;
126- break outer;
127- }
128- }
129- }
130-
131- if (truncated) allMatches.pop();
132-
133- return {
134- matches: allMatches,
135- totalMatches: allMatches.length,
136- truncated,
137- };
138- },
55+ name: "grep",
56+ description:
57+ "Search for a regex pattern across files. Returns file paths, line numbers, and context. " +
58+ "Use this to find code patterns, function definitions, or specific text.",
59+ schema: GrepInput,
60+ execute: async (input) => {
61+ const cwd = input.cwd ?? process.cwd();
62+ const flags = input.caseSensitive ? "" : "i";
63+ const regex = new RegExp(input.pattern, flags);
64+ const maxResults = input.maxResults ?? 50;
65+ const contextLines = input.contextLines ?? 2;
66+ const include = input.include ?? "**/*";
67+
68+ const fileGlob = new Bun.Glob(include);
69+ const ignoreGlob = DEFAULT_IGNORE.map((p) => new Bun.Glob(p));
70+
71+ const allMatches: GrepMatch[] = [];
72+ let truncated = false;
73+
74+ outer: for await (const relPath of fileGlob.scan({
75+ cwd,
76+ onlyFiles: true,
77+ })) {
78+ // Skip ignored
79+ if (
80+ ignoreGlob.some(
81+ (g) => g.match(relPath) || g.match(relPath.split("/")[0] ?? ""),
82+ )
83+ ) {
84+ continue;
85+ }
86+
87+ const fullPath = join(cwd, relPath);
88+ let text: string;
89+ try {
90+ text = await Bun.file(fullPath).text();
91+ } catch {
92+ continue;
93+ }
94+
95+ // Skip binary-ish files
96+ if (text.includes("\0")) continue;
97+
98+ const lines = text.split("\n");
99+
100+ for (let i = 0; i < lines.length; i++) {
101+ const line = lines[i] ?? "";
102+ const match = regex.exec(line);
103+ if (!match) continue;
104+
105+ // Gather context
106+ const ctxStart = Math.max(0, i - contextLines);
107+ const ctxEnd = Math.min(lines.length - 1, i + contextLines);
108+ const context: GrepMatch["context"] = [];
109+ for (let c = ctxStart; c <= ctxEnd; c++) {
110+ context.push({
111+ line: c + 1,
112+ text: formatHashLine(c + 1, lines[c] ?? ""),
113+ isMatch: c === i,
114+ });
115+ }
116+
117+ allMatches.push({
118+ file: relPath,
119+ line: i + 1,
120+ column: match.index + 1,
121+ text: formatHashLine(i + 1, line),
122+ context,
123+ });
124+
125+ if (allMatches.length >= maxResults + 1) {
126+ truncated = true;
127+ break outer;
128+ }
129+ }
130+ }
131+
132+ if (truncated) allMatches.pop();
133+
134+ return {
135+ matches: allMatches,
136+ totalMatches: allMatches.length,
137+ truncated,
138+ };
139+ },
139140 };
src/tools/hashline.ts+50−0
@@ -0,0 +1,50 @@
1+const FNV_OFFSET_BASIS = 0x811c9dc5;
2+const FNV_PRIME = 0x01000193;
3+const HASH_SCAN_RANGE = 10;
4+
5+export function hashLine(content: string): string {
6+ let hash = FNV_OFFSET_BASIS;
7+ for (let i = 0; i < content.length; i++) {
8+ hash ^= content.charCodeAt(i);
9+ hash = (hash * FNV_PRIME) >>> 0;
10+ }
11+ const twoHex = (hash & 0xff).toString(16).padStart(2, "0");
12+ return twoHex;
13+}
14+
15+export function formatHashLine(lineNum: number, content: string): string {
16+ return `${lineNum}:${hashLine(content)}| ${content}`;
17+}
18+
19+export function findLineByHash(
20+ lines: string[],
21+ hash: string,
22+ hintLine: number,
23+): number | null {
24+ const normalized = hash.toLowerCase();
25+ const hintIdx = hintLine - 1;
26+ const foundMatches: number[] = [];
27+
28+ const matches = (idx: number): boolean => {
29+ const line = lines[idx] ?? "";
30+ return hashLine(line) === normalized;
31+ };
32+
33+ if (hintIdx >= 0 && hintIdx < lines.length) {
34+ if (matches(hintIdx)) return hintIdx + 1;
35+ }
36+
37+ for (let offset = 1; offset <= HASH_SCAN_RANGE; offset++) {
38+ const lower = hintIdx - offset;
39+ if (lower >= 0 && lower < lines.length && matches(lower)) {
40+ foundMatches.push(lower + 1);
41+ }
42+ const higher = hintIdx + offset;
43+ if (higher >= 0 && higher < lines.length && matches(higher)) {
44+ foundMatches.push(higher + 1);
45+ }
46+ }
47+
48+ if (foundMatches.length === 1) return foundMatches[0] ?? null;
49+ return null;
50+}
src/tools/read.ts+20−24
@@ -1,21 +1,23 @@
11 import { join, relative } from "node:path";
22 import { z } from "zod";
33 import type { ToolDef } from "../llm-api/types.ts";
4+import { formatHashLine } from "./hashline.ts";
45
56 const ReadInput = z.object({
67 path: z.string().describe("File path to read (absolute or relative to cwd)"),
7- startLine: z
8+ line: z
89 .number()
910 .int()
1011 .min(1)
1112 .optional()
12- .describe("First line to read (1-indexed, inclusive)"),
13- endLine: z
13+ .describe("1-indexed starting line (default: 1)"),
14+ count: z
1415 .number()
1516 .int()
1617 .min(1)
18+ .max(500)
1719 .optional()
18- .describe("Last line to read (1-indexed, inclusive)"),
20+ .describe("Lines to read (default: 500, max: 500)"),
1921 cwd: z
2022 .string()
2123 .optional()
@@ -28,19 +30,20 @@ export interface ReadOutput {
2830 path: string;
2931 content: string;
3032 totalLines: number;
31- startLine: number;
32- endLine: number;
33+ line: number;
3334 truncated: boolean;
3435 }
3536
36-const MAX_LINES = 2000;
37-const MAX_BYTES = 200_000;
37+const MAX_COUNT = 500;
38+const MAX_BYTES = 1_000_000;
3839
3940 export const readTool: ToolDef<ReadInput, ReadOutput> = {
4041 name: "read",
4142 description:
42- "Read a file's contents. Optionally specify a line range with startLine/endLine. " +
43- "Lines are 1-indexed. Large files are automatically truncated.",
43+ "Read a file's contents. `line` sets the starting line (1-indexed, default 1). " +
44+ "`count` sets how many lines to read (default 500, max 500). " +
45+ "Check `truncated` and `totalLines` in the result to detect when more content exists; " +
46+ "paginate by incrementing `line`.",
4447 schema: ReadInput,
4548 execute: async (input) => {
4649 const cwd = input.cwd ?? process.cwd();
@@ -65,30 +68,23 @@ export const readTool: ToolDef<ReadInput, ReadOutput> = {
6568 const allLines = raw.split("\n");
6669 const totalLines = allLines.length;
6770
68- const startLine = input.startLine ?? 1;
69- const endLine =
70- input.endLine ?? Math.min(totalLines, startLine + MAX_LINES - 1);
71+ const startLine = input.line ?? 1;
72+ const count = Math.min(input.count ?? MAX_COUNT, MAX_COUNT);
7173
7274 const clampedStart = Math.max(1, Math.min(startLine, totalLines));
73- const clampedEnd = Math.max(clampedStart, Math.min(endLine, totalLines));
75+ const endLine = Math.min(totalLines, clampedStart + count - 1);
76+ const truncated = endLine < totalLines;
7477
75- // Hard cap on lines returned
76- const lineCount = clampedEnd - clampedStart + 1;
77- const hardEnd =
78- lineCount > MAX_LINES ? clampedStart + MAX_LINES - 1 : clampedEnd;
79- const truncated = hardEnd < clampedEnd || hardEnd < totalLines;
80-
81- const selectedLines = allLines.slice(clampedStart - 1, hardEnd);
78+ const selectedLines = allLines.slice(clampedStart - 1, endLine);
8279 const content = selectedLines
83- .map((line, i) => `${clampedStart + i}: ${line}`)
80+ .map((line, i) => formatHashLine(clampedStart + i, line))
8481 .join("\n");
8582
8683 return {
8784 path: relative(cwd, filePath),
8885 content,
8986 totalLines,
90- startLine: clampedStart,
91- endLine: hardEnd,
87+ line: clampedStart,
9288 truncated,
9389 };
9490 },