rob-revisited/ide/ui/js/agent.js

740 lines
37 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Claude, seen working in the IDE.
//
// ClaudeWatch: the Claude window's stream (claude.event) shown where it happens: the file Claude reads opens at the
// lines it reads, an edit is marked before (what it replaces) and after (what it wrote), its commands appear in the Run
// window with their output, its searches in the Find window, its plan above the conversation. The keyboard stays where
// the user is; nothing moves while the user types in an editor.
//
// AgentTools: the IDE's own tools for Claude (MCP server jumphp-ide, JumPHP\Ide\Agent): PHP hands each call over as
// agent.call {call, tool, args}, this does it in the interface and answers with agent.reply.
import { backend } from './backend.js';
import { monaco } from './editor.js';
import { el, dialog, notify, prefs } from './ui.js';
import { EditReview, STEP_TOOLS, applyHunks, newStepId, planStep, remember } from './steps.js';
import { profileAgentTools } from './profiler.js';
import { cryoAgentTools } from './cryo.js';
import { boardAgentTools } from './board.js';
import { composerAgentTools } from './composer.js';
import { consoleAgentTools } from './symfony-console.js';
import { dockerAgentTools } from './docker.js';
import { cpcAgentTools } from './cpc.js';
import { svnAgentTools } from './vcs.js';
export const IDE_TOOL = 'mcp__jumphp-ide__';
/** Where a file path of Claude's (often absolute) is in the project, or null outside it. */
function relative(app, path) {
if (!path) return null;
const root = app.project?.root || '';
if (root && path.startsWith(root + '/')) return path.slice(root.length + 1);
return path.startsWith('/') ? null : path.replace(/^\.\//, '');
}
function text(content) {
if (typeof content === 'string') return content;
if (Array.isArray(content)) return content.map((c) => (typeof c === 'string' ? c : c.text || '')).join('\n');
return '';
}
/** Marks on lines of a file: a coloured band, a label after the first line. They stay with the file's model. */
class Marks {
constructor(app) {
this.app = app;
this.byKey = new Map(); // key -> {model, ids, timer}
}
set(key, path, startLine, endLine, kind, label, ms = 0) {
this.clear(key);
const model = this.app.editors.files.get(path)?.model;
if (!model || model.isDisposed()) return;
const last = model.getLineCount();
const start = Math.max(1, Math.min(startLine, last));
const end = Math.max(start, Math.min(endLine || start, last));
const decorations = [{
range: new monaco.Range(start, 1, end, model.getLineMaxColumn(end)),
options: { isWholeLine: true, className: `claude-mark ${kind}`, hoverMessage: label ? { value: label } : undefined, linesDecorationsClassName: `claude-mark-gutter ${kind}`,
overviewRuler: { color: { read: '#56a8f5', edit: '#cf8e6d', done: '#5fb865', note: '#c77dbb' }[kind] || '#d97757', position: monaco.editor.OverviewRulerLane.Right } },
}];
if (label) {
decorations.push({ range: new monaco.Range(start, model.getLineMaxColumn(start), start, model.getLineMaxColumn(start)),
options: { after: { content: ` ✦ ${label}`, inlineClassName: `claude-mark-label ${kind}` } } });
}
const ids = model.deltaDecorations([], decorations);
const entry = { model, ids, timer: ms ? setTimeout(() => this.clear(key), ms) : null };
this.byKey.set(key, entry);
}
clear(key) {
const entry = this.byKey.get(key);
if (!entry) return;
clearTimeout(entry.timer);
if (!entry.model.isDisposed()) entry.model.deltaDecorations(entry.ids, []);
this.byKey.delete(key);
}
clearAll(prefix = '') {
for (const key of [...this.byKey.keys()]) if (key.startsWith(prefix)) this.clear(key);
}
}
/** The line range of a text in a model (its first match), or null. */
function find(model, needle) {
if (!model || !needle) return null;
const matches = model.findMatches(needle, false, false, true, null, false, 1);
if (!matches.length) return null;
return { start: matches[0].range.startLineNumber, end: matches[0].range.endLineNumber };
}
export class ClaudeWatch {
constructor(app, panel) {
this.app = app;
this.panel = panel;
this.marks = new Marks(app);
this.on = prefs.get('claudeFollow', true);
this.uses = new Map(); // tool_use id -> {name, input, path}
this.lastTyping = 0;
document.addEventListener('keydown', (e) => { if (e.target.closest?.('.monaco-editor')) this.lastTyping = Date.now(); }, true);
}
toggle(on = !this.on) {
this.on = on;
prefs.set('claudeFollow', on);
if (!on) this.marks.clearAll('w:');
}
/** The user types in an editor: do not take the editor away. */
busy() { return Date.now() - this.lastTyping < 2500; }
async show(path, line, endLine) {
if (this.busy() && this.app.editors.activePath() !== path) {
await this.app.editors.load(path).catch(() => null);
return;
}
await this.app.editors.open(path, { preview: true, focus: false, ...(line ? { line, endLine: endLine || line, select: false } : {}) });
this.app.tree?.reveal(path);
}
status(text) { this.app.status?.(text); }
/** Claude starts a tool (an assistant message's tool_use). */
async use(part) {
const input = part.input || {};
const path = relative(this.app, input.file_path || input.notebook_path);
this.uses.set(part.id, { name: part.name, input, path });
if (!this.on || part.name.startsWith(IDE_TOOL)) return;
try {
switch (part.name) {
case 'Read': {
if (!path) return;
const from = Number(input.offset) || 0;
const to = from && input.limit ? from + Number(input.limit) - 1 : 0;
this.status(`Claude reads ${path}`);
await this.show(path, from || 1, to || undefined);
this.marks.set('w:' + part.id, path, from || 1, to || from || 1, 'read', from ? `Claude reads lines ${from}–${to || '…'}` : 'Claude reads this file', 2500);
break;
}
case 'Edit': case 'MultiEdit': {
if (!path) return;
this.status(`Claude edits ${path}`);
if (this.panel.mode === 'step') break; // Step by step: the review shows the change (steps.js)
await this.show(path);
const model = this.app.editors.files.get(path)?.model;
const first = part.name === 'Edit' ? input.old_string : input.edits?.[0]?.old_string;
const at = find(model, first);
if (at) {
this.app.editors.reveal(this.app.editors.focused, { line: at.start, endLine: at.end, select: false, focus: false });
this.marks.set('w:' + part.id, path, at.start, at.end, 'edit', 'Claude is changing this');
}
break;
}
case 'Write': {
if (!path) return;
this.status(`Claude writes ${path}`);
break;
}
case 'Bash': {
if (!this.app.tools.run) return;
const command = String(input.command || '');
this.app.runner.addExternal('claude:' + part.id, 'Claude: ' + (input.description || command).slice(0, 40), command, { show: !this.busy() });
this.status(`Claude runs ${command.slice(0, 80)}`);
break;
}
case 'Grep': {
if (!input.pattern || this.busy()) return;
this.app.find.show({ query: String(input.pattern), regex: true, include: input.glob || '', quiet: true });
this.status(`Claude searches ${input.pattern}`);
break;
}
case 'Glob': this.status(`Claude looks for ${input.pattern}`); break;
case 'TodoWrite': this.panel.showPlan(input.todos || []); break;
}
} catch (e) {
console.warn('[claude watch]', e);
}
}
/** A tool ended (a user message's tool_result). */
async result(part) {
const use = this.uses.get(part.tool_use_id);
if (!use) return;
this.uses.delete(part.tool_use_id);
const { name, input, path } = use;
if (name === 'Bash' && this.app.tools.run) {
this.app.runner.finishExternal('claude:' + part.tool_use_id, text(part.content), !!part.is_error);
return;
}
if (!this.on || !path || part.is_error || !['Edit', 'MultiEdit', 'Write'].includes(name)) {
this.marks.clear('w:' + part.tool_use_id);
return;
}
// what Claude wrote: into the editor (from the disk), marked
await this.app.editors.reloadFromDisk([path]);
if (name === 'Write' && !this.app.editors.files.has(path)) await this.show(path);
else if (!this.busy()) await this.show(path);
const model = this.app.editors.files.get(path)?.model;
if (!model) return;
let at;
if (name === 'Write') at = { start: 1, end: Math.min(model.getLineCount(), 400) };
else at = find(model, name === 'Edit' ? input.new_string : input.edits?.at(-1)?.new_string) || null;
this.marks.clear('w:' + part.tool_use_id);
if (!at) return;
if (!this.busy() && this.app.editors.activePath() === path) this.app.editors.reveal(this.app.editors.focused, { line: at.start, endLine: at.end, select: false, focus: false });
this.marks.set('w:' + part.tool_use_id, path, at.start, at.end, 'done', name === 'Write' ? 'Claude wrote this file' : 'Claude changed this', 6000);
this.app.tree?.refresh();
}
/** The answer ended: what is still marked goes, the plan stays. */
done() {
this.panel.tools?.review?.cancelAll();
for (const [id, use] of this.uses) if (use.name === 'Bash') this.app.runner?.finishExternal('claude:' + id, '', true);
this.uses.clear();
this.status('Claude is done');
}
}
/** The run configurations Claude may start with a command line: bin/jumphp's checks, builds and runs, not any program. */
const RUN_COMMANDS = ['test', 'shot', 'build', 'build:remote', 'build:site', 'webshot', 'siteshot', 'lint', 'run', 'app:test', 'app:shot', 'app:run', 'serve'];
function parseCommand(line) {
const words = (String(line).match(/"[^"]*"|'[^']*'|\S+/g) || []).map((w) => w.replace(/^(["'])(.*)\1$/, '$2'));
const env = {};
while (words.length && /^JUMPHP_[A-Z_]+=/.test(words[0])) {
const [k, ...v] = words.shift().split('=');
env[k] = v.join('=');
}
if (words[0] === 'jumphp') words[0] = 'bin/jumphp';
return { words, env };
}
export class AgentTools {
constructor(app, watch) {
this.app = app;
this.watch = watch;
this.marks = watch.marks;
backend.on('agent.call', (p) => this.call(p));
}
async call({ call, tool, args }) {
let result = null;
let error = null;
try {
const fn = this['tool_' + tool];
if (!fn) throw new Error(`the IDE has no tool ${tool}`);
result = await fn.call(this, args || {});
} catch (e) {
error = e?.message || String(e);
}
backend.invoke('agent.reply', { call, result: result ?? 'ok', error }).catch(() => null);
}
path(args) {
const path = relative(this.app, String(args.path || ''));
if (!path) throw new Error('give a path of the project (relative to its root)');
return path;
}
async open(path, line, endLine) {
const tab = await this.app.editors.open(path, { focus: false, ...(line ? { line, endLine: endLine || line } : {}) });
if (!tab) throw new Error(`cannot open ${path}`);
this.app.tree?.reveal(path);
return tab;
}
tool_get_state() {
const eds = this.app.editors;
const ed = eds.editor();
const sel = ed?.getSelection();
const model = ed?.getModel();
const active = eds.activePath();
return {
project: this.app.project?.name,
root: this.app.project?.root,
open_files: [...new Set(eds.groups.flatMap((g) => g.tabs.filter((t) => t.kind !== 'diff').map((t) => t.path)))],
unsaved: eds.dirtyPaths(),
active: active ? {
path: active,
cursor: ed?.getPosition() ? { line: ed.getPosition().lineNumber, column: ed.getPosition().column } : null,
selection: sel && !sel.isEmpty() && model ? { start_line: sel.startLineNumber, end_line: sel.endLineNumber, text: model.getValueInRange(sel).slice(0, 8000) } : null,
} : null,
tool_windows: this.app.open,
available_tool_windows: Object.keys(this.app.tools),
run_configurations: (this.app.runner?.configs || []).map((c) => ({ id: c.id, label: c.label, kind: c.kind, command: c.command.join(' ') })),
problems: this.app.problems?.count() ?? 0,
};
}
async tool_open_file(args) {
const path = this.path(args);
await this.open(path, Number(args.line) || 0, Number(args.end_line) || 0);
return `opened ${path}`;
}
async tool_highlight(args) {
const path = this.path(args);
const start = Number(args.start_line) || 1;
const end = Number(args.end_line) || start;
await this.open(path, start, end);
this.app.editors.editor()?.setSelection(new monaco.Range(start, 1, start, 1));
this.marks.set('note:' + path + ':' + start, path, start, end, 'note', args.message ? `Claude: ${args.message}` : 'Claude', 0);
return `highlighted ${path}:${start}-${end}`;
}
tool_clear_highlights() {
this.marks.clearAll('note:');
return 'cleared';
}
async tool_show_diff(args) {
if (!args.path) {
if (!this.app.tools.commit) throw new Error('this project has no Git');
this.app.showTool('commit', true);
return 'the Commit window shows the changed files';
}
const path = this.path(args);
await this.app.git.diff(path);
return `diff of ${path} shown`;
}
tool_show_tool(args) {
const id = String(args.tool || '');
if (!this.app.tools[id]) throw new Error(`no tool window ${id} here (there are: ${Object.keys(this.app.tools).join(', ')})`);
this.app.showTool(id, true);
return `${id} shown`;
}
async tool_find_in_files(args) {
const query = String(args.query || '');
if (!query) throw new Error('nothing to find');
this.app.find.show({ query, regex: !!args.regex, include: args.include || '', quiet: true });
const r = await backend.invoke('search.text', { query, options: { ...this.app.find.options, regex: !!args.regex, include: args.include || '' } });
return { matches: r.matches, files: r.files, truncated: !!r.truncated,
results: r.results.slice(0, 30).map((f) => ({ path: f.path, lines: f.matches.slice(0, 10).map((m) => m.line) })) };
}
async tool_search_engine(args) {
const query = String(args.query || '');
if (!query) throw new Error('nothing to find');
const r = await backend.invoke('search.engine', { query, limit: Math.min(200, +args.limit || 30) });
return { total: r.total, complete: r.complete, ms: r.ms,
results: r.results.map((f) => ({ path: f.path, score: f.score, lines: f.lines.map((l) => ({ line: l.line, text: l.text.trim().slice(0, 200) })) })) };
}
async tool_recent_changes(args) {
const minutes = +args.since_minutes || 0;
const files = await backend.invoke('files.recent', { since: minutes * 60, ext: args.ext || '', limit: Math.min(500, +args.limit || 50) });
const git = this.app.git?.byPath;
return files.map((f) => ({ path: f.path, modified: new Date(f.mtime * 1000).toISOString(), size: f.size,
git: git?.get(f.path)?.status || null, origin: f.origin || 'unknown' }));
}
/** A run configuration from an id, a label or a command line (bin/jumphp test pong): {config, env}. */
resolveRun(args) {
const runner = this.app.runner;
if (!runner || !this.app.project?.capabilities?.run) throw new Error('nothing runs in this project here');
const wanted = String(args.config || '').trim();
let config = runner.configs.find((c) => c.id === wanted) || runner.configs.find((c) => c.label.toLowerCase() === wanted.toLowerCase());
let env = {};
if (!config) {
const parsed = parseCommand(wanted);
config = runner.configs.find((c) => c.command.join(' ') === parsed.words.join(' '));
env = parsed.env;
if (!config) {
if (parsed.words[0] !== 'bin/jumphp' || !RUN_COMMANDS.includes(parsed.words[1])) {
throw new Error(`unknown run configuration "${wanted}": use an id of get_state, or bin/jumphp ${RUN_COMMANDS.join(' | ')} …`);
}
const kind = /test$/.test(parsed.words[1]) ? 'test' : /shot$/.test(parsed.words[1]) ? 'shot' : parsed.words[1].startsWith('build') ? 'build' : 'run';
config = { id: 'adhoc', kind, label: parsed.words.slice(1).join(' '), command: parsed.words };
}
}
return { config, env };
}
async tool_run(args) {
const runner = this.app.runner;
const { config, env } = this.resolveRun(args);
if (args.wait === false) {
const id = await runner.start(config, env);
if (id === null || id === undefined) throw new Error(`${config.label} could not start`);
return { started: config.label, run: id };
}
const end = await runner.startAndWait(config, env);
if (!end) throw new Error(`${config.label} could not start`);
const run = runner.runs.find((r) => r.id === end.id);
const t = end.tests;
return {
configuration: config.label, exit_code: end.code, seconds: end.seconds, error: end.error || undefined,
tests: t ? { passed: t.passed, failed: t.failed, skipped: t.skipped } : undefined,
screenshot: end.image || undefined,
output_end: (run?.output || '').slice(-4000),
};
}
// the debugger (Xdebug): the same one the user drives, shown in the gutter and the Debug window -------------------
debugger() {
if (!this.app.debugger) throw new Error('no debugger here: it needs a JumPHP project run on this computer (bin/jumphp with Docker)');
return this.app.debugger;
}
/** Where it stopped, with the variables of a frame (short: the values Xdebug gives at depth 1). */
async debugState(frame = 0) {
const d = this.debugger();
if (!d.paused) return { status: (d.sessions || []).length ? 'running' : 'not debugging', breakpoints: await backend.invoke('debug.breakpoints.list') };
const p = d.paused;
let variables = [];
try { variables = await backend.invoke('debug.variables', { session: p.session, depth: frame }); } catch (e) { variables = [{ name: 'error', value: e.message }]; }
return {
status: 'paused', session: p.session, path: p.path, line: p.line, frame,
stack: p.stack.map((f) => `#${f.level} ${f.where} ${f.path ? `${f.path}:${f.line}` : `(outside the project) line ${f.line}`}`),
variables: variables.slice(0, 80).map((v) => ({ name: v.name, type: v.type, value: v.value, expandable: v.children || undefined })),
};
}
/** Waits for the program to stop at a breakpoint, end, or the time to pass. */
waitDebug(seconds, runId = null, untilEnd = false) {
return new Promise((resolve) => {
const offs = [];
const done = (what) => { offs.forEach((off) => off?.()); clearTimeout(timer); resolve(what); };
const timer = setTimeout(() => done('timeout'), seconds * 1000);
offs.push(backend.on('debug.paused', () => setTimeout(() => done('paused'), 50)));
if (runId !== null) offs.push(backend.on('run.exit', (p) => { if (p.id === runId) done('ended'); }));
if (untilEnd) offs.push(backend.on('debug.ended', () => done('ended')));
});
}
async tool_debug_breakpoints(args) {
const d = this.debugger();
if (args.clear_all) d.clearAll();
if (args.path) {
const path = this.path(args);
const lines = (args.lines || []).map((l) => (typeof l === 'object' ? { line: Number(l.line), condition: l.condition || null } : { line: Number(l), condition: null }))
.filter((b) => b.line > 0).sort((a, b) => a.line - b.line);
await d.set(path, lines);
if (lines.length) await this.open(path, lines[0].line);
}
return { breakpoints: await backend.invoke('debug.breakpoints.list') };
}
async tool_debug_run(args) {
const d = this.debugger();
const { config, env } = this.resolveRun(args);
const id = await this.app.runner.start(config, { ...env, JUMPHP_XDEBUG: String((await backend.invoke('debug.listen')).port) });
if (id === null || id === undefined) throw new Error(`${config.label} could not start`);
this.app.showTool('debug', true);
const what = await this.waitDebug(Number(args.timeout) || 120, id);
if (what === 'paused') return this.debugState();
const run = this.app.runner.runs.find((r) => r.id === id);
return { status: what === 'ended' ? 'the program ended without stopping at a breakpoint' : `still running after ${Number(args.timeout) || 120} s (no breakpoint reached yet: debug_state later, or debug_step stop)`,
run: id, exit_code: run?.code, output_end: (run?.output || '').slice(-3000) };
}
async tool_debug_state(args) {
return this.debugState(Number(args.frame) || 0);
}
async tool_debug_step(args) {
const d = this.debugger();
const how = String(args.action || 'step_over');
const session = d.paused?.session || d.sessions?.[0]?.id;
if (!session) throw new Error('no program is being debugged: debug_run first');
if (how === 'stop') { await d.step('stop'); return { status: 'stopped' }; }
const wait = this.waitDebug(Number(args.timeout) || 60, null, true);
d.step(how);
const what = await wait;
if (what === 'paused') return this.debugState();
return { status: what === 'ended' ? 'the program ended' : 'running (no breakpoint reached yet)' };
}
async tool_debug_eval(args) {
const d = this.debugger();
if (!d.paused) throw new Error('the program is not stopped: debug_run with a breakpoint first');
const expression = String(args.expression || '');
const r = await backend.invoke('debug.eval', { session: d.paused.session, expression });
d.evaluated = { ...r, name: expression, expression };
d.render();
return { type: r.type, value: r.value, items: (r.items || []).slice(0, 80).map((v) => ({ name: v.name, type: v.type, value: v.value })) };
}
async tool_debug_run_to(args) {
const d = this.debugger();
if (!d.paused) throw new Error('the program is not stopped: debug_run with a breakpoint first');
const path = this.path(args);
const wait = this.waitDebug(Number(args.timeout) || 60, null, true);
d.runTo(path, Number(args.line));
const what = await wait;
if (what === 'paused') return this.debugState();
return { status: what === 'ended' ? 'the program ended before that line' : 'running (that line not reached yet)' };
}
async tool_debug_set_value(args) {
const d = this.debugger();
if (!d.paused) throw new Error('the program is not stopped');
const frame = Number(args.frame) || 0;
const r = await backend.invoke('debug.set', { session: d.paused.session, fullname: String(args.name), expression: String(args.value), depth: frame });
if (frame === d.frame) await d.showFrame();
return r ? { name: r.fullname || args.name, type: r.type, value: r.value } : null;
}
async tool_debug_exceptions(args) {
const d = this.debugger();
if (Array.isArray(args.classes)) await d.setExceptions(args.classes.map(String));
return { exceptions: d.exceptions };
}
async tool_debug_variables(args) {
const d = this.debugger();
if (!d.paused) throw new Error('the program is not stopped');
const frame = Number(args.frame) || 0;
if (!args.name) return (await this.debugState(frame)).variables;
const r = await backend.invoke('debug.children', { session: d.paused.session, fullname: String(args.name), depth: frame });
return r ? { name: r.fullname || args.name, type: r.type, value: r.value, items: (r.items || []).slice(0, 200).map((v) => ({ name: v.name, fullname: v.fullname, type: v.type, value: v.value, expandable: v.children || undefined })) } : null;
}
async tool_play(args) {
const path = this.path(args);
if (!this.app.playTarget(path)) throw new Error(`nothing to play in ${path}`);
await this.app.playFile(path);
return `playing ${path}`;
}
async tool_diagnostics(args) {
if (!args.path) {
const out = {};
for (const [path, list] of this.app.problems.byPath) if (list.length) out[path] = list;
return Object.keys(out).length ? out : 'no problems in the open files';
}
const path = this.path(args);
const file = await this.app.editors.load(path);
if (!file.model) throw new Error(`${path} is not a text file`);
const list = await backend.invoke('php.diagnostics', { path, text: file.model.getValue() });
return list.length ? list.map((d) => `${path}:${d.startLine}:${d.startColumn} ${d.severity}: ${d.message}`).join('\n') : `no problems in ${path}`;
}
tool_ask_user(args) {
const question = String(args.question || '');
const options = Array.isArray(args.options) ? args.options.map(String).slice(0, 8) : [];
return new Promise((resolve) => {
let answered = false;
const answer = (value) => { answered = true; resolve({ answer: value }); };
const input = el('textarea.input', { rows: 2, placeholder: options.length ? 'Or another answer…' : 'Your answer…', style: { width: '100%' } });
const choices = el('div.claude-choices', {}, ...options.map((o) => el('button.btn', { onclick: () => { answer(o); box.close(); } }, o)));
const box = dialog({
title: 'Claude asks', sticky: true,
body: el('div.claude-ask', {}, el('p', {}, question), options.length ? choices : null, input),
buttons: [{ label: 'Skip' }, { label: 'Answer', primary: true, action: () => { if (!input.value.trim()) return false; answer(input.value.trim()); } }],
onClose: () => { if (!answered) resolve({ answer: null, skipped: true }); },
});
this.app.showTool('claude', true);
notify(question.slice(0, 140), 'info', { title: 'Claude asks you' });
});
}
/**
* claude --permission-prompt-tool: a tool that needs a yes (a command, a web page...). The user answers in a dialog:
* once, always for this session (the same command, or the same tool), or no. Claude Code reads the answer as JSON.
*/
tool_permission(args) {
const name = String(args.tool_name || '');
const input = args.input && typeof args.input === 'object' ? args.input : {};
if (STEP_TOOLS.includes(name) && this.watch.panel.mode === 'step') return this.reviewStep(name, input);
const command = name === 'Bash' ? String(input.command || '') : '';
const what = command || input.url || input.file_path || input.path || input.pattern || JSON.stringify(input).slice(0, 400);
// what a "yes" covers: the first word of a command (curl, docker, npm...), else the whole tool
const key = command ? `Bash:${command.trim().split(/\s+/)[0]}` : name;
const allow = () => JSON.stringify({ behavior: 'allow', updatedInput: input });
if (this.permissionGranted(key)) return Promise.resolve(allow());
return new Promise((resolve) => {
let answered = false;
const answer = (yes) => {
answered = true;
if (yes) this.grantPermission(key, duration.value, scope.value === 'all');
resolve(yes ? allow() : JSON.stringify({ behavior: 'deny', message: 'The user said no in the IDE. Do something else, or ask them (ask_user) why.' }));
};
// how long the yes lasts: once, some minutes, this session (until the IDE closes), always (kept for the next sessions)
const duration = el('select.input.small', {}, ...[['once', 'Only this time'], ['5', 'For 5 minutes'], ['15', 'For 15 minutes'], ['60', 'For 1 hour'],
['session', 'For this session'], ['always', 'Always']].map(([v, t]) => el('option', { value: v }, t)));
const scope = el('select.input.small', {}, el('option', { value: 'key' }, command ? `Same kind of command (“${key.slice(5)}”)` : `Every ${name}`),
el('option', { value: 'all' }, 'Everything Claude asks'));
const body = el('div.claude-ask', {},
el('p', {}, command ? 'Claude wants to run this command:' : `Claude wants to use ${name}:`),
el('pre.claude-permission', { style: { whiteSpace: 'pre-wrap', maxHeight: '240px', overflow: 'auto' } }, String(what)),
input.description ? el('p.pub-faint', {}, String(input.description)) : null,
el('div.claude-ask-allow', { style: { display: 'flex', gap: '6px', flexWrap: 'wrap', marginTop: '8px' } }, duration, scope));
dialog({
title: 'Claude asks for permission', body, sticky: true,
onClose: () => { if (!answered) answer(false); },
buttons: [{ label: 'No', action: () => answer(false) }, { label: 'Allow', primary: true, action: () => answer(true) }],
});
this.app.showTool('claude', true);
notify(String(what).slice(0, 140), 'info', { title: 'Claude asks for permission' });
});
}
/**
* Mode "Step by step": a change of Claude's is shown as a diff in the editor and waits for the user (steps.js).
* Answers Claude Code with the blocks kept (updatedInput), or a refusal carrying the user's message.
*/
async reviewStep(name, input) {
const allow = (updated = input) => JSON.stringify({ behavior: 'allow', updatedInput: updated });
const path = relative(this.app, input.file_path);
const panel = this.watch.panel;
const conv = panel.active;
if (!path || !conv) return allow();
const file = await backend.invoke('file.read', { path }).catch(() => null);
const before = typeof file?.content === 'string' && !file.readOnly ? file.content : null;
if (name !== 'Write' && before === null) return allow(); // Claude Code reports that error by itself
const plan = planStep(name, input, before);
if (plan.error) return allow();
const id = newStepId();
const lines = (t) => (t === '' ? 0 : t.replace(/\n$/, '').split('\n').length);
const item = {
role: 'step', id, name, path, n: conv.items.filter((i) => i.role === 'step').length + 1, status: 'pending', time: Date.now(),
ask: [...conv.items].reverse().find((i) => i.role === 'user')?.text || '',
hunks: plan.hunks.map((h) => ({ kind: h.kind, old: h.kind === 'write' ? '' : h.old, new: h.kind === 'write' ? '' : h.new, all: !!h.all, index: h.index })),
added: plan.hunks.reduce((n, h) => n + lines(h.new), 0), removed: plan.hunks.reduce((n, h) => n + lines(h.kind === 'write' ? (plan.before ?? '') : h.old), 0),
};
if (name === 'Write') item.writeBefore = before !== null && before.length <= 60000 ? before : (before === null ? null : undefined);
this.review ??= new EditReview(this.app);
const answer = await this.review.ask(item, plan, conv);
const accepted = plan.hunks.filter((h) => answer.keep.has(h.index));
if (!accepted.length) {
item.status = 'declined';
conv.refreshStep(item);
return JSON.stringify({ behavior: 'deny', message: `The user declined this change${answer.message ? `: ${answer.message}` : ''}. Do not apply it as it is; take their message into account, or ask them (ask_user).` });
}
const partial = accepted.length < plan.hunks.length;
item.status = partial ? 'partial' : 'accepted';
item.hunks = item.hunks.filter((h) => answer.keep.has(h.index));
remember(id, { before: plan.before, after: applyHunks(plan.before, plan.hunks, answer.keep) });
conv.refreshStep(item);
const updated = partial && name === 'MultiEdit' ? { ...input, edits: (input.edits || []).filter((_, i) => answer.keep.has(i)) } : input;
if (answer.message) conv.add({ role: 'note', text: `You told Claude: ${answer.message}` });
return allow(updated);
}
/** Is this kind of tool (key) allowed now: for the session, for a time not over yet, or always (prefs)? '*' = everything. */
permissionGranted(key) {
const now = Date.now();
const rules = (this.grants ??= new Map());
for (const k of [key, '*']) {
const until = rules.get(k);
if (until === undefined) continue;
if (until === Infinity || until > now) return true;
rules.delete(k);
}
const always = prefs.get('claudeAlwaysAllow', []);
return Array.isArray(always) && (always.includes(key) || always.includes('*'));
}
/** @param how 'once' | minutes | 'session' | 'always' */
grantPermission(key, how, everything = false) {
if (how === 'once') {
if (!everything) return;
key = '*';
how = '1'; // "everything, only this time" makes no sense: a minute
}
if (everything) key = '*';
if (how === 'always') {
const list = prefs.get('claudeAlwaysAllow', []);
if (!list.includes(key)) prefs.set('claudeAlwaysAllow', [...list, key]);
return;
}
(this.grants ??= new Map()).set(key, how === 'session' ? Infinity : Date.now() + Number(how) * 60000);
}
/** Forget every permission given (the session's, the timed ones, the always ones). */
revokePermissions() { this.grants = new Map(); prefs.set('claudeAlwaysAllow', []); }
/** The Terminal tool window's tabs (desktop IDE only). */
async terminalPanel() {
const panel = this.app.terminal;
if (!panel) throw new Error('this IDE has no Terminal (the desktop IDE only)');
this.app.showTool('terminal', true);
if (!panel.terms.length) { await panel.open(); await panel.ready(panel.current()); }
return panel;
}
async terminalTab(args) {
const panel = await this.terminalPanel();
const t = args.tab !== undefined ? panel.terms.find((x) => x.id === Number(args.tab)) : panel.current();
if (!t) throw new Error('no such Terminal tab (see terminal_list)');
return [panel, t];
}
async tool_terminal_list() {
const panel = await this.terminalPanel();
return panel.terms.map((t) => ({ tab: t.id, label: t.label, active: t === panel.active, running: !t.ended, cols: t.term.cols, rows: t.term.rows }));
}
async tool_terminal_send(args) {
const [panel, t] = await this.terminalTab(args);
if (t.ended) throw new Error('that shell has ended');
panel.active = t; panel.render();
const keys = { 'ctrl-c': '\x03', 'ctrl-d': '\x04', esc: '\x1b', enter: '\r', tab: '\t', up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D' };
let data = String(args.text ?? '');
if (data !== '' && args.enter !== false) data += '\r';
for (const k of args.keys || []) data += keys[k] ?? '';
if (data === '') throw new Error('nothing to send (text or keys)');
panel.input(t, data);
return `sent to tab ${t.id}`;
}
async tool_terminal_read(args) {
const [, t] = await this.terminalTab(args);
const wait = Math.min(15000, Math.max(0, Number(args.wait_ms) || 0));
if (wait) await new Promise((r) => setTimeout(r, wait));
const buf = t.term.buffer.active;
const all = [];
for (let i = 0; i < buf.length; i++) all.push(buf.getLine(i)?.translateToString(true) ?? '');
while (all.length && all[all.length - 1].trim() === '') all.pop();
return all.slice(-Math.min(500, Math.max(1, Number(args.lines) || 40))).join('\n') || '(empty screen)';
}
tool_notify(args) {
notify(String(args.message || ''), ['info', 'success', 'error'].includes(args.kind) ? args.kind : 'info', { title: 'Claude' });
return 'shown';
}
}
Object.assign(AgentTools.prototype, cryoAgentTools); // cryo_inspect / cryo_diff / cryo_sandbox / cryo_live (cryo.js)
Object.assign(AgentTools.prototype, dockerAgentTools); // docker_ps / docker_logs / docker_hub_search / docker_pull (docker.js)
Object.assign(AgentTools.prototype, profileAgentTools); // profile_run / profile_summary / profile_compare (profiler.js)
Object.assign(AgentTools.prototype, composerAgentTools); // composer_search / composer_package / composer_outdated / composer_require / composer_remove (composer.js)
Object.assign(AgentTools.prototype, consoleAgentTools); // symfony_commands / symfony_run (symfony-console.js)
Object.assign(AgentTools.prototype, boardAgentTools); // board_list / board_add_card / board_move_card / board_update_card / notes_list / note_save (board.js)
Object.assign(AgentTools.prototype, cpcAgentTools); // cpc_run / cpc_dump / cpc_extract_gfx / cpc_extract_sound (cpc.js)
Object.assign(AgentTools.prototype, svnAgentTools); // svn_status / svn_diff / svn_commit / svn_update / svn_log (vcs.js)
export function ideToolLabel(name, input) {
const tool = name.slice(IDE_TOOL.length);
const what = input.path ? `${input.path}${input.start_line || input.line ? ':' + (input.start_line || input.line) : ''}` : input.config || input.question || input.message || input.query || input.package || input.tool || '';
return { tool, what: String(what), label: { get_state: 'Looked at the IDE', open_file: 'Opened', highlight: 'Pointed at', clear_highlights: 'Cleared the marks',
show_diff: 'Showed the changes', show_tool: 'Showed', find_in_files: 'Showed a search', search_engine: 'Searched', recent_changes: 'Listed the recent changes',run: 'Ran', play: 'Played', diagnostics: 'Checked',
terminal_list: 'Listed the Terminal tabs', terminal_send: 'Typed in the Terminal', terminal_read: 'Read the Terminal',
ask_user: 'Asked you', notify: 'Told you', permission: 'Asked your permission',
profile_run: 'Profiled', profile_summary: 'Read a profile', profile_compare: 'Compared two profiles',
cryo_inspect: 'Read a Cryo file', cryo_diff: 'Compared two snapshots', cryo_sandbox: 'Ran PHP in a sandbox', cryo_live: 'Read the live memory', cryo_why: 'Looked why an object is alive', cryo_freeze: 'Froze the game',
ab_start: 'Started an A/B test', ab_changes: 'Read the A/B changes', ab_run: 'Ran the A/B test', ab_stop: 'Ended the A/B test',
composer_search: 'Searched Packagist', composer_package: 'Read a package', composer_outdated: 'Checked the outdated packages', composer_require: 'Required a package', composer_remove: 'Removed a package' }[tool] || tool };
}