Read-only mirror of github.com/ondeinference/ed.
Mirrored from https://github.com/ondeinference/ed.git
Synced Nov 23, 01:00 UTC
| 1 | //! The agent handle. |
| 2 | |
| 3 | use std::collections::{HashMap, HashSet}; |
| 4 | use std::future::Future; |
| 5 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 6 | use std::sync::Arc; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use log::{error, info}; |
| 10 | use onde::inference::types::{format_duration, ChatMessage}; |
| 11 | use onde::inference::{ |
| 12 | ChatEngine, EngineInfo, EngineStatus, GgufModelConfig, InferenceError, SamplingConfig, |
| 13 | ToolCallingSupport, ToolDefinition, ToolResult, |
| 14 | }; |
| 15 | use web_time::Instant; |
| 16 | |
| 17 | use crate::{ |
| 18 | stream::chunk_error, tool::truncate_output, AgentConfig, AgentError, AgentReply, |
| 19 | AgentToolDefinition, ApprovalDecision, ApprovalHandler, ApprovalRequest, ChatReply, |
| 20 | DenyApprovals, EventSink, NoopSink, RejectingExecutor, TextStream, ToolCall, |
| 21 | ToolExecutionResult, ToolExecutor, ToolRisk, |
| 22 | }; |
| 23 | |
| 24 | /// An embeddable chat agent over a single [`ChatEngine`]. |
| 25 | /// |
| 26 | /// Hold one per application. Ed is `Send + Sync` and every method takes |
| 27 | /// `&self`, so it can live behind a `OnceLock`, a framework's managed state, |
| 28 | /// or an `Arc` — whichever the host prefers. It is not cloneable by design: |
| 29 | /// one Ed owns one engine owns one loaded model, and copying that handle |
| 30 | /// around tends to mean two parts of an app disagree about which model is up. |
| 31 | pub struct Ed<S = NoopSink> { |
| 32 | engine: ChatEngine, |
| 33 | sink: S, |
| 34 | tools: tokio::sync::RwLock<HashMap<String, AgentToolDefinition>>, |
| 35 | executor: Arc<dyn ToolExecutor>, |
| 36 | approvals: Arc<dyn ApprovalHandler>, |
| 37 | session_grants: tokio::sync::Mutex<HashSet<String>>, |
| 38 | turn: tokio::sync::Mutex<()>, |
| 39 | cancelled: AtomicBool, |
| 40 | agent_config: AgentConfig, |
| 41 | } |
| 42 | |
| 43 | impl Ed<NoopSink> { |
| 44 | /// An agent that reports nothing. Poll [`info`](Ed::info) for state. |
| 45 | pub fn new() -> Self { |
| 46 | Self::with_sink(NoopSink) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl Default for Ed<NoopSink> { |
| 51 | fn default() -> Self { |
| 52 | Self::new() |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl<S: EventSink> Ed<S> { |
| 57 | /// An agent that reports transitions and replies to `sink`. |
| 58 | pub fn with_sink(sink: S) -> Self { |
| 59 | Self::with_agent( |
| 60 | sink, |
| 61 | Arc::new(RejectingExecutor), |
| 62 | Arc::new(DenyApprovals), |
| 63 | AgentConfig::default(), |
| 64 | ) |
| 65 | } |
| 66 | |
| 67 | /// Build an agent with host-defined tool execution and approval handling. |
| 68 | pub fn with_agent( |
| 69 | sink: S, |
| 70 | executor: Arc<dyn ToolExecutor>, |
| 71 | approvals: Arc<dyn ApprovalHandler>, |
| 72 | config: AgentConfig, |
| 73 | ) -> Self { |
| 74 | Self::with_agent_and_app_id(sink, executor, approvals, config, None) |
| 75 | } |
| 76 | |
| 77 | /// Associate telemetry with an Onde app id. See [`ChatEngine::with_app_id`]. |
| 78 | pub fn with_app_id(sink: S, onde_app_id: Option<String>) -> Self { |
| 79 | Self::with_agent_and_app_id( |
| 80 | sink, |
| 81 | Arc::new(RejectingExecutor), |
| 82 | Arc::new(DenyApprovals), |
| 83 | AgentConfig::default(), |
| 84 | onde_app_id, |
| 85 | ) |
| 86 | } |
| 87 | |
| 88 | /// The full constructor: tools, approvals, and an Onde app id together. |
| 89 | /// |
| 90 | /// The narrower constructors each fill in defaults for what they don't |
| 91 | /// take. Use this one when you need both host tools and telemetry, which |
| 92 | /// the others cannot express between them. |
| 93 | pub fn with_agent_and_app_id( |
| 94 | sink: S, |
| 95 | executor: Arc<dyn ToolExecutor>, |
| 96 | approvals: Arc<dyn ApprovalHandler>, |
| 97 | config: AgentConfig, |
| 98 | onde_app_id: Option<String>, |
| 99 | ) -> Self { |
| 100 | Self { |
| 101 | engine: ChatEngine::with_app_id(onde_app_id), |
| 102 | sink, |
| 103 | tools: tokio::sync::RwLock::new(HashMap::new()), |
| 104 | executor, |
| 105 | approvals, |
| 106 | session_grants: tokio::sync::Mutex::new(HashSet::new()), |
| 107 | turn: tokio::sync::Mutex::new(()), |
| 108 | cancelled: AtomicBool::new(false), |
| 109 | agent_config: config.validated(), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// The underlying engine. |
| 114 | /// |
| 115 | /// An escape hatch for the parts of `onde` Ed deliberately doesn't wrap — |
| 116 | /// system prompts, alternative load paths, tool calling. Reach for it when |
| 117 | /// you need them; anything you find yourself writing here for a second |
| 118 | /// application is a candidate to move into Ed. |
| 119 | pub fn engine(&self) -> &ChatEngine { |
| 120 | &self.engine |
| 121 | } |
| 122 | |
| 123 | /// Run any load, reporting the transitions around it. |
| 124 | /// |
| 125 | /// Emits [`EngineStatus::Loading`] before `load` starts and then either |
| 126 | /// [`Ready`](EngineStatus::Ready) or [`Error`](EngineStatus::Error). That |
| 127 | /// sequence is the whole reason this method exists: calling a |
| 128 | /// [`ChatEngine`] load path directly leaves the UI with no way to know a |
| 129 | /// multi-minute download has begun. |
| 130 | /// |
| 131 | /// Ed takes a closure rather than wrapping each load path by name because |
| 132 | /// `onde`'s load APIs take types Ed has no business in its public |
| 133 | /// signature — `ChatEngine::load_assigned_model` takes an `Environment` |
| 134 | /// from the smbCloud SDK, and *which* crate that type comes from changed |
| 135 | /// between `onde` releases. Naming it here would drag that dependency into |
| 136 | /// every host and pin them all to Ed's version of it. Passing a closure |
| 137 | /// keeps Ed's dependency surface to `onde` alone and works for load paths |
| 138 | /// that don't exist yet. |
| 139 | /// |
| 140 | /// ```no_run |
| 141 | /// # use ed_agent::{Ed, GgufModelConfig}; |
| 142 | /// # async fn example(ed: Ed) { |
| 143 | /// ed.load_with("Qwen 2.5", |engine| { |
| 144 | /// engine.load_gguf_model(GgufModelConfig::qwen25_1_5b(), None, None) |
| 145 | /// }) |
| 146 | /// .await |
| 147 | /// .expect("load"); |
| 148 | /// # } |
| 149 | /// ``` |
| 150 | /// |
| 151 | /// `model_name` is what the host wants the UI to show while loading; it is |
| 152 | /// reported with each transition and needn't match what the engine ends up |
| 153 | /// calling the model. |
| 154 | pub async fn load_with<'a, F, Fut>( |
| 155 | &'a self, |
| 156 | model_name: &str, |
| 157 | load: F, |
| 158 | ) -> Result<Duration, InferenceError> |
| 159 | where |
| 160 | F: FnOnce(&'a ChatEngine) -> Fut, |
| 161 | Fut: Future<Output = Result<Duration, InferenceError>>, |
| 162 | { |
| 163 | info!("ed: loading model {model_name}"); |
| 164 | self.sink |
| 165 | .status_changed(EngineStatus::Loading, Some(model_name), None); |
| 166 | |
| 167 | match load(&self.engine).await { |
| 168 | Ok(elapsed) => { |
| 169 | info!("ed: loaded {model_name} in {}", format_duration(elapsed)); |
| 170 | self.sink |
| 171 | .status_changed(EngineStatus::Ready, Some(model_name), None); |
| 172 | Ok(elapsed) |
| 173 | } |
| 174 | Err(err) => { |
| 175 | error!("ed: failed to load {model_name}: {err}"); |
| 176 | let message = err.to_string(); |
| 177 | self.sink |
| 178 | .status_changed(EngineStatus::Error, Some(model_name), Some(&message)); |
| 179 | Err(err) |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// Load a GGUF model, reporting each transition. |
| 185 | /// |
| 186 | /// A convenience over [`load_with`](Ed::load_with) for the most common |
| 187 | /// path. Downloads the weights first if they aren't in the local cache, so |
| 188 | /// the `Loading` state can last a long time on a cold start. |
| 189 | pub async fn load( |
| 190 | &self, |
| 191 | config: GgufModelConfig, |
| 192 | system_prompt: Option<String>, |
| 193 | sampling: Option<SamplingConfig>, |
| 194 | ) -> Result<Duration, InferenceError> { |
| 195 | let model_name = config.display_name.clone(); |
| 196 | self.load_with(&model_name, |engine| { |
| 197 | engine.load_gguf_model(config, system_prompt, sampling) |
| 198 | }) |
| 199 | .await |
| 200 | } |
| 201 | |
| 202 | /// Unload the current model, returning its display name if one was loaded. |
| 203 | pub async fn unload(&self) -> Option<String> { |
| 204 | let unloaded = self.engine.unload_model().await; |
| 205 | if let Some(name) = &unloaded { |
| 206 | info!("ed: unloaded {name}"); |
| 207 | } |
| 208 | self.sink |
| 209 | .status_changed(EngineStatus::Unloaded, unloaded.as_deref(), None); |
| 210 | unloaded |
| 211 | } |
| 212 | |
| 213 | /// Run one inference turn. |
| 214 | /// |
| 215 | /// Never returns an error: a failure is reported in |
| 216 | /// [`ChatReply::error`] so a caller has one shape to render either way. |
| 217 | /// The reply also goes to the sink, so a host can render it from an event |
| 218 | /// instead of awaiting this call — see [`EventSink::replied`]. |
| 219 | pub async fn send(&self, message: impl Into<String>) -> ChatReply { |
| 220 | let reply = match self.engine.send_message(message).await { |
| 221 | Ok(result) => ChatReply::ok(result.text, result.duration_display), |
| 222 | Err(err) => { |
| 223 | error!("ed: inference failed: {err}"); |
| 224 | ChatReply::failed(err) |
| 225 | } |
| 226 | }; |
| 227 | self.sink.replied(&reply); |
| 228 | reply |
| 229 | } |
| 230 | |
| 231 | /// Stream the reply to one message, for plain chat without tools. |
| 232 | /// |
| 233 | /// Returns once generation has started; the stream yields text deltas as |
| 234 | /// they are produced. Unlike [`run`](Ed::run) this takes no turn lock and |
| 235 | /// reports nothing to the sink, so don't overlap it with another turn. |
| 236 | /// Drop the stream to cancel; a [`cancel`](Ed::cancel) call is not needed. |
| 237 | pub async fn stream(&self, message: impl Into<String>) -> Result<TextStream, InferenceError> { |
| 238 | Ok(TextStream::new(self.engine.stream_message(message).await?)) |
| 239 | } |
| 240 | |
| 241 | /// One-shot generation over explicit messages. |
| 242 | /// |
| 243 | /// Leaves the conversation history untouched; the engine's system prompt |
| 244 | /// is still applied. `sampling` overrides the engine's for this call only. |
| 245 | pub async fn generate( |
| 246 | &self, |
| 247 | messages: Vec<ChatMessage>, |
| 248 | sampling: Option<SamplingConfig>, |
| 249 | ) -> Result<String, InferenceError> { |
| 250 | Ok(self.engine.generate(messages, sampling).await?.text) |
| 251 | } |
| 252 | |
| 253 | /// Set the system prompt used for every later turn. |
| 254 | /// |
| 255 | /// Like the other engine setters below, and `restore_history`, this does |
| 256 | /// nothing until a model is loaded: `onde` keeps these on the loaded model. |
| 257 | pub async fn set_system_prompt(&self, prompt: impl Into<String>) { |
| 258 | self.engine.set_system_prompt(prompt).await; |
| 259 | } |
| 260 | |
| 261 | pub async fn clear_system_prompt(&self) { |
| 262 | self.engine.clear_system_prompt().await; |
| 263 | } |
| 264 | |
| 265 | /// Change the default sampling parameters. |
| 266 | pub async fn set_sampling(&self, sampling: SamplingConfig) { |
| 267 | self.engine.set_sampling(sampling).await; |
| 268 | } |
| 269 | |
| 270 | /// Replace the conversation with `messages`. |
| 271 | /// |
| 272 | /// For switching to a saved session or restoring one at launch. Clears |
| 273 | /// the current history first, and with it every `AllowForSession` grant, |
| 274 | /// exactly as [`clear_history`](Ed::clear_history) does: a restored |
| 275 | /// conversation starts without consent from the previous one. |
| 276 | pub async fn restore_history(&self, messages: Vec<ChatMessage>) { |
| 277 | self.clear_history().await; |
| 278 | let count = messages.len(); |
| 279 | for message in messages { |
| 280 | self.engine.push_history(message).await; |
| 281 | } |
| 282 | info!("ed: restored {count} messages"); |
| 283 | } |
| 284 | |
| 285 | /// Register a host capability that the model may request. |
| 286 | pub async fn register_tool(&self, tool: AgentToolDefinition) -> Result<(), AgentError> { |
| 287 | tool.validate()?; |
| 288 | let mut tools = self.tools.write().await; |
| 289 | if tools.contains_key(&tool.name) { |
| 290 | return Err(AgentError::DuplicateTool { |
| 291 | name: tool.name.clone(), |
| 292 | }); |
| 293 | } |
| 294 | tools.insert(tool.name.clone(), tool); |
| 295 | Ok(()) |
| 296 | } |
| 297 | |
| 298 | pub async fn unregister_tool(&self, name: &str) -> bool { |
| 299 | self.tools.write().await.remove(name).is_some() |
| 300 | } |
| 301 | |
| 302 | pub async fn remove_all_tools(&self) { |
| 303 | self.tools.write().await.clear(); |
| 304 | self.session_grants.lock().await.clear(); |
| 305 | } |
| 306 | |
| 307 | /// Request cancellation of the active agent turn. |
| 308 | pub fn cancel(&self) { |
| 309 | self.cancelled.store(true, Ordering::Release); |
| 310 | } |
| 311 | |
| 312 | async fn execute_tool_call( |
| 313 | &self, |
| 314 | call: &ToolCall, |
| 315 | registered: &HashMap<String, AgentToolDefinition>, |
| 316 | ) -> ToolExecutionResult { |
| 317 | let Some(definition) = registered.get(&call.name) else { |
| 318 | return ToolExecutionResult { |
| 319 | tool_call_id: call.id.clone(), |
| 320 | content: format!("tool {:?} is not registered", call.name), |
| 321 | is_error: true, |
| 322 | }; |
| 323 | }; |
| 324 | |
| 325 | if !matches!( |
| 326 | serde_json::from_str::<serde_json::Value>(&call.arguments), |
| 327 | Ok(serde_json::Value::Object(_)) |
| 328 | ) { |
| 329 | return ToolExecutionResult { |
| 330 | tool_call_id: call.id.clone(), |
| 331 | content: "tool arguments must be a valid JSON object".to_string(), |
| 332 | is_error: true, |
| 333 | }; |
| 334 | } |
| 335 | |
| 336 | let approved = if definition.risk == ToolRisk::ReadOnly |
| 337 | || self.session_grants.lock().await.contains(&call.name) |
| 338 | { |
| 339 | true |
| 340 | } else { |
| 341 | let request = ApprovalRequest { |
| 342 | call: call.clone(), |
| 343 | risk: definition.risk, |
| 344 | }; |
| 345 | self.sink.approval_requested(&request); |
| 346 | match self.approvals.approve(request).await { |
| 347 | ApprovalDecision::AllowOnce => true, |
| 348 | ApprovalDecision::AllowForSession => { |
| 349 | self.session_grants.lock().await.insert(call.name.clone()); |
| 350 | true |
| 351 | } |
| 352 | ApprovalDecision::Deny => false, |
| 353 | } |
| 354 | }; |
| 355 | |
| 356 | if !approved { |
| 357 | return ToolExecutionResult { |
| 358 | tool_call_id: call.id.clone(), |
| 359 | content: format!("tool {:?} was denied by the user", call.name), |
| 360 | is_error: true, |
| 361 | }; |
| 362 | } |
| 363 | |
| 364 | self.sink.tool_started(call); |
| 365 | match self.executor.execute(&call.name, &call.arguments).await { |
| 366 | Ok(content) => ToolExecutionResult { |
| 367 | tool_call_id: call.id.clone(), |
| 368 | content: truncate_output(content, self.agent_config.max_tool_output_chars), |
| 369 | is_error: false, |
| 370 | }, |
| 371 | Err(error) => ToolExecutionResult { |
| 372 | tool_call_id: call.id.clone(), |
| 373 | content: truncate_output( |
| 374 | format!("tool execution failed: {error}"), |
| 375 | self.agent_config.max_tool_output_chars, |
| 376 | ), |
| 377 | is_error: true, |
| 378 | }, |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Run a complete local agent turn, including any requested host tools. |
| 383 | /// |
| 384 | /// With no tools registered this is one inference call. Otherwise Ed |
| 385 | /// alternates between the model and the host's executor until the model |
| 386 | /// answers in text, or until |
| 387 | /// [`max_tool_rounds`](AgentConfig::max_tool_rounds) is spent, whichever |
| 388 | /// comes first. Reaching the budget is reported to the sink as a warning, |
| 389 | /// and yields [`AgentError::ToolRoundsExhausted`] if there is no usable |
| 390 | /// text by then. |
| 391 | /// |
| 392 | /// Reports [`EventSink::agent_replied`] on success. It does *not* report |
| 393 | /// [`EventSink::replied`]; that belongs to [`send`](Ed::send). |
| 394 | pub async fn run(&self, message: impl Into<String>) -> Result<AgentReply, AgentError> { |
| 395 | let _turn = self.turn.lock().await; |
| 396 | self.cancelled.store(false, Ordering::Release); |
| 397 | |
| 398 | let registered = self.tools.read().await.clone(); |
| 399 | if registered.is_empty() { |
| 400 | // Deliberately not routed through `send`: that reports a |
| 401 | // `ChatReply` to the sink, and a host listening for both events |
| 402 | // would render this turn's answer twice. An agent turn reports |
| 403 | // `agent_replied` and nothing else. |
| 404 | let started = Instant::now(); |
| 405 | let mut rx = self.engine.stream_message(message).await.map_err(|error| { |
| 406 | AgentError::Inference { |
| 407 | reason: error.to_string(), |
| 408 | } |
| 409 | })?; |
| 410 | let mut text = String::new(); |
| 411 | while let Some(chunk) = rx.recv().await { |
| 412 | if self.cancelled.load(Ordering::Acquire) { |
| 413 | // Dropping the receiver stops generation. |
| 414 | return Err(AgentError::Cancelled); |
| 415 | } |
| 416 | if chunk.done { |
| 417 | if let Some(error) = chunk_error(&chunk) { |
| 418 | return Err(AgentError::Inference { |
| 419 | reason: error.to_string(), |
| 420 | }); |
| 421 | } |
| 422 | break; |
| 423 | } |
| 424 | if !chunk.delta.is_empty() { |
| 425 | self.sink.text_delta(&chunk.delta); |
| 426 | text.push_str(&chunk.delta); |
| 427 | } |
| 428 | } |
| 429 | if text.trim().is_empty() { |
| 430 | return Err(AgentError::EmptyReply); |
| 431 | } |
| 432 | let elapsed = started.elapsed(); |
| 433 | let agent_reply = AgentReply { |
| 434 | text, |
| 435 | duration_seconds: elapsed.as_secs_f64(), |
| 436 | duration: format_duration(elapsed), |
| 437 | tool_rounds: 0, |
| 438 | }; |
| 439 | self.sink.agent_replied(&agent_reply); |
| 440 | return Ok(agent_reply); |
| 441 | } |
| 442 | |
| 443 | match self.engine.tool_calling_support().await { |
| 444 | ToolCallingSupport::Unsupported => return Err(AgentError::UnsupportedModel), |
| 445 | ToolCallingSupport::Unknown => self |
| 446 | .sink |
| 447 | .warning("the loaded model has not been verified for tool calling"), |
| 448 | ToolCallingSupport::Supported => {} |
| 449 | } |
| 450 | |
| 451 | let mut definitions: Vec<ToolDefinition> = registered |
| 452 | .values() |
| 453 | .map(|tool| ToolDefinition { |
| 454 | name: tool.name.clone(), |
| 455 | description: tool.description.clone(), |
| 456 | parameters_schema: tool.parameters_schema.clone(), |
| 457 | }) |
| 458 | .collect(); |
| 459 | definitions.sort_by(|left, right| left.name.cmp(&right.name)); |
| 460 | |
| 461 | let mut result = self |
| 462 | .engine |
| 463 | .send_message_with_tools(message.into(), &definitions) |
| 464 | .await |
| 465 | .map_err(|error| AgentError::Inference { |
| 466 | reason: error.to_string(), |
| 467 | })?; |
| 468 | let mut duration_seconds = result.duration_secs; |
| 469 | let mut rounds = 0_u8; |
| 470 | let max_rounds = self.agent_config.max_tool_rounds; |
| 471 | let mut exhausted = false; |
| 472 | |
| 473 | while !result.tool_calls.is_empty() { |
| 474 | if !self.agent_config.allows_round(rounds) { |
| 475 | // The budget only stops Ed *offering* tools; it cannot stop the |
| 476 | // model asking. `onde` parses tool calls out of every response |
| 477 | // whether or not tools were sent, so a model that keeps |
| 478 | // emitting tool-call syntax would loop here until `rounds` |
| 479 | // overflowed and wrapped back under the limit. This is the |
| 480 | // loop's only hard exit. |
| 481 | // |
| 482 | // The model's last turn is already in history carrying these |
| 483 | // calls. Leaving them unanswered would make the next turn's |
| 484 | // message sequence invalid, so close them out the way |
| 485 | // cancelling does. |
| 486 | let unanswered = result |
| 487 | .tool_calls |
| 488 | .iter() |
| 489 | .map(|pending| ToolResult { |
| 490 | tool_call_id: pending.id.clone(), |
| 491 | content: "tool was not executed: the agent ran out of tool rounds" |
| 492 | .to_string(), |
| 493 | }) |
| 494 | .collect(); |
| 495 | self.engine.record_tool_results(unanswered).await; |
| 496 | self.sink.warning(&format!( |
| 497 | "the agent stopped after {max_rounds} tool rounds; the model kept requesting tools" |
| 498 | )); |
| 499 | exhausted = true; |
| 500 | break; |
| 501 | } |
| 502 | rounds += 1; |
| 503 | let mut tool_results = Vec::with_capacity(result.tool_calls.len()); |
| 504 | |
| 505 | for (index, requested) in result.tool_calls.iter().enumerate() { |
| 506 | if self.cancelled.load(Ordering::Acquire) { |
| 507 | for pending in &result.tool_calls[index..] { |
| 508 | tool_results.push(ToolResult { |
| 509 | tool_call_id: pending.id.clone(), |
| 510 | content: "tool was not executed because the user cancelled the turn" |
| 511 | .to_string(), |
| 512 | }); |
| 513 | } |
| 514 | self.engine.record_tool_results(tool_results).await; |
| 515 | return Err(AgentError::Cancelled); |
| 516 | } |
| 517 | |
| 518 | let call = ToolCall { |
| 519 | id: requested.id.clone(), |
| 520 | name: requested.function_name.clone(), |
| 521 | arguments: requested.arguments.clone(), |
| 522 | }; |
| 523 | self.sink.tool_requested(&call); |
| 524 | |
| 525 | let execution = self.execute_tool_call(&call, ®istered).await; |
| 526 | self.sink.tool_finished(&execution); |
| 527 | tool_results.push(ToolResult { |
| 528 | tool_call_id: execution.tool_call_id, |
| 529 | content: execution.content, |
| 530 | }); |
| 531 | } |
| 532 | |
| 533 | if self.cancelled.load(Ordering::Acquire) { |
| 534 | self.engine.record_tool_results(tool_results).await; |
| 535 | return Err(AgentError::Cancelled); |
| 536 | } |
| 537 | |
| 538 | let next_tools = if self.agent_config.allows_round(rounds) { |
| 539 | Some(definitions.as_slice()) |
| 540 | } else { |
| 541 | None |
| 542 | }; |
| 543 | result = self |
| 544 | .engine |
| 545 | .send_tool_results(tool_results, next_tools) |
| 546 | .await |
| 547 | .map_err(|error| AgentError::Inference { |
| 548 | reason: error.to_string(), |
| 549 | })?; |
| 550 | duration_seconds += result.duration_secs; |
| 551 | } |
| 552 | |
| 553 | if result.text.trim().is_empty() { |
| 554 | return Err(if exhausted { |
| 555 | AgentError::ToolRoundsExhausted { rounds: max_rounds } |
| 556 | } else { |
| 557 | AgentError::EmptyReply |
| 558 | }); |
| 559 | } |
| 560 | // Tool rounds are not streamed: `onde` only parses tool calls out of a |
| 561 | // complete response, so the answer arrives whole. Report it as one |
| 562 | // delta so a host rendering deltas sees every turn the same way. |
| 563 | self.sink.text_delta(&result.text); |
| 564 | let reply = AgentReply { |
| 565 | text: result.text, |
| 566 | duration_seconds, |
| 567 | duration: format_duration(Duration::from_secs_f64(duration_seconds)), |
| 568 | tool_rounds: rounds, |
| 569 | }; |
| 570 | self.sink.agent_replied(&reply); |
| 571 | Ok(reply) |
| 572 | } |
| 573 | |
| 574 | /// Current status, loaded model, footprint, and history length. |
| 575 | pub async fn info(&self) -> EngineInfo { |
| 576 | self.engine.info().await |
| 577 | } |
| 578 | |
| 579 | /// Whether a model is loaded and ready. |
| 580 | pub async fn is_loaded(&self) -> bool { |
| 581 | self.engine.is_loaded().await |
| 582 | } |
| 583 | |
| 584 | /// The conversation so far. |
| 585 | pub async fn history(&self) -> Vec<ChatMessage> { |
| 586 | self.engine.history().await |
| 587 | } |
| 588 | |
| 589 | /// Clear the conversation, returning how many messages were dropped. |
| 590 | /// |
| 591 | /// Leaves the model loaded — this starts a new conversation, it doesn't |
| 592 | /// tear down the engine. |
| 593 | /// |
| 594 | /// Also drops every `AllowForSession` grant. The user approved those |
| 595 | /// mutating tools for a conversation, and this ends the conversation; |
| 596 | /// carrying the grants into the next one would keep consent alive past the |
| 597 | /// thing it was given for. |
| 598 | pub async fn clear_history(&self) -> usize { |
| 599 | let cleared = self.engine.clear_history().await; |
| 600 | self.session_grants.lock().await.clear(); |
| 601 | info!("ed: cleared {cleared} messages"); |
| 602 | cleared |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | #[cfg(test)] |
| 607 | mod tests { |
| 608 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 609 | use std::sync::Mutex; |
| 610 | |
| 611 | use super::*; |
| 612 | |
| 613 | /// Records everything Ed reports, so a test can assert on the sequence of |
| 614 | /// transitions rather than only the final state. |
| 615 | #[derive(Default)] |
| 616 | struct RecordingSink { |
| 617 | statuses: Mutex<Vec<(EngineStatus, Option<String>)>>, |
| 618 | errors: Mutex<Vec<Option<String>>>, |
| 619 | replies: Mutex<Vec<ChatReply>>, |
| 620 | } |
| 621 | |
| 622 | impl RecordingSink { |
| 623 | fn statuses(&self) -> Vec<(EngineStatus, Option<String>)> { |
| 624 | self.statuses.lock().unwrap().clone() |
| 625 | } |
| 626 | |
| 627 | fn errors(&self) -> Vec<Option<String>> { |
| 628 | self.errors.lock().unwrap().clone() |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | impl EventSink for &'static RecordingSink { |
| 633 | fn status_changed( |
| 634 | &self, |
| 635 | status: EngineStatus, |
| 636 | model_name: Option<&str>, |
| 637 | error: Option<&str>, |
| 638 | ) { |
| 639 | self.statuses |
| 640 | .lock() |
| 641 | .unwrap() |
| 642 | .push((status, model_name.map(str::to_owned))); |
| 643 | self.errors.lock().unwrap().push(error.map(str::to_owned)); |
| 644 | } |
| 645 | |
| 646 | fn replied(&self, reply: &ChatReply) { |
| 647 | self.replies.lock().unwrap().push(reply.clone()); |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | fn sink() -> &'static RecordingSink { |
| 652 | Box::leak(Box::new(RecordingSink::default())) |
| 653 | } |
| 654 | |
| 655 | struct CountingExecutor(AtomicUsize); |
| 656 | |
| 657 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))] |
| 658 | #[cfg_attr( |
| 659 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 660 | async_trait::async_trait |
| 661 | )] |
| 662 | impl ToolExecutor for CountingExecutor { |
| 663 | async fn execute(&self, tool_name: &str, _: &str) -> Result<String, String> { |
| 664 | self.0.fetch_add(1, Ordering::Relaxed); |
| 665 | Ok(format!("{tool_name} completed")) |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | struct FixedApproval(ApprovalDecision); |
| 670 | |
| 671 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), async_trait::async_trait(?Send))] |
| 672 | #[cfg_attr( |
| 673 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 674 | async_trait::async_trait |
| 675 | )] |
| 676 | impl ApprovalHandler for FixedApproval { |
| 677 | async fn approve(&self, _: ApprovalRequest) -> ApprovalDecision { |
| 678 | self.0 |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | fn call(name: &str) -> ToolCall { |
| 683 | ToolCall { |
| 684 | id: "call-1".to_owned(), |
| 685 | name: name.to_owned(), |
| 686 | arguments: "{}".to_owned(), |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | #[tokio::test] |
| 691 | async fn a_fresh_agent_reports_itself_unloaded_and_empty() { |
| 692 | let ed = Ed::new(); |
| 693 | let info = ed.info().await; |
| 694 | |
| 695 | assert_eq!(info.status, EngineStatus::Unloaded); |
| 696 | assert_eq!(info.model_name, None); |
| 697 | assert_eq!(info.history_length, 0); |
| 698 | assert!(!ed.is_loaded().await); |
| 699 | assert!(ed.history().await.is_empty()); |
| 700 | } |
| 701 | |
| 702 | #[tokio::test] |
| 703 | async fn unloading_reports_the_transition_even_with_nothing_loaded() { |
| 704 | // The status still has to reach the host: a UI that asked to unload |
| 705 | // needs to see `Unloaded` regardless of whether work was done, or the |
| 706 | // view sits on a stale "ready" forever. |
| 707 | let sink = sink(); |
| 708 | let ed = Ed::with_sink(sink); |
| 709 | |
| 710 | assert_eq!(ed.unload().await, None); |
| 711 | assert_eq!(sink.statuses(), vec![(EngineStatus::Unloaded, None)]); |
| 712 | } |
| 713 | |
| 714 | #[tokio::test] |
| 715 | async fn clearing_an_empty_history_drops_nothing() { |
| 716 | let ed = Ed::new(); |
| 717 | assert_eq!(ed.clear_history().await, 0); |
| 718 | } |
| 719 | |
| 720 | #[tokio::test] |
| 721 | async fn the_default_sink_swallows_reports_without_panicking() { |
| 722 | // `Ed::new()` is the no-sink path; exercising it guards against a |
| 723 | // future notification being added that assumes a real sink exists. |
| 724 | let ed = Ed::default(); |
| 725 | ed.unload().await; |
| 726 | assert_eq!(ed.info().await.status, EngineStatus::Unloaded); |
| 727 | } |
| 728 | |
| 729 | #[tokio::test] |
| 730 | async fn a_successful_load_reports_loading_then_ready() { |
| 731 | // The ordering is the feature: a UI that only ever sees the final |
| 732 | // state has no way to put up a spinner for a load that can take |
| 733 | // minutes. |
| 734 | let sink = sink(); |
| 735 | let ed = Ed::with_sink(sink); |
| 736 | |
| 737 | let elapsed = ed |
| 738 | .load_with("Test model", |_| async { Ok(Duration::from_secs(2)) }) |
| 739 | .await |
| 740 | .expect("the closure succeeded"); |
| 741 | |
| 742 | assert_eq!(elapsed, Duration::from_secs(2)); |
| 743 | assert_eq!( |
| 744 | sink.statuses(), |
| 745 | vec![ |
| 746 | (EngineStatus::Loading, Some("Test model".to_owned())), |
| 747 | (EngineStatus::Ready, Some("Test model".to_owned())), |
| 748 | ] |
| 749 | ); |
| 750 | } |
| 751 | |
| 752 | #[tokio::test] |
| 753 | async fn a_failed_load_reports_loading_then_error_with_the_reason() { |
| 754 | let sink = sink(); |
| 755 | let ed = Ed::with_sink(sink); |
| 756 | |
| 757 | let err = ed |
| 758 | .load_with("Test model", |_| async { |
| 759 | Err(InferenceError::Other { |
| 760 | reason: "no weights".to_owned(), |
| 761 | }) |
| 762 | }) |
| 763 | .await |
| 764 | .expect_err("the closure failed"); |
| 765 | |
| 766 | assert!(err.to_string().contains("no weights")); |
| 767 | assert_eq!( |
| 768 | sink.statuses(), |
| 769 | vec![ |
| 770 | (EngineStatus::Loading, Some("Test model".to_owned())), |
| 771 | (EngineStatus::Error, Some("Test model".to_owned())), |
| 772 | ] |
| 773 | ); |
| 774 | assert_eq!(sink.errors(), vec![None, Some("no weights".to_owned())]); |
| 775 | } |
| 776 | |
| 777 | #[tokio::test] |
| 778 | async fn read_only_tools_run_without_an_approval_round_trip() { |
| 779 | let executor = Arc::new(CountingExecutor(AtomicUsize::new(0))); |
| 780 | let ed = Ed::with_agent( |
| 781 | NoopSink, |
| 782 | executor.clone(), |
| 783 | Arc::new(FixedApproval(ApprovalDecision::Deny)), |
| 784 | AgentConfig::default(), |
| 785 | ); |
| 786 | ed.register_tool(AgentToolDefinition::read_only( |
| 787 | "clock", |
| 788 | "Read the clock", |
| 789 | r#"{"type":"object"}"#, |
| 790 | )) |
| 791 | .await |
| 792 | .unwrap(); |
| 793 | let tools = ed.tools.read().await.clone(); |
| 794 | |
| 795 | let result = ed.execute_tool_call(&call("clock"), &tools).await; |
| 796 | |
| 797 | assert!(!result.is_error); |
| 798 | assert_eq!(executor.0.load(Ordering::Relaxed), 1); |
| 799 | } |
| 800 | |
| 801 | #[tokio::test] |
| 802 | async fn denied_mutating_tools_never_reach_the_executor() { |
| 803 | let executor = Arc::new(CountingExecutor(AtomicUsize::new(0))); |
| 804 | let ed = Ed::with_agent( |
| 805 | NoopSink, |
| 806 | executor.clone(), |
| 807 | Arc::new(FixedApproval(ApprovalDecision::Deny)), |
| 808 | AgentConfig::default(), |
| 809 | ); |
| 810 | ed.register_tool(AgentToolDefinition::mutating( |
| 811 | "save_note", |
| 812 | "Save a note", |
| 813 | r#"{"type":"object"}"#, |
| 814 | )) |
| 815 | .await |
| 816 | .unwrap(); |
| 817 | let tools = ed.tools.read().await.clone(); |
| 818 | |
| 819 | let result = ed.execute_tool_call(&call("save_note"), &tools).await; |
| 820 | |
| 821 | assert!(result.is_error); |
| 822 | assert!(result.content.contains("denied")); |
| 823 | assert_eq!(executor.0.load(Ordering::Relaxed), 0); |
| 824 | } |
| 825 | |
| 826 | #[tokio::test] |
| 827 | async fn a_session_grant_applies_to_later_calls_of_the_same_tool() { |
| 828 | let executor = Arc::new(CountingExecutor(AtomicUsize::new(0))); |
| 829 | let ed = Ed::with_agent( |
| 830 | NoopSink, |
| 831 | executor.clone(), |
| 832 | Arc::new(FixedApproval(ApprovalDecision::AllowForSession)), |
| 833 | AgentConfig::default(), |
| 834 | ); |
| 835 | ed.register_tool(AgentToolDefinition::mutating( |
| 836 | "save_note", |
| 837 | "Save a note", |
| 838 | r#"{"type":"object"}"#, |
| 839 | )) |
| 840 | .await |
| 841 | .unwrap(); |
| 842 | let tools = ed.tools.read().await.clone(); |
| 843 | |
| 844 | ed.execute_tool_call(&call("save_note"), &tools).await; |
| 845 | ed.execute_tool_call(&call("save_note"), &tools).await; |
| 846 | |
| 847 | assert_eq!(executor.0.load(Ordering::Relaxed), 2); |
| 848 | assert!(ed.session_grants.lock().await.contains("save_note")); |
| 849 | } |
| 850 | |
| 851 | #[tokio::test] |
| 852 | async fn clearing_the_conversation_revokes_session_grants() { |
| 853 | // The grant was given for a conversation. Clearing the history ends |
| 854 | // that conversation, so the next one has to ask again. |
| 855 | let executor = Arc::new(CountingExecutor(AtomicUsize::new(0))); |
| 856 | let ed = Ed::with_agent( |
| 857 | NoopSink, |
| 858 | executor.clone(), |
| 859 | Arc::new(FixedApproval(ApprovalDecision::AllowForSession)), |
| 860 | AgentConfig::default(), |
| 861 | ); |
| 862 | ed.register_tool(AgentToolDefinition::mutating( |
| 863 | "save_note", |
| 864 | "Save a note", |
| 865 | r#"{"type":"object"}"#, |
| 866 | )) |
| 867 | .await |
| 868 | .unwrap(); |
| 869 | let tools = ed.tools.read().await.clone(); |
| 870 | ed.execute_tool_call(&call("save_note"), &tools).await; |
| 871 | assert!(ed.session_grants.lock().await.contains("save_note")); |
| 872 | |
| 873 | ed.clear_history().await; |
| 874 | |
| 875 | assert!(ed.session_grants.lock().await.is_empty()); |
| 876 | } |
| 877 | |
| 878 | #[tokio::test] |
| 879 | async fn unknown_tools_return_an_error_result_instead_of_executing() { |
| 880 | let executor = Arc::new(CountingExecutor(AtomicUsize::new(0))); |
| 881 | let ed = Ed::with_agent( |
| 882 | NoopSink, |
| 883 | executor.clone(), |
| 884 | Arc::new(FixedApproval(ApprovalDecision::AllowOnce)), |
| 885 | AgentConfig::default(), |
| 886 | ); |
| 887 | |
| 888 | let result = ed |
| 889 | .execute_tool_call(&call("missing"), &HashMap::new()) |
| 890 | .await; |
| 891 | |
| 892 | assert!(result.is_error); |
| 893 | assert!(result.content.contains("not registered")); |
| 894 | assert_eq!(executor.0.load(Ordering::Relaxed), 0); |
| 895 | } |
| 896 | |
| 897 | #[tokio::test] |
| 898 | async fn tool_arguments_must_be_a_json_object() { |
| 899 | let executor = Arc::new(CountingExecutor(AtomicUsize::new(0))); |
| 900 | let ed = Ed::with_agent( |
| 901 | NoopSink, |
| 902 | executor.clone(), |
| 903 | Arc::new(FixedApproval(ApprovalDecision::AllowOnce)), |
| 904 | AgentConfig::default(), |
| 905 | ); |
| 906 | ed.register_tool(AgentToolDefinition::read_only( |
| 907 | "clock", |
| 908 | "Read the clock", |
| 909 | r#"{"type":"object"}"#, |
| 910 | )) |
| 911 | .await |
| 912 | .unwrap(); |
| 913 | let tools = ed.tools.read().await.clone(); |
| 914 | let mut invalid = call("clock"); |
| 915 | invalid.arguments = "[]".to_owned(); |
| 916 | |
| 917 | let result = ed.execute_tool_call(&invalid, &tools).await; |
| 918 | |
| 919 | assert!(result.is_error); |
| 920 | assert!(result.content.contains("JSON object")); |
| 921 | assert_eq!(executor.0.load(Ordering::Relaxed), 0); |
| 922 | } |
| 923 | |
| 924 | #[tokio::test] |
| 925 | async fn restoring_history_revokes_session_grants() { |
| 926 | let ed = Ed::with_agent( |
| 927 | NoopSink, |
| 928 | Arc::new(CountingExecutor(AtomicUsize::new(0))), |
| 929 | Arc::new(FixedApproval(ApprovalDecision::AllowForSession)), |
| 930 | AgentConfig::default(), |
| 931 | ); |
| 932 | ed.register_tool(AgentToolDefinition::mutating( |
| 933 | "save_note", |
| 934 | "Save a note", |
| 935 | r#"{"type":"object"}"#, |
| 936 | )) |
| 937 | .await |
| 938 | .unwrap(); |
| 939 | let tools = ed.tools.read().await.clone(); |
| 940 | ed.execute_tool_call(&call("save_note"), &tools).await; |
| 941 | assert!(ed.session_grants.lock().await.contains("save_note")); |
| 942 | |
| 943 | ed.restore_history(Vec::new()).await; |
| 944 | |
| 945 | assert!(ed.session_grants.lock().await.is_empty()); |
| 946 | } |
| 947 | |
| 948 | #[tokio::test] |
| 949 | async fn generation_and_streaming_need_a_loaded_model() { |
| 950 | let ed = Ed::new(); |
| 951 | assert!(matches!( |
| 952 | ed.generate(vec![ChatMessage::user("hi")], None).await, |
| 953 | Err(InferenceError::NoModelLoaded) |
| 954 | )); |
| 955 | assert!(matches!( |
| 956 | ed.stream("hi").await, |
| 957 | Err(InferenceError::NoModelLoaded) |
| 958 | )); |
| 959 | } |
| 960 | } |