Skip to main content

mermaid_cli/domain/
cmd.rs

1//! Everything the reducer asks the outside world to do.
2//!
3//! `Cmd` values are inert data structures. The reducer returns them
4//! alongside each new `State`; `effect::EffectRunner::dispatch` then
5//! turns them into real work (spawning tokio tasks, writing files,
6//! hitting HTTP endpoints, killing processes). The reducer itself
7//! never performs any I/O.
8//!
9//! This is the "effects as data" pattern from Elm/Redux. Three
10//! payoffs this rewrite relies on:
11//!
12//!   1. **Testable reducer.** Assertions are `state, cmds = update(...)
13//!      ; assert_eq!(cmds[0], Cmd::CallModel { … })`. No tokio, no
14//!      mocks, no filesystem.
15//!   2. **Uniform middleware.** Retry, tracing, rate-limiting wrap the
16//!      dispatcher once instead of being re-implemented per adapter.
17//!   3. **Replayable sessions.** `--record` dumps every `Msg`; the
18//!      effects the reducer asked for are fully determined by the Msg
19//!      log + initial state, so `--replay` is a pure fold.
20
21use std::collections::HashMap;
22use std::path::PathBuf;
23
24use crate::app::McpServerConfig;
25use crate::models::ChatMessage;
26use crate::models::ReasoningLevel;
27use crate::models::tool_call::ToolCall as ModelToolCall;
28use crate::runtime::{SafetyMode, TaskStatus};
29use crate::session::ConversationHistory;
30
31use super::state::ApprovalChoice;
32
33use super::compaction::{CompactionArchive, CompactionRecord, CompactionRequest};
34use super::ids::{ToolCallId, TurnId};
35use super::runtime::ManagedProcess;
36
37/// A single side-effect request. Most variants are one-shot; `CallModel`
38/// and `ExecuteTool` spawn long-running tasks inside a per-turn
39/// `TurnScope`.
40// Several variants legitimately carry large payloads (a full
41// `ConversationHistory` / `ChatRequest`). Boxing them would churn ~20
42// construction + match sites for no real gain — `Cmd` values are short-lived
43// and moved, not stored in bulk.
44#[allow(clippy::large_enum_variant)]
45#[derive(Debug, Clone)]
46pub enum Cmd {
47    // ── Model + tool execution (the scope-spawning variants) ────────
48    /// Dispatch the next chat request. Effect runner maps this onto
49    /// `ModelProvider::chat` for the session's active provider.
50    CallModel { turn: TurnId, request: ChatRequest },
51    /// Generate a compact context checkpoint without continuing into
52    /// a normal assistant turn.
53    CompactConversation {
54        turn: TurnId,
55        request: CompactionRequest,
56    },
57    /// Run one tool in parallel with any other tools in the same turn.
58    /// The runner wires `ExecContext::token` to the turn's scope so
59    /// `Cmd::CancelScope` aborts them all at once.
60    ///
61    /// `model_id` is the active session's model id at the moment this
62    /// tool call was emitted. The runner passes it into `ExecContext`
63    /// so tools like `SubagentTool` can spawn children against the
64    /// same provider the parent is using.
65    ExecuteTool {
66        turn: TurnId,
67        call_id: ToolCallId,
68        source: ModelToolCall,
69        model_id: String,
70        /// Effective live safety mode (from `state.session.safety_mode`) at
71        /// the moment this call was emitted. The runner builds the policy
72        /// gate / Auto classifier from this rather than the static config.
73        safety_mode: SafetyMode,
74        /// The user's stated intent for the turn (latest user message),
75        /// passed to the Auto-mode classifier as alignment context.
76        intent: Option<String>,
77    },
78    /// Cancel every task in the given turn's `TurnScope`. After the
79    /// scope drains, the runner emits a `Msg::StreamDone` (with a
80    /// synthetic "cancelled" marker in usage, or a batch of
81    /// `ToolFinished { outcome: Cancelled }` for tools already running)
82    /// so the reducer can transition back to `Idle`.
83    CancelScope(TurnId),
84    /// Ctrl+B: signal the turn's scope to BACKGROUND (not cancel) its running
85    /// work. The scope's background token fires; detachable tools (execute_
86    /// command) move their child to a background process and return. The scope
87    /// is left intact (unlike `CancelScope`).
88    BackgroundScope(TurnId),
89
90    /// Resolve an inline approval prompt: deliver the user's decision to the
91    /// parked tool task via the `ApprovalBroker`. NOT turn-scoped — it's a
92    /// fire-and-forget to the broker (the tool task it unblocks is the
93    /// turn-scoped work).
94    ResolveApproval {
95        call_id: ToolCallId,
96        decision: ApprovalChoice,
97    },
98
99    // ── Persistence ─────────────────────────────────────────────────
100    /// Save the current conversation to disk. No-op if unchanged since
101    /// last save (effect-side idempotence).
102    SaveConversation(ConversationHistory),
103    /// Persist the raw messages removed by a compaction, then the compacted
104    /// (message-stripped) conversation. Both are written by ONE effect task,
105    /// archive first — only overwriting the conversation if the archive
106    /// persisted — so a failed/lagging archive can never lose messages while
107    /// the stripped conversation is saved over the old one.
108    SaveCompactionArchive {
109        archive: CompactionArchive,
110        record: CompactionRecord,
111        conversation: ConversationHistory,
112    },
113    /// Persist a daemon-visible background process record.
114    SaveProcess(ManagedProcess),
115    /// Persist the active model ID as `last_used_model`.
116    PersistLastModel(String),
117    /// Persist reasoning level tied to a specific model ID.
118    PersistReasoningFor {
119        model_id: String,
120        level: ReasoningLevel,
121    },
122    /// Re-stat `MERMAID.md` (cheap); emits `Msg::InstructionsChanged`
123    /// only when the mtime moved or the file appeared/disappeared.
124    RefreshInstructions,
125    /// Re-scan the memory directories (cheap); emits `Msg::MemoryChanged`.
126    RefreshMemory,
127    /// List saved memories; emits `Msg::RuntimeText` with the rendered list.
128    ListMemory,
129    /// Save free-text to private memory; emits `Msg::MemoryChanged` + status.
130    RememberMemory { text: String },
131    /// Delete a memory by name/id; emits `Msg::MemoryChanged` + status.
132    ForgetMemory { id: String },
133    /// Model-assisted prune of duplicate/obsolete memories, reversible via a
134    /// checkpoint. Emits `Msg::RuntimeText` (the report) + `Msg::MemoryChanged`.
135    ConsolidateMemory { model_id: String },
136    /// Load a specific conversation by ID and emit
137    /// `Msg::ConversationLoaded`. Reducer consumes that event to
138    /// replace the current session.
139    LoadConversation(String),
140    /// Scan the conversations directory for the /load picker. Emits
141    /// `Msg::ConversationsListed` with one `ConversationSummary` per
142    /// saved session (newest first). The reducer transitions to
143    /// `UiMode::ConversationList` and the render shows the picker.
144    ListConversations,
145    /// List durable daemon/runtime tasks.
146    ListRuntimeTasks { limit: usize },
147    /// Load one durable daemon/runtime task and its timeline.
148    LoadRuntimeTask { id: String },
149    /// List durable daemon/runtime background processes.
150    ListRuntimeProcesses { limit: usize },
151    /// Print one durable process log into the conversation.
152    ShowRuntimeProcessLogs { id: String },
153    /// Stop a durable process by pid.
154    StopRuntimeProcess { id: String },
155    /// Restart a durable process using its recorded command/cwd.
156    RestartRuntimeProcess { id: String },
157    /// Open a URL, path, or process target.
158    OpenRuntimeTarget { target: String },
159    /// Show listening ports.
160    ShowRuntimePorts,
161    /// List pending approval records.
162    ListRuntimeApprovals,
163    /// Mark one approval as approved or denied.
164    DecideRuntimeApproval { id: String, decision: String },
165    /// List restore checkpoints.
166    ListRuntimeCheckpoints { limit: usize },
167    /// List installed plugins.
168    ListRuntimePlugins,
169    /// Update one durable task's status.
170    UpdateRuntimeTaskStatus {
171        id: String,
172        status: TaskStatus,
173        final_report: Option<String>,
174    },
175    /// Create a shadow checkpoint for explicit paths.
176    CreateRuntimeCheckpoint { paths: Vec<PathBuf> },
177    /// Restore files from a shadow checkpoint.
178    RestoreRuntimeCheckpoint { id: String },
179    /// Show provider/model capability information.
180    ShowRuntimeModelInfo { model: String },
181
182    // ── MCP lifecycle ───────────────────────────────────────────────
183    /// Start every configured MCP server; each one emits
184    /// `Msg::McpServerReady` or `Msg::McpServerErrored` as it comes up.
185    InitMcpServers(HashMap<String, McpServerConfig>),
186    /// Stop a running server (e.g. config was removed, or app quit).
187    StopMcpServer { name: String },
188
189    // ── Ollama helpers ──────────────────────────────────────────────
190    /// `ollama pull <model>` with progress → `Msg::ModelPullFinished`.
191    PullOllamaModel { model: String },
192
193    // ── UI side-effects (cross-process) ─────────────────────────────
194    /// `xdg-open` / `open` / `start` on a file path. Used by the
195    /// image-paste preview and the "open in editor" affordance.
196    OpenInSystem(PathBuf),
197
198    // ── Status line ─────────────────────────────────────────────────
199    /// Schedule `Msg::StatusDismiss` after `ms` milliseconds. Reducer
200    /// uses this to self-clear transient status lines.
201    DismissStatusAfter { ms: u64 },
202
203    // ── Attachments ─────────────────────────────────────────────────
204    /// Persist a pasted image to a temp file so the TUI can open it
205    /// via `OpenInSystem`. Emits no follow-up Msg on success; failure
206    /// is a log-and-drop.
207    WriteImageToTemp {
208        path: PathBuf,
209        bytes: Vec<u8>,
210        format: String,
211    },
212
213    /// Read the system clipboard on a blocking task. The per-platform
214    /// dispatch (xclip / wl-paste / pngpaste / PowerShell) can block
215    /// for hundreds of ms on macOS via osascript, so it never runs on
216    /// the reducer thread. Emits `Msg::Paste(Paste::Image|Text)` on
217    /// success; `Msg::TransientStatus` when the clipboard is empty or
218    /// the read fails.
219    ReadClipboard,
220
221    /// Write text to the system clipboard on a blocking task (mirrors
222    /// `ReadClipboard`'s per-platform dispatch). Used by in-app drag-select
223    /// copy. Emits a `Msg::TransientStatus` ("Copied N chars" / failure).
224    CopyToClipboard(String),
225
226    // ── Terminal lifecycle ──────────────────────────────────────────
227    /// Exit the main loop. No reply message — the loop observes
228    /// `state.should_exit` after the reducer returns and breaks out.
229    Exit,
230    /// Write the OSC 2 terminal-title sequence. Reducer diffs
231    /// against `ui.last_title_dispatched` so this only fires on
232    /// actual title changes, not every frame.
233    SetTerminalTitle(String),
234}
235
236/// Inputs a model needs to generate a turn. Built by the reducer from
237/// `Session` + `Settings` + current `MERMAID.md` context. Pure data —
238/// no provider-specific knowledge here (that's in
239/// `providers::model::*::chat`).
240#[derive(Debug, Clone)]
241pub struct ChatRequest {
242    pub model_id: String,
243    pub messages: Vec<ChatMessage>,
244    pub system_prompt: String,
245    /// `MERMAID.md` content to suffix onto the system prompt. `None` if
246    /// no file was loaded for this project.
247    pub instructions: Option<String>,
248    pub reasoning: ReasoningLevel,
249    pub temperature: f32,
250    pub max_tokens: usize,
251    /// Tool definitions advertised to the model. Combination of the
252    /// built-in tool set + any advertised MCP tools from `McpState`.
253    pub tools: Vec<ToolDefinition>,
254}
255
256/// Provider-agnostic tool definition sent in the request. Concrete
257/// adapters (`providers::model::ollama`, etc.) translate this into
258/// whatever wire shape their API expects.
259#[derive(Debug, Clone)]
260pub struct ToolDefinition {
261    pub name: String,
262    pub description: String,
263    pub input_schema: serde_json::Value,
264}
265
266impl ToolDefinition {
267    /// Wire shape: `{type: "function", function: {name, description,
268    /// parameters}}`. This is the OpenAI / Ollama Chat Completions
269    /// format; Anthropic and Gemini adapters translate further from
270    /// here. Single-canonical-shape keeps adapters from drifting.
271    pub fn to_openai_json(&self) -> serde_json::Value {
272        serde_json::json!({
273            "type": "function",
274            "function": {
275                "name": self.name,
276                "description": self.description,
277                "parameters": self.input_schema,
278            }
279        })
280    }
281}
282
283impl Cmd {
284    /// Human-readable tag, for tracing + replay logs. Stable across
285    /// refactors (tests assert against it).
286    pub fn tag(&self) -> &'static str {
287        match self {
288            Cmd::CallModel { .. } => "call_model",
289            Cmd::CompactConversation { .. } => "compact_conversation",
290            Cmd::ExecuteTool { .. } => "execute_tool",
291            Cmd::CancelScope(_) => "cancel_scope",
292            Cmd::BackgroundScope(_) => "background_scope",
293            Cmd::ResolveApproval { .. } => "resolve_approval",
294            Cmd::SaveConversation(_) => "save_conversation",
295            Cmd::SaveCompactionArchive { .. } => "save_compaction_archive",
296            Cmd::SaveProcess(_) => "save_process",
297            Cmd::PersistLastModel(_) => "persist_last_model",
298            Cmd::PersistReasoningFor { .. } => "persist_reasoning_for",
299            Cmd::RefreshInstructions => "refresh_instructions",
300            Cmd::RefreshMemory => "refresh_memory",
301            Cmd::ListMemory => "list_memory",
302            Cmd::RememberMemory { .. } => "remember_memory",
303            Cmd::ForgetMemory { .. } => "forget_memory",
304            Cmd::ConsolidateMemory { .. } => "consolidate_memory",
305            Cmd::LoadConversation(_) => "load_conversation",
306            Cmd::ListConversations => "list_conversations",
307            Cmd::ListRuntimeTasks { .. } => "list_runtime_tasks",
308            Cmd::LoadRuntimeTask { .. } => "load_runtime_task",
309            Cmd::ListRuntimeProcesses { .. } => "list_runtime_processes",
310            Cmd::ShowRuntimeProcessLogs { .. } => "show_runtime_process_logs",
311            Cmd::StopRuntimeProcess { .. } => "stop_runtime_process",
312            Cmd::RestartRuntimeProcess { .. } => "restart_runtime_process",
313            Cmd::OpenRuntimeTarget { .. } => "open_runtime_target",
314            Cmd::ShowRuntimePorts => "show_runtime_ports",
315            Cmd::ListRuntimeApprovals => "list_runtime_approvals",
316            Cmd::DecideRuntimeApproval { .. } => "decide_runtime_approval",
317            Cmd::ListRuntimeCheckpoints { .. } => "list_runtime_checkpoints",
318            Cmd::ListRuntimePlugins => "list_runtime_plugins",
319            Cmd::UpdateRuntimeTaskStatus { .. } => "update_runtime_task_status",
320            Cmd::CreateRuntimeCheckpoint { .. } => "create_runtime_checkpoint",
321            Cmd::RestoreRuntimeCheckpoint { .. } => "restore_runtime_checkpoint",
322            Cmd::ShowRuntimeModelInfo { .. } => "show_runtime_model_info",
323            Cmd::InitMcpServers(_) => "init_mcp_servers",
324            Cmd::StopMcpServer { .. } => "stop_mcp_server",
325            Cmd::PullOllamaModel { .. } => "pull_ollama_model",
326            Cmd::OpenInSystem(_) => "open_in_system",
327            Cmd::DismissStatusAfter { .. } => "dismiss_status_after",
328            Cmd::WriteImageToTemp { .. } => "write_image_to_temp",
329            Cmd::ReadClipboard => "read_clipboard",
330            Cmd::CopyToClipboard(_) => "copy_to_clipboard",
331            Cmd::Exit => "exit",
332            Cmd::SetTerminalTitle(_) => "set_terminal_title",
333        }
334    }
335
336    /// True iff this command needs to run inside a `TurnScope` so it
337    /// can be cancelled by `Cmd::CancelScope`. The effect runner uses
338    /// this to decide between "spawn into `JoinSet`" and "spawn detached".
339    pub fn is_turn_scoped(&self) -> bool {
340        matches!(
341            self,
342            Cmd::CallModel { .. } | Cmd::CompactConversation { .. } | Cmd::ExecuteTool { .. }
343        )
344    }
345
346    /// For traces + the `--record` file — some `Cmd` payloads are huge
347    /// (think `ChatRequest::messages`). This returns a compact
348    /// identifier that doesn't dump the full payload.
349    pub fn summary(&self) -> String {
350        match self {
351            Cmd::CallModel { turn, request } => format!(
352                "call_model(turn={}, model={}, msgs={})",
353                turn,
354                request.model_id,
355                request.messages.len()
356            ),
357            Cmd::CompactConversation { turn, request } => format!(
358                "compact_conversation(turn={}, model={}, trigger={}, msgs={})",
359                turn,
360                request.chat.model_id,
361                request.trigger.as_str(),
362                request.chat.messages.len()
363            ),
364            Cmd::ExecuteTool {
365                turn,
366                call_id,
367                source,
368                ..
369            } => format!(
370                "execute_tool(turn={}, call={}, fn={})",
371                turn, call_id, source.function.name
372            ),
373            Cmd::CancelScope(turn) => format!("cancel_scope(turn={})", turn),
374            Cmd::BackgroundScope(turn) => format!("background_scope(turn={})", turn),
375            Cmd::ResolveApproval { call_id, decision } => {
376                format!("resolve_approval(call={}, {:?})", call_id, decision)
377            },
378            Cmd::SaveConversation(c) => format!("save_conversation(id={})", c.id),
379            Cmd::SaveCompactionArchive {
380                archive, record, ..
381            } => format!(
382                "save_compaction_archive(conversation={}, id={})",
383                archive.conversation_id, record.id
384            ),
385            Cmd::SaveProcess(p) => format!("save_process(id={}, pid={})", p.id, p.pid),
386            Cmd::PersistLastModel(m) => format!("persist_last_model({})", m),
387            Cmd::PersistReasoningFor { model_id, level } => {
388                format!("persist_reasoning_for({}, {:?})", model_id, level)
389            },
390            Cmd::RefreshInstructions => "refresh_instructions".to_string(),
391            Cmd::RefreshMemory => "refresh_memory".to_string(),
392            Cmd::ListMemory => "list_memory".to_string(),
393            Cmd::RememberMemory { .. } => "remember_memory".to_string(),
394            Cmd::ForgetMemory { .. } => "forget_memory".to_string(),
395            Cmd::ConsolidateMemory { .. } => "consolidate_memory".to_string(),
396            Cmd::LoadConversation(id) => format!("load_conversation({})", id),
397            Cmd::ListConversations => "list_conversations".to_string(),
398            Cmd::ListRuntimeTasks { limit } => format!("list_runtime_tasks(limit={})", limit),
399            Cmd::LoadRuntimeTask { id } => format!("load_runtime_task({})", id),
400            Cmd::ListRuntimeProcesses { limit } => {
401                format!("list_runtime_processes(limit={})", limit)
402            },
403            Cmd::ShowRuntimeProcessLogs { id } => format!("show_runtime_process_logs({})", id),
404            Cmd::StopRuntimeProcess { id } => format!("stop_runtime_process({})", id),
405            Cmd::RestartRuntimeProcess { id } => format!("restart_runtime_process({})", id),
406            Cmd::OpenRuntimeTarget { target } => format!("open_runtime_target({})", target),
407            Cmd::ShowRuntimePorts => "show_runtime_ports".to_string(),
408            Cmd::ListRuntimeApprovals => "list_runtime_approvals".to_string(),
409            Cmd::DecideRuntimeApproval { id, decision } => {
410                format!("decide_runtime_approval({}, {})", id, decision)
411            },
412            Cmd::ListRuntimeCheckpoints { limit } => {
413                format!("list_runtime_checkpoints(limit={})", limit)
414            },
415            Cmd::ListRuntimePlugins => "list_runtime_plugins".to_string(),
416            Cmd::UpdateRuntimeTaskStatus { id, status, .. } => {
417                format!("update_runtime_task_status({}, {})", id, status)
418            },
419            Cmd::CreateRuntimeCheckpoint { paths } => {
420                format!("create_runtime_checkpoint(n={})", paths.len())
421            },
422            Cmd::RestoreRuntimeCheckpoint { id } => format!("restore_runtime_checkpoint({})", id),
423            Cmd::ShowRuntimeModelInfo { model } => format!("show_runtime_model_info({})", model),
424            Cmd::InitMcpServers(m) => format!("init_mcp_servers(n={})", m.len()),
425            Cmd::StopMcpServer { name } => format!("stop_mcp_server({})", name),
426            Cmd::PullOllamaModel { model } => format!("pull_ollama_model({})", model),
427            Cmd::OpenInSystem(p) => format!("open_in_system({})", p.display()),
428            Cmd::DismissStatusAfter { ms } => format!("dismiss_status_after({}ms)", ms),
429            Cmd::WriteImageToTemp {
430                path,
431                format,
432                bytes,
433            } => format!(
434                "write_image_to_temp(path={}, fmt={}, n={})",
435                path.display(),
436                format,
437                bytes.len()
438            ),
439            Cmd::ReadClipboard => "read_clipboard".to_string(),
440            Cmd::CopyToClipboard(t) => format!("copy_to_clipboard(n={})", t.chars().count()),
441            Cmd::Exit => "exit".to_string(),
442            Cmd::SetTerminalTitle(t) => format!("set_terminal_title({})", t),
443        }
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    #[test]
452    fn turn_scoped_variants_marked_correctly() {
453        let request = ChatRequest {
454            model_id: "m".to_string(),
455            messages: vec![],
456            system_prompt: String::new(),
457            instructions: None,
458            reasoning: ReasoningLevel::Medium,
459            temperature: 0.7,
460            max_tokens: 4096,
461            tools: vec![],
462        };
463        assert!(
464            Cmd::CallModel {
465                turn: TurnId(1),
466                request,
467            }
468            .is_turn_scoped()
469        );
470        assert!(
471            !Cmd::SaveConversation(ConversationHistory::new("/p".to_string(), "m".to_string()))
472                .is_turn_scoped()
473        );
474        assert!(!Cmd::RefreshInstructions.is_turn_scoped());
475        assert!(!Cmd::Exit.is_turn_scoped());
476    }
477
478    #[test]
479    fn cmd_tags_are_stable() {
480        assert_eq!(Cmd::Exit.tag(), "exit");
481        assert_eq!(Cmd::RefreshInstructions.tag(), "refresh_instructions");
482        assert_eq!(Cmd::CancelScope(TurnId(1)).tag(), "cancel_scope");
483    }
484
485    #[test]
486    fn cmd_summary_includes_identifying_fields() {
487        let c = Cmd::CancelScope(TurnId(42));
488        let s = c.summary();
489        assert!(s.contains("turn#42"));
490    }
491}