From e91e5e0e37df62d7ef0923cfa7453807cfb21853 Mon Sep 17 00:00:00 2001 From: mawkone Date: Sun, 1 Mar 2026 15:27:29 -0800 Subject: [PATCH] refactor: split tools.ts into registry-based domain files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces the single 800-line tools.ts and its switch dispatcher with a Theia-inspired registry pattern — each tool domain is its own file, and dispatch is a plain Map.get() call with no central routing function. New structure in src/tools/: registry.ts — ToolDefinition (with handler), registerTool(), executeTool(), ALL_TOOLS context.ts — ToolContext, MemoryUpdate interfaces security.ts — PROTECTED_* constants + assertGiteaWritable/assertCoolifyDeployable utils.ts — safeResolve(), EXCLUDED set file.ts — read_file, write_file, replace_in_file, list_directory, find_files, search_code shell.ts — execute_command git.ts — git_commit_and_push coolify.ts — coolify_*, list_all_apps, get_app_status, deploy_app gitea.ts — gitea_*, list_repos, list_all_issues, read_repo_file agent.ts — spawn_agent, get_job_status memory.ts — save_memory index.ts — barrel with side-effect imports + re-exports Adding a new tool now requires only a new file + registerTool() call. No switch statement, no shared array to edit. External API unchanged. Made-with: Cursor --- dist/orchestrator.js | 35 +- dist/tools/agent.d.ts | 1 + dist/tools/agent.js | 61 +++ dist/tools/context.d.ts | 19 + dist/tools/context.js | 2 + dist/tools/coolify.d.ts | 1 + dist/tools/coolify.js | 158 ++++++++ dist/tools/file.d.ts | 1 + dist/tools/file.js | 215 +++++++++++ dist/tools/git.d.ts | 1 + dist/tools/git.js | 94 +++++ dist/tools/gitea.d.ts | 1 + dist/tools/gitea.js | 166 ++++++++ dist/tools/index.d.ts | 10 + dist/tools/index.js | 22 ++ dist/tools/memory.d.ts | 1 + dist/tools/memory.js | 28 ++ dist/tools/registry.d.ts | 16 + dist/tools/registry.js | 23 ++ dist/tools/security.d.ts | 11 + dist/tools/security.js | 44 +++ dist/tools/shell.d.ts | 1 + dist/tools/shell.js | 76 ++++ dist/tools/utils.d.ts | 4 + dist/tools/utils.js | 48 +++ src/tools.ts | 798 --------------------------------------- src/tools/agent.ts | 59 +++ src/tools/context.ts | 20 + src/tools/coolify.ts | 161 ++++++++ src/tools/file.ts | 172 +++++++++ src/tools/git.ts | 66 ++++ src/tools/gitea.ts | 170 +++++++++ src/tools/index.ts | 14 + src/tools/memory.ts | 27 ++ src/tools/registry.ts | 34 ++ src/tools/security.ts | 48 +++ src/tools/shell.ts | 43 +++ src/tools/utils.ts | 13 + 38 files changed, 1854 insertions(+), 810 deletions(-) create mode 100644 dist/tools/agent.d.ts create mode 100644 dist/tools/agent.js create mode 100644 dist/tools/context.d.ts create mode 100644 dist/tools/context.js create mode 100644 dist/tools/coolify.d.ts create mode 100644 dist/tools/coolify.js create mode 100644 dist/tools/file.d.ts create mode 100644 dist/tools/file.js create mode 100644 dist/tools/git.d.ts create mode 100644 dist/tools/git.js create mode 100644 dist/tools/gitea.d.ts create mode 100644 dist/tools/gitea.js create mode 100644 dist/tools/index.d.ts create mode 100644 dist/tools/index.js create mode 100644 dist/tools/memory.d.ts create mode 100644 dist/tools/memory.js create mode 100644 dist/tools/registry.d.ts create mode 100644 dist/tools/registry.js create mode 100644 dist/tools/security.d.ts create mode 100644 dist/tools/security.js create mode 100644 dist/tools/shell.d.ts create mode 100644 dist/tools/shell.js create mode 100644 dist/tools/utils.d.ts create mode 100644 dist/tools/utils.js delete mode 100644 src/tools.ts create mode 100644 src/tools/agent.ts create mode 100644 src/tools/context.ts create mode 100644 src/tools/coolify.ts create mode 100644 src/tools/file.ts create mode 100644 src/tools/git.ts create mode 100644 src/tools/gitea.ts create mode 100644 src/tools/index.ts create mode 100644 src/tools/memory.ts create mode 100644 src/tools/registry.ts create mode 100644 src/tools/security.ts create mode 100644 src/tools/shell.ts create mode 100644 src/tools/utils.ts diff --git a/dist/orchestrator.js b/dist/orchestrator.js index 6b2c680..7a8866b 100644 --- a/dist/orchestrator.js +++ b/dist/orchestrator.js @@ -102,10 +102,14 @@ async function orchestratorChat(sessionId, userMessage, ctx, opts) { let finalReply = ''; let finalReasoning = null; const toolCallNames = []; - // Build messages with system prompt prepended + // Build system prompt — inject project knowledge if provided + const systemContent = opts?.knowledgeContext + ? `${SYSTEM_PROMPT}\n\n## Project Memory (known facts)\n${opts.knowledgeContext}` + : SYSTEM_PROMPT; + // Build messages with system prompt prepended; keep last 40 for cost control const buildMessages = () => [ - { role: 'system', content: SYSTEM_PROMPT }, - ...session.history + { role: 'system', content: systemContent }, + ...session.history.slice(-40) ]; while (turn < MAX_TURNS) { turn++; @@ -119,15 +123,20 @@ async function orchestratorChat(sessionId, userMessage, ctx, opts) { // Record reasoning for the final turn (informational, not stored in history) if (response.reasoning) finalReasoning = response.reasoning; - // Build assistant message to add to history - const assistantMsg = { - role: 'assistant', - content: response.content, - tool_calls: response.tool_calls.length > 0 ? response.tool_calls : undefined - }; - session.history.push(assistantMsg); + // Only push assistant message if it has actual content or tool calls; + // skip empty turns that result from mid-reasoning token exhaustion. + const hasContent = response.content !== null && response.content !== ''; + const hasToolCalls = response.tool_calls.length > 0; + if (hasContent || hasToolCalls) { + const assistantMsg = { + role: 'assistant', + content: response.content, + tool_calls: hasToolCalls ? response.tool_calls : undefined + }; + session.history.push(assistantMsg); + } // No tool calls — we have the final answer - if (response.tool_calls.length === 0) { + if (!hasToolCalls) { finalReply = response.content ?? ''; break; } @@ -166,7 +175,9 @@ async function orchestratorChat(sessionId, userMessage, ctx, opts) { turns: turn, toolCalls: toolCallNames, model: llm.modelId, - history: session.history.slice(-40), + history: session.history + .filter(m => m.role !== 'assistant' || m.content || m.tool_calls?.length) + .slice(-40), memoryUpdates: ctx.memoryUpdates }; } diff --git a/dist/tools/agent.d.ts b/dist/tools/agent.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/tools/agent.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/tools/agent.js b/dist/tools/agent.js new file mode 100644 index 0000000..0b2fe74 --- /dev/null +++ b/dist/tools/agent.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const registry_1 = require("./registry"); +(0, registry_1.registerTool)({ + name: 'spawn_agent', + description: 'Dispatch a sub-agent job to run in the background. Returns a job ID. Use this to delegate specialized work to Coder, PM, or Marketing agents.', + parameters: { + type: 'object', + properties: { + agent: { type: 'string', description: '"Coder", "PM", or "Marketing"' }, + task: { type: 'string', description: 'Detailed task description for the agent' }, + repo: { type: 'string', description: 'Gitea repo in "owner/name" format the agent should work on' } + }, + required: ['agent', 'task', 'repo'] + }, + async handler(args, _ctx) { + const runnerUrl = process.env.AGENT_RUNNER_URL || 'http://localhost:3333'; + try { + const res = await fetch(`${runnerUrl}/api/agent/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Internal': 'true' }, + body: JSON.stringify({ agent: args.agent, task: args.task, repo: args.repo }) + }); + const data = await res.json(); + return { jobId: data.jobId, agent: args.agent, status: 'dispatched' }; + } + catch (err) { + return { error: `Failed to spawn agent: ${err instanceof Error ? err.message : String(err)}` }; + } + } +}); +(0, registry_1.registerTool)({ + name: 'get_job_status', + description: 'Check the status of a previously spawned agent job by job ID.', + parameters: { + type: 'object', + properties: { + job_id: { type: 'string', description: 'Job ID returned by spawn_agent' } + }, + required: ['job_id'] + }, + async handler(args, _ctx) { + const runnerUrl = process.env.AGENT_RUNNER_URL || 'http://localhost:3333'; + try { + const res = await fetch(`${runnerUrl}/api/jobs/${String(args.job_id)}`); + const job = await res.json(); + return { + id: job.id, + agent: job.agent, + status: job.status, + progress: job.progress, + toolCalls: job.toolCalls?.length, + result: job.result, + error: job.error + }; + } + catch (err) { + return { error: `Failed to get job: ${err instanceof Error ? err.message : String(err)}` }; + } + } +}); diff --git a/dist/tools/context.d.ts b/dist/tools/context.d.ts new file mode 100644 index 0000000..b383000 --- /dev/null +++ b/dist/tools/context.d.ts @@ -0,0 +1,19 @@ +export interface MemoryUpdate { + key: string; + type: string; + value: string; +} +export interface ToolContext { + workspaceRoot: string; + gitea: { + apiUrl: string; + apiToken: string; + username: string; + }; + coolify: { + apiUrl: string; + apiToken: string; + }; + /** Accumulated memory updates from save_memory tool calls in this turn */ + memoryUpdates: MemoryUpdate[]; +} diff --git a/dist/tools/context.js b/dist/tools/context.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/dist/tools/context.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/tools/coolify.d.ts b/dist/tools/coolify.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/tools/coolify.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/tools/coolify.js b/dist/tools/coolify.js new file mode 100644 index 0000000..dd2ddae --- /dev/null +++ b/dist/tools/coolify.js @@ -0,0 +1,158 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const registry_1 = require("./registry"); +const security_1 = require("./security"); +async function coolifyFetch(path, ctx, method = 'GET', body) { + const res = await fetch(`${ctx.coolify.apiUrl}/api/v1${path}`, { + method, + headers: { + 'Authorization': `Bearer ${ctx.coolify.apiToken}`, + 'Content-Type': 'application/json', + 'Accept': 'application/json' + }, + body: body ? JSON.stringify(body) : undefined + }); + if (!res.ok) + return { error: `Coolify API error: ${res.status} ${res.statusText}` }; + return res.json(); +} +(0, registry_1.registerTool)({ + name: 'coolify_list_projects', + description: 'List all projects in the Coolify instance. Returns project names and UUIDs.', + parameters: { type: 'object', properties: {} }, + async handler(_args, ctx) { + const projects = await coolifyFetch('/projects', ctx); + if (!Array.isArray(projects)) + return projects; + return projects.filter((p) => p.uuid !== security_1.PROTECTED_COOLIFY_PROJECT); + } +}); +(0, registry_1.registerTool)({ + name: 'coolify_list_applications', + description: 'List applications in a Coolify project.', + parameters: { + type: 'object', + properties: { + project_uuid: { type: 'string', description: 'Project UUID from coolify_list_projects' } + }, + required: ['project_uuid'] + }, + async handler(args, ctx) { + const all = await coolifyFetch('/applications', ctx); + if (!Array.isArray(all)) + return all; + return all.filter((a) => a.project_uuid === String(args.project_uuid)); + } +}); +(0, registry_1.registerTool)({ + name: 'coolify_deploy', + description: 'Trigger a deployment for a Coolify application.', + parameters: { + type: 'object', + properties: { + application_uuid: { type: 'string', description: 'Application UUID to deploy' } + }, + required: ['application_uuid'] + }, + async handler(args, ctx) { + const appUuid = String(args.application_uuid); + (0, security_1.assertCoolifyDeployable)(appUuid); + const apps = await coolifyFetch('/applications', ctx); + if (Array.isArray(apps)) { + const app = apps.find((a) => a.uuid === appUuid); + if (app?.project_uuid === security_1.PROTECTED_COOLIFY_PROJECT) { + return { error: `SECURITY: App "${appUuid}" belongs to the protected Vibn project. Agents cannot deploy platform apps.` }; + } + } + return coolifyFetch(`/applications/${appUuid}/deploy`, ctx, 'POST'); + } +}); +(0, registry_1.registerTool)({ + name: 'coolify_get_logs', + description: 'Get recent deployment logs for a Coolify application.', + parameters: { + type: 'object', + properties: { + application_uuid: { type: 'string', description: 'Application UUID' } + }, + required: ['application_uuid'] + }, + async handler(args, ctx) { + return coolifyFetch(`/applications/${String(args.application_uuid)}/logs?limit=50`, ctx); + } +}); +(0, registry_1.registerTool)({ + name: 'list_all_apps', + description: 'List all Coolify applications across all projects with their status (running/stopped/error) and domain.', + parameters: { type: 'object', properties: {} }, + async handler(_args, ctx) { + const apps = await coolifyFetch('/applications', ctx); + if (!Array.isArray(apps)) + return apps; + return apps + .filter((a) => a.project_uuid !== security_1.PROTECTED_COOLIFY_PROJECT && !security_1.PROTECTED_COOLIFY_APPS.has(a.uuid)) + .map((a) => ({ + uuid: a.uuid, + name: a.name, + fqdn: a.fqdn, + status: a.status, + repo: a.git_repository, + branch: a.git_branch + })); + } +}); +(0, registry_1.registerTool)({ + name: 'get_app_status', + description: 'Get the current deployment status and recent logs for a specific Coolify application by name or UUID.', + parameters: { + type: 'object', + properties: { + app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend") or UUID' } + }, + required: ['app_name'] + }, + async handler(args, ctx) { + const apps = await coolifyFetch('/applications', ctx); + if (!Array.isArray(apps)) + return apps; + const appName = String(args.app_name); + const app = apps.find((a) => a.name?.toLowerCase() === appName.toLowerCase() || a.uuid === appName); + if (!app) + return { error: `App "${appName}" not found` }; + if (security_1.PROTECTED_COOLIFY_APPS.has(app.uuid) || app.project_uuid === security_1.PROTECTED_COOLIFY_PROJECT) { + return { error: `SECURITY: "${appName}" is a protected Vibn platform app. Status is not exposed to agents.` }; + } + const logs = await coolifyFetch(`/applications/${app.uuid}/logs?limit=20`, ctx); + return { name: app.name, uuid: app.uuid, status: app.status, fqdn: app.fqdn, logs }; + } +}); +(0, registry_1.registerTool)({ + name: 'deploy_app', + description: 'Trigger a Coolify deployment for an app by name. Use after an agent commits code.', + parameters: { + type: 'object', + properties: { + app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend")' } + }, + required: ['app_name'] + }, + async handler(args, ctx) { + const apps = await coolifyFetch('/applications', ctx); + if (!Array.isArray(apps)) + return apps; + const appName = String(args.app_name); + const app = apps.find((a) => a.name?.toLowerCase() === appName.toLowerCase() || a.uuid === appName); + if (!app) + return { error: `App "${appName}" not found` }; + if (security_1.PROTECTED_COOLIFY_APPS.has(app.uuid) || app.project_uuid === security_1.PROTECTED_COOLIFY_PROJECT) { + return { + error: `SECURITY: "${appName}" is a protected Vibn platform application. ` + + `Agents can only deploy user project apps, not platform infrastructure.` + }; + } + const result = await fetch(`${ctx.coolify.apiUrl}/api/v1/deploy?uuid=${app.uuid}&force=false`, { + headers: { 'Authorization': `Bearer ${ctx.coolify.apiToken}` } + }); + return result.json(); + } +}); diff --git a/dist/tools/file.d.ts b/dist/tools/file.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/tools/file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/tools/file.js b/dist/tools/file.js new file mode 100644 index 0000000..05b7e70 --- /dev/null +++ b/dist/tools/file.js @@ -0,0 +1,215 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __importStar(require("fs")); +const path = __importStar(require("path")); +const cp = __importStar(require("child_process")); +const util = __importStar(require("util")); +const minimatch_1 = require("minimatch"); +const registry_1 = require("./registry"); +const utils_1 = require("./utils"); +const execAsync = util.promisify(cp.exec); +(0, registry_1.registerTool)({ + name: 'read_file', + description: 'Read the complete content of a file in the workspace. Always read before editing.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root (e.g. "src/index.ts")' } + }, + required: ['path'] + }, + async handler(args, ctx) { + const abs = (0, utils_1.safeResolve)(ctx.workspaceRoot, String(args.path)); + try { + return fs.readFileSync(abs, 'utf8'); + } + catch { + return { error: `File not found: ${args.path}` }; + } + } +}); +(0, registry_1.registerTool)({ + name: 'write_file', + description: 'Write complete content to a file. Creates parent directories if needed. Overwrites existing files.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root' }, + content: { type: 'string', description: 'Complete new file content' } + }, + required: ['path', 'content'] + }, + async handler(args, ctx) { + const abs = (0, utils_1.safeResolve)(ctx.workspaceRoot, String(args.path)); + fs.mkdirSync(path.dirname(abs), { recursive: true }); + fs.writeFileSync(abs, String(args.content), 'utf8'); + return { success: true, path: args.path, bytes: Buffer.byteLength(String(args.content)) }; + } +}); +(0, registry_1.registerTool)({ + name: 'replace_in_file', + description: 'Replace an exact string in a file. The old_content must match character-for-character. Read the file first.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root' }, + old_content: { type: 'string', description: 'Exact text to replace' }, + new_content: { type: 'string', description: 'Replacement text' } + }, + required: ['path', 'old_content', 'new_content'] + }, + async handler(args, ctx) { + const abs = (0, utils_1.safeResolve)(ctx.workspaceRoot, String(args.path)); + const current = fs.readFileSync(abs, 'utf8'); + if (!current.includes(String(args.old_content))) { + return { error: 'old_content not found in file. Read the file again to get the current content.' }; + } + fs.writeFileSync(abs, current.replace(String(args.old_content), String(args.new_content)), 'utf8'); + return { success: true, path: args.path }; + } +}); +(0, registry_1.registerTool)({ + name: 'list_directory', + description: 'List files and subdirectories in a directory. Directories have trailing "/".', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root. Use "." for root.' } + }, + required: ['path'] + }, + async handler(args, ctx) { + const abs = (0, utils_1.safeResolve)(ctx.workspaceRoot, String(args.path)); + try { + const entries = fs.readdirSync(abs, { withFileTypes: true }); + return entries + .filter(e => !utils_1.EXCLUDED.has(e.name)) + .map(e => e.isDirectory() ? `${e.name}/` : e.name); + } + catch { + return { error: `Directory not found: ${args.path}` }; + } + } +}); +(0, registry_1.registerTool)({ + name: 'find_files', + description: 'Find files matching a glob pattern in the workspace. Returns up to 200 relative paths.', + parameters: { + type: 'object', + properties: { + pattern: { type: 'string', description: 'Glob pattern e.g. "**/*.ts", "src/**/*.test.js"' } + }, + required: ['pattern'] + }, + async handler(args, ctx) { + const matcher = new minimatch_1.Minimatch(String(args.pattern), { dot: false }); + const results = []; + function walk(dir) { + if (results.length >= 200) + return; + let entries; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } + catch { + return; + } + for (const e of entries) { + if (utils_1.EXCLUDED.has(e.name)) + continue; + const abs = path.join(dir, e.name); + const rel = path.relative(ctx.workspaceRoot, abs).split(path.sep).join('/'); + if (e.isDirectory()) { + walk(abs); + } + else if (matcher.match(rel)) { + results.push(rel); + } + } + } + walk(ctx.workspaceRoot); + return { files: results, truncated: results.length >= 200 }; + } +}); +(0, registry_1.registerTool)({ + name: 'search_code', + description: 'Search file contents for a string or regex pattern. Returns file path, line number, and matching line.', + parameters: { + type: 'object', + properties: { + query: { type: 'string', description: 'Search term or regex' }, + file_extensions: { + type: 'array', + items: { type: 'string' }, + description: 'Optional: limit to these extensions e.g. ["ts","js"]' + } + }, + required: ['query'] + }, + async handler(args, ctx) { + const extensions = args.file_extensions; + const globPatterns = extensions?.map(e => `*.${e}`) || []; + const rgArgs = ['--line-number', '--no-heading', '--color=never', '--max-count=30']; + for (const ex of utils_1.EXCLUDED) { + rgArgs.push('--glob', `!${ex}`); + } + if (globPatterns.length > 0) { + for (const g of globPatterns) + rgArgs.push('--glob', g); + } + rgArgs.push('--fixed-strings', String(args.query), ctx.workspaceRoot); + try { + const { stdout } = await execAsync(`rg ${rgArgs.map(a => `'${a}'`).join(' ')}`, { + cwd: ctx.workspaceRoot, timeout: 15000 + }); + return stdout.trim().split('\n').filter(Boolean).map(line => { + const m = line.match(/^(.+?):(\d+):(.*)$/); + if (!m) + return null; + return { + file: path.relative(ctx.workspaceRoot, m[1]).split(path.sep).join('/'), + line: parseInt(m[2]), + content: m[3].trim() + }; + }).filter(Boolean); + } + catch (err) { + if (err.code === 1) + return []; // ripgrep exit 1 = no matches + return { error: `Search failed: ${err.message}` }; + } + } +}); diff --git a/dist/tools/git.d.ts b/dist/tools/git.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/tools/git.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/tools/git.js b/dist/tools/git.js new file mode 100644 index 0000000..649b983 --- /dev/null +++ b/dist/tools/git.js @@ -0,0 +1,94 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const cp = __importStar(require("child_process")); +const util = __importStar(require("util")); +const registry_1 = require("./registry"); +const security_1 = require("./security"); +const execAsync = util.promisify(cp.exec); +(0, registry_1.registerTool)({ + name: 'git_commit_and_push', + description: 'Stage all changes, commit with a message, and push to the remote. Call this when work is complete.', + parameters: { + type: 'object', + properties: { + message: { type: 'string', description: 'Commit message describing the changes made' } + }, + required: ['message'] + }, + async handler(args, ctx) { + const cwd = ctx.workspaceRoot; + const { apiUrl, apiToken, username } = ctx.gitea; + const message = String(args.message); + try { + // Check remote URL before committing — block pushes to protected repos + let remoteCheck = ''; + try { + remoteCheck = (await execAsync('git remote get-url origin', { cwd })).stdout.trim(); + } + catch { /* no remote yet */ } + for (const protectedRepo of security_1.PROTECTED_GITEA_REPOS) { + const repoPath = protectedRepo.replace('mark/', ''); + if (remoteCheck.includes(`/${repoPath}`) || remoteCheck.includes(`/${repoPath}.git`)) { + return { + error: `SECURITY: This workspace is linked to a protected Vibn platform repo (${protectedRepo}). ` + + `Agents cannot push to platform repos. Only user project repos are writable.` + }; + } + } + await execAsync('git add -A', { cwd }); + await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd }); + // Strip any existing credentials from remote URL and re-inject cleanly + let remoteUrl = ''; + try { + remoteUrl = (await execAsync('git remote get-url origin', { cwd })).stdout.trim(); + } + catch { /* no remote */ } + const cleanUrl = remoteUrl.replace(/https:\/\/[^@]+@/, 'https://'); + const baseUrl = cleanUrl || apiUrl; + const authedUrl = baseUrl.replace('https://', `https://${username}:${apiToken}@`); + await execAsync(`git remote set-url origin "${authedUrl}"`, { cwd }).catch(async () => { + await execAsync(`git remote add origin "${authedUrl}"`, { cwd }); + }); + const branch = (await execAsync('git rev-parse --abbrev-ref HEAD', { cwd })).stdout.trim(); + await execAsync(`git push -u origin "${branch}"`, { cwd, timeout: 60000 }); + return { success: true, message, branch }; + } + catch (err) { + const cleaned = (err.message || '').replace(new RegExp(apiToken, 'g'), '***'); + return { error: `Git operation failed: ${cleaned}` }; + } + } +}); diff --git a/dist/tools/gitea.d.ts b/dist/tools/gitea.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/tools/gitea.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/tools/gitea.js b/dist/tools/gitea.js new file mode 100644 index 0000000..755f7cd --- /dev/null +++ b/dist/tools/gitea.js @@ -0,0 +1,166 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const registry_1 = require("./registry"); +const security_1 = require("./security"); +async function giteaFetch(path, ctx, method = 'GET', body) { + const res = await fetch(`${ctx.gitea.apiUrl}/api/v1${path}`, { + method, + headers: { + 'Authorization': `token ${ctx.gitea.apiToken}`, + 'Content-Type': 'application/json', + 'Accept': 'application/json' + }, + body: body ? JSON.stringify(body) : undefined + }); + if (!res.ok) + return { error: `Gitea API error: ${res.status} ${res.statusText}` }; + return res.json(); +} +(0, registry_1.registerTool)({ + name: 'gitea_create_issue', + description: 'Create a new issue in a Gitea repository.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repository in "owner/name" format' }, + title: { type: 'string', description: 'Issue title' }, + body: { type: 'string', description: 'Issue body (markdown)' }, + labels: { type: 'array', items: { type: 'string' }, description: 'Optional label names' } + }, + required: ['repo', 'title', 'body'] + }, + async handler(args, ctx) { + const repo = String(args.repo); + (0, security_1.assertGiteaWritable)(repo); + return giteaFetch(`/repos/${repo}/issues`, ctx, 'POST', { + title: args.title, + body: args.body, + labels: args.labels + }); + } +}); +(0, registry_1.registerTool)({ + name: 'gitea_list_issues', + description: 'List open issues in a Gitea repository.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repository in "owner/name" format' }, + state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' } + }, + required: ['repo'] + }, + async handler(args, ctx) { + const state = String(args.state || 'open'); + return giteaFetch(`/repos/${String(args.repo)}/issues?state=${state}&limit=20`, ctx); + } +}); +(0, registry_1.registerTool)({ + name: 'gitea_close_issue', + description: 'Close an issue in a Gitea repository.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repository in "owner/name" format' }, + issue_number: { type: 'number', description: 'Issue number to close' } + }, + required: ['repo', 'issue_number'] + }, + async handler(args, ctx) { + const repo = String(args.repo); + (0, security_1.assertGiteaWritable)(repo); + return giteaFetch(`/repos/${repo}/issues/${Number(args.issue_number)}`, ctx, 'PATCH', { state: 'closed' }); + } +}); +(0, registry_1.registerTool)({ + name: 'list_repos', + description: 'List all Git repositories in the Gitea organization. Returns repo names, descriptions, and last update time.', + parameters: { type: 'object', properties: {} }, + async handler(_args, ctx) { + const res = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/search?limit=50`, { + headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } + }); + const data = await res.json(); + return (data.data || []) + .filter((r) => !security_1.PROTECTED_GITEA_REPOS.has(r.full_name)) + .map((r) => ({ + name: r.full_name, + description: r.description, + default_branch: r.default_branch, + updated: r.updated, + stars: r.stars_count, + open_issues: r.open_issues_count + })); + } +}); +(0, registry_1.registerTool)({ + name: 'list_all_issues', + description: 'List open issues across all repos or a specific repo. Use this to understand what work is queued or in progress.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Optional: "owner/name" to scope to one repo. Omit for all repos.' }, + state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' } + } + }, + async handler(args, ctx) { + const state = String(args.state || 'open'); + if (args.repo) { + const repo = String(args.repo); + if (security_1.PROTECTED_GITEA_REPOS.has(repo)) { + return { error: `SECURITY: "${repo}" is a protected Vibn platform repo. Agents cannot access its issues.` }; + } + return giteaFetch(`/repos/${repo}/issues?state=${state}&limit=20`, ctx); + } + // Fetch across all non-protected repos + const reposRes = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/search?limit=50`, { + headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } + }); + const reposData = await reposRes.json(); + const repos = (reposData.data || []).filter((r) => !security_1.PROTECTED_GITEA_REPOS.has(r.full_name)); + const allIssues = []; + for (const r of repos.slice(0, 10)) { + const issues = await giteaFetch(`/repos/${r.full_name}/issues?state=${state}&limit=10`, ctx); + if (Array.isArray(issues)) { + allIssues.push(...issues.map((i) => ({ + repo: r.full_name, + number: i.number, + title: i.title, + state: i.state, + labels: i.labels?.map((l) => l.name), + created: i.created_at + }))); + } + } + return allIssues; + } +}); +(0, registry_1.registerTool)({ + name: 'read_repo_file', + description: 'Read a file from any Gitea repository without cloning it. Useful for understanding project structure.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repo in "owner/name" format' }, + path: { type: 'string', description: 'File path within the repo (e.g. "src/app/page.tsx")' } + }, + required: ['repo', 'path'] + }, + async handler(args, ctx) { + const repo = String(args.repo); + const filePath = String(args.path); + try { + const res = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/${repo}/contents/${filePath}`, { + headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } + }); + if (!res.ok) + return { error: `File not found: ${filePath} in ${repo}` }; + const data = await res.json(); + const content = Buffer.from(data.content, 'base64').toString('utf8'); + return { repo, path: filePath, content }; + } + catch (err) { + return { error: `Failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}` }; + } + } +}); diff --git a/dist/tools/index.d.ts b/dist/tools/index.d.ts new file mode 100644 index 0000000..2d23dcd --- /dev/null +++ b/dist/tools/index.d.ts @@ -0,0 +1,10 @@ +import './file'; +import './shell'; +import './git'; +import './gitea'; +import './coolify'; +import './agent'; +import './memory'; +export { ALL_TOOLS, executeTool, ToolDefinition } from './registry'; +export { ToolContext, MemoryUpdate } from './context'; +export { PROTECTED_GITEA_REPOS, PROTECTED_COOLIFY_PROJECT, PROTECTED_COOLIFY_APPS, assertGiteaWritable, assertCoolifyDeployable } from './security'; diff --git a/dist/tools/index.js b/dist/tools/index.js new file mode 100644 index 0000000..aa672ca --- /dev/null +++ b/dist/tools/index.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertCoolifyDeployable = exports.assertGiteaWritable = exports.PROTECTED_COOLIFY_APPS = exports.PROTECTED_COOLIFY_PROJECT = exports.PROTECTED_GITEA_REPOS = exports.executeTool = exports.ALL_TOOLS = void 0; +// Import domain files first — side effects register each tool into the registry. +// Order determines ALL_TOOLS array order (informational only). +require("./file"); +require("./shell"); +require("./git"); +require("./gitea"); +require("./coolify"); +require("./agent"); +require("./memory"); +// Re-export the public API — identical surface to the old tools.ts +var registry_1 = require("./registry"); +Object.defineProperty(exports, "ALL_TOOLS", { enumerable: true, get: function () { return registry_1.ALL_TOOLS; } }); +Object.defineProperty(exports, "executeTool", { enumerable: true, get: function () { return registry_1.executeTool; } }); +var security_1 = require("./security"); +Object.defineProperty(exports, "PROTECTED_GITEA_REPOS", { enumerable: true, get: function () { return security_1.PROTECTED_GITEA_REPOS; } }); +Object.defineProperty(exports, "PROTECTED_COOLIFY_PROJECT", { enumerable: true, get: function () { return security_1.PROTECTED_COOLIFY_PROJECT; } }); +Object.defineProperty(exports, "PROTECTED_COOLIFY_APPS", { enumerable: true, get: function () { return security_1.PROTECTED_COOLIFY_APPS; } }); +Object.defineProperty(exports, "assertGiteaWritable", { enumerable: true, get: function () { return security_1.assertGiteaWritable; } }); +Object.defineProperty(exports, "assertCoolifyDeployable", { enumerable: true, get: function () { return security_1.assertCoolifyDeployable; } }); diff --git a/dist/tools/memory.d.ts b/dist/tools/memory.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/tools/memory.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/tools/memory.js b/dist/tools/memory.js new file mode 100644 index 0000000..5c1fca3 --- /dev/null +++ b/dist/tools/memory.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const registry_1 = require("./registry"); +(0, registry_1.registerTool)({ + name: 'save_memory', + description: 'Persist an important fact about this project to long-term memory. Use this to save decisions, tech stack choices, feature descriptions, constraints, or goals so they are remembered across conversations.', + parameters: { + type: 'object', + properties: { + key: { type: 'string', description: 'Short unique label (e.g. "primary_language", "auth_strategy", "deploy_target")' }, + type: { + type: 'string', + enum: ['tech_stack', 'decision', 'feature', 'goal', 'constraint', 'note'], + description: 'Category of the memory item' + }, + value: { type: 'string', description: 'The fact to remember (1-3 sentences)' } + }, + required: ['key', 'type', 'value'] + }, + async handler(args, ctx) { + ctx.memoryUpdates.push({ + key: String(args.key), + type: String(args.type), + value: String(args.value) + }); + return { saved: true, key: args.key, type: args.type }; + } +}); diff --git a/dist/tools/registry.d.ts b/dist/tools/registry.d.ts new file mode 100644 index 0000000..30b9206 --- /dev/null +++ b/dist/tools/registry.d.ts @@ -0,0 +1,16 @@ +import { ToolContext } from './context'; +export interface ToolDefinition { + name: string; + description: string; + parameters: Record; + /** Implementation — called by executeTool(). Not sent to the LLM. */ + handler: (args: Record, ctx: ToolContext) => Promise; +} +/** + * Mutable array kept in sync with the registry. + * Used by agents.ts to pick tool subsets by name (backwards-compatible with ALL_TOOLS). + */ +export declare const ALL_TOOLS: ToolDefinition[]; +export declare function registerTool(tool: ToolDefinition): void; +/** Dispatch a tool call by name — O(1) map lookup, no switch needed. */ +export declare function executeTool(name: string, args: Record, ctx: ToolContext): Promise; diff --git a/dist/tools/registry.js b/dist/tools/registry.js new file mode 100644 index 0000000..225c12d --- /dev/null +++ b/dist/tools/registry.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ALL_TOOLS = void 0; +exports.registerTool = registerTool; +exports.executeTool = executeTool; +/** Live registry — grows as domain files are imported. */ +const _registry = new Map(); +/** + * Mutable array kept in sync with the registry. + * Used by agents.ts to pick tool subsets by name (backwards-compatible with ALL_TOOLS). + */ +exports.ALL_TOOLS = []; +function registerTool(tool) { + _registry.set(tool.name, tool); + exports.ALL_TOOLS.push(tool); +} +/** Dispatch a tool call by name — O(1) map lookup, no switch needed. */ +async function executeTool(name, args, ctx) { + const tool = _registry.get(name); + if (!tool) + return { error: `Unknown tool: ${name}` }; + return tool.handler(args, ctx); +} diff --git a/dist/tools/security.d.ts b/dist/tools/security.d.ts new file mode 100644 index 0000000..1662406 --- /dev/null +++ b/dist/tools/security.d.ts @@ -0,0 +1,11 @@ +/** Gitea repos agents can NEVER push to, commit to, or write issues on. */ +export declare const PROTECTED_GITEA_REPOS: Set; +/** Coolify project UUID for the VIBN platform — agents cannot deploy here. */ +export declare const PROTECTED_COOLIFY_PROJECT = "f4owwggokksgw0ogo0844os0"; +/** + * Specific Coolify app UUIDs that must never be deployed by an agent. + * Belt-and-suspenders check in case the project UUID filter is bypassed. + */ +export declare const PROTECTED_COOLIFY_APPS: Set; +export declare function assertGiteaWritable(repo: string): void; +export declare function assertCoolifyDeployable(appUuid: string): void; diff --git a/dist/tools/security.js b/dist/tools/security.js new file mode 100644 index 0000000..673c3b9 --- /dev/null +++ b/dist/tools/security.js @@ -0,0 +1,44 @@ +"use strict"; +// ============================================================================= +// SECURITY GUARDRAILS — Protected VIBN Platform Resources +// +// These repos and Coolify resources belong to the Vibn platform itself. +// Agents must never be allowed to push code or trigger deployments here. +// Read-only operations (list, read file, get status) are still permitted +// so agents can observe platform state, but all mutations are blocked. +// ============================================================================= +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PROTECTED_COOLIFY_APPS = exports.PROTECTED_COOLIFY_PROJECT = exports.PROTECTED_GITEA_REPOS = void 0; +exports.assertGiteaWritable = assertGiteaWritable; +exports.assertCoolifyDeployable = assertCoolifyDeployable; +/** Gitea repos agents can NEVER push to, commit to, or write issues on. */ +exports.PROTECTED_GITEA_REPOS = new Set([ + 'mark/vibn-frontend', + 'mark/theia-code-os', + 'mark/vibn-agent-runner', + 'mark/vibn-api', + 'mark/master-ai', +]); +/** Coolify project UUID for the VIBN platform — agents cannot deploy here. */ +exports.PROTECTED_COOLIFY_PROJECT = 'f4owwggokksgw0ogo0844os0'; +/** + * Specific Coolify app UUIDs that must never be deployed by an agent. + * Belt-and-suspenders check in case the project UUID filter is bypassed. + */ +exports.PROTECTED_COOLIFY_APPS = new Set([ + 'y4cscsc8s08c8808go0448s0', // vibn-frontend + 'kggs4ogckc0w8ggwkkk88kck', // vibn-postgres + 'o4wwck0g0c04wgoo4g4s0004', // gitea +]); +function assertGiteaWritable(repo) { + if (exports.PROTECTED_GITEA_REPOS.has(repo)) { + throw new Error(`SECURITY: Repo "${repo}" is a protected Vibn platform repo. ` + + `Agents cannot push code or modify issues in this repository.`); + } +} +function assertCoolifyDeployable(appUuid) { + if (exports.PROTECTED_COOLIFY_APPS.has(appUuid)) { + throw new Error(`SECURITY: App "${appUuid}" is a protected Vibn platform application. ` + + `Agents cannot trigger deployments for this application.`); + } +} diff --git a/dist/tools/shell.d.ts b/dist/tools/shell.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dist/tools/shell.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/tools/shell.js b/dist/tools/shell.js new file mode 100644 index 0000000..fd884c5 --- /dev/null +++ b/dist/tools/shell.js @@ -0,0 +1,76 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +const cp = __importStar(require("child_process")); +const util = __importStar(require("util")); +const registry_1 = require("./registry"); +const utils_1 = require("./utils"); +const execAsync = util.promisify(cp.exec); +const BLOCKED_COMMANDS = ['rm -rf /', 'mkfs', ':(){:|:&};:']; +(0, registry_1.registerTool)({ + name: 'execute_command', + description: 'Run a shell command in the workspace and return stdout + stderr. 120s timeout. Use for: npm install, npm test, git status, building, etc.', + parameters: { + type: 'object', + properties: { + command: { type: 'string', description: 'Shell command to run' }, + working_directory: { type: 'string', description: 'Optional: relative subdirectory to run in' } + }, + required: ['command'] + }, + async handler(args, ctx) { + const command = String(args.command); + if (BLOCKED_COMMANDS.some(b => command.includes(b))) { + return { error: 'Command blocked for safety.' }; + } + const cwd = args.working_directory + ? (0, utils_1.safeResolve)(ctx.workspaceRoot, String(args.working_directory)) + : ctx.workspaceRoot; + try { + const { stdout, stderr } = await execAsync(command, { + cwd, timeout: 120000, maxBuffer: 1024 * 1024 + }); + return { exitCode: 0, stdout: stdout.trim(), stderr: stderr.trim() }; + } + catch (err) { + return { + exitCode: err.code, + stdout: (err.stdout || '').trim(), + stderr: (err.stderr || '').trim(), + error: err.message + }; + } + } +}); diff --git a/dist/tools/utils.d.ts b/dist/tools/utils.d.ts new file mode 100644 index 0000000..a78f2a2 --- /dev/null +++ b/dist/tools/utils.d.ts @@ -0,0 +1,4 @@ +/** Directory names to skip when walking or listing workspaces. */ +export declare const EXCLUDED: Set; +/** Resolve a relative path safely within a workspace root — throws if it tries to escape. */ +export declare function safeResolve(root: string, rel: string): string; diff --git a/dist/tools/utils.js b/dist/tools/utils.js new file mode 100644 index 0000000..1fe64f0 --- /dev/null +++ b/dist/tools/utils.js @@ -0,0 +1,48 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EXCLUDED = void 0; +exports.safeResolve = safeResolve; +const path = __importStar(require("path")); +/** Directory names to skip when walking or listing workspaces. */ +exports.EXCLUDED = new Set(['node_modules', '.git', 'dist', 'build', 'lib', '.cache', 'coverage']); +/** Resolve a relative path safely within a workspace root — throws if it tries to escape. */ +function safeResolve(root, rel) { + const resolved = path.resolve(root, rel); + if (!resolved.startsWith(path.resolve(root))) { + throw new Error(`Path escapes workspace: ${rel}`); + } + return resolved; +} diff --git a/src/tools.ts b/src/tools.ts deleted file mode 100644 index 97524b2..0000000 --- a/src/tools.ts +++ /dev/null @@ -1,798 +0,0 @@ -import * as fs from 'fs'; -import * as path from 'path'; -import * as cp from 'child_process'; -import * as util from 'util'; -import { Minimatch } from 'minimatch'; - -const execAsync = util.promisify(cp.exec); - -// ============================================================================= -// SECURITY GUARDRAILS — Protected VIBN Platform Resources -// -// These repos and Coolify resources belong to the Vibn platform itself. -// Agents must never be allowed to push code or trigger deployments here. -// Read-only operations (list, read file, get status) are still permitted -// so agents can observe the platform state, but all mutations are blocked. -// ============================================================================= - -/** Gitea repos that agents can NEVER push to, commit to, or write issues on. */ -const PROTECTED_GITEA_REPOS = new Set([ - 'mark/vibn-frontend', - 'mark/theia-code-os', - 'mark/vibn-agent-runner', - 'mark/vibn-api', - 'mark/master-ai', -]); - -/** Coolify project UUID for the VIBN platform — agents cannot deploy here. */ -const PROTECTED_COOLIFY_PROJECT = 'f4owwggokksgw0ogo0844os0'; - -/** - * Specific Coolify app UUIDs that must never be deployed by an agent. - * This is a belt-and-suspenders check in case the project UUID filter is bypassed. - */ -const PROTECTED_COOLIFY_APPS = new Set([ - 'y4cscsc8s08c8808go0448s0', // vibn-frontend - 'kggs4ogckc0w8ggwkkk88kck', // vibn-postgres - 'o4wwck0g0c04wgoo4g4s0004', // gitea -]); - -function assertGiteaWritable(repo: string): void { - if (PROTECTED_GITEA_REPOS.has(repo)) { - throw new Error( - `SECURITY: Repo "${repo}" is a protected Vibn platform repo. ` + - `Agents cannot push code or modify issues in this repository.` - ); - } -} - -function assertCoolifyDeployable(appUuid: string): void { - if (PROTECTED_COOLIFY_APPS.has(appUuid)) { - throw new Error( - `SECURITY: App "${appUuid}" is a protected Vibn platform application. ` + - `Agents cannot trigger deployments for this application.` - ); - } -} - -// --------------------------------------------------------------------------- -// Context passed to every tool call — workspace root + credentials -// --------------------------------------------------------------------------- - -export interface MemoryUpdate { - key: string; - type: string; // e.g. "tech_stack" | "decision" | "feature" | "goal" | "constraint" | "note" - value: string; -} - -export interface ToolContext { - workspaceRoot: string; - gitea: { - apiUrl: string; - apiToken: string; - username: string; - }; - coolify: { - apiUrl: string; - apiToken: string; - }; - /** Accumulated memory updates from save_memory tool calls in this turn */ - memoryUpdates: MemoryUpdate[]; -} - -// --------------------------------------------------------------------------- -// Tool definitions (schema for Gemini function calling) -// --------------------------------------------------------------------------- - -export interface ToolDefinition { - name: string; - description: string; - parameters: Record; -} - -export const ALL_TOOLS: ToolDefinition[] = [ - { - name: 'read_file', - description: 'Read the complete content of a file in the workspace. Always read before editing.', - parameters: { - type: 'object', - properties: { - path: { type: 'string', description: 'Relative path from workspace root (e.g. "src/index.ts")' } - }, - required: ['path'] - } - }, - { - name: 'write_file', - description: 'Write complete content to a file. Creates parent directories if needed. Overwrites existing files.', - parameters: { - type: 'object', - properties: { - path: { type: 'string', description: 'Relative path from workspace root' }, - content: { type: 'string', description: 'Complete new file content' } - }, - required: ['path', 'content'] - } - }, - { - name: 'replace_in_file', - description: 'Replace an exact string in a file. The old_content must match character-for-character. Read the file first.', - parameters: { - type: 'object', - properties: { - path: { type: 'string', description: 'Relative path from workspace root' }, - old_content: { type: 'string', description: 'Exact text to replace' }, - new_content: { type: 'string', description: 'Replacement text' } - }, - required: ['path', 'old_content', 'new_content'] - } - }, - { - name: 'list_directory', - description: 'List files and subdirectories in a directory. Directories have trailing "/".', - parameters: { - type: 'object', - properties: { - path: { type: 'string', description: 'Relative path from workspace root. Use "." for root.' } - }, - required: ['path'] - } - }, - { - name: 'find_files', - description: 'Find files matching a glob pattern in the workspace. Returns up to 200 relative paths.', - parameters: { - type: 'object', - properties: { - pattern: { type: 'string', description: 'Glob pattern e.g. "**/*.ts", "src/**/*.test.js"' } - }, - required: ['pattern'] - } - }, - { - name: 'search_code', - description: 'Search file contents for a string or regex pattern. Returns file path, line number, and matching line.', - parameters: { - type: 'object', - properties: { - query: { type: 'string', description: 'Search term or regex' }, - file_extensions: { - type: 'array', - items: { type: 'string' }, - description: 'Optional: limit to these extensions e.g. ["ts","js"]' - } - }, - required: ['query'] - } - }, - { - name: 'execute_command', - description: 'Run a shell command in the workspace and return stdout + stderr. 120s timeout. Use for: npm install, npm test, git status, building, etc.', - parameters: { - type: 'object', - properties: { - command: { type: 'string', description: 'Shell command to run' }, - working_directory: { type: 'string', description: 'Optional: relative subdirectory to run in' } - }, - required: ['command'] - } - }, - { - name: 'git_commit_and_push', - description: 'Stage all changes, commit with a message, and push to the remote. Call this when work is complete.', - parameters: { - type: 'object', - properties: { - message: { type: 'string', description: 'Commit message describing the changes made' } - }, - required: ['message'] - } - }, - { - name: 'coolify_list_projects', - description: 'List all projects in the Coolify instance. Returns project names and UUIDs.', - parameters: { type: 'object', properties: {} } - }, - { - name: 'coolify_list_applications', - description: 'List applications in a Coolify project.', - parameters: { - type: 'object', - properties: { - project_uuid: { type: 'string', description: 'Project UUID from coolify_list_projects' } - }, - required: ['project_uuid'] - } - }, - { - name: 'coolify_deploy', - description: 'Trigger a deployment for a Coolify application.', - parameters: { - type: 'object', - properties: { - application_uuid: { type: 'string', description: 'Application UUID to deploy' } - }, - required: ['application_uuid'] - } - }, - { - name: 'coolify_get_logs', - description: 'Get recent deployment logs for a Coolify application.', - parameters: { - type: 'object', - properties: { - application_uuid: { type: 'string', description: 'Application UUID' } - }, - required: ['application_uuid'] - } - }, - { - name: 'gitea_create_issue', - description: 'Create a new issue in a Gitea repository.', - parameters: { - type: 'object', - properties: { - repo: { type: 'string', description: 'Repository in "owner/name" format' }, - title: { type: 'string', description: 'Issue title' }, - body: { type: 'string', description: 'Issue body (markdown)' }, - labels: { type: 'array', items: { type: 'string' }, description: 'Optional label names' } - }, - required: ['repo', 'title', 'body'] - } - }, - { - name: 'gitea_list_issues', - description: 'List open issues in a Gitea repository.', - parameters: { - type: 'object', - properties: { - repo: { type: 'string', description: 'Repository in "owner/name" format' }, - state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' } - }, - required: ['repo'] - } - }, - { - name: 'gitea_close_issue', - description: 'Close an issue in a Gitea repository.', - parameters: { - type: 'object', - properties: { - repo: { type: 'string', description: 'Repository in "owner/name" format' }, - issue_number: { type: 'number', description: 'Issue number to close' } - }, - required: ['repo', 'issue_number'] - } - }, - { - name: 'spawn_agent', - description: 'Dispatch a sub-agent job to run in the background. Returns a job ID. Use this to delegate specialized work to Coder, PM, or Marketing agents.', - parameters: { - type: 'object', - properties: { - agent: { type: 'string', description: '"Coder", "PM", or "Marketing"' }, - task: { type: 'string', description: 'Detailed task description for the agent' }, - repo: { type: 'string', description: 'Gitea repo in "owner/name" format the agent should work on' } - }, - required: ['agent', 'task', 'repo'] - } - }, - - // ------------------------------------------------------------------------- - // Orchestrator-only tools — project-wide awareness - // ------------------------------------------------------------------------- - { - name: 'list_repos', - description: 'List all Git repositories in the Gitea organization. Returns repo names, descriptions, and last update time.', - parameters: { type: 'object', properties: {} } - }, - { - name: 'list_all_issues', - description: 'List open issues across all repos or a specific repo. Use this to understand what work is queued or in progress.', - parameters: { - type: 'object', - properties: { - repo: { type: 'string', description: 'Optional: "owner/name" to scope to one repo. Omit for all repos.' }, - state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' } - } - } - }, - { - name: 'list_all_apps', - description: 'List all Coolify applications across all projects with their status (running/stopped/error) and domain.', - parameters: { type: 'object', properties: {} } - }, - { - name: 'get_app_status', - description: 'Get the current deployment status and recent logs for a specific Coolify application by name or UUID.', - parameters: { - type: 'object', - properties: { - app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend") or UUID' } - }, - required: ['app_name'] - } - }, - { - name: 'read_repo_file', - description: 'Read a file from any Gitea repository without cloning it. Useful for understanding project structure.', - parameters: { - type: 'object', - properties: { - repo: { type: 'string', description: 'Repo in "owner/name" format' }, - path: { type: 'string', description: 'File path within the repo (e.g. "src/app/page.tsx")' } - }, - required: ['repo', 'path'] - } - }, - { - name: 'get_job_status', - description: 'Check the status of a previously spawned agent job by job ID.', - parameters: { - type: 'object', - properties: { - job_id: { type: 'string', description: 'Job ID returned by spawn_agent' } - }, - required: ['job_id'] - } - }, - { - name: 'deploy_app', - description: 'Trigger a Coolify deployment for an app by name. Use after an agent commits code.', - parameters: { - type: 'object', - properties: { - app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend")' } - }, - required: ['app_name'] - } - }, - { - name: 'save_memory', - description: 'Persist an important fact about this project to long-term memory. Use this to save decisions, tech stack choices, feature descriptions, constraints, or goals so they are remembered across conversations.', - parameters: { - type: 'object', - properties: { - key: { type: 'string', description: 'Short unique label (e.g. "primary_language", "auth_strategy", "deploy_target")' }, - type: { - type: 'string', - enum: ['tech_stack', 'decision', 'feature', 'goal', 'constraint', 'note'], - description: 'Category of the memory item' - }, - value: { type: 'string', description: 'The fact to remember (1-3 sentences)' } - }, - required: ['key', 'type', 'value'] - } - } -]; - -// --------------------------------------------------------------------------- -// Tool executor — routes call.name → implementation -// --------------------------------------------------------------------------- - -export async function executeTool( - name: string, - args: Record, - ctx: ToolContext -): Promise { - switch (name) { - case 'read_file': return readFile(String(args.path), ctx); - case 'write_file': return writeFile(String(args.path), String(args.content), ctx); - case 'replace_in_file': return replaceInFile(String(args.path), String(args.old_content), String(args.new_content), ctx); - case 'list_directory': return listDirectory(String(args.path), ctx); - case 'find_files': return findFiles(String(args.pattern), ctx); - case 'search_code': return searchCode(String(args.query), args.file_extensions as string[] | undefined, ctx); - case 'execute_command': return executeCommand(String(args.command), args.working_directory as string | undefined, ctx); - case 'git_commit_and_push': return gitCommitAndPush(String(args.message), ctx); - case 'coolify_list_projects': return coolifyListProjects(ctx); - case 'coolify_list_applications': return coolifyListApplications(String(args.project_uuid), ctx); - case 'coolify_deploy': return coolifyDeploy(String(args.application_uuid), ctx); - case 'coolify_get_logs': return coolifyGetLogs(String(args.application_uuid), ctx); - case 'gitea_create_issue': return giteaCreateIssue(String(args.repo), String(args.title), String(args.body), args.labels as string[] | undefined, ctx); - case 'gitea_list_issues': return giteaListIssues(String(args.repo), (args.state as string) || 'open', ctx); - case 'gitea_close_issue': return giteaCloseIssue(String(args.repo), Number(args.issue_number), ctx); - case 'spawn_agent': return spawnAgentTool(String(args.agent), String(args.task), String(args.repo), ctx); - // Orchestrator tools - case 'list_repos': return listRepos(ctx); - case 'list_all_issues': return listAllIssues(args.repo as string | undefined, (args.state as string) || 'open', ctx); - case 'list_all_apps': return listAllApps(ctx); - case 'get_app_status': return getAppStatus(String(args.app_name), ctx); - case 'read_repo_file': return readRepoFile(String(args.repo), String(args.path), ctx); - case 'get_job_status': return getJobStatus(String(args.job_id)); - case 'deploy_app': return deployApp(String(args.app_name), ctx); - default: - return { error: `Unknown tool: ${name}` }; - } -} - -// --------------------------------------------------------------------------- -// Implementations -// --------------------------------------------------------------------------- - -const EXCLUDED = new Set(['node_modules', '.git', 'dist', 'build', 'lib', '.cache', 'coverage']); - -function safeResolve(root: string, rel: string): string { - const resolved = path.resolve(root, rel); - if (!resolved.startsWith(path.resolve(root))) { - throw new Error(`Path escapes workspace: ${rel}`); - } - return resolved; -} - -async function readFile(filePath: string, ctx: ToolContext): Promise { - const abs = safeResolve(ctx.workspaceRoot, filePath); - try { - return fs.readFileSync(abs, 'utf8'); - } catch { - return JSON.stringify({ error: `File not found: ${filePath}` }); - } -} - -async function writeFile(filePath: string, content: string, ctx: ToolContext): Promise { - const abs = safeResolve(ctx.workspaceRoot, filePath); - fs.mkdirSync(path.dirname(abs), { recursive: true }); - fs.writeFileSync(abs, content, 'utf8'); - return { success: true, path: filePath, bytes: Buffer.byteLength(content) }; -} - -async function replaceInFile(filePath: string, oldContent: string, newContent: string, ctx: ToolContext): Promise { - const abs = safeResolve(ctx.workspaceRoot, filePath); - const current = fs.readFileSync(abs, 'utf8'); - if (!current.includes(oldContent)) { - return { error: 'old_content not found in file. Read the file again to get the current content.' }; - } - fs.writeFileSync(abs, current.replace(oldContent, newContent), 'utf8'); - return { success: true, path: filePath }; -} - -async function listDirectory(dirPath: string, ctx: ToolContext): Promise { - const abs = safeResolve(ctx.workspaceRoot, dirPath); - try { - const entries = fs.readdirSync(abs, { withFileTypes: true }); - return entries - .filter(e => !EXCLUDED.has(e.name)) - .map(e => e.isDirectory() ? `${e.name}/` : e.name); - } catch { - return { error: `Directory not found: ${dirPath}` }; - } -} - -async function findFiles(pattern: string, ctx: ToolContext): Promise { - const matcher = new Minimatch(pattern, { dot: false }); - const results: string[] = []; - - function walk(dir: string): void { - if (results.length >= 200) return; - let entries: fs.Dirent[]; - try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } - for (const e of entries) { - if (EXCLUDED.has(e.name)) continue; - const abs = path.join(dir, e.name); - const rel = path.relative(ctx.workspaceRoot, abs).split(path.sep).join('/'); - if (e.isDirectory()) { - walk(abs); - } else if (matcher.match(rel)) { - results.push(rel); - } - } - } - - walk(ctx.workspaceRoot); - return { files: results, truncated: results.length >= 200 }; -} - -async function searchCode(query: string, extensions: string[] | undefined, ctx: ToolContext): Promise { - const globPatterns = extensions?.map(e => `*.${e}`) || []; - const args = ['--line-number', '--no-heading', '--color=never', '--max-count=30']; - for (const ex of EXCLUDED) { args.push('--glob', `!${ex}`); } - if (globPatterns.length > 0) { for (const g of globPatterns) args.push('--glob', g); } - args.push('--fixed-strings', query, ctx.workspaceRoot); - - try { - const { stdout } = await execAsync(`rg ${args.map(a => `'${a}'`).join(' ')}`, { cwd: ctx.workspaceRoot, timeout: 15000 }); - const lines = stdout.trim().split('\n').filter(Boolean).map(line => { - const m = line.match(/^(.+?):(\d+):(.*)$/); - if (!m) return null; - return { file: path.relative(ctx.workspaceRoot, m[1]).split(path.sep).join('/'), line: parseInt(m[2]), content: m[3].trim() }; - }).filter(Boolean); - return lines; - } catch (err: any) { - if (err.code === 1) return []; // ripgrep exit 1 = no matches - return { error: `Search failed: ${err.message}` }; - } -} - -async function executeCommand(command: string, workingDir: string | undefined, ctx: ToolContext): Promise { - const BLOCKED = ['rm -rf /', 'mkfs', ':(){:|:&};:']; - if (BLOCKED.some(b => command.includes(b))) { - return { error: 'Command blocked for safety.' }; - } - const cwd = workingDir ? safeResolve(ctx.workspaceRoot, workingDir) : ctx.workspaceRoot; - try { - const { stdout, stderr } = await execAsync(command, { cwd, timeout: 120_000, maxBuffer: 1024 * 1024 }); - return { exitCode: 0, stdout: stdout.trim(), stderr: stderr.trim() }; - } catch (err: any) { - return { exitCode: err.code, stdout: (err.stdout || '').trim(), stderr: (err.stderr || '').trim(), error: err.message }; - } -} - -async function gitCommitAndPush(message: string, ctx: ToolContext): Promise { - const cwd = ctx.workspaceRoot; - const { apiUrl, apiToken, username } = ctx.gitea; - - try { - // Check the remote URL before committing — block pushes to protected repos - let remoteCheck = ''; - try { remoteCheck = (await execAsync('git remote get-url origin', { cwd })).stdout.trim(); } catch { /* ok */ } - for (const protectedRepo of PROTECTED_GITEA_REPOS) { - const repoPath = protectedRepo.replace('mark/', ''); - if (remoteCheck.includes(`/${repoPath}`) || remoteCheck.includes(`/${repoPath}.git`)) { - return { - error: `SECURITY: This workspace is linked to a protected Vibn platform repo (${protectedRepo}). ` + - `Agents cannot push to platform repos. Only user project repos are writable.` - }; - } - } - - await execAsync('git add -A', { cwd }); - await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd }); - - // Get current remote URL, strip any existing credentials, re-inject cleanly - let remoteUrl = ''; - try { - remoteUrl = (await execAsync('git remote get-url origin', { cwd })).stdout.trim(); - } catch { /* no remote yet */ } - - const cleanUrl = remoteUrl.replace(/https:\/\/[^@]+@/, 'https://'); - const baseUrl = cleanUrl || apiUrl; - const authedUrl = baseUrl.replace('https://', `https://${username}:${apiToken}@`); - - await execAsync(`git remote set-url origin "${authedUrl}"`, { cwd }).catch(async () => { - await execAsync(`git remote add origin "${authedUrl}"`, { cwd }); - }); - - const branch = (await execAsync('git rev-parse --abbrev-ref HEAD', { cwd })).stdout.trim(); - await execAsync(`git push -u origin "${branch}"`, { cwd, timeout: 60_000 }); - - return { success: true, message, branch }; - } catch (err: any) { - const cleaned = (err.message || '').replace(new RegExp(apiToken, 'g'), '***'); - return { error: `Git operation failed: ${cleaned}` }; - } -} - -// --------------------------------------------------------------------------- -// Coolify tools -// --------------------------------------------------------------------------- - -async function coolifyFetch(path: string, ctx: ToolContext, method = 'GET', body?: unknown): Promise { - const res = await fetch(`${ctx.coolify.apiUrl}/api/v1${path}`, { - method, - headers: { - 'Authorization': `Bearer ${ctx.coolify.apiToken}`, - 'Content-Type': 'application/json', - 'Accept': 'application/json' - }, - body: body ? JSON.stringify(body) : undefined - }); - if (!res.ok) return { error: `Coolify API error: ${res.status} ${res.statusText}` }; - return res.json(); -} - -async function coolifyListProjects(ctx: ToolContext): Promise { - const projects = await coolifyFetch('/projects', ctx) as any[]; - if (!Array.isArray(projects)) return projects; - // Filter out the protected VIBN project entirely — agents don't need to see it - return projects.filter((p: any) => p.uuid !== PROTECTED_COOLIFY_PROJECT); -} - -async function coolifyListApplications(projectUuid: string, ctx: ToolContext): Promise { - const all = await coolifyFetch('/applications', ctx) as any[]; - if (!Array.isArray(all)) return all; - return all.filter((a: any) => a.project_uuid === projectUuid); -} - -async function coolifyDeploy(appUuid: string, ctx: ToolContext): Promise { - assertCoolifyDeployable(appUuid); - // Also check the app belongs to the right project - const apps = await coolifyFetch('/applications', ctx) as any[]; - if (Array.isArray(apps)) { - const app = apps.find((a: any) => a.uuid === appUuid); - if (app?.project_uuid === PROTECTED_COOLIFY_PROJECT) { - return { error: `SECURITY: App "${appUuid}" belongs to the protected Vibn project. Agents cannot deploy platform apps.` }; - } - } - return coolifyFetch(`/applications/${appUuid}/deploy`, ctx, 'POST'); -} - -async function coolifyGetLogs(appUuid: string, ctx: ToolContext): Promise { - return coolifyFetch(`/applications/${appUuid}/logs?limit=50`, ctx); -} - -// --------------------------------------------------------------------------- -// Gitea tools -// --------------------------------------------------------------------------- - -async function giteaFetch(path: string, ctx: ToolContext, method = 'GET', body?: unknown): Promise { - const res = await fetch(`${ctx.gitea.apiUrl}/api/v1${path}`, { - method, - headers: { - 'Authorization': `token ${ctx.gitea.apiToken}`, - 'Content-Type': 'application/json', - 'Accept': 'application/json' - }, - body: body ? JSON.stringify(body) : undefined - }); - if (!res.ok) return { error: `Gitea API error: ${res.status} ${res.statusText}` }; - return res.json(); -} - -async function giteaCreateIssue(repo: string, title: string, body: string, labels: string[] | undefined, ctx: ToolContext): Promise { - assertGiteaWritable(repo); - return giteaFetch(`/repos/${repo}/issues`, ctx, 'POST', { title, body, labels }); -} - -async function giteaListIssues(repo: string, state: string, ctx: ToolContext): Promise { - return giteaFetch(`/repos/${repo}/issues?state=${state}&limit=20`, ctx); -} - -async function giteaCloseIssue(repo: string, issueNumber: number, ctx: ToolContext): Promise { - assertGiteaWritable(repo); - return giteaFetch(`/repos/${repo}/issues/${issueNumber}`, ctx, 'PATCH', { state: 'closed' }); -} - -// --------------------------------------------------------------------------- -// Spawn agent (used by Orchestrator to delegate to specialists) -// Calls back to the AgentRunner HTTP API to queue a new job. -// --------------------------------------------------------------------------- - -async function spawnAgentTool(agent: string, task: string, repo: string, _ctx: ToolContext): Promise { - const runnerUrl = process.env.AGENT_RUNNER_URL || 'http://localhost:3333'; - try { - const res = await fetch(`${runnerUrl}/api/agent/run`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'X-Internal': 'true' }, - body: JSON.stringify({ agent, task, repo }) - }); - const data = await res.json() as any; - return { jobId: data.jobId, agent, status: 'dispatched' }; - } catch (err) { - return { error: `Failed to spawn agent: ${err instanceof Error ? err.message : String(err)}` }; - } -} - -// --------------------------------------------------------------------------- -// Orchestrator tools — project-wide awareness -// --------------------------------------------------------------------------- - -async function listRepos(ctx: ToolContext): Promise { - const res = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/search?limit=50&token=${ctx.gitea.apiToken}`, { - headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } - }); - const data = await res.json() as any; - return (data.data || []) - // Hide protected platform repos from agent's view entirely - .filter((r: any) => !PROTECTED_GITEA_REPOS.has(r.full_name)) - .map((r: any) => ({ - name: r.full_name, - description: r.description, - default_branch: r.default_branch, - updated: r.updated, - stars: r.stars_count, - open_issues: r.open_issues_count - })); -} - -async function listAllIssues(repo: string | undefined, state: string, ctx: ToolContext): Promise { - if (repo) { - if (PROTECTED_GITEA_REPOS.has(repo)) { - return { error: `SECURITY: "${repo}" is a protected Vibn platform repo. Agents cannot access its issues.` }; - } - return giteaFetch(`/repos/${repo}/issues?state=${state}&limit=20`, ctx); - } - // Fetch across all non-protected repos - const repos = await listRepos(ctx) as any[]; - const allIssues: unknown[] = []; - for (const r of repos.slice(0, 10)) { - const issues = await giteaFetch(`/repos/${r.name}/issues?state=${state}&limit=10`, ctx) as any[]; - if (Array.isArray(issues)) { - allIssues.push(...issues.map((i: any) => ({ - repo: r.name, - number: i.number, - title: i.title, - state: i.state, - labels: i.labels?.map((l: any) => l.name), - created: i.created_at - }))); - } - } - return allIssues; -} - -async function listAllApps(ctx: ToolContext): Promise { - const apps = await coolifyFetch('/applications', ctx) as any[]; - if (!Array.isArray(apps)) return apps; - return apps - // Filter out apps that belong to the protected VIBN project - .filter((a: any) => a.project_uuid !== PROTECTED_COOLIFY_PROJECT && !PROTECTED_COOLIFY_APPS.has(a.uuid)) - .map((a: any) => ({ - uuid: a.uuid, - name: a.name, - fqdn: a.fqdn, - status: a.status, - repo: a.git_repository, - branch: a.git_branch - })); -} - -async function getAppStatus(appName: string, ctx: ToolContext): Promise { - const apps = await coolifyFetch('/applications', ctx) as any[]; - if (!Array.isArray(apps)) return apps; - const app = apps.find((a: any) => - a.name?.toLowerCase() === appName.toLowerCase() || a.uuid === appName - ); - if (!app) return { error: `App "${appName}" not found` }; - if (PROTECTED_COOLIFY_APPS.has(app.uuid) || app.project_uuid === PROTECTED_COOLIFY_PROJECT) { - return { error: `SECURITY: "${appName}" is a protected Vibn platform app. Status is not exposed to agents.` }; - } - const logs = await coolifyFetch(`/applications/${app.uuid}/logs?limit=20`, ctx); - return { name: app.name, uuid: app.uuid, status: app.status, fqdn: app.fqdn, logs }; -} - -async function readRepoFile(repo: string, filePath: string, ctx: ToolContext): Promise { - try { - const res = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/${repo}/contents/${filePath}`, { - headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } - }); - if (!res.ok) return { error: `File not found: ${filePath} in ${repo}` }; - const data = await res.json() as any; - const content = Buffer.from(data.content, 'base64').toString('utf8'); - return { repo, path: filePath, content }; - } catch (err) { - return { error: `Failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}` }; - } -} - -async function getJobStatus(jobId: string): Promise { - const runnerUrl = process.env.AGENT_RUNNER_URL || 'http://localhost:3333'; - try { - const res = await fetch(`${runnerUrl}/api/jobs/${jobId}`); - const job = await res.json() as any; - return { - id: job.id, - agent: job.agent, - status: job.status, - progress: job.progress, - toolCalls: job.toolCalls?.length, - result: job.result, - error: job.error - }; - } catch (err) { - return { error: `Failed to get job: ${err instanceof Error ? err.message : String(err)}` }; - } -} - -function saveMemory(key: string, type: string, value: string, ctx: ToolContext): unknown { - ctx.memoryUpdates.push({ key, type, value }); - return { saved: true, key, type }; -} - -async function deployApp(appName: string, ctx: ToolContext): Promise { - const apps = await coolifyFetch('/applications', ctx) as any[]; - if (!Array.isArray(apps)) return apps; - const app = apps.find((a: any) => - a.name?.toLowerCase() === appName.toLowerCase() || a.uuid === appName - ); - if (!app) return { error: `App "${appName}" not found` }; - // Block deployment to protected VIBN platform apps - if (PROTECTED_COOLIFY_APPS.has(app.uuid) || app.project_uuid === PROTECTED_COOLIFY_PROJECT) { - return { - error: `SECURITY: "${appName}" is a protected Vibn platform application. ` + - `Agents can only deploy user project apps, not platform infrastructure.` - }; - } - const result = await fetch(`${ctx.coolify.apiUrl}/api/v1/deploy?uuid=${app.uuid}&force=false`, { - headers: { 'Authorization': `Bearer ${ctx.coolify.apiToken}` } - }); - return result.json(); -} diff --git a/src/tools/agent.ts b/src/tools/agent.ts new file mode 100644 index 0000000..74e1f51 --- /dev/null +++ b/src/tools/agent.ts @@ -0,0 +1,59 @@ +import { registerTool } from './registry'; + +registerTool({ + name: 'spawn_agent', + description: 'Dispatch a sub-agent job to run in the background. Returns a job ID. Use this to delegate specialized work to Coder, PM, or Marketing agents.', + parameters: { + type: 'object', + properties: { + agent: { type: 'string', description: '"Coder", "PM", or "Marketing"' }, + task: { type: 'string', description: 'Detailed task description for the agent' }, + repo: { type: 'string', description: 'Gitea repo in "owner/name" format the agent should work on' } + }, + required: ['agent', 'task', 'repo'] + }, + async handler(args, _ctx) { + const runnerUrl = process.env.AGENT_RUNNER_URL || 'http://localhost:3333'; + try { + const res = await fetch(`${runnerUrl}/api/agent/run`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Internal': 'true' }, + body: JSON.stringify({ agent: args.agent, task: args.task, repo: args.repo }) + }); + const data = await res.json() as any; + return { jobId: data.jobId, agent: args.agent, status: 'dispatched' }; + } catch (err) { + return { error: `Failed to spawn agent: ${err instanceof Error ? err.message : String(err)}` }; + } + } +}); + +registerTool({ + name: 'get_job_status', + description: 'Check the status of a previously spawned agent job by job ID.', + parameters: { + type: 'object', + properties: { + job_id: { type: 'string', description: 'Job ID returned by spawn_agent' } + }, + required: ['job_id'] + }, + async handler(args, _ctx) { + const runnerUrl = process.env.AGENT_RUNNER_URL || 'http://localhost:3333'; + try { + const res = await fetch(`${runnerUrl}/api/jobs/${String(args.job_id)}`); + const job = await res.json() as any; + return { + id: job.id, + agent: job.agent, + status: job.status, + progress: job.progress, + toolCalls: job.toolCalls?.length, + result: job.result, + error: job.error + }; + } catch (err) { + return { error: `Failed to get job: ${err instanceof Error ? err.message : String(err)}` }; + } + } +}); diff --git a/src/tools/context.ts b/src/tools/context.ts new file mode 100644 index 0000000..031f964 --- /dev/null +++ b/src/tools/context.ts @@ -0,0 +1,20 @@ +export interface MemoryUpdate { + key: string; + type: string; // "tech_stack" | "decision" | "feature" | "goal" | "constraint" | "note" + value: string; +} + +export interface ToolContext { + workspaceRoot: string; + gitea: { + apiUrl: string; + apiToken: string; + username: string; + }; + coolify: { + apiUrl: string; + apiToken: string; + }; + /** Accumulated memory updates from save_memory tool calls in this turn */ + memoryUpdates: MemoryUpdate[]; +} diff --git a/src/tools/coolify.ts b/src/tools/coolify.ts new file mode 100644 index 0000000..9439ffe --- /dev/null +++ b/src/tools/coolify.ts @@ -0,0 +1,161 @@ +import { registerTool } from './registry'; +import { ToolContext } from './context'; +import { PROTECTED_COOLIFY_PROJECT, PROTECTED_COOLIFY_APPS, assertCoolifyDeployable } from './security'; + +async function coolifyFetch(path: string, ctx: ToolContext, method = 'GET', body?: unknown): Promise { + const res = await fetch(`${ctx.coolify.apiUrl}/api/v1${path}`, { + method, + headers: { + 'Authorization': `Bearer ${ctx.coolify.apiToken}`, + 'Content-Type': 'application/json', + 'Accept': 'application/json' + }, + body: body ? JSON.stringify(body) : undefined + }); + if (!res.ok) return { error: `Coolify API error: ${res.status} ${res.statusText}` }; + return res.json(); +} + +registerTool({ + name: 'coolify_list_projects', + description: 'List all projects in the Coolify instance. Returns project names and UUIDs.', + parameters: { type: 'object', properties: {} }, + async handler(_args, ctx) { + const projects = await coolifyFetch('/projects', ctx) as any[]; + if (!Array.isArray(projects)) return projects; + return projects.filter((p: any) => p.uuid !== PROTECTED_COOLIFY_PROJECT); + } +}); + +registerTool({ + name: 'coolify_list_applications', + description: 'List applications in a Coolify project.', + parameters: { + type: 'object', + properties: { + project_uuid: { type: 'string', description: 'Project UUID from coolify_list_projects' } + }, + required: ['project_uuid'] + }, + async handler(args, ctx) { + const all = await coolifyFetch('/applications', ctx) as any[]; + if (!Array.isArray(all)) return all; + return all.filter((a: any) => a.project_uuid === String(args.project_uuid)); + } +}); + +registerTool({ + name: 'coolify_deploy', + description: 'Trigger a deployment for a Coolify application.', + parameters: { + type: 'object', + properties: { + application_uuid: { type: 'string', description: 'Application UUID to deploy' } + }, + required: ['application_uuid'] + }, + async handler(args, ctx) { + const appUuid = String(args.application_uuid); + assertCoolifyDeployable(appUuid); + const apps = await coolifyFetch('/applications', ctx) as any[]; + if (Array.isArray(apps)) { + const app = apps.find((a: any) => a.uuid === appUuid); + if (app?.project_uuid === PROTECTED_COOLIFY_PROJECT) { + return { error: `SECURITY: App "${appUuid}" belongs to the protected Vibn project. Agents cannot deploy platform apps.` }; + } + } + return coolifyFetch(`/applications/${appUuid}/deploy`, ctx, 'POST'); + } +}); + +registerTool({ + name: 'coolify_get_logs', + description: 'Get recent deployment logs for a Coolify application.', + parameters: { + type: 'object', + properties: { + application_uuid: { type: 'string', description: 'Application UUID' } + }, + required: ['application_uuid'] + }, + async handler(args, ctx) { + return coolifyFetch(`/applications/${String(args.application_uuid)}/logs?limit=50`, ctx); + } +}); + +registerTool({ + name: 'list_all_apps', + description: 'List all Coolify applications across all projects with their status (running/stopped/error) and domain.', + parameters: { type: 'object', properties: {} }, + async handler(_args, ctx) { + const apps = await coolifyFetch('/applications', ctx) as any[]; + if (!Array.isArray(apps)) return apps; + return apps + .filter((a: any) => a.project_uuid !== PROTECTED_COOLIFY_PROJECT && !PROTECTED_COOLIFY_APPS.has(a.uuid)) + .map((a: any) => ({ + uuid: a.uuid, + name: a.name, + fqdn: a.fqdn, + status: a.status, + repo: a.git_repository, + branch: a.git_branch + })); + } +}); + +registerTool({ + name: 'get_app_status', + description: 'Get the current deployment status and recent logs for a specific Coolify application by name or UUID.', + parameters: { + type: 'object', + properties: { + app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend") or UUID' } + }, + required: ['app_name'] + }, + async handler(args, ctx) { + const apps = await coolifyFetch('/applications', ctx) as any[]; + if (!Array.isArray(apps)) return apps; + const appName = String(args.app_name); + const app = apps.find((a: any) => + a.name?.toLowerCase() === appName.toLowerCase() || a.uuid === appName + ); + if (!app) return { error: `App "${appName}" not found` }; + if (PROTECTED_COOLIFY_APPS.has(app.uuid) || app.project_uuid === PROTECTED_COOLIFY_PROJECT) { + return { error: `SECURITY: "${appName}" is a protected Vibn platform app. Status is not exposed to agents.` }; + } + const logs = await coolifyFetch(`/applications/${app.uuid}/logs?limit=20`, ctx); + return { name: app.name, uuid: app.uuid, status: app.status, fqdn: app.fqdn, logs }; + } +}); + +registerTool({ + name: 'deploy_app', + description: 'Trigger a Coolify deployment for an app by name. Use after an agent commits code.', + parameters: { + type: 'object', + properties: { + app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend")' } + }, + required: ['app_name'] + }, + async handler(args, ctx) { + const apps = await coolifyFetch('/applications', ctx) as any[]; + if (!Array.isArray(apps)) return apps; + const appName = String(args.app_name); + const app = apps.find((a: any) => + a.name?.toLowerCase() === appName.toLowerCase() || a.uuid === appName + ); + if (!app) return { error: `App "${appName}" not found` }; + if (PROTECTED_COOLIFY_APPS.has(app.uuid) || app.project_uuid === PROTECTED_COOLIFY_PROJECT) { + return { + error: `SECURITY: "${appName}" is a protected Vibn platform application. ` + + `Agents can only deploy user project apps, not platform infrastructure.` + }; + } + const result = await fetch(`${ctx.coolify.apiUrl}/api/v1/deploy?uuid=${app.uuid}&force=false`, { + headers: { 'Authorization': `Bearer ${ctx.coolify.apiToken}` } + }); + return result.json(); + } +}); diff --git a/src/tools/file.ts b/src/tools/file.ts new file mode 100644 index 0000000..e966b72 --- /dev/null +++ b/src/tools/file.ts @@ -0,0 +1,172 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import * as cp from 'child_process'; +import * as util from 'util'; +import { Minimatch } from 'minimatch'; +import { registerTool } from './registry'; +import { safeResolve, EXCLUDED } from './utils'; + +const execAsync = util.promisify(cp.exec); + +registerTool({ + name: 'read_file', + description: 'Read the complete content of a file in the workspace. Always read before editing.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root (e.g. "src/index.ts")' } + }, + required: ['path'] + }, + async handler(args, ctx) { + const abs = safeResolve(ctx.workspaceRoot, String(args.path)); + try { + return fs.readFileSync(abs, 'utf8'); + } catch { + return { error: `File not found: ${args.path}` }; + } + } +}); + +registerTool({ + name: 'write_file', + description: 'Write complete content to a file. Creates parent directories if needed. Overwrites existing files.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root' }, + content: { type: 'string', description: 'Complete new file content' } + }, + required: ['path', 'content'] + }, + async handler(args, ctx) { + const abs = safeResolve(ctx.workspaceRoot, String(args.path)); + fs.mkdirSync(path.dirname(abs), { recursive: true }); + fs.writeFileSync(abs, String(args.content), 'utf8'); + return { success: true, path: args.path, bytes: Buffer.byteLength(String(args.content)) }; + } +}); + +registerTool({ + name: 'replace_in_file', + description: 'Replace an exact string in a file. The old_content must match character-for-character. Read the file first.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root' }, + old_content: { type: 'string', description: 'Exact text to replace' }, + new_content: { type: 'string', description: 'Replacement text' } + }, + required: ['path', 'old_content', 'new_content'] + }, + async handler(args, ctx) { + const abs = safeResolve(ctx.workspaceRoot, String(args.path)); + const current = fs.readFileSync(abs, 'utf8'); + if (!current.includes(String(args.old_content))) { + return { error: 'old_content not found in file. Read the file again to get the current content.' }; + } + fs.writeFileSync(abs, current.replace(String(args.old_content), String(args.new_content)), 'utf8'); + return { success: true, path: args.path }; + } +}); + +registerTool({ + name: 'list_directory', + description: 'List files and subdirectories in a directory. Directories have trailing "/".', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'Relative path from workspace root. Use "." for root.' } + }, + required: ['path'] + }, + async handler(args, ctx) { + const abs = safeResolve(ctx.workspaceRoot, String(args.path)); + try { + const entries = fs.readdirSync(abs, { withFileTypes: true }); + return entries + .filter(e => !EXCLUDED.has(e.name)) + .map(e => e.isDirectory() ? `${e.name}/` : e.name); + } catch { + return { error: `Directory not found: ${args.path}` }; + } + } +}); + +registerTool({ + name: 'find_files', + description: 'Find files matching a glob pattern in the workspace. Returns up to 200 relative paths.', + parameters: { + type: 'object', + properties: { + pattern: { type: 'string', description: 'Glob pattern e.g. "**/*.ts", "src/**/*.test.js"' } + }, + required: ['pattern'] + }, + async handler(args, ctx) { + const matcher = new Minimatch(String(args.pattern), { dot: false }); + const results: string[] = []; + + function walk(dir: string): void { + if (results.length >= 200) return; + let entries: fs.Dirent[]; + try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const e of entries) { + if (EXCLUDED.has(e.name)) continue; + const abs = path.join(dir, e.name); + const rel = path.relative(ctx.workspaceRoot, abs).split(path.sep).join('/'); + if (e.isDirectory()) { + walk(abs); + } else if (matcher.match(rel)) { + results.push(rel); + } + } + } + + walk(ctx.workspaceRoot); + return { files: results, truncated: results.length >= 200 }; + } +}); + +registerTool({ + name: 'search_code', + description: 'Search file contents for a string or regex pattern. Returns file path, line number, and matching line.', + parameters: { + type: 'object', + properties: { + query: { type: 'string', description: 'Search term or regex' }, + file_extensions: { + type: 'array', + items: { type: 'string' }, + description: 'Optional: limit to these extensions e.g. ["ts","js"]' + } + }, + required: ['query'] + }, + async handler(args, ctx) { + const extensions = args.file_extensions as string[] | undefined; + const globPatterns = extensions?.map(e => `*.${e}`) || []; + const rgArgs = ['--line-number', '--no-heading', '--color=never', '--max-count=30']; + for (const ex of EXCLUDED) { rgArgs.push('--glob', `!${ex}`); } + if (globPatterns.length > 0) { for (const g of globPatterns) rgArgs.push('--glob', g); } + rgArgs.push('--fixed-strings', String(args.query), ctx.workspaceRoot); + + try { + const { stdout } = await execAsync(`rg ${rgArgs.map(a => `'${a}'`).join(' ')}`, { + cwd: ctx.workspaceRoot, timeout: 15000 + }); + return stdout.trim().split('\n').filter(Boolean).map(line => { + const m = line.match(/^(.+?):(\d+):(.*)$/); + if (!m) return null; + return { + file: path.relative(ctx.workspaceRoot, m[1]).split(path.sep).join('/'), + line: parseInt(m[2]), + content: m[3].trim() + }; + }).filter(Boolean); + } catch (err: any) { + if (err.code === 1) return []; // ripgrep exit 1 = no matches + return { error: `Search failed: ${err.message}` }; + } + } +}); diff --git a/src/tools/git.ts b/src/tools/git.ts new file mode 100644 index 0000000..661e605 --- /dev/null +++ b/src/tools/git.ts @@ -0,0 +1,66 @@ +import * as cp from 'child_process'; +import * as util from 'util'; +import { registerTool } from './registry'; +import { PROTECTED_GITEA_REPOS } from './security'; + +const execAsync = util.promisify(cp.exec); + +registerTool({ + name: 'git_commit_and_push', + description: 'Stage all changes, commit with a message, and push to the remote. Call this when work is complete.', + parameters: { + type: 'object', + properties: { + message: { type: 'string', description: 'Commit message describing the changes made' } + }, + required: ['message'] + }, + async handler(args, ctx) { + const cwd = ctx.workspaceRoot; + const { apiUrl, apiToken, username } = ctx.gitea; + const message = String(args.message); + + try { + // Check remote URL before committing — block pushes to protected repos + let remoteCheck = ''; + try { + remoteCheck = (await execAsync('git remote get-url origin', { cwd })).stdout.trim(); + } catch { /* no remote yet */ } + + for (const protectedRepo of PROTECTED_GITEA_REPOS) { + const repoPath = protectedRepo.replace('mark/', ''); + if (remoteCheck.includes(`/${repoPath}`) || remoteCheck.includes(`/${repoPath}.git`)) { + return { + error: `SECURITY: This workspace is linked to a protected Vibn platform repo (${protectedRepo}). ` + + `Agents cannot push to platform repos. Only user project repos are writable.` + }; + } + } + + await execAsync('git add -A', { cwd }); + await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd }); + + // Strip any existing credentials from remote URL and re-inject cleanly + let remoteUrl = ''; + try { + remoteUrl = (await execAsync('git remote get-url origin', { cwd })).stdout.trim(); + } catch { /* no remote */ } + + const cleanUrl = remoteUrl.replace(/https:\/\/[^@]+@/, 'https://'); + const baseUrl = cleanUrl || apiUrl; + const authedUrl = baseUrl.replace('https://', `https://${username}:${apiToken}@`); + + await execAsync(`git remote set-url origin "${authedUrl}"`, { cwd }).catch(async () => { + await execAsync(`git remote add origin "${authedUrl}"`, { cwd }); + }); + + const branch = (await execAsync('git rev-parse --abbrev-ref HEAD', { cwd })).stdout.trim(); + await execAsync(`git push -u origin "${branch}"`, { cwd, timeout: 60_000 }); + + return { success: true, message, branch }; + } catch (err: any) { + const cleaned = (err.message || '').replace(new RegExp(apiToken, 'g'), '***'); + return { error: `Git operation failed: ${cleaned}` }; + } + } +}); diff --git a/src/tools/gitea.ts b/src/tools/gitea.ts new file mode 100644 index 0000000..a25e4fe --- /dev/null +++ b/src/tools/gitea.ts @@ -0,0 +1,170 @@ +import { registerTool } from './registry'; +import { ToolContext } from './context'; +import { PROTECTED_GITEA_REPOS, assertGiteaWritable } from './security'; + +async function giteaFetch(path: string, ctx: ToolContext, method = 'GET', body?: unknown): Promise { + const res = await fetch(`${ctx.gitea.apiUrl}/api/v1${path}`, { + method, + headers: { + 'Authorization': `token ${ctx.gitea.apiToken}`, + 'Content-Type': 'application/json', + 'Accept': 'application/json' + }, + body: body ? JSON.stringify(body) : undefined + }); + if (!res.ok) return { error: `Gitea API error: ${res.status} ${res.statusText}` }; + return res.json(); +} + +registerTool({ + name: 'gitea_create_issue', + description: 'Create a new issue in a Gitea repository.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repository in "owner/name" format' }, + title: { type: 'string', description: 'Issue title' }, + body: { type: 'string', description: 'Issue body (markdown)' }, + labels: { type: 'array', items: { type: 'string' }, description: 'Optional label names' } + }, + required: ['repo', 'title', 'body'] + }, + async handler(args, ctx) { + const repo = String(args.repo); + assertGiteaWritable(repo); + return giteaFetch(`/repos/${repo}/issues`, ctx, 'POST', { + title: args.title, + body: args.body, + labels: args.labels + }); + } +}); + +registerTool({ + name: 'gitea_list_issues', + description: 'List open issues in a Gitea repository.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repository in "owner/name" format' }, + state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' } + }, + required: ['repo'] + }, + async handler(args, ctx) { + const state = String(args.state || 'open'); + return giteaFetch(`/repos/${String(args.repo)}/issues?state=${state}&limit=20`, ctx); + } +}); + +registerTool({ + name: 'gitea_close_issue', + description: 'Close an issue in a Gitea repository.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repository in "owner/name" format' }, + issue_number: { type: 'number', description: 'Issue number to close' } + }, + required: ['repo', 'issue_number'] + }, + async handler(args, ctx) { + const repo = String(args.repo); + assertGiteaWritable(repo); + return giteaFetch(`/repos/${repo}/issues/${Number(args.issue_number)}`, ctx, 'PATCH', { state: 'closed' }); + } +}); + +registerTool({ + name: 'list_repos', + description: 'List all Git repositories in the Gitea organization. Returns repo names, descriptions, and last update time.', + parameters: { type: 'object', properties: {} }, + async handler(_args, ctx) { + const res = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/search?limit=50`, { + headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } + }); + const data = await res.json() as any; + return (data.data || []) + .filter((r: any) => !PROTECTED_GITEA_REPOS.has(r.full_name)) + .map((r: any) => ({ + name: r.full_name, + description: r.description, + default_branch: r.default_branch, + updated: r.updated, + stars: r.stars_count, + open_issues: r.open_issues_count + })); + } +}); + +registerTool({ + name: 'list_all_issues', + description: 'List open issues across all repos or a specific repo. Use this to understand what work is queued or in progress.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Optional: "owner/name" to scope to one repo. Omit for all repos.' }, + state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' } + } + }, + async handler(args, ctx) { + const state = String(args.state || 'open'); + if (args.repo) { + const repo = String(args.repo); + if (PROTECTED_GITEA_REPOS.has(repo)) { + return { error: `SECURITY: "${repo}" is a protected Vibn platform repo. Agents cannot access its issues.` }; + } + return giteaFetch(`/repos/${repo}/issues?state=${state}&limit=20`, ctx); + } + // Fetch across all non-protected repos + const reposRes = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/search?limit=50`, { + headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } + }); + const reposData = await reposRes.json() as any; + const repos = (reposData.data || []).filter((r: any) => !PROTECTED_GITEA_REPOS.has(r.full_name)); + + const allIssues: unknown[] = []; + for (const r of repos.slice(0, 10)) { + const issues = await giteaFetch(`/repos/${r.full_name}/issues?state=${state}&limit=10`, ctx) as any[]; + if (Array.isArray(issues)) { + allIssues.push(...issues.map((i: any) => ({ + repo: r.full_name, + number: i.number, + title: i.title, + state: i.state, + labels: i.labels?.map((l: any) => l.name), + created: i.created_at + }))); + } + } + return allIssues; + } +}); + +registerTool({ + name: 'read_repo_file', + description: 'Read a file from any Gitea repository without cloning it. Useful for understanding project structure.', + parameters: { + type: 'object', + properties: { + repo: { type: 'string', description: 'Repo in "owner/name" format' }, + path: { type: 'string', description: 'File path within the repo (e.g. "src/app/page.tsx")' } + }, + required: ['repo', 'path'] + }, + async handler(args, ctx) { + const repo = String(args.repo); + const filePath = String(args.path); + try { + const res = await fetch(`${ctx.gitea.apiUrl}/api/v1/repos/${repo}/contents/${filePath}`, { + headers: { 'Authorization': `token ${ctx.gitea.apiToken}` } + }); + if (!res.ok) return { error: `File not found: ${filePath} in ${repo}` }; + const data = await res.json() as any; + const content = Buffer.from(data.content, 'base64').toString('utf8'); + return { repo, path: filePath, content }; + } catch (err) { + return { error: `Failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}` }; + } + } +}); diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 0000000..20e9748 --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,14 @@ +// Import domain files first — side effects register each tool into the registry. +// Order determines ALL_TOOLS array order (informational only). +import './file'; +import './shell'; +import './git'; +import './gitea'; +import './coolify'; +import './agent'; +import './memory'; + +// Re-export the public API — identical surface to the old tools.ts +export { ALL_TOOLS, executeTool, ToolDefinition } from './registry'; +export { ToolContext, MemoryUpdate } from './context'; +export { PROTECTED_GITEA_REPOS, PROTECTED_COOLIFY_PROJECT, PROTECTED_COOLIFY_APPS, assertGiteaWritable, assertCoolifyDeployable } from './security'; diff --git a/src/tools/memory.ts b/src/tools/memory.ts new file mode 100644 index 0000000..8178d9c --- /dev/null +++ b/src/tools/memory.ts @@ -0,0 +1,27 @@ +import { registerTool } from './registry'; + +registerTool({ + name: 'save_memory', + description: 'Persist an important fact about this project to long-term memory. Use this to save decisions, tech stack choices, feature descriptions, constraints, or goals so they are remembered across conversations.', + parameters: { + type: 'object', + properties: { + key: { type: 'string', description: 'Short unique label (e.g. "primary_language", "auth_strategy", "deploy_target")' }, + type: { + type: 'string', + enum: ['tech_stack', 'decision', 'feature', 'goal', 'constraint', 'note'], + description: 'Category of the memory item' + }, + value: { type: 'string', description: 'The fact to remember (1-3 sentences)' } + }, + required: ['key', 'type', 'value'] + }, + async handler(args, ctx) { + ctx.memoryUpdates.push({ + key: String(args.key), + type: String(args.type), + value: String(args.value) + }); + return { saved: true, key: args.key, type: args.type }; + } +}); diff --git a/src/tools/registry.ts b/src/tools/registry.ts new file mode 100644 index 0000000..480791e --- /dev/null +++ b/src/tools/registry.ts @@ -0,0 +1,34 @@ +import { ToolContext } from './context'; + +export interface ToolDefinition { + name: string; + description: string; + parameters: Record; + /** Implementation — called by executeTool(). Not sent to the LLM. */ + handler: (args: Record, ctx: ToolContext) => Promise; +} + +/** Live registry — grows as domain files are imported. */ +const _registry = new Map(); + +/** + * Mutable array kept in sync with the registry. + * Used by agents.ts to pick tool subsets by name (backwards-compatible with ALL_TOOLS). + */ +export const ALL_TOOLS: ToolDefinition[] = []; + +export function registerTool(tool: ToolDefinition): void { + _registry.set(tool.name, tool); + ALL_TOOLS.push(tool); +} + +/** Dispatch a tool call by name — O(1) map lookup, no switch needed. */ +export async function executeTool( + name: string, + args: Record, + ctx: ToolContext +): Promise { + const tool = _registry.get(name); + if (!tool) return { error: `Unknown tool: ${name}` }; + return tool.handler(args, ctx); +} diff --git a/src/tools/security.ts b/src/tools/security.ts new file mode 100644 index 0000000..344b799 --- /dev/null +++ b/src/tools/security.ts @@ -0,0 +1,48 @@ +// ============================================================================= +// SECURITY GUARDRAILS — Protected VIBN Platform Resources +// +// These repos and Coolify resources belong to the Vibn platform itself. +// Agents must never be allowed to push code or trigger deployments here. +// Read-only operations (list, read file, get status) are still permitted +// so agents can observe platform state, but all mutations are blocked. +// ============================================================================= + +/** Gitea repos agents can NEVER push to, commit to, or write issues on. */ +export const PROTECTED_GITEA_REPOS = new Set([ + 'mark/vibn-frontend', + 'mark/theia-code-os', + 'mark/vibn-agent-runner', + 'mark/vibn-api', + 'mark/master-ai', +]); + +/** Coolify project UUID for the VIBN platform — agents cannot deploy here. */ +export const PROTECTED_COOLIFY_PROJECT = 'f4owwggokksgw0ogo0844os0'; + +/** + * Specific Coolify app UUIDs that must never be deployed by an agent. + * Belt-and-suspenders check in case the project UUID filter is bypassed. + */ +export const PROTECTED_COOLIFY_APPS = new Set([ + 'y4cscsc8s08c8808go0448s0', // vibn-frontend + 'kggs4ogckc0w8ggwkkk88kck', // vibn-postgres + 'o4wwck0g0c04wgoo4g4s0004', // gitea +]); + +export function assertGiteaWritable(repo: string): void { + if (PROTECTED_GITEA_REPOS.has(repo)) { + throw new Error( + `SECURITY: Repo "${repo}" is a protected Vibn platform repo. ` + + `Agents cannot push code or modify issues in this repository.` + ); + } +} + +export function assertCoolifyDeployable(appUuid: string): void { + if (PROTECTED_COOLIFY_APPS.has(appUuid)) { + throw new Error( + `SECURITY: App "${appUuid}" is a protected Vibn platform application. ` + + `Agents cannot trigger deployments for this application.` + ); + } +} diff --git a/src/tools/shell.ts b/src/tools/shell.ts new file mode 100644 index 0000000..974ae2d --- /dev/null +++ b/src/tools/shell.ts @@ -0,0 +1,43 @@ +import * as cp from 'child_process'; +import * as util from 'util'; +import { registerTool } from './registry'; +import { safeResolve } from './utils'; + +const execAsync = util.promisify(cp.exec); + +const BLOCKED_COMMANDS = ['rm -rf /', 'mkfs', ':(){:|:&};:']; + +registerTool({ + name: 'execute_command', + description: 'Run a shell command in the workspace and return stdout + stderr. 120s timeout. Use for: npm install, npm test, git status, building, etc.', + parameters: { + type: 'object', + properties: { + command: { type: 'string', description: 'Shell command to run' }, + working_directory: { type: 'string', description: 'Optional: relative subdirectory to run in' } + }, + required: ['command'] + }, + async handler(args, ctx) { + const command = String(args.command); + if (BLOCKED_COMMANDS.some(b => command.includes(b))) { + return { error: 'Command blocked for safety.' }; + } + const cwd = args.working_directory + ? safeResolve(ctx.workspaceRoot, String(args.working_directory)) + : ctx.workspaceRoot; + try { + const { stdout, stderr } = await execAsync(command, { + cwd, timeout: 120_000, maxBuffer: 1024 * 1024 + }); + return { exitCode: 0, stdout: stdout.trim(), stderr: stderr.trim() }; + } catch (err: any) { + return { + exitCode: err.code, + stdout: (err.stdout || '').trim(), + stderr: (err.stderr || '').trim(), + error: err.message + }; + } + } +}); diff --git a/src/tools/utils.ts b/src/tools/utils.ts new file mode 100644 index 0000000..dc78a71 --- /dev/null +++ b/src/tools/utils.ts @@ -0,0 +1,13 @@ +import * as path from 'path'; + +/** Directory names to skip when walking or listing workspaces. */ +export const EXCLUDED = new Set(['node_modules', '.git', 'dist', 'build', 'lib', '.cache', 'coverage']); + +/** Resolve a relative path safely within a workspace root — throws if it tries to escape. */ +export function safeResolve(root: string, rel: string): string { + const resolved = path.resolve(root, rel); + if (!resolved.startsWith(path.resolve(root))) { + throw new Error(`Path escapes workspace: ${rel}`); + } + return resolved; +}