UNPKG

@pompeii-labs/cli

Version:

Magma CLI

70 lines (69 loc) 2.5 kB
import chalk from "chalk"; import { isAuthenticated } from "../auth.js"; import { authenticatedFetch, endpoint } from "../api.js"; import fs from "fs"; async function streamLogs(options) { console.clear(); let agentId = options.agentId; if (!agentId) { if (!fs.existsSync(".magma/.cache")) { throw new Error("No agent cache found. Have you deployed your agent yet?"); } const config = JSON.parse(fs.readFileSync(".magma/.cache", "utf8")); agentId = config.id; console.log(chalk.dim(`Using agent in current directory: ${chalk.bold(agentId)} `)); } const url = new URL(endpoint(`/agents/${agentId}/logs`)); if (options.tail) url.searchParams.set("tail", options.tail); if (options.follow) url.searchParams.set("follow", "true"); const response = await authenticatedFetch(url.toString()); if (options.follow) { const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; try { while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split("\n\n"); buffer = lines.pop() || ""; for (const line of lines) { if (line.trim() === "data: HEARTBEAT") continue; if (line.startsWith("data: ")) { const logEntry = JSON.parse(line.slice(6)); const formattedTime = new Date(logEntry.timestamp).toLocaleString(); console.log(chalk.dim(formattedTime), logEntry.message); } } } } catch (error) { reader.cancel(); throw error; } } else { const logs = await response.json(); logs.forEach((log) => { const formattedTime = new Date(log.timestamp).toLocaleString(); console.log(chalk.dim(formattedTime), log.message); }); } } function logsCommand(program) { program.command("logs").description("View agent logs").option("-a, --agent <id>", "Agent ID or name").option("-t, --tail <n>", "Number of lines to show", "100").option("-f, --follow", "Follow log output", false).action(async (options) => { if (!isAuthenticated()) { console.log(chalk.red("Not authenticated with Magma. Please run `magma login`.")); process.exit(1); } try { await streamLogs(options); } catch (error) { console.error(chalk.red("\n\u2716 Failed to get logs:"), error.message); process.exit(1); } }); } export { logsCommand };