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                Some(&run_ctx),
363            )
364            .await;
365
366            abk::observability::set_tui_mode(false);
367
368            let task_result = result.unwrap_or_else(|e| abk::cli::TaskResult {
369                success: false,
370                error: Some(e.to_string()),
371                // resume_info will be None here, but the on_checkpoint channel
372                // may have already delivered a valid ResumeInfo via TuiMessage.
373                // The ResumeInfo handler now ignores None when a valid Some exists,
374                // so this None won't clobber the earlier incremental checkpoint.
375                resume_info: None,
376            });
377
378            let msg = if task_result.success {
379                TuiMessage::WorkflowCompleted
380            } else {
381                TuiMessage::WorkflowError(task_result.error.unwrap_or_default())
382            };
383            tx.send(msg).ok();
384            tx.send(TuiMessage::ResumeInfo(task_result.resume_info)).ok();
385        });
386
387        self.input.clear();
388    }
389
390    /// Trigger a session handoff.
391    ///
392    /// Runs a single LLM call using the current session's resume_info to generate
393    /// a briefing. On completion, sends `TuiMessage::HandoffReady(briefing)`.
394    pub fn trigger_handoff(&mut self, hint: String) {
395        if self.resume_info.is_none() {
396            self.output_lines.push("ℹ Nothing to hand off — run a task first".to_string());
397            return;
398        }
399
400        let config_toml = match &self.config_toml {
401            Some(c) => c.clone(),
402            None => {
403                self.output_lines.push("✗ Error: Configuration not loaded".to_string());
404                return;
405            }
406        };
407
408        let secrets = self.secrets.clone().unwrap_or_default();
409        let build_info = self.build_info.clone();
410        let tx = self.workflow_tx.clone();
411
412        let agent_name = self.agent_name.clone();
413        let token_store = self.token_store.clone();
414
415        let resume_info = self.resume_info.take();
416
417        self.workflow_state = WorkflowState::Running;
418        self.auto_scroll = true;
419        self.cancel_token = CancellationToken::new();
420        let child_token = self.cancel_token.clone();
421
422        self.output_lines.push("🔀 Generating session handoff briefing...".to_string());
423
424        tokio::spawn(async move {
425            let (cap_tx, mut cap_rx) = mpsc::unbounded_channel::<CapturedText>();
426            let cap_sink: abk::orchestration::output::SharedSink =
427                Arc::new(HandoffCaptureSink::new(cap_tx, child_token.clone()));
428
429            abk::observability::set_tui_mode(true);
430
431            let base = "Output a session handoff briefing in at most 300 lines. \
432                 Do NOT use any tools. Include: the FULL ABSOLUTE PATH of every \
433                 project/repository being worked on (e.g. /Projects/Foo/bar — never \
434                 omit the leading path), all project/task/workstream UUIDs referenced, \
435                 every file created or modified with its full absolute path, all \
436                 commands run and their outcomes, the current state of the work, any \
437                 blockers, and the exact next action to take. \
438                 Output ONLY the briefing text — no preamble, headers, or closing remarks.";
439            let prompt = if hint.is_empty() {
440                base.to_string()
441            } else {
442                format!("{base}\n\nIn the briefing also consider: {hint}")
443            };
444
445            let (dummy_tx, _dummy_rx) = mpsc::unbounded_channel();
446
447            // Build RunContext for stateless operation
448            let run_ctx = RunContext::new()
449                .with_agent_name(agent_name.clone());
450            #[cfg(feature = "registry-mcp-token")]
451            {
452                // Note: token_store not available in handoff — handoffs don't
453                // need MCP credentials, so we skip it here.
454            }
455
456            let _res = abk::cli::run_task_from_raw_config(
457                &config_toml,
458                secrets,
459                build_info,
460                &prompt,
461                Some(cap_sink),
462                resume_info,
463                Some(dummy_tx),
464                Some(child_token),
465                Some(&run_ctx),
466            )
467            .await;
468
469            abk::observability::set_tui_mode(false);
470
471            let mut text_parts = String::new();
472            let mut reasoning_parts = String::new();
473            while let Ok(captured) = cap_rx.try_recv() {
474                match captured {
475                    CapturedText::Text(s) => text_parts.push_str(&s),
476                    CapturedText::Reasoning(s) => reasoning_parts.push_str(&s),
477                }
478            }
479
480            let briefing = if !text_parts.trim().is_empty() {
481                text_parts.trim().to_string()
482            } else if !reasoning_parts.trim().is_empty() {
483                reasoning_parts.trim().to_string()
484            } else {
485                "Session handoff: briefing unavailable — continue from previous context.".to_string()
486            };
487
488            tx.send(TuiMessage::HandoffReady(briefing)).ok();
489        });
490    }
491}
492
493impl Default for Session {
494    fn default() -> Self {
495        Self::new().0
496    }
497}
498
499/// A sink that forwards ABK `OutputEvent`s to the message channel.
500///
501/// Includes a 3-state atomic state machine (IDLE/REASONING/CONTENT) that
502/// inserts blank separator lines when transitioning between reasoning and
503/// content streams, so the frontend can distinguish them visually.
504pub struct TuiForwardSink {
505    tx: mpsc::UnboundedSender<TuiMessage>,
506    stream_state: AtomicU8,
507}
508
509/// Stream state machine constants.
510const STREAM_IDLE: u8 = 0;
511const STREAM_REASONING: u8 = 1;
512const STREAM_CONTENT: u8 = 2;
513
514impl TuiForwardSink {
515    pub fn new(tx: mpsc::UnboundedSender<TuiMessage>) -> Self {
516        Self {
517            tx,
518            stream_state: AtomicU8::new(STREAM_IDLE),
519        }
520    }
521}
522
523impl abk::orchestration::output::OutputSink for TuiForwardSink {
524    fn emit(&self, event: abk::orchestration::output::OutputEvent) {
525        use abk::orchestration::output::OutputEvent;
526
527        let msg = match event {
528            OutputEvent::StreamingChunk { delta } => {
529                if delta.is_empty() {
530                    return;
531                }
532                let prev = self.stream_state.swap(STREAM_CONTENT, Ordering::Relaxed);
533                if prev != STREAM_CONTENT {
534                    let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
535                }
536                let _ = self.tx.send(TuiMessage::StreamDelta(delta));
537                return;
538            }
539
540            OutputEvent::LlmResponse { text, model } => {
541                TuiMessage::OutputLine(format!("[{}] {}", model, text))
542            }
543
544            OutputEvent::Info { message } => {
545                // Suppress noisy/no-value messages from ABK
546                if message.contains("API call completed successfully") {
547                    return;
548                }
549                TuiMessage::OutputLine(message)
550            }
551
552            OutputEvent::WorkflowStarted { task_description } => {
553                TuiMessage::OutputLine(format!("🚀 Workflow started: {}", task_description))
554            }
555
556            OutputEvent::WorkflowCompleted { reason, iterations } => {
557                TuiMessage::OutputLine(format!(
558                    "✅ Workflow completed after {} iterations: {}",
559                    iterations, reason
560                ))
561            }
562
563            OutputEvent::IterationStarted { iteration, context_tokens } => {
564                let _ = self.tx.send(TuiMessage::ContextTokensUpdated(context_tokens));
565                TuiMessage::OutputLine(format!(
566                    "📡 Iteration {} | Context = {} tokens",
567                    iteration, context_tokens
568                ))
569            }
570
571            OutputEvent::ApiCallStarted {
572                call_number,
573                model,
574                tool_count,
575                streaming,
576                context_tokens,
577                tool_tokens,
578            } => {
579                let mode = if streaming { "Streaming" } else { "Non-streaming" };
580                let total = context_tokens + tool_tokens;
581                let _ = self.tx.send(TuiMessage::ContextTokensUpdated(total));
582                // Blank line separator before each API call for readability
583                let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
584                TuiMessage::OutputLine(format!(
585                    "🔥 API Call {} | Ctx={}({}+{}) | {} | Model: {} | Tools: {}",
586                    call_number, total, context_tokens, tool_tokens, mode, model, tool_count
587                ))
588            }
589
590            OutputEvent::ToolsExecuting { tool_names, hints } => {
591                for (name, hint) in tool_names.into_iter().zip(hints.into_iter()) {
592                    let _ = self.tx.send(TuiMessage::ToolPending { tool_name: name, hint });
593                }
594                self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
595                return;
596            }
597
598            OutputEvent::ToolCompleted {
599                tool_name,
600                success,
601                content,
602                description,
603            } => {
604                if tool_name == "todowrite" && success {
605                    let _ = self.tx.send(TuiMessage::TodoUpdate(content.clone()));
606                }
607                let hint = description;
608                let _ = self.tx.send(TuiMessage::ToolDone { tool_name, success, hint });
609                self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
610                return;
611            }
612
613            OutputEvent::Error { message, context } => {
614                if let Some(ctx) = context {
615                    TuiMessage::OutputLine(format!("❌ Error: {} — {}", message, ctx))
616                } else {
617                    TuiMessage::OutputLine(format!("❌ Error: {}", message))
618                }
619            }
620
621            OutputEvent::ReasoningChunk { delta } => {
622                if delta.is_empty() {
623                    return;
624                }
625                let prev = self.stream_state.swap(STREAM_REASONING, Ordering::Relaxed);
626                if prev != STREAM_REASONING {
627                    let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
628                }
629                let _ = self.tx.send(TuiMessage::ReasoningDelta(delta));
630                return;
631            }
632
633            OutputEvent::McpServerStatus { name, connected, tool_count, error } => {
634                let _ = self.tx.send(TuiMessage::McpServerStatus {
635                    name,
636                    connected,
637                    tool_count,
638                    error,
639                });
640                return;
641            }
642        };
643
644        self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
645        let _ = self.tx.send(msg);
646    }
647}