Something went wrong. Try again.
A full-screen TUI CLI agent powered by local LLMs via Docker Model Runner
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470import { execSync } from "node:child_process";import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync,} from "node:fs";import { join, resolve } from "node:path";import { isRtkAvailable, rtkExec } from "../services/rtk";import { getSkillContent, loadSkills } from "../skills/registry";import type { ToolCall, ToolDefinition, ToolResult } from "../types";
const BLOCKED_COMMANDS = [ "rm -rf /", "rm -rf /*", "sudo", "mkfs", ":(){:|:&};:",];
export async function executeTool( toolCall: ToolCall, toolDef: ToolDefinition, projectDir: string, confirm: (message: string) => Promise<boolean>,): Promise<ToolResult> { const { id, name, arguments: args } = toolCall;
// Safety check for destructive tools if (toolDef.destructive) { const summary = formatToolSummary(name, args); const approved = await confirm(summary); if (!approved) { return { toolCallId: id, name, success: false, result: "Cancelled by user.", }; } }
try { switch (toolDef.handler) { case "builtin": return await executeBuiltin(name, args, projectDir); case "shell": return executeShellTool(toolDef, args, projectDir); case "http": return await executeHttpTool(toolDef, args); case "js": return executeJsTool(toolDef, args, projectDir); default: return { toolCallId: id, name, success: false, result: "Unknown handler.", }; } } catch (error) { return { toolCallId: id, name, success: false, result: `Error: ${error instanceof Error ? error.message : String(error)}`, }; }}
function formatToolSummary(name: string, args: Record<string, string>): string { switch (name) { case "write_file": return `Write file: ${args.path ?? "?"}`; case "shell_exec": return `Run command: ${args.command ?? "?"}`; case "git_propose": return "Create branch for latest proposal?"; case "git_commit": return `Commit: ${args.message ?? "?"}`; case "git_archive": return "Push branch and archive change?"; default: return `Execute ${name}?`; }}
// ─── Built-in tools ──────────────────────────────────────────────
async function executeBuiltin( name: string, args: Record<string, string>, projectDir: string,): Promise<ToolResult> { const id = `builtin_${Date.now()}`;
switch (name) { case "web_search": return { toolCallId: id, name, success: true, result: await webSearch(args.query ?? ""), }; case "get_webpage": return { toolCallId: id, name, success: true, result: await getWebpage(args.url ?? ""), }; case "read_skill": { const skills = loadSkills(projectDir); const content = getSkillContent(skills, args.name ?? ""); return { toolCallId: id, name, success: content !== null, result: content ?? `No skill named "${args.name}". Available: ${skills.map((s) => s.name).join(", ")}`, }; } case "read_file": return { toolCallId: id, name, success: true, result: readFile(args.path ?? "", projectDir), }; case "list_files": return { toolCallId: id, name, success: true, result: listFiles(args.path ?? ".", projectDir), }; case "write_file": return { toolCallId: id, name, success: true, result: writeFile(args.path ?? "", args.content ?? "", projectDir), }; case "shell_exec": return { toolCallId: id, name, success: true, result: shellExec(args.command ?? "", projectDir), }; case "git_propose": return { toolCallId: id, name, success: true, result: gitPropose(projectDir), }; case "git_commit": return { toolCallId: id, name, success: true, result: gitCommit(args.message ?? "", projectDir), }; case "git_archive": return { toolCallId: id, name, success: true, result: gitArchive(projectDir), }; default: return { toolCallId: id, name, success: false, result: `Unknown built-in tool: ${name}`, }; }}
// ─── Web search (DuckDuckGo Lite) ───────────────────────────────
async function webSearch(query: string): Promise<string> { const url = `https://lite.duckduckgo.com/lite/?q=${encodeURIComponent(query)}`; const res = await fetch(url, { headers: { "User-Agent": "Mozilla/5.0 (compatible; paikea/0.1)", }, }); const html = await res.text(); return parseDuckDuckGoLite(html);}
function parseDuckDuckGoLite(html: string): string { const results: string[] = []; const linkRegex = /<a[^>]+class="result-link"[^>]*href="([^"]*)"[^>]*>([^<]*)<\/a>/gi; const snippetRegex = /<td[^>]+class="result-snippet"[^>]*>([\s\S]*?)<\/td>/gi;
const links: { url: string; title: string }[] = []; for (const m of html.matchAll(linkRegex)) { links.push({ url: m[1] ?? "", title: (m[2] ?? "").trim(), }); }
const snippets: string[] = []; for (const m of html.matchAll(snippetRegex)) { snippets.push((m[1] ?? "").replace(/<[^>]+>/g, "").trim()); }
for (let i = 0; i < links.length && i < 10; i++) { const link = links[i]; if (!link) continue; const snippet = snippets[i] ?? ""; results.push(`${i + 1}. ${link.title}\n ${link.url}\n ${snippet}`); }
return results.length > 0 ? results.join("\n\n") : "No results found.";}
// ─── Webpage fetch ──────────────────────────────────────────────
async function getWebpage(url: string): Promise<string> { const res = await fetch(url, { headers: { "User-Agent": "Mozilla/5.0 (compatible; paikea/0.1)", }, }); const html = await res.text(); return stripHtml(html).slice(0, 8000);}
function stripHtml(html: string): string { return html .replace(/<script[\s\S]*?<\/script>/gi, "") .replace(/<style[\s\S]*?<\/style>/gi, "") .replace(/<[^>]+>/g, " ") .replace(/\s+/g, " ") .trim();}
// ─── File operations ────────────────────────────────────────────
function readFile(path: string, projectDir: string): string { const resolved = resolvePath(path, projectDir); if (!existsSync(resolved)) return `File not found: ${path}`; const content = readFileSync(resolved, "utf-8"); return content.length > 10000 ? `${content.slice(0, 10000)}\n... (truncated, ${content.length} chars total)` : content;}
function listFiles(path: string, projectDir: string): string { const resolved = resolvePath(path, projectDir); if (!existsSync(resolved)) return `Directory not found: ${path}`; if (isRtkAvailable()) { try { const out = execSync(`rtk ls "${path}"`, { cwd: projectDir, encoding: "utf-8", timeout: 10000, stdio: ["pipe", "pipe", "pipe"], }); return out.trim(); } catch { // fall through to readdirSync } } const entries = readdirSync(resolved, { withFileTypes: true }); return entries .map((e) => `${e.isDirectory() ? "d" : "f"} ${e.name}`) .join("\n");}
function writeFile(path: string, content: string, projectDir: string): string { const resolved = resolvePath(path, projectDir); mkdirSync(join(resolved, ".."), { recursive: true }); writeFileSync(resolved, content, "utf-8"); return `Written ${content.length} bytes to ${path}`;}
function shellExec(command: string, projectDir: string): string { for (const blocked of BLOCKED_COMMANDS) { if (command.includes(blocked)) { return `Blocked: command "${blocked}" is not allowed.`; } } try { const stdout = rtkExec(command, projectDir); return stdout.length > 8000 ? `${stdout.slice(0, 8000)}\n... (truncated)` : stdout; } catch (error) { const err = error as { status?: number; stderr?: string; message?: string }; return `Exit ${err.status ?? "?"}: ${err.stderr ?? err.message ?? "unknown error"}`; }}
// ─── Custom tool handlers ───────────────────────────────────────
function executeShellTool( toolDef: ToolDefinition, args: Record<string, string>, projectDir: string,): ToolResult { let command = toolDef.command ?? ""; for (const [key, value] of Object.entries(args)) { command = command.replaceAll(`{{${key}}}`, value); } const result = shellExec(command, projectDir); return { toolCallId: `shell_${Date.now()}`, name: toolDef.name, success: true, result, };}
async function executeHttpTool( toolDef: ToolDefinition, args: Record<string, string>,): Promise<ToolResult> { let url = toolDef.url ?? ""; for (const [key, value] of Object.entries(args)) { url = url.replaceAll(`{{${key}}}`, value); } const res = await fetch(url, { method: (toolDef.method ?? "GET").toUpperCase(), }); const body = await res.text(); return { toolCallId: `http_${Date.now()}`, name: toolDef.name, success: res.ok, result: body.slice(0, 8000), };}
function executeJsTool( toolDef: ToolDefinition, args: Record<string, string>, projectDir: string,): ToolResult { const scriptPath = toolDef.script ? resolve(projectDir, ".paikea/tools/handlers", toolDef.script) : undefined; if (!scriptPath || !existsSync(scriptPath)) { return { toolCallId: `js_${Date.now()}`, name: toolDef.name, success: false, result: `Script not found: ${toolDef.script ?? "none"}`, }; } const script = readFileSync(scriptPath, "utf-8"); const fn = new Function("args", "projectDir", script); const result = fn(args, projectDir) as string; return { toolCallId: `js_${Date.now()}`, name: toolDef.name, success: true, result: String(result), };}
// ─── Git tools ─────────────────────────────────────────────────
function gitPropose(projectDir: string): string { const changesDir = join(projectDir, "openspec", "changes"); if (!existsSync(changesDir)) { return "No openspec/changes/ directory found. Create a proposal first."; }
const entries = readdirSync(changesDir, { withFileTypes: true }) .filter((e) => e.isDirectory() && !e.name.startsWith(".")) .map((e) => e.name);
if (entries.length === 0) { return "No changes found in openspec/changes/. Create a proposal first."; }
const latest = entries[entries.length - 1] as string; const branchName = `feat/${latest}`;
try { rtkExec(`git checkout -b ${branchName}`, projectDir); return `Created and switched to branch: ${branchName}`; } catch (error) { const err = error as { stderr?: string; message?: string }; return `Failed to create branch: ${err.stderr ?? err.message ?? "unknown error"}`; }}
function gitCommit(message: string, projectDir: string): string { try { rtkExec("git add -A", projectDir);
const result = rtkExec(`git commit -m "${message}"`, projectDir);
return result.trim() || `Committed: ${message}`; } catch (error) { const err = error as { stderr?: string; message?: string }; return `Commit failed: ${err.stderr ?? err.message ?? "unknown error"}`; }}
const MAIN_BRANCH = "main";
function gitArchive(projectDir: string): string { const run = (cmd: string) => rtkExec(cmd, projectDir);
try { const branch = run("git branch --show-current").trim();
if (!branch) { return "Not on a branch. Cannot archive."; } if (branch === MAIN_BRANCH) { return `Already on ${MAIN_BRANCH}. Switch to the change's feat/<name> branch before archiving.`; }
// Archive the change first: this merges its spec deltas into // openspec/specs/ and moves the change under archive/. Commit the result on // the feature branch so it can be carried into main by the merge below. const archiveResult = run("openspec archive --yes"); run("git add -A"); try { run(`git commit -m ":clipboard: spec: archive ${branch}"`); } catch { // nothing to commit — archive produced no file changes }
// Merge the completed change into main. run(`git checkout ${MAIN_BRANCH}`); run(`git merge --no-ff ${branch} -m "Merge ${branch} into ${MAIN_BRANCH}"`);
// Publishing is best-effort: a locally-initialized repo has no origin, and // that must not fail the archive+merge that already succeeded. let pushed = ""; try { run(`git push origin ${branch}`); run(`git push origin ${MAIN_BRANCH}`); pushed = " Pushed branch and main to origin."; } catch { pushed = " (no origin to push to — skipped.)"; }
return `Archived ${branch} and merged it into ${MAIN_BRANCH}.${pushed}\n${archiveResult.trim()}`; } catch (error) { const err = error as { stderr?: string; message?: string }; return `Archive failed: ${err.stderr ?? err.message ?? "unknown error"}`; }}
// ─── Path safety ────────────────────────────────────────────────
function resolvePath(path: string, projectDir: string): string { const resolved = resolve(projectDir, path); const projectResolved = resolve(projectDir); if (!resolved.startsWith(projectResolved)) { return join(projectDir, path.replace(/^\.\//, "")); } return resolved;}