|
| 1 | +// Resolves recent Gateway sessions and attaches the existing TUI to the selected key. |
| 2 | +import { cancel, isCancel } from "@clack/prompts"; |
| 3 | +import { selectStyled } from "../../packages/terminal-core/src/prompt-select-styled.js"; |
| 4 | +import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js"; |
| 5 | +import { parseAgentSessionKey } from "../routing/session-key.js"; |
| 6 | +import { defaultRuntime } from "../runtime.js"; |
| 7 | +import type { TuiSessionList } from "../tui/tui-backend.js"; |
| 8 | +import { |
| 9 | + buildSessionChoices, |
| 10 | + loadRecentSessions, |
| 11 | + resolveResumeSession, |
| 12 | + type ResumeResolution, |
| 13 | + type SessionPickerChoice, |
| 14 | +} from "../tui/tui-session-picker.js"; |
| 15 | +import type { ResumeCliOptions } from "./resume-cli.js"; |
| 16 | + |
| 17 | +const RESUME_INTERACTIVE_TERMINAL_GUIDANCE = |
| 18 | + "Attaching to a session requires an interactive terminal. Re-run `openclaw resume [query]` from an interactive terminal."; |
| 19 | + |
| 20 | +function requireInteractiveResumeTerminal() { |
| 21 | + if (!process.stdin.isTTY || !process.stdout.isTTY) { |
| 22 | + throw new Error(RESUME_INTERACTIVE_TERMINAL_GUIDANCE); |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +async function fetchResumeSessions( |
| 27 | + opts: ResumeCliOptions, |
| 28 | + options: { agentId?: string; includeGlobal?: boolean } = {}, |
| 29 | +) { |
| 30 | + const { GatewayChatClient } = await import("../tui/gateway-chat.js"); |
| 31 | + const client = await GatewayChatClient.connect(opts); |
| 32 | + try { |
| 33 | + await new Promise<void>((resolve, reject) => { |
| 34 | + let settled = false; |
| 35 | + const finish = (complete: () => void) => { |
| 36 | + if (settled) { |
| 37 | + return; |
| 38 | + } |
| 39 | + settled = true; |
| 40 | + complete(); |
| 41 | + }; |
| 42 | + client.onConnected = () => finish(resolve); |
| 43 | + client.onConnectError = (error) => finish(() => reject(error)); |
| 44 | + client.onDisconnected = (reason) => |
| 45 | + finish(() => reject(new Error(reason || "Gateway connection closed"))); |
| 46 | + client.start(); |
| 47 | + }); |
| 48 | + return await loadRecentSessions(client, options); |
| 49 | + } catch (error) { |
| 50 | + const [{ formatTuiErrorMessage }, { resolveGatewayDisconnectState }] = await Promise.all([ |
| 51 | + import("../tui/tui-formatters.js"), |
| 52 | + import("../tui/tui.js"), |
| 53 | + ]); |
| 54 | + const details = |
| 55 | + error && typeof error === "object" && "details" in error ? error.details : undefined; |
| 56 | + const state = resolveGatewayDisconnectState({ |
| 57 | + reason: formatTuiErrorMessage(error), |
| 58 | + details, |
| 59 | + }); |
| 60 | + throw new Error( |
| 61 | + [ |
| 62 | + state.connectionStatus, |
| 63 | + state.remediation ?? |
| 64 | + "Ensure the Gateway is running and your --url/--token/--password are correct.", |
| 65 | + ].join("\n"), |
| 66 | + { cause: error }, |
| 67 | + ); |
| 68 | + } finally { |
| 69 | + await client.stop(); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +async function promptResumeSession( |
| 74 | + sessions: readonly TuiSessionList["sessions"][number][], |
| 75 | +): Promise<string | null> { |
| 76 | + const choices = buildSessionChoices(sessions); |
| 77 | + if (choices.length === 0) { |
| 78 | + throw new Error( |
| 79 | + "No recent sessions found. Run `openclaw sessions` to inspect sessions or `openclaw tui` to start one.", |
| 80 | + ); |
| 81 | + } |
| 82 | + const selected = await selectStyled({ |
| 83 | + message: "Resume a session", |
| 84 | + options: choices.map((choice) => ({ |
| 85 | + value: choice.value, |
| 86 | + label: formatResumeCandidate(choice), |
| 87 | + hint: choice.description ? sanitizeTerminalText(choice.description) : undefined, |
| 88 | + })), |
| 89 | + }); |
| 90 | + if (isCancel(selected)) { |
| 91 | + cancel("Cancelled."); |
| 92 | + return null; |
| 93 | + } |
| 94 | + return selected; |
| 95 | +} |
| 96 | + |
| 97 | +function reportResumeFailure( |
| 98 | + query: string, |
| 99 | + resolution: Exclude<ResumeResolution, { kind: "match" }>, |
| 100 | +) { |
| 101 | + if (resolution.kind === "ambiguous") { |
| 102 | + defaultRuntime.error(`Session query ${JSON.stringify(query)} is ambiguous. Candidates:`); |
| 103 | + for (const candidate of resolution.candidates) { |
| 104 | + defaultRuntime.error(` ${formatResumeCandidate(candidate)}`); |
| 105 | + } |
| 106 | + defaultRuntime.error("Use a longer name or the exact session key."); |
| 107 | + return; |
| 108 | + } |
| 109 | + defaultRuntime.error(`No recent session matched ${JSON.stringify(query)}.`); |
| 110 | + defaultRuntime.error( |
| 111 | + "Run `openclaw resume` to choose from recent sessions or `openclaw sessions` to inspect all sessions.", |
| 112 | + ); |
| 113 | +} |
| 114 | + |
| 115 | +function formatResumeCandidate(candidate: SessionPickerChoice): string { |
| 116 | + const label = sanitizeTerminalText(candidate.label); |
| 117 | + const key = sanitizeTerminalText(candidate.value); |
| 118 | + return label === key ? key : `${label} [${key}]`; |
| 119 | +} |
| 120 | + |
| 121 | +function resolveExplicitGlobalSessionKey( |
| 122 | + query: string | undefined, |
| 123 | +): { agentId: string; key: string } | undefined { |
| 124 | + const parsed = parseAgentSessionKey(query); |
| 125 | + return parsed?.rest === "global" |
| 126 | + ? { agentId: parsed.agentId, key: `agent:${parsed.agentId}:global` } |
| 127 | + : undefined; |
| 128 | +} |
| 129 | + |
| 130 | +/** Resolve or select one session and run the existing Gateway-backed TUI. */ |
| 131 | +export async function runResumeCommand(query: string | undefined, opts: ResumeCliOptions) { |
| 132 | + requireInteractiveResumeTerminal(); |
| 133 | + const trimmedQuery = query?.trim(); |
| 134 | + const explicitGlobalSession = resolveExplicitGlobalSessionKey(trimmedQuery); |
| 135 | + const sessions = await fetchResumeSessions( |
| 136 | + opts, |
| 137 | + explicitGlobalSession |
| 138 | + ? { agentId: explicitGlobalSession.agentId, includeGlobal: true } |
| 139 | + : undefined, |
| 140 | + ); |
| 141 | + let sessionKey: string | null; |
| 142 | + if (explicitGlobalSession) { |
| 143 | + sessionKey = explicitGlobalSession.key; |
| 144 | + } else if (trimmedQuery) { |
| 145 | + const resolution = resolveResumeSession(sessions, trimmedQuery); |
| 146 | + if (resolution.kind !== "match") { |
| 147 | + reportResumeFailure(trimmedQuery, resolution); |
| 148 | + defaultRuntime.exit(1); |
| 149 | + return; |
| 150 | + } |
| 151 | + sessionKey = resolution.session.value; |
| 152 | + } else { |
| 153 | + sessionKey = await promptResumeSession(sessions); |
| 154 | + } |
| 155 | + if (!sessionKey) { |
| 156 | + return; |
| 157 | + } |
| 158 | + const { runTui } = await import("../tui/tui.js"); |
| 159 | + await runTui({ |
| 160 | + url: opts.url, |
| 161 | + token: opts.token, |
| 162 | + password: opts.password, |
| 163 | + tlsFingerprint: opts.tlsFingerprint, |
| 164 | + session: sessionKey, |
| 165 | + forceProcessExitOnReturn: true, |
| 166 | + }); |
| 167 | +} |
0 commit comments