Skip to main content

orch/engine/
control.rs

1//! Control session — context assembly, one-shot agent invocation, response parsing.
2//!
3//! The control session provides an interactive ops assistant that assembles context
4//! from SQLite (memories, summaries, live state), invokes an agent CLI one-shot
5//! with `--session-id` for conversation continuity, and parses the response for
6//! summary extraction.
7//!
8//! ## Session continuity
9//!
10//! Each named session (e.g., "default", "ops") gets a UUID stored in SQLite KV
11//! (`control:session_id:{name}`). Session agents (claude, kimi, minimax, grok)
12//! receive `--session-id <uuid>` so they resume prior conversation state.
13//! The UUID is regenerated when the agent or model changes.
14//!
15//! ## Model selection
16//!
17//! `/model <spec>` where spec is:
18//! - `agent:model` — explicit agent + model (e.g., `minimax:sonnet`, `opencode:minimax-m2.5-free`)
19//! - `model` — infer agent from model name (e.g., `sonnet` → claude, `gpt-4o` → codex)
20//!
21//! All agents: claude, codex, opencode, kimi, minimax, grok
22//! - kimi and minimax are claude-compatible wrappers (separate binaries in PATH)
23//! - opencode supports `opencode models` for listing available models
24
25use std::collections::HashMap;
26use std::env;
27use std::path::Path;
28use std::process;
29use std::sync::PoisonError;
30use std::sync::{Arc, LazyLock, Mutex};
31use std::time;
32
33use crate::cmd_cache;
34use crate::engine;
35use crate::engine::agents;
36use crate::engine::agents::direct;
37use crate::engine::agents::opencode;
38use crate::engine::agents::{PermissionRules, SandboxLevel};
39use crate::engine::router::RouterConfig;
40use crate::engine::runner::sandbox;
41use crate::github::token;
42use crate::home;
43use crate::store::TaskStore;
44use anyhow::{Context, Result};
45use regex::Regex;
46use sandbox_jail::known;
47use tokio::fs;
48use tokio::process::Command;
49use tokio::sync;
50use tokio::time as tokio_time;
51use tokio::time::{Duration, timeout};
52use uuid::Uuid;
53
54const SUBPROCESS_TIMEOUT: Duration = Duration::from_secs(10);
55
56/// Per-session invocation locks — ensures only one agent invocation runs at a time per session.
57///
58/// Keyed by `session_id`. A new `Arc<tokio::sync::Mutex<()>>` is inserted on first use and
59/// reused for all subsequent calls with the same session_id. Entries are evicted after each
60/// `send_message` call when no concurrent waiters remain. Note: because callers keep a
61/// local `Arc` clone while executing, the map entry + local clone equal 2 strong refs when
62/// there are no other waiters. We therefore test for `Arc::strong_count() == 2` when
63/// deciding to evict the map entry (map entry + local clone). If other waiters exist the
64/// count will be > 2 and we leave the entry in place.
65static SESSION_LOCKS: LazyLock<Mutex<HashMap<String, Arc<sync::Mutex<()>>>>> =
66    LazyLock::new(|| Mutex::new(HashMap::new()));
67
68/// System prompt template, loaded at compile time.
69const SYSTEM_TEMPLATE: &str = include_str!("../../prompts/control_system.md");
70
71/// Timeout for agent invocations (2 minutes).
72const AGENT_TIMEOUT: time::Duration = time::Duration::from_secs(120);
73
74/// Maximum bytes for a single control-session turn payload.
75/// When the combined state + user message exceeds this limit, the payload is split
76/// across multiple sequential turns so the user's question is never truncated.
77const MAX_CONTROL_MESSAGE_BYTES: usize = 32 * 1024;
78
79/// Delivery mode for control session messages.
80enum DeliveryMode {
81    /// Single message delivery (under-limit messages)
82    Single,
83    /// Chunked delivery with session continuity (claude, kimi, minimax) — uses --resume
84    Chunked,
85    /// Chunked delivery without session continuity (codex, opencode) — independent invocations
86    ChunkedNonSession,
87}
88
89/// Parsed model specification from `/model` command.
90#[derive(Debug, Clone, PartialEq)]
91pub struct ModelSpec {
92    pub agent: String,
93    pub model: String,
94}
95
96/// Parsed control command from the chat session.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ControlCommand {
99    Model(Option<String>),
100    Agent(Option<String>),
101    Restart,
102}
103
104/// The agent's first model under `models:` in the config. Empty means orch passes no `--model`
105/// and the agent's CLI uses its own default.
106fn default_model_for_agent(agent: &str) -> String {
107    first_model(&RouterConfig::configured_models(agent))
108}
109
110// A pool keyword such as `opencode:free` names no model, so it is skipped
111fn first_model(models: &[String]) -> String {
112    models
113        .iter()
114        .find(|m| !m.contains(':'))
115        .cloned()
116        .unwrap_or_default()
117}
118
119/// Parse a control-session command.
120pub fn parse_control_command(message: &str) -> Option<ControlCommand> {
121    let trimmed = message.trim();
122    let rest = trimmed.strip_prefix('/')?;
123    let (command, args) = rest
124        .split_once(' ')
125        .map_or((rest, ""), |(cmd, tail)| (cmd, tail.trim()));
126
127    match command {
128        "model" => Some(ControlCommand::Model(
129            (!args.is_empty()).then(|| args.to_string()),
130        )),
131        "agent" => Some(ControlCommand::Agent(
132            (!args.is_empty()).then(|| args.to_string()),
133        )),
134        "restart" => Some(ControlCommand::Restart),
135        _ => None,
136    }
137}
138
139/// Parse a model spec string into agent + model.
140///
141/// Formats:
142/// - `agent:model` → explicit (e.g., `minimax:sonnet`, `opencode:minimax-m2.5-free`)
143/// - `model` → infer agent from model name
144pub fn parse_model_spec(spec: &str, current_agent: &str) -> ModelSpec {
145    if let Some((agent, model)) = spec.split_once(':') {
146        ModelSpec {
147            agent: agent.to_string(),
148            model: RouterConfig::normalize_model_identifier(model),
149        }
150    } else {
151        let model = RouterConfig::normalize_model_identifier(spec);
152        let configured: Vec<(String, Vec<String>)> = engine::configured_agents()
153            .into_iter()
154            .map(|agent| {
155                let models = RouterConfig::configured_models(&agent);
156                (agent, models)
157            })
158            .collect();
159        ModelSpec {
160            agent: infer_agent(&model, &configured, current_agent),
161            model,
162        }
163    }
164}
165
166/// The agent whose `models:` entry lists the model, or the current agent when none does.
167fn infer_agent(model: &str, configured: &[(String, Vec<String>)], current_agent: &str) -> String {
168    configured
169        .iter()
170        .find(|(_, models)| models.iter().any(|m| m == model))
171        .map_or(current_agent, |(agent, _)| agent.as_str())
172        .to_string()
173}
174
175/// Validate that an agent name is known and installed.
176///
177/// Performs lightweight checks (known agent + binary in PATH) without
178/// a test invocation. Used by `/agent` before persisting.
179pub fn validate_agent(agent: &str) -> Result<()> {
180    let agents = engine::configured_agents();
181    if !agents.iter().any(|a| a == agent) {
182        anyhow::bail!(
183            "unknown agent '{}'. Available: {}",
184            agent,
185            agents.join(", ")
186        );
187    }
188    if !cmd_cache::command_exists(agent) {
189        anyhow::bail!("agent '{agent}' not found in PATH. Is it installed?");
190    }
191    Ok(())
192}
193
194/// Validate a model spec by running a quick test invocation.
195///
196/// Sends "hello" to the agent with the specified model to verify
197/// the agent binary exists and the model is available.
198#[expect(clippy::print_stderr, reason = "progress line for `orch chat /model`")]
199pub async fn validate_model(spec: &ModelSpec) -> Result<()> {
200    // 1. Check agent is known and installed
201    validate_agent(&spec.agent)?;
202
203    // 3. For opencode, pre-check against `opencode models` list (fast rejection)
204    if spec.agent == "opencode"
205        && let Ok(models) = list_opencode_models().await
206        && !models.iter().any(|m| m == &spec.model)
207    {
208        let suggestions: Vec<_> = models
209            .iter()
210            .filter(|m| m.contains(&spec.model) || spec.model.contains(m.as_str()))
211            .take(10)
212            .cloned()
213            .collect();
214        let shown = if suggestions.is_empty() {
215            models.iter().take(20).cloned().collect()
216        } else {
217            suggestions
218        };
219        anyhow::bail!(
220            "model '{}' not found in opencode. Available models:\n{}",
221            spec.model,
222            shown.join("\n")
223        );
224    }
225
226    // 4. Test invocation — always run to verify the model actually works
227    eprintln!("Testing {}:{} ...", spec.agent, spec.model);
228    let result = test_invoke(&spec.agent, &spec.model).await;
229    match result {
230        Ok(()) => Ok(()),
231        Err(e) => anyhow::bail!(
232            "model '{}' on agent '{}' is not available: {e}",
233            spec.model,
234            spec.agent
235        ),
236    }
237}
238
239/// List available opencode models via `opencode models`.
240async fn list_opencode_models() -> Result<Vec<String>> {
241    match opencode::run_opencode_models_cli(time::Duration::from_secs(10)).await {
242        (models, "ok" | "empty_output") => Ok(models),
243        (_, reason) => anyhow::bail!("opencode models failed: {reason}"),
244    }
245}
246
247/// Run a minimal test invocation to verify agent+model availability.
248async fn test_invoke(agent: &str, model: &str) -> Result<()> {
249    let msg = "Reply with just the word 'ok'.";
250    // Reuse invoke_agent — it already handles temp files, timeout, and error checking
251    invoke_agent(agent, model, "", msg).await?;
252    Ok(())
253}
254
255/// Assembled context for a chat invocation.
256#[derive(Debug)]
257pub struct ChatContext {
258    /// System prompt (instructions, role, commands)
259    pub system: String,
260    /// User-visible context prepended to the message (live state, memories)
261    pub state: String,
262}
263
264/// Assemble the chat context from SQLite state and live system info.
265pub async fn assemble_context(store: &TaskStore, session_id: &str) -> Result<ChatContext> {
266    // 1. Gather memories from KV (keys matching control:memory:{session}:*)
267    // Use kv_list_prefix which correctly escapes LIKE metacharacters so that
268    // session names containing '_' or '%' don't leak memories from other sessions.
269    let memory_prefix = format!("control:memory:{session_id}:");
270    let raw_memories = store
271        .kv_list_prefix(&memory_prefix)
272        .await
273        .unwrap_or_else(|e| {
274            tracing::warn!(session_id, error = %e, "failed to load control memories from store");
275            Vec::new()
276        });
277    let memories = if raw_memories.is_empty() {
278        "(none)".to_string()
279    } else {
280        raw_memories
281            .iter()
282            .map(|(key, value)| {
283                let short_key = key.strip_prefix("control:memory:").unwrap_or(key);
284                format!("- **{short_key}**: {value}")
285            })
286            .collect::<Vec<_>>()
287            .join("\n")
288    };
289
290    // 2. Recent conversation summaries
291    let summaries = store
292        .control_recent_summaries(session_id, 20)
293        .await
294        .unwrap_or_else(|e| {
295            tracing::warn!(session_id, error = %e, "failed to load control summaries from store");
296            Vec::new()
297        });
298    let recent_summaries = if summaries.is_empty() {
299        "(no recent conversation)".to_string()
300    } else {
301        summaries
302            .iter()
303            .map(|s| format!("- {s}"))
304            .collect::<Vec<_>>()
305            .join("\n")
306    };
307
308    // 3-5. Run independent subprocess calls in parallel (best-effort, 10s timeout each)
309    let (service_status, task_list, job_list) = tokio::join!(
310        async {
311            let mut cmd = Command::new("brew");
312            cmd.args(["services", "info", "orch"]).kill_on_drop(true);
313            match timeout(SUBPROCESS_TIMEOUT, cmd.output()).await {
314                Ok(Ok(output)) if output.status.success() => {
315                    String::from_utf8_lossy(&output.stdout).trim().to_string()
316                }
317                _ => "(could not check service status)".to_string(),
318            }
319        },
320        async {
321            let mut cmd = Command::new("orch");
322            cmd.args(["task", "list"]).kill_on_drop(true);
323            match timeout(SUBPROCESS_TIMEOUT, cmd.output()).await {
324                Ok(Ok(output)) if output.status.success() => {
325                    String::from_utf8_lossy(&output.stdout).trim().to_string()
326                }
327                _ => "(could not fetch live state)".to_string(),
328            }
329        },
330        async {
331            let mut cmd = Command::new("orch");
332            cmd.args(["job", "list"]).kill_on_drop(true);
333            match timeout(SUBPROCESS_TIMEOUT, cmd.output()).await {
334                Ok(Ok(output)) if output.status.success() => {
335                    String::from_utf8_lossy(&output.stdout).trim().to_string()
336                }
337                _ => "(no jobs configured)".to_string(),
338            }
339        },
340    );
341
342    let version = env!("ORCH_VERSION");
343    let state = format!(
344        "## Current Live State\n### Version\norch {version}\n\n### Service\n{service_status}\n\n### Tasks\n{task_list}\n\n### Scheduled Jobs\n{job_list}\n\n### Memories\n{memories}\n\n### Recent Conversation\n{recent_summaries}"
345    );
346
347    // 6. Build system prompt (instructions only, no live state in system prompt)
348    let system = SYSTEM_TEMPLATE.to_string();
349
350    Ok(ChatContext { system, state })
351}
352
353/// Get the current model from KV, defaulting to the current agent's configured model when the
354/// key is absent. Returns an error if the store read fails.
355pub async fn get_model(store: &TaskStore) -> Result<String> {
356    match store
357        .kv_get("control:model")
358        .await
359        .context("reading control:model from store")?
360    {
361        Some(model) => Ok(model),
362        None => Ok(default_model_for_agent(&get_agent(store).await?)),
363    }
364}
365
366/// Get the current agent from KV, defaulting to `"claude"` when the key is absent.
367/// Returns an error if the store read fails.
368pub async fn get_agent(store: &TaskStore) -> Result<String> {
369    Ok(store
370        .kv_get("control:agent")
371        .await
372        .context("reading control:agent from store")?
373        .unwrap_or_else(|| "claude".to_string()))
374}
375
376/// Get the current control session spec from KV.
377pub async fn get_current_spec(store: &TaskStore) -> Result<ModelSpec> {
378    Ok(ModelSpec {
379        agent: get_agent(store).await?,
380        model: get_model(store).await?,
381    })
382}
383
384/// Set the current model in KV.
385pub async fn set_model(store: &TaskStore, model: &str) -> Result<()> {
386    store
387        .kv_set("control:model", model)
388        .await
389        .context("setting control model")?;
390    Ok(())
391}
392
393/// Set the current agent in KV.
394pub async fn set_agent(store: &TaskStore, agent: &str) -> Result<()> {
395    store
396        .kv_set("control:agent", agent)
397        .await
398        .context("setting control agent")?;
399    Ok(())
400}
401
402/// Set the current model and agent in KV.
403pub async fn set_model_spec(store: &TaskStore, spec: &ModelSpec) -> Result<()> {
404    set_model(store, &spec.model).await?;
405    set_agent(store, &spec.agent).await?;
406    Ok(())
407}
408
409/// Set the current agent and its default model in KV.
410pub async fn set_agent_spec(store: &TaskStore, agent: &str) -> Result<ModelSpec> {
411    let spec = ModelSpec {
412        agent: agent.to_string(),
413        model: default_model_for_agent(agent),
414    };
415    set_model_spec(store, &spec).await?;
416    Ok(spec)
417}
418
419fn display_model(model: &str) -> &str {
420    if model.is_empty() { "default" } else { model }
421}
422
423fn format_current_spec(spec: &ModelSpec) -> String {
424    format!("Current: {}:{}", spec.agent, display_model(&spec.model))
425}
426
427fn format_switched_spec(spec: &ModelSpec) -> String {
428    format!(
429        "Switched to **{}:{}** (validated)",
430        spec.agent,
431        display_model(&spec.model)
432    )
433}
434
435async fn handle_control_command(
436    store: &TaskStore,
437    session_id: &str,
438    channel_thread: Option<&str>,
439    command: ControlCommand,
440) -> Result<String> {
441    match command {
442        ControlCommand::Model(None) | ControlCommand::Agent(None) => {
443            Ok(format_current_spec(&get_current_spec(store).await?))
444        }
445        ControlCommand::Model(Some(new_spec)) => {
446            let spec = parse_model_spec(&new_spec, &get_agent(store).await?);
447            validate_model(&spec).await?;
448            set_model_spec(store, &spec).await?;
449            // Reset session UUID so next message starts a fresh conversation
450            reset_session_uuid(store, session_id).await?;
451            Ok(format_switched_spec(&spec))
452        }
453        ControlCommand::Agent(Some(agent)) => {
454            validate_agent(&agent)?;
455            let spec = set_agent_spec(store, &agent).await?;
456            // Reset session UUID so next message starts a fresh conversation
457            reset_session_uuid(store, session_id).await?;
458            Ok(format_switched_spec(&spec))
459        }
460        ControlCommand::Restart => {
461            // Store the conversation key so the post-restart startup check can send a confirmation.
462            if let Some(ct) = channel_thread {
463                store.kv_set("control:restart_pending", ct).await.ok();
464            }
465            // Delay the SIGTERM slightly so the acknowledgment reply is delivered first.
466            tokio::spawn(async {
467                tokio_time::sleep(Duration::from_secs(2)).await;
468                let pid = process::id().to_string();
469                let _ = Command::new("kill").args(["-TERM", &pid]).status().await;
470            });
471            Ok("Restarting orch service\u{2026} I'll confirm here when back online.".to_string())
472        }
473    }
474}
475
476/// Handle a control-session command if present.
477pub async fn maybe_handle_control_command(
478    store: &TaskStore,
479    session_id: &str,
480    channel_thread: Option<&str>,
481    message: &str,
482) -> Result<Option<String>> {
483    Ok(match parse_control_command(message) {
484        Some(command) => {
485            Some(handle_control_command(store, session_id, channel_thread, command).await?)
486        }
487        None => None,
488    })
489}
490
491/// Memory entry parsed from an agent response.
492#[derive(Debug, Clone, PartialEq, Eq)]
493pub struct MemoryEntry {
494    pub key: String,
495    pub value: String,
496}
497
498/// Parsed agent response metadata.
499#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct ParsedResponse {
501    pub clean_text: String,
502    pub summary: Option<String>,
503    pub memories: Vec<MemoryEntry>,
504}
505
506static MEMORY_RE: LazyLock<Regex> = LazyLock::new(|| {
507    Regex::new(r#"(?s)<memory\s+key="([^"]+)">(.+?)</memory>"#).expect("valid memory regex")
508});
509
510static SUMMARY_RE: LazyLock<Regex> =
511    LazyLock::new(|| Regex::new(r"(?s)<summary>(.+?)</summary>").expect("valid summary regex"));
512
513/// Parse an agent response, extracting optional `<summary>` and `<memory>` tags.
514pub fn parse_response(raw: &str) -> ParsedResponse {
515    let mut clean = raw.to_string();
516    let memories = MEMORY_RE
517        .captures_iter(raw)
518        .map(|caps| MemoryEntry {
519            key: caps[1].trim().to_string(),
520            value: caps[2].trim().to_string(),
521        })
522        .collect::<Vec<_>>();
523    clean = MEMORY_RE.replace_all(&clean, "").to_string();
524
525    let summary = SUMMARY_RE
526        .captures(raw)
527        .map(|caps| caps[1].trim().to_string());
528    clean = SUMMARY_RE.replace_all(&clean, "").to_string();
529
530    ParsedResponse {
531        clean_text: clean.trim().to_string(),
532        summary,
533        memories,
534    }
535}
536
537async fn persist_memories(
538    store: &TaskStore,
539    session_id: &str,
540    memories: &[MemoryEntry],
541) -> Result<()> {
542    for memory in memories {
543        store
544            .kv_set(
545                &format!("control:memory:{session_id}:{}", memory.key),
546                &memory.value,
547            )
548            .await
549            .with_context(|| format!("storing control memory {}", memory.key))?;
550    }
551    Ok(())
552}
553
554/// Result of an agent invocation, including response text and token usage.
555#[derive(Debug)]
556pub struct InvokeResult {
557    pub text: String,
558    pub input_tokens: Option<u64>,
559    pub output_tokens: Option<u64>,
560    /// Cost in USD as the agent reported it
561    pub cost_usd: Option<f64>,
562}
563
564// An empty model omits `--model`, so the agent's CLI uses its own default
565fn model_arg(model: &str) -> Option<&str> {
566    (!model.is_empty()).then_some(model)
567}
568
569fn token_u64_to_i64_saturating(tokens: u64) -> i64 {
570    i64::try_from(tokens).unwrap_or(i64::MAX)
571}
572
573fn opt_token_u64_to_i64_saturating(tokens: Option<u64>) -> Option<i64> {
574    tokens.map(token_u64_to_i64_saturating)
575}
576
577fn total_tokens_u64_to_i64_saturating(
578    input_tokens: Option<u64>,
579    output_tokens: Option<u64>,
580) -> Option<i64> {
581    match (input_tokens, output_tokens) {
582        (Some(input), Some(output)) => {
583            Some(token_u64_to_i64_saturating(input.saturating_add(output)))
584        }
585        (Some(tokens), None) | (None, Some(tokens)) => Some(token_u64_to_i64_saturating(tokens)),
586        _ => None,
587    }
588}
589
590/// Prepare temp directory for agent invocation files.
591///
592/// Uses `~/.orch/state/control/{pid}/` for isolation between concurrent processes.
593async fn prepare_temp_dir() -> Result<String> {
594    let home = home::orch_home()?;
595    let dir = format!("{}/state/control/{}", home.display(), process::id());
596    fs::create_dir_all(&dir).await?;
597    Ok(dir)
598}
599
600/// Invoke an agent CLI one-shot and return structured result with token usage.
601///
602/// Delegates to `agents::direct::run_direct()` for command building, execution,
603/// parsing, and error classification.
604///
605/// Writes temp files to `~/.orch/state/control/{pid}/`.
606pub async fn invoke_agent(
607    agent: &str,
608    model: &str,
609    context: &str,
610    message: &str,
611) -> Result<InvokeResult> {
612    let dir = prepare_temp_dir().await?;
613    let place = control_place(agent, &dir).await?;
614    let result = direct::run_direct_at(
615        agent,
616        model_arg(model),
617        context,
618        message,
619        AGENT_TIMEOUT,
620        &place,
621        None,
622    )
623    .await?;
624
625    Ok(InvokeResult {
626        text: result.text,
627        input_tokens: result.input_tokens,
628        output_tokens: result.output_tokens,
629        cost_usd: result.cost_usd,
630    })
631}
632
633/**
634 * A one-shot agent call outside the chat sandbox, for a prompt that holds only the owner's own text,
635 * such as `orch commit`'s diff or a plan to turn into a roadmap. A chat goes through
636 * [`invoke_agent`], whose context can hold text anyone can write
637 **/
638pub async fn invoke_agent_unsandboxed(
639    agent: &str,
640    model: &str,
641    context: &str,
642    message: &str,
643) -> Result<InvokeResult> {
644    let dir = prepare_temp_dir().await?;
645    let result = direct::run_direct(
646        agent,
647        model_arg(model),
648        context,
649        message,
650        AGENT_TIMEOUT,
651        &dir,
652    )
653    .await?;
654
655    Ok(InvokeResult {
656        text: result.text,
657        input_tokens: result.input_tokens,
658        output_tokens: result.output_tokens,
659        cost_usd: result.cost_usd,
660    })
661}
662
663/**
664 * What the control chat may run on a Claude-compatible agent: orch's commands for looking at and
665 * moving tasks, and gh's read commands. Not `orch config`, which prints secrets, nor the commands
666 * that create work, such as `orch task add` or `orch plan`, since issue text could have asked for it
667 **/
668pub const CONTROL_CHAT_TOOLS: &[&str] = &[
669    "Bash(orch task list:*)",
670    "Bash(orch task get:*)",
671    "Bash(orch task status:*)",
672    "Bash(orch task inspect:*)",
673    "Bash(orch task deps:*)",
674    "Bash(orch task log:*)",
675    "Bash(orch task logs:*)",
676    "Bash(orch task history:*)",
677    "Bash(orch task runs:*)",
678    "Bash(orch task cost:*)",
679    "Bash(orch task tree:*)",
680    "Bash(orch task live:*)",
681    "Bash(orch task retry:*)",
682    "Bash(orch task reroute:*)",
683    "Bash(orch task unblock:*)",
684    "Bash(orch task kill:*)",
685    "Bash(orch task close:*)",
686    "Bash(orch task priority:*)",
687    "Bash(orch stats:*)",
688    "Bash(orch cooldown list:*)",
689    "Bash(orch cooldown clear:*)",
690    "Bash(orch job list:*)",
691    "Bash(orch service status:*)",
692    "Bash(gh pr list:*)",
693    "Bash(gh pr view:*)",
694    "Bash(gh run list:*)",
695    "Bash(gh run view:*)",
696    "Bash(gh issue list:*)",
697    "Bash(gh issue view:*)",
698];
699
700/**
701 * Where a control chat agent runs: sandbox-jail around it, which reads orch's home and hides the
702 * rest of the home and every credential. A Claude-compatible agent also runs only
703 * [`CONTROL_CHAT_TOOLS`] and gets orch's GitHub token for them, since `~/.config/gh` is hidden.
704 * Another agent has no allowlist, so it gets the sandbox and no token. Telegram and the other
705 * channels reach this chat, and its context holds task titles anyone can write
706 **/
707/// Secrets in the daemon's environment that the agent must not inherit, all but its own login
708fn secrets_to_unset(agent: &str) -> Vec<String> {
709    let own = agents::login_env_vars(agent);
710    env::vars_os()
711        .filter_map(|(name, _)| name.into_string().ok())
712        .filter(|name| known::secret_env(name) && !own.contains(&name.as_str()))
713        .collect()
714}
715
716async fn control_place(agent: &str, dir: &str) -> Result<direct::DirectPlace> {
717    let sandbox = sandbox::control_argv(Path::new(dir)).context(
718        "the chat runs inside an OS sandbox and none could start here, see the error below",
719    )?;
720    if agents::is_claude_compatible(agent) {
721        let token = token::shared().get_token().await.ok().flatten();
722        return Ok(direct::DirectPlace {
723            files_dir: dir.to_string(),
724            cwd: dir.to_string(),
725            permissions: PermissionRules::read_only(
726                CONTROL_CHAT_TOOLS.iter().map(ToString::to_string).collect(),
727            ),
728            sandbox,
729            env: token
730                .map(|t| vec![("GH_TOKEN".to_string(), t)])
731                .unwrap_or_default(),
732            unset: secrets_to_unset(agent),
733        });
734    }
735
736    // Codex's own sandbox cannot run inside this one, so it runs without its own
737    let mut permissions = PermissionRules::deny_read_only();
738    permissions.sandbox = SandboxLevel::Os;
739    Ok(direct::DirectPlace {
740        files_dir: dir.to_string(),
741        cwd: dir.to_string(),
742        permissions,
743        sandbox,
744        env: Vec::new(),
745        unset: secrets_to_unset(agent),
746    })
747}
748
749/// What a project chat agent may run: read and search the project, and orch's read commands. Not
750/// git, whose `--output` writes a file
751pub const PROJECT_CHAT_TOOLS: &[&str] = &[
752    "Read",
753    "Grep",
754    "Glob",
755    "Bash(orch task list:*)",
756    "Bash(orch task inspect:*)",
757    "Bash(orch task deps:*)",
758    "Bash(orch task log:*)",
759];
760
761/**
762 * A project chat turn. The agent runs in the project folder inside sandbox-jail, which lets it
763 * write only its temp dir and hides the rest of the home and every credential, and it may run
764 * [`PROJECT_CHAT_TOOLS`] and nothing else. Its context holds issue text anyone can write
765 **/
766pub async fn invoke_project_chat(
767    agent: &str,
768    model: &str,
769    context: &str,
770    message: &str,
771    project: &Path,
772) -> Result<InvokeResult> {
773    let dir = prepare_temp_dir().await?;
774    let sandbox = sandbox::chat_argv(project, Path::new(&dir))?;
775    let place = direct::DirectPlace {
776        files_dir: dir.clone(),
777        cwd: project.to_string_lossy().to_string(),
778        permissions: PermissionRules::read_only(
779            PROJECT_CHAT_TOOLS.iter().map(ToString::to_string).collect(),
780        ),
781        sandbox,
782        env: Vec::new(),
783        unset: secrets_to_unset(agent),
784    };
785    let result = direct::run_direct_at(
786        agent,
787        model_arg(model),
788        context,
789        message,
790        AGENT_TIMEOUT,
791        &place,
792        None,
793    )
794    .await?;
795
796    Ok(InvokeResult {
797        text: result.text,
798        input_tokens: result.input_tokens,
799        output_tokens: result.output_tokens,
800        cost_usd: result.cost_usd,
801    })
802}
803
804/// KV key for storing the session UUID for a named session.
805fn session_uuid_key(session_name: &str) -> String {
806    format!("control:session_id:{session_name}")
807}
808
809/// Get or create a session UUID for the given session name.
810///
811/// On first call for a session, generates a new UUID and persists it to KV.
812/// Subsequent calls return the same UUID, giving agents conversation continuity
813/// via `--session-id`.
814/// Get or create a session UUID for the given session name.
815///
816/// On first call for a session, generates a new UUID and persists it to KV.
817/// Subsequent calls return the same UUID, giving agents conversation continuity
818/// via `--session-id` (new) or `--resume` (existing).
819///
820/// Returns `(uuid, is_new)` so callers know whether to create or resume the session.
821pub async fn get_or_create_session_uuid(
822    store: &TaskStore,
823    session_name: &str,
824) -> Result<(String, bool)> {
825    let key = session_uuid_key(session_name);
826    let candidate = Uuid::new_v4().to_string();
827    let stored = store
828        .kv_insert_if_absent(&key, &candidate)
829        .await
830        .context("storing session UUID")?;
831    let is_new = stored == candidate;
832    if is_new {
833        tracing::info!(session_name, uuid = %stored, "created new chat session UUID");
834    }
835    Ok((stored, is_new))
836}
837
838/// Reset the session UUID so the next message starts a fresh conversation.
839///
840/// Called when agent or model changes, since the new agent won't share
841/// the previous agent's session state. Deletes the stored UUID so the next
842/// `get_or_create_session_uuid` call generates a fresh one.
843pub async fn reset_session_uuid(store: &TaskStore, session_name: &str) -> Result<()> {
844    let key = session_uuid_key(session_name);
845    store
846        .kv_delete(&key)
847        .await
848        .context("resetting session UUID")?;
849    tracing::info!(session_name, "reset chat session UUID");
850    Ok(())
851}
852
853/// Invoke an agent one-shot with `--session-id` or `--resume` for conversation continuity.
854///
855/// For claude-compatible agents (claude, kimi, minimax), passes `--session-id <uuid>`
856/// when creating a new session, or `--resume <uuid>` when continuing an existing one.
857/// Other agents get a plain one-shot call.
858pub async fn invoke_agent_with_session(
859    agent: &str,
860    model: &str,
861    context: &str,
862    message: &str,
863    session_uuid: Option<&str>,
864    resume: bool,
865) -> Result<InvokeResult> {
866    let dir = prepare_temp_dir().await?;
867
868    let session = session_uuid.map(|sid| agents::direct::SessionContinuation {
869        session_id: sid,
870        resume,
871    });
872
873    let place = control_place(agent, &dir).await?;
874    let result = direct::run_direct_at(
875        agent,
876        model_arg(model),
877        context,
878        message,
879        AGENT_TIMEOUT,
880        &place,
881        session,
882    )
883    .await?;
884
885    Ok(InvokeResult {
886        text: result.text,
887        input_tokens: result.input_tokens,
888        output_tokens: result.output_tokens,
889        cost_usd: result.cost_usd,
890    })
891}
892
893/// High-level entry point: process a user message and return the assistant response.
894///
895/// Handles `/model` and `/agent` commands, assembles context, invokes the agent,
896/// parses the response for summaries, and stores both user and assistant messages.
897pub async fn send_message(
898    store: &TaskStore,
899    session_id: &str,
900    channel: &str,
901    channel_thread: Option<&str>,
902    message: &str,
903) -> Result<String> {
904    // Handle control commands — don't store as messages.
905    if let Some(response) =
906        maybe_handle_control_command(store, session_id, channel_thread, message).await?
907    {
908        return Ok(response);
909    }
910
911    // Acquire per-session lock — serializes concurrent invocations for the same session.
912    // Messages that arrive while an invocation is running will queue here and execute in order.
913    let session_lock = {
914        let mut map = SESSION_LOCKS.lock().unwrap_or_else(PoisonError::into_inner);
915        Arc::clone(
916            map.entry(session_id.to_string())
917                .or_insert_with(|| Arc::new(sync::Mutex::new(()))),
918        )
919    };
920    let guard = session_lock.lock().await;
921
922    // Store user message
923    store
924        .insert_control_message(
925            session_id,
926            "user",
927            channel,
928            channel_thread,
929            message,
930            None,
931            None,
932            None,
933            None,
934            None,
935            None,
936            None,
937        )
938        .await?;
939
940    // Assemble context
941    let ctx = assemble_context(store, session_id).await?;
942
943    // Resolve model and agent from KV
944    let model = get_model(store).await?;
945    let agent = get_agent(store).await?;
946
947    // Prepend live state to user message so the LLM sees it directly
948    let full_message = format!("{}\n\n---\n\n{}", ctx.state, message);
949
950    // Get or create a session UUID for conversation continuity
951    let (session_uuid, is_new) = get_or_create_session_uuid(store, session_id).await?;
952
953    // When the combined payload exceeds the per-turn limit, split it across multiple
954    // sequential turns so the user's question (trailing content) is never truncated.
955    // For session-supporting agents (claude, kimi, minimax), use --resume for continuity
956    // and persist ALL intermediate assistant responses so local transcript matches provider.
957    // For other agents (codex, opencode), split into chunks and send each as independent
958    // invocation (no --resume), each getting its own persisted assistant response.
959    let agent_has_sessions = agents::supports_session(&agent);
960    let (chunks, delivery_mode) = if full_message.len() > MAX_CONTROL_MESSAGE_BYTES {
961        tracing::info!(
962            bytes = full_message.len(),
963            limit = MAX_CONTROL_MESSAGE_BYTES,
964            agent = %agent,
965            agent_has_sessions,
966            "control session payload exceeds limit"
967        );
968        if agent_has_sessions {
969            // Session agents: split into chunks for sequential delivery with --resume
970            (
971                build_control_chunks(&ctx.state, message, true),
972                DeliveryMode::Chunked,
973            )
974        } else {
975            // Non-session agents: split into chunks, send each independently
976            (
977                build_control_chunks(&ctx.state, message, false),
978                DeliveryMode::ChunkedNonSession,
979            )
980        }
981    } else {
982        (vec![full_message], DeliveryMode::Single)
983    };
984
985    let _num_chunks = chunks.len();
986
987    // Deliver chunks based on mode
988    let result = match delivery_mode {
989        DeliveryMode::Chunked => {
990            // Session-based delivery (claude, kimi, minimax) — use --resume for continuity
991            // Persist ALL intermediate responses so local DB matches provider transcript.
992            let mut active_uuid = session_uuid.clone();
993            let mut is_first_chunk = !is_new;
994            let mut last_result: Option<InvokeResult> = None;
995
996            for chunk in &chunks {
997                let r = invoke_agent_with_session(
998                    &agent,
999                    &model,
1000                    &ctx.system,
1001                    chunk,
1002                    Some(&active_uuid),
1003                    is_first_chunk,
1004                )
1005                .await;
1006                let chunk_result = match r {
1007                    Ok(result) => result,
1008                    Err(e) => {
1009                        let err_str = e.to_string();
1010                        let is_stale = err_str.contains("stale session");
1011                        let is_timeout = err_str.contains("timeout after")
1012                            || err_str.contains("timed out after");
1013                        if is_stale || is_timeout {
1014                            if is_stale {
1015                                tracing::info!(
1016                                    session_id,
1017                                    "chat session UUID expired; resetting and retrying with fresh session"
1018                                );
1019                            } else {
1020                                tracing::info!(
1021                                    session_id,
1022                                    "chat session timed out; resetting and retrying with fresh session"
1023                                );
1024                            }
1025                            reset_session_uuid(store, session_id).await?;
1026                            let (fresh_uuid, _) =
1027                                get_or_create_session_uuid(store, session_id).await?;
1028                            active_uuid = fresh_uuid;
1029                            is_first_chunk = false;
1030                            let fresh_result = invoke_agent_with_session(
1031                                &agent,
1032                                &model,
1033                                &ctx.system,
1034                                chunk,
1035                                Some(&active_uuid),
1036                                false,
1037                            )
1038                            .await?;
1039
1040                            if is_timeout {
1041                                InvokeResult {
1042                                    text: format!(
1043                                        "_(New session started.)_\n\n{}",
1044                                        fresh_result.text
1045                                    ),
1046                                    ..fresh_result
1047                                }
1048                            } else {
1049                                fresh_result
1050                            }
1051                        } else {
1052                            return Err(e);
1053                        }
1054                    }
1055                };
1056
1057                // Persist this chunk's assistant response (even intermediate ones)
1058                let parsed = parse_response(&chunk_result.text);
1059                let total_tokens = total_tokens_u64_to_i64_saturating(
1060                    chunk_result.input_tokens,
1061                    chunk_result.output_tokens,
1062                );
1063                let input_tokens = opt_token_u64_to_i64_saturating(chunk_result.input_tokens);
1064                let output_tokens = opt_token_u64_to_i64_saturating(chunk_result.output_tokens);
1065                let cost_usd = chunk_result.cost_usd;
1066                store
1067                    .insert_control_message(
1068                        session_id,
1069                        "assistant",
1070                        channel,
1071                        channel_thread,
1072                        &parsed.clean_text,
1073                        parsed.summary.as_deref(),
1074                        Some(&model),
1075                        Some(&agent),
1076                        input_tokens,
1077                        output_tokens,
1078                        total_tokens,
1079                        cost_usd,
1080                    )
1081                    .await?;
1082                persist_memories(store, session_id, &parsed.memories).await?;
1083
1084                last_result = Some(chunk_result);
1085            }
1086
1087            // Return final clean_text directly — all chunks already persisted inline
1088            let final_parsed = parse_response(&last_result.expect("at least one chunk").text);
1089            final_parsed.clean_text
1090        }
1091        DeliveryMode::ChunkedNonSession => {
1092            // Non-session agents (codex, opencode) — each chunk is independent invocation
1093            // No --resume, but each chunk's response is persisted to keep transcript complete.
1094            let mut last_text = String::new();
1095
1096            for chunk in &chunks {
1097                let chunk_result = invoke_agent(&agent, &model, &ctx.system, chunk).await?;
1098
1099                // Persist this chunk's assistant response
1100                let parsed = parse_response(&chunk_result.text);
1101                let total_tokens = total_tokens_u64_to_i64_saturating(
1102                    chunk_result.input_tokens,
1103                    chunk_result.output_tokens,
1104                );
1105                let input_tokens = opt_token_u64_to_i64_saturating(chunk_result.input_tokens);
1106                let output_tokens = opt_token_u64_to_i64_saturating(chunk_result.output_tokens);
1107                let cost_usd = chunk_result.cost_usd;
1108                store
1109                    .insert_control_message(
1110                        session_id,
1111                        "assistant",
1112                        channel,
1113                        channel_thread,
1114                        &parsed.clean_text,
1115                        parsed.summary.as_deref(),
1116                        Some(&model),
1117                        Some(&agent),
1118                        input_tokens,
1119                        output_tokens,
1120                        total_tokens,
1121                        cost_usd,
1122                    )
1123                    .await?;
1124                persist_memories(store, session_id, &parsed.memories).await?;
1125
1126                last_text = parsed.clean_text;
1127            }
1128
1129            last_text
1130        }
1131        DeliveryMode::Single => {
1132            // Single message delivery (under-limit messages) — use invoke_agent_with_session
1133            // for conversation continuity with --session-id / --resume
1134            let mut active_uuid = session_uuid.clone();
1135            let mut is_first_chunk = !is_new;
1136            let chunk_result = loop {
1137                let r = invoke_agent_with_session(
1138                    &agent,
1139                    &model,
1140                    &ctx.system,
1141                    &chunks[0],
1142                    Some(&active_uuid),
1143                    is_first_chunk,
1144                )
1145                .await;
1146                match r {
1147                    Ok(result) => break result,
1148                    Err(e) => {
1149                        let err_str = e.to_string();
1150                        let is_stale = err_str.contains("stale session");
1151                        let is_timeout = err_str.contains("timeout after")
1152                            || err_str.contains("timed out after");
1153                        if is_stale || is_timeout {
1154                            if is_stale {
1155                                tracing::info!(
1156                                    session_id,
1157                                    "chat session UUID expired; resetting and retrying with fresh session"
1158                                );
1159                            } else {
1160                                tracing::info!(
1161                                    session_id,
1162                                    "chat session timed out; resetting and retrying with fresh session"
1163                                );
1164                            }
1165                            reset_session_uuid(store, session_id).await?;
1166                            let (fresh_uuid, _) =
1167                                get_or_create_session_uuid(store, session_id).await?;
1168                            active_uuid = fresh_uuid;
1169                            is_first_chunk = false;
1170                            continue;
1171                        }
1172                        return Err(e);
1173                    }
1174                }
1175            };
1176
1177            // Parse response for summary and memory tags
1178            let parsed = parse_response(&chunk_result.text);
1179
1180            // Store assistant message with token usage.
1181            // Must happen before persist_memories so that if the DB write fails the
1182            // KV store is not left with orphaned memory keys that have no corresponding
1183            // conversation history entry.
1184            let total_tokens = total_tokens_u64_to_i64_saturating(
1185                chunk_result.input_tokens,
1186                chunk_result.output_tokens,
1187            );
1188            let input_tokens = opt_token_u64_to_i64_saturating(chunk_result.input_tokens);
1189            let output_tokens = opt_token_u64_to_i64_saturating(chunk_result.output_tokens);
1190            let cost_usd = chunk_result.cost_usd;
1191            store
1192                .insert_control_message(
1193                    session_id,
1194                    "assistant",
1195                    channel,
1196                    channel_thread,
1197                    &parsed.clean_text,
1198                    parsed.summary.as_deref(),
1199                    Some(&model),
1200                    Some(&agent),
1201                    input_tokens,
1202                    output_tokens,
1203                    total_tokens,
1204                    cost_usd,
1205                )
1206                .await?;
1207            persist_memories(store, session_id, &parsed.memories).await?;
1208
1209            parsed.clean_text
1210        }
1211    };
1212
1213    // Release the per-session lock before eviction check.
1214    drop(guard);
1215
1216    // Evict the session lock entry if no concurrent waiters are holding a reference.
1217    // After drop(guard) above the remaining strong references are:
1218    // - the map entry
1219    // - the local `session_lock` clone held by this function.
1220    // That sums to 2 when there are no other waiters. If another waiter entered
1221    // concurrently the count will be > 2 and we should not evict. Only remove the
1222    // map entry when the strong_count == 2.
1223    if Arc::strong_count(&session_lock) == 2 {
1224        let mut map = SESSION_LOCKS.lock().unwrap_or_else(PoisonError::into_inner);
1225        // Re-check under the map lock: a concurrent caller may have cloned the Arc
1226        // between our strong_count check above and acquiring the map lock.
1227        if map
1228            .get(session_id)
1229            .is_some_and(|l| Arc::strong_count(l) == 2)
1230        {
1231            map.remove(session_id);
1232        }
1233    }
1234
1235    Ok(result)
1236}
1237
1238/// Split `text` into chunks of at most `max_bytes` bytes each.
1239/// Prefers splitting at newline boundaries to preserve readability.
1240fn chunk_text(text: &str, max_bytes: usize) -> Vec<String> {
1241    if text.len() <= max_bytes {
1242        return vec![text.to_string()];
1243    }
1244    let mut chunks = Vec::new();
1245    let mut start = 0;
1246    let total = text.len();
1247
1248    while start < total {
1249        let mut end = (start + max_bytes).min(total);
1250        // Respect UTF-8 char boundaries
1251        while end > start && !text.is_char_boundary(end) {
1252            end -= 1;
1253        }
1254        if end == start {
1255            // Single char exceeds limit — advance past it
1256            if let Some(ch) = text[start..].chars().next() {
1257                end = start + ch.len_utf8();
1258            } else {
1259                break;
1260            }
1261        }
1262        // Prefer splitting at a newline within the chunk
1263        if end < total
1264            && let Some(nl_offset) = text[start..end].rfind('\n')
1265        {
1266            end = start + nl_offset + 1;
1267        }
1268        chunks.push(text[start..end].to_string());
1269        start = end;
1270    }
1271    chunks
1272}
1273
1274/// Build control session message chunks for agents with or without session support.
1275///
1276/// For session-supporting agents (claude, kimi, minimax), chunks are raw text pieces
1277/// that will be sent sequentially with `--resume` for conversation continuity.
1278///
1279/// For non-session agents (codex, opencode), each chunk is prefixed with a header
1280/// indicating its position in the sequence, since each invocation is independent.
1281fn build_control_chunks(state: &str, message: &str, agent_has_sessions: bool) -> Vec<String> {
1282    let header_reserve = if agent_has_sessions { 0 } else { 200 };
1283    let effective_limit = MAX_CONTROL_MESSAGE_BYTES.saturating_sub(header_reserve);
1284    let mut parts = Vec::new();
1285
1286    // Split state into chunks
1287    let state_chunks = chunk_text(state, effective_limit);
1288    for (i, chunk) in state_chunks.iter().enumerate() {
1289        let prefixed = if agent_has_sessions {
1290            chunk.clone()
1291        } else {
1292            format!(
1293                "[Context chunk {}/{}]\n{}",
1294                i + 1,
1295                state_chunks.len(),
1296                chunk
1297            )
1298        };
1299        parts.push(prefixed);
1300    }
1301
1302    // Split user message if needed, then add as final chunk(s)
1303    let msg_chunks = chunk_text(message, effective_limit);
1304    for (i, chunk) in msg_chunks.iter().enumerate() {
1305        let prefixed = if agent_has_sessions {
1306            chunk.clone()
1307        } else if msg_chunks.len() == 1 {
1308            format!("[Context complete. User question:]\n{chunk}")
1309        } else {
1310            format!(
1311                "[User question chunk {}/{}]\n{}",
1312                i + 1,
1313                msg_chunks.len(),
1314                chunk
1315            )
1316        };
1317        parts.push(prefixed);
1318    }
1319    parts
1320}
1321
1322#[cfg(test)]
1323mod tests {
1324    use tokio::runtime::Runtime;
1325
1326    use std::collections::BTreeSet;
1327
1328    use super::*;
1329    use crate::store::TaskStore;
1330
1331    #[test]
1332    fn parse_spec_agent_model() {
1333        let spec = parse_model_spec("minimax:sonnet", "claude");
1334        assert_eq!(spec.agent, "minimax");
1335        assert_eq!(spec.model, "sonnet");
1336    }
1337
1338    #[test]
1339    fn parse_spec_opencode_model() {
1340        let spec = parse_model_spec("opencode:minimax-m2.5-free", "claude");
1341        assert_eq!(spec.agent, "opencode");
1342        assert_eq!(spec.model, "minimax-m2.5-free");
1343    }
1344
1345    fn configured(entries: &[(&str, &[&str])]) -> Vec<(String, Vec<String>)> {
1346        entries
1347            .iter()
1348            .map(|(agent, models)| {
1349                (
1350                    agent.to_string(),
1351                    models.iter().map(ToString::to_string).collect(),
1352                )
1353            })
1354            .collect()
1355    }
1356
1357    #[test]
1358    fn infer_agent_finds_the_agent_whose_config_lists_the_model() {
1359        let configured = configured(&[("claude", &["sonnet"]), ("codex", &["gpt-4o"])]);
1360        assert_eq!(infer_agent("gpt-4o", &configured, "claude"), "codex");
1361        assert_eq!(infer_agent("sonnet", &configured, "codex"), "claude");
1362    }
1363
1364    #[test]
1365    fn infer_agent_keeps_the_current_agent_for_an_unlisted_model() {
1366        let configured = configured(&[("claude", &["sonnet"])]);
1367        assert_eq!(
1368            infer_agent("deepseek-r1", &configured, "opencode"),
1369            "opencode"
1370        );
1371    }
1372
1373    #[test]
1374    fn first_model_skips_pool_keywords() {
1375        let models = vec!["opencode:free".to_string(), "provider/model".to_string()];
1376        assert_eq!(first_model(&models), "provider/model");
1377    }
1378
1379    #[test]
1380    fn first_model_is_empty_without_models() {
1381        assert_eq!(first_model(&[]), "");
1382        assert_eq!(model_arg(""), None);
1383        assert_eq!(model_arg("sonnet"), Some("sonnet"));
1384    }
1385
1386    #[tokio::test]
1387    async fn assemble_context_includes_memories_and_summaries() {
1388        let store = TaskStore::open_memory().await.unwrap();
1389        store
1390            .kv_set("control:memory:default:tz", "User timezone is UTC-3")
1391            .await
1392            .unwrap();
1393        store
1394            .insert_control_message(
1395                "default",
1396                "assistant",
1397                "cli",
1398                None,
1399                "response",
1400                Some("checked status"),
1401                Some("sonnet"),
1402                Some("claude"),
1403                None,
1404                None,
1405                None,
1406                None,
1407            )
1408            .await
1409            .unwrap();
1410
1411        let ctx = assemble_context(&store, "default").await.unwrap();
1412        assert!(ctx.state.contains("UTC-3"), "should include memories");
1413        assert!(
1414            ctx.state.contains("checked status"),
1415            "should include summaries"
1416        );
1417    }
1418
1419    #[test]
1420    fn extract_summary_from_response() {
1421        let response = "Here are your tasks.\n\n<summary>listed 3 active tasks</summary>";
1422        let parsed = parse_response(response);
1423        assert_eq!(parsed.summary.as_deref(), Some("listed 3 active tasks"));
1424        assert!(!parsed.clean_text.contains("<summary>"));
1425    }
1426
1427    #[test]
1428    fn extract_summary_missing() {
1429        let response = "No tasks found.";
1430        let parsed = parse_response(response);
1431        assert_eq!(parsed.summary, None);
1432        assert_eq!(parsed.clean_text, "No tasks found.");
1433    }
1434
1435    #[test]
1436    fn extract_summary_closing_tag_before_opening_does_not_panic() {
1437        // </summary> appears before <summary> — must not panic
1438        let response = "Example: </summary> is a closing tag.\n<summary>actual summary</summary>";
1439        let parsed = parse_response(response);
1440        assert_eq!(parsed.summary.as_deref(), Some("actual summary"));
1441        assert!(!parsed.clean_text.contains("<summary>"));
1442    }
1443
1444    #[test]
1445    fn extract_memory_tags() {
1446        let response = r#"Remember these.
1447
1448<memory key="tz">User timezone is UTC-3</memory>
1449<memory key="theme">Prefer concise answers</memory>
1450
1451<summary>stored two memories</summary>"#;
1452        let parsed = parse_response(response);
1453        assert_eq!(parsed.memories.len(), 2);
1454        assert_eq!(parsed.memories[0].key, "tz");
1455        assert_eq!(parsed.memories[0].value, "User timezone is UTC-3");
1456        assert_eq!(parsed.memories[1].key, "theme");
1457        assert_eq!(parsed.memories[1].value, "Prefer concise answers");
1458        assert_eq!(parsed.summary.as_deref(), Some("stored two memories"));
1459        assert!(!parsed.clean_text.contains("<memory"));
1460    }
1461
1462    #[tokio::test]
1463    async fn persist_memories_writes_to_kv() {
1464        let store = TaskStore::open_memory().await.unwrap();
1465        let memories = vec![MemoryEntry {
1466            key: "tz".to_string(),
1467            value: "User timezone is UTC-3".to_string(),
1468        }];
1469
1470        persist_memories(&store, "default", &memories)
1471            .await
1472            .unwrap();
1473
1474        assert_eq!(
1475            store
1476                .kv_get("control:memory:default:tz")
1477                .await
1478                .unwrap()
1479                .as_deref(),
1480            Some("User timezone is UTC-3")
1481        );
1482    }
1483
1484    #[tokio::test]
1485    async fn send_message_model_switch() {
1486        let store = TaskStore::open_memory().await.unwrap();
1487        set_agent(&store, "unlisted-agent").await.unwrap();
1488        let model = get_model(&store).await.unwrap();
1489        assert_eq!(model, "", "an agent with no models: entry gets no --model");
1490
1491        // /model with explicit agent:model — will fail validation (no binary in test)
1492        // so test parse_model_spec + set_model_spec directly
1493        let spec = parse_model_spec("minimax:sonnet", "claude");
1494        set_model_spec(&store, &spec).await.unwrap();
1495        assert_eq!(get_model(&store).await.unwrap(), "sonnet");
1496        assert_eq!(get_agent(&store).await.unwrap(), "minimax");
1497    }
1498
1499    #[tokio::test]
1500    async fn send_message_model_show_current() {
1501        let store = TaskStore::open_memory().await.unwrap();
1502        set_agent(&store, "unlisted-agent").await.unwrap();
1503        let response = send_message(&store, "default", "cli", None, "/model")
1504            .await
1505            .unwrap();
1506        assert_eq!(response, "Current: unlisted-agent:default");
1507    }
1508
1509    #[tokio::test]
1510    async fn send_message_agent_show_current() {
1511        let store = TaskStore::open_memory().await.unwrap();
1512        set_agent(&store, "unlisted-agent").await.unwrap();
1513        let response = send_message(&store, "default", "cli", None, "/agent")
1514            .await
1515            .unwrap();
1516        assert_eq!(response, "Current: unlisted-agent:default");
1517    }
1518
1519    #[tokio::test]
1520    async fn send_message_agent_switches_with_default_model() {
1521        let store = TaskStore::open_memory().await.unwrap();
1522        // Directly set agent spec to bypass validation (no binary in test env)
1523        let spec = set_agent_spec(&store, "unlisted-agent").await.unwrap();
1524        assert_eq!(spec.agent, "unlisted-agent");
1525        assert_eq!(
1526            spec.model, "",
1527            "an agent with no models: entry gets no --model"
1528        );
1529        assert_eq!(get_agent(&store).await.unwrap(), "unlisted-agent");
1530        assert_eq!(get_model(&store).await.unwrap(), "");
1531    }
1532
1533    #[test]
1534    fn parse_control_command_model_and_agent() {
1535        assert_eq!(
1536            parse_control_command("/model"),
1537            Some(ControlCommand::Model(None))
1538        );
1539        assert_eq!(
1540            parse_control_command("/agent"),
1541            Some(ControlCommand::Agent(None))
1542        );
1543        assert_eq!(
1544            parse_control_command("/agent codex"),
1545            Some(ControlCommand::Agent(Some("codex".to_string())))
1546        );
1547        assert_eq!(
1548            parse_control_command("/model opencode:deepseek-r1"),
1549            Some(ControlCommand::Model(Some(
1550                "opencode:deepseek-r1".to_string()
1551            )))
1552        );
1553        assert_eq!(
1554            parse_control_command("/restart"),
1555            Some(ControlCommand::Restart)
1556        );
1557        assert_eq!(parse_control_command("/kill"), None);
1558        assert_eq!(parse_control_command("/session"), None);
1559    }
1560
1561    #[test]
1562    fn control_prompt_slash_commands_match_supported_surface() {
1563        let documented = Regex::new(r"`/([a-z]+)(?:[^`]*)`")
1564            .unwrap()
1565            .captures_iter(SYSTEM_TEMPLATE)
1566            .map(|caps| caps[1].to_string())
1567            .collect::<BTreeSet<_>>();
1568
1569        let expected = ["agent", "model", "restart"]
1570            .into_iter()
1571            .map(str::to_string)
1572            .collect::<BTreeSet<_>>();
1573
1574        assert_eq!(documented, expected);
1575    }
1576
1577    #[tokio::test]
1578    async fn set_agent_spec_persists_default_model() {
1579        let store = TaskStore::open_memory().await.unwrap();
1580        let spec = set_agent_spec(&store, "unlisted-agent").await.unwrap();
1581        assert_eq!(spec.agent, "unlisted-agent");
1582        assert_eq!(spec.model, "");
1583        assert_eq!(get_agent(&store).await.unwrap(), "unlisted-agent");
1584        assert_eq!(get_model(&store).await.unwrap(), "");
1585    }
1586
1587    #[tokio::test]
1588    async fn send_message_model_switch_does_not_store() {
1589        let store = TaskStore::open_memory().await.unwrap();
1590        // set directly to avoid validation in test env
1591        let spec = parse_model_spec("claude:haiku", "claude");
1592        set_model_spec(&store, &spec).await.unwrap();
1593        let messages = store
1594            .list_control_messages("default", None, 10)
1595            .await
1596            .unwrap();
1597        assert_eq!(messages.len(), 0);
1598    }
1599
1600    #[test]
1601    fn validate_unknown_agent_fails() {
1602        let spec = ModelSpec {
1603            agent: "nonexistent".to_string(),
1604            model: "test".to_string(),
1605        };
1606        let rt = Runtime::new().unwrap();
1607        let result = rt.block_on(validate_model(&spec));
1608        assert!(result.is_err());
1609        assert!(result.unwrap_err().to_string().contains("unknown agent"));
1610    }
1611
1612    #[test]
1613    fn validate_agent_rejects_unknown() {
1614        let result = validate_agent("nonexistent");
1615        assert!(result.is_err());
1616        let err = result.unwrap_err().to_string();
1617        assert!(err.contains("unknown agent"), "got: {err}");
1618    }
1619
1620    #[test]
1621    fn validate_agent_rejects_empty() {
1622        let result = validate_agent("");
1623        assert!(result.is_err());
1624        assert!(result.unwrap_err().to_string().contains("unknown agent"));
1625    }
1626
1627    #[tokio::test]
1628    async fn agent_command_rejects_unknown_before_persisting() {
1629        let store = TaskStore::open_memory().await.unwrap();
1630        // Set a known-good agent first
1631        set_agent(&store, "claude").await.unwrap();
1632
1633        // Try switching to an unknown agent — should fail
1634        let result =
1635            maybe_handle_control_command(&store, "default", None, "/agent bogusagent").await;
1636        assert!(result.is_err(), "should reject unknown agent");
1637        assert!(result.unwrap_err().to_string().contains("unknown agent"));
1638
1639        // Verify the original agent is still set (not overwritten)
1640        assert_eq!(get_agent(&store).await.unwrap(), "claude");
1641    }
1642
1643    #[test]
1644    fn token_u64_to_i64_saturating_caps_large_values() {
1645        assert_eq!(token_u64_to_i64_saturating(u64::MAX), i64::MAX);
1646    }
1647
1648    #[test]
1649    fn total_tokens_u64_to_i64_saturating_caps_single_large_value() {
1650        assert_eq!(
1651            total_tokens_u64_to_i64_saturating(Some(u64::MAX), None),
1652            Some(i64::MAX)
1653        );
1654    }
1655
1656    #[test]
1657    fn total_tokens_u64_to_i64_saturating_caps_large_sum() {
1658        assert_eq!(
1659            total_tokens_u64_to_i64_saturating(Some(u64::MAX), Some(1)),
1660            Some(i64::MAX)
1661        );
1662    }
1663
1664    #[tokio::test]
1665    async fn insert_control_message_stores_cost_usd() {
1666        let store = TaskStore::open_memory().await.unwrap();
1667
1668        let input_tokens: u64 = 500_000;
1669        let output_tokens: u64 = 100_000;
1670        let cost_usd = Some(0.25);
1671
1672        store
1673            .insert_control_message(
1674                "default",
1675                "assistant",
1676                "cli",
1677                None,
1678                "hello",
1679                Some("greeted"),
1680                Some("sonnet"),
1681                Some("claude"),
1682                opt_token_u64_to_i64_saturating(Some(input_tokens)),
1683                opt_token_u64_to_i64_saturating(Some(output_tokens)),
1684                total_tokens_u64_to_i64_saturating(Some(input_tokens), Some(output_tokens)),
1685                cost_usd,
1686            )
1687            .await
1688            .unwrap();
1689
1690        let messages = store
1691            .list_control_messages("default", None, 10)
1692            .await
1693            .unwrap();
1694        assert_eq!(messages.len(), 1);
1695        let msg = &messages[0];
1696        assert!(msg.cost_usd.is_some(), "cost_usd must be stored, not NULL");
1697        assert_eq!(
1698            msg.cost_usd,
1699            Some(0.25),
1700            "the reported cost is stored as is"
1701        );
1702    }
1703
1704    #[tokio::test]
1705    async fn session_uuid_created_and_stable() {
1706        let store = TaskStore::open_memory().await.unwrap();
1707        let (uuid1, is_new1) = get_or_create_session_uuid(&store, "default").await.unwrap();
1708        let (uuid2, is_new2) = get_or_create_session_uuid(&store, "default").await.unwrap();
1709        assert_eq!(uuid1, uuid2, "same session should return same UUID");
1710        assert!(is_new1, "first call should be new");
1711        assert!(!is_new2, "second call should be existing");
1712        assert_eq!(uuid1.len(), 36, "should be a valid UUID string");
1713    }
1714
1715    #[tokio::test]
1716    async fn session_uuid_differs_per_session() {
1717        let store = TaskStore::open_memory().await.unwrap();
1718        let (uuid_default, _) = get_or_create_session_uuid(&store, "default").await.unwrap();
1719        let (uuid_ops, _) = get_or_create_session_uuid(&store, "ops").await.unwrap();
1720        assert_ne!(uuid_default, uuid_ops);
1721    }
1722
1723    #[tokio::test]
1724    async fn session_uuid_reset_creates_new() {
1725        let store = TaskStore::open_memory().await.unwrap();
1726        let (uuid1, _) = get_or_create_session_uuid(&store, "default").await.unwrap();
1727        reset_session_uuid(&store, "default").await.unwrap();
1728        let (uuid2, is_new2) = get_or_create_session_uuid(&store, "default").await.unwrap();
1729        assert_ne!(uuid1, uuid2, "reset should produce a new UUID");
1730        assert!(is_new2, "after reset should be new");
1731    }
1732
1733    /// Verify that the timeout error patterns used in send_message recovery match
1734    /// the actual error strings produced by the agent runner (AgentError::Timeout
1735    /// formats as "timeout after Xs"; run_shell_command formats as "agent timed out
1736    /// after Xs"). Both must trigger session reset rather than bubbling up as errors.
1737    #[test]
1738    fn timeout_error_patterns_match_runner_output() {
1739        let patterns = ["timeout after 1800s", "agent timed out after 120s"];
1740        for &msg in &patterns {
1741            let is_timeout = msg.contains("timeout after") || msg.contains("timed out after");
1742            assert!(is_timeout, "pattern should be detected as timeout: {msg:?}");
1743        }
1744        // Unrelated errors must not be misidentified as timeouts.
1745        let non_timeout = [
1746            "rate limit: 429",
1747            "stale session (session expired): abc",
1748            "auth error: invalid key",
1749        ];
1750        for &msg in &non_timeout {
1751            let is_timeout = msg.contains("timeout after") || msg.contains("timed out after");
1752            assert!(
1753                !is_timeout,
1754                "pattern must not be detected as timeout: {msg:?}"
1755            );
1756        }
1757    }
1758
1759    // ── chunk_text ──────────────────────────────────────────────────────────────
1760
1761    #[test]
1762    fn chunk_text_under_limit_returns_single_chunk() {
1763        let text = "hello world";
1764        let chunks = chunk_text(text, 100);
1765        assert_eq!(chunks, vec!["hello world".to_string()]);
1766    }
1767
1768    #[test]
1769    fn chunk_text_exact_limit_returns_single_chunk() {
1770        let text = "abcde";
1771        let chunks = chunk_text(text, 5);
1772        assert_eq!(chunks.len(), 1);
1773        assert_eq!(chunks[0], "abcde");
1774    }
1775
1776    #[test]
1777    fn chunk_text_splits_and_reassembles() {
1778        let text = "line1\nline2\nline3\nline4\nline5";
1779        let chunks = chunk_text(text, 12);
1780        let reassembled: String = chunks.join("");
1781        assert_eq!(reassembled, text);
1782    }
1783
1784    #[test]
1785    fn chunk_text_respects_utf8_boundaries() {
1786        // 4-byte emoji placed at the split boundary
1787        let content = format!("{}😀", "x".repeat(97)); // 101 bytes; limit=100 cuts inside emoji
1788
1789        let chunks = chunk_text(&content, 100);
1790        let reassembled: String = chunks.join("");
1791        assert_eq!(reassembled, content);
1792        for c in &chunks {
1793            assert!(
1794                str::from_utf8(c.as_bytes()).is_ok(),
1795                "chunk is not valid UTF-8"
1796            );
1797        }
1798    }
1799
1800    #[test]
1801    fn chunk_text_prefers_newline_boundary() {
1802        // "aaaa\nbbbb" with limit=6 — should split after the '\n', not mid-word
1803        let text = "aaaa\nbbbb";
1804        let chunks = chunk_text(text, 6);
1805        // First chunk should end with '\n' (split at newline, not byte 6 into "aaaa\nb")
1806        assert!(
1807            chunks[0].ends_with('\n'),
1808            "expected split at newline, got: {:?}",
1809            chunks[0]
1810        );
1811        let reassembled: String = chunks.join("");
1812        assert_eq!(reassembled, text);
1813    }
1814
1815    #[test]
1816    fn chunk_text_empty_string() {
1817        let chunks = chunk_text("", 32);
1818        assert!(chunks.is_empty() || chunks == vec![String::new()]);
1819    }
1820
1821    // ── build_control_chunks ────────────────────────────────────────────────
1822
1823    #[test]
1824    fn build_control_chunks_session_agent_splits_state_and_message() {
1825        // build_control_chunks always splits state and message into separate chunks
1826        // (it's only called when full_message exceeds the limit)
1827        let state = "state content";
1828        let message = "user question";
1829        let chunks = build_control_chunks(state, message, true);
1830        assert_eq!(chunks.len(), 2);
1831        assert_eq!(chunks[0], "state content");
1832        assert_eq!(chunks[1], "user question");
1833    }
1834
1835    #[test]
1836    fn build_control_chunks_session_agent_long_state_splits() {
1837        // Long state gets split into multiple chunks
1838        let state = "line\n".repeat(10000); // ~60KB
1839        let message = "question";
1840        let chunks = build_control_chunks(&state, message, true);
1841        // Should have multiple state chunks + 1 message chunk
1842        assert!(chunks.len() >= 3);
1843        // All but last are state chunks
1844        for chunk in &chunks[..chunks.len() - 1] {
1845            assert!(chunk.contains("line"));
1846        }
1847        // Last is message
1848        assert_eq!(chunks.last().unwrap(), "question");
1849    }
1850
1851    #[test]
1852    fn build_control_chunks_non_session_agent_adds_headers() {
1853        let state = "state content";
1854        let message = "user question";
1855        let chunks = build_control_chunks(state, message, false);
1856        assert_eq!(chunks.len(), 2);
1857        assert!(chunks[0].starts_with("[Context chunk 1/1]"));
1858        assert!(chunks[0].contains("state content"));
1859        assert!(chunks[1].starts_with("[Context complete. User question:]"));
1860        assert!(chunks[1].contains("user question"));
1861    }
1862
1863    #[test]
1864    fn build_control_chunks_non_session_agent_splits_long_message() {
1865        let state = "state";
1866        let message = "x".repeat(50000); // Exceeds 32KB limit
1867        let chunks = build_control_chunks(state, &message, false);
1868        // Should have 1 state chunk + multiple message chunks
1869        assert!(chunks.len() >= 2);
1870        assert!(chunks[0].starts_with("[Context chunk 1/1]"));
1871        // Message chunks should have question headers
1872        for chunk in &chunks[1..] {
1873            assert!(chunk.starts_with("[User question chunk"));
1874        }
1875        // Verify reassembly (without headers)
1876        let reassembled_state = chunks[0].split_once('\n').map_or("", |(_, r)| r);
1877        assert_eq!(reassembled_state, "state");
1878    }
1879
1880    #[test]
1881    fn build_control_chunks_non_session_agent_long_state_splits() {
1882        let state = "line\n".repeat(10000); // ~60KB
1883        let message = "question";
1884        let chunks = build_control_chunks(&state, message, false);
1885        // Multiple state chunks + 1 message chunk
1886        assert!(chunks.len() >= 3);
1887        for (i, chunk) in chunks.iter().enumerate() {
1888            if i < chunks.len() - 1 {
1889                assert!(chunk.starts_with(&format!("[Context chunk {}/", i + 1)));
1890                assert!(chunk.contains("line"));
1891            } else {
1892                assert!(chunk.starts_with("[Context complete. User question:]"));
1893                assert_eq!(chunk.split_once('\n').map_or("", |(_, r)| r), "question");
1894            }
1895        }
1896    }
1897}