UNPKG

create-eliza

Version:

Initialize an Eliza project

359 lines (353 loc) 12.2 kB
import { createRequire } from 'module'; const require = createRequire(import.meta.url); import { handleError } from "./chunk-S7QJ5TCR.js"; import { source_default } from "./chunk-BY3DNMXE.js"; import { logger } from "./chunk-UWEMLI2Z.js"; import { Command } from "./chunk-CKY7YPIS.js"; // src/commands/agent.ts import fs from "node:fs"; import path from "node:path"; // src/utils/helpers.ts function formatMessageExamples(examples) { if (!examples || examples.length === 0) return "No message examples"; return examples.map((conversation, i) => { const messages = conversation.map((msg) => { const user = msg.name === "{{name1}}" ? "Anon" : msg.name; return ` ${user}: ${msg.content.text}`; }).join("\n"); return ` Conversation ${i + 1}: ${messages}`; }).join("\n"); } function displayAgent(data, title = "Agent Review") { logHeader(title); logger.info(`Name: ${data.name}`); logger.info( `Username: ${data.username || data.name?.toLowerCase().replace(/\s+/g, "_")}` ); logger.info("\nBio:"); for (const line of Array.isArray(data.bio) ? data.bio : [data.bio]) { logger.info(` ${line}`); } logger.info("\nAdjectives:"); for (const adj of data.adjectives || []) { logger.info(` ${adj}`); } if (data.topics && data.topics.length > 0) { logger.info("\nTopics:"); for (const topic of data.topics) { logger.info(` ${topic}`); } } if (data.plugins && data.plugins.length > 0) { logger.info("\nPlugins:"); for (const plugin of data.plugins) { logger.info(` ${plugin}`); } } if (data.style) { if (data.style.all && data.style.all.length > 0) { logger.info("\nGeneral Style:"); for (const style of data.style.all) { logger.info(` ${style}`); } } if (data.style.chat && data.style.chat.length > 0) { logger.info("\nChat Style:"); for (const style of data.style.chat) { logger.info(` ${style}`); } } if (data.style.post && data.style.post.length > 0) { logger.info("\nPost Style:"); for (const style of data.style.post) { logger.info(` ${style}`); } } } if (data.postExamples && data.postExamples.length > 0) { logger.info("\nPost Examples:"); for (const post of data.postExamples) { logger.info(` ${post}`); } } if (data.messageExamples && data.messageExamples.length > 0) { logger.info("\nMessage Examples:"); logger.info(formatMessageExamples(data.messageExamples)); } } function logHeader(title) { const padding = 2; const titleStr = `=== ${title} ===`; const paddedTitle = " ".repeat(padding) + titleStr + " ".repeat(padding); const borderLength = paddedTitle.length; const topBorder = source_default.green(`\u250C${"\u2500".repeat(borderLength)}\u2510`); const bottomBorder = source_default.green(`\u2514${"\u2500".repeat(borderLength)}\u2518`); const middleRow = source_default.green(`\u2502${paddedTitle}\u2502`); logger.info(` ${topBorder} ${middleRow} ${bottomBorder}`); } // src/commands/agent.ts var AGENT_RUNTIME_URL = process.env.AGENT_RUNTIME_URL?.replace(/\/$/, "") || "http://localhost:3000"; var AGENTS_BASE_URL = `${AGENT_RUNTIME_URL}/agents`; async function getAgents() { const response = await fetch(`${AGENTS_BASE_URL}`); if (!response.ok) { throw new Error(`Failed to fetch agents list: ${response.statusText}`); } return (await response.json()).data?.agents || []; } async function resolveAgentId(idOrNameOrIndex) { const agents = await getAgents(); const agentByName = agents.find( (agent2) => agent2.name.toLowerCase() === idOrNameOrIndex.toLowerCase() ); if (agentByName) { return agentByName.id; } const agentById = agents.find((agent2) => agent2.id === idOrNameOrIndex); if (agentById) { return agentById.id; } if (!Number.isNaN(Number(idOrNameOrIndex))) { return agents[Number(idOrNameOrIndex)].id; } throw new Error(`Agent not found: ${idOrNameOrIndex}`); } var agent = new Command().name("agent").description("manage ElizaOS agents"); agent.command("list").alias("ls").description("list available agents").option("-j, --json", "output as JSON").action(async (opts) => { try { const agents = await getAgents(); const agentData = agents.map((agent2) => ({ Name: agent2.name, ID: agent2.id, Status: agent2.status || "unknown" })); if (opts.json) { logger.info(JSON.stringify(agentData, null, 2)); } else { logger.info("\nAvailable agents:"); if (agentData.length === 0) { logger.info("No agents found"); } else { console.table(agentData); } } process.exit(0); } catch (error) { handleError(error); } }); agent.command("get").alias("g").description("get agent details").requiredOption( "-n, --name <name>", "agent id, name, or index number from list" ).option("-j, --json", "output as JSON").option("-o, --output <file>", "output to file (default: {name}.json)").action(async (opts) => { try { const resolvedAgentId = await resolveAgentId(opts.name); logger.info(`Getting agent ${resolvedAgentId}`); const response = await fetch(`${AGENTS_BASE_URL}/${resolvedAgentId}`); if (!response.ok) { const errorData = await response.json(); throw new Error( errorData.error?.message || `Failed to get agent: ${response.statusText}` ); } const { data: agent2 } = await response.json(); displayAgent(agent2, "Agent Details"); if (opts.json) { const jsonPath = opts.output || path.join(process.cwd(), `${agent2.name || "agent"}.json`); const { id, createdAt, updatedAt, enabled, ...agentConfig } = agent2; fs.writeFileSync(jsonPath, JSON.stringify(agentConfig, null, 2)); logger.success(`Saved agent configuration to ${jsonPath}`); } process.exit(0); } catch (error) { handleError(error); } }); agent.command("start").alias("s").description("start an agent").option("-n, --name <name>", "character name to start the agent with").option("-j, --json <json>", "character JSON string").option("-p, --path <path>", "local path to character JSON file").option("-r, --remote <url>", "remote URL to character JSON file").action(async (opts) => { try { const response = await (async () => { const payload = {}; const headers = { "Content-Type": "application/json" }; const startOption = opts.json ? "json" : opts.remote ? "remote" : opts.path ? "path" : opts.name ? "name" : "none"; switch (startOption) { case "json": try { payload.characterJson = JSON.parse(opts.json); return await fetch(`${AGENTS_BASE_URL}`, { method: "POST", headers, body: JSON.stringify(payload) }); } catch (error) { throw new Error(`Failed to parse JSON string: ${error.message}`); } case "remote": if (!opts.remote.startsWith("http://") && !opts.remote.startsWith("https://")) { throw new Error("Remote URL must start with http:// or https://"); } payload.characterPath = opts.remote; return await fetch(`${AGENTS_BASE_URL}`, { method: "POST", headers, body: JSON.stringify(payload) }); case "path": try { const fileContent = fs.readFileSync(opts.path, "utf8"); payload.characterJson = JSON.parse(fileContent); return await fetch(`${AGENTS_BASE_URL}`, { method: "POST", headers, body: JSON.stringify(payload) }); } catch (error) { throw new Error( `Failed to read or parse local JSON file: ${error.message}` ); } case "name": { const agentId = await resolveAgentId(opts.name); try { return await fetch(`${AGENTS_BASE_URL}/${agentId}`, { method: "POST", headers, body: JSON.stringify(payload) }); } catch (error) { throw new Error( `Failed to start agent by name: ${error.message}` ); } } default: throw new Error( "Please provide either a character name, path to JSON file, remote URL, or character JSON string" ); } })(); if (!response.ok) { const errorData = await response.json(); throw new Error( errorData.error?.message || `Failed to start agent: ${response.statusText}` ); } const data = await response.json(); const result = data.data; if (!result) { throw new Error("Failed to start agent: No data returned from server"); } logger.success( `Successfully started agent ${result.character.name} (${result.id})` ); } catch (error) { handleError(error); } }); agent.command("stop").alias("st").description("stop an agent").requiredOption( "-n, --name <name>", "agent id, name, or index number from list" ).action(async (opts) => { try { const resolvedAgentId = await resolveAgentId(opts.name); logger.info(`Stopping agent ${resolvedAgentId}`); const response = await fetch(`${AGENTS_BASE_URL}/${resolvedAgentId}`, { method: "PUT" }); if (!response.ok) { const errorData = await response.json(); throw new Error( errorData.error?.message || `Failed to stop agent: ${response.statusText}` ); } logger.success(`Successfully stopped agent ${opts.name}`); } catch (error) { handleError(error); } }); agent.command("remove").alias("rm").description("remove an agent").requiredOption( "-n, --name <name>", "agent id, name, or index number from list" ).action(async (opts) => { try { const resolvedAgentId = await resolveAgentId(opts.name); logger.info(`Removing agent ${resolvedAgentId}`); const response = await fetch(`${AGENTS_BASE_URL}/${resolvedAgentId}`, { method: "DELETE" }); if (!response.ok) { const errorData = await response.json(); throw new Error( errorData.error?.message || `Failed to remove agent: ${response.statusText}` ); } logger.success(`Successfully removed agent ${opts.name}`); } catch (error) { handleError(error); } }); agent.command("set").description("update agent configuration").requiredOption( "-n, --name <name>", "agent id, name, or index number from list" ).option("-c, --config <json>", "configuration as JSON string").option("-f, --file <path>", "path to configuration JSON file").action(async (opts) => { try { const resolvedAgentId = await resolveAgentId(opts.name); logger.info(`Updating configuration for agent ${resolvedAgentId}`); let config; if (opts.config) { try { config = JSON.parse(opts.config); } catch (error) { throw new Error( `Failed to parse config JSON string: ${error.message}` ); } } else if (opts.file) { try { config = JSON.parse(fs.readFileSync(opts.file, "utf8")); } catch (error) { throw new Error( `Failed to read or parse config file: ${error.message}` ); } } else { throw new Error( "Please provide either a config JSON string (-c) or a config file path (-f)" ); } const response = await fetch(`${AGENTS_BASE_URL}/${resolvedAgentId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ updates: config }) }); if (!response.ok) { const errorData = await response.json(); throw new Error( errorData.error?.message || `Failed to update agent configuration: ${response.statusText}` ); } const data = await response.json(); const result = data.data; logger.success( `Successfully updated configuration for agent ${result?.id || resolvedAgentId}` ); } catch (error) { handleError(error); } }); export { agent }; //# sourceMappingURL=chunk-W2EX7M24.js.map