use std::io::{self, IsTerminal as _};
use dekopon_config::load_discovered;
use dekopon_tui::{
App, ConsoleOptions, ModelChoice,
session::{TRACE_PREFIX, connect, resolve_console_credential},
};
use thiserror::Error;
use crate::cli::{Cli, ConsoleArgs};
#[derive(Debug, Error)]
pub enum ConsoleError {
#[error(transparent)]
Config(Box<dekopon_config::ConfigError>),
#[error(transparent)]
Session(#[from] dekopon_tui::SessionError),
#[error(transparent)]
Exit(#[from] dekopon_tui::ConsoleExit),
#[error("could not start the console runtime")]
Runtime(#[source] io::Error),
#[error(
"no console subject: pass --subject <SUBJECT> or set DEKOPON_CONSOLE_SUBJECT, for example \
dev.console.{}. The broker must also set allowDevelopmentSubjects, hold an attestor grant \
covering that namespace, and map the subject to a principal",
whoami()
)]
NoSubject,
}
fn whoami() -> String {
std::env::var("USER")
.ok()
.filter(|user| !user.is_empty() && user.chars().all(|c| c.is_ascii_alphanumeric()))
.map_or_else(|| "you".to_owned(), |user| user.to_ascii_lowercase())
}
#[must_use]
pub fn is_interactive() -> bool {
io::stdin().is_terminal() && io::stdout().is_terminal()
}
pub fn execute(cli: &Cli, args: &ConsoleArgs) -> Result<(), ConsoleError> {
let subject = args.subject.clone().ok_or(ConsoleError::NoSubject)?;
let catalog = load_discovered(cli.config.clone())
.map_err(|error| ConsoleError::Config(Box::new(error)))?;
let agents = catalog.agents().cloned().collect();
let mut options = ConsoleOptions::new(subject.clone(), args.model.clone());
options.catalog = cli.config.clone();
options.socket = args.socket.clone();
options.server_uid = args.server_uid;
options.prompt_limits.max_steps = args.max_steps;
options.prompt_limits.max_capability_calls = args.max_capability_calls;
options.model_choice = match &args.endpoint {
Some(endpoint) => ModelChoice::OpenAiCompatible {
endpoint: endpoint.clone(),
api_key_env: args.api_key_env.clone(),
},
None => ModelChoice::ChatGptSubscription {
auth_file: args.auth_file.clone(),
},
};
let credential = match &options.model_choice {
ModelChoice::ChatGptSubscription { auth_file } => {
resolve_console_credential(auth_file.as_deref())?
.display()
.to_string()
}
ModelChoice::OpenAiCompatible { endpoint, .. } => endpoint.clone(),
};
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(ConsoleError::Runtime)?;
let (client, socket) = runtime.block_on(connect(&options))?;
tracing::debug!(
trace_prefix = TRACE_PREFIX,
socket_tier = socket.tier().label(),
"opening the console",
);
let app = App::new(
agents,
subject.to_string(),
socket.path().display().to_string(),
credential,
);
runtime.block_on(dekopon_tui::run(app, client, options))?;
Ok(())
}