@nestbox-ai/cli
Version:
The cli tools that helps developers to build agents
172 lines • 9.35 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerCreateFromYamlCommand = registerCreateFromYamlCommand;
const error_1 = require("../../utils/error");
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const cli_table3_1 = __importDefault(require("cli-table3"));
const fs_1 = __importDefault(require("fs"));
const js_yaml_1 = __importDefault(require("js-yaml"));
const user_1 = require("../../utils/user");
const create_1 = require("./create");
const apiUtils_1 = require("./apiUtils");
function registerCreateFromYamlCommand(agentCommand) {
agentCommand
.command("create [firstArg] [secondArg]")
.description("Create multiple agents from a YAML configuration file")
.option("--project <projectId>", "Project ID (defaults to the current project)")
.action((firstArg, secondArg, options) => __awaiter(this, void 0, void 0, function* () {
try {
let apis = (0, apiUtils_1.createApis)();
// Determine which argument is the YAML file path
let yamlFilePath;
if (firstArg === 'file' && secondArg) {
yamlFilePath = secondArg;
}
else if (firstArg) {
yamlFilePath = firstArg;
if (typeof secondArg === 'object' && !options) {
options = secondArg;
}
}
else {
console.error(chalk_1.default.red("Missing YAML file path. Usage: nestbox agent create <yamlFile> OR nestbox agent create file <yamlFile>"));
return;
}
// Check if file exists
if (!fs_1.default.existsSync(yamlFilePath)) {
console.error(chalk_1.default.red(`YAML file not found: ${yamlFilePath}`));
return;
}
// Read and parse the YAML file
const spinner = (0, ora_1.default)(`Reading agents configuration from ${yamlFilePath}...`).start();
try {
const fileContents = fs_1.default.readFileSync(yamlFilePath, 'utf8');
const config = js_yaml_1.default.load(fileContents);
if (!config || !config.agents || !Array.isArray(config.agents)) {
spinner.fail("Invalid YAML configuration: Missing 'agents' array");
console.error(chalk_1.default.red("The YAML file should contain an 'agents' array with agent configurations"));
return;
}
spinner.succeed(`Found ${config.agents.length} agents in configuration file`);
// Process each agent with token refresh support
const results = {
success: 0,
failed: 0,
agents: []
};
// Get user data once
const user = yield (0, user_1.userData)();
for (const agent of config.agents) {
if (!agent.name) {
console.log(chalk_1.default.yellow("Skipping agent with no name defined"));
results.failed++;
results.agents.push({
name: "unnamed",
success: false,
message: "Name is required"
});
continue;
}
let agentType = agent.type || "CHAT";
const resourceType = agentType === "AGENT" ? "Agent" : "Chatbot";
const agentSpinner = (0, ora_1.default)(`Creating ${resourceType.toLowerCase()} '${agent.name}'...`).start();
try {
// Create agent with token refresh support
yield (0, error_1.withTokenRefresh)(() => __awaiter(this, void 0, void 0, function* () {
// Map YAML config to createAgent options
const createOptions = Object.assign(Object.assign({}, options), { goal: agent.goal || "No goal specified", modelBaseId: agent.modelBaseId || "", instanceIP: agent.instanceIP || "localhost", machineInstanceId: agent.machineInstanceId || 1, machineManifestId: agent.machineManifestId || "default", machineName: agent.machineName || `agent-${agent.name.toLowerCase()}`, type: agentType, userId: user.id, parameters: agent.parameters ? agent.parameters.map((p) => {
return {
name: p.name || "unnamed",
description: p.description || "",
default: p.default || "",
isUserParam: p.isUserParam !== undefined ? p.isUserParam : true
};
}) : [] });
yield (0, create_1.createAgent)(agent.name, createOptions, apis.agentsApi, apis.projectsApi);
}), () => {
apis = (0, apiUtils_1.createApis)();
});
agentSpinner.stop();
results.success++;
results.agents.push({
name: agent.name,
success: true,
message: `Created successfully`
});
}
catch (error) {
agentSpinner.fail(`Failed to create ${resourceType.toLowerCase()} '${agent.name}'`);
console.error(chalk_1.default.red(`Error: ${error.message}`));
results.failed++;
results.agents.push({
name: agent.name,
success: false,
message: error.message
});
}
}
// Final summary
console.log(chalk_1.default.blue("\nResource creation summary:"));
const table = new cli_table3_1.default({
head: [
chalk_1.default.white.bold("Name"),
chalk_1.default.white.bold("Type"),
chalk_1.default.white.bold("Status"),
chalk_1.default.white.bold("Message"),
],
style: {
head: [],
border: [],
},
});
results.agents.forEach((agent, index) => {
const agentConfig = config.agents.find(a => a.name === agent.name) || config.agents[index];
const agentType = (agentConfig === null || agentConfig === void 0 ? void 0 : agentConfig.type) || "CHAT";
const resourceType = agentType === "AGENT" ? "Agent" : "Chatbot";
table.push([
agent.name,
resourceType,
agent.success ? chalk_1.default.green("Success") : chalk_1.default.red("Failed"),
agent.message
]);
});
console.log(table.toString());
console.log(`\nTotal: ${results.success + results.failed}, Successful: ${results.success}, Failed: ${results.failed}`);
}
catch (error) {
spinner.fail("Failed to process YAML file");
if (error.code === 'ENOENT') {
console.error(chalk_1.default.red(`File not found: ${yamlFilePath}`));
}
else if (error.name === 'YAMLException') {
console.error(chalk_1.default.red(`Invalid YAML format: ${error.message}`));
}
else {
console.error(chalk_1.default.red("Error:"), error.message || "Unknown error");
}
}
}
catch (error) {
if (error.message && error.message.includes('Authentication')) {
console.error(chalk_1.default.red(error.message));
}
else {
console.error(chalk_1.default.red("Error:"), error instanceof Error ? error.message : "Unknown error");
}
}
}));
}
//# sourceMappingURL=createFromYaml.js.map