use std::path::{Path, PathBuf};
use futures::future::BoxFuture;
#[derive(Debug, Clone, Copy)]
pub struct ExternalStart<'a> {
pub working_dir: &'a Path,
pub worktrees: &'a [PathBuf],
pub commit_worktrees: &'a [PathBuf],
pub working_copies: &'a [PathBuf],
}
pub trait ExternalSubagent: Send + Sync + 'static {
type Session: ExternalSession;
type Error: std::error::Error + Send + Sync + 'static;
fn open(
&self,
start: ExternalStart<'_>,
) -> impl Future<Output = Result<Self::Session, Self::Error>> + Send;
}
pub trait ExternalSession: Send + 'static {
type Error: std::error::Error + Send + Sync + 'static;
fn prompt(&mut self, prompt: &str) -> impl Future<Output = Result<String, Self::Error>> + Send;
fn cancel(&mut self) -> impl Future<Output = ()> + Send;
fn close(self) -> impl Future<Output = ()> + Send;
fn model(&self) -> Option<String>;
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct ExternalError(Box<dyn std::error::Error + Send + Sync>);
trait ExternalSubagentImpl: Send + Sync {
fn open<'a>(
&'a self,
start: ExternalStart<'a>,
) -> BoxFuture<'a, Result<AnyExternalSession, ExternalError>>;
}
impl<B: ExternalSubagent> ExternalSubagentImpl for B {
fn open<'a>(
&'a self,
start: ExternalStart<'a>,
) -> BoxFuture<'a, Result<AnyExternalSession, ExternalError>> {
Box::pin(async move {
let session = ExternalSubagent::open(self, start)
.await
.map_err(|error| ExternalError(Box::new(error)))?;
Ok(AnyExternalSession(Box::new(session)))
})
}
}
trait ExternalSessionImpl: Send {
fn prompt<'a>(&'a mut self, prompt: &'a str) -> BoxFuture<'a, Result<String, ExternalError>>;
fn cancel(&mut self) -> BoxFuture<'_, ()>;
fn close(self: Box<Self>) -> BoxFuture<'static, ()>;
fn model(&self) -> Option<String>;
}
impl<S: ExternalSession> ExternalSessionImpl for S {
fn prompt<'a>(&'a mut self, prompt: &'a str) -> BoxFuture<'a, Result<String, ExternalError>> {
Box::pin(async move {
ExternalSession::prompt(self, prompt)
.await
.map_err(|error| ExternalError(Box::new(error)))
})
}
fn cancel(&mut self) -> BoxFuture<'_, ()> {
Box::pin(ExternalSession::cancel(self))
}
fn close(self: Box<Self>) -> BoxFuture<'static, ()> {
Box::pin(ExternalSession::close(*self))
}
fn model(&self) -> Option<String> {
ExternalSession::model(self)
}
}
pub struct AnyExternalSubagent(Box<dyn ExternalSubagentImpl>);
impl AnyExternalSubagent {
pub fn new(backend: impl ExternalSubagent) -> Self {
Self(Box::new(backend))
}
pub async fn open(
&self,
start: ExternalStart<'_>,
) -> Result<AnyExternalSession, ExternalError> {
self.0.open(start).await
}
}
pub struct AnyExternalSession(Box<dyn ExternalSessionImpl>);
impl AnyExternalSession {
pub async fn prompt(&mut self, prompt: &str) -> Result<String, ExternalError> {
self.0.prompt(prompt).await
}
pub async fn cancel(&mut self) {
self.0.cancel().await;
}
pub async fn close(self) {
self.0.close().await;
}
pub fn model(&self) -> Option<String> {
self.0.model()
}
}