|
| 1 | +import { Task } from "../task/Task" |
| 2 | +import { ToolUse } from "../../shared/tools" |
| 3 | +import { formatResponse } from "../prompts/responses" |
| 4 | +import { ProcessManager } from "../../integrations/terminal/ProcessManager" |
| 5 | + |
| 6 | +import { BaseTool, ToolCallbacks } from "./BaseTool" |
| 7 | + |
| 8 | +/** |
| 9 | + * ListSessionsTool enables the LLM to see all active terminal sessions. |
| 10 | + * |
| 11 | + * This tool lists all terminal sessions that were started by execute_command |
| 12 | + * and can be interacted with using write_stdin or terminated. |
| 13 | + * |
| 14 | + * ## Use Cases |
| 15 | + * |
| 16 | + * - Checking which background processes are still running |
| 17 | + * - Finding a session_id that was forgotten |
| 18 | + * - Auditing resource usage before task completion |
| 19 | + * - Verifying that a server/process is still active |
| 20 | + */ |
| 21 | +export class ListSessionsTool extends BaseTool<"list_sessions"> { |
| 22 | + readonly name = "list_sessions" as const |
| 23 | + |
| 24 | + async execute(_params: Record<string, never>, task: Task, callbacks: ToolCallbacks): Promise<void> { |
| 25 | + const { handleError, pushToolResult } = callbacks |
| 26 | + |
| 27 | + try { |
| 28 | + // Get all sessions from ProcessManager |
| 29 | + const processManager = ProcessManager.getInstance() |
| 30 | + const sessions = processManager.listSessions(task.taskId) |
| 31 | + |
| 32 | + task.consecutiveMistakeCount = 0 |
| 33 | + |
| 34 | + // Format response |
| 35 | + const response = this.formatResponse(sessions) |
| 36 | + |
| 37 | + await task.say("tool", response, undefined, false) |
| 38 | + pushToolResult(formatResponse.toolResult(response)) |
| 39 | + } catch (error) { |
| 40 | + const errorMessage = error instanceof Error ? error.message : String(error) |
| 41 | + await handleError("listing sessions", error instanceof Error ? error : new Error(errorMessage)) |
| 42 | + task.recordToolError("list_sessions") |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + override async handlePartial(task: Task, _block: ToolUse<"list_sessions">): Promise<void> { |
| 47 | + await task.say( |
| 48 | + "tool", |
| 49 | + JSON.stringify({ |
| 50 | + tool: "list_sessions", |
| 51 | + content: "Listing active sessions...", |
| 52 | + }), |
| 53 | + undefined, |
| 54 | + true, |
| 55 | + ) |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Format the sessions list into a readable table. |
| 60 | + */ |
| 61 | + private formatResponse( |
| 62 | + sessions: Array<{ |
| 63 | + sessionId: number |
| 64 | + taskId: string |
| 65 | + command: string |
| 66 | + running: boolean |
| 67 | + lastUsed: number |
| 68 | + }>, |
| 69 | + ): string { |
| 70 | + if (sessions.length === 0) { |
| 71 | + return `## Active Terminal Sessions |
| 72 | +
|
| 73 | +No active sessions found. |
| 74 | +
|
| 75 | +Sessions are created when execute_command starts a process that doesn't complete within the yield time. |
| 76 | +Use execute_command to start a new process that can be interacted with.` |
| 77 | + } |
| 78 | + |
| 79 | + const lines: string[] = [] |
| 80 | + lines.push("## Active Terminal Sessions") |
| 81 | + lines.push("") |
| 82 | + lines.push(`Found ${sessions.length} active session${sessions.length !== 1 ? "s" : ""}:`) |
| 83 | + lines.push("") |
| 84 | + lines.push("| Session | Command | Status | Last Used |") |
| 85 | + lines.push("|---------|---------|--------|-----------|") |
| 86 | + |
| 87 | + for (const session of sessions) { |
| 88 | + const status = session.running ? "🟢 Running" : "⚪ Stopped" |
| 89 | + const lastUsed = this.formatTimeSince(session.lastUsed) |
| 90 | + const command = this.truncateCommand(session.command, 40) |
| 91 | + |
| 92 | + lines.push(`| ${session.sessionId} | \`${command}\` | ${status} | ${lastUsed} |`) |
| 93 | + } |
| 94 | + |
| 95 | + lines.push("") |
| 96 | + lines.push("**Actions:**") |
| 97 | + lines.push("- Use `write_stdin` with a session_id to send input to a running process") |
| 98 | + lines.push("- Use `terminate_session` with a session_id to stop a process") |
| 99 | + |
| 100 | + return lines.join("\n") |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * Format time since a timestamp as a human-readable string. |
| 105 | + */ |
| 106 | + private formatTimeSince(timestamp: number): string { |
| 107 | + const seconds = Math.floor((Date.now() - timestamp) / 1000) |
| 108 | + |
| 109 | + if (seconds < 60) { |
| 110 | + return `${seconds}s ago` |
| 111 | + } |
| 112 | + |
| 113 | + const minutes = Math.floor(seconds / 60) |
| 114 | + if (minutes < 60) { |
| 115 | + return `${minutes}m ago` |
| 116 | + } |
| 117 | + |
| 118 | + const hours = Math.floor(minutes / 60) |
| 119 | + if (hours < 24) { |
| 120 | + return `${hours}h ago` |
| 121 | + } |
| 122 | + |
| 123 | + const days = Math.floor(hours / 24) |
| 124 | + return `${days}d ago` |
| 125 | + } |
| 126 | + |
| 127 | + /** |
| 128 | + * Truncate a command string for display. |
| 129 | + */ |
| 130 | + private truncateCommand(command: string, maxLength: number): string { |
| 131 | + // Remove newlines and extra whitespace |
| 132 | + const cleaned = command.replace(/\s+/g, " ").trim() |
| 133 | + |
| 134 | + if (cleaned.length <= maxLength) { |
| 135 | + return cleaned |
| 136 | + } |
| 137 | + |
| 138 | + return cleaned.slice(0, maxLength - 3) + "..." |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +// Export singleton instance |
| 143 | +export const listSessionsTool = new ListSessionsTool() |
0 commit comments