Skip to main content

trustee_core/
session.rs

1//! Session state — core agent session without any UI concerns.
2//!
3//! This struct holds all the state shared between frontends (TUI, API, Web):
4//! output lines, input, workflow state, config, resume info, MCP servers, etc.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8
9use tokio::sync::mpsc;
10use tokio_util::sync::CancellationToken;
11
12use abk::cli::ResumeInfo;
13use abk::context::RunContext;
14
15use std::sync::atomic::{AtomicU8, Ordering};
16
17use crate::types::{
18    AutoHandoffConfig, BuildInfo, CapturedText, HandoffCaptureSink, McpServerInfo, McpServerStatus,
19    TuiMessage, WorkflowState,
20};
21
22/// Core session state for the Trustee agent.
23///
24/// Holds all state that is independent of the presentation layer (TUI, API, Web).
25/// Frontend crates compose this struct and add their own UI-specific fields.
26pub struct Session {
27    /// Input buffer for user commands
28    pub input: String,
29    /// Output log lines
30    pub output_lines: Vec<String>,
31    /// Sender for messages from async workflows (clone and pass to workflow runners)
32    pub workflow_tx: mpsc::UnboundedSender<TuiMessage>,
33    /// Current workflow lifecycle state
34    pub workflow_state: WorkflowState,
35    /// Configuration TOML for ABK workflows
36    pub config_toml: Option<String>,
37    /// Secrets for ABK workflows
38    pub secrets: Option<HashMap<String, String>>,
39    /// Build info for ABK workflows
40    pub build_info: Option<BuildInfo>,
41    /// Resume info from the last completed task for session continuity
42    pub resume_info: Option<ResumeInfo>,
43    /// Saved resume_info before execute_command consumes it; restored if task
44    /// is cancelled before producing a real checkpoint (mistake-ENTER recovery).
45    pub backup_resume_info: Option<ResumeInfo>,
46    /// Latest todo list from LLM todowrite tool
47    pub todo_lines: Vec<String>,
48    /// Cancellation token for aborting the current workflow
49    pub cancel_token: CancellationToken,
50    /// Command buffered by user during cancellation wind-down.
51    pub pending_command: Option<String>,
52    /// Whether a session handoff (Ctrl+H) should fire once the current workflow cancels.
53    pub handoff_pending: bool,
54    /// In-flight spinner entries: (tool_name, output_lines_index, hint).
55    pub pending_tool_lines: Vec<(String, usize, Option<String>)>,
56    /// Current context token count (updated from ApiCallStarted events).
57    pub current_context_tokens: usize,
58    /// Auto-handoff configuration parsed from [tui.auto_handoff].
59    pub auto_handoff: AutoHandoffConfig,
60    /// MCP server statuses received from agent init
61    pub mcp_servers: Vec<McpServerInfo>,
62    /// Whether the session should quit
63    pub should_quit: bool,
64    /// Whether auto-scroll is enabled (follows new output)
65    pub auto_scroll: bool,
66
67    // --- TMU Phase 1: Stateless Core ---
68    /// Agent name for checkpoint/token paths (replaces ABK_AGENT_NAME env var).
69    /// Defaults to "trustee". Set from config at startup.
70    pub agent_name: String,
71    /// Per-session token store (None = FileTokenStore fallback).
72    /// When set, MCP credential flows use this instead of file-based storage.
73    pub token_store: Option<Arc<dyn pep::token_store::TokenStore>>,
74
75    // --- Project/Session Identity (backward compatible, all None = old behavior) ---
76    /// Storage partition key (replaces path hash). None = hash(working_dir)
77    pub project_id: Option<String>,
78    /// Human-readable project name. None = directory name
79    pub project_name: Option<String>,
80    /// Storage directory name (replaces timestamp slug). None = auto-generate
81    pub session_id: Option<String>,
82    /// Human-readable session name. None = no description
83    pub session_name: Option<String>,
84}
85
86impl Session {
87    /// Create a new Session with default state and a fresh message channel.
88    ///
89    /// Returns `(Session, Receiver)` so the caller can own the receiver
90    /// without locking the session (prevents deadlock in async drain loops).
91    pub fn new() -> (Self, mpsc::UnboundedReceiver<TuiMessage>) {
92        let (workflow_tx, workflow_rx) = mpsc::unbounded_channel();
93        let session = Self {
94            input: String::new(),
95            output_lines: Vec::new(),
96            workflow_tx,
97            workflow_state: WorkflowState::Idle,
98            config_toml: None,
99            secrets: None,
100            build_info: None,
101            resume_info: None,
102            backup_resume_info: None,
103            todo_lines: Vec::new(),
104            cancel_token: CancellationToken::new(),
105            pending_command: None,
106            handoff_pending: false,
107            pending_tool_lines: Vec::new(),
108            current_context_tokens: 0,
109            auto_handoff: AutoHandoffConfig::default(),
110            mcp_servers: Vec::new(),
111            should_quit: false,
112            auto_scroll: true,
113            agent_name: "trustee".to_string(),
114            token_store: None,
115            project_id: None,
116            project_name: None,
117            session_id: None,
118            session_name: None,
119        };
120        (session, workflow_rx)
121    }
122
123    /// Parse auto-handoff configuration from the stored config TOML.
124    pub fn parse_auto_handoff_config(&mut self) {
125        if let Some(ref config_toml) = self.config_toml {
126            self.auto_handoff = crate::config::parse_auto_handoff_config(config_toml);
127        }
128    }
129
130    /// Handle messages from async workflows.
131    ///
132    /// This processes all workflow lifecycle events, output updates, and state transitions.
133    /// Returns `true` if the caller should check for pending commands/handoffs after.
134    pub fn handle_workflow_message(&mut self, msg: TuiMessage) {
135        match msg {
136            TuiMessage::WorkflowCancelled => {
137                self.output_lines.push("⏹ Workflow cancelled".to_string());
138                self.output_lines.push("".to_string());
139                self.workflow_state = WorkflowState::Cancelling;
140            }
141            TuiMessage::OutputLine(line) => {
142                self.output_lines.push(line);
143            }
144            TuiMessage::StreamDelta(delta) => {
145                if let Some(last) = self.output_lines.last_mut() {
146                    last.push_str(&delta);
147                } else {
148                    self.output_lines.push(delta);
149                }
150            }
151            TuiMessage::ReasoningDelta(delta) => {
152                if let Some(last) = self.output_lines.last_mut() {
153                    if !last.starts_with('\x01') {
154                        last.insert(0, '\x01');
155                    }
156                    last.push_str(&delta);
157                } else {
158                    self.output_lines.push(format!("\x01{}", delta));
159                }
160            }
161            TuiMessage::WorkflowCompleted => {
162                self.output_lines.push("✓ Workflow completed".to_string());
163                self.output_lines.push("".to_string());
164                if self.workflow_state == WorkflowState::Running {
165                    self.workflow_state = WorkflowState::Cancelling;
166                }
167            }
168            TuiMessage::WorkflowError(err) => {
169                self.output_lines.push(format!("✗ Error: {}", err));
170                self.output_lines.push("".to_string());
171                if self.workflow_state == WorkflowState::Running {
172                    self.workflow_state = WorkflowState::Cancelling;
173                }
174            }
175            TuiMessage::TodoUpdate(content) => {
176                self.todo_lines = content.lines().map(|l| l.to_string()).collect();
177            }
178            TuiMessage::ToolPending { tool_name, hint } => {
179                let label = match &hint {
180                    Some(h) => format!("⠋ {} {}", tool_name, h),
181                    None => format!("⠋ {}", tool_name),
182                };
183                let idx = self.output_lines.len();
184                self.output_lines.push(label);
185                self.pending_tool_lines.push((tool_name, idx, hint));
186            }
187            TuiMessage::ToolDone { tool_name, success, hint } => {
188                let status = if success { "✓" } else { "✗" };
189                if let Some(pos) = self.pending_tool_lines.iter().position(|(n, _, _)| *n == tool_name) {
190                    let (_, idx, pending_hint) = self.pending_tool_lines.remove(pos);
191                    let h = hint.or(pending_hint);
192                    let label = match &h {
193                        Some(h) => format!("{} {} {}", status, tool_name, h),
194                        None => format!("{} {}", status, tool_name),
195                    };
196                    if idx < self.output_lines.len() {
197                        self.output_lines[idx] = label;
198                        return;
199                    }
200                    self.output_lines.push(label);
201                } else {
202                    let label = match &hint {
203                        Some(h) => format!("{} {} {}", status, tool_name, h),
204                        None => format!("{} {}", status, tool_name),
205                    };
206                    self.output_lines.push(label);
207                }
208            }
209            TuiMessage::ResumeInfo(info) => {
210                if self.workflow_state == WorkflowState::Cancelling && info.is_none() {
211                    self.resume_info = self.backup_resume_info.take();
212                } else if info.is_some() {
213                    // Only overwrite with a valid resume_info.
214                    // Don't let ResumeInfo(None) clobber a valid Some that was
215                    // set by an earlier incremental checkpoint message — this
216                    // happens when the error/cancel path fails to create a
217                    // final checkpoint but earlier checkpoints exist.
218                    self.resume_info = info;
219                    self.backup_resume_info = None;
220                }
221                // If info is None and we're not cancelling, keep existing resume_info.
222                if self.workflow_state == WorkflowState::Cancelling {
223                    self.workflow_state = WorkflowState::Idle;
224                }
225                if self.resume_info.is_some() {
226                    if std::env::var("RUST_LOG")
227                        .map(|v| v.to_lowercase().contains("debug"))
228                        .unwrap_or(false)
229                    {
230                        self.output_lines.push("🔄 Session preserved — next command will continue this session".to_string());
231                    }
232                }
233                if self.workflow_state == WorkflowState::Idle && self.handoff_pending {
234                    self.handoff_pending = false;
235                    self.trigger_handoff(String::new());
236                } else if let Some(cmd) = self.pending_command.take() {
237                    self.input = cmd;
238                    self.execute_command();
239                }
240            }
241            TuiMessage::ContextTokensUpdated(count) => {
242                self.current_context_tokens = count;
243                if self.auto_handoff.enabled
244                    && count >= self.auto_handoff.context_threshold
245                    && self.workflow_state == WorkflowState::Running
246                    && !self.handoff_pending
247                    && self.resume_info.is_some()
248                {
249                    self.handoff_pending = true;
250                    self.cancel_token.cancel();
251                    self.workflow_state = WorkflowState::Cancelling;
252                    self.output_lines.push(format!(
253                        "🔄 Auto-handoff: cancelling workflow, context tokens ({}) ≥ threshold ({})",
254                        count, self.auto_handoff.context_threshold
255                    ));
256                }
257            }
258            TuiMessage::McpServerStatus { name, connected, tool_count, error } => {
259                let status = if connected { McpServerStatus::Connected } else { McpServerStatus::Failed };
260                if let Some(existing) = self.mcp_servers.iter_mut().find(|s| s.name == name) {
261                    existing.status = status;
262                    existing.tool_count = tool_count;
263                    existing.error = error;
264                } else {
265                    self.mcp_servers.push(McpServerInfo { name, status, tool_count, error });
266                }
267            }
268            TuiMessage::HandoffReady(briefing) => {
269                self.workflow_state = WorkflowState::Idle;
270                self.resume_info = None;
271                self.input = briefing;
272                self.execute_command();
273            }
274        }
275        if self.auto_scroll {
276            // Signal to frontend that it should scroll to bottom.
277            // Frontend reads auto_scroll flag directly.
278        }
279    }
280
281    /// Execute the current command in the input buffer.
282    ///
283    /// Spawns an async ABK workflow task, clears the input buffer, and sets
284    /// workflow_state to Running.
285    pub fn execute_command(&mut self) {
286        let command = self.input.trim().to_string();
287
288        if self.workflow_state != WorkflowState::Idle {
289            self.pending_command = Some(command);
290            self.output_lines.push("⏳ Previous workflow finishing — command queued".to_string());
291            self.input.clear();
292            return;
293        }
294
295        let is_continuation = self.resume_info.is_some();
296
297        if !is_continuation {
298            self.output_lines.clear();
299        }
300
301        self.output_lines.push(format!("> {}", command));
302
303        let config_toml = match &self.config_toml {
304            Some(c) => c.clone(),
305            None => {
306                self.output_lines.push("✗ Error: Configuration not loaded".to_string());
307                self.output_lines.push("".to_string());
308                return;
309            }
310        };
311
312        let secrets = self.secrets.clone().unwrap_or_default();
313        let build_info = self.build_info.clone();
314        let tx = self.workflow_tx.clone();
315
316        let agent_name = self.agent_name.clone();
317        let token_store = self.token_store.clone();
318
319        self.backup_resume_info = self.resume_info.clone();
320        let resume_info = self.resume_info.take();
321
322        self.workflow_state = WorkflowState::Running;
323        self.auto_scroll = true;
324
325        self.cancel_token = CancellationToken::new();
326        let child_token = self.cancel_token.clone();
327
328        let (resume_tx, mut resume_rx) = mpsc::unbounded_channel();
329
330        let resume_forward_tx = tx.clone();
331        tokio::spawn(async move {
332            while let Some(info) = resume_rx.recv().await {
333                resume_forward_tx.send(TuiMessage::ResumeInfo(info)).ok();
334            }
335        });
336
337        tokio::spawn(async move {
338            let tui_sink: abk::orchestration::output::SharedSink =
339                Arc::new(crate::session::TuiForwardSink::new(tx.clone()));
340
341            abk::observability::set_tui_mode(true);
342
343            // Build RunContext from session fields for stateless operation
344            let mut run_ctx = RunContext::new()
345                .with_agent_name(agent_name.clone());
346            #[cfg(feature = "registry-mcp-token")]
347            {
348                if let Some(ref ts) = token_store {
349                    run_ctx = run_ctx.with_token_store(ts.clone());
350                }
351            }
352
353            let result = abk::cli::run_task_from_raw_config(
354                &config_toml,
355                secrets,
356                build_info,
357                &command,
358                Some(tui_sink),
359                resume_info,
360                Some(resume_tx),
361                Some(child_token),
362            )
363            .await;
364
365            abk::observability::set_tui_mode(false);
366
367            let task_result = result.unwrap_or_else(|e| abk::cli::TaskResult {
368                success: false,
369                error: Some(e.to_string()),
370                // resume_info will be None here, but the on_checkpoint channel
371                // may have already delivered a valid ResumeInfo via TuiMessage.
372                // The ResumeInfo handler now ignores None when a valid Some exists,
373                // so this None won't clobber the earlier incremental checkpoint.
374                resume_info: None,
375            });
376
377            let msg = if task_result.success {
378                TuiMessage::WorkflowCompleted
379            } else {
380                TuiMessage::WorkflowError(task_result.error.unwrap_or_default())
381            };
382            tx.send(msg).ok();
383            tx.send(TuiMessage::ResumeInfo(task_result.resume_info)).ok();
384        });
385
386        self.input.clear();
387    }
388
389    /// Trigger a session handoff.
390    ///
391    /// Runs a single LLM call using the current session's resume_info to generate
392    /// a briefing. On completion, sends `TuiMessage::HandoffReady(briefing)`.
393    pub fn trigger_handoff(&mut self, hint: String) {
394        if self.resume_info.is_none() {
395            self.output_lines.push("ℹ Nothing to hand off — run a task first".to_string());
396            return;
397        }
398
399        let config_toml = match &self.config_toml {
400            Some(c) => c.clone(),
401            None => {
402                self.output_lines.push("✗ Error: Configuration not loaded".to_string());
403                return;
404            }
405        };
406
407        let secrets = self.secrets.clone().unwrap_or_default();
408        let build_info = self.build_info.clone();
409        let tx = self.workflow_tx.clone();
410
411        let agent_name = self.agent_name.clone();
412        let token_store = self.token_store.clone();
413
414        let resume_info = self.resume_info.take();
415
416        self.workflow_state = WorkflowState::Running;
417        self.auto_scroll = true;
418        self.cancel_token = CancellationToken::new();
419        let child_token = self.cancel_token.clone();
420
421        self.output_lines.push("🔀 Generating session handoff briefing...".to_string());
422
423        tokio::spawn(async move {
424            let (cap_tx, mut cap_rx) = mpsc::unbounded_channel::<CapturedText>();
425            let cap_sink: abk::orchestration::output::SharedSink =
426                Arc::new(HandoffCaptureSink::new(cap_tx, child_token.clone()));
427
428            abk::observability::set_tui_mode(true);
429
430            let base = "Output a session handoff briefing in at most 300 lines. \
431                 Do NOT use any tools. Include: the FULL ABSOLUTE PATH of every \
432                 project/repository being worked on (e.g. /Projects/Foo/bar — never \
433                 omit the leading path), all project/task/workstream UUIDs referenced, \
434                 every file created or modified with its full absolute path, all \
435                 commands run and their outcomes, the current state of the work, any \
436                 blockers, and the exact next action to take. \
437                 Output ONLY the briefing text — no preamble, headers, or closing remarks.";
438            let prompt = if hint.is_empty() {
439                base.to_string()
440            } else {
441                format!("{base}\n\nIn the briefing also consider: {hint}")
442            };
443
444            let (dummy_tx, _dummy_rx) = mpsc::unbounded_channel();
445            let _res = abk::cli::run_task_from_raw_config(
446                &config_toml,
447                secrets,
448                build_info,
449                &prompt,
450                Some(cap_sink),
451                resume_info,
452                Some(dummy_tx),
453                Some(child_token),
454            )
455            .await;
456
457            abk::observability::set_tui_mode(false);
458
459            let mut text_parts = String::new();
460            let mut reasoning_parts = String::new();
461            while let Ok(captured) = cap_rx.try_recv() {
462                match captured {
463                    CapturedText::Text(s) => text_parts.push_str(&s),
464                    CapturedText::Reasoning(s) => reasoning_parts.push_str(&s),
465                }
466            }
467
468            let briefing = if !text_parts.trim().is_empty() {
469                text_parts.trim().to_string()
470            } else if !reasoning_parts.trim().is_empty() {
471                reasoning_parts.trim().to_string()
472            } else {
473                "Session handoff: briefing unavailable — continue from previous context.".to_string()
474            };
475
476            tx.send(TuiMessage::HandoffReady(briefing)).ok();
477        });
478    }
479}
480
481impl Default for Session {
482    fn default() -> Self {
483        Self::new().0
484    }
485}
486
487/// A sink that forwards ABK `OutputEvent`s to the message channel.
488///
489/// Includes a 3-state atomic state machine (IDLE/REASONING/CONTENT) that
490/// inserts blank separator lines when transitioning between reasoning and
491/// content streams, so the frontend can distinguish them visually.
492pub struct TuiForwardSink {
493    tx: mpsc::UnboundedSender<TuiMessage>,
494    stream_state: AtomicU8,
495}
496
497/// Stream state machine constants.
498const STREAM_IDLE: u8 = 0;
499const STREAM_REASONING: u8 = 1;
500const STREAM_CONTENT: u8 = 2;
501
502impl TuiForwardSink {
503    pub fn new(tx: mpsc::UnboundedSender<TuiMessage>) -> Self {
504        Self {
505            tx,
506            stream_state: AtomicU8::new(STREAM_IDLE),
507        }
508    }
509}
510
511impl abk::orchestration::output::OutputSink for TuiForwardSink {
512    fn emit(&self, event: abk::orchestration::output::OutputEvent) {
513        use abk::orchestration::output::OutputEvent;
514
515        let msg = match event {
516            OutputEvent::StreamingChunk { delta } => {
517                if delta.is_empty() {
518                    return;
519                }
520                let prev = self.stream_state.swap(STREAM_CONTENT, Ordering::Relaxed);
521                if prev != STREAM_CONTENT {
522                    let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
523                }
524                let _ = self.tx.send(TuiMessage::StreamDelta(delta));
525                return;
526            }
527
528            OutputEvent::LlmResponse { text, model } => {
529                TuiMessage::OutputLine(format!("[{}] {}", model, text))
530            }
531
532            OutputEvent::Info { message } => {
533                // Suppress noisy/no-value messages from ABK
534                if message.contains("API call completed successfully") {
535                    return;
536                }
537                TuiMessage::OutputLine(message)
538            }
539
540            OutputEvent::WorkflowStarted { task_description } => {
541                TuiMessage::OutputLine(format!("🚀 Workflow started: {}", task_description))
542            }
543
544            OutputEvent::WorkflowCompleted { reason, iterations } => {
545                TuiMessage::OutputLine(format!(
546                    "✅ Workflow completed after {} iterations: {}",
547                    iterations, reason
548                ))
549            }
550
551            OutputEvent::IterationStarted { iteration, context_tokens } => {
552                let _ = self.tx.send(TuiMessage::ContextTokensUpdated(context_tokens));
553                TuiMessage::OutputLine(format!(
554                    "📡 Iteration {} | Context = {} tokens",
555                    iteration, context_tokens
556                ))
557            }
558
559            OutputEvent::ApiCallStarted {
560                call_number,
561                model,
562                tool_count,
563                streaming,
564                context_tokens,
565                tool_tokens,
566            } => {
567                let mode = if streaming { "Streaming" } else { "Non-streaming" };
568                let total = context_tokens + tool_tokens;
569                let _ = self.tx.send(TuiMessage::ContextTokensUpdated(total));
570                // Blank line separator before each API call for readability
571                let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
572                TuiMessage::OutputLine(format!(
573                    "🔥 API Call {} | Ctx={}({}+{}) | {} | Model: {} | Tools: {}",
574                    call_number, total, context_tokens, tool_tokens, mode, model, tool_count
575                ))
576            }
577
578            OutputEvent::ToolsExecuting { tool_names, hints } => {
579                for (name, hint) in tool_names.into_iter().zip(hints.into_iter()) {
580                    let _ = self.tx.send(TuiMessage::ToolPending { tool_name: name, hint });
581                }
582                self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
583                return;
584            }
585
586            OutputEvent::ToolCompleted {
587                tool_name,
588                success,
589                content,
590                description,
591            } => {
592                if tool_name == "todowrite" && success {
593                    let _ = self.tx.send(TuiMessage::TodoUpdate(content.clone()));
594                }
595                let hint = description;
596                let _ = self.tx.send(TuiMessage::ToolDone { tool_name, success, hint });
597                self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
598                return;
599            }
600
601            OutputEvent::Error { message, context } => {
602                if let Some(ctx) = context {
603                    TuiMessage::OutputLine(format!("❌ Error: {} — {}", message, ctx))
604                } else {
605                    TuiMessage::OutputLine(format!("❌ Error: {}", message))
606                }
607            }
608
609            OutputEvent::ReasoningChunk { delta } => {
610                if delta.is_empty() {
611                    return;
612                }
613                let prev = self.stream_state.swap(STREAM_REASONING, Ordering::Relaxed);
614                if prev != STREAM_REASONING {
615                    let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
616                }
617                let _ = self.tx.send(TuiMessage::ReasoningDelta(delta));
618                return;
619            }
620
621            OutputEvent::McpServerStatus { name, connected, tool_count, error } => {
622                let _ = self.tx.send(TuiMessage::McpServerStatus {
623                    name,
624                    connected,
625                    tool_count,
626                    error,
627                });
628                return;
629            }
630        };
631
632        self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
633        let _ = self.tx.send(msg);
634    }
635}