Skip to main content

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