//! Loops through a real App Server (design §12): a start delivers round 1 at //! once with the loop marker; a self-paced `next` clamps its delay and delivers //! round 2; a round without `next` leaves the loop `waiting` and delivers //! nothing more; `stop` is idempotent; expiry settles `expired`; a gone branch //! settles `stopped`; a restart with a delivered round settles by lookup and //! never writes a second one; a `next` or `stop` reply carries a prompt only //! for a loop of the calling branch. A row that waits for a window names one an //! hour out and crosses it with the clock; one that waits for a pass crosses a tick //! (#1536). use dim_agent_capabilities::{defaults, history::HistoryRenderer, host::*}; use dim_agent_runtime::SessionLines; use dim_agent_runtime::{AgentBuilder, AgentConfig}; use dim_agent_types::*; use dim_app_server::{RunningServer, ServerConfig, serve}; use dim_client::{Client, ConnectionConfig, Server}; use serde_json::{Value, json}; use std::{ collections::VecDeque, os::unix::fs::PermissionsExt, path::Path, sync::{Arc, Mutex}, time::Duration, }; use tokio_util::sync::CancellationToken; /// Replies with queued tool batches, then with text; keeps every request. A /// request whose rendered text contains `hold` waits until `release`, the way /// `support::Script` does (support/mod.rs). #[derive(Default)] struct Script { batches: Mutex>>, requests: Mutex>>, held: Mutex>, release: tokio::sync::Notify, } impl Script { fn push(&self, calls: Vec) { self.batches.lock().unwrap().push_back(calls); } fn count(&self) -> usize { self.requests.lock().unwrap().len() } /// Holds every request whose rendered text contains `marker`. fn hold(&self, marker: &str) { *self.held.lock().unwrap() = Some(marker.to_owned()); } fn release(&self) { *self.held.lock().unwrap() = None; self.release.notify_waiters(); } /// The text and error flag of the result for `id`, as the model reads them. fn tool_result(&self, id: &str) -> Option<(String, bool)> { self.requests.lock().unwrap().iter().find_map(|request| { request.messages.iter().find_map(|message| { let MessageContent::Parts(parts) = &message.content else { return None; }; parts.iter().find_map(|part| match part { MessagePart::ToolResult { tool_use_id, content: ToolContent::Text(text), is_error, .. } if tool_use_id == id => Some((text.clone(), is_error == &Some(true))), _ => None, }) }) }) } } impl ModelDriver for Script { fn invoke( &self, request: Arc, _: ModelConnection, cancel: CancellationToken, ) -> HostFuture<'_, ModelStream> { Box::pin(async move { let rendered = format!("{request:?}"); self.requests.lock().unwrap().push(request); loop { let released = self.release.notified(); let held = self .held .lock() .unwrap() .as_ref() .is_some_and(|marker| rendered.contains(marker.as_str())); if !held { break; } tokio::select! { _ = released => {} _ = cancel.cancelled() => break, } } let id = format!("m{}", self.count()); let mut chunks = vec![Ok(ModelChunk::MessageStart { message_id: id.clone(), })]; let reason = match self.batches.lock().unwrap().pop_front() { Some(calls) => { for call in calls { chunks.push(Ok(ModelChunk::ToolStart { id: call.id.clone(), name: call.name.clone(), })); chunks.push(Ok(ModelChunk::ToolUse(call))); } ModelStopReason::ToolUse } None => { chunks.push(Ok(ModelChunk::Text("done".into()))); chunks.push(Ok(ModelChunk::TextEnd)); ModelStopReason::EndTurn } }; chunks.push(Ok(ModelChunk::MessageStop { message_id: id, reason, })); Ok(Box::pin(futures_util::stream::iter(chunks)) as ModelStream) }) } } fn home() -> tempfile::TempDir { let home = tempfile::tempdir().unwrap(); std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); std::fs::create_dir_all(home.path().join("scheduler")).unwrap(); home } async fn start(home: &Path, model: Arc