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
85    /// Resolve an inline approval prompt: deliver the user's decision to the
86    /// parked tool task via the `ApprovalBroker`. NOT turn-scoped — it's a
87    /// fire-and-forget to the broker (the tool task it unblocks is the
88    /// turn-scoped work).
89    ResolveApproval {
90        call_id: ToolCallId,
91        decision: ApprovalChoice,
92    },
93
94    // ── Persistence ─────────────────────────────────────────────────
95    /// Save the current conversation to disk. No-op if unchanged since
96    /// last save (effect-side idempotence).
97    SaveConversation(ConversationHistory),
98    /// Persist the raw messages removed by a compaction, then the compacted
99    /// (message-stripped) conversation. Both are written by ONE effect task,
100    /// archive first — only overwriting the conversation if the archive
101    /// persisted — so a failed/lagging archive can never lose messages while
102    /// the stripped conversation is saved over the old one.
103    SaveCompactionArchive {
104        archive: CompactionArchive,
105        record: CompactionRecord,
106        conversation: ConversationHistory,
107    },
108    /// Persist a daemon-visible background process record.
109    SaveProcess(ManagedProcess),
110    /// Persist the active model ID as `last_used_model`.
111    PersistLastModel(String),
112    /// Persist reasoning level tied to a specific model ID.
113    PersistReasoningFor {
114        model_id: String,
115        level: ReasoningLevel,
116    },
117    /// Re-stat `MERMAID.md` (cheap); emits `Msg::InstructionsChanged`
118    /// only when the mtime moved or the file appeared/disappeared.
119    RefreshInstructions,
120    /// Re-scan the memory directories (cheap); emits `Msg::MemoryChanged`.
121    RefreshMemory,
122    /// List saved memories; emits `Msg::RuntimeText` with the rendered list.
123    ListMemory,
124    /// Save free-text to private memory; emits `Msg::MemoryChanged` + status.
125    RememberMemory { text: String },
126    /// Delete a memory by name/id; emits `Msg::MemoryChanged` + status.
127    ForgetMemory { id: String },
128    /// Model-assisted prune of duplicate/obsolete memories, reversible via a
129    /// checkpoint. Emits `Msg::RuntimeText` (the report) + `Msg::MemoryChanged`.
130    ConsolidateMemory { model_id: String },
131    /// Load a specific conversation by ID and emit
132    /// `Msg::ConversationLoaded`. Reducer consumes that event to
133    /// replace the current session.
134    LoadConversation(String),
135    /// Scan the conversations directory for the /load picker. Emits
136    /// `Msg::ConversationsListed` with one `ConversationSummary` per
137    /// saved session (newest first). The reducer transitions to
138    /// `UiMode::ConversationList` and the render shows the picker.
139    ListConversations,
140    /// List durable daemon/runtime tasks.
141    ListRuntimeTasks { limit: usize },
142    /// Load one durable daemon/runtime task and its timeline.
143    LoadRuntimeTask { id: String },
144    /// List durable daemon/runtime background processes.
145    ListRuntimeProcesses { limit: usize },
146    /// Print one durable process log into the conversation.
147    ShowRuntimeProcessLogs { id: String },
148    /// Stop a durable process by pid.
149    StopRuntimeProcess { id: String },
150    /// Restart a durable process using its recorded command/cwd.
151    RestartRuntimeProcess { id: String },
152    /// Open a URL, path, or process target.
153    OpenRuntimeTarget { target: String },
154    /// Show listening ports.
155    ShowRuntimePorts,
156    /// List pending approval records.
157    ListRuntimeApprovals,
158    /// Mark one approval as approved or denied.
159    DecideRuntimeApproval { id: String, decision: String },
160    /// List restore checkpoints.
161    ListRuntimeCheckpoints { limit: usize },
162    /// List installed plugins.
163    ListRuntimePlugins,
164    /// Update one durable task's status.
165    UpdateRuntimeTaskStatus {
166        id: String,
167        status: TaskStatus,
168        final_report: Option<String>,
169    },
170    /// Create a shadow checkpoint for explicit paths.
171    CreateRuntimeCheckpoint { paths: Vec<PathBuf> },
172    /// Restore files from a shadow checkpoint.
173    RestoreRuntimeCheckpoint { id: String },
174    /// Show provider/model capability information.
175    ShowRuntimeModelInfo { model: String },
176
177    // ── MCP lifecycle ───────────────────────────────────────────────
178    /// Start every configured MCP server; each one emits
179    /// `Msg::McpServerReady` or `Msg::McpServerErrored` as it comes up.
180    InitMcpServers(HashMap<String, McpServerConfig>),
181    /// Stop a running server (e.g. config was removed, or app quit).
182    StopMcpServer { name: String },
183
184    // ── Ollama helpers ──────────────────────────────────────────────
185    /// `ollama pull <model>` with progress → `Msg::ModelPullFinished`.
186    PullOllamaModel { model: String },
187
188    // ── UI side-effects (cross-process) ─────────────────────────────
189    /// `xdg-open` / `open` / `start` on a file path. Used by the
190    /// image-paste preview and the "open in editor" affordance.
191    OpenInSystem(PathBuf),
192
193    // ── Status line ─────────────────────────────────────────────────
194    /// Schedule `Msg::StatusDismiss` after `ms` milliseconds. Reducer
195    /// uses this to self-clear transient status lines.
196    DismissStatusAfter { ms: u64 },
197
198    // ── Attachments ─────────────────────────────────────────────────
199    /// Persist a pasted image to a temp file so the TUI can open it
200    /// via `OpenInSystem`. Emits no follow-up Msg on success; failure
201    /// is a log-and-drop.
202    WriteImageToTemp {
203        path: PathBuf,
204        bytes: Vec<u8>,
205        format: String,
206    },
207
208    /// Read the system clipboard on a blocking task. The per-platform
209    /// dispatch (xclip / wl-paste / pngpaste / PowerShell) can block
210    /// for hundreds of ms on macOS via osascript, so it never runs on
211    /// the reducer thread. Emits `Msg::Paste(Paste::Image|Text)` on
212    /// success; `Msg::TransientStatus` when the clipboard is empty or
213    /// the read fails.
214    ReadClipboard,
215
216    /// Write text to the system clipboard on a blocking task (mirrors
217    /// `ReadClipboard`'s per-platform dispatch). Used by in-app drag-select
218    /// copy. Emits a `Msg::TransientStatus` ("Copied N chars" / failure).
219    CopyToClipboard(String),
220
221    // ── Terminal lifecycle ──────────────────────────────────────────
222    /// Exit the main loop. No reply message — the loop observes
223    /// `state.should_exit` after the reducer returns and breaks out.
224    Exit,
225    /// Write the OSC 2 terminal-title sequence. Reducer diffs
226    /// against `ui.last_title_dispatched` so this only fires on
227    /// actual title changes, not every frame.
228    SetTerminalTitle(String),
229}
230
231/// Inputs a model needs to generate a turn. Built by the reducer from
232/// `Session` + `Settings` + current `MERMAID.md` context. Pure data —
233/// no provider-specific knowledge here (that's in
234/// `providers::model::*::chat`).
235#[derive(Debug, Clone)]
236pub struct ChatRequest {
237    pub model_id: String,
238    pub messages: Vec<ChatMessage>,
239    pub system_prompt: String,
240    /// `MERMAID.md` content to suffix onto the system prompt. `None` if
241    /// no file was loaded for this project.
242    pub instructions: Option<String>,
243    pub reasoning: ReasoningLevel,
244    pub temperature: f32,
245    pub max_tokens: usize,
246    /// Tool definitions advertised to the model. Combination of the
247    /// built-in tool set + any advertised MCP tools from `McpState`.
248    pub tools: Vec<ToolDefinition>,
249}
250
251/// Provider-agnostic tool definition sent in the request. Concrete
252/// adapters (`providers::model::ollama`, etc.) translate this into
253/// whatever wire shape their API expects.
254#[derive(Debug, Clone)]
255pub struct ToolDefinition {
256    pub name: String,
257    pub description: String,
258    pub input_schema: serde_json::Value,
259}
260
261impl ToolDefinition {
262    /// Wire shape: `{type: "function", function: {name, description,
263    /// parameters}}`. This is the OpenAI / Ollama Chat Completions
264    /// format; Anthropic and Gemini adapters translate further from
265    /// here. Single-canonical-shape keeps adapters from drifting.
266    pub fn to_openai_json(&self) -> serde_json::Value {
267        serde_json::json!({
268            "type": "function",
269            "function": {
270                "name": self.name,
271                "description": self.description,
272                "parameters": self.input_schema,
273            }
274        })
275    }
276}
277
278impl Cmd {
279    /// Human-readable tag, for tracing + replay logs. Stable across
280    /// refactors (tests assert against it).
281    pub fn tag(&self) -> &'static str {
282        match self {
283            Cmd::CallModel { .. } => "call_model",
284            Cmd::CompactConversation { .. } => "compact_conversation",
285            Cmd::ExecuteTool { .. } => "execute_tool",
286            Cmd::CancelScope(_) => "cancel_scope",
287            Cmd::ResolveApproval { .. } => "resolve_approval",
288            Cmd::SaveConversation(_) => "save_conversation",
289            Cmd::SaveCompactionArchive { .. } => "save_compaction_archive",
290            Cmd::SaveProcess(_) => "save_process",
291            Cmd::PersistLastModel(_) => "persist_last_model",
292            Cmd::PersistReasoningFor { .. } => "persist_reasoning_for",
293            Cmd::RefreshInstructions => "refresh_instructions",
294            Cmd::RefreshMemory => "refresh_memory",
295            Cmd::ListMemory => "list_memory",
296            Cmd::RememberMemory { .. } => "remember_memory",
297            Cmd::ForgetMemory { .. } => "forget_memory",
298            Cmd::ConsolidateMemory { .. } => "consolidate_memory",
299            Cmd::LoadConversation(_) => "load_conversation",
300            Cmd::ListConversations => "list_conversations",
301            Cmd::ListRuntimeTasks { .. } => "list_runtime_tasks",
302            Cmd::LoadRuntimeTask { .. } => "load_runtime_task",
303            Cmd::ListRuntimeProcesses { .. } => "list_runtime_processes",
304            Cmd::ShowRuntimeProcessLogs { .. } => "show_runtime_process_logs",
305            Cmd::StopRuntimeProcess { .. } => "stop_runtime_process",
306            Cmd::RestartRuntimeProcess { .. } => "restart_runtime_process",
307            Cmd::OpenRuntimeTarget { .. } => "open_runtime_target",
308            Cmd::ShowRuntimePorts => "show_runtime_ports",
309            Cmd::ListRuntimeApprovals => "list_runtime_approvals",
310            Cmd::DecideRuntimeApproval { .. } => "decide_runtime_approval",
311            Cmd::ListRuntimeCheckpoints { .. } => "list_runtime_checkpoints",
312            Cmd::ListRuntimePlugins => "list_runtime_plugins",
313            Cmd::UpdateRuntimeTaskStatus { .. } => "update_runtime_task_status",
314            Cmd::CreateRuntimeCheckpoint { .. } => "create_runtime_checkpoint",
315            Cmd::RestoreRuntimeCheckpoint { .. } => "restore_runtime_checkpoint",
316            Cmd::ShowRuntimeModelInfo { .. } => "show_runtime_model_info",
317            Cmd::InitMcpServers(_) => "init_mcp_servers",
318            Cmd::StopMcpServer { .. } => "stop_mcp_server",
319            Cmd::PullOllamaModel { .. } => "pull_ollama_model",
320            Cmd::OpenInSystem(_) => "open_in_system",
321            Cmd::DismissStatusAfter { .. } => "dismiss_status_after",
322            Cmd::WriteImageToTemp { .. } => "write_image_to_temp",
323            Cmd::ReadClipboard => "read_clipboard",
324            Cmd::CopyToClipboard(_) => "copy_to_clipboard",
325            Cmd::Exit => "exit",
326            Cmd::SetTerminalTitle(_) => "set_terminal_title",
327        }
328    }
329
330    /// True iff this command needs to run inside a `TurnScope` so it
331    /// can be cancelled by `Cmd::CancelScope`. The effect runner uses
332    /// this to decide between "spawn into `JoinSet`" and "spawn detached".
333    pub fn is_turn_scoped(&self) -> bool {
334        matches!(
335            self,
336            Cmd::CallModel { .. } | Cmd::CompactConversation { .. } | Cmd::ExecuteTool { .. }
337        )
338    }
339
340    /// For traces + the `--record` file — some `Cmd` payloads are huge
341    /// (think `ChatRequest::messages`). This returns a compact
342    /// identifier that doesn't dump the full payload.
343    pub fn summary(&self) -> String {
344        match self {
345            Cmd::CallModel { turn, request } => format!(
346                "call_model(turn={}, model={}, msgs={})",
347                turn,
348                request.model_id,
349                request.messages.len()
350            ),
351            Cmd::CompactConversation { turn, request } => format!(
352                "compact_conversation(turn={}, model={}, trigger={}, msgs={})",
353                turn,
354                request.chat.model_id,
355                request.trigger.as_str(),
356                request.chat.messages.len()
357            ),
358            Cmd::ExecuteTool {
359                turn,
360                call_id,
361                source,
362                ..
363            } => format!(
364                "execute_tool(turn={}, call={}, fn={})",
365                turn, call_id, source.function.name
366            ),
367            Cmd::CancelScope(turn) => format!("cancel_scope(turn={})", turn),
368            Cmd::ResolveApproval { call_id, decision } => {
369                format!("resolve_approval(call={}, {:?})", call_id, decision)
370            },
371            Cmd::SaveConversation(c) => format!("save_conversation(id={})", c.id),
372            Cmd::SaveCompactionArchive {
373                archive, record, ..
374            } => format!(
375                "save_compaction_archive(conversation={}, id={})",
376                archive.conversation_id, record.id
377            ),
378            Cmd::SaveProcess(p) => format!("save_process(id={}, pid={})", p.id, p.pid),
379            Cmd::PersistLastModel(m) => format!("persist_last_model({})", m),
380            Cmd::PersistReasoningFor { model_id, level } => {
381                format!("persist_reasoning_for({}, {:?})", model_id, level)
382            },
383            Cmd::RefreshInstructions => "refresh_instructions".to_string(),
384            Cmd::RefreshMemory => "refresh_memory".to_string(),
385            Cmd::ListMemory => "list_memory".to_string(),
386            Cmd::RememberMemory { .. } => "remember_memory".to_string(),
387            Cmd::ForgetMemory { .. } => "forget_memory".to_string(),
388            Cmd::ConsolidateMemory { .. } => "consolidate_memory".to_string(),
389            Cmd::LoadConversation(id) => format!("load_conversation({})", id),
390            Cmd::ListConversations => "list_conversations".to_string(),
391            Cmd::ListRuntimeTasks { limit } => format!("list_runtime_tasks(limit={})", limit),
392            Cmd::LoadRuntimeTask { id } => format!("load_runtime_task({})", id),
393            Cmd::ListRuntimeProcesses { limit } => {
394                format!("list_runtime_processes(limit={})", limit)
395            },
396            Cmd::ShowRuntimeProcessLogs { id } => format!("show_runtime_process_logs({})", id),
397            Cmd::StopRuntimeProcess { id } => format!("stop_runtime_process({})", id),
398            Cmd::RestartRuntimeProcess { id } => format!("restart_runtime_process({})", id),
399            Cmd::OpenRuntimeTarget { target } => format!("open_runtime_target({})", target),
400            Cmd::ShowRuntimePorts => "show_runtime_ports".to_string(),
401            Cmd::ListRuntimeApprovals => "list_runtime_approvals".to_string(),
402            Cmd::DecideRuntimeApproval { id, decision } => {
403                format!("decide_runtime_approval({}, {})", id, decision)
404            },
405            Cmd::ListRuntimeCheckpoints { limit } => {
406                format!("list_runtime_checkpoints(limit={})", limit)
407            },
408            Cmd::ListRuntimePlugins => "list_runtime_plugins".to_string(),
409            Cmd::UpdateRuntimeTaskStatus { id, status, .. } => {
410                format!("update_runtime_task_status({}, {})", id, status)
411            },
412            Cmd::CreateRuntimeCheckpoint { paths } => {
413                format!("create_runtime_checkpoint(n={})", paths.len())
414            },
415            Cmd::RestoreRuntimeCheckpoint { id } => format!("restore_runtime_checkpoint({})", id),
416            Cmd::ShowRuntimeModelInfo { model } => format!("show_runtime_model_info({})", model),
417            Cmd::InitMcpServers(m) => format!("init_mcp_servers(n={})", m.len()),
418            Cmd::StopMcpServer { name } => format!("stop_mcp_server({})", name),
419            Cmd::PullOllamaModel { model } => format!("pull_ollama_model({})", model),
420            Cmd::OpenInSystem(p) => format!("open_in_system({})", p.display()),
421            Cmd::DismissStatusAfter { ms } => format!("dismiss_status_after({}ms)", ms),
422            Cmd::WriteImageToTemp {
423                path,
424                format,
425                bytes,
426            } => format!(
427                "write_image_to_temp(path={}, fmt={}, n={})",
428                path.display(),
429                format,
430                bytes.len()
431            ),
432            Cmd::ReadClipboard => "read_clipboard".to_string(),
433            Cmd::CopyToClipboard(t) => format!("copy_to_clipboard(n={})", t.chars().count()),
434            Cmd::Exit => "exit".to_string(),
435            Cmd::SetTerminalTitle(t) => format!("set_terminal_title({})", t),
436        }
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn turn_scoped_variants_marked_correctly() {
446        let request = ChatRequest {
447            model_id: "m".to_string(),
448            messages: vec![],
449            system_prompt: String::new(),
450            instructions: None,
451            reasoning: ReasoningLevel::Medium,
452            temperature: 0.7,
453            max_tokens: 4096,
454            tools: vec![],
455        };
456        assert!(
457            Cmd::CallModel {
458                turn: TurnId(1),
459                request,
460            }
461            .is_turn_scoped()
462        );
463        assert!(
464            !Cmd::SaveConversation(ConversationHistory::new("/p".to_string(), "m".to_string()))
465                .is_turn_scoped()
466        );
467        assert!(!Cmd::RefreshInstructions.is_turn_scoped());
468        assert!(!Cmd::Exit.is_turn_scoped());
469    }
470
471    #[test]
472    fn cmd_tags_are_stable() {
473        assert_eq!(Cmd::Exit.tag(), "exit");
474        assert_eq!(Cmd::RefreshInstructions.tag(), "refresh_instructions");
475        assert_eq!(Cmd::CancelScope(TurnId(1)).tag(), "cancel_scope");
476    }
477
478    #[test]
479    fn cmd_summary_includes_identifying_fields() {
480        let c = Cmd::CancelScope(TurnId(42));
481        let s = c.summary();
482        assert!(s.contains("turn#42"));
483    }
484}