1use std::collections::HashMap;
26use std::env;
27use std::path::Path;
28use std::process;
29use std::sync::PoisonError;
30use std::sync::{Arc, LazyLock, Mutex};
31use std::time;
32
33use crate::cmd_cache;
34use crate::engine;
35use crate::engine::agents;
36use crate::engine::agents::direct;
37use crate::engine::agents::opencode;
38use crate::engine::agents::{PermissionRules, SandboxLevel};
39use crate::engine::router::RouterConfig;
40use crate::engine::runner::sandbox;
41use crate::github::token;
42use crate::home;
43use crate::store::TaskStore;
44use anyhow::{Context, Result};
45use regex::Regex;
46use sandbox_jail::known;
47use tokio::fs;
48use tokio::process::Command;
49use tokio::sync;
50use tokio::time as tokio_time;
51use tokio::time::{Duration, timeout};
52use uuid::Uuid;
53
54const SUBPROCESS_TIMEOUT: Duration = Duration::from_secs(10);
55
56static SESSION_LOCKS: LazyLock<Mutex<HashMap<String, Arc<sync::Mutex<()>>>>> =
66 LazyLock::new(|| Mutex::new(HashMap::new()));
67
68const SYSTEM_TEMPLATE: &str = include_str!("../../prompts/control_system.md");
70
71const AGENT_TIMEOUT: time::Duration = time::Duration::from_secs(120);
73
74const MAX_CONTROL_MESSAGE_BYTES: usize = 32 * 1024;
78
79enum DeliveryMode {
81 Single,
83 Chunked,
85 ChunkedNonSession,
87}
88
89#[derive(Debug, Clone, PartialEq)]
91pub struct ModelSpec {
92 pub agent: String,
93 pub model: String,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ControlCommand {
99 Model(Option<String>),
100 Agent(Option<String>),
101 Restart,
102}
103
104fn default_model_for_agent(agent: &str) -> String {
107 first_model(&RouterConfig::configured_models(agent))
108}
109
110fn first_model(models: &[String]) -> String {
112 models
113 .iter()
114 .find(|m| !m.contains(':'))
115 .cloned()
116 .unwrap_or_default()
117}
118
119pub fn parse_control_command(message: &str) -> Option<ControlCommand> {
121 let trimmed = message.trim();
122 let rest = trimmed.strip_prefix('/')?;
123 let (command, args) = rest
124 .split_once(' ')
125 .map_or((rest, ""), |(cmd, tail)| (cmd, tail.trim()));
126
127 match command {
128 "model" => Some(ControlCommand::Model(
129 (!args.is_empty()).then(|| args.to_string()),
130 )),
131 "agent" => Some(ControlCommand::Agent(
132 (!args.is_empty()).then(|| args.to_string()),
133 )),
134 "restart" => Some(ControlCommand::Restart),
135 _ => None,
136 }
137}
138
139pub fn parse_model_spec(spec: &str, current_agent: &str) -> ModelSpec {
145 if let Some((agent, model)) = spec.split_once(':') {
146 ModelSpec {
147 agent: agent.to_string(),
148 model: RouterConfig::normalize_model_identifier(model),
149 }
150 } else {
151 let model = RouterConfig::normalize_model_identifier(spec);
152 let configured: Vec<(String, Vec<String>)> = engine::configured_agents()
153 .into_iter()
154 .map(|agent| {
155 let models = RouterConfig::configured_models(&agent);
156 (agent, models)
157 })
158 .collect();
159 ModelSpec {
160 agent: infer_agent(&model, &configured, current_agent),
161 model,
162 }
163 }
164}
165
166fn infer_agent(model: &str, configured: &[(String, Vec<String>)], current_agent: &str) -> String {
168 configured
169 .iter()
170 .find(|(_, models)| models.iter().any(|m| m == model))
171 .map_or(current_agent, |(agent, _)| agent.as_str())
172 .to_string()
173}
174
175pub fn validate_agent(agent: &str) -> Result<()> {
180 let agents = engine::configured_agents();
181 if !agents.iter().any(|a| a == agent) {
182 anyhow::bail!(
183 "unknown agent '{}'. Available: {}",
184 agent,
185 agents.join(", ")
186 );
187 }
188 if !cmd_cache::command_exists(agent) {
189 anyhow::bail!("agent '{agent}' not found in PATH. Is it installed?");
190 }
191 Ok(())
192}
193
194#[expect(clippy::print_stderr, reason = "progress line for `orch chat /model`")]
199pub async fn validate_model(spec: &ModelSpec) -> Result<()> {
200 validate_agent(&spec.agent)?;
202
203 if spec.agent == "opencode"
205 && let Ok(models) = list_opencode_models().await
206 && !models.iter().any(|m| m == &spec.model)
207 {
208 let suggestions: Vec<_> = models
209 .iter()
210 .filter(|m| m.contains(&spec.model) || spec.model.contains(m.as_str()))
211 .take(10)
212 .cloned()
213 .collect();
214 let shown = if suggestions.is_empty() {
215 models.iter().take(20).cloned().collect()
216 } else {
217 suggestions
218 };
219 anyhow::bail!(
220 "model '{}' not found in opencode. Available models:\n{}",
221 spec.model,
222 shown.join("\n")
223 );
224 }
225
226 eprintln!("Testing {}:{} ...", spec.agent, spec.model);
228 let result = test_invoke(&spec.agent, &spec.model).await;
229 match result {
230 Ok(()) => Ok(()),
231 Err(e) => anyhow::bail!(
232 "model '{}' on agent '{}' is not available: {e}",
233 spec.model,
234 spec.agent
235 ),
236 }
237}
238
239async fn list_opencode_models() -> Result<Vec<String>> {
241 match opencode::run_opencode_models_cli(time::Duration::from_secs(10)).await {
242 (models, "ok" | "empty_output") => Ok(models),
243 (_, reason) => anyhow::bail!("opencode models failed: {reason}"),
244 }
245}
246
247async fn test_invoke(agent: &str, model: &str) -> Result<()> {
249 let msg = "Reply with just the word 'ok'.";
250 invoke_agent(agent, model, "", msg).await?;
252 Ok(())
253}
254
255#[derive(Debug)]
257pub struct ChatContext {
258 pub system: String,
260 pub state: String,
262}
263
264pub async fn assemble_context(store: &TaskStore, session_id: &str) -> Result<ChatContext> {
266 let memory_prefix = format!("control:memory:{session_id}:");
270 let raw_memories = store
271 .kv_list_prefix(&memory_prefix)
272 .await
273 .unwrap_or_else(|e| {
274 tracing::warn!(session_id, error = %e, "failed to load control memories from store");
275 Vec::new()
276 });
277 let memories = if raw_memories.is_empty() {
278 "(none)".to_string()
279 } else {
280 raw_memories
281 .iter()
282 .map(|(key, value)| {
283 let short_key = key.strip_prefix("control:memory:").unwrap_or(key);
284 format!("- **{short_key}**: {value}")
285 })
286 .collect::<Vec<_>>()
287 .join("\n")
288 };
289
290 let summaries = store
292 .control_recent_summaries(session_id, 20)
293 .await
294 .unwrap_or_else(|e| {
295 tracing::warn!(session_id, error = %e, "failed to load control summaries from store");
296 Vec::new()
297 });
298 let recent_summaries = if summaries.is_empty() {
299 "(no recent conversation)".to_string()
300 } else {
301 summaries
302 .iter()
303 .map(|s| format!("- {s}"))
304 .collect::<Vec<_>>()
305 .join("\n")
306 };
307
308 let (service_status, task_list, job_list) = tokio::join!(
310 async {
311 let mut cmd = Command::new("brew");
312 cmd.args(["services", "info", "orch"]).kill_on_drop(true);
313 match timeout(SUBPROCESS_TIMEOUT, cmd.output()).await {
314 Ok(Ok(output)) if output.status.success() => {
315 String::from_utf8_lossy(&output.stdout).trim().to_string()
316 }
317 _ => "(could not check service status)".to_string(),
318 }
319 },
320 async {
321 let mut cmd = Command::new("orch");
322 cmd.args(["task", "list"]).kill_on_drop(true);
323 match timeout(SUBPROCESS_TIMEOUT, cmd.output()).await {
324 Ok(Ok(output)) if output.status.success() => {
325 String::from_utf8_lossy(&output.stdout).trim().to_string()
326 }
327 _ => "(could not fetch live state)".to_string(),
328 }
329 },
330 async {
331 let mut cmd = Command::new("orch");
332 cmd.args(["job", "list"]).kill_on_drop(true);
333 match timeout(SUBPROCESS_TIMEOUT, cmd.output()).await {
334 Ok(Ok(output)) if output.status.success() => {
335 String::from_utf8_lossy(&output.stdout).trim().to_string()
336 }
337 _ => "(no jobs configured)".to_string(),
338 }
339 },
340 );
341
342 let version = env!("ORCH_VERSION");
343 let state = format!(
344 "## Current Live State\n### Version\norch {version}\n\n### Service\n{service_status}\n\n### Tasks\n{task_list}\n\n### Scheduled Jobs\n{job_list}\n\n### Memories\n{memories}\n\n### Recent Conversation\n{recent_summaries}"
345 );
346
347 let system = SYSTEM_TEMPLATE.to_string();
349
350 Ok(ChatContext { system, state })
351}
352
353pub async fn get_model(store: &TaskStore) -> Result<String> {
356 match store
357 .kv_get("control:model")
358 .await
359 .context("reading control:model from store")?
360 {
361 Some(model) => Ok(model),
362 None => Ok(default_model_for_agent(&get_agent(store).await?)),
363 }
364}
365
366pub async fn get_agent(store: &TaskStore) -> Result<String> {
369 Ok(store
370 .kv_get("control:agent")
371 .await
372 .context("reading control:agent from store")?
373 .unwrap_or_else(|| "claude".to_string()))
374}
375
376pub async fn get_current_spec(store: &TaskStore) -> Result<ModelSpec> {
378 Ok(ModelSpec {
379 agent: get_agent(store).await?,
380 model: get_model(store).await?,
381 })
382}
383
384pub async fn set_model(store: &TaskStore, model: &str) -> Result<()> {
386 store
387 .kv_set("control:model", model)
388 .await
389 .context("setting control model")?;
390 Ok(())
391}
392
393pub async fn set_agent(store: &TaskStore, agent: &str) -> Result<()> {
395 store
396 .kv_set("control:agent", agent)
397 .await
398 .context("setting control agent")?;
399 Ok(())
400}
401
402pub async fn set_model_spec(store: &TaskStore, spec: &ModelSpec) -> Result<()> {
404 set_model(store, &spec.model).await?;
405 set_agent(store, &spec.agent).await?;
406 Ok(())
407}
408
409pub async fn set_agent_spec(store: &TaskStore, agent: &str) -> Result<ModelSpec> {
411 let spec = ModelSpec {
412 agent: agent.to_string(),
413 model: default_model_for_agent(agent),
414 };
415 set_model_spec(store, &spec).await?;
416 Ok(spec)
417}
418
419fn display_model(model: &str) -> &str {
420 if model.is_empty() { "default" } else { model }
421}
422
423fn format_current_spec(spec: &ModelSpec) -> String {
424 format!("Current: {}:{}", spec.agent, display_model(&spec.model))
425}
426
427fn format_switched_spec(spec: &ModelSpec) -> String {
428 format!(
429 "Switched to **{}:{}** (validated)",
430 spec.agent,
431 display_model(&spec.model)
432 )
433}
434
435async fn handle_control_command(
436 store: &TaskStore,
437 session_id: &str,
438 channel_thread: Option<&str>,
439 command: ControlCommand,
440) -> Result<String> {
441 match command {
442 ControlCommand::Model(None) | ControlCommand::Agent(None) => {
443 Ok(format_current_spec(&get_current_spec(store).await?))
444 }
445 ControlCommand::Model(Some(new_spec)) => {
446 let spec = parse_model_spec(&new_spec, &get_agent(store).await?);
447 validate_model(&spec).await?;
448 set_model_spec(store, &spec).await?;
449 reset_session_uuid(store, session_id).await?;
451 Ok(format_switched_spec(&spec))
452 }
453 ControlCommand::Agent(Some(agent)) => {
454 validate_agent(&agent)?;
455 let spec = set_agent_spec(store, &agent).await?;
456 reset_session_uuid(store, session_id).await?;
458 Ok(format_switched_spec(&spec))
459 }
460 ControlCommand::Restart => {
461 if let Some(ct) = channel_thread {
463 store.kv_set("control:restart_pending", ct).await.ok();
464 }
465 tokio::spawn(async {
467 tokio_time::sleep(Duration::from_secs(2)).await;
468 let pid = process::id().to_string();
469 let _ = Command::new("kill").args(["-TERM", &pid]).status().await;
470 });
471 Ok("Restarting orch service\u{2026} I'll confirm here when back online.".to_string())
472 }
473 }
474}
475
476pub async fn maybe_handle_control_command(
478 store: &TaskStore,
479 session_id: &str,
480 channel_thread: Option<&str>,
481 message: &str,
482) -> Result<Option<String>> {
483 Ok(match parse_control_command(message) {
484 Some(command) => {
485 Some(handle_control_command(store, session_id, channel_thread, command).await?)
486 }
487 None => None,
488 })
489}
490
491#[derive(Debug, Clone, PartialEq, Eq)]
493pub struct MemoryEntry {
494 pub key: String,
495 pub value: String,
496}
497
498#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct ParsedResponse {
501 pub clean_text: String,
502 pub summary: Option<String>,
503 pub memories: Vec<MemoryEntry>,
504}
505
506static MEMORY_RE: LazyLock<Regex> = LazyLock::new(|| {
507 Regex::new(r#"(?s)<memory\s+key="([^"]+)">(.+?)</memory>"#).expect("valid memory regex")
508});
509
510static SUMMARY_RE: LazyLock<Regex> =
511 LazyLock::new(|| Regex::new(r"(?s)<summary>(.+?)</summary>").expect("valid summary regex"));
512
513pub fn parse_response(raw: &str) -> ParsedResponse {
515 let mut clean = raw.to_string();
516 let memories = MEMORY_RE
517 .captures_iter(raw)
518 .map(|caps| MemoryEntry {
519 key: caps[1].trim().to_string(),
520 value: caps[2].trim().to_string(),
521 })
522 .collect::<Vec<_>>();
523 clean = MEMORY_RE.replace_all(&clean, "").to_string();
524
525 let summary = SUMMARY_RE
526 .captures(raw)
527 .map(|caps| caps[1].trim().to_string());
528 clean = SUMMARY_RE.replace_all(&clean, "").to_string();
529
530 ParsedResponse {
531 clean_text: clean.trim().to_string(),
532 summary,
533 memories,
534 }
535}
536
537async fn persist_memories(
538 store: &TaskStore,
539 session_id: &str,
540 memories: &[MemoryEntry],
541) -> Result<()> {
542 for memory in memories {
543 store
544 .kv_set(
545 &format!("control:memory:{session_id}:{}", memory.key),
546 &memory.value,
547 )
548 .await
549 .with_context(|| format!("storing control memory {}", memory.key))?;
550 }
551 Ok(())
552}
553
554#[derive(Debug)]
556pub struct InvokeResult {
557 pub text: String,
558 pub input_tokens: Option<u64>,
559 pub output_tokens: Option<u64>,
560 pub cost_usd: Option<f64>,
562}
563
564fn model_arg(model: &str) -> Option<&str> {
566 (!model.is_empty()).then_some(model)
567}
568
569fn token_u64_to_i64_saturating(tokens: u64) -> i64 {
570 i64::try_from(tokens).unwrap_or(i64::MAX)
571}
572
573fn opt_token_u64_to_i64_saturating(tokens: Option<u64>) -> Option<i64> {
574 tokens.map(token_u64_to_i64_saturating)
575}
576
577fn total_tokens_u64_to_i64_saturating(
578 input_tokens: Option<u64>,
579 output_tokens: Option<u64>,
580) -> Option<i64> {
581 match (input_tokens, output_tokens) {
582 (Some(input), Some(output)) => {
583 Some(token_u64_to_i64_saturating(input.saturating_add(output)))
584 }
585 (Some(tokens), None) | (None, Some(tokens)) => Some(token_u64_to_i64_saturating(tokens)),
586 _ => None,
587 }
588}
589
590async fn prepare_temp_dir() -> Result<String> {
594 let home = home::orch_home()?;
595 let dir = format!("{}/state/control/{}", home.display(), process::id());
596 fs::create_dir_all(&dir).await?;
597 Ok(dir)
598}
599
600pub async fn invoke_agent(
607 agent: &str,
608 model: &str,
609 context: &str,
610 message: &str,
611) -> Result<InvokeResult> {
612 let dir = prepare_temp_dir().await?;
613 let place = control_place(agent, &dir).await?;
614 let result = direct::run_direct_at(
615 agent,
616 model_arg(model),
617 context,
618 message,
619 AGENT_TIMEOUT,
620 &place,
621 None,
622 )
623 .await?;
624
625 Ok(InvokeResult {
626 text: result.text,
627 input_tokens: result.input_tokens,
628 output_tokens: result.output_tokens,
629 cost_usd: result.cost_usd,
630 })
631}
632
633pub async fn invoke_agent_unsandboxed(
639 agent: &str,
640 model: &str,
641 context: &str,
642 message: &str,
643) -> Result<InvokeResult> {
644 let dir = prepare_temp_dir().await?;
645 let result = direct::run_direct(
646 agent,
647 model_arg(model),
648 context,
649 message,
650 AGENT_TIMEOUT,
651 &dir,
652 )
653 .await?;
654
655 Ok(InvokeResult {
656 text: result.text,
657 input_tokens: result.input_tokens,
658 output_tokens: result.output_tokens,
659 cost_usd: result.cost_usd,
660 })
661}
662
663pub const CONTROL_CHAT_TOOLS: &[&str] = &[
669 "Bash(orch task list:*)",
670 "Bash(orch task get:*)",
671 "Bash(orch task status:*)",
672 "Bash(orch task inspect:*)",
673 "Bash(orch task deps:*)",
674 "Bash(orch task log:*)",
675 "Bash(orch task logs:*)",
676 "Bash(orch task history:*)",
677 "Bash(orch task runs:*)",
678 "Bash(orch task cost:*)",
679 "Bash(orch task tree:*)",
680 "Bash(orch task live:*)",
681 "Bash(orch task retry:*)",
682 "Bash(orch task reroute:*)",
683 "Bash(orch task unblock:*)",
684 "Bash(orch task kill:*)",
685 "Bash(orch task close:*)",
686 "Bash(orch task priority:*)",
687 "Bash(orch stats:*)",
688 "Bash(orch cooldown list:*)",
689 "Bash(orch cooldown clear:*)",
690 "Bash(orch job list:*)",
691 "Bash(orch service status:*)",
692 "Bash(gh pr list:*)",
693 "Bash(gh pr view:*)",
694 "Bash(gh run list:*)",
695 "Bash(gh run view:*)",
696 "Bash(gh issue list:*)",
697 "Bash(gh issue view:*)",
698];
699
700fn secrets_to_unset(agent: &str) -> Vec<String> {
709 let own = agents::login_env_vars(agent);
710 env::vars_os()
711 .filter_map(|(name, _)| name.into_string().ok())
712 .filter(|name| known::secret_env(name) && !own.contains(&name.as_str()))
713 .collect()
714}
715
716async fn control_place(agent: &str, dir: &str) -> Result<direct::DirectPlace> {
717 let sandbox = sandbox::control_argv(Path::new(dir)).context(
718 "the chat runs inside an OS sandbox and none could start here, see the error below",
719 )?;
720 if agents::is_claude_compatible(agent) {
721 let token = token::shared().get_token().await.ok().flatten();
722 return Ok(direct::DirectPlace {
723 files_dir: dir.to_string(),
724 cwd: dir.to_string(),
725 permissions: PermissionRules::read_only(
726 CONTROL_CHAT_TOOLS.iter().map(ToString::to_string).collect(),
727 ),
728 sandbox,
729 env: token
730 .map(|t| vec![("GH_TOKEN".to_string(), t)])
731 .unwrap_or_default(),
732 unset: secrets_to_unset(agent),
733 });
734 }
735
736 let mut permissions = PermissionRules::deny_read_only();
738 permissions.sandbox = SandboxLevel::Os;
739 Ok(direct::DirectPlace {
740 files_dir: dir.to_string(),
741 cwd: dir.to_string(),
742 permissions,
743 sandbox,
744 env: Vec::new(),
745 unset: secrets_to_unset(agent),
746 })
747}
748
749pub const PROJECT_CHAT_TOOLS: &[&str] = &[
752 "Read",
753 "Grep",
754 "Glob",
755 "Bash(orch task list:*)",
756 "Bash(orch task inspect:*)",
757 "Bash(orch task deps:*)",
758 "Bash(orch task log:*)",
759];
760
761pub async fn invoke_project_chat(
767 agent: &str,
768 model: &str,
769 context: &str,
770 message: &str,
771 project: &Path,
772) -> Result<InvokeResult> {
773 let dir = prepare_temp_dir().await?;
774 let sandbox = sandbox::chat_argv(project, Path::new(&dir))?;
775 let place = direct::DirectPlace {
776 files_dir: dir.clone(),
777 cwd: project.to_string_lossy().to_string(),
778 permissions: PermissionRules::read_only(
779 PROJECT_CHAT_TOOLS.iter().map(ToString::to_string).collect(),
780 ),
781 sandbox,
782 env: Vec::new(),
783 unset: secrets_to_unset(agent),
784 };
785 let result = direct::run_direct_at(
786 agent,
787 model_arg(model),
788 context,
789 message,
790 AGENT_TIMEOUT,
791 &place,
792 None,
793 )
794 .await?;
795
796 Ok(InvokeResult {
797 text: result.text,
798 input_tokens: result.input_tokens,
799 output_tokens: result.output_tokens,
800 cost_usd: result.cost_usd,
801 })
802}
803
804fn session_uuid_key(session_name: &str) -> String {
806 format!("control:session_id:{session_name}")
807}
808
809pub async fn get_or_create_session_uuid(
822 store: &TaskStore,
823 session_name: &str,
824) -> Result<(String, bool)> {
825 let key = session_uuid_key(session_name);
826 let candidate = Uuid::new_v4().to_string();
827 let stored = store
828 .kv_insert_if_absent(&key, &candidate)
829 .await
830 .context("storing session UUID")?;
831 let is_new = stored == candidate;
832 if is_new {
833 tracing::info!(session_name, uuid = %stored, "created new chat session UUID");
834 }
835 Ok((stored, is_new))
836}
837
838pub async fn reset_session_uuid(store: &TaskStore, session_name: &str) -> Result<()> {
844 let key = session_uuid_key(session_name);
845 store
846 .kv_delete(&key)
847 .await
848 .context("resetting session UUID")?;
849 tracing::info!(session_name, "reset chat session UUID");
850 Ok(())
851}
852
853pub async fn invoke_agent_with_session(
859 agent: &str,
860 model: &str,
861 context: &str,
862 message: &str,
863 session_uuid: Option<&str>,
864 resume: bool,
865) -> Result<InvokeResult> {
866 let dir = prepare_temp_dir().await?;
867
868 let session = session_uuid.map(|sid| agents::direct::SessionContinuation {
869 session_id: sid,
870 resume,
871 });
872
873 let place = control_place(agent, &dir).await?;
874 let result = direct::run_direct_at(
875 agent,
876 model_arg(model),
877 context,
878 message,
879 AGENT_TIMEOUT,
880 &place,
881 session,
882 )
883 .await?;
884
885 Ok(InvokeResult {
886 text: result.text,
887 input_tokens: result.input_tokens,
888 output_tokens: result.output_tokens,
889 cost_usd: result.cost_usd,
890 })
891}
892
893pub async fn send_message(
898 store: &TaskStore,
899 session_id: &str,
900 channel: &str,
901 channel_thread: Option<&str>,
902 message: &str,
903) -> Result<String> {
904 if let Some(response) =
906 maybe_handle_control_command(store, session_id, channel_thread, message).await?
907 {
908 return Ok(response);
909 }
910
911 let session_lock = {
914 let mut map = SESSION_LOCKS.lock().unwrap_or_else(PoisonError::into_inner);
915 Arc::clone(
916 map.entry(session_id.to_string())
917 .or_insert_with(|| Arc::new(sync::Mutex::new(()))),
918 )
919 };
920 let guard = session_lock.lock().await;
921
922 store
924 .insert_control_message(
925 session_id,
926 "user",
927 channel,
928 channel_thread,
929 message,
930 None,
931 None,
932 None,
933 None,
934 None,
935 None,
936 None,
937 )
938 .await?;
939
940 let ctx = assemble_context(store, session_id).await?;
942
943 let model = get_model(store).await?;
945 let agent = get_agent(store).await?;
946
947 let full_message = format!("{}\n\n---\n\n{}", ctx.state, message);
949
950 let (session_uuid, is_new) = get_or_create_session_uuid(store, session_id).await?;
952
953 let agent_has_sessions = agents::supports_session(&agent);
960 let (chunks, delivery_mode) = if full_message.len() > MAX_CONTROL_MESSAGE_BYTES {
961 tracing::info!(
962 bytes = full_message.len(),
963 limit = MAX_CONTROL_MESSAGE_BYTES,
964 agent = %agent,
965 agent_has_sessions,
966 "control session payload exceeds limit"
967 );
968 if agent_has_sessions {
969 (
971 build_control_chunks(&ctx.state, message, true),
972 DeliveryMode::Chunked,
973 )
974 } else {
975 (
977 build_control_chunks(&ctx.state, message, false),
978 DeliveryMode::ChunkedNonSession,
979 )
980 }
981 } else {
982 (vec![full_message], DeliveryMode::Single)
983 };
984
985 let _num_chunks = chunks.len();
986
987 let result = match delivery_mode {
989 DeliveryMode::Chunked => {
990 let mut active_uuid = session_uuid.clone();
993 let mut is_first_chunk = !is_new;
994 let mut last_result: Option<InvokeResult> = None;
995
996 for chunk in &chunks {
997 let r = invoke_agent_with_session(
998 &agent,
999 &model,
1000 &ctx.system,
1001 chunk,
1002 Some(&active_uuid),
1003 is_first_chunk,
1004 )
1005 .await;
1006 let chunk_result = match r {
1007 Ok(result) => result,
1008 Err(e) => {
1009 let err_str = e.to_string();
1010 let is_stale = err_str.contains("stale session");
1011 let is_timeout = err_str.contains("timeout after")
1012 || err_str.contains("timed out after");
1013 if is_stale || is_timeout {
1014 if is_stale {
1015 tracing::info!(
1016 session_id,
1017 "chat session UUID expired; resetting and retrying with fresh session"
1018 );
1019 } else {
1020 tracing::info!(
1021 session_id,
1022 "chat session timed out; resetting and retrying with fresh session"
1023 );
1024 }
1025 reset_session_uuid(store, session_id).await?;
1026 let (fresh_uuid, _) =
1027 get_or_create_session_uuid(store, session_id).await?;
1028 active_uuid = fresh_uuid;
1029 is_first_chunk = false;
1030 let fresh_result = invoke_agent_with_session(
1031 &agent,
1032 &model,
1033 &ctx.system,
1034 chunk,
1035 Some(&active_uuid),
1036 false,
1037 )
1038 .await?;
1039
1040 if is_timeout {
1041 InvokeResult {
1042 text: format!(
1043 "_(New session started.)_\n\n{}",
1044 fresh_result.text
1045 ),
1046 ..fresh_result
1047 }
1048 } else {
1049 fresh_result
1050 }
1051 } else {
1052 return Err(e);
1053 }
1054 }
1055 };
1056
1057 let parsed = parse_response(&chunk_result.text);
1059 let total_tokens = total_tokens_u64_to_i64_saturating(
1060 chunk_result.input_tokens,
1061 chunk_result.output_tokens,
1062 );
1063 let input_tokens = opt_token_u64_to_i64_saturating(chunk_result.input_tokens);
1064 let output_tokens = opt_token_u64_to_i64_saturating(chunk_result.output_tokens);
1065 let cost_usd = chunk_result.cost_usd;
1066 store
1067 .insert_control_message(
1068 session_id,
1069 "assistant",
1070 channel,
1071 channel_thread,
1072 &parsed.clean_text,
1073 parsed.summary.as_deref(),
1074 Some(&model),
1075 Some(&agent),
1076 input_tokens,
1077 output_tokens,
1078 total_tokens,
1079 cost_usd,
1080 )
1081 .await?;
1082 persist_memories(store, session_id, &parsed.memories).await?;
1083
1084 last_result = Some(chunk_result);
1085 }
1086
1087 let final_parsed = parse_response(&last_result.expect("at least one chunk").text);
1089 final_parsed.clean_text
1090 }
1091 DeliveryMode::ChunkedNonSession => {
1092 let mut last_text = String::new();
1095
1096 for chunk in &chunks {
1097 let chunk_result = invoke_agent(&agent, &model, &ctx.system, chunk).await?;
1098
1099 let parsed = parse_response(&chunk_result.text);
1101 let total_tokens = total_tokens_u64_to_i64_saturating(
1102 chunk_result.input_tokens,
1103 chunk_result.output_tokens,
1104 );
1105 let input_tokens = opt_token_u64_to_i64_saturating(chunk_result.input_tokens);
1106 let output_tokens = opt_token_u64_to_i64_saturating(chunk_result.output_tokens);
1107 let cost_usd = chunk_result.cost_usd;
1108 store
1109 .insert_control_message(
1110 session_id,
1111 "assistant",
1112 channel,
1113 channel_thread,
1114 &parsed.clean_text,
1115 parsed.summary.as_deref(),
1116 Some(&model),
1117 Some(&agent),
1118 input_tokens,
1119 output_tokens,
1120 total_tokens,
1121 cost_usd,
1122 )
1123 .await?;
1124 persist_memories(store, session_id, &parsed.memories).await?;
1125
1126 last_text = parsed.clean_text;
1127 }
1128
1129 last_text
1130 }
1131 DeliveryMode::Single => {
1132 let mut active_uuid = session_uuid.clone();
1135 let mut is_first_chunk = !is_new;
1136 let chunk_result = loop {
1137 let r = invoke_agent_with_session(
1138 &agent,
1139 &model,
1140 &ctx.system,
1141 &chunks[0],
1142 Some(&active_uuid),
1143 is_first_chunk,
1144 )
1145 .await;
1146 match r {
1147 Ok(result) => break result,
1148 Err(e) => {
1149 let err_str = e.to_string();
1150 let is_stale = err_str.contains("stale session");
1151 let is_timeout = err_str.contains("timeout after")
1152 || err_str.contains("timed out after");
1153 if is_stale || is_timeout {
1154 if is_stale {
1155 tracing::info!(
1156 session_id,
1157 "chat session UUID expired; resetting and retrying with fresh session"
1158 );
1159 } else {
1160 tracing::info!(
1161 session_id,
1162 "chat session timed out; resetting and retrying with fresh session"
1163 );
1164 }
1165 reset_session_uuid(store, session_id).await?;
1166 let (fresh_uuid, _) =
1167 get_or_create_session_uuid(store, session_id).await?;
1168 active_uuid = fresh_uuid;
1169 is_first_chunk = false;
1170 continue;
1171 }
1172 return Err(e);
1173 }
1174 }
1175 };
1176
1177 let parsed = parse_response(&chunk_result.text);
1179
1180 let total_tokens = total_tokens_u64_to_i64_saturating(
1185 chunk_result.input_tokens,
1186 chunk_result.output_tokens,
1187 );
1188 let input_tokens = opt_token_u64_to_i64_saturating(chunk_result.input_tokens);
1189 let output_tokens = opt_token_u64_to_i64_saturating(chunk_result.output_tokens);
1190 let cost_usd = chunk_result.cost_usd;
1191 store
1192 .insert_control_message(
1193 session_id,
1194 "assistant",
1195 channel,
1196 channel_thread,
1197 &parsed.clean_text,
1198 parsed.summary.as_deref(),
1199 Some(&model),
1200 Some(&agent),
1201 input_tokens,
1202 output_tokens,
1203 total_tokens,
1204 cost_usd,
1205 )
1206 .await?;
1207 persist_memories(store, session_id, &parsed.memories).await?;
1208
1209 parsed.clean_text
1210 }
1211 };
1212
1213 drop(guard);
1215
1216 if Arc::strong_count(&session_lock) == 2 {
1224 let mut map = SESSION_LOCKS.lock().unwrap_or_else(PoisonError::into_inner);
1225 if map
1228 .get(session_id)
1229 .is_some_and(|l| Arc::strong_count(l) == 2)
1230 {
1231 map.remove(session_id);
1232 }
1233 }
1234
1235 Ok(result)
1236}
1237
1238fn chunk_text(text: &str, max_bytes: usize) -> Vec<String> {
1241 if text.len() <= max_bytes {
1242 return vec![text.to_string()];
1243 }
1244 let mut chunks = Vec::new();
1245 let mut start = 0;
1246 let total = text.len();
1247
1248 while start < total {
1249 let mut end = (start + max_bytes).min(total);
1250 while end > start && !text.is_char_boundary(end) {
1252 end -= 1;
1253 }
1254 if end == start {
1255 if let Some(ch) = text[start..].chars().next() {
1257 end = start + ch.len_utf8();
1258 } else {
1259 break;
1260 }
1261 }
1262 if end < total
1264 && let Some(nl_offset) = text[start..end].rfind('\n')
1265 {
1266 end = start + nl_offset + 1;
1267 }
1268 chunks.push(text[start..end].to_string());
1269 start = end;
1270 }
1271 chunks
1272}
1273
1274fn build_control_chunks(state: &str, message: &str, agent_has_sessions: bool) -> Vec<String> {
1282 let header_reserve = if agent_has_sessions { 0 } else { 200 };
1283 let effective_limit = MAX_CONTROL_MESSAGE_BYTES.saturating_sub(header_reserve);
1284 let mut parts = Vec::new();
1285
1286 let state_chunks = chunk_text(state, effective_limit);
1288 for (i, chunk) in state_chunks.iter().enumerate() {
1289 let prefixed = if agent_has_sessions {
1290 chunk.clone()
1291 } else {
1292 format!(
1293 "[Context chunk {}/{}]\n{}",
1294 i + 1,
1295 state_chunks.len(),
1296 chunk
1297 )
1298 };
1299 parts.push(prefixed);
1300 }
1301
1302 let msg_chunks = chunk_text(message, effective_limit);
1304 for (i, chunk) in msg_chunks.iter().enumerate() {
1305 let prefixed = if agent_has_sessions {
1306 chunk.clone()
1307 } else if msg_chunks.len() == 1 {
1308 format!("[Context complete. User question:]\n{chunk}")
1309 } else {
1310 format!(
1311 "[User question chunk {}/{}]\n{}",
1312 i + 1,
1313 msg_chunks.len(),
1314 chunk
1315 )
1316 };
1317 parts.push(prefixed);
1318 }
1319 parts
1320}
1321
1322#[cfg(test)]
1323mod tests {
1324 use tokio::runtime::Runtime;
1325
1326 use std::collections::BTreeSet;
1327
1328 use super::*;
1329 use crate::store::TaskStore;
1330
1331 #[test]
1332 fn parse_spec_agent_model() {
1333 let spec = parse_model_spec("minimax:sonnet", "claude");
1334 assert_eq!(spec.agent, "minimax");
1335 assert_eq!(spec.model, "sonnet");
1336 }
1337
1338 #[test]
1339 fn parse_spec_opencode_model() {
1340 let spec = parse_model_spec("opencode:minimax-m2.5-free", "claude");
1341 assert_eq!(spec.agent, "opencode");
1342 assert_eq!(spec.model, "minimax-m2.5-free");
1343 }
1344
1345 fn configured(entries: &[(&str, &[&str])]) -> Vec<(String, Vec<String>)> {
1346 entries
1347 .iter()
1348 .map(|(agent, models)| {
1349 (
1350 agent.to_string(),
1351 models.iter().map(ToString::to_string).collect(),
1352 )
1353 })
1354 .collect()
1355 }
1356
1357 #[test]
1358 fn infer_agent_finds_the_agent_whose_config_lists_the_model() {
1359 let configured = configured(&[("claude", &["sonnet"]), ("codex", &["gpt-4o"])]);
1360 assert_eq!(infer_agent("gpt-4o", &configured, "claude"), "codex");
1361 assert_eq!(infer_agent("sonnet", &configured, "codex"), "claude");
1362 }
1363
1364 #[test]
1365 fn infer_agent_keeps_the_current_agent_for_an_unlisted_model() {
1366 let configured = configured(&[("claude", &["sonnet"])]);
1367 assert_eq!(
1368 infer_agent("deepseek-r1", &configured, "opencode"),
1369 "opencode"
1370 );
1371 }
1372
1373 #[test]
1374 fn first_model_skips_pool_keywords() {
1375 let models = vec!["opencode:free".to_string(), "provider/model".to_string()];
1376 assert_eq!(first_model(&models), "provider/model");
1377 }
1378
1379 #[test]
1380 fn first_model_is_empty_without_models() {
1381 assert_eq!(first_model(&[]), "");
1382 assert_eq!(model_arg(""), None);
1383 assert_eq!(model_arg("sonnet"), Some("sonnet"));
1384 }
1385
1386 #[tokio::test]
1387 async fn assemble_context_includes_memories_and_summaries() {
1388 let store = TaskStore::open_memory().await.unwrap();
1389 store
1390 .kv_set("control:memory:default:tz", "User timezone is UTC-3")
1391 .await
1392 .unwrap();
1393 store
1394 .insert_control_message(
1395 "default",
1396 "assistant",
1397 "cli",
1398 None,
1399 "response",
1400 Some("checked status"),
1401 Some("sonnet"),
1402 Some("claude"),
1403 None,
1404 None,
1405 None,
1406 None,
1407 )
1408 .await
1409 .unwrap();
1410
1411 let ctx = assemble_context(&store, "default").await.unwrap();
1412 assert!(ctx.state.contains("UTC-3"), "should include memories");
1413 assert!(
1414 ctx.state.contains("checked status"),
1415 "should include summaries"
1416 );
1417 }
1418
1419 #[test]
1420 fn extract_summary_from_response() {
1421 let response = "Here are your tasks.\n\n<summary>listed 3 active tasks</summary>";
1422 let parsed = parse_response(response);
1423 assert_eq!(parsed.summary.as_deref(), Some("listed 3 active tasks"));
1424 assert!(!parsed.clean_text.contains("<summary>"));
1425 }
1426
1427 #[test]
1428 fn extract_summary_missing() {
1429 let response = "No tasks found.";
1430 let parsed = parse_response(response);
1431 assert_eq!(parsed.summary, None);
1432 assert_eq!(parsed.clean_text, "No tasks found.");
1433 }
1434
1435 #[test]
1436 fn extract_summary_closing_tag_before_opening_does_not_panic() {
1437 let response = "Example: </summary> is a closing tag.\n<summary>actual summary</summary>";
1439 let parsed = parse_response(response);
1440 assert_eq!(parsed.summary.as_deref(), Some("actual summary"));
1441 assert!(!parsed.clean_text.contains("<summary>"));
1442 }
1443
1444 #[test]
1445 fn extract_memory_tags() {
1446 let response = r#"Remember these.
1447
1448<memory key="tz">User timezone is UTC-3</memory>
1449<memory key="theme">Prefer concise answers</memory>
1450
1451<summary>stored two memories</summary>"#;
1452 let parsed = parse_response(response);
1453 assert_eq!(parsed.memories.len(), 2);
1454 assert_eq!(parsed.memories[0].key, "tz");
1455 assert_eq!(parsed.memories[0].value, "User timezone is UTC-3");
1456 assert_eq!(parsed.memories[1].key, "theme");
1457 assert_eq!(parsed.memories[1].value, "Prefer concise answers");
1458 assert_eq!(parsed.summary.as_deref(), Some("stored two memories"));
1459 assert!(!parsed.clean_text.contains("<memory"));
1460 }
1461
1462 #[tokio::test]
1463 async fn persist_memories_writes_to_kv() {
1464 let store = TaskStore::open_memory().await.unwrap();
1465 let memories = vec![MemoryEntry {
1466 key: "tz".to_string(),
1467 value: "User timezone is UTC-3".to_string(),
1468 }];
1469
1470 persist_memories(&store, "default", &memories)
1471 .await
1472 .unwrap();
1473
1474 assert_eq!(
1475 store
1476 .kv_get("control:memory:default:tz")
1477 .await
1478 .unwrap()
1479 .as_deref(),
1480 Some("User timezone is UTC-3")
1481 );
1482 }
1483
1484 #[tokio::test]
1485 async fn send_message_model_switch() {
1486 let store = TaskStore::open_memory().await.unwrap();
1487 set_agent(&store, "unlisted-agent").await.unwrap();
1488 let model = get_model(&store).await.unwrap();
1489 assert_eq!(model, "", "an agent with no models: entry gets no --model");
1490
1491 let spec = parse_model_spec("minimax:sonnet", "claude");
1494 set_model_spec(&store, &spec).await.unwrap();
1495 assert_eq!(get_model(&store).await.unwrap(), "sonnet");
1496 assert_eq!(get_agent(&store).await.unwrap(), "minimax");
1497 }
1498
1499 #[tokio::test]
1500 async fn send_message_model_show_current() {
1501 let store = TaskStore::open_memory().await.unwrap();
1502 set_agent(&store, "unlisted-agent").await.unwrap();
1503 let response = send_message(&store, "default", "cli", None, "/model")
1504 .await
1505 .unwrap();
1506 assert_eq!(response, "Current: unlisted-agent:default");
1507 }
1508
1509 #[tokio::test]
1510 async fn send_message_agent_show_current() {
1511 let store = TaskStore::open_memory().await.unwrap();
1512 set_agent(&store, "unlisted-agent").await.unwrap();
1513 let response = send_message(&store, "default", "cli", None, "/agent")
1514 .await
1515 .unwrap();
1516 assert_eq!(response, "Current: unlisted-agent:default");
1517 }
1518
1519 #[tokio::test]
1520 async fn send_message_agent_switches_with_default_model() {
1521 let store = TaskStore::open_memory().await.unwrap();
1522 let spec = set_agent_spec(&store, "unlisted-agent").await.unwrap();
1524 assert_eq!(spec.agent, "unlisted-agent");
1525 assert_eq!(
1526 spec.model, "",
1527 "an agent with no models: entry gets no --model"
1528 );
1529 assert_eq!(get_agent(&store).await.unwrap(), "unlisted-agent");
1530 assert_eq!(get_model(&store).await.unwrap(), "");
1531 }
1532
1533 #[test]
1534 fn parse_control_command_model_and_agent() {
1535 assert_eq!(
1536 parse_control_command("/model"),
1537 Some(ControlCommand::Model(None))
1538 );
1539 assert_eq!(
1540 parse_control_command("/agent"),
1541 Some(ControlCommand::Agent(None))
1542 );
1543 assert_eq!(
1544 parse_control_command("/agent codex"),
1545 Some(ControlCommand::Agent(Some("codex".to_string())))
1546 );
1547 assert_eq!(
1548 parse_control_command("/model opencode:deepseek-r1"),
1549 Some(ControlCommand::Model(Some(
1550 "opencode:deepseek-r1".to_string()
1551 )))
1552 );
1553 assert_eq!(
1554 parse_control_command("/restart"),
1555 Some(ControlCommand::Restart)
1556 );
1557 assert_eq!(parse_control_command("/kill"), None);
1558 assert_eq!(parse_control_command("/session"), None);
1559 }
1560
1561 #[test]
1562 fn control_prompt_slash_commands_match_supported_surface() {
1563 let documented = Regex::new(r"`/([a-z]+)(?:[^`]*)`")
1564 .unwrap()
1565 .captures_iter(SYSTEM_TEMPLATE)
1566 .map(|caps| caps[1].to_string())
1567 .collect::<BTreeSet<_>>();
1568
1569 let expected = ["agent", "model", "restart"]
1570 .into_iter()
1571 .map(str::to_string)
1572 .collect::<BTreeSet<_>>();
1573
1574 assert_eq!(documented, expected);
1575 }
1576
1577 #[tokio::test]
1578 async fn set_agent_spec_persists_default_model() {
1579 let store = TaskStore::open_memory().await.unwrap();
1580 let spec = set_agent_spec(&store, "unlisted-agent").await.unwrap();
1581 assert_eq!(spec.agent, "unlisted-agent");
1582 assert_eq!(spec.model, "");
1583 assert_eq!(get_agent(&store).await.unwrap(), "unlisted-agent");
1584 assert_eq!(get_model(&store).await.unwrap(), "");
1585 }
1586
1587 #[tokio::test]
1588 async fn send_message_model_switch_does_not_store() {
1589 let store = TaskStore::open_memory().await.unwrap();
1590 let spec = parse_model_spec("claude:haiku", "claude");
1592 set_model_spec(&store, &spec).await.unwrap();
1593 let messages = store
1594 .list_control_messages("default", None, 10)
1595 .await
1596 .unwrap();
1597 assert_eq!(messages.len(), 0);
1598 }
1599
1600 #[test]
1601 fn validate_unknown_agent_fails() {
1602 let spec = ModelSpec {
1603 agent: "nonexistent".to_string(),
1604 model: "test".to_string(),
1605 };
1606 let rt = Runtime::new().unwrap();
1607 let result = rt.block_on(validate_model(&spec));
1608 assert!(result.is_err());
1609 assert!(result.unwrap_err().to_string().contains("unknown agent"));
1610 }
1611
1612 #[test]
1613 fn validate_agent_rejects_unknown() {
1614 let result = validate_agent("nonexistent");
1615 assert!(result.is_err());
1616 let err = result.unwrap_err().to_string();
1617 assert!(err.contains("unknown agent"), "got: {err}");
1618 }
1619
1620 #[test]
1621 fn validate_agent_rejects_empty() {
1622 let result = validate_agent("");
1623 assert!(result.is_err());
1624 assert!(result.unwrap_err().to_string().contains("unknown agent"));
1625 }
1626
1627 #[tokio::test]
1628 async fn agent_command_rejects_unknown_before_persisting() {
1629 let store = TaskStore::open_memory().await.unwrap();
1630 set_agent(&store, "claude").await.unwrap();
1632
1633 let result =
1635 maybe_handle_control_command(&store, "default", None, "/agent bogusagent").await;
1636 assert!(result.is_err(), "should reject unknown agent");
1637 assert!(result.unwrap_err().to_string().contains("unknown agent"));
1638
1639 assert_eq!(get_agent(&store).await.unwrap(), "claude");
1641 }
1642
1643 #[test]
1644 fn token_u64_to_i64_saturating_caps_large_values() {
1645 assert_eq!(token_u64_to_i64_saturating(u64::MAX), i64::MAX);
1646 }
1647
1648 #[test]
1649 fn total_tokens_u64_to_i64_saturating_caps_single_large_value() {
1650 assert_eq!(
1651 total_tokens_u64_to_i64_saturating(Some(u64::MAX), None),
1652 Some(i64::MAX)
1653 );
1654 }
1655
1656 #[test]
1657 fn total_tokens_u64_to_i64_saturating_caps_large_sum() {
1658 assert_eq!(
1659 total_tokens_u64_to_i64_saturating(Some(u64::MAX), Some(1)),
1660 Some(i64::MAX)
1661 );
1662 }
1663
1664 #[tokio::test]
1665 async fn insert_control_message_stores_cost_usd() {
1666 let store = TaskStore::open_memory().await.unwrap();
1667
1668 let input_tokens: u64 = 500_000;
1669 let output_tokens: u64 = 100_000;
1670 let cost_usd = Some(0.25);
1671
1672 store
1673 .insert_control_message(
1674 "default",
1675 "assistant",
1676 "cli",
1677 None,
1678 "hello",
1679 Some("greeted"),
1680 Some("sonnet"),
1681 Some("claude"),
1682 opt_token_u64_to_i64_saturating(Some(input_tokens)),
1683 opt_token_u64_to_i64_saturating(Some(output_tokens)),
1684 total_tokens_u64_to_i64_saturating(Some(input_tokens), Some(output_tokens)),
1685 cost_usd,
1686 )
1687 .await
1688 .unwrap();
1689
1690 let messages = store
1691 .list_control_messages("default", None, 10)
1692 .await
1693 .unwrap();
1694 assert_eq!(messages.len(), 1);
1695 let msg = &messages[0];
1696 assert!(msg.cost_usd.is_some(), "cost_usd must be stored, not NULL");
1697 assert_eq!(
1698 msg.cost_usd,
1699 Some(0.25),
1700 "the reported cost is stored as is"
1701 );
1702 }
1703
1704 #[tokio::test]
1705 async fn session_uuid_created_and_stable() {
1706 let store = TaskStore::open_memory().await.unwrap();
1707 let (uuid1, is_new1) = get_or_create_session_uuid(&store, "default").await.unwrap();
1708 let (uuid2, is_new2) = get_or_create_session_uuid(&store, "default").await.unwrap();
1709 assert_eq!(uuid1, uuid2, "same session should return same UUID");
1710 assert!(is_new1, "first call should be new");
1711 assert!(!is_new2, "second call should be existing");
1712 assert_eq!(uuid1.len(), 36, "should be a valid UUID string");
1713 }
1714
1715 #[tokio::test]
1716 async fn session_uuid_differs_per_session() {
1717 let store = TaskStore::open_memory().await.unwrap();
1718 let (uuid_default, _) = get_or_create_session_uuid(&store, "default").await.unwrap();
1719 let (uuid_ops, _) = get_or_create_session_uuid(&store, "ops").await.unwrap();
1720 assert_ne!(uuid_default, uuid_ops);
1721 }
1722
1723 #[tokio::test]
1724 async fn session_uuid_reset_creates_new() {
1725 let store = TaskStore::open_memory().await.unwrap();
1726 let (uuid1, _) = get_or_create_session_uuid(&store, "default").await.unwrap();
1727 reset_session_uuid(&store, "default").await.unwrap();
1728 let (uuid2, is_new2) = get_or_create_session_uuid(&store, "default").await.unwrap();
1729 assert_ne!(uuid1, uuid2, "reset should produce a new UUID");
1730 assert!(is_new2, "after reset should be new");
1731 }
1732
1733 #[test]
1738 fn timeout_error_patterns_match_runner_output() {
1739 let patterns = ["timeout after 1800s", "agent timed out after 120s"];
1740 for &msg in &patterns {
1741 let is_timeout = msg.contains("timeout after") || msg.contains("timed out after");
1742 assert!(is_timeout, "pattern should be detected as timeout: {msg:?}");
1743 }
1744 let non_timeout = [
1746 "rate limit: 429",
1747 "stale session (session expired): abc",
1748 "auth error: invalid key",
1749 ];
1750 for &msg in &non_timeout {
1751 let is_timeout = msg.contains("timeout after") || msg.contains("timed out after");
1752 assert!(
1753 !is_timeout,
1754 "pattern must not be detected as timeout: {msg:?}"
1755 );
1756 }
1757 }
1758
1759 #[test]
1762 fn chunk_text_under_limit_returns_single_chunk() {
1763 let text = "hello world";
1764 let chunks = chunk_text(text, 100);
1765 assert_eq!(chunks, vec!["hello world".to_string()]);
1766 }
1767
1768 #[test]
1769 fn chunk_text_exact_limit_returns_single_chunk() {
1770 let text = "abcde";
1771 let chunks = chunk_text(text, 5);
1772 assert_eq!(chunks.len(), 1);
1773 assert_eq!(chunks[0], "abcde");
1774 }
1775
1776 #[test]
1777 fn chunk_text_splits_and_reassembles() {
1778 let text = "line1\nline2\nline3\nline4\nline5";
1779 let chunks = chunk_text(text, 12);
1780 let reassembled: String = chunks.join("");
1781 assert_eq!(reassembled, text);
1782 }
1783
1784 #[test]
1785 fn chunk_text_respects_utf8_boundaries() {
1786 let content = format!("{}😀", "x".repeat(97)); let chunks = chunk_text(&content, 100);
1790 let reassembled: String = chunks.join("");
1791 assert_eq!(reassembled, content);
1792 for c in &chunks {
1793 assert!(
1794 str::from_utf8(c.as_bytes()).is_ok(),
1795 "chunk is not valid UTF-8"
1796 );
1797 }
1798 }
1799
1800 #[test]
1801 fn chunk_text_prefers_newline_boundary() {
1802 let text = "aaaa\nbbbb";
1804 let chunks = chunk_text(text, 6);
1805 assert!(
1807 chunks[0].ends_with('\n'),
1808 "expected split at newline, got: {:?}",
1809 chunks[0]
1810 );
1811 let reassembled: String = chunks.join("");
1812 assert_eq!(reassembled, text);
1813 }
1814
1815 #[test]
1816 fn chunk_text_empty_string() {
1817 let chunks = chunk_text("", 32);
1818 assert!(chunks.is_empty() || chunks == vec![String::new()]);
1819 }
1820
1821 #[test]
1824 fn build_control_chunks_session_agent_splits_state_and_message() {
1825 let state = "state content";
1828 let message = "user question";
1829 let chunks = build_control_chunks(state, message, true);
1830 assert_eq!(chunks.len(), 2);
1831 assert_eq!(chunks[0], "state content");
1832 assert_eq!(chunks[1], "user question");
1833 }
1834
1835 #[test]
1836 fn build_control_chunks_session_agent_long_state_splits() {
1837 let state = "line\n".repeat(10000); let message = "question";
1840 let chunks = build_control_chunks(&state, message, true);
1841 assert!(chunks.len() >= 3);
1843 for chunk in &chunks[..chunks.len() - 1] {
1845 assert!(chunk.contains("line"));
1846 }
1847 assert_eq!(chunks.last().unwrap(), "question");
1849 }
1850
1851 #[test]
1852 fn build_control_chunks_non_session_agent_adds_headers() {
1853 let state = "state content";
1854 let message = "user question";
1855 let chunks = build_control_chunks(state, message, false);
1856 assert_eq!(chunks.len(), 2);
1857 assert!(chunks[0].starts_with("[Context chunk 1/1]"));
1858 assert!(chunks[0].contains("state content"));
1859 assert!(chunks[1].starts_with("[Context complete. User question:]"));
1860 assert!(chunks[1].contains("user question"));
1861 }
1862
1863 #[test]
1864 fn build_control_chunks_non_session_agent_splits_long_message() {
1865 let state = "state";
1866 let message = "x".repeat(50000); let chunks = build_control_chunks(state, &message, false);
1868 assert!(chunks.len() >= 2);
1870 assert!(chunks[0].starts_with("[Context chunk 1/1]"));
1871 for chunk in &chunks[1..] {
1873 assert!(chunk.starts_with("[User question chunk"));
1874 }
1875 let reassembled_state = chunks[0].split_once('\n').map_or("", |(_, r)| r);
1877 assert_eq!(reassembled_state, "state");
1878 }
1879
1880 #[test]
1881 fn build_control_chunks_non_session_agent_long_state_splits() {
1882 let state = "line\n".repeat(10000); let message = "question";
1884 let chunks = build_control_chunks(&state, message, false);
1885 assert!(chunks.len() >= 3);
1887 for (i, chunk) in chunks.iter().enumerate() {
1888 if i < chunks.len() - 1 {
1889 assert!(chunk.starts_with(&format!("[Context chunk {}/", i + 1)));
1890 assert!(chunk.contains("line"));
1891 } else {
1892 assert!(chunk.starts_with("[Context complete. User question:]"));
1893 assert_eq!(chunk.split_once('\n').map_or("", |(_, r)| r), "question");
1894 }
1895 }
1896 }
1897}