@ondeinference / ed Mirror · read-only
Fork 0

Read-only mirror of github.com/ondeinference/ed.

Mirrored from https://github.com/ondeinference/ed.git

Synced Nov 23, 01:00 UTC

development
rs 1,504 lines 56.7 KB
Raw
1 //! [`AcpServer`]: the ACP v1 agent behind every Onde product. Owns sessions (in memory, backed
2 //! by [`SessionStore`]), the turn loop, auth, and the model and auto-approve config options.
3 //! Everything product-specific comes from the [`Profile`].
4
5 use std::collections::{HashMap, HashSet};
6 use std::path::{Path, PathBuf};
7 use std::sync::atomic::{AtomicBool, Ordering};
8 use std::sync::{Arc, Mutex};
9 use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
11 use agent_client_protocol::schema::ProtocolVersion;
12 use agent_client_protocol::schema::v1::{
13 AuthMethod, AuthMethodTerminal, AuthenticateRequest, AuthenticateResponse,
14 AvailableCommandsUpdate, ClientCapabilities, CloseSessionRequest, CloseSessionResponse,
15 ConfigOptionUpdate, ContentBlock, ContentChunk, DeleteSessionRequest, DeleteSessionResponse,
16 ListSessionsRequest, ListSessionsResponse, LoadSessionRequest, LoadSessionResponse,
17 LogoutResponse, McpServer, MessageId, NewSessionRequest, NewSessionResponse, PromptRequest,
18 PromptResponse, RequestId, ResumeSessionRequest, ResumeSessionResponse, SessionConfigOption,
19 SessionConfigOptionCategory, SessionConfigSelectOption, SessionConfigSelectOptions, SessionId,
20 SessionInfo, SessionInfoUpdate, SessionNotification, SessionUpdate,
21 SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, StopReason, ToolCall,
22 ToolCallContent, ToolCallLocation, ToolCallStatus, ToolCallUpdateFields, UsageUpdate,
23 };
24 use agent_client_protocol::{Client, ConnectionTo, Responder};
25 use serde_json::{Value, json};
26 use tokio_util::sync::CancellationToken;
27
28 use ed_mcp::{ClientInfo, McpToolset, ToolsetConfig};
29
30 use crate::auth::{AuthCtx, AuthProvider};
31 use crate::content as prompt;
32 use crate::llm::{Delta, EndpointError, LlmClient, LlmConfig, LlmEnv};
33 use crate::store::{SessionStore, StoredSession};
34 use crate::tools::{self, ToolCtx, ToolOutcome, Toolset, absolutize, normalize};
35 use crate::{CommandCtx, Profile, PromptCtx, SessionCtx};
36
37 const MAX_TURNS: usize = 50;
38 /// Id of the session config option that selects the model.
39 pub const MODEL_CONFIG_ID: &str = "model";
40 /// Id of the boolean session config option that skips permission prompts.
41 pub const AUTO_APPROVE_CONFIG_ID: &str = "auto_approve";
42 /// Context window reported in `usage_update` when `<PREFIX>_CONTEXT_WINDOW` is unset.
43 const DEFAULT_CONTEXT_WINDOW: u64 = 128_000;
44 /// Id of the terminal auth method advertised on initialize.
45 pub const AUTH_METHOD_ID: &str = "terminal-setup";
46 /// Cap on the sessions returned by `session/list`.
47 const MAX_LISTED: usize = 200;
48 /// How long `run_command` may run when `<PREFIX>_COMMAND_TIMEOUT_SECS` is unset.
49 const DEFAULT_COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
50
51 /// The terminal auth method: clients run `<agent> --setup`.
52 pub fn auth_methods() -> Vec<AuthMethod> {
53 vec![AuthMethod::Terminal(
54 AuthMethodTerminal::new(AUTH_METHOD_ID, "Run in terminal")
55 .description("Interactive setup: choose a provider and store an API key")
56 .args(vec!["--setup".into()]),
57 )]
58 }
59
60 /// Whether the client can run terminal auth. ACP v1 has the `auth.terminal` capability; clients
61 /// that predate it (including the ACP registry's validator, which probes every listed agent)
62 /// say so with `_meta["terminal-auth"]: true` instead. Offering no method to such a client
63 /// fails registry validation, so either signal counts.
64 pub fn supports_terminal_auth(caps: &ClientCapabilities) -> bool {
65 caps.auth.terminal
66 || caps
67 .meta
68 .as_ref()
69 .and_then(|m| m.get("terminal-auth"))
70 .and_then(Value::as_bool)
71 .unwrap_or(false)
72 }
73
74 pub fn auth_required_error(agent: &str) -> agent_client_protocol::Error {
75 agent_client_protocol::Error::auth_required().data(format!(
76 "No API key configured. Authenticate with the terminal method (`{agent} --setup`)."
77 ))
78 }
79
80 /// The only protocol version this agent speaks is v1. A client proposing a newer version gets
81 /// v1 back (it can then decide whether to continue); an older (v0) client is told v1 too, as
82 /// the spec requires the latest supported version when the requested one isn't supported.
83 pub fn negotiate_version(client: ProtocolVersion) -> ProtocolVersion {
84 let _ = client;
85 ProtocolVersion::V1
86 }
87
88 struct Session {
89 cwd: PathBuf,
90 /// Additional workspace roots (from the request's `additional_directories`).
91 roots: Vec<PathBuf>,
92 model: String,
93 /// Conversation history without the system prompt (rebuilt every turn).
94 messages: Vec<Value>,
95 cancel: CancellationToken,
96 always_allowed: Arc<Mutex<HashSet<String>>>,
97 always_rejected: Arc<Mutex<HashSet<String>>>,
98 /// Approve tool calls without asking; the `auto_approve` config option. Not persisted:
99 /// a reopened session starts from the process default (`--yolo`).
100 auto_approve: Arc<AtomicBool>,
101 title: Option<String>,
102 /// Last activity, seconds since the Unix epoch.
103 updated_at: u64,
104 mcp: Arc<McpToolset>,
105 /// A turn is running; its history is checked out of `messages`.
106 busy: bool,
107 }
108
109 impl Session {
110 fn fresh(
111 cwd: PathBuf,
112 roots: Vec<PathBuf>,
113 model: String,
114 yolo: bool,
115 mcp: Arc<McpToolset>,
116 ) -> Self {
117 Self::restored(
118 StoredSession {
119 cwd,
120 roots,
121 model,
122 title: None,
123 updated_at: now_secs(),
124 messages: Vec::new(),
125 },
126 yolo,
127 mcp,
128 )
129 }
130
131 /// A session brought back from the store. Permission grants start fresh; MCP servers are
132 /// connected by the request that reopens it.
133 fn restored(stored: StoredSession, yolo: bool, mcp: Arc<McpToolset>) -> Self {
134 Self {
135 cwd: stored.cwd,
136 roots: stored.roots,
137 model: stored.model,
138 messages: stored.messages,
139 cancel: CancellationToken::new(),
140 always_allowed: Arc::default(),
141 always_rejected: Arc::default(),
142 auto_approve: Arc::new(AtomicBool::new(yolo)),
143 title: stored.title,
144 updated_at: stored.updated_at,
145 mcp,
146 busy: false,
147 }
148 }
149
150 fn stored(&self) -> StoredSession {
151 StoredSession {
152 cwd: self.cwd.clone(),
153 roots: self.roots.clone(),
154 model: self.model.clone(),
155 title: self.title.clone(),
156 updated_at: self.updated_at,
157 messages: self.messages.clone(),
158 }
159 }
160 }
161
162 fn new_message_id() -> MessageId {
163 MessageId::new(uuid::Uuid::new_v4().to_string())
164 }
165
166 /// ACP v1 requires absolute `cwd` and `additionalDirectories`.
167 fn check_absolute(cwd: &Path, roots: &[PathBuf]) -> agent_client_protocol::Result<()> {
168 if !cwd.is_absolute() {
169 return Err(invalid("cwd must be an absolute path"));
170 }
171 if roots.iter().any(|r| !r.is_absolute()) {
172 return Err(invalid(
173 "additionalDirectories entries must be absolute paths",
174 ));
175 }
176 Ok(())
177 }
178
179 pub fn now_secs() -> u64 {
180 SystemTime::now()
181 .duration_since(UNIX_EPOCH)
182 .map(|d| d.as_secs())
183 .unwrap_or(0)
184 }
185
186 /// ISO 8601 UTC timestamp without sub-second precision (no chrono dependency).
187 pub fn iso8601(secs: u64) -> String {
188 let days = secs / 86_400;
189 let secs_of_day = secs % 86_400;
190 let (h, m, s) = (
191 secs_of_day / 3600,
192 secs_of_day % 3600 / 60,
193 secs_of_day % 60,
194 );
195 // Civil-from-days algorithm (Howard Hinnant).
196 let z = days as i64 + 719_468;
197 let era = z.div_euclid(146_097);
198 let doe = z.rem_euclid(146_097);
199 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
200 let y = yoe + era * 400;
201 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
202 let mp = (5 * doy + 2) / 153;
203 let d = doy - (153 * mp + 2) / 5 + 1;
204 let mo = if mp < 10 { mp + 3 } else { mp - 9 };
205 let y = if mo <= 2 { y + 1 } else { y };
206 format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
207 }
208
209 /// Derive a short session title from the first user prompt.
210 pub fn session_title(prompt: &str) -> String {
211 const MAX: usize = 80;
212 let first = prompt.lines().next().unwrap_or("").trim();
213 if first.chars().count() <= MAX {
214 first.to_string()
215 } else {
216 let cut: String = first.chars().take(MAX - 1).collect();
217 format!("{}…", cut.trim_end())
218 }
219 }
220
221 /// Map a failed turn to an ACP internal error. Endpoint failures carry `{ message, status }`
222 /// so hosts can show the provider's message without parsing it out of a string.
223 fn internal(e: &anyhow::Error) -> agent_client_protocol::Error {
224 match e.chain().find_map(|c| c.downcast_ref::<EndpointError>()) {
225 Some(ep) => agent_client_protocol::Error::internal_error()
226 .data(json!({ "message": ep.message, "status": ep.status })),
227 None => agent_client_protocol::Error::internal_error().data(format!("{e:#}")),
228 }
229 }
230
231 fn invalid(msg: impl Into<String>) -> agent_client_protocol::Error {
232 agent_client_protocol::Error::invalid_params().data(msg.into())
233 }
234
235 fn unknown_session(id: &SessionId) -> agent_client_protocol::Error {
236 invalid(format!("unknown session {id}"))
237 }
238
239 /// A tool message; `failed` is kept in a private field that never reaches the model.
240 fn tool_message(id: &str, content: &str, failed: bool) -> Value {
241 let mut m = json!({ "role": "tool", "tool_call_id": id, "content": content });
242 if failed {
243 m["x_failed"] = json!(true);
244 }
245 m
246 }
247
248 fn wire_message(m: &Value) -> Value {
249 match m.as_object() {
250 Some(o) if o.contains_key("x_failed") => {
251 let mut o = o.clone();
252 o.remove("x_failed");
253 Value::Object(o)
254 }
255 _ => m.clone(),
256 }
257 }
258
259 fn locations_of(paths: &[PathBuf]) -> Vec<ToolCallLocation> {
260 paths
261 .iter()
262 .map(|p| ToolCallLocation::new(absolutize(p)))
263 .collect()
264 }
265
266 /// Text of a stored user message (`content` is a string, or an array of parts).
267 fn user_text(msg: &Value) -> String {
268 match msg.get("content") {
269 Some(Value::String(s)) => s.clone(),
270 Some(Value::Array(parts)) => parts
271 .iter()
272 .filter_map(|p| match p.get("type").and_then(Value::as_str) {
273 Some("text") => p.get("text").and_then(Value::as_str).map(String::from),
274 Some("image_url") => Some("[image]".into()),
275 _ => None,
276 })
277 .collect::<Vec<_>>()
278 .join("\n\n"),
279 _ => String::new(),
280 }
281 }
282
283 #[derive(Clone)]
284 pub struct AcpServer {
285 profile: Arc<dyn Profile>,
286 /// The profile's own sign-in, when it has one (see [`Profile::auth`]).
287 auth: Option<Arc<dyn AuthProvider>>,
288 /// The profile's toolsets, built once.
289 toolsets: Arc<Vec<Arc<dyn Toolset>>>,
290 env: LlmEnv,
291 /// Replaced when credentials change: `authenticate`, `logout`, or a key stored by
292 /// `--setup` in another process.
293 llm: Arc<Mutex<LlmClient>>,
294 /// Process default for each session's `auto_approve` (`--yolo` / `<PREFIX>_YOLO`).
295 yolo: bool,
296 /// How the agent was launched: `tui` (interactive terminal UI) or `acp` (editor).
297 surface: &'static str,
298 client_caps: Arc<Mutex<ClientCapabilities>>,
299 sessions: Arc<Mutex<HashMap<SessionId, Session>>>,
300 /// Models offered for selection, fetched from `GET /models` on first use and dropped
301 /// when credentials change or a thread opens.
302 models: Arc<tokio::sync::Mutex<Option<Vec<String>>>>,
303 store: SessionStore,
304 data_dir: PathBuf,
305 }
306
307 impl AcpServer {
308 pub fn new(profile: Arc<dyn Profile>, yolo: bool, surface: &'static str) -> Self {
309 let env = profile.info().env;
310 let data_dir = env.data_dir();
311 let auth = profile.auth();
312 Self {
313 toolsets: Arc::new(profile.toolsets()),
314 llm: Arc::new(Mutex::new(LlmClient::new(Self::config_for(
315 auth.as_deref(),
316 &env,
317 )))),
318 profile,
319 auth,
320 env,
321 yolo,
322 surface,
323 client_caps: Arc::default(),
324 sessions: Arc::default(),
325 models: Arc::default(),
326 store: SessionStore::new(&data_dir),
327 data_dir,
328 }
329 }
330
331 /// The provider's stored session when the profile has one, else the environment. A
332 /// signed-out provider yields the environment's endpoint with no key, so a stray
333 /// `ONDE_API_KEY` can't stand in for the product's own sign-in.
334 fn config_for(auth: Option<&dyn AuthProvider>, env: &LlmEnv) -> LlmConfig {
335 match auth {
336 None => LlmConfig::from_env(env),
337 Some(auth) => auth.llm_config().unwrap_or_else(|| LlmConfig {
338 api_key: None,
339 ..LlmConfig::from_env(env)
340 }),
341 }
342 }
343
344 /// The auth methods for `initialize`. A provider's method is offered whatever the client
345 /// can do; terminal auth only to a client that can run it.
346 pub fn auth_methods(&self, caps: &ClientCapabilities) -> Vec<AuthMethod> {
347 match &self.auth {
348 Some(auth) => vec![auth.method()],
349 None if supports_terminal_auth(caps) => auth_methods(),
350 None => Vec::new(),
351 }
352 }
353
354 pub fn set_client_caps(&self, caps: ClientCapabilities) {
355 *self.client_caps.lock().unwrap() = caps;
356 }
357
358 fn llm(&self) -> LlmClient {
359 self.llm.lock().unwrap().clone()
360 }
361
362 pub fn has_api_key(&self) -> bool {
363 self.llm().has_api_key()
364 }
365
366 pub fn model(&self) -> String {
367 self.llm().model().to_string()
368 }
369
370 /// Re-read credentials (environment + stored `env` file) and report whether a key is
371 /// configured. Editors run terminal auth (`<agent> --setup`) in a separate process
372 /// and then retry `session/new` or `session/load` on this one without calling
373 /// `authenticate`, so the stored key has to be picked up here. The model list is only
374 /// dropped when the configuration actually changed.
375 pub async fn refresh_credentials(&self) -> bool {
376 let fresh = Self::config_for(self.auth.as_deref(), &self.env);
377 let changed = fresh != *self.llm().config();
378 if changed {
379 tracing::info!(
380 "credentials changed; reloading provider {}",
381 fresh.provider.name()
382 );
383 *self.llm.lock().unwrap() = LlmClient::new(fresh);
384 *self.models.lock().await = None;
385 }
386 self.has_api_key()
387 }
388
389 /// `authenticate`: the client has run `<agent> --setup`; pick up the stored key.
390 pub async fn authenticate(
391 &self,
392 req: AuthenticateRequest,
393 connection: &ConnectionTo<Client>,
394 request_id: RequestId,
395 ) -> agent_client_protocol::Result<AuthenticateResponse> {
396 if let Some(auth) = &self.auth {
397 if req.method_id != *auth.method().id() {
398 return Err(invalid(format!("unknown auth method {}", req.method_id.0)));
399 }
400 let caps = self.client_caps.lock().unwrap().clone();
401 auth.authenticate(AuthCtx {
402 connection,
403 request_id,
404 client_caps: &caps,
405 })
406 .await?;
407 // A new session means a new bearer, and possibly a different model list.
408 *self.models.lock().await = None;
409 *self.llm.lock().unwrap() =
410 LlmClient::new(Self::config_for(self.auth.as_deref(), &self.env));
411 return if self.has_api_key() {
412 Ok(AuthenticateResponse::new())
413 } else {
414 Err(self.auth_required())
415 };
416 }
417 if &*req.method_id.0 != AUTH_METHOD_ID {
418 return Err(invalid(format!("unknown auth method {}", req.method_id.0)));
419 }
420 if self.refresh_credentials().await {
421 Ok(AuthenticateResponse::new())
422 } else {
423 Err(self.auth_required())
424 }
425 }
426
427 /// `logout`: remove the stored key and forget it. Every file the key may be loaded from
428 /// goes, or the agent would still be signed in afterwards; one failed removal doesn't stop
429 /// the others. A key exported in the agent's own environment can't be removed from here
430 /// and keeps the agent signed in.
431 pub async fn logout(&self) -> agent_client_protocol::Result<LogoutResponse> {
432 if let Some(auth) = &self.auth {
433 return match auth.logout().await {
434 Ok(()) => {
435 *self.models.lock().await = None;
436 *self.llm.lock().unwrap() =
437 LlmClient::new(Self::config_for(self.auth.as_deref(), &self.env));
438 Ok(LogoutResponse::new())
439 }
440 Err(e) => {
441 Err(agent_client_protocol::Error::internal_error().data(format!("{e:#}")))
442 }
443 };
444 }
445 let failures: Vec<String> = self
446 .env
447 .config_file_candidates()
448 .into_iter()
449 .filter_map(|path| match std::fs::remove_file(&path) {
450 Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
451 Some(format!("removing {}: {e}", path.display()))
452 }
453 _ => None,
454 })
455 .collect();
456 self.refresh_credentials().await;
457 if !failures.is_empty() {
458 return Err(agent_client_protocol::Error::internal_error().data(failures.join("; ")));
459 }
460 Ok(LogoutResponse::new())
461 }
462
463 fn scratch_dir(&self, id: &SessionId) -> Option<PathBuf> {
464 let id = crate::store::sanitize_id(&id.0).ok()?;
465 Some(self.data_dir.join("scratch").join(id))
466 }
467
468 fn remove_scratch(&self, id: &SessionId) {
469 if let Some(dir) = self.scratch_dir(id) {
470 let _ = std::fs::remove_dir_all(dir);
471 }
472 }
473
474 /// `AUTH_REQUIRED`, naming this agent's setup command.
475 pub fn auth_required(&self) -> agent_client_protocol::Error {
476 if let Some(auth) = &self.auth {
477 return agent_client_protocol::Error::auth_required().data(format!(
478 "Not signed in. Authenticate with the {} method.",
479 auth.method().name()
480 ));
481 }
482 auth_required_error(self.profile.info().name)
483 }
484
485 /// How a session's MCP servers are connected.
486 fn mcp_config(&self) -> ToolsetConfig {
487 let info = self.profile.info();
488 ToolsetConfig::new(ClientInfo::new(info.name, info.version))
489 }
490
491 async fn connect_mcp(
492 &self,
493 servers: &[agent_client_protocol::schema::v1::McpServer],
494 ) -> Arc<McpToolset> {
495 Arc::new(
496 McpToolset::connect(
497 self.mcp_config(),
498 servers,
499 &self.profile.builtin_mcp_servers(),
500 )
501 .await,
502 )
503 }
504
505 fn system_prompt(&self, cwd: &Path, roots: &[PathBuf], mcp: &McpToolset) -> String {
506 self.profile.system_prompt(&PromptCtx {
507 surface: self.surface,
508 cwd,
509 roots,
510 mcp,
511 })
512 }
513
514 /// Forget the cached model list, so the next `models()` asks the endpoint again. Called when a
515 /// thread opens: an endpoint scoped to an app can change what it lists between threads.
516 async fn forget_models(&self) {
517 *self.models.lock().await = None;
518 }
519
520 /// The selectable models. Falls back to just the configured model if the endpoint
521 /// can't list them; the configured model is always offered.
522 async fn models(&self) -> Vec<String> {
523 let mut cache = self.models.lock().await;
524 if let Some(ids) = &*cache {
525 return ids.clone();
526 }
527 let llm = self.llm();
528 let default = llm.model().to_string();
529 // An explicit list wins; editors show this list as the model picker.
530 let configured: Vec<String> = match self.auth.as_ref().and_then(|a| a.models()) {
531 Some(models) => models,
532 None => std::env::var(self.env.var("MODELS"))
533 .unwrap_or_default()
534 .split(',')
535 .map(|m| m.trim().to_string())
536 .filter(|m| !m.is_empty())
537 .collect(),
538 };
539 let mut ids = if !configured.is_empty() {
540 configured
541 } else {
542 match llm.models().await {
543 Ok(models) => models.into_iter().map(|m| m.id).collect(),
544 Err(e) => {
545 tracing::warn!("listing models failed, offering only {default}: {e:#}");
546 Vec::new()
547 }
548 }
549 };
550 if !ids.contains(&default) {
551 ids.insert(0, default);
552 }
553 *cache = Some(ids.clone());
554 ids
555 }
556
557 /// Whether the client advertised `session.configOptions.boolean`, which ACP requires
558 /// before an agent may offer `type: "boolean"` options.
559 fn boolean_options_supported(&self) -> bool {
560 self.client_caps
561 .lock()
562 .unwrap()
563 .session
564 .as_ref()
565 .and_then(|s| s.config_options.as_ref())
566 .is_some_and(|c| c.boolean.is_some())
567 }
568
569 async fn config_options(&self, model: &str, auto_approve: bool) -> Vec<SessionConfigOption> {
570 let options = self
571 .models()
572 .await
573 .into_iter()
574 .map(|id| SessionConfigSelectOption::new(id.clone(), id))
575 .collect();
576 let mut config = vec![
577 SessionConfigOption::select(
578 MODEL_CONFIG_ID,
579 "Model",
580 model.to_string(),
581 SessionConfigSelectOptions::Ungrouped(options),
582 )
583 .category(SessionConfigOptionCategory::Model),
584 ];
585 if self.boolean_options_supported() {
586 config.push(
587 SessionConfigOption::boolean(
588 AUTO_APPROVE_CONFIG_ID,
589 "Auto-approve actions",
590 auto_approve,
591 )
592 .description("Run tools that change things without asking for permission"),
593 );
594 }
595 config
596 }
597
598 /// The model and auto-approve setting of a live session.
599 fn session_settings(&self, id: &SessionId) -> Option<(String, bool)> {
600 self.sessions
601 .lock()
602 .unwrap()
603 .get(id)
604 .map(|s| (s.model.clone(), s.auto_approve.load(Ordering::Relaxed)))
605 }
606
607 async fn session_config_options(
608 &self,
609 id: &SessionId,
610 ) -> agent_client_protocol::Result<Vec<SessionConfigOption>> {
611 let (model, auto_approve) = self
612 .session_settings(id)
613 .ok_or_else(|| unknown_session(id))?;
614 Ok(self.config_options(&model, auto_approve).await)
615 }
616
617 pub async fn set_config_option(
618 &self,
619 req: SetSessionConfigOptionRequest,
620 connection: &ConnectionTo<Client>,
621 ) -> agent_client_protocol::Result<SetSessionConfigOptionResponse> {
622 let id = req.session_id.clone();
623 self.restore(&id).await?;
624 match &*req.config_id.0 {
625 MODEL_CONFIG_ID => {
626 let Some(model) = req.value.as_value_id().map(|v| v.0.to_string()) else {
627 return Err(invalid("model must be a value id"));
628 };
629 if !self.models().await.contains(&model) {
630 return Err(invalid(format!("unknown model {model}")));
631 }
632 match self.sessions.lock().unwrap().get_mut(&id) {
633 Some(s) => s.model = model.clone(),
634 None => return Err(unknown_session(&id)),
635 }
636 self.persist(&id).await;
637 tracing::info!("session {id} now uses model {model}");
638 }
639 AUTO_APPROVE_CONFIG_ID if self.boolean_options_supported() => {
640 let Some(on) = req.value.as_bool() else {
641 return Err(invalid("auto_approve must be a boolean"));
642 };
643 match self.sessions.lock().unwrap().get(&id) {
644 Some(s) => s.auto_approve.store(on, Ordering::Relaxed),
645 None => return Err(unknown_session(&id)),
646 }
647 tracing::info!("session {id} auto-approve {on}");
648 }
649 other => return Err(invalid(format!("unknown config option {other}"))),
650 }
651 let options = self.session_config_options(&id).await?;
652 // Tell every view of the session about the change, not just the requester.
653 connection.send_notification(SessionNotification::new(
654 id,
655 SessionUpdate::ConfigOptionUpdate(ConfigOptionUpdate::new(options.clone())),
656 ))?;
657 Ok(SetSessionConfigOptionResponse::new(options))
658 }
659
660 /// Save a session that is not running a turn (a turn checks the history out; the
661 /// end-of-turn save covers it).
662 async fn persist(&self, id: &SessionId) {
663 let stored = self
664 .sessions
665 .lock()
666 .unwrap()
667 .get(id)
668 .filter(|s| !s.busy)
669 .map(Session::stored);
670 let Some(stored) = stored else { return };
671 let store = self.store.clone();
672 let sid = id.0.to_string();
673 match tokio::task::spawn_blocking(move || store.save(&sid, &stored)).await {
674 Ok(Ok(())) => {}
675 Ok(Err(e)) => tracing::warn!("saving session {id} failed: {e:#}"),
676 Err(e) => tracing::warn!("saving session {id} failed: {e}"),
677 }
678 }
679
680 /// Bring a stored session into memory without rebinding it (a prompt or config change
681 /// for a thread the client reopened without `session/load`). Errors if it is unknown.
682 async fn restore(&self, id: &SessionId) -> agent_client_protocol::Result<()> {
683 if self.sessions.lock().unwrap().contains_key(id) {
684 return Ok(());
685 }
686 let stored = self
687 .load_stored(id)
688 .await?
689 .ok_or_else(|| unknown_session(id))?;
690 tracing::info!("restored session {id} from disk");
691 self.sessions
692 .lock()
693 .unwrap()
694 .entry(id.clone())
695 .or_insert_with(|| Session::restored(stored, self.yolo, self.no_mcp()));
696 Ok(())
697 }
698
699 async fn load_stored(
700 &self,
701 id: &SessionId,
702 ) -> agent_client_protocol::Result<Option<StoredSession>> {
703 let store = self.store.clone();
704 let sid = id.0.to_string();
705 tokio::task::spawn_blocking(move || store.load(&sid))
706 .await
707 .map_err(|e| agent_client_protocol::Error::internal_error().data(e.to_string()))?
708 .map_err(|e| agent_client_protocol::Error::internal_error().data(format!("{e:#}")))
709 }
710
711 /// A session placeholder until its MCP servers are connected.
712 fn no_mcp(&self) -> Arc<McpToolset> {
713 Arc::new(McpToolset::empty(self.mcp_config()))
714 }
715
716 fn session_mcp(&self, id: &SessionId) -> Arc<McpToolset> {
717 self.sessions
718 .lock()
719 .unwrap()
720 .get(id)
721 .map(|s| s.mcp.clone())
722 .unwrap_or_else(|| self.no_mcp())
723 }
724
725 /// `AvailableCommandsUpdate` for a session, sent after the response that created it.
726 pub fn send_commands(
727 &self,
728 connection: &ConnectionTo<Client>,
729 id: &SessionId,
730 ) -> agent_client_protocol::Result<()> {
731 let mcp = self.session_mcp(id);
732 let commands = self.profile.slash_commands(&SessionCtx { mcp: &mcp });
733 connection.send_notification(SessionNotification::new(
734 id.clone(),
735 SessionUpdate::AvailableCommandsUpdate(AvailableCommandsUpdate::new(commands)),
736 ))
737 }
738
739 pub async fn new_session(
740 &self,
741 req: NewSessionRequest,
742 ) -> agent_client_protocol::Result<NewSessionResponse> {
743 check_absolute(&req.cwd, &req.additional_directories)?;
744 // Lexical normalization only: the client sees `cwd` again in `session/list`, so
745 // symlinks in it are not rewritten.
746 let cwd = normalize(&req.cwd);
747 let roots: Vec<PathBuf> = req
748 .additional_directories
749 .iter()
750 .map(|r| normalize(r))
751 .collect();
752 let id = SessionId::new(uuid::Uuid::new_v4().to_string());
753 let model = self.model();
754 let mcp = self.connect_mcp(&req.mcp_servers).await;
755 let session = Session::fresh(cwd, roots, model.clone(), self.yolo, mcp);
756 self.sessions.lock().unwrap().insert(id.clone(), session);
757 // Saved right away so the thread survives a restart before its first prompt.
758 self.persist(&id).await;
759 self.forget_models().await;
760 let options = self.config_options(&model, self.yolo).await;
761 Ok(NewSessionResponse::new(id).config_options(options))
762 }
763
764 /// Live and stored sessions, optionally filtered by working directory, newest first.
765 pub fn list_sessions(
766 &self,
767 req: ListSessionsRequest,
768 ) -> agent_client_protocol::Result<ListSessionsResponse> {
769 // Every session fits on one page, so no cursor is ever handed out; any cursor is stale.
770 if let Some(cursor) = &req.cursor {
771 return Err(invalid(format!("invalid cursor {cursor}")));
772 }
773 struct Row {
774 id: SessionId,
775 cwd: PathBuf,
776 roots: Vec<PathBuf>,
777 title: Option<String>,
778 updated_at: u64,
779 }
780 let mut rows: HashMap<String, Row> = self
781 .store
782 .list()
783 .into_iter()
784 .map(|(id, s)| {
785 (
786 id.clone(),
787 Row {
788 id: SessionId::new(id),
789 cwd: s.cwd,
790 roots: s.roots,
791 title: s.title,
792 updated_at: s.updated_at,
793 },
794 )
795 })
796 .collect();
797 // Live state wins over the (possibly older) stored copy.
798 for (id, s) in self.sessions.lock().unwrap().iter() {
799 rows.insert(
800 id.0.to_string(),
801 Row {
802 id: id.clone(),
803 cwd: s.cwd.clone(),
804 roots: s.roots.clone(),
805 title: s.title.clone(),
806 updated_at: s.updated_at,
807 },
808 );
809 }
810 // Stored cwds are normalized, so normalize the filter the same way.
811 let wanted = req.cwd.as_deref().map(normalize);
812 let mut rows: Vec<Row> = rows
813 .into_values()
814 .filter(|r| wanted.as_ref().is_none_or(|cwd| *cwd == normalize(&r.cwd)))
815 .collect();
816 rows.sort_by(|a, b| {
817 b.updated_at
818 .cmp(&a.updated_at)
819 .then_with(|| a.id.0.cmp(&b.id.0))
820 });
821 rows.truncate(MAX_LISTED);
822 Ok(ListSessionsResponse::new(
823 rows.into_iter()
824 .map(|r| {
825 SessionInfo::new(r.id, r.cwd)
826 .additional_directories(r.roots)
827 .title(r.title)
828 .updated_at(iso8601(r.updated_at))
829 })
830 .collect(),
831 ))
832 }
833
834 pub fn cancel(&self, session_id: &SessionId) {
835 if let Some(s) = self.sessions.lock().unwrap().get(session_id) {
836 s.cancel.cancel();
837 }
838 }
839
840 /// Make `id` live for `session/load` and `session/resume`: from memory, else from the
841 /// store; rebind cwd and roots, and reconnect MCP servers from the request. A well-formed
842 /// id with no saved history (a thread from a process that never saved it) reopens empty
843 /// under the same id, so the editor's thread opens instead of failing to launch. Returns
844 /// whether the history was lost.
845 async fn reopen(
846 &self,
847 id: &SessionId,
848 cwd: &Path,
849 roots: &[PathBuf],
850 mcp_servers: &[McpServer],
851 ) -> agent_client_protocol::Result<bool> {
852 check_absolute(cwd, roots)?;
853 if crate::store::sanitize_id(&id.0).is_err() {
854 return Err(unknown_session(id));
855 }
856 let live = self.sessions.lock().unwrap().contains_key(id);
857 let stored = if live {
858 None
859 } else {
860 self.load_stored(id).await?
861 };
862 let history_lost = !live && stored.is_none();
863 let cwd = normalize(cwd);
864 let roots: Vec<PathBuf> = roots.iter().map(|r| normalize(r)).collect();
865 let mcp = self.connect_mcp(mcp_servers).await;
866
867 let old_mcp = {
868 let mut sessions = self.sessions.lock().unwrap();
869 if !sessions.contains_key(id) {
870 let session = match stored {
871 Some(stored) => Session::restored(stored, self.yolo, self.no_mcp()),
872 None => {
873 tracing::warn!("session {id} has no saved history; reopening it empty");
874 Session::fresh(
875 cwd.clone(),
876 roots.clone(),
877 self.model(),
878 self.yolo,
879 self.no_mcp(),
880 )
881 }
882 };
883 sessions.insert(id.clone(), session);
884 }
885 let s = sessions.get_mut(id).ok_or_else(|| unknown_session(id))?;
886 s.cwd = cwd;
887 if !roots.is_empty() {
888 s.roots = roots;
889 }
890 s.updated_at = now_secs();
891 std::mem::replace(&mut s.mcp, mcp)
892 };
893 if let Some(old) = Arc::into_inner(old_mcp) {
894 tokio::spawn(old.shutdown());
895 }
896 self.persist(id).await;
897 Ok(history_lost)
898 }
899
900 /// Tell the user a reopened thread starts without its earlier history. Shown in the
901 /// thread only; the model doesn't see it.
902 fn notify_history_lost(
903 &self,
904 connection: &ConnectionTo<Client>,
905 id: &SessionId,
906 ) -> agent_client_protocol::Result<()> {
907 connection.send_notification(SessionNotification::new(
908 id.clone(),
909 SessionUpdate::AgentMessageChunk(
910 ContentChunk::new(
911 format!(
912 "{} no longer has this conversation's history, so it starts fresh \
913 from here.",
914 self.profile.info().display_name
915 )
916 .into(),
917 )
918 .message_id(new_message_id()),
919 ),
920 ))
921 }
922
923 /// Replay a session's conversation as `session/update` notifications (text, tool calls
924 /// with their status and output), then respond with config options. `session/load`.
925 pub async fn load_session(
926 &self,
927 req: LoadSessionRequest,
928 connection: &ConnectionTo<Client>,
929 ) -> agent_client_protocol::Result<LoadSessionResponse> {
930 let id = req.session_id.clone();
931 let history_lost = self
932 .reopen(&id, &req.cwd, &req.additional_directories, &req.mcp_servers)
933 .await?;
934 let (messages, cwd, roots) = {
935 let sessions = self.sessions.lock().unwrap();
936 let s = sessions.get(&id).ok_or_else(|| unknown_session(&id))?;
937 (s.messages.clone(), s.cwd.clone(), s.roots.clone())
938 };
939 let notify = |update: SessionUpdate| {
940 connection.send_notification(SessionNotification::new(id.clone(), update))
941 };
942 // Tool output by call id, from the stored `tool` messages.
943 let results: HashMap<&str, (&str, bool)> = messages
944 .iter()
945 .filter(|m| m.get("role").and_then(Value::as_str) == Some("tool"))
946 .filter_map(|m| {
947 Some((
948 m.get("tool_call_id")?.as_str()?,
949 (
950 m.get("content").and_then(Value::as_str).unwrap_or(""),
951 m.get("x_failed").and_then(Value::as_bool).unwrap_or(false),
952 ),
953 ))
954 })
955 .collect();
956 for msg in &messages {
957 match msg.get("role").and_then(Value::as_str).unwrap_or("") {
958 "user" => {
959 let text = user_text(msg);
960 if !text.is_empty() {
961 notify(SessionUpdate::UserMessageChunk(
962 ContentChunk::new(text.into()).message_id(new_message_id()),
963 ))?;
964 }
965 }
966 "assistant" => {
967 let text = msg.get("content").and_then(Value::as_str).unwrap_or("");
968 if !text.is_empty() {
969 notify(SessionUpdate::AgentMessageChunk(
970 ContentChunk::new(text.to_string().into()).message_id(new_message_id()),
971 ))?;
972 }
973 let calls = msg.get("tool_calls").and_then(Value::as_array);
974 for tc in calls.into_iter().flatten() {
975 let call_id = tc.get("id").and_then(Value::as_str).unwrap_or("unknown");
976 let name = tc
977 .pointer("/function/name")
978 .and_then(Value::as_str)
979 .unwrap_or("unknown");
980 let args: Value = tc
981 .pointer("/function/arguments")
982 .and_then(Value::as_str)
983 .and_then(|a| serde_json::from_str(a).ok())
984 .unwrap_or_else(|| json!({}));
985 let (title, kind, locations) =
986 tools::describe(&self.toolsets, &cwd, &roots, name, &args);
987 let mut call = ToolCall::new(call_id.to_string(), title)
988 .name(name.to_string())
989 .kind(kind)
990 .locations(locations)
991 .raw_input(args);
992 match results.get(call_id) {
993 Some((output, failed)) => {
994 call = call
995 .status(if *failed {
996 ToolCallStatus::Failed
997 } else {
998 ToolCallStatus::Completed
999 })
1000 .content(vec![ToolCallContent::from(output.to_string())])
1001 .raw_output(json!({ "output": output, "failed": failed }));
1002 }
1003 // The turn was interrupted before this call produced a result.
1004 None => call = call.status(ToolCallStatus::Failed),
1005 }
1006 notify(SessionUpdate::ToolCall(call))?;
1007 }
1008 }
1009 // system and tool messages are not replayed on their own.
1010 _ => {}
1011 }
1012 }
1013 if history_lost {
1014 self.notify_history_lost(connection, &id)?;
1015 }
1016 self.forget_models().await;
1017 Ok(LoadSessionResponse::new().config_options(self.session_config_options(&id).await?))
1018 }
1019
1020 /// Rebind a session to a new cwd / additional directories without replaying it.
1021 pub async fn resume_session(
1022 &self,
1023 req: ResumeSessionRequest,
1024 connection: &ConnectionTo<Client>,
1025 ) -> agent_client_protocol::Result<ResumeSessionResponse> {
1026 let id = req.session_id.clone();
1027 let history_lost = self
1028 .reopen(&id, &req.cwd, &req.additional_directories, &req.mcp_servers)
1029 .await?;
1030 if history_lost {
1031 self.notify_history_lost(connection, &id)?;
1032 }
1033 self.forget_models().await;
1034 Ok(ResumeSessionResponse::new().config_options(self.session_config_options(&id).await?))
1035 }
1036
1037 /// Cancel any in-progress work, release MCP servers and scratch audio. The stored
1038 /// conversation stays; `session/delete` removes it.
1039 pub fn close_session(
1040 &self,
1041 req: CloseSessionRequest,
1042 ) -> agent_client_protocol::Result<CloseSessionResponse> {
1043 let id = req.session_id.clone();
1044 let removed = self.sessions.lock().unwrap().remove(&id);
1045 match removed {
1046 Some(s) => self.release(&id, s),
1047 // A session from an earlier process that was never reopened has nothing to close.
1048 None if self.store.load(&id.0).ok().flatten().is_some() => {}
1049 None => return Err(unknown_session(&id)),
1050 }
1051 Ok(CloseSessionResponse::new())
1052 }
1053
1054 /// Forget a session, in memory and on disk, with its scratch audio. Idempotent: deleting
1055 /// an unknown session succeeds.
1056 pub fn delete_session(
1057 &self,
1058 req: DeleteSessionRequest,
1059 ) -> agent_client_protocol::Result<DeleteSessionResponse> {
1060 let id = req.session_id.clone();
1061 if let Some(s) = self.sessions.lock().unwrap().remove(&id) {
1062 self.release(&id, s);
1063 }
1064 // A malformed id can't name a stored session; nothing to remove.
1065 if crate::store::sanitize_id(&id.0).is_ok() {
1066 self.store.delete(&id.0).map_err(|e| {
1067 agent_client_protocol::Error::internal_error().data(format!("{e:#}"))
1068 })?;
1069 }
1070 self.remove_scratch(&id);
1071 Ok(DeleteSessionResponse::new())
1072 }
1073
1074 fn release(&self, id: &SessionId, s: Session) {
1075 s.cancel.cancel();
1076 self.remove_scratch(id);
1077 if let Some(mcp) = Arc::into_inner(s.mcp) {
1078 tokio::spawn(mcp.shutdown());
1079 }
1080 }
1081
1082 /// Stop everything: used when the connection ends.
1083 pub async fn shutdown(&self) {
1084 let sessions: Vec<Session> = self
1085 .sessions
1086 .lock()
1087 .unwrap()
1088 .drain()
1089 .map(|(_, s)| s)
1090 .collect();
1091 for s in sessions {
1092 s.cancel.cancel();
1093 if let Some(mcp) = Arc::into_inner(s.mcp) {
1094 mcp.shutdown().await;
1095 }
1096 }
1097 for server in self.profile.builtin_mcp_servers() {
1098 server.shutdown().await;
1099 }
1100 }
1101
1102 pub async fn prompt(
1103 &self,
1104 request: PromptRequest,
1105 responder: Responder<PromptResponse>,
1106 connection: ConnectionTo<Client>,
1107 ) -> agent_client_protocol::Result<()> {
1108 // A client may prompt a reopened thread without loading or resuming it first.
1109 if let Err(e) = self.restore(&request.session_id).await {
1110 return responder.respond_with_error(e);
1111 }
1112 if let Some(reply) = self.answer_slash(&request).await {
1113 connection.send_notification(SessionNotification::new(
1114 request.session_id.clone(),
1115 SessionUpdate::AgentMessageChunk(
1116 ContentChunk::new(reply.into()).message_id(new_message_id()),
1117 ),
1118 ))?;
1119 return responder.respond(PromptResponse::new(StopReason::EndTurn));
1120 }
1121 match self.run_turn(request, connection).await {
1122 Ok(stop) => responder.respond(PromptResponse::new(stop)),
1123 Err(e) if e.downcast_ref::<UnknownSession>().is_some() => {
1124 responder.respond_with_error(invalid(e.to_string()))
1125 }
1126 Err(e) => responder.respond_with_error(internal(&e)),
1127 }
1128 }
1129
1130 /// The profile's reply to a slash command it answers without the model, for a prompt that
1131 /// is a single text block. The reply is not added to the conversation.
1132 async fn answer_slash(&self, request: &PromptRequest) -> Option<String> {
1133 let [ContentBlock::Text(text)] = request.prompt.as_slice() else {
1134 return None;
1135 };
1136 if !text.text.trim_start().starts_with('/') {
1137 return None;
1138 }
1139 let (model, _) = self.session_settings(&request.session_id)?;
1140 let models = self.models().await;
1141 let mcp = self.session_mcp(&request.session_id);
1142 self.profile.answer_slash(
1143 &text.text,
1144 &CommandCtx {
1145 mcp: &mcp,
1146 model: &model,
1147 models: &models,
1148 },
1149 )
1150 }
1151
1152 async fn run_turn(
1153 &self,
1154 request: PromptRequest,
1155 connection: ConnectionTo<Client>,
1156 ) -> anyhow::Result<StopReason> {
1157 let session_id = request.session_id.clone();
1158 let caps = self.client_caps.lock().unwrap().clone();
1159 let blocks =
1160 prompt::resolve_resource_links(&request.prompt, &caps, &connection, &session_id).await;
1161 let prompt_text = prompt::prompt_to_text(&blocks, &self.profile.audio_hints());
1162 // Check the session out for the turn.
1163 let (
1164 cwd,
1165 roots,
1166 model,
1167 history,
1168 cancel,
1169 always_allowed,
1170 always_rejected,
1171 auto_approve,
1172 mcp,
1173 new_title,
1174 ) = {
1175 let mut sessions = self.sessions.lock().unwrap();
1176 let s = sessions
1177 .get_mut(&session_id)
1178 .ok_or_else(|| UnknownSession(session_id.to_string()))?;
1179 if s.busy {
1180 anyhow::bail!("a prompt is already running for session {session_id}");
1181 }
1182 s.busy = true;
1183 s.cancel = CancellationToken::new();
1184 s.updated_at = now_secs();
1185 let new_title = if s.title.is_none() && !prompt_text.trim().is_empty() {
1186 s.title = Some(session_title(&prompt_text));
1187 s.title.clone()
1188 } else {
1189 None
1190 };
1191 (
1192 s.cwd.clone(),
1193 s.roots.clone(),
1194 s.model.clone(),
1195 std::mem::take(&mut s.messages),
1196 s.cancel.clone(),
1197 s.always_allowed.clone(),
1198 s.always_rejected.clone(),
1199 s.auto_approve.clone(),
1200 s.mcp.clone(),
1201 new_title,
1202 )
1203 };
1204 if let Some(title) = new_title {
1205 let update = SessionInfoUpdate::new()
1206 .title(title)
1207 .updated_at(iso8601(now_secs()));
1208 let _ = connection.send_notification(SessionNotification::new(
1209 session_id.clone(),
1210 SessionUpdate::SessionInfoUpdate(update),
1211 ));
1212 }
1213
1214 let mut messages = vec![json!({
1215 "role": "system",
1216 "content": self.system_prompt(&cwd, &roots, &mcp),
1217 })];
1218 messages.extend(history);
1219
1220 let ctx = ToolCtx {
1221 connection: connection.clone(),
1222 session_id: session_id.clone(),
1223 cwd,
1224 roots,
1225 caps,
1226 cancel,
1227 auto_approve,
1228 always_allowed,
1229 always_rejected,
1230 mcp,
1231 command_timeout: std::env::var(self.env.var("COMMAND_TIMEOUT_SECS"))
1232 .ok()
1233 .and_then(|v| v.parse().ok())
1234 .map(Duration::from_secs)
1235 .unwrap_or(DEFAULT_COMMAND_TIMEOUT),
1236 };
1237 let result = self.turn(&ctx, &model, &mut messages, &blocks).await;
1238
1239 // Check the history back in, even when the turn failed.
1240 let history = messages.split_off(1);
1241 let stored = {
1242 let mut sessions = self.sessions.lock().unwrap();
1243 sessions.get_mut(&session_id).map(|s| {
1244 s.messages = history;
1245 s.busy = false;
1246 s.updated_at = now_secs();
1247 s.stored()
1248 })
1249 };
1250 if let Some(stored) = stored {
1251 let updated_at = stored.updated_at;
1252 let store = self.store.clone();
1253 let id = session_id.0.to_string();
1254 let saved = tokio::task::spawn_blocking(move || store.save(&id, &stored)).await;
1255 if let Ok(Err(e)) | Err(e) = saved.map_err(anyhow::Error::from) {
1256 tracing::warn!("saving session {session_id} failed: {e:#}");
1257 }
1258 let _ = connection.send_notification(SessionNotification::new(
1259 session_id.clone(),
1260 SessionUpdate::SessionInfoUpdate(
1261 SessionInfoUpdate::new().updated_at(iso8601(updated_at)),
1262 ),
1263 ));
1264 }
1265 result
1266 }
1267
1268 /// Everything inside a turn after the session is checked out.
1269 async fn turn(
1270 &self,
1271 ctx: &ToolCtx,
1272 model: &str,
1273 messages: &mut Vec<Value>,
1274 blocks: &[ContentBlock],
1275 ) -> anyhow::Result<StopReason> {
1276 let audio_paths = match self.scratch_dir(&ctx.session_id) {
1277 Some(dir) => prompt::save_audio_blocks(blocks, &dir).await?,
1278 None => Vec::new(),
1279 };
1280 let hints = self.profile.audio_hints();
1281 let slash = self.profile.expand_slash(
1282 &prompt::prompt_to_text(blocks, &hints),
1283 &SessionCtx { mcp: &ctx.mcp },
1284 );
1285 let content = prompt::prompt_to_content(blocks, &audio_paths, slash.as_deref(), &hints);
1286 messages.push(json!({ "role": "user", "content": content }));
1287 self.agent_loop(ctx, model, messages).await
1288 }
1289
1290 async fn agent_loop(
1291 &self,
1292 ctx: &ToolCtx,
1293 model: &str,
1294 messages: &mut Vec<Value>,
1295 ) -> anyhow::Result<StopReason> {
1296 let llm = self.llm();
1297 let tool_defs = tools::definitions(&self.toolsets, &ctx.mcp);
1298 let notify = |update: SessionUpdate| {
1299 ctx.connection
1300 .send_notification(SessionNotification::new(ctx.session_id.clone(), update))
1301 };
1302 // `size` is the model's context window, which OpenAI-style endpoints don't report.
1303 let context_window = std::env::var(self.env.var("CONTEXT_WINDOW"))
1304 .ok()
1305 .and_then(|v| v.parse().ok())
1306 .unwrap_or(DEFAULT_CONTEXT_WINDOW);
1307
1308 for _ in 0..MAX_TURNS {
1309 // One message id per assistant message (and per thought), so clients can group
1310 // the streamed chunks.
1311 let message_id = new_message_id();
1312 let thought_id = new_message_id();
1313 let wire: Vec<Value> = messages.iter().map(wire_message).collect();
1314 let completion = tokio::select! {
1315 r = llm.complete(model, &wire, &tool_defs, |delta| {
1316 let update = match delta {
1317 Delta::Text(t) => SessionUpdate::AgentMessageChunk(
1318 ContentChunk::new(t.to_string().into()).message_id(message_id.clone()),
1319 ),
1320 Delta::Reasoning(t) => SessionUpdate::AgentThoughtChunk(
1321 ContentChunk::new(t.to_string().into()).message_id(thought_id.clone()),
1322 ),
1323 };
1324 if let Err(e) = notify(update) {
1325 tracing::warn!("failed to send update: {e}");
1326 }
1327 }) => r?,
1328 () = ctx.cancel.cancelled() => return Ok(StopReason::Cancelled),
1329 };
1330 messages.push(completion.to_message());
1331 if let Some(usage) = completion.usage {
1332 let used = usage.used();
1333 notify(SessionUpdate::UsageUpdate(UsageUpdate::new(
1334 used,
1335 context_window.max(used),
1336 )))?;
1337 }
1338
1339 if completion.tool_calls.is_empty() {
1340 return Ok(match completion.finish_reason.as_deref() {
1341 Some("length") => StopReason::MaxTokens,
1342 Some("content_filter") => StopReason::Refusal,
1343 _ => StopReason::EndTurn,
1344 });
1345 }
1346
1347 for tc in &completion.tool_calls {
1348 // Every tool call needs a matching tool message, even after cancellation.
1349 if ctx.cancel.is_cancelled() {
1350 messages.push(tool_message(&tc.id, "Cancelled by user.", true));
1351 continue;
1352 }
1353 let parsed: Result<Value, _> = serde_json::from_str(&tc.arguments);
1354 let args = parsed.as_ref().cloned().unwrap_or_else(|_| json!({}));
1355 let (title, kind, locations) =
1356 tools::describe(&self.toolsets, &ctx.cwd, &ctx.roots, &tc.name, &args);
1357 notify(SessionUpdate::ToolCall(
1358 ToolCall::new(tc.id.clone(), title)
1359 .name(tc.name.clone())
1360 .kind(kind)
1361 .status(ToolCallStatus::InProgress)
1362 .locations(locations)
1363 .raw_input(args.clone()),
1364 ))?;
1365
1366 let outcome: ToolOutcome = if parsed.is_err() {
1367 ToolOutcome::err(format!("Invalid JSON arguments: {}", tc.arguments))
1368 } else {
1369 tools::execute(
1370 ctx,
1371 &self.toolsets,
1372 self.profile.as_ref(),
1373 &tc.id,
1374 &tc.name,
1375 args,
1376 )
1377 .await
1378 };
1379
1380 let mut fields = ToolCallUpdateFields::new()
1381 .status(if outcome.failed {
1382 ToolCallStatus::Failed
1383 } else {
1384 ToolCallStatus::Completed
1385 })
1386 .content(outcome.content)
1387 .raw_output(json!({ "output": outcome.text, "failed": outcome.failed }));
1388 if !outcome.locations.is_empty() {
1389 fields = fields.locations(locations_of(&outcome.locations));
1390 }
1391 ctx.update(&tc.id, fields)?;
1392 messages.push(tool_message(&tc.id, &outcome.text, outcome.failed));
1393 }
1394 if ctx.cancel.is_cancelled() {
1395 return Ok(StopReason::Cancelled);
1396 }
1397 }
1398 Ok(StopReason::MaxTurnRequests)
1399 }
1400 }
1401
1402 /// Marker error: the prompt named a session that doesn't exist.
1403 #[derive(Debug)]
1404 struct UnknownSession(String);
1405
1406 impl std::fmt::Display for UnknownSession {
1407 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1408 write!(f, "unknown session {}", self.0)
1409 }
1410 }
1411
1412 impl std::error::Error for UnknownSession {}
1413
1414 #[cfg(test)]
1415 mod tests {
1416 use super::*;
1417 use crate::llm::EndpointError;
1418
1419 #[test]
1420 fn internal_exposes_endpoint_status_and_message() {
1421 let e = anyhow::Error::new(EndpointError {
1422 source_name: "LLM endpoint".into(),
1423 status: 429,
1424 message: "slow down".into(),
1425 })
1426 .context("running turn");
1427 let err = internal(&e);
1428 assert_eq!(
1429 err.data,
1430 Some(json!({ "message": "slow down", "status": 429 }))
1431 );
1432 }
1433
1434 #[test]
1435 fn internal_falls_back_to_string_data() {
1436 let err = internal(&anyhow::anyhow!("boom"));
1437 assert_eq!(err.data, Some(json!("boom")));
1438 }
1439
1440 #[test]
1441 fn iso8601_known_dates() {
1442 assert_eq!(iso8601(0), "1970-01-01T00:00:00Z");
1443 assert_eq!(iso8601(1_700_000_000), "2023-11-14T22:13:20Z");
1444 assert_eq!(iso8601(951_782_400), "2000-02-29T00:00:00Z");
1445 }
1446
1447 #[test]
1448 fn titles_are_trimmed_and_single_line() {
1449 assert_eq!(session_title(" hello\nworld"), "hello");
1450 let long = "x".repeat(200);
1451 let t = session_title(&long);
1452 assert_eq!(t.chars().count(), 80);
1453 assert!(t.ends_with('…'));
1454 }
1455
1456 #[test]
1457 fn terminal_auth_support_from_capability_or_legacy_meta() {
1458 let caps = |v: Value| serde_json::from_value::<ClientCapabilities>(v).unwrap();
1459 assert!(!supports_terminal_auth(&caps(json!({}))));
1460 assert!(supports_terminal_auth(&caps(
1461 json!({"auth": {"terminal": true}})
1462 )));
1463 // The ACP registry validator's payload.
1464 assert!(supports_terminal_auth(&caps(
1465 json!({"terminal": true, "_meta": {"terminal_output": true, "terminal-auth": true}})
1466 )));
1467 assert!(!supports_terminal_auth(&caps(
1468 json!({"_meta": {"terminal-auth": false}})
1469 )));
1470 }
1471
1472 #[test]
1473 fn version_negotiation_always_v1() {
1474 assert_eq!(negotiate_version(ProtocolVersion::V1), ProtocolVersion::V1);
1475 assert_eq!(
1476 negotiate_version(ProtocolVersion::from(7)),
1477 ProtocolVersion::V1
1478 );
1479 assert_eq!(
1480 negotiate_version(ProtocolVersion::from(0)),
1481 ProtocolVersion::V1
1482 );
1483 }
1484
1485 #[test]
1486 fn private_failure_flag_never_reaches_the_wire() {
1487 let m = tool_message("c1", "boom", true);
1488 assert_eq!(m["x_failed"], true);
1489 let w = wire_message(&m);
1490 assert!(w.get("x_failed").is_none());
1491 assert_eq!(w["content"], "boom");
1492 assert!(tool_message("c1", "ok", false).get("x_failed").is_none());
1493 }
1494
1495 #[test]
1496 fn user_text_handles_parts() {
1497 let m = json!({"role": "user", "content": [
1498 {"type": "text", "text": "hi"},
1499 {"type": "image_url", "image_url": {"url": "x"}}
1500 ]});
1501 assert_eq!(user_text(&m), "hi\n\n[image]");
1502 assert_eq!(user_text(&json!({"content": "plain"})), "plain");
1503 }
1504 }