Skip to main content

agent_engine/session/
actor_cmds.rs

1//! `SessionActor` — command bodies that belong to the TUI port (A3):
2//! `engine_command` (structured reply), `submit_prepared`, `plugin_command`,
3//! `resume`, `session_name`, `emit_subagent_rows`. Kept apart from
4//! `actor.rs` so the turn machine (B) and the command surface (A) never
5//! touch the same file.
6
7use std::sync::Arc;
8
9use super::actor::{Live, SessionActor};
10use super::types::*;
11
12/// `/compact [instructions]` as the engine parses it (no runtime mutation).
13fn compact_request(cmd: &str, arg: &str) -> Option<crate::engine::commands::CommandResult> {
14    match crate::engine::commands::evaluate_engine_command(cmd, arg) {
15        Some(r @ crate::engine::commands::CommandResult::Compact { .. }) => Some(r),
16        _ => None,
17    }
18}
19
20/// `handle_engine_command` on `runtime` + the `QueryResult` value clients
21/// render. Returns `(value, view_changed)`. Shared by the actor and the
22/// TUI's `ScriptedTransport` so both answer identically.
23pub fn engine_command_reply(
24    cmd: &str,
25    arg: &str,
26    runtime: &mut crate::Runtime,
27    session: &mut crate::Session,
28) -> (serde_json::Value, bool) {
29    use crate::engine::commands::{handle_engine_command, CommandResult};
30    match handle_engine_command(cmd, arg, runtime) {
31        None => (serde_json::json!({ "kind": "unhandled" }), false),
32        Some(CommandResult::Quit) => (serde_json::json!({ "kind": "quit" }), false),
33        Some(CommandResult::ModelChanged {
34            model,
35            reasoning_clamped,
36        }) => {
37            session.model = runtime.model().to_string();
38            let mut text = format!("model → {}", model);
39            let mut clamp = serde_json::Value::Null;
40            if let Some(c) = reasoning_clamped {
41                session.thinking_level = runtime.thinking_level().to_string();
42                text.push_str(&format!(
43                    "\nthinking → {} (clamped from {}: not supported by {})",
44                    c.to.as_str(),
45                    c.from.as_str(),
46                    runtime.model()
47                ));
48                clamp = serde_json::json!({ "from": c.from.as_str(), "to": c.to.as_str() });
49            }
50            (
51                serde_json::json!({
52                    "kind": "notice",
53                    "event": "model_changed",
54                    "text": text,
55                    "model": runtime.model(),
56                    "clamp": clamp,
57                }),
58                true,
59            )
60        }
61        Some(CommandResult::ThinkingChanged { spec }) => {
62            session.thinking_level = spec.config_value();
63            (
64                serde_json::json!({
65                    "kind": "notice",
66                    "event": "thinking_changed",
67                    "text": format!("thinking → {}", spec.level()),
68                    "level": spec.level().to_string(),
69                    "config_value": spec.config_value(),
70                }),
71                true,
72            )
73        }
74        Some(CommandResult::Compact { .. }) => (serde_json::json!({ "kind": "none" }), false),
75        Some(CommandResult::Error(e)) => (serde_json::json!({ "kind": "error", "text": e }), false),
76        Some(CommandResult::Output(text)) => {
77            (serde_json::json!({ "kind": "output", "text": text }), false)
78        }
79        Some(_) => (serde_json::json!({ "kind": "none" }), false),
80    }
81}
82
83impl SessionActor {
84    /// `engine::commands::handle_engine_command` on THE runtime; reply as a
85    /// `QueryResult` the client renders. `kind`/`text` are what chat.rs
86    /// reads (`notice`/`error`/`output`/`quit`/`unhandled`); the TUI reads
87    /// the structured extras (`event`, `model`, `clamp`, `level`,
88    /// `config_value`) to render its own lines byte-for-byte.
89    pub(crate) async fn engine_command(&mut self, id: u64, cmd: String, arg: String) {
90        use crate::engine::commands::CommandResult;
91        // TUI-only commands that need the actor's session (it owns the
92        // journal): `saveas` names/unnames + force-saves.
93        if cmd == "saveas" {
94            let value = self.session_name(&arg).await;
95            self.emit(SessionEventWire::QueryResult { id, value });
96            return;
97        }
98        let (value, view_changed) =
99            engine_command_reply(&cmd, &arg, &mut self.runtime, &mut self.conv.session);
100        if view_changed {
101            self.publish_view().await;
102        }
103        if let Some(CommandResult::Compact {
104            custom_instructions,
105        }) = compact_request(&cmd, &arg)
106        {
107            self.compact(custom_instructions, "manual").await;
108        }
109        self.emit(SessionEventWire::QueryResult { id, value });
110    }
111
112    /// `/saveas <name>` | `/saveas` (clear). Force-saves even with no
113    /// messages — persist the name change (commands.rs `saveas` arm).
114    async fn session_name(&mut self, arg: &str) -> serde_json::Value {
115        let trimmed = arg.trim();
116        // This saves `conv.session` directly (even with no messages): a
117        // queued save of it, without the new name, must not land after.
118        self.persister.flush().await;
119        if trimmed.is_empty() {
120            self.conv.session.clear_name();
121            let _ = self.conv.session.save().await;
122            self.sync_name();
123            self.emit_conversation();
124            return serde_json::json!({
125                "kind": "output", "text": "session name cleared", "name": serde_json::Value::Null,
126            });
127        }
128        match self.conv.session.set_name(trimmed) {
129            Ok(()) => {
130                let _ = self.conv.session.save().await;
131                self.sync_name();
132                self.emit_conversation();
133                serde_json::json!({
134                    "kind": "output",
135                    "text": format!("session named '{}'", trimmed),
136                    "name": trimmed,
137                })
138            }
139            Err(e) => serde_json::json!({ "kind": "error", "text": e.to_string() }),
140        }
141    }
142
143    /// dispatch.rs LoadSkill (:330-360): pre-built tool_use/tool_result pair
144    /// (+ optional user text) then a turn. Does NOT reset
145    /// `consecutive_auto_turns`.
146    pub(crate) async fn submit_prepared(
147        &mut self,
148        messages: Vec<crate::SharedMessage>,
149        user_text: Option<String>,
150    ) {
151        if self.streaming {
152            self.emit(SessionEventWire::SystemNotice(
153                "cannot load a skill while streaming".into(),
154            ));
155            return;
156        }
157        self.conv.api_messages.extend(messages);
158        if let Some(text) = user_text {
159            self.conv
160                .api_messages
161                .push(Arc::new(serde_json::json!({"role": "user", "content": text})));
162        }
163        self.start_turn(TurnTrigger::PluginCommand, None).await;
164    }
165
166    /// commands.rs:123-158: tools-backed (non-interactive) plugin command on
167    /// THE runtime's tool set. Reply `{kind:"plugin_output", status, stdout,
168    /// stderr}` or `{kind:"error", text}`.
169    pub(crate) async fn plugin_command(&mut self, id: u64, plugin: String, name: String, arg: String) {
170        let value = match Self::find_plugin_command(&plugin, &name) {
171            None => serde_json::json!({
172                "kind": "error",
173                "text": format!("unknown plugin command /{plugin}:{name}"),
174            }),
175            Some(cmd) => match crate::skills::commands::execute_plugin_command_with_tools(
176                &cmd,
177                &arg,
178                self.runtime.tools_shared(),
179            )
180            .await
181            {
182                Ok(output) => serde_json::json!({
183                    "kind": "plugin_output",
184                    "status": output.status,
185                    "stdout": output.stdout,
186                    "stderr": output.stderr,
187                }),
188                Err(e) => serde_json::json!({ "kind": "error", "text": e.to_string() }),
189            },
190        };
191        self.emit(SessionEventWire::QueryResult { id, value });
192    }
193
194    fn find_plugin_command(
195        plugin: &str,
196        name: &str,
197    ) -> Option<Arc<crate::skills::registry::RegisteredPluginCommand>> {
198        let host = crate::host::EngineHost::current()?;
199        match host.command_registry().resolve(&format!("{plugin}:{name}")) {
200            crate::skills::registry::Resolution::PluginCommand(c) => Some(c),
201            _ => None,
202        }
203    }
204
205    /// commands.rs:647-693 `/resume`: save current, load `query`, restore
206    /// model/reasoning/system prompt, swap conversation. Reply `Resumed{id}`
207    /// then `Conversation`; error → `QueryResult{id, {kind:"error", text}}`.
208    pub(crate) async fn resume(&mut self, id: u64, query: String) {
209        if self.streaming {
210            self.emit(SessionEventWire::QueryResult {
211                id,
212                value: serde_json::json!({ "kind": "error", "text": "cannot resume while streaming" }),
213            });
214            return;
215        }
216        // Queued saves first: resuming the CURRENT session reloads it from
217        // disk, which must hold its latest state.
218        self.persister.flush().await;
219        let session = match crate::resolve_session(&query) {
220            Ok(s) => s,
221            Err(e) => {
222                self.emit(SessionEventWire::QueryResult {
223                    id,
224                    value: serde_json::json!({ "kind": "error", "text": e.to_string() }),
225                });
226                return;
227            }
228        };
229        let old_id = self.conv.session.id.clone();
230        let new_id = session.id.clone();
231        // F10: the journal lock follows the conversation. Take the new lock
232        // FIRST, before anything changes: a session locked by another
233        // process (or another session of this daemon) is live there right
234        // now, and resuming it here would fork its history. The old lock is
235        // only released once the new one is held.
236        let new_lock = if new_id == old_id {
237            None // resuming the current session: keep its lock
238        } else {
239            match Self::try_lock_session(&new_id) {
240                Ok(lock) => Some(lock),
241                Err(e @ agent_core::session_lock::SessionLockError::Held { .. })
242                | Err(e @ agent_core::session_lock::SessionLockError::CompactedInto { .. }) => {
243                    self.emit(SessionEventWire::QueryResult {
244                        id,
245                        value: serde_json::json!({
246                            "kind": "error",
247                            "text": format!("cannot resume: {e}"),
248                        }),
249                    });
250                    return;
251                }
252                Err(e) => {
253                    // I/O trouble (e.g. a read-only sessions dir): proceed
254                    // unlocked, as create/unpark do.
255                    tracing::warn!(session = %new_id, "resume: session lock: {e}");
256                    None
257                }
258            }
259        };
260        self.runtime.set_model(session.model.clone());
261        // A resumed session owns its saved choice. Preserve that explicit
262        // provenance across later model switches.
263        let clamp_notice = self
264            .runtime
265            .restore_session_reasoning(&session.thinking_level)
266            .map(|clamp| {
267                format!(
268                    "thinking → {} (clamped from {}: not supported by {})",
269                    clamp.to.as_str(),
270                    clamp.from.as_str(),
271                    self.runtime.model()
272                )
273            });
274        if let Some(ref sp) = session.system_prompt {
275            self.runtime.set_system_prompt(sp.clone());
276        }
277        self.save().await;
278        let via = if crate::chain::load_chain(&query).is_ok() {
279            Some(format!("chain '{}'", query))
280        } else if crate::find_session_by_name(&query).is_ok() {
281            Some(format!("name '{}'", query))
282        } else {
283            None
284        };
285        if new_id != old_id {
286            // Drops (releases) the old lock; `None` = proceeding unlocked.
287            self.session_lock = new_lock;
288        }
289        self.conv = Live::new(crate::engine::session::ConversationState::from_resumed(session));
290        // Crash recovery is the lock holder's alone (`recover_turn_draft`).
291        if self.config.persist && self.session_lock.is_some() {
292            crate::engine::setup::recover_turn_draft(&mut self.conv).await;
293        }
294        if clamp_notice.is_some() {
295            // Keep the session file in sync with the clamped runtime.
296            self.conv.session.thinking_level = self.runtime.thinking_level().to_string();
297        }
298        self.consecutive_auto_turns = 0;
299        self.runtime.set_session_id(Some(new_id.clone()));
300        self.journal_id.store(Arc::new(new_id.clone()));
301        self.publish_view().await;
302        self.emit(SessionEventWire::Resumed {
303            id,
304            old_id,
305            new_id,
306            via,
307            clamp_notice,
308        });
309        self.emit_conversation();
310    }
311
312    /// `runtime.subagent_registry().display_rows()` → `SubagentRows`
313    /// (called at Done/Error and from the 1 Hz arm B adds).
314    #[allow(dead_code)]
315    pub(crate) fn emit_subagent_rows(&mut self) {
316        let rows = self
317            .runtime
318            .subagent_registry()
319            .lock()
320            .unwrap_or_else(|p| p.into_inner())
321            .display_rows();
322        self.emit(SessionEventWire::SubagentRows(rows));
323    }
324
325    /// Any non-terminal subagent row (drives the 1 Hz arm).
326    #[allow(dead_code)]
327    pub(crate) fn has_live_subagents(&self) -> bool {
328        self.runtime
329            .subagent_registry()
330            .lock()
331            .unwrap_or_else(|p| p.into_inner())
332            .display_rows()
333            .iter()
334            .any(|r| matches!(r.status, crate::runtime::subagent::SubagentStatus::Running))
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    //! `/resume`'s reasoning restore is the runtime's `restore_session_reasoning`
341    //! + the clamp line above; pin the two behaviours the TUI tests pinned.
342    use crate::Runtime;
343
344    #[tokio::test]
345    async fn restore_session_reasoning_keeps_explicit_provenance() {
346        let mut runtime = Runtime::new().await.unwrap();
347        runtime.set_model("openai-codex/gpt-5.6-sol".to_string());
348        let clamp = runtime.restore_session_reasoning("ultra");
349        assert!(clamp.is_none());
350        assert_eq!(
351            runtime.reasoning_level(),
352            agent_core::reasoning::ReasoningLevel::Ultra
353        );
354        assert!(runtime.is_reasoning_explicit());
355        runtime.set_model("openai-codex/gpt-5.6-terra".to_string());
356        assert_eq!(
357            runtime.reasoning_level(),
358            agent_core::reasoning::ReasoningLevel::Ultra
359        );
360    }
361
362    #[tokio::test]
363    async fn restore_session_reasoning_clamps_unsupported_level() {
364        let mut runtime = Runtime::new().await.unwrap();
365        runtime.set_model("xai-auth/grok-4.6".to_string());
366        let clamp = runtime.restore_session_reasoning("xhigh");
367        assert!(clamp.is_some());
368        assert_eq!(
369            runtime.reasoning_level(),
370            agent_core::reasoning::ReasoningLevel::High
371        );
372        assert!(runtime.is_reasoning_explicit());
373    }
374}