Skip to main content

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