feat: add agent delete command and bulk tab close operations

This commit is contained in:
Mohamed Boudra
2026-03-07 12:32:49 +07:00
parent 6b51088f39
commit 1d1c7058f1
21 changed files with 783 additions and 86 deletions
+12 -1
View File
@@ -13,6 +13,7 @@ import { runDaemonUpdateCommandOrExit } from './commands/daemon/update.js'
import { runLsCommand } from './commands/agent/ls.js'
import { runRunCommand } from './commands/agent/run.js'
import { runLogsCommand } from './commands/agent/logs.js'
import { runDeleteCommand } from './commands/agent/delete.js'
import { runStopCommand } from './commands/agent/stop.js'
import { runSendCommand } from './commands/agent/send.js'
import { runInspectCommand } from './commands/agent/inspect.js'
@@ -108,7 +109,7 @@ export function createCli(): Command {
program
.command('stop')
.description('Stop an agent (cancel if running, then terminate)')
.description('Interrupt an agent if it is running (no-op for idle agents)')
.argument('[id]', 'Agent ID (or prefix) - optional if --all or --cwd specified')
.option('--all', 'Stop all agents')
.option('--cwd <path>', 'Stop all agents in directory')
@@ -116,6 +117,16 @@ export function createCli(): Command {
.option('--host <host>', 'Daemon host:port (default: localhost:6767)')
.action(withOutput(runStopCommand))
program
.command('delete')
.description('Delete an agent (interrupt if running, then hard-delete)')
.argument('[id]', 'Agent ID (or prefix) - optional if --all or --cwd specified')
.option('--all', 'Delete all agents')
.option('--cwd <path>', 'Delete all agents in directory')
.option('--json', 'Output in JSON format')
.option('--host <host>', 'Daemon host:port (default: localhost:6767)')
.action(withOutput(runDeleteCommand))
program
.command('send')
.description('Send a message/task to an existing agent')
+1 -1
View File
@@ -85,7 +85,7 @@ export async function runArchiveCommand(
code: 'AGENT_RUNNING',
message: `Agent ${agentId.slice(0, 7)} is currently running`,
details:
'Use --force to archive a running agent (it will interrupt the active run), or stop it first with: paseo agent stop',
'Use --force to archive a running agent (it will interrupt the active run), or stop it first with: paseo agent stop. Use paseo agent delete to hard-delete it.',
}
throw error
}
+114
View File
@@ -0,0 +1,114 @@
import type { Command } from 'commander'
import { connectToDaemon, getDaemonHost } from '../../utils/client.js'
import type { CommandOptions, SingleResult, OutputSchema, CommandError } from '../../output/index.js'
export interface DeleteResult {
deletedCount: number
agentIds: string[]
}
export const deleteSchema: OutputSchema<DeleteResult> = {
idField: (item) => item.agentIds.join('\n'),
columns: [{ header: 'DELETED', field: 'deletedCount' }],
}
export interface AgentDeleteOptions extends CommandOptions {
all?: boolean
cwd?: string
}
export type AgentDeleteResult = SingleResult<DeleteResult>
export async function runDeleteCommand(
id: string | undefined,
options: AgentDeleteOptions,
_command: Command
): Promise<AgentDeleteResult> {
const host = getDaemonHost({ host: options.host as string | undefined })
if (!id && !options.all && !options.cwd) {
const error: CommandError = {
code: 'MISSING_ARGUMENT',
message: 'Agent ID required unless --all or --cwd is specified',
details: 'Usage: paseo agent delete <id> | --all | --cwd <path>',
}
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 {
const fetchPayload = await client.fetchAgents({ filter: { includeArchived: true } })
let agents = fetchPayload.entries.map((entry) => entry.agent)
const deletedIds: string[] = []
if (options.all) {
agents = agents.filter((a) => !a.archivedAt)
} else if (options.cwd) {
const filterCwd = options.cwd
agents = agents.filter((a) => {
if (a.archivedAt) return false
const agentCwd = a.cwd.replace(/\/$/, '')
const targetCwd = filterCwd.replace(/\/$/, '')
return agentCwd === targetCwd || agentCwd.startsWith(targetCwd + '/')
})
} else if (id) {
const fetchResult = await client.fetchAgent(id)
if (!fetchResult) {
const error: CommandError = {
code: 'AGENT_NOT_FOUND',
message: `No agent found matching: ${id}`,
details: 'Use `paseo ls` to list available agents',
}
throw error
}
agents = [fetchResult.agent]
}
for (const agent of agents) {
try {
if (agent.status === 'running') {
await client.cancelAgent(agent.id)
}
await client.deleteAgent(agent.id)
deletedIds.push(agent.id)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
console.error(`Warning: Failed to delete agent ${agent.id.slice(0, 7)}: ${message}`)
}
}
await client.close()
return {
type: 'single',
data: {
deletedCount: deletedIds.length,
agentIds: deletedIds,
},
schema: deleteSchema,
}
} catch (err) {
await client.close().catch(() => {})
if (err && typeof err === 'object' && 'code' in err) {
throw err
}
const message = err instanceof Error ? err.message : String(err)
const error: CommandError = {
code: 'DELETE_AGENT_FAILED',
message: `Failed to delete agent(s): ${message}`,
}
throw error
}
}
+12 -1
View File
@@ -1,6 +1,7 @@
import { Command } from 'commander'
import { runModeCommand } from './mode.js'
import { runArchiveCommand } from './archive.js'
import { runDeleteCommand } from './delete.js'
import { runLsCommand } from './ls.js'
import { runRunCommand } from './run.js'
import { runLogsCommand } from './logs.js'
@@ -68,7 +69,7 @@ export function createAgentCommand(): Command {
agent
.command('stop')
.description('Stop an agent (cancel if running, then terminate)')
.description('Interrupt an agent if it is running (no-op for idle agents)')
.argument('[id]', 'Agent ID (or prefix) - optional if --all or --cwd specified')
.option('--all', 'Stop all agents')
.option('--cwd <path>', 'Stop all agents in directory')
@@ -76,6 +77,16 @@ export function createAgentCommand(): Command {
.option('--host <host>', 'Daemon host:port (default: localhost:6767)')
.action(withOutput(runStopCommand))
agent
.command('delete')
.description('Delete an agent (interrupt if running, then hard-delete)')
.argument('[id]', 'Agent ID (or prefix) - optional if --all or --cwd specified')
.option('--all', 'Delete all agents')
.option('--cwd <path>', 'Delete all agents in directory')
.option('--json', 'Output in JSON format')
.option('--host <host>', 'Daemon host:port (default: localhost:6767)')
.action(withOutput(runDeleteCommand))
agent
.command('send')
.description('Send a message/task to an existing agent')
+4 -7
View File
@@ -12,7 +12,7 @@ export interface StopResult {
export const stopSchema: OutputSchema<StopResult> = {
// For quiet mode, output the stopped agent IDs (one per line)
idField: (item) => item.agentIds.join('\n'),
columns: [{ header: 'STOPPED', field: 'stoppedCount' }],
columns: [{ header: 'INTERRUPTED', field: 'stoppedCount' }],
}
export interface AgentStopOptions extends CommandOptions {
@@ -83,18 +83,15 @@ export async function runStopCommand(
agents = [fetchResult.agent]
}
// Stop each agent
// Interrupt each running agent. Idle agents are a no-op.
for (const agent of agents) {
try {
// Cancel if running
if (agent.status === 'running') {
await client.cancelAgent(agent.id)
stoppedIds.push(agent.id)
}
// Delete the agent
await client.deleteAgent(agent.id)
stoppedIds.push(agent.id)
} catch (err) {
// Continue stopping other agents even if one fails
// Continue interrupting other agents even if one fails
const message = err instanceof Error ? err.message : String(err)
console.error(`Warning: Failed to stop agent ${agent.id.slice(0, 7)}: ${message}`)
}
+1 -1
View File
@@ -3,7 +3,7 @@
/**
* Phase 6: Stop Command Tests
*
* Tests the stop command - stopping agents (cancel if running, then terminate) (top-level command).
* Tests the stop command - interrupting agents (no-op if idle) (top-level command).
* Since daemon may not be running, we test both:
* - Help and argument parsing
* - Graceful error handling when daemon not running
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env npx tsx
/**
* Delete Command Tests
*
* Tests the delete command - hard-deleting agents (interrupt if running first).
* Since daemon may not be running, we test both:
* - Help and argument parsing
* - Graceful error handling when daemon not running
* - All flags are accepted
*/
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('=== Delete Command Tests ===\n')
const port = 10000 + Math.floor(Math.random() * 50000)
const paseoHome = await mkdtemp(join(tmpdir(), 'paseo-delete-test-home-'))
try {
{
console.log('Test 1: delete --help shows options')
const result = await $`npm run cli -- delete --help`.nothrow()
assert.strictEqual(result.exitCode, 0, 'delete --help should exit 0')
assert(result.stdout.includes('--all'), 'help should mention --all flag')
assert(result.stdout.includes('--cwd'), 'help should mention --cwd option')
assert(result.stdout.includes('--host'), 'help should mention --host option')
assert(result.stdout.includes('[id]'), 'help should mention optional id argument')
console.log('✓ delete --help shows options\n')
}
{
console.log('Test 2: delete requires ID, --all, or --cwd')
const result =
await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npm run cli -- delete`.nothrow()
assert.notStrictEqual(result.exitCode, 0, 'should fail without id, --all, or --cwd')
const output = result.stdout + result.stderr
const hasError =
output.toLowerCase().includes('missing') ||
output.toLowerCase().includes('required') ||
output.toLowerCase().includes('argument') ||
output.toLowerCase().includes('id')
assert(hasError, 'error should mention missing argument')
console.log('✓ delete requires ID, --all, or --cwd\n')
}
{
console.log('Test 3: delete handles daemon not running')
const result =
await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npm run cli -- delete abc123`.nothrow()
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('✓ delete handles daemon not running\n')
}
{
console.log('Test 4: delete --all flag is accepted')
const result =
await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npm run cli -- delete --all`.nothrow()
const output = result.stdout + result.stderr
assert(!output.includes('unknown option'), 'should accept --all flag')
assert(!output.includes('error: option'), 'should not have option parsing error')
console.log('✓ delete --all flag is accepted\n')
}
{
console.log('Test 5: delete --cwd flag is accepted')
const result =
await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npm run cli -- delete --cwd /tmp`.nothrow()
const output = result.stdout + result.stderr
assert(!output.includes('unknown option'), 'should accept --cwd flag')
assert(!output.includes('error: option'), 'should not have option parsing error')
console.log('✓ delete --cwd flag is accepted\n')
}
{
console.log('Test 6: delete with ID and --host flag is accepted')
const result =
await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npm run cli -- delete abc123 --host localhost:${port}`.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('✓ delete with ID and --host flag is accepted\n')
}
{
console.log('Test 7: paseo --help shows delete command')
const result = await $`npm run cli -- --help`.nothrow()
assert.strictEqual(result.exitCode, 0, 'paseo --help should exit 0')
assert(result.stdout.includes('delete'), 'help should mention delete command')
console.log('✓ paseo --help shows delete command\n')
}
{
console.log('Test 8: -q (quiet) flag is accepted with delete')
const result =
await $`PASEO_HOST=localhost:${port} PASEO_HOME=${paseoHome} npm run cli -- -q delete 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 delete\n')
}
} finally {
await rm(paseoHome, { recursive: true, force: true })
}
console.log('=== All delete tests passed ===')
+24 -11
View File
@@ -12,8 +12,9 @@
* 3. List agents with `paseo ls`
* 4. Wait for agent with `paseo wait <id>`
* 5. Inspect agent with `paseo inspect <id>`
* 6. Stop agent with `paseo stop <id>`
* 7. Cleanup: stop daemon, remove temp dirs
* 6. Stop agent with `paseo stop <id>` and verify it remains inspectable
* 7. Delete agent with `paseo delete <id>`
* 8. Cleanup: stop daemon, remove temp dirs
*
* CRITICAL RULES:
* - NEVER use port 6767 (user's running daemon)
@@ -197,17 +198,28 @@ async function test_agent_stop(agentId: string): Promise<void> {
assert.strictEqual(result.exitCode, 0, 'agent stop should succeed')
// Verify agent is no longer in running list
const psResult = await ctx.paseo(['ls', '--json'])
const agents = JSON.parse(psResult.stdout.trim()) as Array<{ id: string; status?: string }>
const inspectResult = await ctx.paseo(['inspect', agentId])
assert.strictEqual(inspectResult.exitCode, 0, 'agent should remain inspectable after stop')
assert(!inspectResult.stdout.toLowerCase().includes('running'), 'Agent should not be running after stop')
// Agent might still be in list but should not be running
const ourAgent = agents.find((a) => agentId.startsWith(a.id) || a.id.startsWith(agentId.slice(0, 7)))
if (ourAgent) {
assert(ourAgent.status !== 'running', 'Agent should not be running after stop')
}
console.log('PASS: agent stop interrupted without deleting the agent')
}
console.log('PASS: agent stop completed successfully')
async function test_agent_delete(agentId: string): Promise<void> {
console.log('\n--- Test: agent delete ---')
const result = await ctx.paseo(['delete', agentId])
console.log('Exit code:', result.exitCode)
console.log('Stdout:', result.stdout)
if (result.stderr) console.log('Stderr:', result.stderr)
assert.strictEqual(result.exitCode, 0, 'agent delete should succeed')
const inspectResult = await ctx.paseo(['inspect', agentId])
assert.notStrictEqual(inspectResult.exitCode, 0, 'deleted agent should not be inspectable')
console.log('PASS: agent delete removed the agent')
}
async function main(): Promise<void> {
@@ -232,6 +244,7 @@ async function main(): Promise<void> {
await test_agent_logs(agentId)
await test_agent_stop(agentId)
await test_agent_delete(agentId)
console.log('\n=== All E2E tests passed! ===')
} catch (err) {
+6 -6
View File
@@ -157,18 +157,18 @@ async function test_verify_logs(agentId: string): Promise<void> {
console.log('PASS: Agent logs show activity from both tasks')
}
async function test_agent_stop(agentId: string): Promise<void> {
console.log('\n--- Test: Stop agent ---')
async function test_agent_delete(agentId: string): Promise<void> {
console.log('\n--- Test: Delete agent ---')
const result = await ctx.paseo(['stop', agentId])
const result = await ctx.paseo(['delete', agentId])
console.log('Exit code:', result.exitCode)
console.log('Stdout:', result.stdout)
if (result.stderr) console.log('Stderr:', result.stderr)
assert.strictEqual(result.exitCode, 0, 'agent stop should succeed')
assert.strictEqual(result.exitCode, 0, 'agent delete should succeed')
console.log('PASS: Agent stopped successfully')
console.log('PASS: Agent deleted successfully')
}
async function main(): Promise<void> {
@@ -190,7 +190,7 @@ async function main(): Promise<void> {
await test_verify_logs(agentId)
// Cleanup agent
await test_agent_stop(agentId)
await test_agent_delete(agentId)
console.log('\n=== All agent-send E2E tests passed! ===')
} catch (err) {
+7 -7
View File
@@ -215,18 +215,18 @@ async function test_agent_continues(agentId: string): Promise<void> {
console.log('PASS: Agent completed after permission was granted')
}
async function test_agent_stop(agentId: string): Promise<void> {
console.log('\n--- Test: Stop agent ---')
async function test_agent_delete(agentId: string): Promise<void> {
console.log('\n--- Test: Delete agent ---')
const result = await ctx.paseo(['stop', agentId])
const result = await ctx.paseo(['delete', agentId])
console.log('Exit code:', result.exitCode)
console.log('Stdout:', result.stdout)
if (result.stderr) console.log('Stderr:', result.stderr)
assert.strictEqual(result.exitCode, 0, 'agent stop should succeed')
assert.strictEqual(result.exitCode, 0, 'agent delete should succeed')
console.log('PASS: Agent stopped successfully')
console.log('PASS: Agent deleted successfully')
}
async function main(): Promise<void> {
@@ -270,10 +270,10 @@ async function main(): Promise<void> {
console.error(err)
process.exitCode = 1
} finally {
// Always try to stop the agent if it was created
// Always try to delete the agent if it was created
if (agentId) {
try {
await test_agent_stop(agentId)
await test_agent_delete(agentId)
} catch {
// Ignore errors during cleanup
}