Skip to main content

microclaw_engine/
headless.rs

1//! Headless one-shot mode: `microclaw run -p "<prompt>"`.
2//!
3//! Runs a single prompt through the shared agent loop without starting any
4//! channel, prints the final reply to stdout, and exits non-zero on failure
5//! — the scripting/CI entry point (grok-build's headless mode equivalent).
6//! Runs share the `headless` channel; `--session <name>` selects a named
7//! chat so consecutive runs can keep conversation context.
8
9use std::collections::HashMap;
10use std::path::Path;
11use std::sync::Arc;
12
13use tokio::sync::{mpsc, RwLock};
14
15use crate::agent_engine::{run_agent_turn, AgentEvent, AgentRequestContext, AgentTurn};
16use crate::chat_turn_queue::PendingMessage;
17use crate::config::Config;
18use crate::hooks::HookManager;
19use crate::internal::channels::channel_adapter::ChannelRegistry;
20use crate::internal::runtime::{ExecutionContext, ExecutionResult, RunExecutor};
21use crate::internal::storage::db::{call_blocking, Database, StoredMessage};
22use crate::memory::MemoryManager;
23use crate::memory_backend::{MemoryBackend, MemoryMcpClient};
24use crate::runtime::AppState;
25use crate::skill_management::{archive_skill, install_skill, SkillInstallOutcome};
26use crate::skills::{SkillAvailability, SkillManager};
27use crate::tools::ToolRegistry;
28use crate::{embedding, llm};
29use microclaw_core::run_protocol::{
30    AgentProfile, RunRequest, RuntimeCapabilities, RuntimeControl, RuntimeError, RuntimeErrorCode,
31    SessionId,
32};
33use microclaw_core::runtime_event::RuntimeEventEnvelope;
34
35pub const HEADLESS_CHANNEL: &str = "headless";
36pub const CODE_CHANNEL: &str = "code";
37/// `RunRequest::metadata` key: `true` makes gated tool calls wait in-run for
38/// `RuntimeControl::ResolveApproval` (see [`crate::approval_broker`]).
39pub const INTERACTIVE_APPROVALS_KEY: &str = "interactive_approvals";
40
41#[derive(Debug, Clone)]
42pub struct HeadlessRunRequest {
43    pub prompt: String,
44    pub session: Option<String>,
45    pub sender_name: String,
46    pub run_id: Option<String>,
47    pub caller_channel: String,
48}
49
50impl HeadlessRunRequest {
51    pub fn cli(prompt: String, session: Option<String>) -> Self {
52        Self {
53            prompt,
54            session,
55            sender_name: "cli".into(),
56            run_id: None,
57            caller_channel: HEADLESS_CHANNEL.into(),
58        }
59    }
60
61    pub fn code(prompt: String, session: Option<String>, run_id: String) -> Self {
62        Self {
63            prompt,
64            session,
65            sender_name: "code".into(),
66            run_id: Some(run_id),
67            caller_channel: CODE_CHANNEL.into(),
68        }
69    }
70}
71
72#[derive(Debug, Clone)]
73pub struct HeadlessRunResult {
74    pub run_id: String,
75    pub chat_id: i64,
76    pub response: String,
77}
78
79/// One stored message of an embedded session.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct HeadlessSessionMessage {
82    /// `true` for the agent's replies, `false` for user prompts.
83    pub from_agent: bool,
84    pub content: String,
85    pub timestamp: String,
86}
87
88/// One filesystem checkpoint of a session's working directory.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct HeadlessCheckpoint {
91    pub commit: String,
92    pub label: String,
93    pub timestamp: String,
94}
95
96/// Token usage of one session.
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct HeadlessUsage {
99    pub requests: i64,
100    pub input_tokens: i64,
101    pub output_tokens: i64,
102    /// `(model, requests, input_tokens, output_tokens)`, largest first.
103    pub by_model: Vec<(String, i64, i64, i64)>,
104}
105
106/// Result of compacting a session.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub struct HeadlessCompaction {
109    pub messages_before: usize,
110    pub messages_after: usize,
111}
112
113/// UI-neutral projection of one durable Subagent run.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct HeadlessSubagentRun {
116    pub run_id: String,
117    pub parent_run_id: Option<String>,
118    pub depth: u32,
119    pub label: Option<String>,
120    pub task: String,
121    pub status: String,
122    pub progress: Option<String>,
123    pub result: Option<String>,
124    pub error: Option<String>,
125    pub created_at: String,
126    pub started_at: Option<String>,
127    pub finished_at: Option<String>,
128    pub cancel_requested: bool,
129}
130
131/// Reusable application service for one-shot tasks.
132///
133/// It owns the existing provider-neutral Agent Engine state but starts no
134/// channel, Web server, or scheduler. Both `microclaw run` and MicroClaw Code call this
135/// service instead of assembling or copying an Agent Loop.
136#[derive(Clone)]
137pub struct HeadlessRuntime {
138    state: Arc<AppState>,
139}
140
141/// Adapter from the existing shared Agent Engine to the embeddable Runtime contract.
142///
143/// This is intentionally channel-free: the caller selects the logical channel used for policy,
144/// persistence, cancellation, and steering. Product UIs consume `microclaw-engine` rather than
145/// calling the Agent Engine directly.
146pub struct HeadlessRunExecutor {
147    runtime: HeadlessRuntime,
148    caller_channel: String,
149}
150
151impl HeadlessRunExecutor {
152    pub fn new(runtime: HeadlessRuntime, caller_channel: impl Into<String>) -> Self {
153        Self {
154            runtime,
155            caller_channel: caller_channel.into(),
156        }
157    }
158}
159
160#[async_trait::async_trait]
161impl RunExecutor for HeadlessRunExecutor {
162    async fn execute(
163        &self,
164        profile: AgentProfile,
165        request: RunRequest,
166        mut context: ExecutionContext,
167    ) -> Result<ExecutionResult, RuntimeError> {
168        let session = request
169            .session_id
170            .clone()
171            .unwrap_or_else(|| SessionId::new("default"));
172        // Opt-in in-run approvals: while this guard lives, gated tool calls
173        // wait for `RuntimeControl::ResolveApproval` instead of ending the
174        // run with a text prompt.
175        let interactive_approvals = request
176            .metadata
177            .get(INTERACTIVE_APPROVALS_KEY)
178            .and_then(serde_json::Value::as_bool)
179            .unwrap_or(false);
180        let approval_chat_id = if interactive_approvals {
181            Some(
182                self.runtime
183                    .resolve_session_chat_id(session.as_str())
184                    .await
185                    .map_err(runtime_internal_error)?,
186            )
187        } else {
188            None
189        };
190        let _approval_broker = approval_chat_id
191            .map(|chat_id| crate::approval_broker::register(&self.caller_channel, chat_id));
192        let (legacy_event_tx, mut legacy_event_rx) = mpsc::unbounded_channel();
193        let run = self.runtime.run_with_profile(
194            HeadlessRunRequest {
195                prompt: request.prompt,
196                session: Some(session.to_string()),
197                sender_name: self.caller_channel.clone(),
198                run_id: Some(context.run_id().to_string()),
199                caller_channel: self.caller_channel.clone(),
200            },
201            profile,
202            Some(legacy_event_tx),
203        );
204        tokio::pin!(run);
205
206        let result = loop {
207            tokio::select! {
208                result = &mut run => break result,
209                event = legacy_event_rx.recv() => {
210                    if let Some(envelope) = event {
211                        forward_runtime_event(&context, envelope.event)?;
212                    }
213                }
214                control = context.next_control_request() => {
215                    if let Some(control) = control {
216                        match control.control().clone() {
217                        RuntimeControl::Cancel { .. } => {
218                            let cancelled = self.runtime
219                                .cancel_session_for_channel(&self.caller_channel, session.as_str())
220                                .await
221                                .map_err(runtime_internal_error)?;
222                            if cancelled > 0 {
223                                control.accept();
224                            } else {
225                                control.reject(RuntimeError {
226                                    code: RuntimeErrorCode::Unavailable,
227                                    message: "the run finished before cancellation was accepted".into(),
228                                    retryable: false,
229                                });
230                            }
231                        }
232                        RuntimeControl::Steer { message, .. } => {
233                            let accepted = self.runtime
234                                .steer_session_for_channel(
235                                    &self.caller_channel,
236                                    session.as_str(),
237                                    &message,
238                                )
239                                .await
240                                .map_err(runtime_internal_error)?;
241                            if accepted {
242                                control.accept();
243                            } else {
244                                control.reject(RuntimeError {
245                                    code: RuntimeErrorCode::Unavailable,
246                                    message: "the run finished before the update could be queued".into(),
247                                    retryable: false,
248                                });
249                            }
250                        }
251                        RuntimeControl::ResolveApproval { approval_id, decision, .. } => {
252                            let Some(chat_id) = approval_chat_id else {
253                                control.reject(RuntimeError {
254                                    code: RuntimeErrorCode::Unavailable,
255                                    message: format!(
256                                        "in-run approvals are off for this run; set request metadata `{INTERACTIVE_APPROVALS_KEY}: true`"
257                                    ),
258                                    retryable: false,
259                                });
260                                continue;
261                            };
262                            let Some(decision) = crate::approval_broker::ApprovalDecision::parse(&decision) else {
263                                control.reject(RuntimeError {
264                                    code: RuntimeErrorCode::InvalidRequest,
265                                    message: format!(
266                                        "unknown approval decision `{decision}` (use 1/approve, 2/always, 3/deny or defer)"
267                                    ),
268                                    retryable: false,
269                                });
270                                continue;
271                            };
272                            if crate::approval_broker::resolve(
273                                &self.caller_channel,
274                                chat_id,
275                                &approval_id,
276                                decision,
277                            ) {
278                                control.accept();
279                            } else {
280                                control.reject(RuntimeError {
281                                    code: RuntimeErrorCode::Unavailable,
282                                    message: format!("no pending approval `{approval_id}`"),
283                                    retryable: false,
284                                });
285                            }
286                        }
287                        }
288                    }
289                }
290            }
291        }
292        .map_err(runtime_internal_error)?;
293
294        while let Ok(envelope) = legacy_event_rx.try_recv() {
295            forward_runtime_event(&context, envelope.event)?;
296        }
297
298        let mut output = ExecutionResult::new(session, result.response);
299        output.metadata.insert(
300            "chat_id".into(),
301            serde_json::Value::Number(result.chat_id.into()),
302        );
303        Ok(output)
304    }
305
306    fn capabilities(&self) -> RuntimeCapabilities {
307        RuntimeCapabilities {
308            streaming: true,
309            cancellation: true,
310            steering: true,
311            approvals: true,
312            skills: true,
313            subagents: true,
314            remote_workers: false,
315        }
316    }
317}
318
319fn forward_runtime_event(
320    context: &ExecutionContext,
321    event: microclaw_core::runtime_event::RuntimeEvent,
322) -> Result<(), RuntimeError> {
323    if matches!(
324        event,
325        microclaw_core::runtime_event::RuntimeEvent::FinalResponse { .. }
326            | microclaw_core::runtime_event::RuntimeEvent::Cancelled { .. }
327    ) {
328        return Ok(());
329    }
330    context.emit(event)
331}
332
333fn runtime_internal_error(error: impl std::fmt::Display) -> RuntimeError {
334    RuntimeError {
335        code: RuntimeErrorCode::Internal,
336        message: error.to_string(),
337        retryable: false,
338    }
339}
340
341impl HeadlessRuntime {
342    /// Return the Skills visible to this runtime, including availability diagnostics when
343    /// requested. Embedding facades use this to present a catalog without exposing runtime state.
344    pub fn skill_catalog(&self, include_unavailable: bool) -> Vec<SkillAvailability> {
345        self.state
346            .skills
347            .discover_skills_with_status(include_unavailable)
348    }
349
350    /// Invalidate cached integrity verdicts and rebuild the runtime's Skill catalog.
351    pub fn reload_skill_catalog(&self, include_unavailable: bool) -> Vec<SkillAvailability> {
352        self.state.skills.reload();
353        self.skill_catalog(include_unavailable)
354    }
355
356    /// Change runtime-scoped Skill enablement without rewriting the Skill package.
357    pub fn set_skill_enabled(&self, name: &str, enabled: bool) -> Result<(), String> {
358        self.state.skills.set_enabled(name, enabled)?;
359        self.state.skills.reload();
360        Ok(())
361    }
362
363    /// Install or update a Skill through the shared governed package path.
364    pub async fn install_skill(&self, reference: &str) -> Result<SkillInstallOutcome, String> {
365        install_skill(&self.state.config, &self.state.skills, reference).await
366    }
367
368    /// Recoverably remove a Skill and return its archive location.
369    pub fn archive_skill(&self, name: &str) -> Result<std::path::PathBuf, String> {
370        archive_skill(&self.state.skills, name)
371    }
372
373    /// List durable Subagent runs belonging to a named embedded session.
374    pub fn subagent_runs(
375        &self,
376        session: &str,
377        limit: usize,
378    ) -> anyhow::Result<Vec<HeadlessSubagentRun>> {
379        let external_chat_id = format!("headless:{}", session.trim());
380        let Some(chat_id) = self
381            .state
382            .db
383            .find_chat_id(HEADLESS_CHANNEL, &external_chat_id)?
384        else {
385            return Ok(Vec::new());
386        };
387        Ok(self
388            .state
389            .db
390            .list_subagent_runs(chat_id, limit.clamp(1, 1_000))?
391            .into_iter()
392            .map(|run| HeadlessSubagentRun {
393                run_id: run.run_id,
394                parent_run_id: run.parent_run_id,
395                depth: run.depth.max(0) as u32,
396                label: run.label,
397                task: run.task,
398                status: run.status,
399                progress: run.progress_text,
400                result: run.result_text,
401                error: run.error_text,
402                created_at: run.created_at,
403                started_at: run.started_at,
404                finished_at: run.finished_at,
405                cancel_requested: run.cancel_requested,
406            })
407            .collect())
408    }
409
410    /// The most recent `limit` stored messages of a named embedded session,
411    /// oldest first: user prompts (including steering) and final replies.
412    /// Empty for a session that never ran.
413    pub fn session_messages(
414        &self,
415        session: &str,
416        limit: usize,
417    ) -> anyhow::Result<Vec<HeadlessSessionMessage>> {
418        let external_chat_id = format!("headless:{}", session.trim());
419        let Some(chat_id) = self
420            .state
421            .db
422            .find_chat_id(HEADLESS_CHANNEL, &external_chat_id)?
423        else {
424            return Ok(Vec::new());
425        };
426        Ok(self
427            .state
428            .db
429            .get_recent_messages(chat_id, limit.clamp(1, 10_000))?
430            .into_iter()
431            .map(|message| HeadlessSessionMessage {
432                from_agent: message.is_from_bot,
433                content: message.content,
434                timestamp: message.timestamp,
435            })
436            .collect())
437    }
438
439    async fn existing_session_chat_id(&self, session: &str) -> anyhow::Result<Option<i64>> {
440        let external_chat_id = format!("headless:{}", session.trim());
441        let db = self.state.db.clone();
442        Ok(call_blocking(db, move |db| {
443            db.find_chat_id(HEADLESS_CHANNEL, &external_chat_id)
444        })
445        .await?)
446    }
447
448    fn checkpoint_paths(
449        &self,
450        channel: &str,
451        chat_id: i64,
452    ) -> anyhow::Result<(std::path::PathBuf, std::path::PathBuf)> {
453        if !self.state.config.checkpoints_enabled {
454            anyhow::bail!("checkpoints are disabled for this runtime");
455        }
456        let working_dir = crate::internal::tool_runtime::runtime::working_dir_for_context(
457            Path::new(&self.state.config.working_dir),
458            self.state.config.working_dir_isolation,
459            channel,
460            chat_id,
461        );
462        let shadow_root = std::path::PathBuf::from(&self.state.config.data_dir).join("checkpoints");
463        let shadow_repo = crate::checkpoint::shadow_repo_path(&shadow_root, &working_dir);
464        Ok((shadow_repo, working_dir))
465    }
466
467    /// Snapshot the session's working directory now and return the checkpoint
468    /// that holds its current state (a new one, or the latest when nothing
469    /// changed since). Requires `checkpoints_enabled`.
470    pub async fn checkpoint_session(
471        &self,
472        channel: &str,
473        session: &str,
474        label: &str,
475    ) -> anyhow::Result<Option<HeadlessCheckpoint>> {
476        let chat_id = self.resolve_session_chat_id(session).await?;
477        let (shadow_repo, working_dir) = self.checkpoint_paths(channel, chat_id)?;
478        crate::checkpoint::snapshot(&shadow_repo, &working_dir, label)
479            .await
480            .map_err(anyhow::Error::msg)?;
481        Ok(crate::checkpoint::list(&shadow_repo, &working_dir, 1)
482            .await
483            .map_err(anyhow::Error::msg)?
484            .into_iter()
485            .next()
486            .map(|c| HeadlessCheckpoint {
487                commit: c.commit,
488                label: c.label,
489                timestamp: c.timestamp,
490            }))
491    }
492
493    /// Recent checkpoints of the session's working directory, newest first.
494    pub async fn session_checkpoints(
495        &self,
496        channel: &str,
497        session: &str,
498        limit: usize,
499    ) -> anyhow::Result<Vec<HeadlessCheckpoint>> {
500        let chat_id = self.resolve_session_chat_id(session).await?;
501        let (shadow_repo, working_dir) = self.checkpoint_paths(channel, chat_id)?;
502        Ok(
503            crate::checkpoint::list(&shadow_repo, &working_dir, limit.clamp(1, 500))
504                .await
505                .map_err(anyhow::Error::msg)?
506                .into_iter()
507                .map(|c| HeadlessCheckpoint {
508                    commit: c.commit,
509                    label: c.label,
510                    timestamp: c.timestamp,
511                })
512                .collect(),
513        )
514    }
515
516    /// Restore the session's working directory to `commit`. The current
517    /// state is checkpointed first, so a restore can itself be undone.
518    pub async fn restore_session_checkpoint(
519        &self,
520        channel: &str,
521        session: &str,
522        commit: &str,
523    ) -> anyhow::Result<Option<HeadlessCheckpoint>> {
524        let before = self
525            .checkpoint_session(channel, session, &format!("before restoring {commit}"))
526            .await?;
527        let chat_id = self.resolve_session_chat_id(session).await?;
528        let (shadow_repo, working_dir) = self.checkpoint_paths(channel, chat_id)?;
529        crate::checkpoint::restore(&shadow_repo, &working_dir, commit)
530            .await
531            .map_err(anyhow::Error::msg)?;
532        Ok(before)
533    }
534
535    /// Token usage recorded for a session.
536    pub async fn session_usage(&self, session: &str) -> anyhow::Result<HeadlessUsage> {
537        let Some(chat_id) = self.existing_session_chat_id(session).await? else {
538            return Ok(HeadlessUsage::default());
539        };
540        let db = self.state.db.clone();
541        Ok(call_blocking(db, move |db| {
542            let summary = db.get_llm_usage_summary(Some(chat_id))?;
543            let by_model = db
544                .get_llm_usage_by_model(Some(chat_id), None, Some(20))?
545                .into_iter()
546                .map(|m| (m.model, m.requests, m.input_tokens, m.output_tokens))
547                .collect();
548            Ok::<_, microclaw_core::error::MicroClawError>(HeadlessUsage {
549                requests: summary.requests,
550                input_tokens: summary.input_tokens,
551                output_tokens: summary.output_tokens,
552                by_model,
553            })
554        })
555        .await?)
556    }
557
558    /// The model the next run of this session uses.
559    pub async fn session_model(&self, channel: &str, session: &str) -> anyhow::Result<String> {
560        let chat_id = self.resolve_session_chat_id(session).await?;
561        Ok(
562            crate::agent_engine::resolve_effective_provider_and_model(
563                &self.state,
564                channel,
565                chat_id,
566            )
567            .await
568            .1,
569        )
570    }
571
572    /// Override the model for one session (`None` clears the override).
573    /// Runtime-only, like `/model here`. Returns the effective model.
574    pub async fn set_session_model(
575        &self,
576        channel: &str,
577        session: &str,
578        model: Option<&str>,
579    ) -> anyhow::Result<String> {
580        let chat_id = self.resolve_session_chat_id(session).await?;
581        let key = crate::chat_commands::chat_scoped_override_key(channel, chat_id);
582        {
583            let mut overrides = self.state.llm_model_overrides.write().await;
584            match model {
585                Some(model) => {
586                    let model = crate::config::normalize_model_name(model)
587                        .ok_or_else(|| anyhow::anyhow!("invalid model name `{model}`"))?;
588                    overrides.insert(key, model);
589                }
590                None => {
591                    overrides.remove(&key);
592                }
593            }
594        }
595        self.session_model(channel, session).await
596    }
597
598    /// Summarize older messages of a session now, keeping the last
599    /// `keep_recent` verbatim (the same compaction a long session gets
600    /// automatically).
601    pub async fn compact_session(
602        &self,
603        channel: &str,
604        session: &str,
605        keep_recent: usize,
606    ) -> anyhow::Result<HeadlessCompaction> {
607        let Some(chat_id) = self.existing_session_chat_id(session).await? else {
608            anyhow::bail!("session `{session}` has no conversation yet");
609        };
610        let db = self.state.db.clone();
611        let Some((json, _)) = call_blocking(db, move |db| db.load_session(chat_id)).await? else {
612            anyhow::bail!("session `{session}` has no conversation yet");
613        };
614        let messages: Vec<microclaw_core::llm_types::Message> = serde_json::from_str(&json)?;
615        let before = messages.len();
616        let compacted = crate::agent_engine::compact_messages(
617            &self.state,
618            channel,
619            chat_id,
620            &messages,
621            keep_recent.max(2),
622        )
623        .await;
624        let after = compacted.len();
625        if after < before {
626            let json = serde_json::to_string(&compacted)?;
627            let db = self.state.db.clone();
628            call_blocking(db, move |db| db.save_session(chat_id, &json)).await?;
629        }
630        Ok(HeadlessCompaction {
631            messages_before: before,
632            messages_after: after,
633        })
634    }
635
636    /// Copy a session's conversation (agent context and stored messages)
637    /// into a new session. Fails when `to` already has a conversation.
638    pub async fn fork_session(&self, from: &str, to: &str) -> anyhow::Result<()> {
639        let Some(from_id) = self.existing_session_chat_id(from).await? else {
640            anyhow::bail!("session `{from}` has no conversation to fork");
641        };
642        let to_id = self.resolve_session_chat_id(to).await?;
643        let parent_key = format!("headless:{}", from.trim());
644        let db = self.state.db.clone();
645        call_blocking(db, move |db| {
646            if db.load_session(to_id)?.is_some() {
647                return Err(microclaw_core::error::MicroClawError::Config(
648                    "the target session already has a conversation".into(),
649                ));
650            }
651            for message in db.get_all_messages(from_id)? {
652                db.store_message(&StoredMessage {
653                    id: uuid::Uuid::new_v4().to_string(),
654                    chat_id: to_id,
655                    ..message
656                })?;
657            }
658            if let Some((json, _)) = db.load_session(from_id)? {
659                let fork_point = serde_json::from_str::<Vec<serde_json::Value>>(&json)
660                    .map(|m| m.len() as i64)
661                    .ok();
662                db.save_session_with_meta(to_id, &json, Some(&parent_key), fork_point, None)?;
663            }
664            Ok(())
665        })
666        .await?;
667        Ok(())
668    }
669
670    /// Persist and promptly signal cancellation for one Subagent owned by the session.
671    pub fn cancel_subagent(&self, session: &str, run_id: &str) -> anyhow::Result<bool> {
672        let external_chat_id = format!("headless:{}", session.trim());
673        let Some(chat_id) = self
674            .state
675            .db
676            .find_chat_id(HEADLESS_CHANNEL, &external_chat_id)?
677        else {
678            return Ok(false);
679        };
680        Ok(crate::tools::subagents::request_subagent_cancel(
681            &self.state.config,
682            &self.state.db,
683            chat_id,
684            run_id,
685        )?)
686    }
687
688    /// Build a standalone runtime from a loaded product config.
689    ///
690    /// This is the Code/headless bootstrap path. It intentionally initializes
691    /// no chat adapters, Web routes, scheduler, or gateway.
692    pub async fn load(mut config: Config) -> anyhow::Result<Self> {
693        let data_root = config.data_root_dir();
694        let runtime_data_dir = config.runtime_data_dir();
695        let skills_data_dir = config.skills_data_dir();
696        crate::builtin_skills::ensure_builtin_skills(Path::new(&skills_data_dir))?;
697
698        let db = Database::new(&runtime_data_dir)?;
699        let memory = MemoryManager::new(&runtime_data_dir);
700        let skills = SkillManager::from_skills_and_runtime(&skills_data_dir, &runtime_data_dir)
701            .with_config_verification(&config);
702        let mcp_manager = crate::mcp::McpManager::from_config_paths(
703            &crate::mcp::collect_config_paths(&data_root),
704            config.mcp_request_timeout_secs(),
705        )
706        .await;
707
708        config.data_dir = runtime_data_dir;
709        config.skills_dir = Some(skills_data_dir);
710        Ok(Self::new(config, db, memory, skills, mcp_manager))
711    }
712
713    pub fn new(
714        config: Config,
715        db: Database,
716        memory: MemoryManager,
717        skills: SkillManager,
718        mcp_manager: crate::mcp::McpManager,
719    ) -> Self {
720        let db = Arc::new(db);
721        let llm = llm::create_provider(&config);
722        let embedding = embedding::create_provider(&config);
723        let channel_registry = Arc::new(ChannelRegistry::new());
724
725        let memory_backend = Arc::new(MemoryBackend::new(
726            db.clone(),
727            MemoryMcpClient::discover(&mcp_manager),
728            &config.data_dir,
729        ));
730        let mut tools = ToolRegistry::new(
731            &config,
732            channel_registry.clone(),
733            db.clone(),
734            memory_backend.clone(),
735        );
736        tools.register_mcp_tools(&mcp_manager);
737
738        let chat_turn_queue = Arc::new(crate::chat_turn_queue::ChatTurnQueue::new(
739            config.chat_turn_queue_max_pending,
740        ));
741        let (skill_review_queue, _skill_review_worker) =
742            crate::skill_review::build_skill_review_channel();
743        let state = Arc::new(AppState {
744            config: config.clone(),
745            channel_registry,
746            db: db.clone(),
747            memory: Arc::new(memory),
748            skills: Arc::new(skills),
749            hooks: Arc::new(HookManager::from_config(&config).with_db(db.clone())),
750            llm: Arc::from(llm),
751            llm_provider_overrides: Arc::new(RwLock::new(HashMap::new())),
752            llm_model_overrides: Arc::new(RwLock::new(HashMap::new())),
753            embedding,
754            memory_backend,
755            tools: Arc::new(tools),
756            chat_turn_queue,
757            skill_review_queue,
758            metric_exporter: None,
759            trace_exporter: None,
760            log_exporter: None,
761        });
762        Self { state }
763    }
764
765    /// Build the public embeddable Runtime over this configured Agent Engine.
766    pub fn into_embedded_runtime(
767        self,
768        caller_channel: impl Into<String>,
769        max_concurrent_runs: usize,
770    ) -> Result<crate::internal::runtime::Runtime, crate::internal::runtime::RuntimeBuildError>
771    {
772        crate::internal::runtime::Runtime::builder()
773            .executor(HeadlessRunExecutor::new(self, caller_channel))
774            .max_concurrent_runs(max_concurrent_runs)
775            .build()
776    }
777
778    pub async fn run(
779        &self,
780        request: HeadlessRunRequest,
781        event_tx: Option<mpsc::UnboundedSender<RuntimeEventEnvelope>>,
782    ) -> anyhow::Result<HeadlessRunResult> {
783        self.run_with_profile(request, AgentProfile::default(), event_tx)
784            .await
785    }
786
787    pub async fn run_with_profile(
788        &self,
789        request: HeadlessRunRequest,
790        profile: AgentProfile,
791        event_tx: Option<mpsc::UnboundedSender<RuntimeEventEnvelope>>,
792    ) -> anyhow::Result<HeadlessRunResult> {
793        let session_name = request
794            .session
795            .clone()
796            .unwrap_or_else(|| "default".to_string());
797        let chat_id = self.resolve_session_chat_id(&session_name).await?;
798        let caller_channel = request.caller_channel;
799
800        let stored = StoredMessage {
801            id: uuid::Uuid::new_v4().to_string(),
802            chat_id,
803            sender_name: request.sender_name,
804            content: request.prompt,
805            is_from_bot: false,
806            timestamp: chrono::Utc::now().to_rfc3339(),
807        };
808        let _ = call_blocking(self.state.db.clone(), move |db| db.store_message(&stored)).await;
809
810        let run_id = request
811            .run_id
812            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
813        let (raw_event_tx, bridge) = match event_tx {
814            Some(envelope_tx) => {
815                let (raw_tx, raw_rx) = mpsc::unbounded_channel();
816                let bridge = spawn_event_envelope_bridge(run_id.clone(), raw_rx, envelope_tx);
817                (Some(raw_tx), Some(bridge))
818            }
819            None => (None, None),
820        };
821        let response = run_agent_turn(
822            &self.state,
823            AgentTurn::new(AgentRequestContext {
824                caller_channel: &caller_channel,
825                chat_id,
826                chat_type: "private",
827            })
828            .events(raw_event_tx.as_ref())
829            .profile(profile),
830        )
831        .await;
832        drop(raw_event_tx);
833        if let Some(bridge) = bridge {
834            bridge.await?;
835        }
836        let response = response?;
837
838        let bot_msg = StoredMessage {
839            id: uuid::Uuid::new_v4().to_string(),
840            chat_id,
841            sender_name: "microclaw".to_string(),
842            content: response.clone(),
843            is_from_bot: true,
844            timestamp: chrono::Utc::now().to_rfc3339(),
845        };
846        let _ = call_blocking(self.state.db.clone(), move |db| db.store_message(&bot_msg)).await;
847
848        Ok(HeadlessRunResult {
849            run_id,
850            chat_id,
851            response,
852        })
853    }
854
855    /// Cancel active work for a named headless session.
856    ///
857    /// This delegates to the same run-control registry used by chat, Web, and
858    /// scheduler adapters, so callers stop the real Agent Engine rather than
859    /// merely hiding its output.
860    pub async fn cancel_session(&self, session: &str) -> anyhow::Result<usize> {
861        self.cancel_session_for_channel(HEADLESS_CHANNEL, session)
862            .await
863    }
864
865    pub async fn cancel_code_session(&self, session: &str) -> anyhow::Result<usize> {
866        self.cancel_session_for_channel(CODE_CHANNEL, session).await
867    }
868
869    async fn cancel_session_for_channel(
870        &self,
871        channel: &str,
872        session: &str,
873    ) -> anyhow::Result<usize> {
874        let chat_id = self.resolve_session_chat_id(session).await?;
875        Ok(crate::run_control::abort_runs(channel, chat_id).await)
876    }
877
878    /// Add a user update to an active named session.
879    ///
880    /// The shared Agent Engine drains this queue at its normal tool/end-turn
881    /// breakpoints. Returning `false` means the run ended before the update
882    /// could be queued; callers must not report it as accepted.
883    pub async fn steer_session(&self, session: &str, content: &str) -> anyhow::Result<bool> {
884        self.steer_session_for_channel(HEADLESS_CHANNEL, session, content)
885            .await
886    }
887
888    pub async fn steer_code_session(&self, session: &str, content: &str) -> anyhow::Result<bool> {
889        self.steer_session_for_channel(CODE_CHANNEL, session, content)
890            .await
891    }
892
893    async fn steer_session_for_channel(
894        &self,
895        channel: &str,
896        session: &str,
897        content: &str,
898    ) -> anyhow::Result<bool> {
899        let content = content.trim();
900        if content.is_empty() {
901            anyhow::bail!("steering update must not be empty");
902        }
903        let chat_id = self.resolve_session_chat_id(session).await?;
904        let message_id = uuid::Uuid::new_v4().to_string();
905        let timestamp = chrono::Utc::now().to_rfc3339();
906        let pending = PendingMessage {
907            sender_name: "code".into(),
908            content: content.to_string(),
909            message_id: message_id.clone(),
910            timestamp: timestamp.clone(),
911        };
912        if !self
913            .state
914            .chat_turn_queue
915            .enqueue_if_busy(channel, chat_id, pending)
916            .await
917        {
918            return Ok(false);
919        }
920
921        let stored = StoredMessage {
922            id: message_id,
923            chat_id,
924            sender_name: "code".into(),
925            content: content.to_string(),
926            is_from_bot: false,
927            timestamp,
928        };
929        call_blocking(self.state.db.clone(), move |db| db.store_message(&stored)).await?;
930        Ok(true)
931    }
932
933    async fn resolve_session_chat_id(&self, session: &str) -> anyhow::Result<i64> {
934        let external_chat_id = format!("headless:{session}");
935        let title = format!("headless-{session}");
936        Ok(call_blocking(self.state.db.clone(), move |db| {
937            db.resolve_or_create_chat_id(
938                HEADLESS_CHANNEL,
939                &external_chat_id,
940                Some(&title),
941                "headless",
942            )
943        })
944        .await?)
945    }
946}
947
948fn spawn_event_envelope_bridge(
949    run_id: String,
950    mut raw_rx: mpsc::UnboundedReceiver<AgentEvent>,
951    envelope_tx: mpsc::UnboundedSender<RuntimeEventEnvelope>,
952) -> tokio::task::JoinHandle<()> {
953    tokio::spawn(async move {
954        let mut sequence = 0_u64;
955        while let Some(event) = raw_rx.recv().await {
956            sequence = sequence.saturating_add(1);
957            if envelope_tx
958                .send(RuntimeEventEnvelope::new(&run_id, sequence, event))
959                .is_err()
960            {
961                break;
962            }
963        }
964    })
965}
966
967#[allow(clippy::too_many_arguments)]
968pub async fn run_once(
969    config: Config,
970    db: Database,
971    memory: MemoryManager,
972    skills: SkillManager,
973    mcp_manager: crate::mcp::McpManager,
974    prompt: String,
975    session: Option<String>,
976    json: bool,
977) -> anyhow::Result<i32> {
978    let runtime = HeadlessRuntime::new(config, db, memory, skills, mcp_manager)
979        .into_embedded_runtime(HEADLESS_CHANNEL, 1)?;
980    let mut request = RunRequest::new(prompt);
981    request.session_id = session.map(SessionId::new);
982    let result = runtime
983        .agent(AgentProfile {
984            name: "MicroClaw CLI".into(),
985            ..AgentProfile::default()
986        })
987        .run(request)
988        .result()
989        .await;
990
991    match result {
992        Ok(result) => {
993            let chat_id = result
994                .metadata
995                .get("chat_id")
996                .and_then(serde_json::Value::as_i64);
997            if json {
998                println!(
999                    "{}",
1000                    serde_json::json!({
1001                        "ok": true,
1002                        "response": result.final_text,
1003                        "chat_id": chat_id,
1004                        "run_id": result.run_id.to_string(),
1005                    })
1006                );
1007            } else {
1008                println!("{}", result.final_text);
1009            }
1010            Ok(0)
1011        }
1012        Err(e) => {
1013            if json {
1014                println!(
1015                    "{}",
1016                    serde_json::json!({"ok": false, "error": e.to_string()})
1017                );
1018            } else {
1019                eprintln!("Error: {e}");
1020            }
1021            Ok(1)
1022        }
1023    }
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028    use super::*;
1029    use crate::config::WorkingDirIsolation;
1030    use crate::llm::LlmProvider;
1031    use microclaw_core::error::MicroClawError;
1032    use microclaw_core::llm_types::{
1033        Message, MessagesResponse, ResponseContentBlock, ToolDefinition,
1034    };
1035    use microclaw_core::runtime_event::RuntimeEvent;
1036
1037    static RUNTIME_TEST_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
1038        std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
1039
1040    struct FakeLlm;
1041
1042    struct SlowLlm;
1043
1044    struct CapturingLlm {
1045        system_prompt: Arc<std::sync::Mutex<String>>,
1046    }
1047
1048    struct ToolCapturingLlm {
1049        tools: Arc<std::sync::Mutex<Vec<String>>>,
1050    }
1051
1052    struct SteeringLlm {
1053        calls: Arc<std::sync::atomic::AtomicUsize>,
1054        first_call_started: Arc<tokio::sync::Notify>,
1055        saw_update: Arc<std::sync::atomic::AtomicBool>,
1056    }
1057
1058    #[async_trait::async_trait]
1059    impl LlmProvider for FakeLlm {
1060        async fn send_message(
1061            &self,
1062            _system: &str,
1063            _messages: Vec<Message>,
1064            _tools: Option<Vec<ToolDefinition>>,
1065        ) -> Result<MessagesResponse, MicroClawError> {
1066            Ok(MessagesResponse {
1067                content: vec![ResponseContentBlock::Text {
1068                    text: "real agent loop response".into(),
1069                }],
1070                stop_reason: Some("end_turn".into()),
1071                usage: None,
1072            })
1073        }
1074    }
1075
1076    #[async_trait::async_trait]
1077    impl LlmProvider for SlowLlm {
1078        async fn send_message(
1079            &self,
1080            _system: &str,
1081            _messages: Vec<Message>,
1082            _tools: Option<Vec<ToolDefinition>>,
1083        ) -> Result<MessagesResponse, MicroClawError> {
1084            tokio::time::sleep(std::time::Duration::from_secs(30)).await;
1085            unreachable!("the cancellation test must stop the pending model call")
1086        }
1087    }
1088
1089    #[async_trait::async_trait]
1090    impl LlmProvider for CapturingLlm {
1091        async fn send_message(
1092            &self,
1093            system: &str,
1094            _messages: Vec<Message>,
1095            _tools: Option<Vec<ToolDefinition>>,
1096        ) -> Result<MessagesResponse, MicroClawError> {
1097            *self.system_prompt.lock().unwrap() = system.to_string();
1098            Ok(MessagesResponse {
1099                content: vec![ResponseContentBlock::Text {
1100                    text: "profile applied".into(),
1101                }],
1102                stop_reason: Some("end_turn".into()),
1103                usage: None,
1104            })
1105        }
1106    }
1107
1108    #[async_trait::async_trait]
1109    impl LlmProvider for ToolCapturingLlm {
1110        async fn send_message(
1111            &self,
1112            _system: &str,
1113            _messages: Vec<Message>,
1114            tools: Option<Vec<ToolDefinition>>,
1115        ) -> Result<MessagesResponse, MicroClawError> {
1116            *self.tools.lock().unwrap() = tools
1117                .unwrap_or_default()
1118                .into_iter()
1119                .map(|tool| tool.name)
1120                .collect();
1121            Ok(MessagesResponse {
1122                content: vec![ResponseContentBlock::Text {
1123                    text: "policy applied".into(),
1124                }],
1125                stop_reason: Some("end_turn".into()),
1126                usage: None,
1127            })
1128        }
1129    }
1130
1131    #[async_trait::async_trait]
1132    impl LlmProvider for SteeringLlm {
1133        async fn send_message(
1134            &self,
1135            _system: &str,
1136            messages: Vec<Message>,
1137            _tools: Option<Vec<ToolDefinition>>,
1138        ) -> Result<MessagesResponse, MicroClawError> {
1139            let call = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1140            if call == 0 {
1141                self.first_call_started.notify_one();
1142                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1143                return Ok(MessagesResponse {
1144                    content: vec![ResponseContentBlock::ToolUse {
1145                        id: "todo-read-1".into(),
1146                        name: "todo_read".into(),
1147                        input: serde_json::json!({}),
1148                        thought_signature: None,
1149                    }],
1150                    stop_reason: Some("tool_use".into()),
1151                    usage: None,
1152                });
1153            }
1154            let rendered = format!("{messages:?}");
1155            self.saw_update.store(
1156                rendered.contains("Focus on the parser first"),
1157                std::sync::atomic::Ordering::SeqCst,
1158            );
1159            Ok(MessagesResponse {
1160                content: vec![ResponseContentBlock::Text {
1161                    text: "steering applied".into(),
1162                }],
1163                stop_reason: Some("end_turn".into()),
1164                usage: None,
1165            })
1166        }
1167    }
1168
1169    fn runtime_with_fake_llm(base: &Path) -> HeadlessRuntime {
1170        runtime_with_llm(base, Box::new(FakeLlm))
1171    }
1172
1173    fn runtime_with_llm(base: &Path, llm: Box<dyn LlmProvider>) -> HeadlessRuntime {
1174        let runtime_dir = base.join("runtime");
1175        std::fs::create_dir_all(&runtime_dir).unwrap();
1176        let mut config = Config::test_defaults();
1177        config.data_dir = runtime_dir.display().to_string();
1178        config.working_dir = base.display().to_string();
1179        config.working_dir_isolation = WorkingDirIsolation::Shared;
1180        let runtime_dir = runtime_dir.display().to_string();
1181        let db = Arc::new(Database::new(&runtime_dir).unwrap());
1182        let memory_backend = Arc::new(MemoryBackend::local_only(db.clone()));
1183        let channel_registry = Arc::new(ChannelRegistry::new());
1184        HeadlessRuntime {
1185            state: Arc::new(AppState {
1186                config: config.clone(),
1187                channel_registry: channel_registry.clone(),
1188                db: db.clone(),
1189                memory: Arc::new(MemoryManager::new(&runtime_dir)),
1190                skills: Arc::new(SkillManager::from_skills_dir(&config.skills_data_dir())),
1191                hooks: Arc::new(HookManager::from_config(&config)),
1192                llm: Arc::from(llm),
1193                llm_provider_overrides: Arc::new(RwLock::new(HashMap::new())),
1194                llm_model_overrides: Arc::new(RwLock::new(HashMap::new())),
1195                embedding: None,
1196                memory_backend: memory_backend.clone(),
1197                tools: Arc::new(ToolRegistry::new(
1198                    &config,
1199                    channel_registry,
1200                    db,
1201                    memory_backend,
1202                )),
1203                chat_turn_queue: Arc::new(crate::chat_turn_queue::ChatTurnQueue::new(20)),
1204                skill_review_queue: crate::skill_review::build_skill_review_channel().0,
1205                metric_exporter: None,
1206                trace_exporter: None,
1207                log_exporter: None,
1208            }),
1209        }
1210    }
1211
1212    #[tokio::test]
1213    async fn event_bridge_adds_stable_run_id_and_monotonic_sequence() {
1214        let (raw_tx, raw_rx) = mpsc::unbounded_channel();
1215        let (envelope_tx, mut envelope_rx) = mpsc::unbounded_channel();
1216        let bridge = spawn_event_envelope_bridge("work-run-1".into(), raw_rx, envelope_tx);
1217
1218        raw_tx
1219            .send(RuntimeEvent::Iteration { iteration: 1 })
1220            .unwrap();
1221        raw_tx
1222            .send(RuntimeEvent::FinalResponse {
1223                text: "done".into(),
1224            })
1225            .unwrap();
1226        drop(raw_tx);
1227        bridge.await.unwrap();
1228
1229        let first = envelope_rx.recv().await.unwrap();
1230        let second = envelope_rx.recv().await.unwrap();
1231        assert_eq!(first.run_id, "work-run-1");
1232        assert_eq!(first.sequence, 1);
1233        assert_eq!(second.run_id, "work-run-1");
1234        assert_eq!(second.sequence, 2);
1235        assert!(envelope_rx.recv().await.is_none());
1236    }
1237
1238    #[tokio::test]
1239    async fn reusable_runtime_executes_real_agent_loop_and_emits_envelopes() {
1240        let _guard = RUNTIME_TEST_LOCK.lock().await;
1241        let directory = tempfile::tempdir().unwrap();
1242        let runtime = runtime_with_fake_llm(directory.path());
1243        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
1244
1245        let result = runtime
1246            .run(
1247                HeadlessRunRequest::code(
1248                    "answer through the shared loop".into(),
1249                    Some("work-test".into()),
1250                    "work-run-test".into(),
1251                ),
1252                Some(event_tx),
1253            )
1254            .await
1255            .unwrap();
1256        let mut events = Vec::new();
1257        while let Some(event) = event_rx.recv().await {
1258            events.push(event);
1259        }
1260
1261        assert_eq!(result.run_id, "work-run-test");
1262        assert_eq!(result.response, "real agent loop response");
1263        assert!(!events.is_empty());
1264        assert!(events.iter().enumerate().all(|(index, envelope)| {
1265            envelope.run_id == "work-run-test" && envelope.sequence == index as u64 + 1
1266        }));
1267        assert!(events.iter().any(|envelope| matches!(
1268            envelope.event,
1269            RuntimeEvent::FinalResponse { ref text } if text == "real agent loop response"
1270        )));
1271    }
1272
1273    #[tokio::test]
1274    async fn durable_subagents_are_observable_and_cancellable_through_headless_runtime() {
1275        use crate::storage::db::subagents::CreateSubagentRunParams;
1276
1277        let _guard = RUNTIME_TEST_LOCK.lock().await;
1278        let directory = tempfile::tempdir().unwrap();
1279        let runtime = runtime_with_fake_llm(directory.path());
1280        let chat_id = runtime
1281            .resolve_session_chat_id("sdk-session")
1282            .await
1283            .unwrap();
1284        runtime
1285            .state
1286            .db
1287            .create_subagent_run(CreateSubagentRunParams {
1288                run_id: "delegated-1",
1289                parent_run_id: Some("main-1"),
1290                depth: 1,
1291                token_budget: 10_000,
1292                chat_id,
1293                caller_channel: HEADLESS_CHANNEL,
1294                task: "inspect the parser",
1295                context: "",
1296                provider: "test",
1297                model: "test",
1298                label: Some("parser review"),
1299            })
1300            .unwrap();
1301
1302        let tasks = runtime.subagent_runs("sdk-session", 20).unwrap();
1303        assert_eq!(tasks.len(), 1);
1304        assert_eq!(tasks[0].parent_run_id.as_deref(), Some("main-1"));
1305        assert_eq!(tasks[0].depth, 1);
1306        assert_eq!(tasks[0].label.as_deref(), Some("parser review"));
1307        assert!(runtime
1308            .cancel_subagent("sdk-session", "delegated-1")
1309            .unwrap());
1310        assert!(runtime.subagent_runs("sdk-session", 20).unwrap()[0].cancel_requested);
1311    }
1312
1313    #[tokio::test]
1314    async fn embedded_agent_profile_applies_prompt_and_selected_skills() {
1315        let _guard = RUNTIME_TEST_LOCK.lock().await;
1316        let directory = tempfile::tempdir().unwrap();
1317        let captured = Arc::new(std::sync::Mutex::new(String::new()));
1318        let headless = runtime_with_llm(
1319            directory.path(),
1320            Box::new(CapturingLlm {
1321                system_prompt: captured.clone(),
1322            }),
1323        );
1324        let skill_dir = headless.state.skills.skills_dir().join("rust-review");
1325        std::fs::create_dir_all(&skill_dir).unwrap();
1326        std::fs::write(
1327            skill_dir.join("SKILL.md"),
1328            "---\nname: rust-review\ndescription: Review Rust\n---\nCHECK_AGENT_SKILL_BODY\n",
1329        )
1330        .unwrap();
1331        let runtime = headless.into_embedded_runtime(CODE_CHANNEL, 1).unwrap();
1332        let profile = AgentProfile {
1333            name: "reviewer".into(),
1334            system_prompt: Some("CHECK_AGENT_PROFILE_PROMPT".into()),
1335            skills: vec!["rust-review".into()],
1336            ..AgentProfile::default()
1337        };
1338
1339        let result = runtime
1340            .agent(profile)
1341            .run(RunRequest::new("review this crate"))
1342            .result()
1343            .await
1344            .unwrap();
1345
1346        assert_eq!(result.final_text, "profile applied");
1347        let system = captured.lock().unwrap();
1348        assert!(system.contains("CHECK_AGENT_PROFILE_PROMPT"), "{system}");
1349        assert!(system.contains("CHECK_AGENT_SKILL_BODY"), "{system}");
1350    }
1351
1352    #[tokio::test]
1353    async fn embedded_read_only_profile_hides_mutating_tools() {
1354        let _guard = RUNTIME_TEST_LOCK.lock().await;
1355        let directory = tempfile::tempdir().unwrap();
1356        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1357        let runtime = runtime_with_llm(
1358            directory.path(),
1359            Box::new(ToolCapturingLlm {
1360                tools: captured.clone(),
1361            }),
1362        )
1363        .into_embedded_runtime(CODE_CHANNEL, 1)
1364        .unwrap();
1365        let profile = AgentProfile {
1366            name: "reviewer".into(),
1367            tool_policy: microclaw_core::run_protocol::ToolPolicy::ReadOnly,
1368            ..AgentProfile::default()
1369        };
1370
1371        runtime
1372            .agent(profile)
1373            .run(RunRequest::new("inspect this project"))
1374            .result()
1375            .await
1376            .unwrap();
1377
1378        let tools = captured.lock().unwrap();
1379        assert!(tools.iter().any(|name| name == "read_file"), "{tools:?}");
1380        assert!(!tools.iter().any(|name| name == "write_file"), "{tools:?}");
1381        assert!(!tools.iter().any(|name| name == "bash"), "{tools:?}");
1382    }
1383
1384    #[tokio::test]
1385    async fn cancelling_a_headless_session_stops_the_real_agent_loop() {
1386        let _guard = RUNTIME_TEST_LOCK.lock().await;
1387        let directory = tempfile::tempdir().unwrap();
1388        let runtime = Arc::new(runtime_with_llm(directory.path(), Box::new(SlowLlm)));
1389        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
1390        let running_runtime = runtime.clone();
1391        let run = tokio::spawn(async move {
1392            running_runtime
1393                .run(
1394                    HeadlessRunRequest::code(
1395                        "wait for cancellation".into(),
1396                        Some("cancel-test".into()),
1397                        "cancel-run-test".into(),
1398                    ),
1399                    Some(event_tx),
1400                )
1401                .await
1402        });
1403
1404        tokio::time::timeout(std::time::Duration::from_secs(5), async {
1405            loop {
1406                if runtime.cancel_code_session("cancel-test").await.unwrap() > 0 {
1407                    break;
1408                }
1409                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1410            }
1411        })
1412        .await
1413        .expect("run should register for cancellation");
1414
1415        let result = tokio::time::timeout(std::time::Duration::from_secs(5), run)
1416            .await
1417            .expect("cancelled run should finish promptly")
1418            .unwrap()
1419            .unwrap();
1420        assert_eq!(result.response, crate::run_control::STOPPED_TEXT);
1421
1422        let mut cancelled = false;
1423        while let Some(envelope) = event_rx.recv().await {
1424            cancelled |= matches!(envelope.event, RuntimeEvent::Cancelled { .. });
1425        }
1426        assert!(cancelled);
1427    }
1428
1429    #[tokio::test]
1430    async fn steering_uses_the_active_agent_turn_queue() {
1431        let _guard = RUNTIME_TEST_LOCK.lock().await;
1432        let directory = tempfile::tempdir().unwrap();
1433        let runtime = runtime_with_fake_llm(directory.path());
1434        let chat_id = runtime.resolve_session_chat_id("steer-test").await.unwrap();
1435        let turn = runtime
1436            .state
1437            .chat_turn_queue
1438            .acquire(HEADLESS_CHANNEL, chat_id)
1439            .await
1440            .unwrap();
1441
1442        assert!(runtime
1443            .steer_session("steer-test", "Focus on the parser first")
1444            .await
1445            .unwrap());
1446        let pending = runtime
1447            .state
1448            .chat_turn_queue
1449            .drain_pending(HEADLESS_CHANNEL, chat_id)
1450            .await;
1451        assert_eq!(pending.len(), 1);
1452        assert_eq!(pending[0].sender_name, "code");
1453        assert_eq!(pending[0].content, "Focus on the parser first");
1454        drop(turn);
1455
1456        assert!(!runtime
1457            .steer_session("steer-test", "This run is already idle")
1458            .await
1459            .unwrap());
1460    }
1461
1462    #[tokio::test]
1463    async fn steering_reaches_the_real_agent_loop_after_a_tool_breakpoint() {
1464        let _guard = RUNTIME_TEST_LOCK.lock().await;
1465        let directory = tempfile::tempdir().unwrap();
1466        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1467        let first_call_started = Arc::new(tokio::sync::Notify::new());
1468        let saw_update = Arc::new(std::sync::atomic::AtomicBool::new(false));
1469        let runtime = Arc::new(runtime_with_llm(
1470            directory.path(),
1471            Box::new(SteeringLlm {
1472                calls: calls.clone(),
1473                first_call_started: first_call_started.clone(),
1474                saw_update: saw_update.clone(),
1475            }),
1476        ));
1477        let running_runtime = runtime.clone();
1478        let run = tokio::spawn(async move {
1479            running_runtime
1480                .run(
1481                    HeadlessRunRequest::code(
1482                        "Start with the whole task".into(),
1483                        Some("live-steer".into()),
1484                        "live-steer-run".into(),
1485                    ),
1486                    None,
1487                )
1488                .await
1489        });
1490
1491        tokio::time::timeout(
1492            std::time::Duration::from_secs(5),
1493            first_call_started.notified(),
1494        )
1495        .await
1496        .expect("first model call should start");
1497        assert!(runtime
1498            .steer_code_session("live-steer", "Focus on the parser first")
1499            .await
1500            .unwrap());
1501        let result = run.await.unwrap().unwrap();
1502
1503        assert_eq!(result.response, "steering applied");
1504        assert!(calls.load(std::sync::atomic::Ordering::SeqCst) >= 2);
1505        assert!(saw_update.load(std::sync::atomic::Ordering::SeqCst));
1506    }
1507
1508    /// Calls `bash` once, then reports what the tool result said.
1509    struct ApprovalLlm {
1510        calls: Arc<std::sync::atomic::AtomicUsize>,
1511    }
1512
1513    #[async_trait::async_trait]
1514    impl LlmProvider for ApprovalLlm {
1515        async fn send_message(
1516            &self,
1517            _system: &str,
1518            messages: Vec<Message>,
1519            _tools: Option<Vec<ToolDefinition>>,
1520        ) -> Result<MessagesResponse, MicroClawError> {
1521            let call = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1522            if call == 0 {
1523                return Ok(MessagesResponse {
1524                    content: vec![ResponseContentBlock::ToolUse {
1525                        id: "bash-1".into(),
1526                        name: "bash".into(),
1527                        input: serde_json::json!({"command": "echo in-run-ok"}),
1528                        thought_signature: None,
1529                    }],
1530                    stop_reason: Some("tool_use".into()),
1531                    usage: None,
1532                });
1533            }
1534            let rendered = format!("{messages:?}");
1535            let text = if rendered.contains("denied this bash call") {
1536                "saw denial"
1537            } else if rendered.contains("in-run-ok") {
1538                "saw output"
1539            } else {
1540                "saw nothing"
1541            };
1542            Ok(MessagesResponse {
1543                content: vec![ResponseContentBlock::Text { text: text.into() }],
1544                stop_reason: Some("end_turn".into()),
1545                usage: None,
1546            })
1547        }
1548    }
1549
1550    async fn run_with_in_run_answer(session: &str, answer: Option<&str>) -> (String, usize) {
1551        let directory = tempfile::tempdir().unwrap();
1552        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1553        let engine = runtime_with_llm(
1554            directory.path(),
1555            Box::new(ApprovalLlm {
1556                calls: calls.clone(),
1557            }),
1558        );
1559        let runtime = engine.into_embedded_runtime(CODE_CHANNEL, 1).unwrap();
1560        let mut request = RunRequest::new("run the command");
1561        request.session_id = Some(SessionId::new(session));
1562        if answer.is_some() {
1563            request.metadata.insert(
1564                INTERACTIVE_APPROVALS_KEY.into(),
1565                serde_json::Value::Bool(true),
1566            );
1567        }
1568        let mut run = runtime.agent(AgentProfile::default()).run(request);
1569        let controller = run.controller();
1570        let mut approvals = 0;
1571        tokio::time::timeout(std::time::Duration::from_secs(20), async {
1572            while let Some(envelope) = run.next_event().await {
1573                if let RuntimeEvent::ApprovalRequired { approval_id, .. } = envelope.event {
1574                    approvals += 1;
1575                    // Only the in-run request has a waiter; a deferral is
1576                    // followed by the text-path card.
1577                    if let Some(answer) = answer.filter(|_| approvals == 1) {
1578                        controller
1579                            .resolve_approval_confirmed(approval_id, answer)
1580                            .await
1581                            .unwrap();
1582                    }
1583                }
1584            }
1585        })
1586        .await
1587        .expect("run should finish");
1588        let result = run.result().await.unwrap();
1589        (result.final_text, approvals)
1590    }
1591
1592    #[tokio::test]
1593    async fn in_run_approval_continues_the_same_run() {
1594        let _guard = RUNTIME_TEST_LOCK.lock().await;
1595        let (text, approvals) = run_with_in_run_answer("in-run-approve", Some("1")).await;
1596        assert_eq!(approvals, 1);
1597        assert_eq!(text, "saw output");
1598    }
1599
1600    #[tokio::test]
1601    async fn in_run_denial_reaches_the_model_without_running_the_tool() {
1602        let _guard = RUNTIME_TEST_LOCK.lock().await;
1603        let (text, approvals) = run_with_in_run_answer("in-run-deny", Some("deny")).await;
1604        assert_eq!(approvals, 1);
1605        assert_eq!(text, "saw denial");
1606    }
1607
1608    #[tokio::test]
1609    async fn a_deferred_approval_ends_the_run_with_the_text_prompt() {
1610        let _guard = RUNTIME_TEST_LOCK.lock().await;
1611        let (text, approvals) = run_with_in_run_answer("in-run-defer", Some("defer")).await;
1612        // The in-run request, then the text-path card that ends the run.
1613        assert_eq!(approvals, 2);
1614        assert!(text.contains("bash"), "{text}");
1615    }
1616
1617    #[tokio::test]
1618    async fn without_the_opt_in_an_approval_still_ends_the_run() {
1619        let _guard = RUNTIME_TEST_LOCK.lock().await;
1620        let (text, approvals) = run_with_in_run_answer("text-approval", None).await;
1621        assert_eq!(approvals, 1);
1622        assert!(text.contains("bash"), "{text}");
1623        assert!(!crate::approval_broker::is_registered(CODE_CHANNEL, 1));
1624    }
1625
1626    #[tokio::test]
1627    async fn sessions_fork_switch_models_and_compact() {
1628        let _guard = RUNTIME_TEST_LOCK.lock().await;
1629        let directory = tempfile::tempdir().unwrap();
1630        let runtime = runtime_with_fake_llm(directory.path());
1631        runtime
1632            .run(
1633                HeadlessRunRequest::code("first".into(), Some("orig".into()), "r1".into()),
1634                None,
1635            )
1636            .await
1637            .unwrap();
1638        runtime.fork_session("orig", "copy").await.unwrap();
1639        let copied = runtime.session_messages("copy", 10).unwrap();
1640        assert_eq!(copied.len(), 2);
1641        assert_eq!(copied[0].content, "first");
1642        assert!(runtime.fork_session("orig", "copy").await.is_err());
1643        assert!(runtime.fork_session("missing", "x").await.is_err());
1644
1645        let default_model = runtime.session_model(CODE_CHANNEL, "copy").await.unwrap();
1646        assert_eq!(
1647            runtime
1648                .set_session_model(CODE_CHANNEL, "copy", Some("other-model"))
1649                .await
1650                .unwrap(),
1651            "other-model"
1652        );
1653        assert_eq!(
1654            runtime.session_model(CODE_CHANNEL, "orig").await.unwrap(),
1655            default_model
1656        );
1657        assert_eq!(
1658            runtime
1659                .set_session_model(CODE_CHANNEL, "copy", None)
1660                .await
1661                .unwrap(),
1662            default_model
1663        );
1664
1665        let short = runtime
1666            .compact_session(CODE_CHANNEL, "orig", 8)
1667            .await
1668            .unwrap();
1669        assert_eq!(short.messages_before, short.messages_after);
1670        assert!(runtime
1671            .compact_session(CODE_CHANNEL, "never-ran", 8)
1672            .await
1673            .is_err());
1674    }
1675
1676    #[tokio::test]
1677    async fn session_checkpoints_restore_the_workspace() {
1678        let _guard = RUNTIME_TEST_LOCK.lock().await;
1679        let directory = tempfile::tempdir().unwrap();
1680        let mut runtime = runtime_with_fake_llm(directory.path());
1681        Arc::get_mut(&mut runtime.state)
1682            .unwrap()
1683            .config
1684            .checkpoints_enabled = true;
1685        let workspace = directory.path().join("shared");
1686        std::fs::create_dir_all(&workspace).unwrap();
1687        std::fs::write(workspace.join("a.txt"), "one").unwrap();
1688
1689        let first = runtime
1690            .checkpoint_session(CODE_CHANNEL, "cp", "start")
1691            .await
1692            .unwrap()
1693            .unwrap();
1694        // Nothing changed: the same checkpoint comes back.
1695        let again = runtime
1696            .checkpoint_session(CODE_CHANNEL, "cp", "again")
1697            .await
1698            .unwrap()
1699            .unwrap();
1700        assert_eq!(again.commit, first.commit);
1701
1702        std::fs::write(workspace.join("a.txt"), "two").unwrap();
1703        std::fs::write(workspace.join("b.txt"), "new").unwrap();
1704        let before = runtime
1705            .restore_session_checkpoint(CODE_CHANNEL, "cp", &first.commit)
1706            .await
1707            .unwrap()
1708            .unwrap();
1709        assert_eq!(
1710            std::fs::read_to_string(workspace.join("a.txt")).unwrap(),
1711            "one"
1712        );
1713        assert!(!workspace.join("b.txt").exists());
1714        // The state before the restore was kept and can be restored too.
1715        runtime
1716            .restore_session_checkpoint(CODE_CHANNEL, "cp", &before.commit)
1717            .await
1718            .unwrap();
1719        assert_eq!(
1720            std::fs::read_to_string(workspace.join("a.txt")).unwrap(),
1721            "two"
1722        );
1723        assert!(workspace.join("b.txt").exists());
1724        assert!(
1725            runtime
1726                .session_checkpoints(CODE_CHANNEL, "cp", 10)
1727                .await
1728                .unwrap()
1729                .len()
1730                >= 3
1731        );
1732    }
1733}