xonecas.io
64875
Mc

mini-coder / commit c5797d6

refactor: split edit tool into write, edit, and insert

- Add write tool: create or fully overwrite files
- Add insert tool: insert lines before/after an anchor
- Simplify edit tool: replace/delete lines only (no more file creation or insertPosition)
- Extract generateDiff into shared diff.ts
- Update README with new tools

xonecas2026-02-20 c5797d60a6a84283bc2a003cadbc23b55b3a40c5 parent 9c643a8

8 files changed

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

README.md+4โˆ’2
@@ -34,7 +34,9 @@ I come equipped with a tight, reliable set of tools:
3434 | ๐Ÿ” `glob` | Find files by pattern across your project |
3535 | ๐Ÿงฒ `grep` | Search file contents with regex |
3636 | ๐Ÿ“– `read` | Read files (with line-range support) |
37-| โœ๏ธ `edit` | Make precise, targeted edits (no full rewrites) |
37+| ๐Ÿ“ `write` | Create a new file or fully overwrite an existing file |
38+| โœ๏ธ `edit` | Replace or delete lines using hashline anchors |
39+| โž• `insert` | Insert lines before/after an anchor without replacing |
3840 | ๐Ÿš `shell` | Run shell commands and see their output |
3941 | ๐Ÿค– `subagent` | Spawn a focused mini-me for parallel subtasks |
4042
@@ -92,7 +94,7 @@ src/
9294 agent/ # Main REPL loop + tool registry
9395 cli/ # Input, output, slash commands
9496 llm-api/ # Provider factory + streaming turn logic
95- tools/ # glob, grep, read, edit, shell, subagent
97+ tools/ # glob, grep, read, write, edit, insert, shell, subagent
9698 mcp/ # MCP server connections
9799 session/ # SQLite-backed session & history management
98100 ```
TODO.md+15โˆ’154
@@ -2,40 +2,7 @@
22
33 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.
44
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-
21-# Undo needs to restore working directory
22-
23-Besides undoing the conversation turn, it should restore some snapshot, using git?
24-
25----
26-
27-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.
28-
29----
30-
31-# Plan mode changes
32-
33-- Allow read tools + mcp
34-- When plan mode is on, add a `<system-message>PLAN MODE ACTIVE -- READ ONLY</system-message>` suffix to the user messages.
35-
36----
37-
38-# LLMs don't know their cwd?:
5+Causes confusion
396
407 ```
418 โ–ถ create a readme file and introduce yourself
@@ -51,145 +18,39 @@ Subagent needs visibity on the ui somehow... that accounts for multiple in paral
5118
5219 ---
5320
54-Oauth Open AI support?
55-
56-## How opencode Implements OpenAI (Codex) OAuth Login
57-
58-The implementation is spread across several layers, all in `packages/opencode/src/plugin/codex.ts` as the core, wired together through a plugin/provider-auth system.
59-
60----
61-
62-### Architecture Overview
63-
64-```
65-UI (dialog-connect-provider.tsx)
66- โ†“ HTTP
67-Server routes (server/routes/provider.ts)
68- โ†“
69-ProviderAuth namespace (provider/auth.ts)
70- โ†“
71-Plugin system (plugin/index.ts)
72- โ†“
73-CodexAuthPlugin (plugin/codex.ts) โ† OAuth logic lives here
74- โ†“
75-Auth storage (auth/index.ts) โ† Persists tokens to auth.json
76-```
77-
78----
79-
80-### 1. The Plugin: `plugin/codex.ts`
81-
82-This is the heart of the OpenAI OAuth flow. It registers itself for the `"openai"` provider and exposes **two OAuth methods** plus a fallback API key method:
21+# Fix implementation error
8322
84-#### Method 1: **Browser-based (PKCE + redirect)**
85-```
86-label: "ChatGPT Pro/Plus (browser)"
87-type: "oauth", method: "auto"
88-```
89-- Spawns a local HTTP server on port `1455` (`http://localhost:1455/auth/callback`) as the OAuth redirect URI
90-- Generates a **PKCE** (`code_verifier` / `code_challenge`) pair using `crypto.subtle.digest("SHA-256")`
91-- Generates a CSRF `state` token
92-- Builds the authorization URL against `https://auth.openai.com/oauth/authorize` with:
93- - `client_id: "app_EMoamEEZ73f0CkXaXp7hrann"`
94- - `scope: "openid profile email offline_access"`
95- - `code_challenge_method: "S256"`
96- - `codex_cli_simplified_flow: "true"`, `originator: "opencode"`
97-- Returns `method: "auto"` โ€” the UI opens the URL, then polls by awaiting the callback promise
98-- When the browser redirects back, the local server handles `/auth/callback`, validates `state` (CSRF check), then POSTs the code + PKCE verifier to `https://auth.openai.com/oauth/token` to exchange for tokens
99-
100-#### Method 2: **Headless (Device Code flow)**
101-```
102-label: "ChatGPT Pro/Plus (headless)"
103-type: "oauth", method: "auto"
104-```
105-- POSTs to `https://auth.openai.com/api/accounts/deviceauth/usercode` to get a `device_auth_id` and `user_code`
106-- Returns `url: "https://auth.openai.com/codex/device"` and `instructions: "Enter code: <user_code>"`
107-- Polls `https://auth.openai.com/api/accounts/deviceauth/token` until approved, then exchanges the `authorization_code` (plus `code_verifier` returned by the server) at `https://auth.openai.com/oauth/token`
23+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.
10824
109-#### Method 3: **API Key (manual)**
110-```
111-label: "Manually enter API Key"
112-type: "api"
113-```
25+- Refactor sessions table to include content, tool call pairs and everything we need to remake
26+the history on resume. This breaks the schema, this is ok, we generate a new one.
27+- Ensure we don't break message format expected by the sdks.
11428
11529 ---
11630
117-### 2. Token Handling
118-
119-After a successful OAuth exchange, the plugin returns:
120-```ts
121-{ type: "success", refresh: "...", access: "...", expires: Date.now() + expires_in * 1000, accountId: "..." }
122-```
123-
124-`accountId` is extracted from the **JWT `id_token`** claims, looking for `chatgpt_account_id` (used to set the `ChatGPT-Account-Id` header for org subscriptions).
125-
126-The `auth.ts` `loader` hook intercepts every API call:
127-- If the **access token is expired**, it silently **refreshes** via `refresh_token` at `https://auth.openai.com/oauth/token`
128-- Strips the dummy `Authorization` header set by the AI SDK
129-- Injects `Authorization: Bearer <access_token>` and optionally `ChatGPT-Account-Id: <accountId>`
130-- **Rewrites the URL** for `/v1/responses` or `/chat/completions` requests to the Codex endpoint: `https://chatgpt.com/backend-api/codex/responses`
131-
132-A special constant `OAUTH_DUMMY_KEY = "opencode-oauth-dummy-key"` is returned as `apiKey` to satisfy the AI SDK's requirement for an API key, while the real auth is handled in the custom `fetch` interceptor.
31+src/tools/subagent.ts -- It should not include a model choice
13332
13433 ---
13534
136-### 3. Storage: `auth/index.ts`
35+# Undo needs to restore working directory
13736
138-All tokens are persisted to `~/.opencode/auth.json` (mode `0o600`) as a discriminated union:
139-```ts
140-{ type: "oauth", refresh: "...", access: "...", expires: 1234567890, accountId?: "..." }
141-```
37+Besides undoing the conversation turn, it should restore some snapshot, using git?
14238
14339 ---
14440
145-### 4. Server Routes: `server/routes/provider.ts`
146-
147-Two HTTP endpoints (via Hono) expose the OAuth flow to the UI:
41+# Plan mode changes
14842
149-| Endpoint | Purpose |
150-|---|---|
151-| `POST /:providerID/oauth/authorize` | Calls `ProviderAuth.authorize()` โ†’ triggers the plugin's `authorize()` โ†’ returns `{ url, method, instructions }` |
152-| `POST /:providerID/oauth/callback` | Calls `ProviderAuth.callback()` โ†’ triggers the plugin's `callback(code?)` โ†’ persists tokens via `Auth.set()` |
153-| `GET /auth` | Lists all auth methods from all plugins |
43+- Allow read tools + mcp
44+- When plan mode is on, add a `<system-message>PLAN MODE ACTIVE -- READ ONLY</system-message>` suffix to the user messages.
15445
15546 ---
15647
157-### 5. `ProviderAuth` Coordinator: `provider/auth.ts`
48+# Fix tools not saved to db.
15849
159-Acts as the bridge between the server routes and plugins:
160-- `authorize()` โ€” calls the plugin's `method.authorize()` and stores the pending `AuthOuathResult` in instance state
161-- `callback()` โ€” retrieves the pending result, calls `result.callback(code?)`, then:
162- - If result has `key` โ†’ saves `{ type: "api", key }` to `Auth`
163- - If result has `refresh` โ†’ saves `{ type: "oauth", access, refresh, expires, accountId? }` to `Auth`
50+- We are breaking existing sessions on resume, update the db and code to store the full session messages.
16451
16552 ---
16653
167-### 6. UI: `dialog-connect-provider.tsx`
168-
169-The UI presents the method list and drives the flow:
170-
171-```
172-Method selected โ†’ selectMethod(index)
173- โ””โ”€ if type === "oauth":
174- โ†’ calls provider.oauth.authorize({ providerID, method: index })
175- โ†’ stores authorization { url, method: "auto"|"code", instructions }
176- โ””โ”€ if method === "auto": OAuthAutoView
177- Opens URL via platform.openLink()
178- Shows confirmation code from instructions (e.g. "Enter code: XXXX")
179- Calls provider.oauth.callback({ providerID, method }) โ€” awaits completion
180- if method === "code": OAuthCodeView
181- Opens URL via platform.openLink()
182- User pastes the code manually
183- Calls provider.oauth.callback({ providerID, method, code })
184-```
54+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.
18555
18656 ---
187-
188-### Key Constants (OpenAI-specific)
189-| Constant | Value |
190-|---|---|
191-| `CLIENT_ID` | `app_EMoamEEZ73f0CkXaXp7hrann` |
192-| `ISSUER` | `https://auth.openai.com` |
193-| `CODEX_API_ENDPOINT` | `https://chatgpt.com/backend-api/codex/responses` |
194-| `OAUTH_PORT` | `1455` |
195-| Scopes | `openid profile email offline_access` |
src/agent/tools.ts+7โˆ’0
@@ -2,9 +2,11 @@ import type { ToolDef } from "../llm-api/types.ts";
22 import { editTool } from "../tools/edit.ts";
33 import { globTool } from "../tools/glob.ts";
44 import { grepTool } from "../tools/grep.ts";
5+import { insertTool } from "../tools/insert.ts";
56 import { readTool } from "../tools/read.ts";
67 import { shellTool } from "../tools/shell.ts";
78 import { createSubagentTool } from "../tools/subagent.ts";
9+import { writeTool } from "../tools/write.ts";
810
911 // โ”€โ”€โ”€ Hook types โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1012
@@ -65,10 +67,15 @@ export function buildToolSet(opts: {
6567 }): ToolDef[] {
6668 const depth = opts.depth ?? 0;
6769 return [
70+ // Read-only: discover and inspect files
6871 withCwdDefault(globTool as ToolDef, opts.cwd),
6972 withCwdDefault(grepTool as ToolDef, opts.cwd),
7073 withCwdDefault(readTool as ToolDef, opts.cwd),
74+ // Write: create/overwrite, replace/delete, insert
75+ withCwdDefault(writeTool as ToolDef, opts.cwd),
7176 withCwdDefault(editTool as ToolDef, opts.cwd),
77+ withCwdDefault(insertTool as ToolDef, opts.cwd),
78+ // Shell and subagent
7279 withCwdDefault(shellTool as ToolDef, opts.cwd),
7380 createSubagentTool(async (prompt, model) => {
7481 if (depth >= MAX_SUBAGENT_DEPTH) {
src/tools/diff.ts+79โˆ’0
@@ -0,0 +1,79 @@
1+export function generateDiff(
2+ filePath: string,
3+ before: string,
4+ after: string,
5+): string {
6+ const beforeLines = before === "" ? [] : before.split("\n");
7+ const afterLines = after === "" ? [] : after.split("\n");
8+
9+ const diff = computeUnifiedDiff(beforeLines, afterLines);
10+
11+ if (diff.length === 0) return "(no changes)";
12+
13+ return `--- ${filePath}\n+++ ${filePath}\n${diff}`;
14+}
15+
16+function computeUnifiedDiff(before: string[], after: string[]): string {
17+ const CONTEXT = 3;
18+
19+ // Find the first differing index and the last differing index in each array
20+ // independently, so hunk sizes are correct when the two arrays differ in length.
21+ let firstDiff = -1;
22+ let lastDiffBefore = -1;
23+ let lastDiffAfter = -1;
24+
25+ for (let i = 0; i < before.length; i++) {
26+ if (before[i] !== after[i]) {
27+ if (firstDiff === -1) firstDiff = i;
28+ lastDiffBefore = i;
29+ }
30+ }
31+ for (let i = 0; i < after.length; i++) {
32+ if (after[i] !== before[i]) {
33+ if (firstDiff === -1) firstDiff = i;
34+ lastDiffAfter = i;
35+ }
36+ }
37+
38+ if (firstDiff === -1) return "";
39+
40+ // Clamp: if one side has no differing lines past firstDiff, end at firstDiff
41+ if (lastDiffBefore === -1) lastDiffBefore = firstDiff;
42+ if (lastDiffAfter === -1) lastDiffAfter = firstDiff;
43+
44+ const hunkStart = Math.max(0, firstDiff - CONTEXT);
45+ const hunkEndBefore = Math.min(before.length, lastDiffBefore + 1 + CONTEXT);
46+ const hunkEndAfter = Math.min(after.length, lastDiffAfter + 1 + CONTEXT);
47+
48+ const lines: string[] = [];
49+ lines.push(
50+ `@@ -${hunkStart + 1},${hunkEndBefore - hunkStart} ` +
51+ `+${hunkStart + 1},${hunkEndAfter - hunkStart} @@`,
52+ );
53+
54+ // Context before
55+ for (let i = hunkStart; i < firstDiff; i++) {
56+ lines.push(` ${before[i] ?? ""}`);
57+ }
58+
59+ // Removed lines
60+ for (let i = firstDiff; i <= lastDiffBefore && i < before.length; i++) {
61+ lines.push(`-${before[i] ?? ""}`);
62+ }
63+
64+ // Added lines
65+ for (let i = firstDiff; i <= lastDiffAfter && i < after.length; i++) {
66+ lines.push(`+${after[i] ?? ""}`);
67+ }
68+
69+ // Context after
70+ for (
71+ let i = lastDiffBefore + 1;
72+ i < hunkEndBefore && i < before.length;
73+ i++
74+ ) {
75+ lines.push(` ${before[i] ?? ""}`);
76+ }
77+
78+ return lines.join("\n");
79+}
src/tools/edit.ts+36โˆ’146
@@ -1,24 +1,26 @@
1-import { existsSync, mkdirSync } from "node:fs";
2-import { dirname, join, relative } from "node:path";
1+import { join, relative } from "node:path";
32 import { z } from "zod";
43 import type { ToolDef } from "../llm-api/types.ts";
4+import { generateDiff } from "./diff.ts";
55 import { findLineByHash } from "./hashline.ts";
66
77 const EditInput = z.object({
88 path: z.string().describe("File path to edit (absolute or relative to cwd)"),
9- startAnchor: z.string().optional().describe('Start anchor, e.g. "11:a3"'),
9+ startAnchor: z
10+ .string()
11+ .describe('Start anchor from a prior read/grep, e.g. "11:a3"'),
1012 endAnchor: z
1113 .string()
1214 .optional()
13- .describe('End anchor (inclusive), e.g. "33:0e"'),
15+ .describe(
16+ 'End anchor (inclusive), e.g. "33:0e". Omit to target only the startAnchor line.',
17+ ),
1418 newContent: z
1519 .string()
1620 .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"),
21+ .describe(
22+ "Replacement text. Omit or pass empty string to delete the range.",
23+ ),
2224 cwd: z
2325 .string()
2426 .optional()
@@ -29,10 +31,7 @@ type EditInput = z.infer<typeof EditInput>;
2931
3032 export interface EditOutput {
3133 path: string;
32- success: boolean;
33- /** Unified-style diff of the change */
3434 diff: string;
35- created: boolean;
3635 }
3736
3837 const HASH_NOT_FOUND_ERROR =
@@ -41,9 +40,11 @@ const HASH_NOT_FOUND_ERROR =
4140 export const editTool: ToolDef<EditInput, EditOutput> = {
4241 name: "edit",
4342 description:
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.",
43+ "Replace or delete a range of lines in an existing file using hashline anchors. " +
44+ 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
45+ "Provide startAnchor alone to target a single line, or add endAnchor for a range. " +
46+ "Set newContent to the replacement text, or omit it to delete the range. " +
47+ "To create or overwrite a file use `write`. To insert without replacing any lines use `insert`.",
4748 schema: EditInput,
4849 execute: async (input) => {
4950 const cwd = input.cwd ?? process.cwd();
@@ -52,42 +53,11 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
5253 : join(cwd, input.path);
5354
5455 const relPath = relative(cwd, filePath);
55- let created = false;
56-
57- // โ”€โ”€ Creating a new file โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
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-
68- const dir = dirname(filePath);
69- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
70-
71- const existing = await Bun.file(filePath).exists();
72- if (existing) {
73- throw new Error(
74- `File "${relPath}" already exists. Provide startAnchor to edit an existing file.`,
75- );
76- }
77-
78- await Bun.write(filePath, input.newContent);
79- created = true;
80-
81- const diff = generateDiff(relPath, "", input.newContent);
82- return { path: relPath, success: true, diff, created };
83- }
8456
85- // โ”€โ”€ Editing an existing file โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
8657 const file = Bun.file(filePath);
87- const exists = await file.exists();
88- if (!exists) {
58+ if (!(await file.exists())) {
8959 throw new Error(
90- `File not found: "${relPath}". To create a new file, omit startAnchor.`,
60+ `File not found: "${relPath}". To create a new file use the \`write\` tool.`,
9161 );
9262 }
9363
@@ -95,17 +65,12 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
9565 const end = input.endAnchor
9666 ? parseAnchor(input.endAnchor, "endAnchor")
9767 : null;
68+
9869 if (end && end.line < start.line) {
9970 throw new Error(
10071 "endAnchor line number must be >= startAnchor line number.",
10172 );
10273 }
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- }
10974
11075 const original = await file.text();
11176 const lines = original.split("\n");
@@ -123,35 +88,22 @@ export const editTool: ToolDef<EditInput, EditOutput> = {
12388 throw new Error("endAnchor resolves before startAnchor.");
12489 }
12590
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- }
91+ const replacement =
92+ input.newContent === undefined || input.newContent === ""
93+ ? []
94+ : input.newContent.split("\n");
95+
96+ const updatedLines = [
97+ ...lines.slice(0, startLine - 1),
98+ ...replacement,
99+ ...lines.slice(endLine),
100+ ];
149101
150102 const updated = updatedLines.join("\n");
151103 await Bun.write(filePath, updated);
152104
153105 const diff = generateDiff(relPath, original, updated);
154- return { path: relPath, success: true, diff, created };
106+ return { path: relPath, diff };
155107 },
156108 };
157109
@@ -163,7 +115,9 @@ interface ParsedAnchor {
163115 function parseAnchor(value: string, name: string): ParsedAnchor {
164116 const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
165117 if (!match) {
166- throw new Error(`Invalid ${name}. Expected "line:hh".`);
118+ throw new Error(
119+ `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
120+ );
167121 }
168122
169123 const line = Number(match[1]);
@@ -173,74 +127,10 @@ function parseAnchor(value: string, name: string): ParsedAnchor {
173127
174128 const hash = match[2];
175129 if (!hash) {
176- throw new Error(`Invalid ${name}. Expected "line:hh".`);
130+ throw new Error(
131+ `Invalid ${name}. Expected format: "line:hh" (e.g. "11:a3").`,
132+ );
177133 }
178134
179135 return { line, hash: hash.toLowerCase() };
180136 }
181-
182-// โ”€โ”€โ”€ Simple unified diff generator โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
183-
184-function generateDiff(filePath: string, before: string, after: string): string {
185- const beforeLines = before === "" ? [] : before.split("\n");
186- const afterLines = after === "" ? [] : after.split("\n");
187-
188- // Find changed regions using a simple LCS-based approach
189- // For our use case, we just show the hunks around the changed area
190- const diff = computeUnifiedDiff(beforeLines, afterLines);
191-
192- if (diff.length === 0) return "(no changes)";
193-
194- return `--- ${filePath}\n+++ ${filePath}\n${diff}`;
195-}
196-
197-function computeUnifiedDiff(before: string[], after: string[]): string {
198- const CONTEXT = 3;
199-
200- // Simple O(n) approach: find the first and last differing line
201- let firstDiff = -1;
202- let lastDiffBefore = before.length;
203- let lastDiffAfter = after.length;
204-
205- for (let i = 0; i < Math.max(before.length, after.length); i++) {
206- if (before[i] !== after[i]) {
207- if (firstDiff === -1) firstDiff = i;
208- lastDiffBefore = i + 1;
209- lastDiffAfter = i + 1;
210- }
211- }
212-
213- if (firstDiff === -1) return "";
214-
215- const hunkStart = Math.max(0, firstDiff - CONTEXT);
216- const hunkEndBefore = Math.min(before.length, lastDiffBefore + CONTEXT);
217- const hunkEndAfter = Math.min(after.length, lastDiffAfter + CONTEXT);
218-
219- const lines: string[] = [];
220- lines.push(
221- `@@ -${hunkStart + 1},${hunkEndBefore - hunkStart} ` +
222- `+${hunkStart + 1},${hunkEndAfter - hunkStart} @@`,
223- );
224-
225- // Context before
226- for (let i = hunkStart; i < firstDiff; i++) {
227- lines.push(` ${before[i] ?? ""}`);
228- }
229-
230- // Removed lines
231- for (let i = firstDiff; i < lastDiffBefore && i < before.length; i++) {
232- lines.push(`-${before[i] ?? ""}`);
233- }
234-
235- // Added lines
236- for (let i = firstDiff; i < lastDiffAfter && i < after.length; i++) {
237- lines.push(`+${after[i] ?? ""}`);
238- }
239-
240- // Context after
241- for (let i = lastDiffBefore; i < hunkEndBefore && i < before.length; i++) {
242- lines.push(` ${before[i] ?? ""}`);
243- }
244-
245- return lines.join("\n");
246-}
src/tools/grep.ts+119โˆ’119
@@ -4,137 +4,137 @@ import type { ToolDef } from "../llm-api/types.ts";
44 import { formatHashLine } from "./hashline.ts";
55
66 const GrepInput = z.object({
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),
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),
2626 });
2727
2828 type GrepInput = z.infer<typeof GrepInput>;
2929
3030 export interface GrepMatch {
31- file: string;
32- line: number;
33- column: number;
34- text: string;
35- 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 }>;
3636 }
3737
3838 export interface GrepOutput {
39- matches: GrepMatch[];
40- totalMatches: number;
41- truncated: boolean;
39+ matches: GrepMatch[];
40+ totalMatches: number;
41+ truncated: boolean;
4242 }
4343
4444 const DEFAULT_IGNORE = [
45- "node_modules",
46- ".git",
47- "dist",
48- "*.db",
49- "*.db-shm",
50- "*.db-wal",
51- "bun.lock",
45+ "node_modules",
46+ ".git",
47+ "dist",
48+ "*.db",
49+ "*.db-shm",
50+ "*.db-wal",
51+ "bun.lock",
5252 ];
5353
5454 export const grepTool: ToolDef<GrepInput, GrepOutput> = {
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- },
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+ },
140140 };
src/tools/insert.ts+106โˆ’0
@@ -0,0 +1,106 @@
1+import { join, relative } from "node:path";
2+import { z } from "zod";
3+import type { ToolDef } from "../llm-api/types.ts";
4+import { generateDiff } from "./diff.ts";
5+import { findLineByHash } from "./hashline.ts";
6+
7+const InsertInput = 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"),
16+ cwd: z
17+ .string()
18+ .optional()
19+ .describe("Working directory for resolving relative paths"),
20+});
21+
22+type InsertInput = z.infer<typeof InsertInput>;
23+
24+export interface InsertOutput {
25+ path: string;
26+ diff: string;
27+}
28+
29+const HASH_NOT_FOUND_ERROR =
30+ "Hash not found. Re-read the file to get current anchors.";
31+
32+export const insertTool: ToolDef<InsertInput, InsertOutput> = {
33+ name: "insert",
34+ description:
35+ "Insert new lines before or after an anchor line in an existing file. " +
36+ "The anchor line itself is not modified. " +
37+ 'Anchors come from the `read` or `grep` tools (format: "line:hash", e.g. "11:a3"). ' +
38+ "To replace or delete lines use `edit`. To create or overwrite a file use `write`.",
39+ schema: InsertInput,
40+ execute: async (input) => {
41+ const cwd = input.cwd ?? process.cwd();
42+ const filePath = input.path.startsWith("/")
43+ ? input.path
44+ : join(cwd, input.path);
45+
46+ const relPath = relative(cwd, filePath);
47+
48+ const file = Bun.file(filePath);
49+ if (!(await file.exists())) {
50+ throw new Error(
51+ `File not found: "${relPath}". To create a new file use the \`write\` tool.`,
52+ );
53+ }
54+
55+ const parsed = parseAnchor(input.anchor);
56+
57+ const original = await file.text();
58+ const lines = original.split("\n");
59+
60+ const anchorLine = findLineByHash(lines, parsed.hash, parsed.line);
61+ if (!anchorLine) throw new Error(HASH_NOT_FOUND_ERROR);
62+
63+ const insertAt = input.position === "before" ? anchorLine - 1 : anchorLine;
64+ const insertLines = input.content.split("\n");
65+
66+ const updatedLines = [
67+ ...lines.slice(0, insertAt),
68+ ...insertLines,
69+ ...lines.slice(insertAt),
70+ ];
71+
72+ const updated = updatedLines.join("\n");
73+ await Bun.write(filePath, updated);
74+
75+ const diff = generateDiff(relPath, original, updated);
76+ return { path: relPath, diff };
77+ },
78+};
79+
80+interface ParsedAnchor {
81+ line: number;
82+ hash: string;
83+}
84+
85+function parseAnchor(value: string): ParsedAnchor {
86+ const match = /^\s*(\d+):([0-9a-fA-F]{2})\s*$/.exec(value);
87+ if (!match) {
88+ throw new Error(
89+ `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
90+ );
91+ }
92+
93+ const line = Number(match[1]);
94+ if (!Number.isInteger(line) || line < 1) {
95+ throw new Error("Invalid anchor line number.");
96+ }
97+
98+ const hash = match[2];
99+ if (!hash) {
100+ throw new Error(
101+ `Invalid anchor. Expected format: "line:hh" (e.g. "11:a3").`,
102+ );
103+ }
104+
105+ return { line, hash: hash.toLowerCase() };
106+}
src/tools/write.ts+51โˆ’0
@@ -0,0 +1,51 @@
1+import { existsSync, mkdirSync } from "node:fs";
2+import { dirname, join, relative } from "node:path";
3+import { z } from "zod";
4+import type { ToolDef } from "../llm-api/types.ts";
5+import { generateDiff } from "./diff.ts";
6+
7+const WriteInput = 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"),
10+ cwd: z
11+ .string()
12+ .optional()
13+ .describe("Working directory for resolving relative paths"),
14+});
15+
16+type WriteInput = z.infer<typeof WriteInput>;
17+
18+export interface WriteOutput {
19+ path: string;
20+ diff: string;
21+ created: boolean;
22+}
23+
24+export const writeTool: ToolDef<WriteInput, WriteOutput> = {
25+ name: "write",
26+ description:
27+ "Create a new file or fully overwrite an existing file with the given content. " +
28+ "Use this for new files or when replacing an entire file. " +
29+ "For targeted line edits on existing files, use `edit` or `insert` instead.",
30+ schema: WriteInput,
31+ execute: async (input) => {
32+ const cwd = input.cwd ?? process.cwd();
33+ const filePath = input.path.startsWith("/")
34+ ? input.path
35+ : join(cwd, input.path);
36+
37+ const relPath = relative(cwd, filePath);
38+
39+ const dir = dirname(filePath);
40+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
41+
42+ const file = Bun.file(filePath);
43+ const created = !(await file.exists());
Cut short: this commit's diff is over 1000 lines.