hotl 0.2.0

Human-on-the-loop terminal AI agent: steering TUI + headless mode, gated tools under a kernel sandbox floor, session resume + undo, MCP/ACP, any Anthropic or OpenAI-compatible model — plus `hotl watch`, a tmux dashboard for the agents you already run.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Bare `hotl` — terminal runtime for the execute console. All decisions live
//! in `hotl-tui` (pure Elm core); this file owns the I/O: raw mode, the event
//! loop, `$EDITOR` suspension, and the in-process duplex to `acp::serve`. The
//! TUI is a pure ACP client — it never touches the engine directly.

use std::collections::VecDeque;
use std::io::{self, Stdout};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use crossterm::event::{Event, KeyEventKind};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, SetTitle,
};
use hotl_theme::Palette;
use hotl_tui::app::{update, Cmd, Msg, Phase, State};
use hotl_tui::client::{read_server_msg, AcpClient, ServerMsg};
use hotl_tui::view::view;
use ratatui::prelude::*;
use serde_json::{json, Value};
use tokio::io::{BufReader, DuplexStream, ReadHalf, WriteHalf};
use tokio::sync::mpsc;

type ServerReader = BufReader<ReadHalf<DuplexStream>>;
type Client = AcpClient<WriteHalf<DuplexStream>>;

pub async fn tui_main(args: Vec<String>) -> i32 {
    use std::io::IsTerminal;
    if !(io::stdin().is_terminal() && io::stdout().is_terminal()) {
        eprintln!(
            "hotl: the console TUI needs a terminal — use `hotl -p \"prompt\"` for scripted runs"
        );
        return 2;
    }
    let spec = match resolve_spec(&args) {
        Ok(s) => s,
        Err(code) => return code,
    };
    let (factory, model) = match crate::agent::acp_factory().await {
        Ok(pair) => pair,
        Err(code) => return code,
    };
    let vim_mode = crate::config::Config::load(&crate::agent::config_dir())
        .behavior
        .vim_mode
        .unwrap_or(true);
    if let Some(hint) = crate::setup::first_run_hint(&crate::agent::config_dir()) {
        eprintln!("hotl: {hint}");
    }
    // Same [settings.theme] table (and warning behavior) as `hotl watch`;
    // warnings print as plain lines before the alternate screen owns stdout.
    let (watch_cfg, theme_warn) = watch_types::HotlConfig::load_with_warning();
    if let Some(w) = theme_warn {
        eprintln!("hotl: {w}");
    }
    let palette = Palette::from(&watch_cfg.settings.theme.resolve().0);

    let (client_io, server_io) = tokio::io::duplex(64 * 1024);
    let (sread, swrite) = tokio::io::split(server_io);
    tokio::spawn(crate::acp::serve(sread, swrite, factory));
    let (cread, cwrite) = tokio::io::split(client_io);
    let mut reader = BufReader::new(cread);
    let mut client = AcpClient::new(cwrite);

    if let Err(e) = handshake(&mut client, &mut reader, spec).await {
        eprintln!("hotl: {e}");
        return 1;
    }

    let suspended = Arc::new(AtomicBool::new(false));
    let keys = spawn_key_reader(suspended.clone());
    let mut guard = match TerminalGuard::enter() {
        Ok(g) => g,
        Err(e) => {
            eprintln!("hotl: {e}");
            return 1;
        }
    };
    let state = State::new(vim_mode, model);
    let result = run_loop(
        &mut guard,
        &mut client,
        &mut reader,
        keys,
        &suspended,
        state,
        palette,
    )
    .await;
    drop(guard);
    match result {
        Ok(code) => code,
        Err(e) => {
            eprintln!("hotl: {e}");
            1
        }
    }
}

/// initialize + session/new|load before entering raw mode, so wiring errors
/// print as plain lines instead of corrupting an alt-screen.
async fn handshake(
    client: &mut Client,
    reader: &mut ServerReader,
    spec: Option<String>,
) -> Result<(), String> {
    let init = client.request("initialize", Value::Null).await;
    wait_response(reader, init).await?;
    let open = match spec {
        None => client.request("session/new", Value::Null).await,
        Some(sid) => {
            client
                .request("session/load", json!({"sessionId": sid}))
                .await
        }
    };
    wait_response(reader, open).await?;
    Ok(())
}

async fn wait_response(reader: &mut ServerReader, want: u64) -> Result<Value, String> {
    loop {
        match read_server_msg(reader).await {
            None => return Err("server closed during handshake".into()),
            Some(ServerMsg::Response { id, result }) if id == want => return result,
            Some(_) => {}
        }
    }
}

#[allow(clippy::too_many_arguments)]
async fn run_loop(
    guard: &mut TerminalGuard,
    client: &mut Client,
    reader: &mut ServerReader,
    mut keys: mpsc::Receiver<Event>,
    suspended: &AtomicBool,
    mut state: State,
    palette: Palette,
) -> io::Result<i32> {
    let mut prompt_ids: VecDeque<u64> = VecDeque::new();
    // 8 ticks/sec, armed only while a turn runs — idle schedules no wakeups.
    let mut ticker = tokio::time::interval(Duration::from_millis(125));
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    loop {
        guard.terminal.draw(|f| view(&state, &palette, f))?;
        let msg = tokio::select! {
            ev = keys.recv() => match ev {
                Some(Event::Key(k)) if k.kind == KeyEventKind::Press => Some(Msg::Key(k)),
                Some(_) => None, // resize etc: redraw happens on loop
                None => return Ok(1),
            },
            sm = read_server_msg(reader) => match sm {
                Some(m) => translate(m, &mut prompt_ids),
                None => return Ok(1), // server hung up
            },
            _ = ticker.tick(), if state.phase != Phase::Idle => Some(Msg::Tick),
        };
        let Some(msg) = msg else { continue };
        let mut queue: VecDeque<Cmd> = update(&mut state, msg).into();
        while let Some(cmd) = queue.pop_front() {
            match cmd {
                Cmd::SendPrompt(text) => {
                    prompt_ids.push_back(
                        client
                            .request("session/prompt", json!({"text": text}))
                            .await,
                    );
                }
                Cmd::SendSteer(text) => {
                    client.request("session/steer", json!({"text": text})).await;
                }
                Cmd::Cancel => {
                    client.request("session/cancel", Value::Null).await;
                }
                Cmd::ReplyPermission {
                    req_id,
                    allow,
                    message,
                } => client.reply_permission(req_id, allow, message).await,
                Cmd::SetTitle(title) => {
                    let _ = execute!(io::stdout(), SetTitle(&title));
                }
                Cmd::OpenEditor(text) => {
                    let content = suspended_editor(guard, suspended, &text);
                    queue.extend(update(&mut state, Msg::EditorDone(content)));
                }
                Cmd::Quit => return Ok(0),
            }
        }
    }
}

fn translate(msg: ServerMsg, prompt_ids: &mut VecDeque<u64>) -> Option<Msg> {
    match msg {
        ServerMsg::Update(v) => Some(Msg::Update(v)),
        ServerMsg::PermissionRequest {
            req_id,
            summary,
            protected_why,
        } => Some(Msg::PermissionRequest {
            req_id,
            summary,
            protected_why,
        }),
        ServerMsg::Response { id, result } => {
            // Only prompt replies become messages; steer/cancel acks are noise.
            let pos = prompt_ids.iter().position(|&p| p == id)?;
            prompt_ids.remove(pos);
            Some(prompt_result_msg(result))
        }
    }
}

fn prompt_result_msg(result: Result<Value, String>) -> Msg {
    match result {
        Ok(v) => {
            let text = ["text", "message", "pattern", "tool"]
                .iter()
                .find_map(|k| v.pointer(&format!("/outcome/{k}")).and_then(Value::as_str))
                .map(String::from);
            Msg::PromptResult {
                outcome_kind: v
                    .pointer("/outcome/kind")
                    .and_then(Value::as_str)
                    .unwrap_or("error")
                    .to_string(),
                outcome_text: text,
                usage: v.get("usage").cloned().unwrap_or(Value::Null),
            }
        }
        Err(e) => Msg::PromptResult {
            outcome_kind: "error".into(),
            outcome_text: Some(e),
            usage: Value::Null,
        },
    }
}

/// Crossterm events read on a plain thread (no event-stream feature needed);
/// `suspended` parks it while `$EDITOR` owns the terminal.
fn spawn_key_reader(suspended: Arc<AtomicBool>) -> mpsc::Receiver<Event> {
    let (tx, rx) = mpsc::channel(64);
    std::thread::spawn(move || loop {
        if suspended.load(Ordering::Relaxed) {
            std::thread::sleep(Duration::from_millis(50));
            continue;
        }
        match crossterm::event::poll(Duration::from_millis(100)) {
            Ok(true) => match crossterm::event::read() {
                Ok(ev) => {
                    if tx.blocking_send(ev).is_err() {
                        return;
                    }
                }
                Err(_) => return,
            },
            Ok(false) => {}
            Err(_) => return,
        }
    });
    rx
}

fn suspended_editor(
    guard: &mut TerminalGuard,
    suspended: &AtomicBool,
    text: &str,
) -> Option<String> {
    suspended.store(true, Ordering::Relaxed);
    guard.suspend();
    let content = run_external_editor(text);
    guard.resume();
    suspended.store(false, Ordering::Relaxed);
    content
}

/// Blocking is fine — the TUI is suspended. `None` = unchanged or aborted.
fn run_external_editor(text: &str) -> Option<String> {
    let path = std::env::temp_dir().join(format!("hotl-tui-{}.md", std::process::id()));
    std::fs::write(&path, text).ok()?;
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".into());
    let status = std::process::Command::new("sh")
        .arg("-c")
        .arg(format!("{editor} '{}'", path.display()))
        .status();
    let content = match status {
        Ok(s) if s.success() => std::fs::read_to_string(&path).ok(),
        _ => None,
    };
    let _ = std::fs::remove_file(&path);
    content.filter(|c| c.trim_end() != text.trim_end())
}

fn resolve_spec(args: &[String]) -> Result<Option<String>, i32> {
    match args.first().map(String::as_str) {
        None => Ok(None),
        // The one-time migration hint: `tui` was a subcommand before the
        // default flip, and would otherwise read as a session-id prefix.
        Some("tui") => {
            eprintln!("hotl: the TUI is now just `hotl` (the `tui` subcommand was removed)");
            Err(2)
        }
        Some(flag) if flag.starts_with('-') && flag != "--resume" => {
            eprintln!("hotl: unknown argument `{flag}` (try --help)");
            Err(2)
        }
        Some("--resume") => match args.get(1) {
            Some(p) => by_prefix(p).map(Some),
            None => pick_session().map(Some),
        },
        Some(prefix) => by_prefix(prefix).map(Some),
    }
}

fn by_prefix(prefix: &str) -> Result<String, i32> {
    let sessions = newest_first();
    let matches: Vec<_> = sessions
        .iter()
        .filter(|(id, ..)| id.starts_with(prefix))
        .collect();
    match matches.len() {
        1 => Ok(matches[0].0.clone()),
        0 => {
            eprintln!("hotl: no session matches `{prefix}`");
            Err(2)
        }
        n => {
            eprintln!("hotl: `{prefix}` is ambiguous ({n} sessions)");
            Err(2)
        }
    }
}

fn newest_first() -> Vec<(String, PathBuf, SystemTime)> {
    let mut sessions = hotl_store::list_sessions(&crate::agent::sessions_dir());
    sessions.sort_by_key(|s| std::cmp::Reverse(s.2));
    sessions
}

/// Plain pre-TUI list prompt (the in-TUI picker is a v1 cut).
fn pick_session() -> Result<String, i32> {
    let sessions = newest_first();
    if sessions.is_empty() {
        eprintln!("hotl: no sessions to resume");
        return Err(2);
    }
    eprintln!("pick a session:");
    for (i, (id, _, t)) in sessions.iter().enumerate().take(20) {
        eprintln!("  {}) {id}  {}", i + 1, age(*t));
    }
    eprint!("> ");
    let mut line = String::new();
    if io::stdin().read_line(&mut line).is_err() {
        return Err(2);
    }
    match line.trim().parse::<usize>() {
        Ok(n) if (1..=sessions.len().min(20)).contains(&n) => Ok(sessions[n - 1].0.clone()),
        _ => {
            eprintln!("hotl: not a valid choice");
            Err(2)
        }
    }
}

fn age(t: SystemTime) -> String {
    let secs = t.elapsed().map(|d| d.as_secs()).unwrap_or(0);
    match secs {
        0..=59 => format!("{secs}s ago"),
        60..=3599 => format!("{}m ago", secs / 60),
        3600..=86399 => format!("{}h ago", secs / 3600),
        s => format!("{}d ago", s / 86400),
    }
}

/// Owns raw mode + alt screen, restoring on drop (mirrors watch.rs) — an
/// early error, normal exit, or panic all leave the shell usable.
struct TerminalGuard {
    terminal: Terminal<CrosstermBackend<Stdout>>,
}

impl TerminalGuard {
    fn enter() -> io::Result<Self> {
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        if let Err(e) = execute!(stdout, EnterAlternateScreen) {
            let _ = disable_raw_mode();
            return Err(e);
        }
        match Terminal::new(CrosstermBackend::new(stdout)) {
            Ok(terminal) => Ok(TerminalGuard { terminal }),
            Err(e) => {
                let _ = execute!(io::stdout(), LeaveAlternateScreen);
                let _ = disable_raw_mode();
                Err(e)
            }
        }
    }

    /// Hand the real screen to `$EDITOR`…
    fn suspend(&mut self) {
        let _ = disable_raw_mode();
        let _ = execute!(self.terminal.backend_mut(), LeaveAlternateScreen);
    }

    /// …and take it back.
    fn resume(&mut self) {
        let _ = enable_raw_mode();
        let _ = execute!(self.terminal.backend_mut(), EnterAlternateScreen);
        let _ = self.terminal.clear();
    }
}

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        let _ = disable_raw_mode();
        let _ = execute!(self.terminal.backend_mut(), LeaveAlternateScreen);
        let _ = self.terminal.show_cursor();
    }
}

#[cfg(test)]
mod tests {
    use super::resolve_spec;

    fn v(args: &[&str]) -> Vec<String> {
        args.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn bare_args_open_a_new_session() {
        assert_eq!(resolve_spec(&v(&[])), Ok(None));
    }

    #[test]
    fn tui_literal_gets_the_migration_hint() {
        // Pre-flip muscle memory: `hotl tui` must not read as an id prefix.
        assert_eq!(resolve_spec(&v(&["tui"])), Err(2));
    }

    #[test]
    fn unknown_flags_are_rejected_before_session_lookup() {
        assert_eq!(resolve_spec(&v(&["--json"])), Err(2));
        assert_eq!(resolve_spec(&v(&["-x"])), Err(2));
    }
}