UNPKG

local-agent

Version:

A CLI agentic system for orchestrating tools and memory with per-folder scoping

202 lines 8.53 kB
"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.RESET = exports.YELLOW = exports.RED = exports.GREEN = void 0; exports.getMissingProjectFiles = getMissingProjectFiles; exports.initializeProjectFiles = initializeProjectFiles; exports.validateAndLoadFiles = validateAndLoadFiles; exports.loadAllMcpTools = loadAllMcpTools; /** * @fileoverview * Initialization utilities for the local agent project. * Handles validation and creation of required configuration files, memory directory, * and loading of Model Context Protocol (MCP) tools for agent operation. * All log messages use the prefix [local-agent] for consistency and clarity. */ const fs_1 = require("fs"); const default_configs_1 = require("./default-configs"); const types_1 = require("./types"); const mcp_1 = require("@agentic/mcp"); /** * Checks for missing required files and the memory directory in the project. * * @param {string[]} REQUIRED_FILES - List of required file names to check for existence. * @param {string} MEMORY_DIR - Name of the memory directory to check. * @returns {string[]} Array of missing items (file names and/or the memory directory). */ function getMissingProjectFiles(REQUIRED_FILES, MEMORY_DIR) { const missing = []; for (const file of REQUIRED_FILES) { if (!(0, fs_1.existsSync)(file)) { missing.push(file); } } if (!(0, fs_1.existsSync)(MEMORY_DIR)) { missing.push(MEMORY_DIR + "/"); } return missing; } /** * Creates any missing required files and the memory directory for the project. * Populates files with default content where appropriate. * * @param {string[]} REQUIRED_FILES - List of required file names to create if missing. * @param {string} MEMORY_DIR - Name of the memory directory to create if missing. */ function initializeProjectFiles(REQUIRED_FILES, MEMORY_DIR) { for (const file of REQUIRED_FILES) { if (!(0, fs_1.existsSync)(file)) { let content = ""; if (file === "system.md") content = ""; else if (file === "mcp-tools.json") content = JSON.stringify(default_configs_1.DEFAULT_TOOLS, null, 2); else if (file === "local-agent.json") content = JSON.stringify(default_configs_1.DEFAULT_CONFIG, null, 2); else if (file === "keys.json") content = JSON.stringify(default_configs_1.DEFAULT_KEYS, null, 2); else if (file.endsWith(".json")) content = "{}"; (0, fs_1.writeFileSync)(file, content, "utf8"); console.log(`[local-agent] Created missing file: ${file}`); } } if (!(0, fs_1.existsSync)(MEMORY_DIR)) { (0, fs_1.mkdirSync)(MEMORY_DIR); console.log(`[local-agent] Created missing folder: ${MEMORY_DIR}/`); } } const readline = __importStar(require("readline")); /** * Checks for missing files/dirs, prompts user to initialize if needed, and loads config/tools/keys. * Exits if user declines initialization or after initializing. */ /** * Validates the presence of all required files and the memory directory. * If any are missing, prompts the user to initialize the project and exits if declined. * Loads and parses the agent configuration, MCP tools, and API keys from their respective files. * * @param {string[]} REQUIRED_FILES - List of required file names. * @param {string} MEMORY_DIR - Name of the memory directory. * @returns {Promise<{ config: any, tools: any, keys: any }>} Parsed configuration, tools, and keys. */ async function validateAndLoadFiles(REQUIRED_FILES, MEMORY_DIR) { const missing = getMissingProjectFiles(REQUIRED_FILES, MEMORY_DIR); if (missing.length > 0) { console.log(`${exports.YELLOW}[local-agent] The following required files or directories are missing:${exports.RESET}`); for (const item of missing) { console.log(` - ${item}`); } // Wrap readline in a Promise to ensure async/await flow await new Promise((resolve) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("[local-agent] Would you like to initialize the project now? (y/n): ", (answer) => { rl.close(); if (answer.trim().toLowerCase().startsWith("y")) { initializeProjectFiles(REQUIRED_FILES, MEMORY_DIR); console.log(`${exports.GREEN}[local-agent] Project initialized. Please review the created files.${exports.RESET}`); process.exit(0); } else { console.log(`${exports.RED}[local-agent] Project not initialized. Exiting.${exports.RESET}`); process.exit(1); } resolve(); }); }); // This line is never reached, but is required for type safety return undefined; } let config; let tools; let keys; try { config = types_1.GenerateTextParamsSchema.parse(JSON.parse((0, fs_1.readFileSync)("local-agent.json", "utf8"))); } catch (err) { console.error("[local-agent] Invalid local-agent.json:", err); process.exit(1); } try { const toolsData = JSON.parse((0, fs_1.readFileSync)("mcp-tools.json", "utf8")); tools = types_1.ToolsJsonSchema.parse(toolsData); } catch (err) { console.error("[local-agent] Invalid mcp-tools.json:", err); process.exit(1); } try { keys = types_1.KeysJsonSchema.parse(JSON.parse((0, fs_1.readFileSync)("keys.json", "utf8"))); } catch (err) { console.error("[local-agent] Invalid keys.json:", err); process.exit(1); } return { config, tools, keys }; } exports.GREEN = "\x1b[32m"; exports.RED = "\x1b[31m"; exports.YELLOW = "\x1b[33m"; exports.RESET = "\x1b[0m"; /** * Loads all Model Context Protocol (MCP) tools defined in the tools configuration. * Returns an object containing the loaded tools and a status array for each tool. * * @param {any} toolsConfig - The parsed tools configuration object (from mcp-tools.json). * @returns {Promise<{ loadedTools: Record<string, any>, toolStatus: Array<{name: string, status: "success"|"fail", error?: string}> }>} * An object with loaded MCP tools and their load status. */ async function loadAllMcpTools(toolsConfig) { const loadedTools = {}; const toolStatus = []; for (const [name, serverProcess] of Object.entries(toolsConfig.mcpServers || {})) { try { const tool = await (0, mcp_1.createMcpTools)({ name: `agentic-mcp-${name}`, serverProcess: serverProcess }); loadedTools[name] = tool; toolStatus.push({ name, status: "success" }); } catch (err) { toolStatus.push({ name, status: "fail", error: err instanceof Error ? err.message : String(err) }); } } return { loadedTools, toolStatus }; } //# sourceMappingURL=initialization.js.map