@ondeinference / ed Mirror · read-only / commits / 6e503e4
Fork 0

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

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

Synced Nov 23, 01:00 UTC

ed-acp-tauri: run an external ACP agent over stdio

AgentState::external starts a child process that speaks ACP, such as Anthropic's claude through claude-agent-acp, and serves it with the same client as the in-process agent: session updates, permission prompts, fs/* inside the session roots and URL elicitation. The child is killed when the connection ends, on logout or when the state is dropped. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Nov 1, 2026 at 12:16 UTC 6e503e45d90ecd41add60f7db0a6978079a24440
2 files changed +192 -66
crates/ed-acp-tauri/src/client.rs
+173 -66
@@ -26,9 +26,10 @@ use agent_client_protocol::schema::v1::{
26 SetSessionConfigOptionRequest, TextContent, WriteTextFileRequest, WriteTextFileResponse,
27 };
28 use agent_client_protocol::schema::ProtocolVersion;
29 -use agent_client_protocol::{Agent, Channel, Client, ConnectionTo};
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;
31 -use ed_acp::{cli, LlmConfig, ServeOptions};
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,8 +37,8 @@ use tauri_plugin_opener::OpenerExt;
37 use tokio::sync::oneshot;
38
39 use crate::{
39 - AgentSessionOpened, AgentSessionSummary, AgentStatus, AgentTurnEndedPayload, HostConfig, Roots,
40 - AUTH_REQUIRED,
40 + AgentSessionOpened, AgentSessionSummary, AgentStatus, AgentTurnEndedPayload, ExternalConfig,
41 + HostConfig, Roots, AUTH_REQUIRED,
42 };
43
44 type Pending = Arc<Mutex<HashMap<String, oneshot::Sender<RequestPermissionOutcome>>>>;
@@ -46,12 +47,34 @@ 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 {
49 - config: HostConfig,
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`.
@@ -200,9 +223,41 @@ fn without_api_key(existing: &str, model_var: &str) -> (String, bool) {
223 }
224
225 impl AgentState {
203 - pub fn new(config: HostConfig) -> Self {
226 + /// An agent served in this process from the host's [`Profile`].
227 + pub fn new(host: HostConfig) -> Self {
228 Self {
205 - config,
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(),
@@ -211,10 +266,7 @@ impl AgentState {
266
267 /// The live connection, starting the agent and the client on first use or after the
268 /// previous connection ended.
214 - async fn connection(
215 - &self,
216 - app: &AppHandle,
217 - ) -> Result<(ConnectionTo<Agent>, Vec<String>), String> {
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) {
@@ -228,22 +280,7 @@ impl AgentState {
280 }
281
282 async fn connect(&self, app: &AppHandle) -> Result<Live, String> {
231 - let (agent_end, client_end) = Channel::duplex();
232 -
233 - let opts = ServeOptions {
234 - yolo: false,
235 - surface: self.config.surface,
236 - };
237 - let profile = (self.config.profile)();
238 - let agent_name = profile.info().display_name;
239 - tauri::async_runtime::spawn(async move {
240 - if let Err(e) = ed_acp::serve(profile, opts, agent_end).await {
241 - error!("{agent_name} agent stopped: {e}");
242 - }
243 - });
244 -
245 - let (ready_tx, ready_rx) =
246 - oneshot::channel::<Result<(ConnectionTo<Agent>, Vec<String>), 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
@@ -345,45 +382,56 @@ impl AgentState {
382 let pending = self.permissions.clone();
383 let client_name = self.config.client_name;
384 let client_version = self.config.client_version;
348 - tauri::async_runtime::spawn(async move {
349 - let result = client
350 - .connect_with(client_end, |conn: ConnectionTo<Agent>| async move {
351 - let init = conn
352 - .send_request(
353 - InitializeRequest::new(ProtocolVersion::V1)
354 - .client_capabilities(
355 - ClientCapabilities::new()
356 - .fs(FileSystemCapabilities::new()
357 - .read_text_file(true)
358 - .write_text_file(true))
359 - .elicitation(
360 - ElicitationCapabilities::new()
361 - .url(ElicitationUrlCapabilities::new()),
362 - ),
363 - )
364 - .client_info(Implementation::new(client_name, client_version)),
365 - )
366 - .block_task()
367 - .await;
368 - match init {
369 - Ok(init) => {
370 - let methods = init
371 - .auth_methods
372 - .iter()
373 - .map(|m| m.id().to_string())
374 - .collect();
375 - let _ = ready_tx.send(Ok((conn, methods)));
376 - // Stay connected until the state is dropped or replaced.
377 - let _ = hung_up.await;
378 - Ok(())
379 - }
380 - Err(e) => {
381 - let _ = ready_tx.send(Err(format!("Agent failed to start: {e}")));
382 - Err(e)
383 - }
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 }
385 - })
386 - .await;
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 }
@@ -395,7 +443,7 @@ impl AgentState {
443 let (conn, auth_methods) = ready_rx
444 .await
445 .map_err(|_| "Agent failed to start.".to_string())??;
398 - info!("Agent connected in-process");
446 + info!("Agent connected ({what})");
447 Ok(Live {
448 conn,
449 auth_methods,
@@ -633,6 +681,13 @@ impl AgentState {
681
682 /// Sign out: the agent forgets its stored session.
683 pub async fn logout(&self, app: &AppHandle) -> Result<(), String> {
684 + // An external agent keeps its session in its own CLI, which this app doesn't touch.
685 + // Ending the process is all that signing out of it means here.
686 + if matches!(self.source, Source::External(_)) {
687 + self.connection.lock().await.take();
688 + self.permissions.lock().unwrap().clear();
689 + return Ok(());
690 + }
691 let (conn, _) = self.connection(app).await?;
692 conn.send_request(LogoutRequest::new())
693 .block_task()
@@ -642,6 +697,58 @@ impl AgentState {
697 }
698 }
699
700 +enum Transport {
701 + Channel(Channel),
702 + Process(AcpAgent),
703 +}
704 +
705 +/// What `run_session` hands over once the agent has initialized: the connection and the auth
706 +/// method ids, or why it could not start.
707 +type Ready = Result<(ConnectionTo<Agent>, Vec<String>), String>;
708 +
709 +/// Initialize the agent, hand the connection to whoever is waiting for it, and stay connected
710 +/// until the state is dropped or replaced.
711 +async fn run_session(
712 + conn: ConnectionTo<Agent>,
713 + client_name: &'static str,
714 + client_version: &'static str,
715 + ready_tx: oneshot::Sender<Ready>,
716 + hung_up: oneshot::Receiver<()>,
717 +) -> agent_client_protocol::Result<()> {
718 + let init = conn
719 + .send_request(
720 + InitializeRequest::new(ProtocolVersion::V1)
721 + .client_capabilities(
722 + ClientCapabilities::new()
723 + .fs(FileSystemCapabilities::new()
724 + .read_text_file(true)
725 + .write_text_file(true))
726 + .elicitation(
727 + ElicitationCapabilities::new().url(ElicitationUrlCapabilities::new()),
728 + ),
729 + )
730 + .client_info(Implementation::new(client_name, client_version)),
731 + )
732 + .block_task()
733 + .await;
734 + match init {
735 + Ok(init) => {
736 + let methods = init
737 + .auth_methods
738 + .iter()
739 + .map(|m| m.id().to_string())
740 + .collect();
741 + let _ = ready_tx.send(Ok((conn, methods)));
742 + let _ = hung_up.await;
743 + Ok(())
744 + }
745 + Err(e) => {
746 + let _ = ready_tx.send(Err(format!("Agent failed to start: {e}")));
747 + Err(e)
748 + }
749 + }
750 +}
751 +
752 /// Answer a URL-mode elicitation by opening its page in the system browser. Only `http` and
753 /// `https` are opened; the user "declines" anything else, or a browser that won't launch.
754 fn open_url(app: &AppHandle, req: &CreateElicitationRequest) -> ElicitationAction {
crates/ed-acp-tauri/src/lib.rs
+19
@@ -119,6 +119,25 @@ impl HostConfig {
119 }
120 }
121
122 +/// An agent that runs as a child process speaking ACP on stdio, for [`AgentState::external`].
123 +#[derive(Clone)]
124 +pub struct ExternalConfig {
125 + /// The executable, resolved by the host (a GUI app's `PATH` is minimal).
126 + pub command: PathBuf,
127 + pub args: Vec<String>,
128 + /// Added to the child's environment.
129 + pub env: Vec<(String, String)>,
130 + /// Reported to the agent as `clientInfo.name`.
131 + pub client_name: &'static str,
132 + /// `clientInfo.version`.
133 + pub client_version: &'static str,
134 + /// As [`HostConfig::roots`].
135 + pub roots: fn(&AppHandle, Option<&Path>) -> Result<Roots, String>,
136 + /// As [`HostConfig::mcp_servers`].
137 + pub mcp_servers: fn(&AppHandle, Option<String>) -> Vec<McpServer>,
138 + pub events: Events,
139 +}
140 +
141 /// Response returned by `agent_status`.
142 #[tsync]
143 #[derive(Debug, Clone, Serialize, Deserialize)]