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        if trimmed.is_empty() {
117            self.conv.session.clear_name();
118            let _ = self.conv.session.save().await;
119            self.sync_name();
120            self.emit_conversation();
121            return serde_json::json!({
122                "kind": "output", "text": "session name cleared", "name": serde_json::Value::Null,
123            });
124        }
125        match self.conv.session.set_name(trimmed) {
126            Ok(()) => {
127                let _ = self.conv.session.save().await;
128                self.sync_name();
129                self.emit_conversation();
130                serde_json::json!({
131                    "kind": "output",
132                    "text": format!("session named '{}'", trimmed),
133                    "name": trimmed,
134                })
135            }
136            Err(e) => serde_json::json!({ "kind": "error", "text": e.to_string() }),
137        }
138    }
139
140    /// dispatch.rs LoadSkill (:330-360): pre-built tool_use/tool_result pair
141    /// (+ optional user text) then a turn. Does NOT fold `abort_context` and
142    /// does NOT reset `consecutive_auto_turns`.
143    pub(crate) async fn submit_prepared(
144        &mut self,
145        messages: Vec<crate::SharedMessage>,
146        user_text: Option<String>,
147    ) {
148        if self.streaming {
149            self.emit(SessionEventWire::SystemNotice(
150                "cannot load a skill while streaming".into(),
151            ));
152            return;
153        }
154        self.conv.api_messages.extend(messages);
155        if let Some(text) = user_text {
156            self.conv
157                .api_messages
158                .push(Arc::new(serde_json::json!({"role": "user", "content": text})));
159        }
160        self.start_turn(TurnTrigger::PluginCommand, None).await;
161    }
162
163    /// commands.rs:123-158: tools-backed (non-interactive) plugin command on
164    /// THE runtime's tool set. Reply `{kind:"plugin_output", status, stdout,
165    /// stderr}` or `{kind:"error", text}`.
166    pub(crate) async fn plugin_command(&mut self, id: u64, plugin: String, name: String, arg: String) {
167        let value = match Self::find_plugin_command(&plugin, &name) {
168            None => serde_json::json!({
169                "kind": "error",
170                "text": format!("unknown plugin command /{plugin}:{name}"),
171            }),
172            Some(cmd) => match crate::skills::commands::execute_plugin_command_with_tools(
173                &cmd,
174                &arg,
175                self.runtime.tools_shared(),
176            )
177            .await
178            {
179                Ok(output) => serde_json::json!({
180                    "kind": "plugin_output",
181                    "status": output.status,
182                    "stdout": output.stdout,
183                    "stderr": output.stderr,
184                }),
185                Err(e) => serde_json::json!({ "kind": "error", "text": e.to_string() }),
186            },
187        };
188        self.emit(SessionEventWire::QueryResult { id, value });
189    }
190
191    fn find_plugin_command(
192        plugin: &str,
193        name: &str,
194    ) -> Option<Arc<crate::skills::registry::RegisteredPluginCommand>> {
195        let host = crate::host::EngineHost::current()?;
196        match host.command_registry().resolve(&format!("{plugin}:{name}")) {
197            crate::skills::registry::Resolution::PluginCommand(c) => Some(c),
198            _ => None,
199        }
200    }
201
202    /// commands.rs:647-693 `/resume`: save current, load `query`, restore
203    /// model/reasoning/system prompt, swap conversation. Reply `Resumed{id}`
204    /// then `Conversation`; error → `QueryResult{id, {kind:"error", text}}`.
205    pub(crate) async fn resume(&mut self, id: u64, query: String) {
206        if self.streaming {
207            self.emit(SessionEventWire::QueryResult {
208                id,
209                value: serde_json::json!({ "kind": "error", "text": "cannot resume while streaming" }),
210            });
211            return;
212        }
213        let session = match crate::resolve_session(&query) {
214            Ok(s) => s,
215            Err(e) => {
216                self.emit(SessionEventWire::QueryResult {
217                    id,
218                    value: serde_json::json!({ "kind": "error", "text": e.to_string() }),
219                });
220                return;
221            }
222        };
223        self.runtime.set_model(session.model.clone());
224        // A resumed session owns its saved choice. Preserve that explicit
225        // provenance across later model switches.
226        let clamp_notice = self
227            .runtime
228            .restore_session_reasoning(&session.thinking_level)
229            .map(|clamp| {
230                format!(
231                    "thinking → {} (clamped from {}: not supported by {})",
232                    clamp.to.as_str(),
233                    clamp.from.as_str(),
234                    self.runtime.model()
235                )
236            });
237        if let Some(ref sp) = session.system_prompt {
238            self.runtime.set_system_prompt(sp.clone());
239        }
240        self.save().await;
241        let old_id = self.conv.session.id.clone();
242        let new_id = session.id.clone();
243        let via = if crate::chain::load_chain(&query).is_ok() {
244            Some(format!("chain '{}'", query))
245        } else if crate::find_session_by_name(&query).is_ok() {
246            Some(format!("name '{}'", query))
247        } else {
248            None
249        };
250        self.conv = Live::new(crate::engine::session::ConversationState::from_resumed(session));
251        if clamp_notice.is_some() {
252            // Keep the session file in sync with the clamped runtime.
253            self.conv.session.thinking_level = self.runtime.thinking_level().to_string();
254        }
255        self.consecutive_auto_turns = 0;
256        self.runtime.set_session_id(Some(new_id.clone()));
257        self.journal_id.store(Arc::new(new_id.clone()));
258        self.publish_view().await;
259        self.emit(SessionEventWire::Resumed {
260            id,
261            old_id,
262            new_id,
263            via,
264            clamp_notice,
265        });
266        self.emit_conversation();
267    }
268
269    /// `runtime.subagent_registry().display_rows()` → `SubagentRows`
270    /// (called at Done/Error and from the 1 Hz arm B adds).
271    #[allow(dead_code)]
272    pub(crate) fn emit_subagent_rows(&mut self) {
273        let rows = self
274            .runtime
275            .subagent_registry()
276            .lock()
277            .unwrap_or_else(|p| p.into_inner())
278            .display_rows();
279        self.emit(SessionEventWire::SubagentRows(rows));
280    }
281
282    /// Any non-terminal subagent row (drives the 1 Hz arm).
283    #[allow(dead_code)]
284    pub(crate) fn has_live_subagents(&self) -> bool {
285        self.runtime
286            .subagent_registry()
287            .lock()
288            .unwrap_or_else(|p| p.into_inner())
289            .display_rows()
290            .iter()
291            .any(|r| matches!(r.status, crate::runtime::subagent::SubagentStatus::Running))
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    //! `/resume`'s reasoning restore is the runtime's `restore_session_reasoning`
298    //! + the clamp line above; pin the two behaviours the TUI tests pinned.
299    use crate::Runtime;
300
301    #[tokio::test]
302    async fn restore_session_reasoning_keeps_explicit_provenance() {
303        let mut runtime = Runtime::new().await.unwrap();
304        runtime.set_model("openai-codex/gpt-5.6-sol".to_string());
305        let clamp = runtime.restore_session_reasoning("ultra");
306        assert!(clamp.is_none());
307        assert_eq!(
308            runtime.reasoning_level(),
309            agent_core::reasoning::ReasoningLevel::Ultra
310        );
311        assert!(runtime.is_reasoning_explicit());
312        runtime.set_model("openai-codex/gpt-5.6-terra".to_string());
313        assert_eq!(
314            runtime.reasoning_level(),
315            agent_core::reasoning::ReasoningLevel::Ultra
316        );
317    }
318
319    #[tokio::test]
320    async fn restore_session_reasoning_clamps_unsupported_level() {
321        let mut runtime = Runtime::new().await.unwrap();
322        runtime.set_model("xai-auth/grok-4.6".to_string());
323        let clamp = runtime.restore_session_reasoning("xhigh");
324        assert!(clamp.is_some());
325        assert_eq!(
326            runtime.reasoning_level(),
327            agent_core::reasoning::ReasoningLevel::High
328        );
329        assert!(runtime.is_reasoning_explicit());
330    }
331}