|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Atom++ — AI (M4, feature 1: agentic multi-file tasks) |
| 3 | + * |
| 4 | + * An autonomous coding agent. Given a goal, Claude reads/searches/edits files and runs |
| 5 | + * commands via tools to accomplish it. Read-only tools run automatically; every file write |
| 6 | + * and command is GATED behind an inline Approve/Skip card IN THE CHAT (with a readable diff). |
| 7 | + * Assistant text streams live. Step-capped and cancellable. Direct to the provider. |
| 8 | + *--------------------------------------------------------------------------------------------*/ |
| 9 | +// @ts-check |
| 10 | +'use strict'; |
| 11 | + |
| 12 | +const vscode = require('vscode'); |
| 13 | +const fs = require('fs'); |
| 14 | +const path = require('path'); |
| 15 | +const cp = require('child_process'); |
| 16 | +const { streamClaudeAgentTurn } = require('./providers'); |
| 17 | + |
| 18 | +const SYSTEM = [ |
| 19 | + "You are Atom++'s built-in autonomous coding agent. You accomplish the user's goal in their", |
| 20 | + 'workspace using the provided tools. Rules:', |
| 21 | + '- Be DECISIVE and FAST. Read only the file you are changing (plus at most 1 other if truly needed), then ACT. Do NOT write long multi-point plans — at most ONE short sentence before each tool call.', |
| 22 | + '- Start acting within your first 1-2 turns. Use read_file / list_files / search to understand code before editing — never guess file contents.', |
| 23 | + '- CRITICAL: never end your turn by merely describing an edit ("now let me refactor…"). If you intend to change a file, you MUST call edit_file or write_file in that SAME turn. Words are not edits.', |
| 24 | + '- To change an EXISTING file, use edit_file with an exact, unique snippet (old_str) and its replacement (new_str). This is preferred — small and reliable. Read the file first so old_str matches exactly. Prefer SEVERAL small edit_file calls over one huge one (smaller edits are faster and easier to review).', |
| 25 | + '- Use write_file ONLY to create a new file (or fully rewrite a short one); it needs the COMPLETE content. Do not rewrite large files — use edit_file repeatedly instead.', |
| 26 | + '- Your file edits are APPLIED IMMEDIATELY and the user reviews them afterward in the editor with Keep/Undo — do NOT wait for approval, and do NOT re-edit a file you just edited. Only run_command still needs approval; if the user skips a command, adapt or stop.', |
| 27 | + '- Paths are relative to the workspace root.', |
| 28 | + '- When the goal is finished, end with a one-line summary starting with "Done:" and STOP (no more tools).' |
| 29 | +].join('\n'); |
| 30 | + |
| 31 | +const TOOLS = [ |
| 32 | + { name: 'list_files', description: 'List workspace files (optional glob like "**/*.js"). Excludes node_modules/.git/build dirs.', input_schema: { type: 'object', properties: { glob: { type: 'string' } } } }, |
| 33 | + { name: 'read_file', description: 'Read a workspace file (path relative to the workspace root).', input_schema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] } }, |
| 34 | + { name: 'search', description: 'Search file contents for a literal string. Returns file:line snippets.', input_schema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } }, |
| 35 | + { name: 'edit_file', description: 'Make a targeted edit to an EXISTING file: replace an exact, unique snippet (old_str) with new_str. Applied immediately; the user reviews it with Keep/Undo. old_str must appear exactly once — include enough surrounding context to be unique.', input_schema: { type: 'object', properties: { path: { type: 'string' }, old_str: { type: 'string' }, new_str: { type: 'string' } }, required: ['path', 'old_str', 'new_str'] } }, |
| 36 | + { name: 'write_file', description: 'Create a new file (or fully overwrite a short one) with the COMPLETE content. For edits to existing files, prefer edit_file. Applied immediately; the user reviews it with Keep/Undo.', input_schema: { type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path', 'content'] } }, |
| 37 | + { name: 'run_command', description: 'Run a shell command in the workspace root. Requires approval.', input_schema: { type: 'object', properties: { command: { type: 'string' }, explanation: { type: 'string' } }, required: ['command'] } } |
| 38 | +]; |
| 39 | + |
| 40 | +const FILE_EXCLUDES = '{**/node_modules/**,**/.git/**,**/out/**,**/dist/**,**/.vscode-test/**,**/*.map}'; |
| 41 | + |
| 42 | +// ---- ripgrep search (self-contained) --------------------------------------- |
| 43 | +function rgPath() { |
| 44 | + const root = vscode.env.appRoot; |
| 45 | + const cands = [ |
| 46 | + path.join(root, 'node_modules', '@vscode', 'ripgrep', 'bin', 'rg'), |
| 47 | + path.join(root, 'node_modules', '@vscode', 'ripgrep-universal', 'bin', process.platform + '-' + process.arch, 'rg') |
| 48 | + ]; |
| 49 | + return cands.find((c) => { try { return fs.existsSync(c); } catch { return false; } }) || null; |
| 50 | +} |
| 51 | +function rgSearch(term, cwd) { |
| 52 | + return new Promise((resolve) => { |
| 53 | + const bin = rgPath(); |
| 54 | + if (!bin || !cwd) { resolve(''); return; } |
| 55 | + const args = ['--line-number', '--no-messages', '--no-config', '-i', '-F', '--max-count', '20', '--max-filesize', '1M', '-g', '!**/node_modules/**', '-g', '!**/.git/**', '-e', term, '.']; |
| 56 | + let out = ''; |
| 57 | + try { |
| 58 | + const child = cp.spawn(bin, args, { cwd }); |
| 59 | + const t = setTimeout(() => { try { child.kill(); } catch { /* */ } resolve(out.slice(0, 6000)); }, 5000); |
| 60 | + child.stdout.on('data', (d) => { out += d.toString(); }); |
| 61 | + child.on('error', () => { clearTimeout(t); resolve(''); }); |
| 62 | + child.on('close', () => { clearTimeout(t); resolve(out.slice(0, 6000)); }); |
| 63 | + } catch { resolve(''); } |
| 64 | + }); |
| 65 | +} |
| 66 | + |
| 67 | +// ---- readable line diff ---------------------------------------------------- |
| 68 | +/** LCS diff of two small line arrays → [{type:'ctx'|'add'|'del', text}]. */ |
| 69 | +function lcsDiff(a, b) { |
| 70 | + const n = a.length, m = b.length; |
| 71 | + if (n === 0) { return b.map((t) => ({ type: 'add', text: t })); } |
| 72 | + if (m === 0) { return a.map((t) => ({ type: 'del', text: t })); } |
| 73 | + if (n > 500 || m > 500) { return a.map((t) => ({ type: 'del', text: t })).concat(b.map((t) => ({ type: 'add', text: t }))); } |
| 74 | + const dp = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1)); |
| 75 | + for (let i = n - 1; i >= 0; i--) { |
| 76 | + for (let j = m - 1; j >= 0; j--) { |
| 77 | + dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]); |
| 78 | + } |
| 79 | + } |
| 80 | + const out = []; |
| 81 | + let i = 0, j = 0; |
| 82 | + while (i < n && j < m) { |
| 83 | + if (a[i] === b[j]) { out.push({ type: 'ctx', text: a[i] }); i++; j++; } |
| 84 | + else if (dp[i + 1][j] >= dp[i][j + 1]) { out.push({ type: 'del', text: a[i] }); i++; } |
| 85 | + else { out.push({ type: 'add', text: b[j] }); j++; } |
| 86 | + } |
| 87 | + while (i < n) { out.push({ type: 'del', text: a[i++] }); } |
| 88 | + while (j < m) { out.push({ type: 'add', text: b[j++] }); } |
| 89 | + return out; |
| 90 | +} |
| 91 | + |
| 92 | +/** Diff old/new content with trimmed common prefix/suffix + a little context. Capped. */ |
| 93 | +function makeDiff(oldStr, newStr) { |
| 94 | + const a = oldStr.length ? oldStr.split('\n') : []; |
| 95 | + const b = newStr.split('\n'); |
| 96 | + let p = 0; |
| 97 | + while (p < a.length && p < b.length && a[p] === b[p]) { p++; } |
| 98 | + let s = 0; |
| 99 | + while (s < a.length - p && s < b.length - p && a[a.length - 1 - s] === b[b.length - 1 - s]) { s++; } |
| 100 | + const aMid = a.slice(p, a.length - s), bMid = b.slice(p, b.length - s); |
| 101 | + const out = []; |
| 102 | + a.slice(Math.max(0, p - 2), p).forEach((t) => out.push({ type: 'ctx', text: t })); |
| 103 | + out.push(...lcsDiff(aMid, bMid)); |
| 104 | + a.slice(a.length - s, a.length - s + 2).forEach((t) => out.push({ type: 'ctx', text: t })); |
| 105 | + if (out.length > 200) { return out.slice(0, 200).concat([{ type: 'ctx', text: '… (diff truncated)' }]); } |
| 106 | + return out; |
| 107 | +} |
| 108 | + |
| 109 | +// ---- workspace helpers ----------------------------------------------------- |
| 110 | +function workspaceRoot() { |
| 111 | + const f = vscode.workspace.workspaceFolders; |
| 112 | + return f && f.length ? f[0].uri.fsPath : null; |
| 113 | +} |
| 114 | +function safeJoin(root, rel) { |
| 115 | + const pth = path.resolve(root, rel); |
| 116 | + if (pth !== root && !pth.startsWith(root + path.sep)) { return null; } |
| 117 | + return pth; |
| 118 | +} |
| 119 | + |
| 120 | +function runCommand(root, command) { |
| 121 | + return new Promise((resolve) => { |
| 122 | + cp.exec(command, { cwd: root, timeout: 60000, maxBuffer: 1 << 20 }, (err, stdout, stderr) => { |
| 123 | + let out = (stdout || '') + (stderr ? '\n[stderr]\n' + stderr : ''); |
| 124 | + if (err && err.killed) { out += '\n[timed out after 60s]'; } |
| 125 | + else if (err) { out += '\n[exit ' + (err.code != null ? err.code : '?') + ']'; } |
| 126 | + resolve(out.slice(0, 8000) || '(no output)'); |
| 127 | + }); |
| 128 | + }); |
| 129 | +} |
| 130 | + |
| 131 | +/** Execute one tool call; returns a string result for the model. */ |
| 132 | +async function runTool(tu, ctx) { |
| 133 | + const root = ctx.root; |
| 134 | + const input = tu.input || {}; |
| 135 | + try { |
| 136 | + if (tu.name === 'list_files') { |
| 137 | + ctx.post({ type: 'agentTool', icon: '📁', text: 'list_files ' + (input.glob || '') }); |
| 138 | + const uris = await vscode.workspace.findFiles(input.glob || '**/*', FILE_EXCLUDES, 600); |
| 139 | + return uris.map((u) => vscode.workspace.asRelativePath(u)).join('\n') || '(no files)'; |
| 140 | + } |
| 141 | + if (tu.name === 'read_file') { |
| 142 | + ctx.post({ type: 'agentTool', icon: '📄', text: 'read ' + input.path }); |
| 143 | + const abs = safeJoin(root, input.path || ''); |
| 144 | + if (!abs || !fs.existsSync(abs)) { return 'ERROR: file not found: ' + input.path; } |
| 145 | + let body = fs.readFileSync(abs, 'utf8'); |
| 146 | + if (body.length > 100 * 1024) { body = body.slice(0, 100 * 1024) + '\n…(truncated)…'; } |
| 147 | + return body; |
| 148 | + } |
| 149 | + if (tu.name === 'search') { |
| 150 | + ctx.post({ type: 'agentTool', icon: '🔎', text: 'search "' + input.query + '"' }); |
| 151 | + return (await rgSearch(String(input.query || ''), root)) || '(no matches)'; |
| 152 | + } |
| 153 | + if (tu.name === 'edit_file') { |
| 154 | + const abs = safeJoin(root, input.path || ''); |
| 155 | + if (!abs) { return 'ERROR: path is outside the workspace'; } |
| 156 | + if (!fs.existsSync(abs)) { return 'ERROR: file not found: ' + input.path + ' (use write_file to create it)'; } |
| 157 | + const cur = fs.readFileSync(abs, 'utf8'); |
| 158 | + const oldStr = String(input.old_str || ''); |
| 159 | + const newStr = String(input.new_str || ''); |
| 160 | + if (!oldStr) { return 'ERROR: old_str is empty.'; } |
| 161 | + const idx = cur.indexOf(oldStr); |
| 162 | + if (idx < 0) { return 'ERROR: old_str was not found in ' + input.path + '. Read the file and copy the exact text (including whitespace).'; } |
| 163 | + if (cur.indexOf(oldStr, idx + 1) >= 0) { return 'ERROR: old_str appears more than once in ' + input.path + '. Add more surrounding context so it is unique.'; } |
| 164 | + const proposed = cur.slice(0, idx) + newStr + cur.slice(idx + oldStr.length); |
| 165 | + const ok = await ctx.applyEdit({ path: input.path, exists: true, proposed }); |
| 166 | + if (!ok) { return 'ERROR: could not apply the edit to ' + input.path + ' (file may be read-only or in conflict).'; } |
| 167 | + ctx.editCount = (ctx.editCount || 0) + 1; |
| 168 | + return 'Applied edit to ' + input.path + ' (the user is reviewing it with Keep/Undo; do not re-edit it).'; |
| 169 | + } |
| 170 | + if (tu.name === 'write_file') { |
| 171 | + const abs = safeJoin(root, input.path || ''); |
| 172 | + if (!abs) { return 'ERROR: path is outside the workspace'; } |
| 173 | + const existed = fs.existsSync(abs); |
| 174 | + const newStr = String(input.content || ''); |
| 175 | + const ok = await ctx.applyEdit({ path: input.path, exists: existed, proposed: newStr }); |
| 176 | + if (!ok) { return 'ERROR: could not write ' + input.path + ' (path may be read-only or in conflict).'; } |
| 177 | + ctx.editCount = (ctx.editCount || 0) + 1; |
| 178 | + return 'Applied edit to ' + input.path + ' (pending the user\'s Keep/Undo review).'; |
| 179 | + } |
| 180 | + if (tu.name === 'run_command') { |
| 181 | + const approved = await ctx.approve({ kind: 'command', command: String(input.command || ''), explanation: input.explanation || '' }); |
| 182 | + if (!approved) { return 'User skipped this command. Do not retry it.'; } |
| 183 | + ctx.post({ type: 'agentTool', icon: '▶️', text: 'ran: ' + input.command }); |
| 184 | + return await runCommand(root, String(input.command || '')); |
| 185 | + } |
| 186 | + return 'ERROR: unknown tool ' + tu.name; |
| 187 | + } catch (e) { |
| 188 | + return 'ERROR: ' + ((e && e.message) || e); |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +/** |
| 193 | + * Run the agent loop until the model stops calling tools (or the step cap / abort). |
| 194 | + * `ctx.messages` is the persistent session transcript — already seeded with the new user goal — |
| 195 | + * and is appended to in place, so subsequent runs remember this one. |
| 196 | + * @param {{messages:any[], apiKey:string, model:string, maxSteps:number, |
| 197 | + * post:(m:any)=>void, approve:(req:any)=>Promise<boolean>, |
| 198 | + * applyEdit:(req:any)=>Promise<boolean>, signal:AbortSignal}} ctx |
| 199 | + * applyEdit applies file edits (apply-then-review); approve gates run_command only. |
| 200 | + */ |
| 201 | +async function runAgent(ctx) { |
| 202 | + const root = workspaceRoot(); |
| 203 | + if (!root) { ctx.post({ type: 'agentError', message: 'Open a folder first — the agent works on your workspace.' }); ctx.post({ type: 'agentDone', reason: 'error' }); return; } |
| 204 | + ctx.root = root; |
| 205 | + |
| 206 | + const messages = ctx.messages; |
| 207 | + let step = 0; |
| 208 | + let reason = 'done'; |
| 209 | + let nudges = 0; |
| 210 | + try { |
| 211 | + while (step++ < ctx.maxSteps) { |
| 212 | + if (ctx.signal.aborted) { reason = 'stopped'; break; } |
| 213 | + ctx.post({ type: 'agentStatus', text: 'thinking…' }); |
| 214 | + let streamed = false; |
| 215 | + const turn = await streamClaudeAgentTurn({ |
| 216 | + apiKey: ctx.apiKey, model: ctx.model, maxTokens: 8192, system: SYSTEM, |
| 217 | + messages, tools: TOOLS, signal: ctx.signal, |
| 218 | + onText: (t) => { streamed = true; ctx.post({ type: 'agentDelta', text: t }); }, |
| 219 | + onToolStart: (name) => { |
| 220 | + const verb = name === 'edit_file' || name === 'write_file' ? 'preparing edit (' + name + ')…' |
| 221 | + : name === 'run_command' ? 'preparing command…' : 'running ' + name + '…'; |
| 222 | + ctx.post({ type: 'agentStatus', text: verb }); |
| 223 | + } |
| 224 | + }); |
| 225 | + if (streamed) { ctx.post({ type: 'agentTurnEnd' }); } |
| 226 | + messages.push({ role: 'assistant', content: turn.content }); |
| 227 | + |
| 228 | + const toolUses = turn.content.filter((c) => c.type === 'tool_use'); |
| 229 | + if (toolUses.length) { |
| 230 | + // CRITICAL: every tool_use MUST get a matching tool_result, even on abort, or the |
| 231 | + // next API call 400s ("tool_use ids were found without tool_result blocks"). |
| 232 | + const results = []; |
| 233 | + let cancelled = false; |
| 234 | + for (const tu of toolUses) { |
| 235 | + if (cancelled || ctx.signal.aborted) { cancelled = true; results.push({ type: 'tool_result', tool_use_id: tu.id, content: 'Cancelled by the user.' }); continue; } |
| 236 | + const out = await runTool(tu, ctx); |
| 237 | + results.push({ type: 'tool_result', tool_use_id: tu.id, content: String(out) }); |
| 238 | + } |
| 239 | + messages.push({ role: 'user', content: results }); |
| 240 | + if (cancelled || ctx.signal.aborted) { reason = 'stopped'; break; } |
| 241 | + nudges = 0; |
| 242 | + continue; |
| 243 | + } |
| 244 | + |
| 245 | + // No tool calls this turn. |
| 246 | + const text = turn.content.filter((c) => c.type === 'text').map((c) => c.text).join(''); |
| 247 | + if (turn.stop_reason === 'max_tokens') { |
| 248 | + ctx.post({ type: 'agentTool', icon: '⚠️', text: 'response was cut off — switching to smaller edits' }); |
| 249 | + messages.push({ role: 'user', content: 'Your last response was cut off (too long). Use edit_file for small, targeted changes instead of rewriting whole files. Continue.' }); |
| 250 | + if (nudges++ < 3) { continue; } |
| 251 | + reason = 'limit'; break; |
| 252 | + } |
| 253 | + if (/(^|\n)\s*done\s*:/i.test(text) || /\bdone\.?\s*$/i.test(text.trim())) { reason = 'done'; break; } |
| 254 | + // The model stalled on intent without acting — nudge it to act (a few times). |
| 255 | + if (nudges++ < 3) { |
| 256 | + messages.push({ role: 'user', content: 'Stop planning. You have read enough. Make your next edit_file (or write_file) call NOW — do not describe it, do it. If the goal is truly complete, reply with a one-line summary starting with "Done:".' }); |
| 257 | + continue; |
| 258 | + } |
| 259 | + reason = 'done'; |
| 260 | + break; |
| 261 | + } |
| 262 | + if (step > ctx.maxSteps) { reason = 'limit'; } |
| 263 | + } catch (e) { |
| 264 | + if (ctx.signal.aborted) { reason = 'stopped'; } |
| 265 | + else { ctx.post({ type: 'agentError', message: String((e && e.message) || e) }); reason = 'error'; } |
| 266 | + } finally { |
| 267 | + ctx.post({ type: 'agentDone', reason, edits: ctx.editCount || 0 }); |
| 268 | + } |
| 269 | +} |
| 270 | + |
| 271 | +module.exports = { runAgent, makeDiff }; |
0 commit comments