diff --git a/packages/cli/src/commands/agent/index.ts b/packages/cli/src/commands/agent/index.ts index 6f08a4e08..ef9a9f486 100644 --- a/packages/cli/src/commands/agent/index.ts +++ b/packages/cli/src/commands/agent/index.ts @@ -4,6 +4,7 @@ import { runRunCommand } from './run.js' import { runSendCommand } from './send.js' import { runStopCommand } from './stop.js' import { runModeCommand } from './mode.js' +import { runInspectCommand } from './inspect.js' import { withOutput } from '../../output/index.js' export function createAgentCommand(): Command { @@ -57,5 +58,12 @@ export function createAgentCommand(): Command { .option('--host ', 'Daemon host:port (default: localhost:6767)') .action(withOutput(runModeCommand)) + agent + .command('inspect') + .description('Show detailed information about an agent') + .argument('', 'Agent ID (or prefix)') + .option('--host ', 'Daemon host:port (default: localhost:6767)') + .action(withOutput(runInspectCommand)) + return agent } diff --git a/packages/cli/src/commands/agent/inspect.ts b/packages/cli/src/commands/agent/inspect.ts new file mode 100644 index 000000000..ba8785d36 --- /dev/null +++ b/packages/cli/src/commands/agent/inspect.ts @@ -0,0 +1,313 @@ +import type { Command } from 'commander' +import { connectToDaemon, getDaemonHost, resolveAgentId } from '../../utils/client.js' +import type { CommandOptions, ListResult, OutputSchema, CommandError } from '../../output/index.js' + +/** Agent snapshot type (loose to allow any shape from daemon client) */ +interface AgentSnapshotLike { + id: string + provider: string + cwd: string + createdAt: string + status: string + title: string | null + archivedAt?: string | null + currentModeId?: string | null + model?: string | null + lastUsage?: { + inputTokens?: number + outputTokens?: number + cachedInputTokens?: number + totalCostUsd?: number + } + capabilities?: { + supportsStreaming?: boolean + supportsSessionPersistence?: boolean + supportsDynamicModes?: boolean + supportsMcpServers?: boolean + } + availableModes?: Array<{ + id: string + label: string + description?: string + }> + pendingPermissions?: Array<{ + id: string + tool?: string + }> + parentAgentId?: string | null +} + +/** Agent inspect data for display */ +interface AgentInspect { + id: string + name: string + provider: string + model: string + status: string + mode: string + cwd: string + createdAt: string + archivedAt: string | null + lastUsage: { + inputTokens: number + outputTokens: number + cachedInputTokens: number + totalCostUsd: number + } | null + capabilities: { + streaming: boolean + persistence: boolean + dynamicModes: boolean + mcpServers: boolean + } | null + availableModes: Array<{ + id: string + label: string + }> | null + pendingPermissions: Array<{ + id: string + tool: string + }> + parentAgentId: string | null +} + +/** Key-value row for table display */ +interface InspectRow { + key: string + value: string +} + +/** Schema for key-value display with custom serialization for JSON/YAML */ +function createInspectSchema(agent: AgentInspect): OutputSchema { + return { + idField: 'key', + columns: [ + { header: 'KEY', field: 'key' }, + { + header: 'VALUE', + field: 'value', + color: (_, item) => { + if (item.key === 'Status') { + if (item.value === 'running') return 'green' + if (item.value === 'idle') return 'yellow' + if (item.value === 'error') return 'red' + } + return undefined + }, + }, + ], + // For JSON/YAML, return the structured agent object + serialize: (_item) => agent, + } +} + +/** Shorten home directory in path */ +function shortenPath(path: string): string { + const home = process.env.HOME + if (home && path.startsWith(home)) { + return '~' + path.slice(home.length) + } + return path +} + +/** Format cost in USD */ +function formatCost(costUsd: number): string { + if (costUsd === 0) return '$0.00' + if (costUsd < 0.01) return `$${costUsd.toFixed(4)}` + return `$${costUsd.toFixed(2)}` +} + +/** Convert agent snapshot to inspection data */ +function toInspectData(snapshot: AgentSnapshotLike): AgentInspect { + const lastUsage = snapshot.lastUsage + ? { + inputTokens: snapshot.lastUsage.inputTokens ?? 0, + outputTokens: snapshot.lastUsage.outputTokens ?? 0, + cachedInputTokens: snapshot.lastUsage.cachedInputTokens ?? 0, + totalCostUsd: snapshot.lastUsage.totalCostUsd ?? 0, + } + : null + + const capabilities = snapshot.capabilities + ? { + streaming: snapshot.capabilities.supportsStreaming ?? false, + persistence: snapshot.capabilities.supportsSessionPersistence ?? false, + dynamicModes: snapshot.capabilities.supportsDynamicModes ?? false, + mcpServers: snapshot.capabilities.supportsMcpServers ?? false, + } + : null + + return { + id: snapshot.id, + name: snapshot.title ?? '-', + provider: snapshot.provider, + model: snapshot.model ?? '-', + status: snapshot.status, + mode: snapshot.currentModeId ?? 'default', + cwd: snapshot.cwd, + createdAt: snapshot.createdAt, + archivedAt: snapshot.archivedAt ?? null, + lastUsage, + capabilities, + availableModes: snapshot.availableModes + ? snapshot.availableModes.map((m) => ({ id: m.id, label: m.label })) + : null, + pendingPermissions: (snapshot.pendingPermissions ?? []).map((p) => ({ + id: p.id, + tool: p.tool ?? 'unknown', + })), + parentAgentId: snapshot.parentAgentId ?? null, + } +} + +/** Convert agent to key-value rows for table display */ +function toInspectRows(agent: AgentInspect): InspectRow[] { + const rows: InspectRow[] = [ + { key: 'Id', value: agent.id }, + { key: 'Name', value: agent.name }, + { key: 'Provider', value: agent.provider }, + { key: 'Model', value: agent.model }, + { key: 'Status', value: agent.status }, + { key: 'Mode', value: agent.mode }, + { key: 'Cwd', value: shortenPath(agent.cwd) }, + { key: 'CreatedAt', value: agent.createdAt }, + ] + + if (agent.archivedAt) { + rows.push({ key: 'ArchivedAt', value: agent.archivedAt }) + } + + if (agent.lastUsage) { + rows.push({ + key: 'LastUsage', + value: `${agent.lastUsage.inputTokens} in, ${agent.lastUsage.outputTokens} out, ${formatCost(agent.lastUsage.totalCostUsd)}`, + }) + } + + if (agent.capabilities) { + const caps = agent.capabilities + const capsList = [ + caps.streaming ? 'Streaming' : null, + caps.persistence ? 'Persistence' : null, + caps.dynamicModes ? 'DynamicModes' : null, + caps.mcpServers ? 'McpServers' : null, + ].filter(Boolean) + rows.push({ key: 'Capabilities', value: capsList.join(', ') || 'none' }) + } + + if (agent.availableModes && agent.availableModes.length > 0) { + rows.push({ + key: 'AvailableModes', + value: agent.availableModes.map((m) => m.id).join(', '), + }) + } + + if (agent.pendingPermissions.length > 0) { + rows.push({ + key: 'PendingPermissions', + value: agent.pendingPermissions.length.toString(), + }) + } else { + rows.push({ key: 'PendingPermissions', value: '[]' }) + } + + rows.push({ + key: 'ParentAgentId', + value: agent.parentAgentId ?? 'null', + }) + + return rows +} + +export type AgentInspectResult = ListResult + +export interface AgentInspectOptions extends CommandOptions { + host?: string +} + +export async function runInspectCommand( + agentIdArg: string, + options: AgentInspectOptions, + _command: Command +): Promise { + const host = getDaemonHost({ host: options.host as string | undefined }) + + // Validate arguments + if (!agentIdArg || agentIdArg.trim().length === 0) { + const error: CommandError = { + code: 'MISSING_AGENT_ID', + message: 'Agent ID is required', + details: 'Usage: paseo agent inspect ', + } + throw error + } + + let client + try { + client = await connectToDaemon({ host: options.host as string | undefined }) + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + const error: CommandError = { + code: 'DAEMON_NOT_RUNNING', + message: `Cannot connect to daemon at ${host}: ${message}`, + details: 'Start the daemon with: paseo daemon start', + } + throw error + } + + try { + // Request session state to get agent information + client.requestSessionState() + + // Wait a moment for the session state to be populated + await new Promise((resolve) => setTimeout(resolve, 500)) + + const agents = client.listAgents() + + // Resolve agent ID (supports prefix matching) + const agentId = resolveAgentId(agentIdArg, agents) + if (!agentId) { + const error: CommandError = { + code: 'AGENT_NOT_FOUND', + message: `Agent not found: ${agentIdArg}`, + details: 'Use "paseo agent ps" to list available agents', + } + throw error + } + + // Get the full agent snapshot + const snapshot = agents.find((a) => a.id === agentId) + if (!snapshot) { + const error: CommandError = { + code: 'AGENT_NOT_FOUND', + message: `Agent not found: ${agentIdArg}`, + details: 'Use "paseo agent ps" to list available agents', + } + throw error + } + + await client.close() + + const inspectData = toInspectData(snapshot) + + return { + type: 'list', + data: toInspectRows(inspectData), + schema: createInspectSchema(inspectData), + } + } catch (err) { + await client.close().catch(() => {}) + + // Re-throw CommandError as-is + if (err && typeof err === 'object' && 'code' in err) { + throw err + } + + const message = err instanceof Error ? err.message : String(err) + const error: CommandError = { + code: 'INSPECT_FAILED', + message: `Failed to inspect agent: ${message}`, + } + throw error + } +} diff --git a/packages/cli/tests/09-agent-inspect.test.ts b/packages/cli/tests/09-agent-inspect.test.ts new file mode 100644 index 000000000..3c7c58830 --- /dev/null +++ b/packages/cli/tests/09-agent-inspect.test.ts @@ -0,0 +1,161 @@ +#!/usr/bin/env npx tsx + +/** + * Phase 9: Agent Inspect Command Tests + * + * Tests the agent inspect command - showing detailed agent information. + * Since daemon may not be running, we test both: + * - Help and argument parsing + * - Graceful error handling when daemon not running + * - All flags are accepted + * + * Tests: + * - agent inspect --help shows options + * - agent inspect requires id argument + * - agent inspect handles daemon not running + * - agent inspect --host flag is accepted + * - agent shows inspect in subcommands + */ + +import assert from 'node:assert' +import { $ } from 'zx' +import { mkdtemp, rm } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' + +$.verbose = false + +console.log('=== Agent Inspect Command Tests ===\n') + +// Get random port that's definitely not in use (never 6767) +const port = 10000 + Math.floor(Math.random() * 50000) +const paseoHome = await mkdtemp(join(tmpdir(), 'paseo-test-home-')) + +try { + // Test 1: agent inspect --help shows options + { + console.log('Test 1: agent inspect --help shows options') + const result = await $`npx paseo agent inspect --help`.nothrow() + assert.strictEqual(result.exitCode, 0, 'agent inspect --help should exit 0') + assert(result.stdout.includes('--host'), 'help should mention --host option') + assert(result.stdout.includes(''), 'help should mention id argument') + console.log(' help should mention --host option') + console.log(' help should mention argument') + console.log('inspect --help shows options\n') + } + + // Test 2: agent inspect requires id argument + { + console.log('Test 2: agent inspect requires id argument') + const result = + await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npx paseo agent inspect`.nothrow() + assert.notStrictEqual(result.exitCode, 0, 'should fail without id') + const output = result.stdout + result.stderr + // Commander should complain about missing argument + const hasMissingArg = + output.toLowerCase().includes('missing') || + output.toLowerCase().includes('required') || + output.toLowerCase().includes('argument') + assert(hasMissingArg, 'error should mention missing argument') + console.log('agent inspect requires id argument\n') + } + + // Test 3: agent inspect handles daemon not running + { + console.log('Test 3: agent inspect handles daemon not running') + const result = + await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npx paseo agent inspect abc123`.nothrow() + // Should fail because daemon not running + assert.notStrictEqual(result.exitCode, 0, 'should fail when daemon not running') + const output = result.stdout + result.stderr + const hasError = + output.toLowerCase().includes('daemon') || + output.toLowerCase().includes('connect') || + output.toLowerCase().includes('cannot') + assert(hasError, 'error message should mention connection issue') + console.log('agent inspect handles daemon not running\n') + } + + // Test 4: agent inspect --host flag is accepted + { + console.log('Test 4: agent inspect --host flag is accepted') + const result = + await $`PASEO_HOME=${paseoHome} npx paseo agent inspect --host localhost:${port} abc123`.nothrow() + const output = result.stdout + result.stderr + assert(!output.includes('unknown option'), 'should accept --host flag') + assert(!output.includes('error: option'), 'should not have option parsing error') + console.log('agent inspect --host flag is accepted\n') + } + + // Test 5: -q (quiet) flag is accepted with agent inspect + { + console.log('Test 5: -q (quiet) flag is accepted with agent inspect') + const result = + await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npx paseo -q agent inspect abc123`.nothrow() + const output = result.stdout + result.stderr + assert(!output.includes('unknown option'), 'should accept -q flag') + assert(!output.includes('error: option'), 'should not have option parsing error') + console.log('-q (quiet) flag is accepted with agent inspect\n') + } + + // Test 6: --format json flag is accepted with agent inspect + { + console.log('Test 6: --format json flag is accepted with agent inspect') + const result = + await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npx paseo --format json agent inspect abc123`.nothrow() + const output = result.stdout + result.stderr + assert(!output.includes('unknown option'), 'should accept --format json flag') + assert(!output.includes('error: option'), 'should not have option parsing error') + console.log('--format json flag is accepted with agent inspect\n') + } + + // Test 7: --format yaml flag is accepted with agent inspect + { + console.log('Test 7: --format yaml flag is accepted with agent inspect') + const result = + await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npx paseo --format yaml agent inspect abc123`.nothrow() + const output = result.stdout + result.stderr + assert(!output.includes('unknown option'), 'should accept --format yaml flag') + assert(!output.includes('error: option'), 'should not have option parsing error') + console.log('--format yaml flag is accepted with agent inspect\n') + } + + // Test 8: agent --help shows inspect subcommand + { + console.log('Test 8: agent --help shows inspect subcommand') + const result = await $`npx paseo agent --help`.nothrow() + assert.strictEqual(result.exitCode, 0, 'agent --help should exit 0') + assert(result.stdout.includes('inspect'), 'help should mention inspect subcommand') + console.log('agent --help shows inspect subcommand\n') + } + + // Test 9: inspect command description is helpful + { + console.log('Test 9: inspect command description is helpful') + const result = await $`npx paseo agent inspect --help`.nothrow() + assert.strictEqual(result.exitCode, 0, 'agent inspect --help should exit 0') + const hasDescription = + result.stdout.toLowerCase().includes('detail') || + result.stdout.toLowerCase().includes('information') || + result.stdout.toLowerCase().includes('show') + assert(hasDescription, 'help should describe what inspect does') + console.log('inspect command description is helpful\n') + } + + // Test 10: ID prefix syntax is mentioned in help + { + console.log('Test 10: inspect command mentions ID') + const result = await $`npx paseo agent inspect --help`.nothrow() + assert.strictEqual(result.exitCode, 0, 'agent inspect --help should exit 0') + const hasIdMention = + result.stdout.toLowerCase().includes('id') || + result.stdout.toLowerCase().includes('prefix') + assert(hasIdMention, 'help should mention ID or prefix') + console.log('inspect command mentions ID\n') + } +} finally { + // Clean up temp directory + await rm(paseoHome, { recursive: true, force: true }) +} + +console.log('=== All agent inspect tests passed ===')