@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 914 lines 35 KB
Raw
1 //! The ACP client side, and the agent it serves in-process.
2 //!
3 //! [`AgentState::connection`] starts both halves on first use:
4 //!
5 //! - `ed_acp::serve(profile)` on one end of a [`Channel::duplex`], exactly what the product's
6 //! agent runs over stdio;
7 //! - an ACP client on the other end, which forwards `session/update` notifications and
8 //! `session/request_permission` requests to the webview, serves `fs/read_text_file` and
9 //! `fs/write_text_file` inside the session's roots, and opens the page of a URL-mode
10 //! elicitation in the system browser.
11
12 use std::collections::HashMap;
13 use std::path::{Path, PathBuf};
14 use std::sync::atomic::{AtomicBool, Ordering};
15 use std::sync::{Arc, Mutex};
16
17 use agent_client_protocol::schema::v1::{
18 AuthMethodId, AuthenticateRequest, CancelNotification, ClientCapabilities,
19 CompleteElicitationNotification, ContentBlock, CreateElicitationRequest,
20 CreateElicitationResponse, ElicitationAcceptAction, ElicitationAction, ElicitationCapabilities,
21 ElicitationMode, ElicitationUrlCapabilities, ErrorCode, FileSystemCapabilities, Implementation,
22 InitializeRequest, ListSessionsRequest, LoadSessionRequest, LogoutRequest, NewSessionRequest,
23 PromptRequest, ReadTextFileRequest, ReadTextFileResponse, RequestPermissionOutcome,
24 RequestPermissionRequest, RequestPermissionResponse, SelectedPermissionOutcome,
25 SessionConfigOption, SessionConfigOptionValue, SessionId, SessionNotification,
26 SetSessionConfigOptionRequest, TextContent, WriteTextFileRequest, WriteTextFileResponse,
27 };
28 use agent_client_protocol::schema::ProtocolVersion;
29 use agent_client_protocol::{AcpAgent, AcpAgentConfig, Agent, Channel, Client, ConnectionTo};
30 use ed_acp::agent_client_protocol::schema::v1::McpServer;
31 use ed_acp::llm::LlmClient;
32 use ed_acp::{cli, LlmConfig, Profile, ServeOptions};
33 use log::{error, info, warn};
34 use serde_json::json;
35 use tauri::{AppHandle, Emitter};
36 use tauri_plugin_opener::OpenerExt;
37 use tokio::sync::oneshot;
38
39 use crate::{
40 AgentSessionOpened, AgentSessionSummary, AgentStatus, AgentTurnEndedPayload, ExternalConfig,
41 HostConfig, Roots, AUTH_REQUIRED,
42 };
43
44 type Pending = Arc<Mutex<HashMap<String, oneshot::Sender<RequestPermissionOutcome>>>>;
45 /// The roots each open session may use, by session id.
46 type SessionRoots = Arc<Mutex<HashMap<String, Roots>>>;
47
48 /// Managed Tauri state: the live connection and the permission requests waiting on the user.
49 pub struct AgentState {
50 config: Common,
51 source: Source,
52 connection: tokio::sync::Mutex<Option<Live>>,
53 permissions: Pending,
54 roots: SessionRoots,
55 }
56
57 /// What an agent needs from the app, whichever way it runs.
58 #[derive(Clone)]
59 struct Common {
60 client_name: &'static str,
61 client_version: &'static str,
62 roots: fn(&AppHandle, Option<&Path>) -> Result<Roots, String>,
63 mcp_servers: fn(&AppHandle, Option<String>) -> Vec<McpServer>,
64 events: crate::Events,
65 }
66
67 /// Where the agent runs.
68 enum Source {
69 /// `ed_acp::serve` on an in-memory channel.
70 InProcess {
71 profile: fn() -> Arc<dyn Profile>,
72 surface: &'static str,
73 },
74 /// A child process that speaks ACP on stdio.
75 External(ExternalConfig),
76 }
77
78 struct Live {
79 conn: ConnectionTo<Agent>,
80 /// The ids of the auth methods the agent advertised in `initialize`.
81 auth_methods: Vec<String>,
82 /// Dropped (or fired) to hang up, which stops the agent too.
83 _hang_up: oneshot::Sender<()>,
84 /// Set when the client side has ended, so the next call reconnects.
85 ended: Arc<AtomicBool>,
86 }
87
88 /// The `cwd` to ask `session/list` for, or `None` for every stored session.
89 ///
90 /// On a desktop the agent's data directory can be shared with the command-line agent, so the
91 /// app asks only for the conversations in the folder it opened. On iOS that directory is
92 /// inside the app's container, which nothing else writes to and whose path changes with every
93 /// app update. Sessions stored under the old path would never match, and the user's earlier
94 /// conversations would drop out of the list. Loading one rebinds it to the current path.
95 fn list_filter(cwd: &Path, private_data_dir: bool) -> Option<PathBuf> {
96 (!private_data_dir).then(|| cwd.to_path_buf())
97 }
98
99 fn list_request(roots: &Roots) -> ListSessionsRequest {
100 ListSessionsRequest::new().cwd(list_filter(&roots.cwd, cfg!(target_os = "ios")))
101 }
102
103 /// What the agent will use, without starting it: the profile's own session when it has an
104 /// auth provider, else the environment and the stored `env` file.
105 pub fn status(host: &HostConfig) -> AgentStatus {
106 let profile = (host.profile)();
107 let config = match profile.auth() {
108 Some(auth) => auth.llm_config(),
109 None => Some(LlmConfig::from_env(&profile.info().env)),
110 };
111 match config {
112 Some(config) => AgentStatus {
113 available: true,
114 has_key: config.api_key.is_some(),
115 model: config.model,
116 },
117 None => AgentStatus {
118 available: true,
119 has_key: false,
120 model: profile.info().env.default_model.to_string(),
121 },
122 }
123 }
124
125 /// What `<agent> --setup` does for Onde Inference, minus the terminal: check the key with Onde
126 /// Cloud, then write it to the agent's `env` file (mode 0600). With a `model` it is written as
127 /// `<PREFIX>_MODEL` beside the key and used for the check, so the agent doesn't fall back to a
128 /// default tier the key isn't allowed to call; without one, or when the key can't call it,
129 /// the model the check passed with is written instead (see `LlmClient::verify_key`). In the App
130 /// Store sandbox that file lives in the app's container, so a key stored by the command-line
131 /// agent isn't shared.
132 pub async fn set_api_key(host: &HostConfig, key: &str, model: Option<&str>) -> Result<(), String> {
133 let info = host.info();
134 let key = key.trim();
135 if !cli::valid_onde_key(key) {
136 return Err("An Onde key looks like \"app-id:app-secret\".".to_string());
137 }
138 let provider_var = info.env.var("PROVIDER");
139 let mut vars = vec![
140 (provider_var, "onde".to_string()),
141 ("ONDE_API_KEY".to_string(), key.to_string()),
142 ];
143 if let Some(model) = model {
144 vars.push((info.env.var("MODEL"), model.to_string()));
145 }
146 let config = LlmConfig::from_lookup(&info.env, |name| {
147 vars.iter()
148 .find(|(k, _)| k == name)
149 .map(|(_, v)| v.clone())
150 .or_else(|| std::env::var(name).ok())
151 });
152 let configured = config.model.clone();
153 let verified = LlmClient::new(config)
154 .verify_key()
155 .await
156 .map_err(|e| format!("Onde Cloud rejected the key: {e:#}"))?;
157 if verified != configured {
158 let model_var = info.env.var("MODEL");
159 vars.retain(|(k, _)| *k != model_var);
160 vars.push((model_var, verified));
161 }
162
163 let dir = info
164 .env
165 .config_dir()
166 .ok_or("No config directory available.")?;
167 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
168 let path = dir.join("env");
169 let existing = std::fs::read_to_string(&path).unwrap_or_default();
170 std::fs::write(&path, cli::with_vars(&existing, &vars))
171 .map_err(|e| format!("{}: {e}", path.display()))?;
172 #[cfg(unix)]
173 {
174 use std::os::unix::fs::PermissionsExt;
175 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
176 .map_err(|e| format!("{}: {e}", path.display()))?;
177 }
178 info!("Stored the agent's Onde key in {}", path.display());
179 Ok(())
180 }
181
182 /// Remove the agent's Onde key, and the model that came with it, from its env file. Nothing to
183 /// do when there is no file or no key in it.
184 pub fn clear_api_key(host: &HostConfig) -> Result<(), String> {
185 let info = host.info();
186 let Some(dir) = info.env.config_dir() else {
187 return Ok(());
188 };
189 let path = dir.join("env");
190 let existing = match std::fs::read_to_string(&path) {
191 Ok(existing) => existing,
192 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
193 Err(e) => return Err(format!("{}: {e}", path.display())),
194 };
195 let (kept, removed) = without_api_key(&existing, &info.env.var("MODEL"));
196 if removed {
197 std::fs::write(&path, kept).map_err(|e| format!("{}: {e}", path.display()))?;
198 info!("Removed the agent's Onde key from {}", path.display());
199 }
200 Ok(())
201 }
202
203 /// `env` file content without any `ONDE_API_KEY` or `model_var` line, and whether a key was
204 /// there.
205 fn without_api_key(existing: &str, model_var: &str) -> (String, bool) {
206 let model_prefix = format!("{model_var}=");
207 let mut removed = false;
208 let kept: Vec<&str> = existing
209 .lines()
210 .filter(|line| {
211 let line = line.trim();
212 let line = line.strip_prefix("export ").unwrap_or(line);
213 let is_key = line.starts_with("ONDE_API_KEY=");
214 removed |= is_key;
215 !is_key && !line.starts_with(&model_prefix)
216 })
217 .collect();
218 let mut out = kept.join("\n");
219 if !out.is_empty() {
220 out.push('\n');
221 }
222 (out, removed)
223 }
224
225 impl AgentState {
226 /// An agent served in this process from the host's [`Profile`].
227 pub fn new(host: HostConfig) -> Self {
228 Self {
229 source: Source::InProcess {
230 profile: host.profile,
231 surface: host.surface,
232 },
233 config: Common {
234 client_name: host.client_name,
235 client_version: host.client_version,
236 roots: host.roots,
237 mcp_servers: host.mcp_servers,
238 events: host.events,
239 },
240 connection: tokio::sync::Mutex::new(None),
241 permissions: Pending::default(),
242 roots: SessionRoots::default(),
243 }
244 }
245
246 /// An agent that runs as a child process speaking ACP on stdio, such as Anthropic's
247 /// `claude` through `claude-agent-acp`. It is started on first use and killed when the
248 /// connection ends: on [`logout`](Self::logout), or when this state is dropped. The same
249 /// client serves it as the in-process agent: session updates, permission prompts, `fs/*`
250 /// inside the session's roots and URL elicitation.
251 pub fn external(external: ExternalConfig) -> Self {
252 Self {
253 config: Common {
254 client_name: external.client_name,
255 client_version: external.client_version,
256 roots: external.roots,
257 mcp_servers: external.mcp_servers,
258 events: external.events,
259 },
260 source: Source::External(external),
261 connection: tokio::sync::Mutex::new(None),
262 permissions: Pending::default(),
263 roots: SessionRoots::default(),
264 }
265 }
266
267 /// The live connection, starting the agent and the client on first use or after the
268 /// previous connection ended.
269 async fn connection(&self, app: &AppHandle) -> Ready {
270 let mut slot = self.connection.lock().await;
271 if let Some(live) = slot.as_ref() {
272 if !live.ended.load(Ordering::SeqCst) {
273 return Ok((live.conn.clone(), live.auth_methods.clone()));
274 }
275 }
276 let live = self.connect(app).await?;
277 let out = (live.conn.clone(), live.auth_methods.clone());
278 *slot = Some(live);
279 Ok(out)
280 }
281
282 async fn connect(&self, app: &AppHandle) -> Result<Live, String> {
283 let (ready_tx, ready_rx) = oneshot::channel::<Ready>();
284 let (hang_up, hung_up) = oneshot::channel::<()>();
285 let ended = Arc::new(AtomicBool::new(false));
286
287 let client = Client
288 .builder()
289 .name(self.config.client_name)
290 .on_receive_notification(
291 {
292 let app = app.clone();
293 let event = self.config.events.session_update;
294 async move |n: SessionNotification, _cx| {
295 if let Err(e) = app.emit(event, &n) {
296 error!("Failed to emit agent session update: {e:?}");
297 }
298 Ok(())
299 }
300 },
301 agent_client_protocol::on_receive_notification!(),
302 )
303 .on_receive_notification(
304 async move |n: CompleteElicitationNotification, _cx| {
305 info!("Sign-in page completed ({})", n.elicitation_id);
306 Ok(())
307 },
308 agent_client_protocol::on_receive_notification!(),
309 )
310 .on_receive_request(
311 {
312 let app = app.clone();
313 async move |req: CreateElicitationRequest, responder, _cx| {
314 responder.respond(CreateElicitationResponse::new(open_url(&app, &req)))
315 }
316 },
317 agent_client_protocol::on_receive_request!(),
318 )
319 .on_receive_request(
320 {
321 let app = app.clone();
322 let pending = self.permissions.clone();
323 let event = self.config.events.permission_requested;
324 async move |req: RequestPermissionRequest, responder, cx| {
325 // Wait for the user off the dispatch loop so updates keep flowing.
326 let request_id = uuid::Uuid::new_v4().to_string();
327 let (answer_tx, answer_rx) = oneshot::channel();
328 pending
329 .lock()
330 .unwrap()
331 .insert(request_id.clone(), answer_tx);
332 let payload = json!({ "requestId": request_id, "request": req });
333 if let Err(e) = app.emit(event, &payload) {
334 error!("Failed to emit agent permission request: {e:?}");
335 pending.lock().unwrap().remove(&request_id);
336 }
337 cx.spawn(async move {
338 let outcome = answer_rx
339 .await
340 .unwrap_or(RequestPermissionOutcome::Cancelled);
341 responder.respond(RequestPermissionResponse::new(outcome))
342 })
343 }
344 },
345 agent_client_protocol::on_receive_request!(),
346 )
347 .on_receive_request(
348 {
349 let roots = self.roots.clone();
350 async move |req: ReadTextFileRequest, responder, _cx| {
351 let roots = roots.clone();
352 let result =
353 tokio::task::spawn_blocking(move || read_text_file(&roots, &req)).await;
354 match result {
355 Ok(Ok(r)) => responder.respond(r),
356 Ok(Err(e)) => responder.respond_with_error(e),
357 Err(e) => responder.respond_with_internal_error(e.to_string()),
358 }
359 }
360 },
361 agent_client_protocol::on_receive_request!(),
362 )
363 .on_receive_request(
364 {
365 let roots = self.roots.clone();
366 async move |req: WriteTextFileRequest, responder, _cx| {
367 let roots = roots.clone();
368 let result =
369 tokio::task::spawn_blocking(move || write_text_file(&roots, &req))
370 .await;
371 match result {
372 Ok(Ok(r)) => responder.respond(r),
373 Ok(Err(e)) => responder.respond_with_error(e),
374 Err(e) => responder.respond_with_internal_error(e.to_string()),
375 }
376 }
377 },
378 agent_client_protocol::on_receive_request!(),
379 );
380
381 let ended_flag = ended.clone();
382 let pending = self.permissions.clone();
383 let client_name = self.config.client_name;
384 let client_version = self.config.client_version;
385 let what = match &self.source {
386 Source::InProcess { .. } => "in-process",
387 Source::External(_) => "external",
388 };
389 let transport = match &self.source {
390 Source::InProcess { profile, surface } => {
391 let (agent_end, client_end) = Channel::duplex();
392 let opts = ServeOptions {
393 yolo: false,
394 surface,
395 };
396 let profile = profile();
397 let agent_name = profile.info().display_name;
398 tauri::async_runtime::spawn(async move {
399 if let Err(e) = ed_acp::serve(profile, opts, agent_end).await {
400 error!("{agent_name} agent stopped: {e}");
401 }
402 });
403 Transport::Channel(client_end)
404 }
405 Source::External(external) => {
406 let mut config = AcpAgentConfig::new(&external.command);
407 for arg in &external.args {
408 config = config.arg(arg);
409 }
410 for (name, value) in &external.env {
411 config = config.env(name, value);
412 }
413 Transport::Process(AcpAgent::new(config))
414 }
415 };
416 tauri::async_runtime::spawn(async move {
417 let result = match transport {
418 Transport::Channel(end) => {
419 client
420 .connect_with(end, |conn| {
421 run_session(conn, client_name, client_version, ready_tx, hung_up)
422 })
423 .await
424 }
425 // Hanging up drops the process transport, which kills the child and its
426 // descendants.
427 Transport::Process(agent) => {
428 client
429 .connect_with(agent, |conn| {
430 run_session(conn, client_name, client_version, ready_tx, hung_up)
431 })
432 .await
433 }
434 };
435 if let Err(e) = result {
436 warn!("Agent connection ended: {e}");
437 }
438 ended_flag.store(true, Ordering::SeqCst);
439 // Nobody can answer these any more.
440 pending.lock().unwrap().clear();
441 });
442
443 let (conn, auth_methods) = ready_rx
444 .await
445 .map_err(|_| "Agent failed to start.".to_string())??;
446 info!("Agent connected ({what})");
447 Ok(Live {
448 conn,
449 auth_methods,
450 _hang_up: hang_up,
451 ended,
452 })
453 }
454
455 fn roots_for(&self, app: &AppHandle, cwd: Option<&Path>) -> Result<Roots, String> {
456 (self.config.roots)(app, cwd)
457 }
458
459 /// The agent's conversations in `cwd` (the host's default roots when `None`), newest
460 /// first.
461 pub async fn list_sessions(
462 &self,
463 app: &AppHandle,
464 cwd: Option<PathBuf>,
465 ) -> Result<Vec<AgentSessionSummary>, String> {
466 let roots = self.roots_for(app, cwd.as_deref())?;
467 let (conn, _) = self.connection(app).await?;
468 let listed = conn
469 .send_request(list_request(&roots))
470 .block_task()
471 .await
472 .map_err(describe)?;
473 Ok(listed
474 .sessions
475 .into_iter()
476 .map(|session| AgentSessionSummary {
477 session_id: session.session_id.to_string(),
478 title: session.title,
479 updated_at: session.updated_at,
480 })
481 .collect())
482 }
483
484 /// Open a conversation in `cwd`: the one named by `session_id`, else (unless `fresh`) the
485 /// latest in that folder, else a new one.
486 pub async fn open_session(
487 &self,
488 app: &AppHandle,
489 cwd: Option<PathBuf>,
490 fresh: bool,
491 access_token: Option<String>,
492 session_id: Option<String>,
493 ) -> Result<AgentSessionOpened, String> {
494 let roots = self.roots_for(app, cwd.as_deref())?;
495 let (conn, _) = self.connection(app).await?;
496 let mcp_servers = (self.config.mcp_servers)(app, access_token);
497 // The one the user picked, else the latest.
498 let picked = session_id.is_some();
499 let target = match session_id {
500 Some(id) => Some(SessionId::new(id)),
501 None if !fresh => conn
502 .send_request(list_request(&roots))
503 .block_task()
504 .await
505 .map_err(describe)?
506 .sessions
507 .into_iter()
508 // Newest first.
509 .next()
510 .map(|latest| latest.session_id),
511 None => None,
512 };
513 if let Some(id) = target {
514 // The agent may read files while it replays, so the roots come first.
515 self.roots
516 .lock()
517 .unwrap()
518 .insert(id.to_string(), roots.clone());
519 let load = LoadSessionRequest::new(id.clone(), roots.cwd.clone())
520 .additional_directories(roots.extra.clone())
521 .mcp_servers(mcp_servers.clone());
522 match conn.send_request(load).block_task().await {
523 Ok(loaded) => {
524 return Ok(AgentSessionOpened {
525 session_id: id.to_string(),
526 restored: true,
527 config_options: option_values(loaded.config_options),
528 });
529 }
530 Err(e) if e.code == ErrorCode::AuthRequired => {
531 self.roots.lock().unwrap().remove(&id.to_string());
532 return Err(AUTH_REQUIRED.to_string());
533 }
534 Err(e) => {
535 self.roots.lock().unwrap().remove(&id.to_string());
536 // One the user picked and can't have is an error to show.
537 if picked {
538 return Err(describe(e));
539 }
540 // The latest no longer loading shouldn't block a new one.
541 warn!("Could not load agent session {id}: {e}");
542 }
543 }
544 }
545 let new = NewSessionRequest::new(roots.cwd.clone())
546 .additional_directories(roots.extra.clone())
547 .mcp_servers(mcp_servers);
548 let session = conn
549 .send_request(new)
550 .block_task()
551 .await
552 .map_err(describe)?;
553 self.roots
554 .lock()
555 .unwrap()
556 .insert(session.session_id.to_string(), roots);
557 Ok(AgentSessionOpened {
558 session_id: session.session_id.to_string(),
559 restored: false,
560 config_options: option_values(session.config_options),
561 })
562 }
563
564 pub async fn prompt(
565 &self,
566 app: &AppHandle,
567 session_id: String,
568 text: String,
569 ) -> Result<(), String> {
570 let (conn, _) = self.connection(app).await?;
571 let request = PromptRequest::new(
572 SessionId::new(session_id.clone()),
573 vec![ContentBlock::Text(TextContent::new(text))],
574 );
575 let app = app.clone();
576 let event = self.config.events.turn_ended;
577 // Returned before the turn ends: a long turn would otherwise hold the invoke
578 // callback open for minutes.
579 tauri::async_runtime::spawn(async move {
580 let result = conn.send_request(request).block_task().await;
581 let payload = match result {
582 Ok(r) => AgentTurnEndedPayload {
583 session_id,
584 stop_reason: serde_json::to_value(r.stop_reason)
585 .ok()
586 .and_then(|v| v.as_str().map(String::from)),
587 error: None,
588 },
589 Err(e) => AgentTurnEndedPayload {
590 session_id,
591 stop_reason: None,
592 error: Some(describe(e)),
593 },
594 };
595 if let Err(e) = app.emit(event, &payload) {
596 error!("Failed to emit agent turn end: {e:?}");
597 }
598 });
599 Ok(())
600 }
601
602 pub async fn cancel(&self, session_id: String) -> Result<(), String> {
603 // ACP: a client cancelling a turn answers its open permission requests with
604 // `cancelled`.
605 for (_, answer) in self.permissions.lock().unwrap().drain() {
606 let _ = answer.send(RequestPermissionOutcome::Cancelled);
607 }
608 let slot = self.connection.lock().await;
609 let Some(live) = slot.as_ref() else {
610 return Ok(());
611 };
612 live.conn
613 .send_notification(CancelNotification::new(SessionId::new(session_id)))
614 .map_err(|e| e.to_string())
615 }
616
617 pub fn respond_permission(
618 &self,
619 request_id: &str,
620 option_id: Option<String>,
621 ) -> Result<(), String> {
622 let answer = self
623 .permissions
624 .lock()
625 .unwrap()
626 .remove(request_id)
627 .ok_or("That request is no longer waiting for an answer.")?;
628 let outcome = match option_id {
629 Some(id) => RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new(id)),
630 None => RequestPermissionOutcome::Cancelled,
631 };
632 let _ = answer.send(outcome);
633 Ok(())
634 }
635
636 /// Change a config option (the model, auto-approve). `value` is a select value id as a
637 /// string, or a boolean. Returns the session's options as they are afterwards.
638 pub async fn set_config_option(
639 &self,
640 app: &AppHandle,
641 session_id: String,
642 config_id: String,
643 value: serde_json::Value,
644 ) -> Result<Vec<serde_json::Value>, String> {
645 let value = match value {
646 serde_json::Value::Bool(value) => SessionConfigOptionValue::from(value),
647 serde_json::Value::String(value) => SessionConfigOptionValue::from(value.as_str()),
648 other => return Err(format!("Not a config option value: {other}")),
649 };
650 let (conn, _) = self.connection(app).await?;
651 let response = conn
652 .send_request(SetSessionConfigOptionRequest::new(
653 SessionId::new(session_id),
654 config_id,
655 value,
656 ))
657 .block_task()
658 .await
659 .map_err(describe)?;
660 Ok(option_values(Some(response.config_options)))
661 }
662
663 /// Sign in with one of the agent's auth methods: `method_id`, else the first it
664 /// advertised. For a product with its own sign-in this opens the browser through the
665 /// client's URL elicitation and returns once the page is finished.
666 pub async fn authenticate(
667 &self,
668 app: &AppHandle,
669 method_id: Option<String>,
670 ) -> Result<(), String> {
671 let (conn, methods) = self.connection(app).await?;
672 let method = method_id
673 .or_else(|| methods.first().cloned())
674 .ok_or("The agent offers no way to sign in.")?;
675 conn.send_request(AuthenticateRequest::new(AuthMethodId::new(method)))
676 .block_task()
677 .await
678 .map_err(|e| e.to_string())?;
679 Ok(())
680 }
681
682 /// Sign out. The in-process agent forgets its stored session. An external agent's child
683 /// process is ended instead, and its own credentials are left alone, so the next connection
684 /// starts it still signed in.
685 pub async fn logout(&self, app: &AppHandle) -> Result<(), String> {
686 // An external agent keeps its session in its own CLI, which this app doesn't touch.
687 // Ending the process is all that signing out of it means here.
688 if matches!(self.source, Source::External(_)) {
689 self.connection.lock().await.take();
690 self.permissions.lock().unwrap().clear();
691 return Ok(());
692 }
693 let (conn, _) = self.connection(app).await?;
694 conn.send_request(LogoutRequest::new())
695 .block_task()
696 .await
697 .map_err(|e| e.to_string())?;
698 Ok(())
699 }
700 }
701
702 enum Transport {
703 Channel(Channel),
704 Process(AcpAgent),
705 }
706
707 /// What `run_session` hands over once the agent has initialized: the connection and the auth
708 /// method ids, or why it could not start.
709 type Ready = Result<(ConnectionTo<Agent>, Vec<String>), String>;
710
711 /// Initialize the agent, hand the connection to whoever is waiting for it, and stay connected
712 /// until the state is dropped or replaced.
713 async fn run_session(
714 conn: ConnectionTo<Agent>,
715 client_name: &'static str,
716 client_version: &'static str,
717 ready_tx: oneshot::Sender<Ready>,
718 hung_up: oneshot::Receiver<()>,
719 ) -> agent_client_protocol::Result<()> {
720 let init = conn
721 .send_request(
722 InitializeRequest::new(ProtocolVersion::V1)
723 .client_capabilities(
724 ClientCapabilities::new()
725 .fs(FileSystemCapabilities::new()
726 .read_text_file(true)
727 .write_text_file(true))
728 .elicitation(
729 ElicitationCapabilities::new().url(ElicitationUrlCapabilities::new()),
730 ),
731 )
732 .client_info(Implementation::new(client_name, client_version)),
733 )
734 .block_task()
735 .await;
736 match init {
737 Ok(init) => {
738 let methods = init
739 .auth_methods
740 .iter()
741 .map(|m| m.id().to_string())
742 .collect();
743 let _ = ready_tx.send(Ok((conn, methods)));
744 let _ = hung_up.await;
745 Ok(())
746 }
747 Err(e) => {
748 let _ = ready_tx.send(Err(format!("Agent failed to start: {e}")));
749 Err(e)
750 }
751 }
752 }
753
754 /// Answer a URL-mode elicitation by opening its page in the system browser. Only `http` and
755 /// `https` are opened; the user "declines" anything else, or a browser that won't launch.
756 fn open_url(app: &AppHandle, req: &CreateElicitationRequest) -> ElicitationAction {
757 let ElicitationMode::Url(mode) = &req.mode else {
758 // Form mode was never advertised.
759 return ElicitationAction::Decline;
760 };
761 if !(mode.url.starts_with("https://") || mode.url.starts_with("http://")) {
762 warn!("Refusing to open a non-web sign-in URL");
763 return ElicitationAction::Decline;
764 }
765 match app.opener().open_url(&mode.url, None::<&str>) {
766 Ok(()) => ElicitationAction::Accept(ElicitationAcceptAction::new()),
767 Err(e) => {
768 warn!("Could not open the sign-in page: {e}");
769 ElicitationAction::Decline
770 }
771 }
772 }
773
774 fn option_values(options: Option<Vec<SessionConfigOption>>) -> Vec<serde_json::Value> {
775 options
776 .unwrap_or_default()
777 .into_iter()
778 .filter_map(|option| serde_json::to_value(option).ok())
779 .collect()
780 }
781
782 /// [`AUTH_REQUIRED`] for a missing key or session, so the page can ask for sign-in; the
783 /// agent's message otherwise.
784 fn describe(e: agent_client_protocol::Error) -> String {
785 if e.code == ErrorCode::AuthRequired {
786 AUTH_REQUIRED.to_string()
787 } else {
788 e.to_string()
789 }
790 }
791
792 fn outside(path: &Path) -> agent_client_protocol::Error {
793 agent_client_protocol::Error::invalid_params().data(format!(
794 "{} is outside the session's workspace",
795 path.display()
796 ))
797 }
798
799 fn roots_of(
800 roots: &SessionRoots,
801 session: &SessionId,
802 path: &Path,
803 ) -> agent_client_protocol::Result<Roots> {
804 roots
805 .lock()
806 .unwrap()
807 .get(&session.to_string())
808 .cloned()
809 .filter(|roots| roots.contains(path))
810 .ok_or_else(|| outside(path))
811 }
812
813 /// `fs/read_text_file`, honouring the optional 1-based `line` and `limit`.
814 fn read_text_file(
815 roots: &SessionRoots,
816 req: &ReadTextFileRequest,
817 ) -> agent_client_protocol::Result<ReadTextFileResponse> {
818 roots_of(roots, &req.session_id, &req.path)?;
819 let content = std::fs::read_to_string(&req.path).map_err(|e| {
820 if e.kind() == std::io::ErrorKind::NotFound {
821 agent_client_protocol::Error::resource_not_found(Some(req.path.display().to_string()))
822 } else {
823 agent_client_protocol::Error::internal_error().data(e.to_string())
824 }
825 })?;
826 let skip = req.line.map_or(0, |l| l.saturating_sub(1) as usize);
827 let take = req.limit.map_or(usize::MAX, |l| l as usize);
828 let content = content
829 .lines()
830 .skip(skip)
831 .take(take)
832 .collect::<Vec<_>>()
833 .join("\n");
834 Ok(ReadTextFileResponse::new(content))
835 }
836
837 /// `fs/write_text_file`: the client creates the file and its parent directories when they
838 /// don't exist.
839 fn write_text_file(
840 roots: &SessionRoots,
841 req: &WriteTextFileRequest,
842 ) -> agent_client_protocol::Result<WriteTextFileResponse> {
843 roots_of(roots, &req.session_id, &req.path)?;
844 let write = || {
845 if let Some(parent) = req.path.parent() {
846 std::fs::create_dir_all(parent)?;
847 }
848 std::fs::write(&req.path, &req.content)
849 };
850 write().map_err(|e| agent_client_protocol::Error::internal_error().data(e.to_string()))?;
851 Ok(WriteTextFileResponse::new())
852 }
853
854 #[cfg(test)]
855 mod tests {
856 use super::*;
857
858 #[test]
859 fn sessions_are_listed_by_directory_unless_the_data_dir_is_private() {
860 let cwd = Path::new("/data/agent");
861 assert_eq!(list_filter(cwd, false), Some(cwd.to_path_buf()));
862 // iOS: the container path changes with every update, so no filter.
863 assert_eq!(list_filter(cwd, true), None);
864 }
865
866 #[test]
867 fn removing_the_key_keeps_every_other_line() {
868 let (kept, removed) = without_api_key(
869 "AGENT_PROVIDER=onde\nONDE_API_KEY=app:secret\nAGENT_MODEL=x\nAGENT_SURFACE=app\n",
870 "AGENT_MODEL",
871 );
872 assert!(removed);
873 assert_eq!(kept, "AGENT_PROVIDER=onde\nAGENT_SURFACE=app\n");
874 }
875
876 #[test]
877 fn an_exported_key_goes_too_and_a_file_without_one_is_untouched() {
878 assert_eq!(
879 without_api_key("export ONDE_API_KEY=a:b\n", "AGENT_MODEL"),
880 (String::new(), true)
881 );
882 assert_eq!(
883 without_api_key("AGENT_PROVIDER=onde\n", "AGENT_MODEL"),
884 ("AGENT_PROVIDER=onde\n".to_string(), false)
885 );
886 assert_eq!(without_api_key("", "AGENT_MODEL"), (String::new(), false));
887 }
888
889 #[test]
890 fn a_similar_variable_is_not_the_key() {
891 let (kept, removed) =
892 without_api_key("ONDE_API_KEY_BACKUP=x\nAGENT_MODEL_X=y\n", "AGENT_MODEL");
893 assert!(!removed);
894 assert_eq!(kept, "ONDE_API_KEY_BACKUP=x\nAGENT_MODEL_X=y\n");
895 }
896
897 #[test]
898 fn a_session_reaches_only_its_own_roots() {
899 let roots = SessionRoots::default();
900 roots.lock().unwrap().insert(
901 "a".into(),
902 Roots {
903 cwd: PathBuf::from("/work/a"),
904 extra: Vec::new(),
905 },
906 );
907 let a = SessionId::new("a");
908 let b = SessionId::new("b");
909 assert!(roots_of(&roots, &a, Path::new("/work/a/src/main.rs")).is_ok());
910 assert!(roots_of(&roots, &a, Path::new("/work/b/src/main.rs")).is_err());
911 // An id nobody opened has no roots at all.
912 assert!(roots_of(&roots, &b, Path::new("/work/a/src/main.rs")).is_err());
913 }
914 }