Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
426
akode-rs/app-server/src/request_processors/account_processor.rs
Normal file
426
akode-rs/app-server/src/request_processors/account_processor.rs
Normal file
@@ -0,0 +1,426 @@
|
||||
use super::*;
|
||||
use crate::auth_mode::auth_mode_to_api;
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
use crate::outgoing_message::AccountNotification;
|
||||
|
||||
mod account_read;
|
||||
mod gateway_oauth;
|
||||
mod security_setup;
|
||||
|
||||
enum RefreshTokenRequestOutcome {
|
||||
NotAttemptedOrSucceeded,
|
||||
FailedTransiently,
|
||||
FailedPermanently,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AccountRequestProcessor {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
model_catalog: Arc<ModelCatalog>,
|
||||
gateway_login: Arc<std::sync::Mutex<Option<gateway_oauth::ActiveGatewayLogin>>>,
|
||||
gateway_clients:
|
||||
Arc<std::sync::Mutex<HashMap<String, Arc<akode_model_provider::GatewayAuthManager>>>>,
|
||||
_gateway_notifications: Arc<tokio_util::task::AbortOnDropHandle<()>>,
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
model_catalog: Arc<ModelCatalog>,
|
||||
) -> Arc<Self> {
|
||||
let gateway_notifications = crate::gateway_oauth_notifications::spawn(
|
||||
Arc::clone(&auth_manager),
|
||||
config_manager.clone(),
|
||||
Arc::clone(&outgoing),
|
||||
);
|
||||
Arc::new(Self {
|
||||
_gateway_notifications: Arc::new(gateway_notifications),
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
outgoing,
|
||||
config,
|
||||
config_manager,
|
||||
model_catalog,
|
||||
gateway_login: Arc::new(std::sync::Mutex::new(/*t*/ None)),
|
||||
gateway_clients: Arc::new(std::sync::Mutex::new(HashMap::new())),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn login_account(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: LoginAccountParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.login_v2(request_id, params).await.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn logout_account(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.logout_v2(request_id).await.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn cancel_login_account(
|
||||
&self,
|
||||
params: CancelLoginAccountParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.cancel_login_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_auth_status(
|
||||
&self,
|
||||
params: GetAuthStatusParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.get_auth_status_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn cancel_active_login(&self) {
|
||||
self.cancel_gateway_login();
|
||||
}
|
||||
|
||||
pub(crate) fn clear_external_auth(&self) {
|
||||
self.auth_manager.clear_external_auth();
|
||||
}
|
||||
|
||||
fn current_account_updated_notification(&self) -> AccountUpdatedNotification {
|
||||
let auth = self.auth_manager.auth_cached();
|
||||
AccountUpdatedNotification {
|
||||
auth_mode: auth
|
||||
.as_ref()
|
||||
.map(CodexAuth::api_auth_mode)
|
||||
.map(auth_mode_to_api),
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_latest_config(&self) -> Config {
|
||||
match self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to reload config, using startup config: {err}");
|
||||
self.config.as_ref().clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Account changes alter app routing, so loaded plugin capabilities must be rebuilt.
|
||||
fn refresh_plugin_caches_after_account_change(
|
||||
config_manager: &ConfigManager,
|
||||
thread_manager: &Arc<ThreadManager>,
|
||||
) {
|
||||
Self::spawn_effective_plugins_changed_task(
|
||||
Arc::clone(thread_manager),
|
||||
config_manager.clone(),
|
||||
);
|
||||
}
|
||||
|
||||
fn spawn_effective_plugins_changed_task(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
thread_manager.plugins_manager().clear_cache();
|
||||
thread_manager.skills_service().clear_cache();
|
||||
crate::mcp_refresh::reload_mcp_config_best_effort(&thread_manager, &config_manager)
|
||||
.await;
|
||||
thread_manager.invalidate_mcp_runtimes().await;
|
||||
});
|
||||
}
|
||||
|
||||
async fn login_v2(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: LoginAccountParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
match params {
|
||||
LoginAccountParams::ApiKey { api_key } => {
|
||||
self.login_api_key_v2(request_id, LoginApiKeyParams { api_key })
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn login_api_key_common(
|
||||
&self,
|
||||
params: &LoginApiKeyParams,
|
||||
) -> std::result::Result<(), JSONRPCErrorError> {
|
||||
if !self
|
||||
.auth_manager
|
||||
.is_login_method_allowed(ForcedLoginMethod::Api)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"API key login is disabled by the configured login policy.",
|
||||
));
|
||||
}
|
||||
|
||||
match login_with_api_key(
|
||||
&self.config.codex_home,
|
||||
¶ms.api_key,
|
||||
self.config.cli_auth_credentials_store_mode,
|
||||
self.config.auth_keyring_backend_kind(),
|
||||
) {
|
||||
Ok(()) => {
|
||||
self.auth_manager.reload().await;
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(internal_error(format!("failed to save api key: {err}"))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn login_api_key_v2(&self, request_id: ConnectionRequestId, params: LoginApiKeyParams) {
|
||||
let result = self
|
||||
.login_api_key_common(¶ms)
|
||||
.await
|
||||
.map(|()| LoginAccountResponse::ApiKey {});
|
||||
let logged_in = result.is_ok();
|
||||
if logged_in {
|
||||
self.model_catalog.invalidate().await;
|
||||
}
|
||||
self.outgoing.send_result(request_id, result).await;
|
||||
|
||||
if logged_in {
|
||||
self.send_login_success_notifications(/*login_id*/ None)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn cancel_login_response(
|
||||
&self,
|
||||
params: CancelLoginAccountParams,
|
||||
) -> Result<CancelLoginAccountResponse, JSONRPCErrorError> {
|
||||
let login_id = params.login_id;
|
||||
Uuid::parse_str(&login_id)
|
||||
.map_err(|_| invalid_request(format!("invalid login id: {login_id}")))?;
|
||||
// No account login flow is cancellable by id.
|
||||
Ok(CancelLoginAccountResponse {
|
||||
status: CancelLoginAccountStatus::NotFound,
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_login_success_notifications(&self, login_id: Option<Uuid>) {
|
||||
self.thread_manager.invalidate_mcp_runtimes().await;
|
||||
self.send_account_login_notifications(AccountLoginCompletedNotification {
|
||||
login_id: login_id.map(|id| id.to_string()),
|
||||
success: true,
|
||||
error: None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn send_account_login_notifications(
|
||||
&self,
|
||||
mut payload: AccountLoginCompletedNotification,
|
||||
) {
|
||||
let auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||
let owner_generation = auth_changes.borrow().owner_generation;
|
||||
if payload.success
|
||||
&& let Err(error) = self.read_account().await
|
||||
{
|
||||
payload.success = false;
|
||||
payload.error = Some(error.to_string());
|
||||
}
|
||||
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
|
||||
Self::refresh_plugin_caches_after_account_change(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
);
|
||||
}
|
||||
|
||||
let success = payload.success;
|
||||
self.outgoing
|
||||
.send_account_notification(
|
||||
/*connection_id*/ None,
|
||||
&auth_changes,
|
||||
owner_generation,
|
||||
AccountNotification::LoginCompleted(payload),
|
||||
)
|
||||
.await;
|
||||
|
||||
if success {
|
||||
let notification = self.current_account_updated_notification();
|
||||
self.outgoing
|
||||
.send_account_notification(
|
||||
/*connection_id*/ None,
|
||||
&auth_changes,
|
||||
owner_generation,
|
||||
AccountNotification::Updated(notification),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn logout_common(&self) -> std::result::Result<Option<AuthMode>, JSONRPCErrorError> {
|
||||
self.cancel_active_login().await;
|
||||
let config =
|
||||
logout_configured_account(&self.config_manager, &self.auth_manager, &self.config)
|
||||
.await?;
|
||||
self.thread_manager.invalidate_mcp_runtimes().await;
|
||||
clear_account_configuration(&self.config_manager, &config).await?;
|
||||
|
||||
self.model_catalog.invalidate().await;
|
||||
|
||||
Self::refresh_plugin_caches_after_account_change(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
);
|
||||
|
||||
// Reflect the current auth method after logout (likely None).
|
||||
Ok(self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.as_ref()
|
||||
.map(CodexAuth::api_auth_mode)
|
||||
.map(auth_mode_to_api))
|
||||
}
|
||||
|
||||
async fn logout_v2(&self, request_id: ConnectionRequestId) -> Result<(), JSONRPCErrorError> {
|
||||
let result = self.logout_common().await;
|
||||
let account_updated = result
|
||||
.as_ref()
|
||||
.ok()
|
||||
.cloned()
|
||||
.map(|auth_mode| AccountUpdatedNotification { auth_mode });
|
||||
self.outgoing
|
||||
.send_result(request_id, result.map(|_| LogoutAccountResponse {}))
|
||||
.await;
|
||||
|
||||
if let Some(payload) = account_updated {
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::AccountUpdated(payload))
|
||||
.await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn refresh_token_if_requested(&self, do_refresh: bool) -> RefreshTokenRequestOutcome {
|
||||
if do_refresh && let Err(err) = self.auth_manager.refresh_token().await {
|
||||
let failed_reason = err.failed_reason();
|
||||
if failed_reason.is_none() {
|
||||
tracing::warn!("failed to refresh token while getting account: {err}");
|
||||
return RefreshTokenRequestOutcome::FailedTransiently;
|
||||
}
|
||||
return RefreshTokenRequestOutcome::FailedPermanently;
|
||||
}
|
||||
RefreshTokenRequestOutcome::NotAttemptedOrSucceeded
|
||||
}
|
||||
|
||||
async fn get_auth_status_response(
|
||||
&self,
|
||||
params: GetAuthStatusParams,
|
||||
) -> Result<GetAuthStatusResponse, JSONRPCErrorError> {
|
||||
let include_token = params.include_token.unwrap_or(false);
|
||||
let do_refresh = params.refresh_token.unwrap_or(false);
|
||||
|
||||
self.refresh_token_if_requested(do_refresh).await;
|
||||
|
||||
// Determine whether auth is required based on the active model provider.
|
||||
// If a custom provider is configured with `requires_openai_auth == false`,
|
||||
// then no auth step is required; otherwise, default to requiring auth.
|
||||
let config = self.load_latest_config().await;
|
||||
let requires_openai_auth = config.model_provider.requires_openai_auth;
|
||||
|
||||
let response = if !requires_openai_auth {
|
||||
GetAuthStatusResponse {
|
||||
auth_method: None,
|
||||
auth_token: None,
|
||||
requires_openai_auth: Some(false),
|
||||
}
|
||||
} else {
|
||||
let auth = if do_refresh {
|
||||
self.auth_manager.auth_cached()
|
||||
} else {
|
||||
self.auth_manager.auth().await
|
||||
};
|
||||
match auth {
|
||||
Some(auth) => {
|
||||
let permanent_refresh_failure =
|
||||
self.auth_manager.refresh_failure_for_auth(&auth).is_some();
|
||||
let auth_mode = auth_mode_to_api(auth.api_auth_mode());
|
||||
let (reported_auth_method, token_opt) = if matches!(auth, CodexAuth::Headers(_))
|
||||
|| include_token && permanent_refresh_failure
|
||||
{
|
||||
// Host-owned and metadata-bearing credentials are never exported.
|
||||
(Some(auth_mode), None)
|
||||
} else {
|
||||
match auth.get_token() {
|
||||
Ok(token) if !token.is_empty() => {
|
||||
let tok = if include_token { Some(token) } else { None };
|
||||
(Some(auth_mode), tok)
|
||||
}
|
||||
Ok(_) => (None, None),
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to get token for auth status: {err}");
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
};
|
||||
GetAuthStatusResponse {
|
||||
auth_method: reported_auth_method,
|
||||
auth_token: token_opt,
|
||||
requires_openai_auth: Some(true),
|
||||
}
|
||||
}
|
||||
None => GetAuthStatusResponse {
|
||||
auth_method: None,
|
||||
auth_token: None,
|
||||
requires_openai_auth: Some(true),
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove account credentials using the current account's policy, even during startup recovery.
|
||||
pub(crate) async fn logout_configured_account(
|
||||
config_manager: &ConfigManager,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
fallback_config: &Config,
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
// Another process may have changed the persisted credentials. Reload both
|
||||
// account authority and its policy before selecting a grant to remove.
|
||||
auth_manager
|
||||
.reload_with_cached_auth()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("logout failed: {err}")))?;
|
||||
let config = config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await;
|
||||
let config = config.unwrap_or_else(|_| fallback_config.clone());
|
||||
|
||||
match auth_manager.logout().await {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
return Err(internal_error(format!("logout failed: {err}")));
|
||||
}
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Discard account-scoped cloud and provider settings after credentials have been removed.
|
||||
pub(crate) async fn clear_account_configuration(
|
||||
config_manager: &ConfigManager,
|
||||
config: &Config,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
// No built-in cloud provider keeps account-scoped settings in config.toml.
|
||||
let _ = (config_manager, config);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Reads the provider-reported account for the current configuration and credentials.
|
||||
|
||||
use super::*;
|
||||
use akode_model_provider::ProviderAccountError;
|
||||
use akode_model_provider::ProviderAccountState;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn get_account(
|
||||
&self,
|
||||
_params: GetAccountParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let account_state = self
|
||||
.read_account()
|
||||
.await
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
Ok(Some(
|
||||
GetAccountResponse {
|
||||
account: account_state.account.map(Account::from),
|
||||
requires_openai_auth: account_state.requires_openai_auth,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn read_account(&self) -> Result<ProviderAccountState, ProviderAccountError> {
|
||||
let config = self.load_latest_config().await;
|
||||
create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(self.auth_manager.clone()),
|
||||
)
|
||||
.account_state()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Gateway sign-in RPCs share credentials with inference and bind cancellation to the initiating connection.
|
||||
//! Cancellation is acknowledged only after the active login releases its slot.
|
||||
|
||||
use super::*;
|
||||
use crate::gateway_oauth_notifications::status_fields;
|
||||
use crate::transport::ConnectionId;
|
||||
use akode_app_server_protocol::GatewayOAuthCancelResponse;
|
||||
use akode_app_server_protocol::GatewayOAuthLoginResponse;
|
||||
use akode_app_server_protocol::GatewayOAuthReadResponse;
|
||||
use akode_login::OAuthSessionManager;
|
||||
use akode_model_provider::GatewayAuthManager;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
pub(super) struct ActiveGatewayLogin {
|
||||
owner: ConnectionId,
|
||||
cancel: CancellationToken,
|
||||
finished: CancellationToken,
|
||||
}
|
||||
|
||||
struct LoginGuard(Arc<std::sync::Mutex<Option<ActiveGatewayLogin>>>);
|
||||
|
||||
impl Drop for LoginGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(active) = self.0.lock().unwrap_or_else(PoisonError::into_inner).take() {
|
||||
active.finished.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
async fn gateway_client(
|
||||
&self,
|
||||
model_provider: Option<String>,
|
||||
) -> Result<(Arc<Config>, Option<Arc<OAuthSessionManager>>), JSONRPCErrorError> {
|
||||
let config = match model_provider.as_deref() {
|
||||
Some(provider_id) => {
|
||||
let config = config_for_provider(&self.config, provider_id)?;
|
||||
// Explicit selectors use startup definitions, so validate against current policy.
|
||||
self.config_manager
|
||||
.check_thread_model_provider(&config)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
config
|
||||
}
|
||||
None => Arc::new(
|
||||
self.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?,
|
||||
),
|
||||
};
|
||||
let manager = akode_model_provider::create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(Arc::clone(&self.auth_manager)),
|
||||
)
|
||||
.gateway_auth_manager()
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
let session = manager
|
||||
.as_deref()
|
||||
.and_then(GatewayAuthManager::oauth_session);
|
||||
// Keep sign-in status alive when clients alternate between providers.
|
||||
if let Some(manager) = &manager {
|
||||
self.gateway_clients
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(config.model_provider_id.clone(), Arc::clone(manager));
|
||||
}
|
||||
Ok((config, session))
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_oauth_read(
|
||||
&self,
|
||||
params: akode_app_server_protocol::GatewayOAuthReadParams,
|
||||
) -> Result<GatewayOAuthReadResponse, JSONRPCErrorError> {
|
||||
let (config, client) = self.gateway_client(params.model_provider).await?;
|
||||
let state = if let Some(client) = client {
|
||||
Some(status_fields(
|
||||
client
|
||||
.status()
|
||||
.await
|
||||
.map_err(|err| internal_error(err.to_string()))?,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(GatewayOAuthReadResponse {
|
||||
provider_id: config.model_provider_id.clone(),
|
||||
provider_name: config.model_provider.name.clone(),
|
||||
required: state.is_some(),
|
||||
status: state.as_ref().map(|state| state.0),
|
||||
error: state.and_then(|state| state.1),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_oauth_login(
|
||||
&self,
|
||||
params: akode_app_server_protocol::GatewayOAuthLoginParams,
|
||||
owner: ConnectionId,
|
||||
connection_gate: &crate::connection_rpc_gate::ConnectionRpcGate,
|
||||
) -> Result<GatewayOAuthLoginResponse, JSONRPCErrorError> {
|
||||
let cancel = CancellationToken::new();
|
||||
let guard = {
|
||||
let mut active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if connection_gate.is_closed() {
|
||||
return Err(invalid_request("The connection is closed"));
|
||||
}
|
||||
if active.is_some() {
|
||||
return Err(invalid_request("Gateway sign-in is already in progress"));
|
||||
}
|
||||
*active = Some(ActiveGatewayLogin {
|
||||
owner,
|
||||
cancel: cancel.clone(),
|
||||
finished: CancellationToken::new(),
|
||||
});
|
||||
LoginGuard(Arc::clone(&self.gateway_login))
|
||||
};
|
||||
let (config, client) = self.gateway_client(params.model_provider).await?;
|
||||
let client = client
|
||||
.ok_or_else(|| invalid_request("The selected provider does not use gateway OAuth"))?;
|
||||
if config.model_provider.requires_openai_auth
|
||||
&& config.model_provider.env_key.is_none()
|
||||
&& config.model_provider.experimental_bearer_token.is_none()
|
||||
&& config.model_provider.auth.is_none()
|
||||
&& self.auth_manager.auth_cached().is_none()
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Sign in to your primary account before signing in to the gateway",
|
||||
));
|
||||
}
|
||||
let (url_tx, url_rx) = tokio::sync::oneshot::channel();
|
||||
let login = client.login_with_browser(cancel.cancelled(), |url| {
|
||||
let _ = url_tx.send(url.to_string());
|
||||
});
|
||||
tokio::pin!(login);
|
||||
let result = tokio::select! {
|
||||
result = &mut login => result,
|
||||
url = url_rx => {
|
||||
if let Ok(url) = url {
|
||||
self.outgoing.send_server_notification_to_connections(&[owner], ServerNotification::GatewayOAuthChanged(akode_app_server_protocol::GatewayOAuthChangedNotification {
|
||||
auth_url: Some(url), provider_id: config.model_provider_id.clone(),
|
||||
status: akode_app_server_protocol::GatewayOAuthStatus::Started, error: None,
|
||||
})).await;
|
||||
}
|
||||
login.await
|
||||
}
|
||||
};
|
||||
result.map_err(|err| internal_error(err.to_string()))?;
|
||||
drop(guard);
|
||||
Ok(GatewayOAuthLoginResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_oauth_cancel(
|
||||
&self,
|
||||
owner: ConnectionId,
|
||||
) -> Result<GatewayOAuthCancelResponse, JSONRPCErrorError> {
|
||||
let finished = {
|
||||
let active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(active) = active.as_ref() else {
|
||||
return Ok(GatewayOAuthCancelResponse {});
|
||||
};
|
||||
if active.owner != owner {
|
||||
return Err(invalid_request(
|
||||
"Gateway sign-in belongs to another connection",
|
||||
));
|
||||
}
|
||||
active.cancel.cancel();
|
||||
active.finished.clone()
|
||||
};
|
||||
finished.cancelled().await;
|
||||
Ok(GatewayOAuthCancelResponse {})
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_connection_closed(&self, owner: ConnectionId) {
|
||||
let active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(active) = active.as_ref()
|
||||
&& active.owner == owner
|
||||
{
|
||||
active.cancel.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cancel_gateway_login(&self) {
|
||||
let active = self
|
||||
.gateway_login
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(active) = active.as_ref() {
|
||||
active.cancel.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! Security reminders are a ChatGPT account feature; aKode credentials never have one.
|
||||
|
||||
use super::*;
|
||||
use akode_app_server_protocol::GetAccountSecuritySetupResponse;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn get_account_security_setup(&self) -> GetAccountSecuritySetupResponse {
|
||||
GetAccountSecuritySetupResponse { notice: None }
|
||||
}
|
||||
}
|
||||
782
akode-rs/app-server/src/request_processors/catalog_processor.rs
Normal file
782
akode-rs/app-server/src/request_processors/catalog_processor.rs
Normal file
@@ -0,0 +1,782 @@
|
||||
use super::*;
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
use akode_config::ConfigPathContext;
|
||||
use akode_core::config::permission_profile_catalog;
|
||||
use akode_hooks::HookListEntryHandler;
|
||||
use akode_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use akode_utils_path_uri::PathConvention;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use futures::StreamExt;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CatalogRequestProcessor {
|
||||
pub(super) outgoing: Arc<OutgoingMessageSender>,
|
||||
pub(super) skills_watcher: Arc<SkillsWatcher>,
|
||||
pub(super) thread_manager: Arc<ThreadManager>,
|
||||
pub(super) config: Arc<Config>,
|
||||
pub(super) config_manager: ConfigManager,
|
||||
model_catalog: Arc<ModelCatalog>,
|
||||
}
|
||||
|
||||
const SKILLS_LIST_CWD_CONCURRENCY: usize = 5;
|
||||
|
||||
fn skills_to_info(
|
||||
skills: &[akode_skills::SkillMetadata],
|
||||
disabled_paths: &HashSet<PathUri>,
|
||||
) -> Vec<akode_app_server_protocol::SkillMetadata> {
|
||||
skills
|
||||
.iter()
|
||||
.map(|skill| {
|
||||
let enabled = !disabled_paths.contains(&skill.path_to_skills_md);
|
||||
akode_app_server_protocol::SkillMetadata {
|
||||
name: skill.name.clone(),
|
||||
description: skill.description.clone(),
|
||||
short_description: skill.short_description.clone(),
|
||||
interface: skill.interface.clone().map(|interface| {
|
||||
akode_app_server_protocol::SkillInterface {
|
||||
display_name: interface.display_name,
|
||||
short_description: interface.short_description,
|
||||
icon_small: interface.icon_small,
|
||||
icon_large: interface.icon_large,
|
||||
|
||||
brand_color: interface.brand_color,
|
||||
default_prompt: interface.default_prompt,
|
||||
}
|
||||
}),
|
||||
dependencies: skill.dependencies.clone().map(|dependencies| {
|
||||
akode_app_server_protocol::SkillDependencies {
|
||||
tools: dependencies
|
||||
.tools
|
||||
.into_iter()
|
||||
.map(|tool| akode_app_server_protocol::SkillToolDependency {
|
||||
r#type: tool.r#type,
|
||||
value: tool.value,
|
||||
description: tool.description,
|
||||
transport: tool.transport,
|
||||
command: tool.command,
|
||||
url: tool.url,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}),
|
||||
path: skill.path_to_skills_md.clone().into(),
|
||||
scope: skill.scope.into(),
|
||||
enabled,
|
||||
plugin_id: skill.plugin_id.clone(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hooks_to_info(hooks: &[akode_hooks::HookListEntry]) -> Vec<HookMetadata> {
|
||||
hooks
|
||||
.iter()
|
||||
.filter(|hook| !hook.builtin)
|
||||
.map(|hook| {
|
||||
let handler = match &hook.handler {
|
||||
HookListEntryHandler::Command { command, r#async } => {
|
||||
HookHandlerMetadata::Command {
|
||||
command: command.clone(),
|
||||
r#async: *r#async,
|
||||
}
|
||||
}
|
||||
HookListEntryHandler::McpTool { server, tool } => HookHandlerMetadata::McpTool {
|
||||
server: server.clone(),
|
||||
tool: tool.clone(),
|
||||
},
|
||||
};
|
||||
HookMetadata {
|
||||
key: hook.key.clone(),
|
||||
event_name: hook.event_name.into(),
|
||||
handler,
|
||||
matcher: hook.matcher.clone(),
|
||||
timeout_sec: hook.timeout_sec,
|
||||
status_message: hook.status_message.clone(),
|
||||
additional_context_limit: hook.additional_context_limit,
|
||||
source_path: hook.source_path.clone(),
|
||||
source: hook.source.into(),
|
||||
plugin_id: hook.plugin_id.clone(),
|
||||
environment_id: hook.environment_id.clone(),
|
||||
display_order: hook.display_order,
|
||||
enabled: hook.enabled,
|
||||
is_managed: hook.is_managed,
|
||||
current_hash: hook.current_hash.clone(),
|
||||
trust_status: hook.trust_status.into(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn errors_to_info(
|
||||
errors: &[akode_skills::SkillError],
|
||||
) -> Vec<akode_app_server_protocol::SkillErrorInfo> {
|
||||
errors
|
||||
.iter()
|
||||
.map(|err| akode_app_server_protocol::SkillErrorInfo {
|
||||
path: err.path.to_path_buf(),
|
||||
message: err.message.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl CatalogRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
model_catalog: Arc<ModelCatalog>,
|
||||
) -> Self {
|
||||
Self {
|
||||
outgoing,
|
||||
skills_watcher,
|
||||
thread_manager,
|
||||
config,
|
||||
config_manager,
|
||||
model_catalog,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn skills_list(
|
||||
&self,
|
||||
params: SkillsListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.skills_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn hooks_list(
|
||||
&self,
|
||||
params: HooksListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.hooks_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn skills_config_write(
|
||||
&self,
|
||||
params: SkillsConfigWriteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.skills_config_write_response_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn skills_extra_roots_set(
|
||||
&self,
|
||||
params: SkillsExtraRootsSetParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.skills_extra_roots_set_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn model_list(
|
||||
&self,
|
||||
params: ModelListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let (active_config, active_models_manager) = self
|
||||
.model_catalog
|
||||
.current()
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
let (config, models_manager) = match params.model_provider.as_deref() {
|
||||
None => (active_config, active_models_manager),
|
||||
Some(provider_id) => {
|
||||
let config = config_for_provider(&self.config, provider_id)?;
|
||||
if provider_id == active_config.model_provider_id
|
||||
&& config.model_provider == active_config.model_provider
|
||||
{
|
||||
(active_config, active_models_manager)
|
||||
} else {
|
||||
// Temporary catalogs must not replace the active provider's disk cache.
|
||||
let manager = self.thread_manager.temporary_models_manager_for_config(
|
||||
&config,
|
||||
&akode_models_manager::manager::ModelCatalogSettings::default(),
|
||||
);
|
||||
(config, manager)
|
||||
}
|
||||
}
|
||||
};
|
||||
// Gate the same provider used by the catalog, including when its model cache is warm.
|
||||
// Resolving credentials may refresh them, but explicit host policy prevents browser login.
|
||||
if let Some(gateway) = akode_model_provider::create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(self.thread_manager.auth_manager()),
|
||||
)
|
||||
.gateway_auth_manager()
|
||||
.map_err(|error| internal_error(error.to_string()))?
|
||||
{
|
||||
// Refreshing credentials can contact the gateway before the catalog's own check.
|
||||
self.config_manager
|
||||
.check_thread_model_provider(&config)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
if let Err(error) = gateway.resolve_access_token().await {
|
||||
let current = self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
// An explicit selection need not match the current default.
|
||||
if current.model_providers.get(&config.model_provider_id)
|
||||
!= Some(&config.model_provider)
|
||||
|| (params.model_provider.is_none()
|
||||
&& current.model_provider_id != config.model_provider_id)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Model provider settings changed. Restart Codex to apply them, then retry fetching the model list",
|
||||
));
|
||||
}
|
||||
return Err(invalid_request(error.to_string()));
|
||||
}
|
||||
}
|
||||
self.list_models(params, config, models_manager)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn experimental_feature_list(
|
||||
&self,
|
||||
params: ExperimentalFeatureListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.experimental_feature_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn permission_profile_list(
|
||||
&self,
|
||||
params: PermissionProfileListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.permission_profile_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn collaboration_mode_list(
|
||||
&self,
|
||||
params: CollaborationModeListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
Self::list_collaboration_modes(self.thread_manager.clone(), params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn mock_experimental_method(
|
||||
&self,
|
||||
params: MockExperimentalMethodParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.mock_experimental_method_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
async fn resolve_cwd_config(
|
||||
&self,
|
||||
cwd: &Path,
|
||||
) -> Result<(AbsolutePathBuf, ConfigLayerStack), String> {
|
||||
let cwd_abs =
|
||||
AbsolutePathBuf::relative_to_current_dir(cwd).map_err(|err| err.to_string())?;
|
||||
let config_layer_stack = self
|
||||
.config_manager
|
||||
.load_config_layers_for_cwd(cwd_abs.clone())
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
|
||||
Ok((cwd_abs, config_layer_stack))
|
||||
}
|
||||
|
||||
async fn load_latest_config(
|
||||
&self,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
self.config_manager
|
||||
.load_latest_config(fallback_cwd)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
}
|
||||
|
||||
async fn list_models(
|
||||
&self,
|
||||
params: ModelListParams,
|
||||
config: Arc<Config>,
|
||||
models_manager: akode_models_manager::manager::SharedModelsManager,
|
||||
) -> Result<ModelListResponse, JSONRPCErrorError> {
|
||||
let ModelListParams {
|
||||
limit,
|
||||
cursor,
|
||||
include_hidden,
|
||||
model_provider: _,
|
||||
} = params;
|
||||
let presets = self
|
||||
.model_catalog
|
||||
.list_models_from_snapshot(
|
||||
config,
|
||||
models_manager,
|
||||
akode_models_manager::manager::RefreshStrategy::OnlineIfUncached,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
let models = supported_models(presets, include_hidden.unwrap_or(false));
|
||||
let total = models.len();
|
||||
|
||||
if total == 0 {
|
||||
return Ok(ModelListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
});
|
||||
}
|
||||
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let effective_limit = effective_limit.min(total);
|
||||
let start = match cursor {
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| invalid_request(format!("invalid cursor: {cursor}")))?,
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total models {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let items = models[start..end].to_vec();
|
||||
let next_cursor = if end < total {
|
||||
Some(end.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ModelListResponse {
|
||||
data: items,
|
||||
next_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
async fn list_collaboration_modes(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
params: CollaborationModeListParams,
|
||||
) -> Result<CollaborationModeListResponse, JSONRPCErrorError> {
|
||||
let CollaborationModeListParams {} = params;
|
||||
let items = thread_manager
|
||||
.list_collaboration_modes()
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
let response = CollaborationModeListResponse { data: items };
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn experimental_feature_list_response(
|
||||
&self,
|
||||
params: ExperimentalFeatureListParams,
|
||||
) -> Result<ExperimentalFeatureListResponse, JSONRPCErrorError> {
|
||||
let ExperimentalFeatureListParams {
|
||||
cursor,
|
||||
limit,
|
||||
thread_id,
|
||||
} = params;
|
||||
let config = match thread_id.as_deref() {
|
||||
Some(thread_id) => {
|
||||
let thread_id = ThreadId::from_string(thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
let thread_config = thread.config().await;
|
||||
self.config_manager
|
||||
.load_latest_config_with_session_layers(
|
||||
&thread_config.config_layer_stack,
|
||||
&thread_config.cwd,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?
|
||||
}
|
||||
None => self.load_latest_config(/*fallback_cwd*/ None).await?,
|
||||
};
|
||||
let data = FEATURES
|
||||
.iter()
|
||||
.map(|spec| {
|
||||
let (stage, display_name, description, announcement) = match spec.stage {
|
||||
Stage::Experimental {
|
||||
name,
|
||||
menu_description,
|
||||
announcement,
|
||||
} => (
|
||||
ApiExperimentalFeatureStage::Beta,
|
||||
Some(name.to_string()),
|
||||
Some(menu_description.to_string()),
|
||||
Some(announcement.to_string()),
|
||||
),
|
||||
Stage::UnderDevelopment => (
|
||||
ApiExperimentalFeatureStage::UnderDevelopment,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
Stage::Stable => (ApiExperimentalFeatureStage::Stable, None, None, None),
|
||||
Stage::Deprecated => {
|
||||
(ApiExperimentalFeatureStage::Deprecated, None, None, None)
|
||||
}
|
||||
Stage::Removed => (ApiExperimentalFeatureStage::Removed, None, None, None),
|
||||
};
|
||||
|
||||
ApiExperimentalFeature {
|
||||
name: spec.key.to_string(),
|
||||
stage,
|
||||
display_name,
|
||||
description,
|
||||
announcement,
|
||||
enabled: config.features.enabled(spec.id),
|
||||
default_enabled: spec.default_enabled,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let total = data.len();
|
||||
if total == 0 {
|
||||
return Ok(ExperimentalFeatureListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
});
|
||||
}
|
||||
|
||||
// Clamp to 1 so limit=0 cannot return a non-advancing page.
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let effective_limit = effective_limit.min(total);
|
||||
let start = match cursor {
|
||||
Some(cursor) => match cursor.parse::<usize>() {
|
||||
Ok(idx) => idx,
|
||||
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total feature flags {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let data = data[start..end].to_vec();
|
||||
let next_cursor = if end < total {
|
||||
Some(end.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(ExperimentalFeatureListResponse { data, next_cursor })
|
||||
}
|
||||
|
||||
async fn permission_profile_list_response(
|
||||
&self,
|
||||
params: PermissionProfileListParams,
|
||||
) -> Result<PermissionProfileListResponse, JSONRPCErrorError> {
|
||||
let PermissionProfileListParams { cursor, limit, cwd } = params;
|
||||
let (cwd, config_layer_stack) = match cwd {
|
||||
Some(cwd) => self
|
||||
.resolve_cwd_config(&PathBuf::from(cwd))
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?,
|
||||
None => (
|
||||
self.config.cwd.clone(),
|
||||
self.config_manager
|
||||
.load_config_layers(/*cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?,
|
||||
),
|
||||
};
|
||||
let context = ConfigPathContext::new(
|
||||
PathConvention::native(),
|
||||
Some(PathUri::from_abs_path(&cwd)),
|
||||
AbsolutePathBufGuard::home_directory()
|
||||
.and_then(|home| PathUri::from_host_native_path(home).ok()),
|
||||
);
|
||||
let profiles = permission_profile_catalog(&config_layer_stack, &context)
|
||||
.map_err(|err| internal_error(format!("failed to resolve permission profiles: {err}")))?
|
||||
.into_iter()
|
||||
.map(|profile| PermissionProfileSummary {
|
||||
id: profile.id,
|
||||
description: profile.description,
|
||||
allowed: profile.allowed,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let total = profiles.len();
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let effective_limit = effective_limit.min(total);
|
||||
let start = match cursor {
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| invalid_request(format!("invalid cursor: {cursor}")))?,
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total permission profiles {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let data = profiles[start..end].to_vec();
|
||||
let next_cursor = (end < total).then_some(end.to_string());
|
||||
|
||||
Ok(PermissionProfileListResponse { data, next_cursor })
|
||||
}
|
||||
|
||||
async fn mock_experimental_method_inner(
|
||||
&self,
|
||||
params: MockExperimentalMethodParams,
|
||||
) -> Result<MockExperimentalMethodResponse, JSONRPCErrorError> {
|
||||
let MockExperimentalMethodParams { value } = params;
|
||||
let response = MockExperimentalMethodResponse { echoed: value };
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn skills_list_response(
|
||||
&self,
|
||||
params: SkillsListParams,
|
||||
) -> Result<SkillsListResponse, JSONRPCErrorError> {
|
||||
let SkillsListParams { cwds, force_reload } = params;
|
||||
let cwds = if cwds.is_empty() {
|
||||
vec![self.config.cwd.to_path_buf()]
|
||||
} else {
|
||||
cwds
|
||||
};
|
||||
|
||||
let skills_service = self.thread_manager.skills_service();
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
if force_reload {
|
||||
plugins_manager.clear_cache();
|
||||
skills_service.clear_cache();
|
||||
}
|
||||
let fs = self
|
||||
.thread_manager
|
||||
.environment_manager()
|
||||
.default_environment()
|
||||
.map(|environment| environment.get_filesystem());
|
||||
let skills_request = skills_service.for_request();
|
||||
let mut data = futures::stream::iter(cwds.into_iter().enumerate())
|
||||
.map(|(index, cwd)| {
|
||||
let fs = fs.clone();
|
||||
let skills_request = &skills_request;
|
||||
let plugins_manager = Arc::clone(&plugins_manager);
|
||||
async move {
|
||||
let config = match self.load_latest_config(Some(cwd.clone())).await {
|
||||
Ok(resolved) => resolved,
|
||||
Err(error) => {
|
||||
let error_path = cwd.clone();
|
||||
return (
|
||||
index,
|
||||
akode_app_server_protocol::SkillsListEntry {
|
||||
cwd,
|
||||
skills: Vec::new(),
|
||||
errors: vec![akode_app_server_protocol::SkillErrorInfo {
|
||||
path: error_path,
|
||||
message: error.message,
|
||||
}],
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let plugins = plugins_manager.plugins_for_config(&plugins_input).await;
|
||||
let plugin_skill_snapshots =
|
||||
plugins_manager.plugin_skill_snapshots_for_config(&plugins_input);
|
||||
let skills_input = akode_skills_extension::HostSkillsLoadInput::new(
|
||||
config.cwd.clone(),
|
||||
plugins.effective_plugin_skill_roots(),
|
||||
config.config_layer_stack,
|
||||
)
|
||||
.with_plugin_skill_snapshots(plugin_skill_snapshots);
|
||||
let skills_input = match self
|
||||
.thread_manager
|
||||
.environment_manager()
|
||||
.default_environment_id()
|
||||
{
|
||||
Some(environment_id) => skills_input.with_environment_id(environment_id),
|
||||
None => skills_input,
|
||||
};
|
||||
let snapshot = skills_request
|
||||
.snapshot_for_cwd(&skills_input, force_reload, fs)
|
||||
.await;
|
||||
let outcome = snapshot.outcome();
|
||||
let errors = errors_to_info(&outcome.errors);
|
||||
let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths);
|
||||
(
|
||||
index,
|
||||
akode_app_server_protocol::SkillsListEntry {
|
||||
cwd,
|
||||
skills,
|
||||
errors,
|
||||
},
|
||||
)
|
||||
}
|
||||
})
|
||||
.buffer_unordered(SKILLS_LIST_CWD_CONCURRENCY)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
data.sort_unstable_by_key(|(index, _)| *index);
|
||||
let data = data.into_iter().map(|(_, entry)| entry).collect();
|
||||
Ok(SkillsListResponse { data })
|
||||
}
|
||||
|
||||
async fn skills_extra_roots_set_response(
|
||||
&self,
|
||||
params: SkillsExtraRootsSetParams,
|
||||
) -> Result<SkillsExtraRootsSetResponse, JSONRPCErrorError> {
|
||||
let SkillsExtraRootsSetParams { extra_roots } = params;
|
||||
self.skills_watcher
|
||||
.register_runtime_extra_roots(&extra_roots);
|
||||
self.thread_manager
|
||||
.skills_service()
|
||||
.set_extra_roots(extra_roots);
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::SkillsChanged(
|
||||
akode_app_server_protocol::SkillsChangedNotification {},
|
||||
))
|
||||
.await;
|
||||
Ok(SkillsExtraRootsSetResponse {})
|
||||
}
|
||||
|
||||
/// Resolve a loaded thread's hook inventory, or inspect configuration for each requested cwd.
|
||||
async fn hooks_list_response(
|
||||
&self,
|
||||
params: HooksListParams,
|
||||
) -> Result<HooksListResponse, JSONRPCErrorError> {
|
||||
let HooksListParams { cwds, thread_id } = params;
|
||||
if let Some(thread_id) = thread_id {
|
||||
if !cwds.is_empty() {
|
||||
return Err(invalid_request("specify either threadId or cwds"));
|
||||
}
|
||||
let thread_id = ThreadId::from_string(&thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
let cwd = thread.config_snapshot().await.cwd().to_path_buf();
|
||||
let hooks = thread.list_hooks();
|
||||
return Ok(HooksListResponse {
|
||||
data: vec![akode_app_server_protocol::HooksListEntry {
|
||||
cwd,
|
||||
hooks: hooks_to_info(&hooks.hooks),
|
||||
warnings: hooks.warnings,
|
||||
errors: Vec::new(),
|
||||
}],
|
||||
});
|
||||
}
|
||||
|
||||
let cwds = if cwds.is_empty() {
|
||||
vec![self.config.cwd.to_path_buf()]
|
||||
} else {
|
||||
cwds
|
||||
};
|
||||
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let mut data = Vec::new();
|
||||
for cwd in cwds {
|
||||
let config = match self
|
||||
.config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides::default(),
|
||||
Some(cwd.clone()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
let error_path = cwd.clone();
|
||||
data.push(akode_app_server_protocol::HooksListEntry {
|
||||
cwd,
|
||||
hooks: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
errors: vec![akode_app_server_protocol::HookErrorInfo {
|
||||
path: error_path,
|
||||
message: err.to_string(),
|
||||
}],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let hooks_enabled = config.features.enabled(Feature::CodexHooks);
|
||||
let plugin_hooks = if hooks_enabled && config.features.enabled(Feature::Plugins) {
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await;
|
||||
akode_core_plugins::PluginHookLoadOutcome {
|
||||
hook_sources: plugin_outcome.effective_plugin_hook_sources(),
|
||||
hook_load_warnings: plugin_outcome.effective_plugin_hook_warnings(),
|
||||
}
|
||||
} else {
|
||||
akode_core_plugins::PluginHookLoadOutcome::default()
|
||||
};
|
||||
let hooks_config = akode_hooks::HooksConfig {
|
||||
feature_enabled: hooks_enabled,
|
||||
bypass_hook_trust: config.bypass_hook_trust,
|
||||
config_layer_stack: Some(config.config_layer_stack),
|
||||
plugin_hook_sources: plugin_hooks.hook_sources,
|
||||
plugin_hook_load_warnings: plugin_hooks.hook_load_warnings,
|
||||
..Default::default()
|
||||
};
|
||||
let hooks = tokio::task::spawn_blocking(move || akode_hooks::list_hooks(hooks_config))
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("hook discovery task failed: {err}")))?;
|
||||
data.push(akode_app_server_protocol::HooksListEntry {
|
||||
cwd,
|
||||
hooks: hooks_to_info(&hooks.hooks),
|
||||
warnings: hooks.warnings,
|
||||
errors: Vec::new(),
|
||||
});
|
||||
}
|
||||
Ok(HooksListResponse { data })
|
||||
}
|
||||
|
||||
async fn skills_config_write_response_inner(
|
||||
&self,
|
||||
params: SkillsConfigWriteParams,
|
||||
) -> Result<SkillsConfigWriteResponse, JSONRPCErrorError> {
|
||||
let SkillsConfigWriteParams {
|
||||
path,
|
||||
name,
|
||||
enabled,
|
||||
} = params;
|
||||
let edit = match (path, name) {
|
||||
(Some(path), None) => ConfigEdit::SetSkillConfig {
|
||||
path: path.into_path_buf(),
|
||||
enabled,
|
||||
},
|
||||
(None, Some(name)) if !name.trim().is_empty() => {
|
||||
ConfigEdit::SetSkillConfigByName { name, enabled }
|
||||
}
|
||||
_ => {
|
||||
return Err(invalid_params(
|
||||
"skills/config/write requires exactly one of path or name",
|
||||
));
|
||||
}
|
||||
};
|
||||
let edits = vec![edit];
|
||||
ConfigEditsBuilder::new(&self.config.codex_home)
|
||||
.with_edits(edits)
|
||||
.apply()
|
||||
.await
|
||||
.map(|()| {
|
||||
self.thread_manager.plugins_manager().clear_cache();
|
||||
self.thread_manager.skills_service().clear_cache();
|
||||
SkillsConfigWriteResponse {
|
||||
effective_enabled: enabled,
|
||||
}
|
||||
})
|
||||
.map_err(|err| internal_error(format!("failed to update skill settings: {err}")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
use super::*;
|
||||
use akode_core::exec_env::inject_apply_patch_env;
|
||||
use akode_core::windows_sandbox::local_binding_policy_for_sandbox;
|
||||
use akode_core::windows_sandbox::managed_proxy_routing_for_windows_sandbox;
|
||||
use akode_protocol::shell_environment::is_non_inheritable_env_var;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CommandExecRequestProcessor {
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
config: Arc<Config>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
command_exec_manager: CommandExecManager,
|
||||
}
|
||||
|
||||
impl CommandExecRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
config: Arc<Config>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
) -> Self {
|
||||
Self {
|
||||
arg0_paths,
|
||||
config,
|
||||
outgoing,
|
||||
config_manager,
|
||||
environment_manager,
|
||||
command_exec_manager: CommandExecManager::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn one_off_command_exec(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: CommandExecParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.require_local_environment()?;
|
||||
self.exec_one_off_command(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn command_exec_write(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecWriteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.command_exec_manager
|
||||
.write(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn command_exec_resize(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecResizeParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.command_exec_manager
|
||||
.resize(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn command_exec_terminate(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecTerminateParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.command_exec_manager
|
||||
.terminate(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
|
||||
self.command_exec_manager
|
||||
.connection_closed(connection_id)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn require_local_environment(&self) -> Result<(), JSONRPCErrorError> {
|
||||
self.environment_manager
|
||||
.try_local_environment()
|
||||
.is_some()
|
||||
.then_some(())
|
||||
.ok_or_else(|| internal_error("local environment is not configured"))
|
||||
}
|
||||
|
||||
async fn exec_one_off_command(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: CommandExecParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
self.exec_one_off_command_inner(request_id.clone(), params)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn exec_one_off_command_inner(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: CommandExecParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
tracing::debug!("ExecOneOffCommand params: {params:?}");
|
||||
|
||||
let request = request_id.clone();
|
||||
|
||||
if params.command.is_empty() {
|
||||
return Err(invalid_request("command must not be empty"));
|
||||
}
|
||||
|
||||
let CommandExecParams {
|
||||
command,
|
||||
process_id,
|
||||
tty,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
disable_output_cap,
|
||||
disable_timeout,
|
||||
timeout_ms,
|
||||
cwd,
|
||||
env: env_overrides,
|
||||
size,
|
||||
sandbox_policy,
|
||||
permission_profile,
|
||||
} = params;
|
||||
if sandbox_policy.is_some() && permission_profile.is_some() {
|
||||
return Err(invalid_request(
|
||||
"`permissionProfile` cannot be combined with `sandboxPolicy`",
|
||||
));
|
||||
}
|
||||
|
||||
if size.is_some() && !tty {
|
||||
return Err(invalid_params("command/exec size requires tty: true"));
|
||||
}
|
||||
|
||||
if disable_output_cap && output_bytes_cap.is_some() {
|
||||
return Err(invalid_params(
|
||||
"command/exec cannot set both outputBytesCap and disableOutputCap",
|
||||
));
|
||||
}
|
||||
|
||||
if disable_timeout && timeout_ms.is_some() {
|
||||
return Err(invalid_params(
|
||||
"command/exec cannot set both timeoutMs and disableTimeout",
|
||||
));
|
||||
}
|
||||
|
||||
let cwd = cwd.map_or_else(|| self.config.cwd.clone(), |cwd| self.config.cwd.join(cwd));
|
||||
let mut env = create_env(
|
||||
&self.config.permissions.shell_environment_policy,
|
||||
/*thread_id*/ None,
|
||||
);
|
||||
if let Some(env_overrides) = env_overrides {
|
||||
for (key, value) in env_overrides {
|
||||
match value {
|
||||
Some(value) => {
|
||||
env.insert(key, value);
|
||||
}
|
||||
None => {
|
||||
env.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
env.retain(|name, _| !is_non_inheritable_env_var(name));
|
||||
inject_apply_patch_env(&mut env);
|
||||
let timeout_ms = match timeout_ms {
|
||||
Some(timeout_ms) => match u64::try_from(timeout_ms) {
|
||||
Ok(timeout_ms) => Some(timeout_ms),
|
||||
Err(_) => {
|
||||
return Err(invalid_params(format!(
|
||||
"command/exec timeoutMs must be non-negative, got {timeout_ms}"
|
||||
)));
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let windows_sandbox_level = WindowsSandboxLevel::from_config(&self.config);
|
||||
let output_bytes_cap = if disable_output_cap {
|
||||
None
|
||||
} else {
|
||||
Some(output_bytes_cap.unwrap_or(DEFAULT_OUTPUT_BYTES_CAP))
|
||||
};
|
||||
let expiration = if disable_timeout {
|
||||
ExecExpiration::Cancellation(CancellationToken::new())
|
||||
} else {
|
||||
match timeout_ms {
|
||||
Some(timeout_ms) => timeout_ms.into(),
|
||||
None => ExecExpiration::DefaultTimeout,
|
||||
}
|
||||
};
|
||||
let capture_policy = if disable_output_cap {
|
||||
ExecCapturePolicy::FullBuffer
|
||||
} else {
|
||||
ExecCapturePolicy::ShellTool
|
||||
};
|
||||
let sandbox_cwd = if permission_profile.is_some() {
|
||||
cwd.clone()
|
||||
} else {
|
||||
self.config.cwd.clone()
|
||||
};
|
||||
let (
|
||||
effective_permission_profile,
|
||||
network_proxy_spec,
|
||||
network_proxy_permission_profile,
|
||||
managed_network_requirements_enabled,
|
||||
windows_sandbox_workspace_roots,
|
||||
) = if let Some(permission_profile) = permission_profile {
|
||||
let overrides = ConfigOverrides {
|
||||
cwd: Some(cwd.to_path_buf()),
|
||||
default_permissions: Some(permission_profile),
|
||||
..Default::default()
|
||||
};
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
overrides,
|
||||
Some(self.config.cwd.to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| invalid_request(format!("invalid permission profile: {err}")))?;
|
||||
if let Some(warning) = config.startup_warnings.iter().find(|warning| {
|
||||
warning.contains("Configured value for `permission_profile` is disallowed")
|
||||
}) {
|
||||
return Err(invalid_request(format!(
|
||||
"invalid permission profile: {warning}"
|
||||
)));
|
||||
}
|
||||
(
|
||||
config.permissions.effective_permission_profile(),
|
||||
config.permissions.network.clone(),
|
||||
config.permissions.permission_profile().clone(),
|
||||
config.managed_network_requirements_enabled(),
|
||||
config.effective_workspace_roots(),
|
||||
)
|
||||
} else if let Some(policy) = sandbox_policy.map(|policy| policy.to_core()) {
|
||||
let mut permissions = self.config.permissions.clone();
|
||||
permissions
|
||||
.set_legacy_sandbox_policy(policy, &sandbox_cwd)
|
||||
.map_err(|err| invalid_request(format!("invalid sandbox policy: {err}")))?;
|
||||
(
|
||||
permissions.effective_permission_profile(),
|
||||
self.config.permissions.network.clone(),
|
||||
self.config.permissions.permission_profile().clone(),
|
||||
self.config.managed_network_requirements_enabled(),
|
||||
self.config.effective_workspace_roots(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
self.config.permissions.effective_permission_profile(),
|
||||
self.config.permissions.network.clone(),
|
||||
self.config.permissions.permission_profile().clone(),
|
||||
self.config.managed_network_requirements_enabled(),
|
||||
self.config.effective_workspace_roots(),
|
||||
)
|
||||
};
|
||||
let started_network_proxy = match network_proxy_spec.as_ref() {
|
||||
Some(spec) => match spec
|
||||
.start_proxy(
|
||||
&network_proxy_permission_profile,
|
||||
managed_proxy_routing_for_windows_sandbox(
|
||||
self.config.effective_local_windows_sandbox_type(),
|
||||
),
|
||||
local_binding_policy_for_sandbox(
|
||||
self.config.effective_local_windows_sandbox_type(),
|
||||
Some(std::env::consts::OS),
|
||||
),
|
||||
/*policy_decider*/ None,
|
||||
/*blocked_request_observer*/ None,
|
||||
managed_network_requirements_enabled,
|
||||
NetworkProxyAuditMetadata::default(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(started) => Some(started),
|
||||
Err(err) => {
|
||||
return Err(internal_error(format!(
|
||||
"failed to start managed network proxy: {err}"
|
||||
)));
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let exec_params = ExecParams {
|
||||
command,
|
||||
cwd: cwd.clone(),
|
||||
expiration,
|
||||
capture_policy,
|
||||
env,
|
||||
network: started_network_proxy
|
||||
.as_ref()
|
||||
.map(akode_core::config::StartedNetworkProxy::proxy),
|
||||
network_environment_id: None,
|
||||
sandbox_permissions: SandboxPermissions::UseDefault,
|
||||
windows_sandbox_level,
|
||||
justification: None,
|
||||
arg0: None,
|
||||
};
|
||||
|
||||
let codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone();
|
||||
let outgoing = self.outgoing.clone();
|
||||
let request_for_task = request.clone();
|
||||
let started_network_proxy_for_task = started_network_proxy;
|
||||
let use_legacy_landlock = self.config.features.use_legacy_landlock();
|
||||
let size = match size.map(crate::command_exec::terminal_size_from_protocol) {
|
||||
Some(Ok(size)) => Some(size),
|
||||
Some(Err(error)) => return Err(error),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let exec_request = akode_core::exec::build_exec_request(
|
||||
exec_params,
|
||||
&effective_permission_profile,
|
||||
&sandbox_cwd,
|
||||
windows_sandbox_workspace_roots.as_slice(),
|
||||
&codex_linux_sandbox_exe,
|
||||
&self.arg0_paths.codex_self_exe,
|
||||
self.config.effective_local_windows_sandbox_type(),
|
||||
use_legacy_landlock,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("exec failed: {err}")))?;
|
||||
self.command_exec_manager
|
||||
.start(StartCommandExecParams {
|
||||
outgoing,
|
||||
request_id: request_for_task,
|
||||
process_id,
|
||||
exec_request,
|
||||
started_network_proxy: started_network_proxy_for_task,
|
||||
tty,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
size,
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
20
akode-rs/app-server/src/request_processors/config_errors.rs
Normal file
20
akode-rs/app-server/src/request_processors/config_errors.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn model_provider_error(provider: &ModelProviderError) -> JSONRPCErrorError {
|
||||
let mut error = invalid_request(provider.to_string());
|
||||
error.data = serde_json::to_value(provider).ok();
|
||||
error
|
||||
}
|
||||
|
||||
pub(crate) fn config_load_error(err: &std::io::Error) -> JSONRPCErrorError {
|
||||
let mut current = err
|
||||
.get_ref()
|
||||
.map(|error| error as &(dyn std::error::Error + 'static));
|
||||
while let Some(source) = current {
|
||||
if let Some(provider_error) = source.downcast_ref::<ModelProviderError>() {
|
||||
return model_provider_error(provider_error);
|
||||
}
|
||||
current = source.source();
|
||||
}
|
||||
invalid_request(format!("failed to load configuration: {err}"))
|
||||
}
|
||||
1298
akode-rs/app-server/src/request_processors/config_processor.rs
Normal file
1298
akode-rs/app-server/src/request_processors/config_processor.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,154 @@
|
||||
//! Regressions for reload entry points composing the final thread configuration.
|
||||
|
||||
use super::config_processor::reload_user_config;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::mcp_refresh::reload_mcp_config;
|
||||
use akode_config::types::AuthKeyringBackendKind;
|
||||
use akode_core::config::ConfigOverrides;
|
||||
use akode_exec_server::EnvironmentManager;
|
||||
use akode_login::CodexAuth;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reloads_accept_a_provider_supplied_by_thread_overrides() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
|
||||
let initial = manager
|
||||
.load_for_cwd(
|
||||
Some(HashMap::from([
|
||||
("model_provider".to_string(), json!("thread-provider")),
|
||||
(
|
||||
"model_providers.thread-provider".to_string(),
|
||||
json!({"name": "Thread provider", "base_url": "https://provider.example/v1", "wire_api": "responses"}),
|
||||
),
|
||||
])),
|
||||
ConfigOverrides::default(),
|
||||
Some(home.path().to_path_buf()),
|
||||
)
|
||||
.await?;
|
||||
let threads = Arc::new(
|
||||
akode_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
initial.model_provider.clone(),
|
||||
initial.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
),
|
||||
);
|
||||
let thread = threads
|
||||
.start_thread(akode_core::StartThreadOptions::new(initial))
|
||||
.await?
|
||||
.thread;
|
||||
|
||||
for enabled in [true, false] {
|
||||
std::fs::write(
|
||||
home.path().join(akode_config::CONFIG_TOML_FILE),
|
||||
format!(
|
||||
"model_provider = 'missing-provider'\n[features]\nsecret_auth_storage = {enabled}\n"
|
||||
),
|
||||
)?;
|
||||
if enabled {
|
||||
reload_mcp_config(&threads, &manager).await?;
|
||||
} else {
|
||||
reload_user_config(&manager, &threads).await;
|
||||
}
|
||||
let config = thread.config().await;
|
||||
assert_eq!(config.model_provider_id, "thread-provider");
|
||||
assert_eq!(
|
||||
config.auth_keyring_backend_kind(),
|
||||
if enabled {
|
||||
AuthKeyringBackendKind::Secrets
|
||||
} else {
|
||||
AuthKeyringBackendKind::Direct
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_reload_promotes_plugin_and_feature_requirements_without_server_changes()
|
||||
-> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let requirements_path = home.path().join("requirements.toml");
|
||||
std::fs::write(&requirements_path, "")?;
|
||||
std::fs::write(
|
||||
home.path().join(akode_config::CONFIG_TOML_FILE),
|
||||
"[features]\nenable_mcp_apps = true\n",
|
||||
)?;
|
||||
let mut overrides = akode_config::LoaderOverrides::without_managed_config_for_tests();
|
||||
overrides.ignore_managed_requirements = false;
|
||||
overrides.system_requirements_path = Some(requirements_path.clone());
|
||||
let manager = ConfigManager::new(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
overrides,
|
||||
/*strict_config*/ false,
|
||||
akode_arg0::Arg0DispatchPaths::default(),
|
||||
Arc::new(akode_config::NoopThreadConfigLoader),
|
||||
);
|
||||
let initial = manager
|
||||
.load_latest_config(Some(home.path().to_path_buf()))
|
||||
.await?;
|
||||
let threads = Arc::new(
|
||||
akode_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
initial.model_provider.clone(),
|
||||
initial.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
),
|
||||
);
|
||||
assert!(
|
||||
initial
|
||||
.features
|
||||
.enabled(akode_features::Feature::EnableMcpApps)
|
||||
);
|
||||
let original_servers = initial.mcp_servers.get().clone();
|
||||
let thread = threads
|
||||
.start_thread(akode_core::StartThreadOptions::new(initial))
|
||||
.await?
|
||||
.thread;
|
||||
std::fs::write(
|
||||
&requirements_path,
|
||||
"[features]\nenable_mcp_apps = false\n[plugins.example.mcp_servers]\n",
|
||||
)?;
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
reload_user_config(&manager, &threads),
|
||||
)
|
||||
.await
|
||||
.expect("policy promotion must terminate");
|
||||
let config = thread.config().await;
|
||||
assert_eq!(config.mcp_servers.get(), &original_servers);
|
||||
assert!(
|
||||
!config
|
||||
.features
|
||||
.enabled(akode_features::Feature::EnableMcpApps)
|
||||
);
|
||||
assert!(
|
||||
config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.plugins
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.value
|
||||
.get("example")
|
||||
.unwrap()
|
||||
.mcp_servers
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.feature_requirements
|
||||
.is_some()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Attempts one new continuation turn immediately after daemon thread restoration.
|
||||
//! Completed or superseded work is discarded; recovery never waits for a later idle event.
|
||||
//! Permissions and the saved local executor selection must match the resumed runtime.
|
||||
|
||||
use super::ThreadRequestProcessor;
|
||||
use akode_app_server_protocol::ThreadEnvironment;
|
||||
use akode_app_server_transport::daemon_recovery::InterruptedTurn;
|
||||
use akode_core::TurnInput;
|
||||
use akode_core::TurnInputRequest;
|
||||
use akode_core::TurnInputSubmission;
|
||||
use akode_core::TurnStartOptions;
|
||||
use akode_core::context::ContextualUserFragment;
|
||||
use akode_core::context::InternalContextSource;
|
||||
use akode_core::context::InternalModelContextFragment;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::EnvironmentConfigState;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::TurnAbortReason;
|
||||
use akode_protocol::protocol::TurnAbortedEvent;
|
||||
use akode_rollout::RolloutItem;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn continue_daemon_turn(&self, thread_id: &str, saved: InterruptedTurn) {
|
||||
let Ok(thread_id) = ThreadId::from_string(thread_id) else {
|
||||
return;
|
||||
};
|
||||
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
|
||||
return;
|
||||
};
|
||||
let Some(path) = thread.rollout_path() else {
|
||||
return;
|
||||
};
|
||||
let history = match akode_rollout::RolloutRecorder::load_rollout_items(&path).await {
|
||||
Ok((history, _, _)) => history,
|
||||
Err(err) => {
|
||||
tracing::warn!(%thread_id, %err, "failed to read interrupted turn history");
|
||||
return;
|
||||
}
|
||||
};
|
||||
// The snapshot has complete recorded input, but the old process may have
|
||||
// completed or replaced its turn during the shutdown grace period.
|
||||
let Some(start) = history
|
||||
.iter()
|
||||
.rposition(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TurnStarted(_))))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !matches!(&history[start], RolloutItem::EventMsg(EventMsg::TurnStarted(event))
|
||||
if event.turn_id == saved.turn_id)
|
||||
|| history[start..].iter().any(|item| match item {
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
|
||||
event.turn_id == saved.turn_id
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => event
|
||||
.turn_id
|
||||
.as_ref()
|
||||
.is_none_or(|turn_id| turn_id == &saved.turn_id),
|
||||
_ => false,
|
||||
})
|
||||
{
|
||||
return;
|
||||
}
|
||||
let previous_context = history.iter().rev().find_map(|item| match item {
|
||||
RolloutItem::TurnContext(context)
|
||||
if context.turn_id.as_ref() == Some(&saved.turn_id) =>
|
||||
{
|
||||
Some(context)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let Some(previous_context) = previous_context else {
|
||||
return;
|
||||
};
|
||||
let config = thread.config_snapshot().await;
|
||||
let [environment] = config.environment_selections() else {
|
||||
return;
|
||||
};
|
||||
if environment.environment_id != akode_exec_server::LOCAL_ENVIRONMENT_ID
|
||||
|| environment.config != EnvironmentConfigState::FromThread
|
||||
|| saved.local_environment.as_ref() != Some(&ThreadEnvironment::from(environment))
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Recovery must not override a stricter saved or newly configured policy.
|
||||
if previous_context.permission_profile != config.permission_profile {
|
||||
return;
|
||||
}
|
||||
let continuation = ContextualUserFragment::into(InternalModelContextFragment::new(
|
||||
InternalContextSource::from_static("daemon_recovery"),
|
||||
"The server restarted and interrupted the previous turn. Continue the unfinished work from the saved conversation. Check the current state before repeating actions that may already have completed.",
|
||||
));
|
||||
let request = TurnInputRequest::new(TurnInput::ResponseItem(continuation)).on_start(
|
||||
TurnStartOptions {
|
||||
turn_trigger: Some("daemon_recovery".to_string()),
|
||||
final_output_json_schema: saved.output_schema,
|
||||
service_tier: saved.service_tier,
|
||||
root_turn_id: previous_context.root_turn_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
// Close the old turn in persisted history before exposing a new running turn.
|
||||
if let Err(err) = thread
|
||||
.append_rollout_items(&[RolloutItem::EventMsg(EventMsg::TurnAborted(
|
||||
TurnAbortedEvent {
|
||||
root_turn_id: None,
|
||||
turn_id: Some(saved.turn_id.clone()),
|
||||
reason: TurnAbortReason::Interrupted,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
))])
|
||||
.await
|
||||
{
|
||||
tracing::warn!(%thread_id, %err, "failed to close interrupted turn history");
|
||||
return;
|
||||
}
|
||||
match thread.continue_turn_if_idle(request, saved.turn_id).await {
|
||||
Ok(TurnInputSubmission::Started { .. }) => {
|
||||
crate::extensions::send_thread_warning(
|
||||
&self.outgoing,
|
||||
&self.thread_state_manager,
|
||||
thread_id,
|
||||
"Resuming interrupted work".to_string(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Ok(TurnInputSubmission::NotSubmitted { reason }) => {
|
||||
tracing::debug!(%thread_id, ?reason, "recovery continuation was not started");
|
||||
}
|
||||
Ok(TurnInputSubmission::Steered { .. } | TurnInputSubmission::Accepted) => {
|
||||
// continue_turn_if_idle uses start_if_idle, which cannot steer or
|
||||
// enter the agent-message path that returns Accepted.
|
||||
unreachable!("continuation must start or decline")
|
||||
}
|
||||
Err(err) => tracing::warn!(%thread_id, %err, "recovery continuation failed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Selects persistent root threads for managed daemon recovery using normal resume semantics.
|
||||
//! Only threads successfully persisted through the existing thread store become candidates.
|
||||
|
||||
use super::ThreadRequestProcessor;
|
||||
use akode_app_server_transport::daemon_recovery::InterruptedTurn;
|
||||
use akode_app_server_transport::daemon_recovery::RecoverySnapshot;
|
||||
use akode_thread_store::PersistContext;
|
||||
use tracing::warn;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "snapshot selection must be serialized against pending unloads"
|
||||
)]
|
||||
pub(crate) async fn daemon_recovery_snapshot(&self) -> RecoverySnapshot {
|
||||
let mut snapshot = RecoverySnapshot::default();
|
||||
for thread_id in self.thread_manager.list_thread_ids().await {
|
||||
let pending_unloads = self.pending_thread_unloads.lock().await;
|
||||
if pending_unloads.contains_key(&thread_id) {
|
||||
continue;
|
||||
}
|
||||
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
|
||||
continue;
|
||||
};
|
||||
let config = thread.config_snapshot().await;
|
||||
if !config.ephemeral
|
||||
&& config.parent_thread_id.is_none()
|
||||
&& !config.session_source.is_non_root_agent()
|
||||
{
|
||||
let interrupted = thread.interrupted_turn().await;
|
||||
if let Err(err) = self
|
||||
.thread_store
|
||||
.persist_thread(thread_id, PersistContext::Standard)
|
||||
.await
|
||||
{
|
||||
warn!(%thread_id, %err, "skipping daemon restore for thread that could not be persisted");
|
||||
continue;
|
||||
}
|
||||
snapshot.loaded.insert(thread_id.to_string());
|
||||
if let Some((turn_id, options, environment)) = interrupted {
|
||||
snapshot.interrupted.insert(
|
||||
thread_id.to_string(),
|
||||
InterruptedTurn {
|
||||
turn_id,
|
||||
output_schema: options.final_output_json_schema,
|
||||
service_tier: options.service_tier,
|
||||
local_environment: Some((&environment).into()),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
23
akode-rs/app-server/src/request_processors/diagnostics.rs
Normal file
23
akode-rs/app-server/src/request_processors/diagnostics.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use akode_app_server_protocol::ServerDiagnosticsGauge;
|
||||
use akode_app_server_protocol::ServerDiagnosticsProcess;
|
||||
use akode_app_server_protocol::ServerDiagnosticsResponse;
|
||||
|
||||
pub(crate) fn read_server_diagnostics() -> ServerDiagnosticsResponse {
|
||||
let diagnostics = akode_diagnostics::snapshot();
|
||||
|
||||
ServerDiagnosticsResponse {
|
||||
process: ServerDiagnosticsProcess {
|
||||
id: diagnostics.process.id,
|
||||
resident_memory_bytes: diagnostics.process.resident_memory_bytes,
|
||||
physical_footprint_bytes: diagnostics.process.physical_footprint_bytes,
|
||||
},
|
||||
gauges: diagnostics
|
||||
.gauges
|
||||
.into_iter()
|
||||
.map(|gauge| ServerDiagnosticsGauge {
|
||||
name: gauge.name.to_string(),
|
||||
value: gauge.value,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
use super::*;
|
||||
use akode_config::ScopedSkillsConfig;
|
||||
use akode_exec_server::RemoteEnvironmentOptions;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct EnvironmentRequestProcessor {
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
}
|
||||
|
||||
impl EnvironmentRequestProcessor {
|
||||
pub(crate) fn new(environment_manager: Arc<EnvironmentManager>) -> Self {
|
||||
Self {
|
||||
environment_manager,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn environment_add(
|
||||
&self,
|
||||
params: EnvironmentAddParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let skills = ScopedSkillsConfig {
|
||||
required: params
|
||||
.skills
|
||||
.and_then(|skills| skills.required)
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let options = RemoteEnvironmentOptions {
|
||||
exec_server_url: params.exec_server_url,
|
||||
connect_timeout: params.connect_timeout_ms.map(Duration::from_millis),
|
||||
http_headers: params
|
||||
.auth_bearer_token
|
||||
.into_iter()
|
||||
.map(|token| {
|
||||
(
|
||||
"Authorization".to_string(),
|
||||
format!("Bearer {}", token.into_inner()),
|
||||
)
|
||||
})
|
||||
.chain(
|
||||
params
|
||||
.websocket_request_id
|
||||
.map(|request_id| ("X-Request-ID".to_string(), request_id)),
|
||||
)
|
||||
.collect(),
|
||||
};
|
||||
self.environment_manager
|
||||
.upsert_environment_with_options(params.environment_id, options, skills)
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
Ok(Some(EnvironmentAddResponse {}.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn environment_info(
|
||||
&self,
|
||||
params: EnvironmentInfoParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let environment_id = params.environment_id;
|
||||
let environment = self
|
||||
.environment_manager
|
||||
.get_environment(&environment_id)
|
||||
.ok_or_else(|| invalid_request(format!("unknown environment id `{environment_id}`")))?;
|
||||
let info = environment.force_info().await.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to get info for environment `{environment_id}`: {err}"
|
||||
))
|
||||
})?;
|
||||
Ok(Some(
|
||||
EnvironmentInfoResponse {
|
||||
shell: EnvironmentShellInfo {
|
||||
name: info.shell.name,
|
||||
path: info.shell.path,
|
||||
},
|
||||
cwd: info.cwd,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn environment_status(
|
||||
&self,
|
||||
params: EnvironmentStatusParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let environment_id = params.environment_id;
|
||||
let (status, error) = match self
|
||||
.environment_manager
|
||||
.get_environment_status(&environment_id)
|
||||
.await
|
||||
{
|
||||
Some(EnvironmentObservedStatus::Ready) => (EnvironmentStatusKind::Ready, None),
|
||||
Some(EnvironmentObservedStatus::Pending) => (EnvironmentStatusKind::Pending, None),
|
||||
Some(EnvironmentObservedStatus::Disconnected { error }) => {
|
||||
(EnvironmentStatusKind::Disconnected, Some(error))
|
||||
}
|
||||
None => (
|
||||
EnvironmentStatusKind::Unknown,
|
||||
Some(format!("unknown environment id `{environment_id}`")),
|
||||
),
|
||||
};
|
||||
Ok(Some(EnvironmentStatusResponse { status, error }.into()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! Builds a redacted doctor report attachment for feedback uploads.
|
||||
//!
|
||||
//! Feedback upload should never depend on doctor succeeding. This module runs
|
||||
//! the configured Codex executable as a subprocess, accepts only valid JSON from
|
||||
//! `akode doctor --json --feedback`, derives a small set of report tags, and otherwise
|
||||
//! skips the attachment with a warning. Keeping the report generation out of the
|
||||
//! app-server process avoids sharing doctor internals across crates while still
|
||||
//! using the CLI's JSON report format with bounded database scans.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_core::config::Config;
|
||||
use akode_feedback::DOCTOR_REPORT_ATTACHMENT_FILENAME;
|
||||
use akode_feedback::FeedbackAttachment;
|
||||
use serde_json::Value;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use tracing::warn;
|
||||
|
||||
// Keep the existing 25-second diagnostic allowance plus the filesystem
|
||||
// probe budget (eight seconds) and a small amount of process overhead.
|
||||
const DOCTOR_FEEDBACK_REPORT_TIMEOUT: Duration = Duration::from_secs(35);
|
||||
const MAX_DOCTOR_TAG_VALUE_LEN: usize = 256;
|
||||
|
||||
/// Redacted doctor report data that can be merged into a feedback upload.
|
||||
pub(crate) struct DoctorFeedbackReport {
|
||||
/// JSON support report to upload as `codex-doctor-report.json`.
|
||||
pub(crate) attachment: FeedbackAttachment,
|
||||
/// Low-cardinality report tags derived from the report status and check ids.
|
||||
pub(crate) tags: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// Runs `akode --cd <workspace> doctor --json --feedback` and returns a best-effort
|
||||
/// feedback attachment.
|
||||
///
|
||||
/// Failure to spawn Codex, finish before the timeout, or parse JSON means the
|
||||
/// feedback upload proceeds without the doctor report. Callers should merge the
|
||||
/// returned tags without overriding explicit client-provided tags.
|
||||
pub(crate) async fn doctor_feedback_report(
|
||||
config: &Config,
|
||||
workspace: &Path,
|
||||
) -> Option<DoctorFeedbackReport> {
|
||||
let executable = config
|
||||
.codex_self_exe
|
||||
.clone()
|
||||
.or_else(|| std::env::current_exe().ok())?;
|
||||
|
||||
let mut command = doctor_command(&executable, workspace, config.codex_home.as_path());
|
||||
command.stdin(Stdio::null());
|
||||
command.kill_on_drop(/*kill_on_drop*/ true);
|
||||
let output = match timeout(DOCTOR_FEEDBACK_REPORT_TIMEOUT, command.output()).await {
|
||||
Ok(Ok(output)) => output,
|
||||
Ok(Err(err)) => {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
error = %err,
|
||||
"failed to run doctor report for feedback; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Err(_) => {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
"timed out running doctor report for feedback; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let Some(json_start) = stdout.find('{') else {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
status = %output.status,
|
||||
stderr = %String::from_utf8_lossy(&output.stderr),
|
||||
"doctor report for feedback did not produce JSON; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
let json = stdout[json_start..].trim();
|
||||
let report: Value = match serde_json::from_str(json) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
executable = %executable.display(),
|
||||
status = %output.status,
|
||||
error = %err,
|
||||
"doctor report for feedback was not valid JSON; skipping attachment"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let pretty = serde_json::to_vec_pretty(&report).unwrap_or_else(|_| json.as_bytes().to_vec());
|
||||
Some(DoctorFeedbackReport {
|
||||
tags: doctor_report_tags(&report),
|
||||
attachment: FeedbackAttachment {
|
||||
filename: DOCTOR_REPORT_ATTACHMENT_FILENAME.to_string(),
|
||||
content_type: Some("application/json".to_string()),
|
||||
buffer: pretty,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn doctor_command(executable: &Path, cwd: &Path, codex_home: &Path) -> Command {
|
||||
let mut command = Command::from(akode_utils_process::background_command(executable));
|
||||
command
|
||||
.arg("--cd")
|
||||
.arg(cwd)
|
||||
.arg("doctor")
|
||||
.arg("--json")
|
||||
.arg("--feedback")
|
||||
.current_dir(codex_home)
|
||||
.env("AKODE_HOME", codex_home);
|
||||
command
|
||||
}
|
||||
|
||||
fn doctor_report_tags(report: &Value) -> BTreeMap<String, String> {
|
||||
let mut tags = BTreeMap::new();
|
||||
if let Some(overall_status) = report.get("overallStatus").and_then(Value::as_str) {
|
||||
tags.insert(
|
||||
"doctor_overall_status".to_string(),
|
||||
truncate_tag_value(overall_status),
|
||||
);
|
||||
}
|
||||
|
||||
let mut ok_count = 0usize;
|
||||
let mut warning_count = 0usize;
|
||||
let mut fail_count = 0usize;
|
||||
let mut failed_checks = Vec::new();
|
||||
let mut warning_checks = Vec::new();
|
||||
if let Some(checks) = report.get("checks") {
|
||||
for check in check_values(checks) {
|
||||
let status = check.get("status").and_then(Value::as_str);
|
||||
let id = check.get("id").and_then(Value::as_str).unwrap_or("unknown");
|
||||
match status {
|
||||
Some("ok") => ok_count += 1,
|
||||
Some("warning") => {
|
||||
warning_count += 1;
|
||||
warning_checks.push(id.to_string());
|
||||
}
|
||||
Some("fail") => {
|
||||
fail_count += 1;
|
||||
failed_checks.push(id.to_string());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
tags.insert("doctor_ok_count".to_string(), ok_count.to_string());
|
||||
tags.insert(
|
||||
"doctor_warning_count".to_string(),
|
||||
warning_count.to_string(),
|
||||
);
|
||||
tags.insert("doctor_fail_count".to_string(), fail_count.to_string());
|
||||
if !failed_checks.is_empty() {
|
||||
tags.insert(
|
||||
"doctor_failed_checks".to_string(),
|
||||
truncate_tag_value(&failed_checks.join(",")),
|
||||
);
|
||||
}
|
||||
if !warning_checks.is_empty() {
|
||||
tags.insert(
|
||||
"doctor_warning_checks".to_string(),
|
||||
truncate_tag_value(&warning_checks.join(",")),
|
||||
);
|
||||
}
|
||||
|
||||
tags
|
||||
}
|
||||
|
||||
/// Iterates checks from both the current keyed JSON shape and older array reports.
|
||||
fn check_values(checks: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
|
||||
match checks {
|
||||
Value::Array(values) => Box::new(values.iter()),
|
||||
Value::Object(values) => Box::new(values.values()),
|
||||
_ => Box::new(std::iter::empty()),
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_tag_value(value: &str) -> String {
|
||||
if value.chars().count() <= MAX_DOCTOR_TAG_VALUE_LEN {
|
||||
return value.to_string();
|
||||
}
|
||||
let prefix = value
|
||||
.chars()
|
||||
.take(MAX_DOCTOR_TAG_VALUE_LEN.saturating_sub(3))
|
||||
.collect::<String>();
|
||||
format!("{prefix}...")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn doctor_command_keeps_missing_workspace_out_of_process_cwd() {
|
||||
let codex_home = tempdir().expect("codex home");
|
||||
let workspace = codex_home.path().join("deleted-workspace");
|
||||
|
||||
let command = doctor_command(Path::new("codex"), &workspace, codex_home.path());
|
||||
let command = command.as_std();
|
||||
|
||||
assert_eq!(command.get_current_dir(), Some(codex_home.path()));
|
||||
assert_eq!(
|
||||
command.get_args().collect::<Vec<_>>(),
|
||||
[
|
||||
"--cd".as_ref(),
|
||||
workspace.as_os_str(),
|
||||
"doctor".as_ref(),
|
||||
"--json".as_ref(),
|
||||
"--feedback".as_ref()
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
command.get_envs().collect::<Vec<_>>(),
|
||||
[("AKODE_HOME".as_ref(), Some(codex_home.path().as_os_str()))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doctor_report_tags_summarize_status_counts() {
|
||||
let report = json!({
|
||||
"overallStatus": "fail",
|
||||
"checks": {
|
||||
"runtime.provenance": {"id": "runtime.provenance", "status": "ok"},
|
||||
"websocket.reachability": {
|
||||
"id": "websocket.reachability",
|
||||
"status": "warning"
|
||||
},
|
||||
"auth.credentials": {"id": "auth.credentials", "status": "fail"}
|
||||
}
|
||||
});
|
||||
|
||||
let tags = doctor_report_tags(&report);
|
||||
|
||||
let expected = BTreeMap::from([
|
||||
("doctor_fail_count".to_string(), "1".to_string()),
|
||||
(
|
||||
"doctor_failed_checks".to_string(),
|
||||
"auth.credentials".to_string(),
|
||||
),
|
||||
("doctor_ok_count".to_string(), "1".to_string()),
|
||||
("doctor_overall_status".to_string(), "fail".to_string()),
|
||||
(
|
||||
"doctor_warning_checks".to_string(),
|
||||
"websocket.reachability".to_string(),
|
||||
),
|
||||
("doctor_warning_count".to_string(), "1".to_string()),
|
||||
]);
|
||||
assert_eq!(tags, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Exercises SQLite log collection, legacy storage, and feedback snapshot ordering.
|
||||
use super::*;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_state::SqliteConfig;
|
||||
use akode_state::StateRuntime;
|
||||
use akode_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum Scenario {
|
||||
Healthy,
|
||||
WriteFailure,
|
||||
Corruption,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_includes_flush_and_query_failures_in_the_same_submission() -> anyhow::Result<()> {
|
||||
for scenario in [
|
||||
Scenario::Healthy,
|
||||
Scenario::WriteFailure,
|
||||
Scenario::Corruption,
|
||||
] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = core_test_support::load_default_config_for_test(&home).await;
|
||||
let sqlite = &config.sqlite;
|
||||
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
|
||||
let pool = sqlite.open_read_write_pool(&sqlite.logs_db_path()).await?;
|
||||
let feedback = CodexFeedback::new();
|
||||
let writer =
|
||||
akode_state::log_db::start(runtime.clone(), std::sync::Arc::new(feedback.clone()));
|
||||
let _guard = tracing_subscriber::registry()
|
||||
.with(feedback.logger_layer())
|
||||
.with(writer.clone())
|
||||
.set_default();
|
||||
let thread_id = ThreadId::new();
|
||||
tracing::info_span!("thread", thread_id = %thread_id)
|
||||
.in_scope(|| tracing::info!("persisted log"));
|
||||
writer.flush().await;
|
||||
match scenario {
|
||||
Scenario::WriteFailure => {
|
||||
sqlx::query("CREATE TRIGGER fail_log_insert BEFORE INSERT ON logs BEGIN SELECT RAISE(ABORT, 'synthetic-secret'); END").execute(&pool).await?;
|
||||
}
|
||||
Scenario::Corruption => {
|
||||
sqlx::raw_sql("PRAGMA writable_schema = ON; UPDATE sqlite_schema SET rootpage = 2147483647 WHERE name = 'logs'; PRAGMA schema_version = 1000000;").execute(&pool).await?;
|
||||
}
|
||||
Scenario::Healthy => {}
|
||||
}
|
||||
let snapshot = feedback.snapshot(Some(thread_id));
|
||||
tracing::info_span!("thread", thread_id = %thread_id)
|
||||
.in_scope(|| tracing::info!("latest log"));
|
||||
let (snapshot, sqlite_logs, legacy_logs) = collect_feedback_logs(
|
||||
&feedback,
|
||||
Some(&writer),
|
||||
Some(&runtime),
|
||||
&config,
|
||||
snapshot,
|
||||
&[thread_id],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(legacy_logs, None);
|
||||
assert_eq!(sqlite_logs.is_some(), scenario == Scenario::Healthy);
|
||||
let logs = String::from_utf8(snapshot.log_attachment(sqlite_logs).buffer)?;
|
||||
assert!(logs.contains("persisted log"));
|
||||
assert!(logs.contains("latest log"));
|
||||
let expected_error = match scenario {
|
||||
Scenario::Healthy => None,
|
||||
Scenario::WriteFailure => Some("constraint"),
|
||||
Scenario::Corruption => Some("corrupt"),
|
||||
};
|
||||
assert_eq!(
|
||||
logs.matches("failed to flush logs to SQLite").count(),
|
||||
usize::from(expected_error.is_some())
|
||||
);
|
||||
if let Some(error) = expected_error {
|
||||
assert!(logs.contains(&format!("failed to flush logs to SQLite error={error:?}")));
|
||||
}
|
||||
assert_eq!(
|
||||
logs.contains("failed to query feedback logs from sqlite"),
|
||||
scenario == Scenario::Corruption
|
||||
);
|
||||
pool.close().await;
|
||||
runtime.close().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_preserves_legacy_logs_when_the_directory_is_unset_or_current_logs_are_empty()
|
||||
-> anyhow::Result<()> {
|
||||
for configured_log_dir in [false, true] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let sqlite_home = home.path().join("sqlite");
|
||||
let mut overrides = vec![(
|
||||
"sqlite_home".to_string(),
|
||||
toml::Value::String(sqlite_home.to_string_lossy().into_owned()),
|
||||
)];
|
||||
if configured_log_dir {
|
||||
overrides.push((
|
||||
"log_dir".to_string(),
|
||||
toml::Value::String(home.path().join("log").to_string_lossy().into_owned()),
|
||||
));
|
||||
}
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(akode_config::LoaderOverrides::without_managed_config_for_tests())
|
||||
.cli_overrides(overrides)
|
||||
.build()
|
||||
.await?;
|
||||
let legacy_sqlite = SqliteConfig::new_for_testing(sqlite_home.abs());
|
||||
let legacy = StateRuntime::init(legacy_sqlite.clone(), "test-provider".to_string()).await?;
|
||||
let pool = legacy_sqlite
|
||||
.open_read_write_pool(&legacy_sqlite.logs_db_path())
|
||||
.await?;
|
||||
let thread_id = ThreadId::new();
|
||||
let now = chrono::Utc::now();
|
||||
let timestamp = now.format("%Y-%m-%dT%H:%M:%S.000000Z");
|
||||
for (id, body) in [
|
||||
(thread_id, "legacy history"),
|
||||
(ThreadId::new(), "unrelated history"),
|
||||
] {
|
||||
sqlx::query(
|
||||
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id)
|
||||
VALUES (?, 0, 'INFO', 'test', ?, ?)",
|
||||
)
|
||||
.bind(now.timestamp())
|
||||
.bind(body)
|
||||
.bind(id.to_string())
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
pool.close().await;
|
||||
legacy.close().await;
|
||||
let legacy_before = std::fs::read(legacy_sqlite.logs_db_path())?;
|
||||
|
||||
let runtime =
|
||||
StateRuntime::init(config.sqlite.clone(), "test-provider".to_string()).await?;
|
||||
let pool = config
|
||||
.sqlite
|
||||
.open_read_write_pool(&config.sqlite.logs_db_path())
|
||||
.await?;
|
||||
let feedback = CodexFeedback::new();
|
||||
for current_has_logs in [false, true] {
|
||||
if current_has_logs {
|
||||
sqlx::query(
|
||||
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id)
|
||||
VALUES (?, 0, 'INFO', 'test', 'current history', ?)",
|
||||
)
|
||||
.bind(now.timestamp())
|
||||
.bind(thread_id.to_string())
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
let (_, current_logs, legacy_logs) = collect_feedback_logs(
|
||||
&feedback,
|
||||
/*log_db*/ None,
|
||||
Some(&runtime),
|
||||
&config,
|
||||
feedback.snapshot(Some(thread_id)),
|
||||
&[thread_id],
|
||||
)
|
||||
.await;
|
||||
let mut expected_current = String::new();
|
||||
if !configured_log_dir {
|
||||
expected_current.push_str(&format!("{timestamp} INFO legacy history\n"));
|
||||
}
|
||||
if current_has_logs {
|
||||
expected_current.push_str(&format!("{timestamp} INFO current history\n"));
|
||||
}
|
||||
assert_eq!(
|
||||
current_logs,
|
||||
(!expected_current.is_empty()).then(|| expected_current.into_bytes())
|
||||
);
|
||||
assert_eq!(
|
||||
legacy_logs,
|
||||
(configured_log_dir && !current_has_logs)
|
||||
.then(|| format!("{timestamp} INFO legacy history\n").into_bytes())
|
||||
);
|
||||
}
|
||||
if configured_log_dir {
|
||||
assert_eq!(std::fs::read(legacy_sqlite.logs_db_path())?, legacy_before);
|
||||
}
|
||||
pool.close().await;
|
||||
runtime.close().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
798
akode-rs/app-server/src/request_processors/feedback_processor.rs
Normal file
798
akode-rs/app-server/src/request_processors/feedback_processor.rs
Normal file
@@ -0,0 +1,798 @@
|
||||
use super::feedback_thread_index::FeedbackThreadIndex;
|
||||
use super::*;
|
||||
use crate::error_code::OVERLOADED_ERROR_CODE;
|
||||
use akode_app_server_protocol::FeedbackSaveParams;
|
||||
use akode_app_server_protocol::FeedbackSaveResponse;
|
||||
use akode_feedback::FeedbackAttachment;
|
||||
use akode_feedback::FeedbackSnapshot;
|
||||
#[cfg(target_os = "windows")]
|
||||
use akode_feedback::WINDOWS_SANDBOX_LOG_ATTACHMENT_FILENAME;
|
||||
use akode_feedback::guardian_review_failures;
|
||||
use akode_rollout::RolloutRecorder;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::LegacyAppPathString;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::path::Path;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
struct SavedFeedback {
|
||||
thread_id: String,
|
||||
prompt_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FeedbackRequestProcessor {
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config: Arc<Config>,
|
||||
feedback: CodexFeedback,
|
||||
log_db: Option<LogDbLayer>,
|
||||
state_db: Option<StateDbHandle>,
|
||||
saves: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl FeedbackRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config: Arc<Config>,
|
||||
feedback: CodexFeedback,
|
||||
log_db: Option<LogDbLayer>,
|
||||
state_db: Option<StateDbHandle>,
|
||||
) -> Self {
|
||||
Self {
|
||||
thread_manager,
|
||||
config,
|
||||
feedback,
|
||||
log_db,
|
||||
state_db,
|
||||
saves: Arc::new(Semaphore::new(/*permits*/ 3)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn feedback_save(
|
||||
&self,
|
||||
params: FeedbackSaveParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
if !Path::new(params.save_path.as_str()).is_absolute() {
|
||||
return Err(invalid_request(
|
||||
"feedback savePath must be an absolute host path",
|
||||
));
|
||||
}
|
||||
let save_path = AbsolutePathBuf::try_from(params.save_path)
|
||||
.map_err(|error| invalid_request(format!("invalid feedback savePath: {error}")))?;
|
||||
let saved_path = LegacyAppPathString::from_abs_path(&save_path);
|
||||
let response = self.feedback_response(params.feedback, save_path).await?;
|
||||
Ok(Some(
|
||||
FeedbackSaveResponse {
|
||||
saved_path,
|
||||
thread_id: response.thread_id,
|
||||
prompt_hash: response.prompt_hash,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn feedback_response(
|
||||
&self,
|
||||
params: FeedbackReportParams,
|
||||
save_path: AbsolutePathBuf,
|
||||
) -> Result<SavedFeedback, JSONRPCErrorError> {
|
||||
let permit = self
|
||||
.saves
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| JSONRPCErrorError {
|
||||
code: OVERLOADED_ERROR_CODE,
|
||||
message:
|
||||
"Three feedback saves are already in progress; try again after one finishes"
|
||||
.to_string(),
|
||||
data: None,
|
||||
})?;
|
||||
|
||||
let FeedbackReportParams {
|
||||
classification,
|
||||
reason,
|
||||
thread_id,
|
||||
include_logs,
|
||||
extra_log_files,
|
||||
tags,
|
||||
} = params;
|
||||
let mut report_tags = tags.unwrap_or_default();
|
||||
|
||||
let conversation_id = match thread_id.as_deref() {
|
||||
Some(thread_id) => match ThreadId::from_string(thread_id) {
|
||||
Ok(conversation_id) => Some(conversation_id),
|
||||
Err(err) => return Err(invalid_request(format!("invalid thread id: {err}"))),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
|
||||
let turn_metadata = if let Some(conversation_id) = conversation_id
|
||||
&& let Some(rollout_path) = self
|
||||
.resolve_rollout_path(conversation_id, self.state_db.as_ref())
|
||||
.await?
|
||||
{
|
||||
feedback_turn_metadata_from_rollout(
|
||||
&rollout_path,
|
||||
report_tags.get("turn_id").map(String::as_str),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
apply_feedback_turn_metadata(&mut report_tags, turn_metadata);
|
||||
let prompt_hash = report_tags.get("prompt_hash").cloned();
|
||||
|
||||
let snapshot = self.feedback.snapshot(conversation_id);
|
||||
let mut extra_attachments = Vec::new();
|
||||
let mut feedback_index = None;
|
||||
let (snapshot, sqlite_feedback_logs, state_db_ctx) = if include_logs {
|
||||
let state_db_ctx = self.state_db.clone();
|
||||
let mut feedback_thread_ids = match conversation_id {
|
||||
Some(conversation_id) => match self
|
||||
.thread_manager
|
||||
.list_agent_subtree_thread_ids(conversation_id)
|
||||
.await
|
||||
{
|
||||
Ok(thread_ids) => thread_ids,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to list feedback subtree for thread_id={conversation_id}: {err}"
|
||||
);
|
||||
vec![conversation_id]
|
||||
}
|
||||
},
|
||||
None => Vec::new(),
|
||||
};
|
||||
if let (Some(state_db), Some(thread_id)) = (&state_db_ctx, conversation_id) {
|
||||
match state_db.list_attached_thread_ids(thread_id).await {
|
||||
Ok(attached_ids) => feedback_thread_ids.extend(attached_ids),
|
||||
Err(err) => {
|
||||
warn!("failed to list attached threads for feedback on {thread_id}: {err}")
|
||||
}
|
||||
}
|
||||
}
|
||||
let failures =
|
||||
guardian_review_failures(state_db_ctx.as_deref(), &feedback_thread_ids).await;
|
||||
if let Some(conversation_id) = conversation_id {
|
||||
let index =
|
||||
FeedbackThreadIndex::new(conversation_id, feedback_thread_ids, &failures);
|
||||
feedback_thread_ids = index
|
||||
.threads
|
||||
.iter()
|
||||
.map(|thread| thread.thread_id)
|
||||
.collect();
|
||||
feedback_index = Some(index);
|
||||
}
|
||||
extra_attachments.extend(failures.attachment);
|
||||
let (snapshot, sqlite_feedback_logs, legacy_logs) = collect_feedback_logs(
|
||||
&self.feedback,
|
||||
self.log_db.as_ref(),
|
||||
state_db_ctx.as_ref(),
|
||||
&self.config,
|
||||
snapshot,
|
||||
&feedback_thread_ids,
|
||||
)
|
||||
.await;
|
||||
if let Some(buffer) = legacy_logs {
|
||||
extra_attachments.push(FeedbackAttachment {
|
||||
filename: "codex-logs-legacy.log".to_string(),
|
||||
content_type: Some("text/plain".to_string()),
|
||||
buffer,
|
||||
});
|
||||
}
|
||||
(snapshot, sqlite_feedback_logs, state_db_ctx)
|
||||
} else {
|
||||
(snapshot, None, None)
|
||||
};
|
||||
let thread_id = snapshot.thread_id.clone();
|
||||
|
||||
let mut attachment_paths = Vec::new();
|
||||
let mut seen_attachment_paths = HashSet::new();
|
||||
// Keep actor/reviewer pairs together: reported thread, recent failed-review
|
||||
// children, then newest remaining children. Captured failures precede these files.
|
||||
if include_logs {
|
||||
for thread in feedback_index
|
||||
.iter_mut()
|
||||
.flat_map(|index| &mut index.threads)
|
||||
{
|
||||
if let Some(rollout_path) = self
|
||||
.resolve_rollout_path(thread.thread_id, state_db_ctx.as_ref())
|
||||
.await?
|
||||
&& seen_attachment_paths.insert(rollout_path.clone())
|
||||
{
|
||||
thread.rollout_filename = akode_rollout::plain_rollout_path(&rollout_path)
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned());
|
||||
attachment_paths.push(FeedbackAttachmentPath {
|
||||
path: rollout_path,
|
||||
attachment_filename_override: None,
|
||||
});
|
||||
}
|
||||
if let Ok(conversation) = self.thread_manager.get_thread(thread.thread_id).await
|
||||
&& let Some(guardian_rollout_path) =
|
||||
conversation.guardian_trunk_rollout_path().await
|
||||
&& seen_attachment_paths.insert(guardian_rollout_path.clone())
|
||||
{
|
||||
let filename = auto_review_rollout_filename(thread.thread_id);
|
||||
thread.guardian_rollout_filename = Some(filename.clone());
|
||||
attachment_paths.push(FeedbackAttachmentPath {
|
||||
path: guardian_rollout_path,
|
||||
attachment_filename_override: Some(filename),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(index) = feedback_index {
|
||||
match index.attachment() {
|
||||
Ok(attachment) => extra_attachments.insert(0, attachment),
|
||||
Err(err) => warn!("failed to serialize feedback thread index: {err}"),
|
||||
}
|
||||
}
|
||||
if let Some(sandbox_log_attachment) =
|
||||
windows_sandbox_log_attachment(&self.config.codex_home)
|
||||
&& seen_attachment_paths.insert(sandbox_log_attachment.path.clone())
|
||||
{
|
||||
attachment_paths.push(sandbox_log_attachment);
|
||||
}
|
||||
}
|
||||
if let Some(extra_log_files) = extra_log_files {
|
||||
for extra_log_file in extra_log_files {
|
||||
if seen_attachment_paths.insert(extra_log_file.clone()) {
|
||||
attachment_paths.push(FeedbackAttachmentPath {
|
||||
path: extra_log_file,
|
||||
attachment_filename_override: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if include_logs {
|
||||
let doctor_cwd = feedback_cwd(
|
||||
&self.thread_manager,
|
||||
self.state_db.as_ref(),
|
||||
conversation_id,
|
||||
self.config.cwd.as_path(),
|
||||
)
|
||||
.await;
|
||||
if let Some(doctor_report) =
|
||||
super::feedback_doctor_report::doctor_feedback_report(&self.config, &doctor_cwd)
|
||||
.await
|
||||
{
|
||||
extra_attachments.push(doctor_report.attachment);
|
||||
for (key, value) in doctor_report.tags {
|
||||
report_tags.entry(key).or_insert(value);
|
||||
}
|
||||
}
|
||||
extra_attachments.extend(
|
||||
super::feedback_rollout_history::history_base_attachments(
|
||||
&self.config.codex_home,
|
||||
&attachment_paths,
|
||||
)
|
||||
.await,
|
||||
);
|
||||
}
|
||||
|
||||
let session_source = self.thread_manager.session_source();
|
||||
let codex_home = self.config.codex_home.clone();
|
||||
|
||||
let save_result = tokio::task::spawn_blocking(move || {
|
||||
// Cancelling the RPC waiter must not release a still-running save's slot.
|
||||
let _permit = permit;
|
||||
if include_logs {
|
||||
extra_attachments
|
||||
.extend(akode_feedback::daemon_log_attachments(codex_home.as_path()));
|
||||
}
|
||||
let tags = (!report_tags.is_empty()).then_some(&report_tags);
|
||||
let options = FeedbackSaveOptions {
|
||||
classification: &classification,
|
||||
reason: reason.as_deref(),
|
||||
tags,
|
||||
include_logs,
|
||||
extra_attachments,
|
||||
extra_attachment_paths: &attachment_paths,
|
||||
session_source: Some(session_source),
|
||||
logs_override: sqlite_feedback_logs,
|
||||
};
|
||||
snapshot.save_feedback(options, save_path.as_path())
|
||||
})
|
||||
.await;
|
||||
|
||||
let save_result = match save_result {
|
||||
Ok(result) => result,
|
||||
Err(join_err) => {
|
||||
return Err(internal_error(format!(
|
||||
"failed to save feedback: {join_err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
save_result.map_err(|err| internal_error(format!("failed to save feedback: {err:#}")))?;
|
||||
Ok(SavedFeedback {
|
||||
thread_id,
|
||||
prompt_hash,
|
||||
})
|
||||
}
|
||||
|
||||
async fn resolve_rollout_path(
|
||||
&self,
|
||||
conversation_id: ThreadId,
|
||||
state_db_ctx: Option<&StateDbHandle>,
|
||||
) -> Result<Option<PathBuf>, JSONRPCErrorError> {
|
||||
if let Ok(conversation) = self.thread_manager.get_thread(conversation_id).await {
|
||||
// Explicit extraLogFiles are collected separately and remain strict, even
|
||||
// when they name this same not-yet-materialized automatic rollout.
|
||||
return conversation.feedback_rollout_path().await.map_err(|error| {
|
||||
internal_error(format!("failed to select feedback rollout: {error}"))
|
||||
});
|
||||
}
|
||||
|
||||
let Some(state_db_ctx) = state_db_ctx else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(state_db_ctx
|
||||
.find_rollout_path_by_id(conversation_id, /*archived_only*/ None)
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
warn!("failed to resolve rollout path for thread_id={conversation_id}: {err}");
|
||||
None
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
async fn feedback_cwd(
|
||||
thread_manager: &ThreadManager,
|
||||
state_db: Option<&StateDbHandle>,
|
||||
conversation_id: Option<ThreadId>,
|
||||
fallback_cwd: &Path,
|
||||
) -> PathBuf {
|
||||
let Some(conversation_id) = conversation_id else {
|
||||
return fallback_cwd.to_path_buf();
|
||||
};
|
||||
|
||||
if let Ok(conversation) = thread_manager.get_thread(conversation_id).await {
|
||||
return conversation.config_snapshot().await.cwd().to_path_buf();
|
||||
}
|
||||
|
||||
let Some(state_db) = state_db else {
|
||||
return fallback_cwd.to_path_buf();
|
||||
};
|
||||
match state_db.get_thread(conversation_id).await {
|
||||
Ok(Some(metadata)) => metadata.cwd,
|
||||
Ok(None) => fallback_cwd.to_path_buf(),
|
||||
Err(err) => {
|
||||
warn!("failed to resolve cwd for feedback thread_id={conversation_id}: {err}");
|
||||
fallback_cwd.to_path_buf()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct FeedbackTurnMetadata {
|
||||
model: String,
|
||||
effort: Option<ReasoningEffort>,
|
||||
prompt_hash: Option<String>,
|
||||
}
|
||||
|
||||
fn apply_feedback_turn_metadata(
|
||||
report_tags: &mut BTreeMap<String, String>,
|
||||
turn_metadata: Option<FeedbackTurnMetadata>,
|
||||
) {
|
||||
// These are reserved tags derived from the persisted rollout rather than
|
||||
// accepted from the feedback request.
|
||||
report_tags.remove("prompt_hash");
|
||||
report_tags.remove("prompt_version");
|
||||
|
||||
if let Some(FeedbackTurnMetadata {
|
||||
model,
|
||||
effort,
|
||||
prompt_hash,
|
||||
}) = turn_metadata
|
||||
{
|
||||
report_tags.insert("model".to_string(), model);
|
||||
report_tags.insert("effort".to_string(), format!("{effort:?}"));
|
||||
if let Some(prompt_hash) = prompt_hash {
|
||||
report_tags.insert("prompt_hash".to_string(), prompt_hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn feedback_turn_metadata_from_rollout(
|
||||
rollout_path: &Path,
|
||||
turn_id: Option<&str>,
|
||||
) -> Option<FeedbackTurnMetadata> {
|
||||
let (items, _, _) = RolloutRecorder::load_rollout_items(rollout_path)
|
||||
.await
|
||||
.ok()?;
|
||||
let prompt_hash = items.iter().find_map(|item| match item {
|
||||
RolloutItem::SessionMeta(meta) => meta
|
||||
.meta
|
||||
.base_instructions
|
||||
.as_ref()
|
||||
.map(|prompt| normalized_prompt_hash(&prompt.text)),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
items.into_iter().rev().find_map(|item| match item {
|
||||
RolloutItem::TurnContext(context)
|
||||
if turn_id.is_none() || context.turn_id.as_deref() == turn_id =>
|
||||
{
|
||||
Some(FeedbackTurnMetadata {
|
||||
model: context.model,
|
||||
effort: context.effort,
|
||||
prompt_hash: prompt_hash.clone(),
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn normalized_prompt_hash(prompt: &str) -> String {
|
||||
let normalized_prompt = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
format!("{:x}", Sha256::digest(normalized_prompt.as_bytes()))
|
||||
}
|
||||
|
||||
fn auto_review_rollout_filename(thread_id: ThreadId) -> String {
|
||||
format!("auto-review-rollout-{thread_id}.jsonl")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_sandbox_log_attachment(codex_home: &Path) -> Option<FeedbackAttachmentPath> {
|
||||
let sandbox_log_path = akode_windows_sandbox::current_log_file_path_for_codex_home(codex_home);
|
||||
sandbox_log_path
|
||||
.is_file()
|
||||
.then_some(FeedbackAttachmentPath {
|
||||
path: sandbox_log_path,
|
||||
attachment_filename_override: Some(WINDOWS_SANDBOX_LOG_ATTACHMENT_FILENAME.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn windows_sandbox_log_attachment(_codex_home: &Path) -> Option<FeedbackAttachmentPath> {
|
||||
None
|
||||
}
|
||||
|
||||
// Refresh logs after SQLite collection without changing the earlier metadata snapshot.
|
||||
async fn collect_feedback_logs(
|
||||
feedback: &CodexFeedback,
|
||||
log_db: Option<&LogDbLayer>,
|
||||
state_db: Option<&StateDbHandle>,
|
||||
config: &Config,
|
||||
mut snapshot: FeedbackSnapshot,
|
||||
thread_ids: &[ThreadId],
|
||||
) -> (FeedbackSnapshot, Option<Vec<u8>>, Option<Vec<u8>>) {
|
||||
if let Some(log_db) = log_db {
|
||||
log_db.flush().await;
|
||||
}
|
||||
let mut sqlite_logs = None;
|
||||
let mut legacy_logs = None;
|
||||
if let Some(state_db) = state_db
|
||||
&& !thread_ids.is_empty()
|
||||
{
|
||||
let thread_ids = thread_ids
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
let thread_id_refs = thread_ids.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
match state_db
|
||||
.query_feedback_logs_for_threads(&thread_id_refs)
|
||||
.await
|
||||
{
|
||||
Ok(logs) if logs.is_empty() => {}
|
||||
Ok(logs) => sqlite_logs = Some(logs),
|
||||
Err(err) => {
|
||||
let thread_ids = thread_ids.join(", ");
|
||||
tracing::warn!(
|
||||
"failed to query feedback logs from sqlite for thread_ids=[{thread_ids}]: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Earlier versions stored logs in sqlite_home/logs_2.sqlite.
|
||||
// Keep this temporary read path so feedback can include logs from before the directory change.
|
||||
// Read the old database when log_dir is unset or the current query returns no logs.
|
||||
if config.configured_log_dir().is_none() || sqlite_logs.is_none() {
|
||||
match state_db
|
||||
.query_legacy_feedback_logs_for_threads(&thread_id_refs)
|
||||
.await
|
||||
{
|
||||
Ok(logs) if logs.is_empty() => {}
|
||||
Ok(logs) => legacy_logs = Some(logs),
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to query legacy feedback logs from sqlite: {err}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if log_db.is_some_and(LogDbLayer::has_write_failure) {
|
||||
sqlite_logs = None;
|
||||
}
|
||||
|
||||
// new logs might arrive to the buffer while collecting metadata e.g. if log db flush fails
|
||||
snapshot.refresh_logs(feedback);
|
||||
(snapshot, sqlite_logs, legacy_logs)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_protocol::protocol::TurnContextItem;
|
||||
use akode_rollout::RolloutLine;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn doctor_uses_loaded_feedback_thread_cwd() -> anyhow::Result<()> {
|
||||
let server = start_mock_server().await;
|
||||
let test = test_codex().build_with_auto_env(&server).await?;
|
||||
let daemon_workspace = tempfile::tempdir()?;
|
||||
|
||||
let cwd = feedback_cwd(
|
||||
&test.thread_manager,
|
||||
/*state_db*/ None,
|
||||
Some(test.session_configured.thread_id),
|
||||
daemon_workspace.path(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(cwd, test.cwd_path());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_tags_drop_unverified_client_prompt_tags() {
|
||||
let mut report_tags = BTreeMap::from([
|
||||
("custom".to_string(), "preserved".to_string()),
|
||||
(
|
||||
"prompt_hash".to_string(),
|
||||
"unverified-client-hash".to_string(),
|
||||
),
|
||||
("prompt_version".to_string(), "client-prompt-v1".to_string()),
|
||||
]);
|
||||
|
||||
apply_feedback_turn_metadata(&mut report_tags, /*turn_metadata*/ None);
|
||||
|
||||
assert_eq!(
|
||||
report_tags,
|
||||
BTreeMap::from([("custom".to_string(), "preserved".to_string())])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_tags_drop_client_prompt_hash_when_rollout_has_no_hash() {
|
||||
let mut report_tags = BTreeMap::from([(
|
||||
"prompt_hash".to_string(),
|
||||
"unverified-client-hash".to_string(),
|
||||
)]);
|
||||
|
||||
apply_feedback_turn_metadata(
|
||||
&mut report_tags,
|
||||
Some(FeedbackTurnMetadata {
|
||||
model: "reported-model".to_string(),
|
||||
effort: Some(ReasoningEffort::High),
|
||||
prompt_hash: None,
|
||||
}),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
report_tags,
|
||||
BTreeMap::from([
|
||||
("effort".to_string(), "Some(High)".to_string()),
|
||||
("model".to_string(), "reported-model".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_tags_replace_client_prompt_hash_with_rollout_hash() {
|
||||
let mut report_tags = BTreeMap::from([(
|
||||
"prompt_hash".to_string(),
|
||||
"unverified-client-hash".to_string(),
|
||||
)]);
|
||||
|
||||
apply_feedback_turn_metadata(
|
||||
&mut report_tags,
|
||||
Some(FeedbackTurnMetadata {
|
||||
model: "reported-model".to_string(),
|
||||
effort: Some(ReasoningEffort::High),
|
||||
prompt_hash: Some("rollout-prompt-hash".to_string()),
|
||||
}),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
report_tags,
|
||||
BTreeMap::from([
|
||||
("effort".to_string(), "Some(High)".to_string()),
|
||||
("model".to_string(), "reported-model".to_string()),
|
||||
("prompt_hash".to_string(), "rollout-prompt-hash".to_string(),),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_tags_do_not_trust_the_prompt_version_from_the_reported_rollout() {
|
||||
let (_tempdir, rollout_path) =
|
||||
feedback_rollout(&[("turn-1", "synthetic-model", Some(ReasoningEffort::High))]);
|
||||
let mut report_tags = BTreeMap::from([(
|
||||
"prompt_version".to_string(),
|
||||
"unverified-client-prompt".to_string(),
|
||||
)]);
|
||||
|
||||
let turn_metadata =
|
||||
feedback_turn_metadata_from_rollout(&rollout_path, Some("turn-1")).await;
|
||||
apply_feedback_turn_metadata(&mut report_tags, turn_metadata);
|
||||
|
||||
assert_eq!(
|
||||
report_tags,
|
||||
BTreeMap::from([
|
||||
("effort".to_string(), "Some(High)".to_string()),
|
||||
("model".to_string(), "synthetic-model".to_string()),
|
||||
(
|
||||
"prompt_hash".to_string(),
|
||||
normalized_prompt_hash("actual developer prompt"),
|
||||
),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_metadata_uses_the_reported_turn() {
|
||||
let (_tempdir, rollout_path) = feedback_rollout(&[
|
||||
("turn-1", "reported-model", Some(ReasoningEffort::High)),
|
||||
("turn-2", "newer-model", Some(ReasoningEffort::Ultra)),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
feedback_turn_metadata_from_rollout(&rollout_path, Some("turn-1")).await,
|
||||
Some(FeedbackTurnMetadata {
|
||||
model: "reported-model".to_string(),
|
||||
effort: Some(ReasoningEffort::High),
|
||||
prompt_hash: Some(normalized_prompt_hash("actual developer prompt")),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_metadata_uses_the_latest_turn_when_no_turn_is_reported() {
|
||||
let (_tempdir, rollout_path) = feedback_rollout(&[
|
||||
("turn-1", "older-model", Some(ReasoningEffort::High)),
|
||||
("turn-2", "latest-model", Some(ReasoningEffort::Ultra)),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
feedback_turn_metadata_from_rollout(&rollout_path, /*turn_id*/ None).await,
|
||||
Some(FeedbackTurnMetadata {
|
||||
model: "latest-model".to_string(),
|
||||
effort: Some(ReasoningEffort::Ultra),
|
||||
prompt_hash: Some(normalized_prompt_hash("actual developer prompt")),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_metadata_does_not_substitute_a_different_turn() {
|
||||
let (_tempdir, rollout_path) =
|
||||
feedback_rollout(&[("turn-1", "different-model", Some(ReasoningEffort::High))]);
|
||||
|
||||
assert_eq!(
|
||||
feedback_turn_metadata_from_rollout(&rollout_path, Some("missing-turn")).await,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_metadata_preserves_unspecified_effort_and_prompt_hash() {
|
||||
let (_tempdir, rollout_path) =
|
||||
feedback_rollout(&[("turn-1", "reported-model", /*effort*/ None)]);
|
||||
|
||||
assert_eq!(
|
||||
feedback_turn_metadata_from_rollout(&rollout_path, Some("turn-1")).await,
|
||||
Some(FeedbackTurnMetadata {
|
||||
model: "reported-model".to_string(),
|
||||
effort: None,
|
||||
prompt_hash: Some(normalized_prompt_hash("actual developer prompt")),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_hashes_the_actual_developer_prompt_from_session_metadata() {
|
||||
let (_tempdir, rollout_path) = feedback_rollout(&[("turn-1", "reported-model", None)]);
|
||||
|
||||
assert_eq!(
|
||||
feedback_turn_metadata_from_rollout(&rollout_path, Some("turn-1"))
|
||||
.await
|
||||
.and_then(|metadata| metadata.prompt_hash),
|
||||
Some(normalized_prompt_hash("actual developer prompt")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_hash_normalizes_whitespace() {
|
||||
assert_eq!(
|
||||
normalized_prompt_hash("actual developer\r\nprompt\t"),
|
||||
"9ae77301cc2a30e729c28661b7a0f9490c80a72e7d23277e7e74f0ac81779541"
|
||||
);
|
||||
}
|
||||
|
||||
fn feedback_rollout(
|
||||
turns: &[(&str, &str, Option<ReasoningEffort>)],
|
||||
) -> (tempfile::TempDir, PathBuf) {
|
||||
let tempdir = tempfile::tempdir().expect("create feedback rollout directory");
|
||||
let rollout_path = tempdir.path().join("feedback-rollout.jsonl");
|
||||
let mut lines = vec![RolloutLine {
|
||||
timestamp: "2026-07-24T00:00:00Z".to_string(),
|
||||
ordinal: None,
|
||||
item: RolloutItem::SessionMeta(Box::new(SessionMetaLine {
|
||||
meta: akode_protocol::protocol::SessionMeta {
|
||||
cwd: tempdir.path().to_path_buf(),
|
||||
base_instructions: Some(akode_protocol::models::BaseInstructions {
|
||||
text: "actual developer prompt".to_string(),
|
||||
provenance: None,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
git: None,
|
||||
})),
|
||||
}];
|
||||
lines.extend(turns.iter().map(|(turn_id, model, effort)| {
|
||||
RolloutLine {
|
||||
timestamp: "2026-07-24T00:00:01Z".to_string(),
|
||||
ordinal: None,
|
||||
item: RolloutItem::TurnContext(TurnContextItem {
|
||||
turn_id: Some((*turn_id).to_string()),
|
||||
root_turn_id: None,
|
||||
direct_only_tool_namespaces: None,
|
||||
disabled_plugin_ids: None,
|
||||
cwd: AbsolutePathBuf::from_absolute_path(tempdir.path())
|
||||
.expect("absolute feedback rollout directory"),
|
||||
approval_policy: akode_protocol::protocol::AskForApproval::Never,
|
||||
approvals_reviewer: None,
|
||||
permission_profile: akode_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
model: (*model).to_string(),
|
||||
comp_hash: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
effort: effort.clone(),
|
||||
summary: Some(ReasoningSummary::Auto),
|
||||
}),
|
||||
}
|
||||
}));
|
||||
let contents = lines
|
||||
.iter()
|
||||
.map(serde_json::to_string)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.expect("serialize feedback rollout")
|
||||
.join("\n");
|
||||
std::fs::write(&rollout_path, format!("{contents}\n")).expect("write feedback rollout");
|
||||
|
||||
(tempdir, rollout_path)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn windows_sandbox_log_attachment_uses_current_log() {
|
||||
let codex_home = tempfile::tempdir().expect("create tempdir");
|
||||
let sandbox_dir = akode_windows_sandbox::sandbox_dir(codex_home.path());
|
||||
std::fs::create_dir_all(&sandbox_dir).expect("create sandbox dir");
|
||||
let sandbox_log_path =
|
||||
akode_windows_sandbox::current_log_file_path_for_codex_home(codex_home.path());
|
||||
std::fs::write(&sandbox_log_path, "sandbox log").expect("write sandbox log");
|
||||
|
||||
let attachment = windows_sandbox_log_attachment(codex_home.path())
|
||||
.map(|attachment| (attachment.path, attachment.attachment_filename_override));
|
||||
|
||||
assert_eq!(
|
||||
attachment,
|
||||
Some((
|
||||
sandbox_log_path,
|
||||
Some(WINDOWS_SANDBOX_LOG_ATTACHMENT_FILENAME.to_string())
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "feedback_log_snapshot_tests.rs"]
|
||||
mod feedback_log_snapshot_tests;
|
||||
@@ -0,0 +1,136 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_feedback::FeedbackAttachment;
|
||||
use akode_feedback::FeedbackAttachmentPath;
|
||||
use akode_feedback::MAX_ATTACHMENT_BYTES;
|
||||
use akode_feedback::MAX_ATTACHMENTS_BYTES;
|
||||
use akode_rollout::find_rollout_path_by_rollout_id;
|
||||
use akode_rollout::read_session_meta_line;
|
||||
use akode_rollout::rollout_id_from_path;
|
||||
|
||||
const MAX_HISTORY_ROLLOUTS: usize = 64;
|
||||
const HISTORY_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub(super) async fn history_base_attachments(
|
||||
codex_home: &Path,
|
||||
attachments: &[FeedbackAttachmentPath],
|
||||
) -> Vec<FeedbackAttachment> {
|
||||
let selected = attachments
|
||||
.iter()
|
||||
.filter_map(|attachment| rollout_id_from_path(&attachment.path))
|
||||
.collect::<HashSet<_>>();
|
||||
let mut pending = attachments
|
||||
.iter()
|
||||
.filter(|attachment| rollout_id_from_path(&attachment.path).is_some())
|
||||
.map(|attachment| attachment.path.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut positions = HashMap::new();
|
||||
let mut ancestors: Vec<(PathBuf, usize)> = Vec::new();
|
||||
// Preserve discovered prefixes if the bounded filesystem walk times out.
|
||||
let discovery = async {
|
||||
let mut next = 0;
|
||||
while next < pending.len() {
|
||||
let path = &pending[next];
|
||||
next += 1;
|
||||
let meta = match read_session_meta_line(path).await {
|
||||
Ok(meta) => meta,
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
?err,
|
||||
"failed to read feedback history metadata at {}",
|
||||
path.display()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(base) = meta.meta.history_base else {
|
||||
continue;
|
||||
};
|
||||
if selected.contains(&base.thread_id) {
|
||||
continue;
|
||||
}
|
||||
let Ok(end_byte_offset) = usize::try_from(base.end_byte_offset) else {
|
||||
continue;
|
||||
};
|
||||
if end_byte_offset > MAX_ATTACHMENT_BYTES {
|
||||
continue;
|
||||
}
|
||||
if let Some(&index) = positions.get(&base.thread_id) {
|
||||
let (_, previous_end_byte_offset): &mut (PathBuf, usize) = &mut ancestors[index];
|
||||
*previous_end_byte_offset = (*previous_end_byte_offset).max(end_byte_offset);
|
||||
continue;
|
||||
}
|
||||
if positions.len() == MAX_HISTORY_ROLLOUTS {
|
||||
tracing::error!("feedback history rollout limit reached");
|
||||
break;
|
||||
}
|
||||
// The wire field names an immutable rollout, not the owner's current thread.
|
||||
let path = match find_rollout_path_by_rollout_id(codex_home, base.thread_id).await {
|
||||
Ok(Some(path)) => path,
|
||||
Ok(None) => continue,
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
?err,
|
||||
"failed to locate feedback history rollout {}",
|
||||
base.thread_id
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
positions.insert(base.thread_id, ancestors.len());
|
||||
pending.push(path.clone());
|
||||
ancestors.push((path, end_byte_offset));
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(HISTORY_LOOKUP_TIMEOUT, discovery)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::error!("feedback history lookup timed out");
|
||||
}
|
||||
// Freeze exactly the inherited bytes before upload. Unreadable or oversized
|
||||
// ancestors are best effort and cannot turn an accepted report into an error.
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut remaining = MAX_ATTACHMENTS_BYTES;
|
||||
let mut result = Vec::new();
|
||||
for (path, end_byte_offset) in ancestors {
|
||||
if end_byte_offset > remaining {
|
||||
continue;
|
||||
}
|
||||
let plain_path = akode_rollout::plain_rollout_path(&path);
|
||||
let Some(filename) = plain_path.file_name() else {
|
||||
continue;
|
||||
};
|
||||
match akode_rollout::read_rollout_prefix(&path, end_byte_offset) {
|
||||
Ok(Some(buffer)) if buffer.len() == end_byte_offset => {
|
||||
remaining -= buffer.len();
|
||||
result.push(FeedbackAttachment {
|
||||
buffer,
|
||||
filename: filename.to_string_lossy().into_owned(),
|
||||
content_type: Some("application/jsonl".to_string()),
|
||||
});
|
||||
}
|
||||
Ok(_) => tracing::error!(
|
||||
"couldn't attach history: incomplete feedback history prefix at {}",
|
||||
path.display()
|
||||
),
|
||||
Err(err) => tracing::error!(
|
||||
?err,
|
||||
"couldn't read feedback history prefix at {}",
|
||||
path.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
result
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default() // Keep uploading the selected rollouts if this task fails.
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "feedback_rollout_history_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,70 @@
|
||||
use super::*;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::HistoryPosition;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn includes_nested_history_bases() -> anyhow::Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let directory = home.path().join("sessions");
|
||||
std::fs::create_dir_all(&directory)?;
|
||||
let (grandparent, grandparent_end) = write_rollout(&directory, /*base*/ None)?;
|
||||
let (parent, parent_end) = write_rollout(&directory, Some(grandparent_end))?;
|
||||
let (rollout, _) = write_rollout(&directory, Some(parent_end))?;
|
||||
|
||||
let attachments = history_base_attachments(
|
||||
home.path(),
|
||||
&[FeedbackAttachmentPath {
|
||||
path: rollout,
|
||||
attachment_filename_override: None,
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
|
||||
let expected = [parent, grandparent]
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
Ok((
|
||||
path.file_name().unwrap().to_string_lossy().into_owned(),
|
||||
std::fs::read(path)?,
|
||||
))
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
assert_eq!(
|
||||
attachments
|
||||
.into_iter()
|
||||
.map(|attachment| (attachment.filename, attachment.buffer))
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_rollout(
|
||||
directory: &Path,
|
||||
base: Option<HistoryPosition>,
|
||||
) -> anyhow::Result<(PathBuf, HistoryPosition)> {
|
||||
let id = ThreadId::new();
|
||||
let ordinal = base.map_or(0, |base| base.end_ordinal_exclusive);
|
||||
let path = directory.join(format!("rollout-2026-09-22T12-00-00-{id}.jsonl"));
|
||||
let meta = json!({
|
||||
"ordinal": ordinal,
|
||||
"timestamp": "2026-09-22T12:00:00Z", "type": "session_meta",
|
||||
"payload": {
|
||||
"id": id, "timestamp": "2026-09-22T12:00:00Z", "cwd": directory,
|
||||
"originator": "test", "cli_version": "test", "history_mode": "paginated", "history_base": base,
|
||||
},
|
||||
});
|
||||
let contents = format!("{meta}\n");
|
||||
std::fs::write(&path, &contents)?;
|
||||
Ok((
|
||||
path,
|
||||
HistoryPosition {
|
||||
thread_id: id,
|
||||
end_ordinal_exclusive: ordinal + 1,
|
||||
end_byte_offset: contents.len() as u64,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Selects a bounded set of spawned descendants and directly attached threads for feedback,
|
||||
//! preserving the reported thread and prioritizing children with retained failed reviews.
|
||||
//! Filenames identify the rollout entries saved in the local feedback archive.
|
||||
|
||||
use akode_feedback::FeedbackAttachment;
|
||||
use akode_feedback::GuardianReviewFailures;
|
||||
use akode_protocol::ThreadId;
|
||||
use serde::Serialize;
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_FEEDBACK_TREE_THREADS: usize = 8;
|
||||
const MAX_LISTED_OMISSIONS: usize = 64;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct FeedbackThreadIndex {
|
||||
pub threads: Vec<FeedbackThread>,
|
||||
retained_failure_thread_ids: Vec<ThreadId>,
|
||||
omitted_thread_ids: Vec<ThreadId>,
|
||||
unlisted_omitted_thread_count: usize,
|
||||
process_discarded_review_records: usize,
|
||||
notes: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct FeedbackThread {
|
||||
pub thread_id: ThreadId,
|
||||
pub rollout_filename: Option<String>,
|
||||
pub guardian_rollout_filename: Option<String>,
|
||||
}
|
||||
|
||||
impl FeedbackThreadIndex {
|
||||
pub fn new(
|
||||
reported_thread_id: ThreadId,
|
||||
mut subtree: Vec<ThreadId>,
|
||||
failures: &GuardianReviewFailures,
|
||||
) -> Self {
|
||||
// UUIDv7 ordering provides a deterministic newest-child fallback.
|
||||
subtree.sort_unstable_by_key(|id| Reverse(id.to_string()));
|
||||
subtree.dedup();
|
||||
subtree.retain(|id| *id != reported_thread_id);
|
||||
let descendants = subtree.iter().copied().collect::<HashSet<_>>();
|
||||
let mut selected = HashSet::from([reported_thread_id]);
|
||||
let mut thread_ids = vec![reported_thread_id];
|
||||
for id in failures.thread_ids.iter().chain(&subtree) {
|
||||
if thread_ids.len() == MAX_FEEDBACK_TREE_THREADS {
|
||||
break;
|
||||
}
|
||||
if descendants.contains(id) && selected.insert(*id) {
|
||||
thread_ids.push(*id);
|
||||
}
|
||||
}
|
||||
let omitted_count = subtree.len().saturating_sub(thread_ids.len() - 1);
|
||||
let omitted_thread_ids = subtree
|
||||
.into_iter()
|
||||
.filter(|id| !selected.contains(id))
|
||||
.take(MAX_LISTED_OMISSIONS)
|
||||
.collect::<Vec<_>>();
|
||||
Self {
|
||||
threads: thread_ids
|
||||
.into_iter()
|
||||
.map(|thread_id| FeedbackThread {
|
||||
thread_id,
|
||||
rollout_filename: None,
|
||||
guardian_rollout_filename: None,
|
||||
})
|
||||
.collect(),
|
||||
retained_failure_thread_ids: failures.thread_ids.clone(),
|
||||
unlisted_omitted_thread_count: omitted_count - omitted_thread_ids.len(),
|
||||
omitted_thread_ids,
|
||||
process_discarded_review_records: failures.process_discarded_records,
|
||||
notes: "Selection only. Null filenames mean no path was available. \
|
||||
Omitted threads exceeded the rollout thread limit; their retained reviews are \
|
||||
still in auto-review-failures.jsonl. Review evidence is persisted and bounded; \
|
||||
missing evidence does not imply no denial. The discarded-record count covers \
|
||||
only the process-wide in-memory fallback and resets on restart.",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn attachment(&self) -> serde_json::Result<FeedbackAttachment> {
|
||||
Ok(FeedbackAttachment {
|
||||
filename: "feedback-thread-index.json".to_string(),
|
||||
buffer: serde_json::to_vec(self)?,
|
||||
content_type: Some("application/json".to_string()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "feedback_thread_index_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,80 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn thread_ids(count: usize) -> Vec<ThreadId> {
|
||||
(0..count)
|
||||
.map(|index| {
|
||||
ThreadId::from_string(&format!("00000000-0000-7000-8000-{index:012x}"))
|
||||
.expect("thread id")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_failed_child_precedes_new_children_and_index_explains_selection() -> anyhow::Result<()> {
|
||||
let ids = thread_ids(/*count*/ 12);
|
||||
let failures = GuardianReviewFailures {
|
||||
attachment: None,
|
||||
thread_ids: vec![ids[1], ids[0]],
|
||||
process_discarded_records: 3,
|
||||
};
|
||||
let mut index = FeedbackThreadIndex::new(ids[0], ids.clone(), &failures);
|
||||
index.threads[0].rollout_filename = Some("parent.jsonl".to_string());
|
||||
index.threads[1].rollout_filename = Some("child.jsonl".to_string());
|
||||
index.threads[1].guardian_rollout_filename = Some("child-reviewer.jsonl".to_string());
|
||||
let attachment = index.attachment()?;
|
||||
let selected = [0, 1, 11, 10, 9, 8, 7, 6];
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&attachment.buffer)?,
|
||||
json!({
|
||||
"threads": selected.into_iter().map(|i| json!({
|
||||
"thread_id": ids[i],
|
||||
"rollout_filename": match i {
|
||||
0 => Some("parent.jsonl"),
|
||||
1 => Some("child.jsonl"),
|
||||
_ => None,
|
||||
},
|
||||
"guardian_rollout_filename": (i == 1).then_some("child-reviewer.jsonl"),
|
||||
})).collect::<Vec<_>>(),
|
||||
"retained_failure_thread_ids": [ids[1], ids[0]],
|
||||
"omitted_thread_ids": [ids[5], ids[4], ids[3], ids[2]],
|
||||
"unlisted_omitted_thread_count": 0,
|
||||
"process_discarded_review_records": 3,
|
||||
"notes": index.notes,
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_priority_keeps_the_reported_thread_and_bounds_omission_details() {
|
||||
let ids = thread_ids(/*count*/ 100);
|
||||
let failures = GuardianReviewFailures {
|
||||
attachment: None,
|
||||
thread_ids: ids[1..10].to_vec(),
|
||||
process_discarded_records: 0,
|
||||
};
|
||||
// Exercise unsorted and duplicate subtree entries without inflating omission counts.
|
||||
let mut subtree = ids.iter().rev().copied().collect::<Vec<_>>();
|
||||
subtree.extend_from_slice(&ids[..3]);
|
||||
let index = FeedbackThreadIndex::new(ids[0], subtree, &failures);
|
||||
assert_eq!(
|
||||
(
|
||||
index
|
||||
.threads
|
||||
.iter()
|
||||
.map(|thread| thread.thread_id)
|
||||
.collect::<Vec<_>>(),
|
||||
index.omitted_thread_ids,
|
||||
index.unlisted_omitted_thread_count,
|
||||
index.retained_failure_thread_ids,
|
||||
),
|
||||
(
|
||||
ids[..8].to_vec(),
|
||||
ids[36..].iter().rev().copied().collect::<Vec<_>>(),
|
||||
28,
|
||||
failures.thread_ids,
|
||||
)
|
||||
);
|
||||
}
|
||||
221
akode-rs/app-server/src/request_processors/fs_processor.rs
Normal file
221
akode-rs/app-server/src/request_processors/fs_processor.rs
Normal file
@@ -0,0 +1,221 @@
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::fs_watch::FsWatchManager;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use akode_app_server_protocol::FsCopyParams;
|
||||
use akode_app_server_protocol::FsCopyResponse;
|
||||
use akode_app_server_protocol::FsCreateDirectoryParams;
|
||||
use akode_app_server_protocol::FsCreateDirectoryResponse;
|
||||
use akode_app_server_protocol::FsGetMetadataParams;
|
||||
use akode_app_server_protocol::FsGetMetadataResponse;
|
||||
use akode_app_server_protocol::FsReadDirectoryEntry;
|
||||
use akode_app_server_protocol::FsReadDirectoryParams;
|
||||
use akode_app_server_protocol::FsReadDirectoryResponse;
|
||||
use akode_app_server_protocol::FsReadFileParams;
|
||||
use akode_app_server_protocol::FsReadFileResponse;
|
||||
use akode_app_server_protocol::FsRemoveParams;
|
||||
use akode_app_server_protocol::FsRemoveResponse;
|
||||
use akode_app_server_protocol::FsUnwatchParams;
|
||||
use akode_app_server_protocol::FsUnwatchResponse;
|
||||
use akode_app_server_protocol::FsWatchParams;
|
||||
use akode_app_server_protocol::FsWatchResponse;
|
||||
use akode_app_server_protocol::FsWriteFileParams;
|
||||
use akode_app_server_protocol::FsWriteFileResponse;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_exec_server::CopyOptions;
|
||||
use akode_exec_server::CreateDirectoryOptions;
|
||||
use akode_exec_server::EnvironmentManager;
|
||||
use akode_exec_server::ExecutorFileSystem;
|
||||
use akode_exec_server::RemoveOptions;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FsRequestProcessor {
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
fs_watch_manager: FsWatchManager,
|
||||
}
|
||||
|
||||
impl FsRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
fs_watch_manager: FsWatchManager,
|
||||
) -> Self {
|
||||
Self {
|
||||
environment_manager,
|
||||
fs_watch_manager,
|
||||
}
|
||||
}
|
||||
|
||||
fn file_system(&self) -> Result<Arc<dyn ExecutorFileSystem>, JSONRPCErrorError> {
|
||||
self.environment_manager
|
||||
.try_local_environment()
|
||||
.map(|environment| environment.get_filesystem())
|
||||
.ok_or_else(|| internal_error("local filesystem is not configured"))
|
||||
}
|
||||
|
||||
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
|
||||
self.fs_watch_manager.connection_closed(connection_id).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn read_file(
|
||||
&self,
|
||||
params: FsReadFileParams,
|
||||
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path);
|
||||
let bytes = self
|
||||
.file_system()?
|
||||
.read_file(&path, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsReadFileResponse {
|
||||
data_base64: STANDARD.encode(bytes),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn write_file(
|
||||
&self,
|
||||
params: FsWriteFileParams,
|
||||
) -> Result<FsWriteFileResponse, JSONRPCErrorError> {
|
||||
let bytes = STANDARD.decode(params.data_base64).map_err(|err| {
|
||||
invalid_request(format!(
|
||||
"fs/writeFile requires valid base64 dataBase64: {err}"
|
||||
))
|
||||
})?;
|
||||
let path = PathUri::from_abs_path(¶ms.path);
|
||||
self.file_system()?
|
||||
.write_file(&path, bytes, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsWriteFileResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn create_directory(
|
||||
&self,
|
||||
params: FsCreateDirectoryParams,
|
||||
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path);
|
||||
self.file_system()?
|
||||
.create_directory(
|
||||
&path,
|
||||
CreateDirectoryOptions {
|
||||
recursive: params.recursive.unwrap_or(true),
|
||||
follow_symlinks: true,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsCreateDirectoryResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn get_metadata(
|
||||
&self,
|
||||
params: FsGetMetadataParams,
|
||||
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path);
|
||||
let metadata = self
|
||||
.file_system()?
|
||||
.get_metadata(&path, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsGetMetadataResponse {
|
||||
is_directory: metadata.is_directory,
|
||||
is_file: metadata.is_file,
|
||||
is_symlink: metadata.is_symlink,
|
||||
created_at_ms: metadata.created_at_ms,
|
||||
modified_at_ms: metadata.modified_at_ms,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn read_directory(
|
||||
&self,
|
||||
params: FsReadDirectoryParams,
|
||||
) -> Result<FsReadDirectoryResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path);
|
||||
let entries = self
|
||||
.file_system()?
|
||||
.read_directory(&path, /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsReadDirectoryResponse {
|
||||
entries: entries
|
||||
.into_iter()
|
||||
.map(|entry| FsReadDirectoryEntry {
|
||||
file_name: entry.file_name,
|
||||
is_directory: entry.is_directory,
|
||||
is_file: entry.is_file,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn remove(
|
||||
&self,
|
||||
params: FsRemoveParams,
|
||||
) -> Result<FsRemoveResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path);
|
||||
self.file_system()?
|
||||
.remove(
|
||||
&path,
|
||||
RemoveOptions {
|
||||
recursive: params.recursive.unwrap_or(true),
|
||||
force: params.force.unwrap_or(true),
|
||||
follow_symlinks: true,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsRemoveResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn copy(
|
||||
&self,
|
||||
params: FsCopyParams,
|
||||
) -> Result<FsCopyResponse, JSONRPCErrorError> {
|
||||
let source_path = PathUri::from_abs_path(¶ms.source_path);
|
||||
let destination_path = PathUri::from_abs_path(¶ms.destination_path);
|
||||
self.file_system()?
|
||||
.copy(
|
||||
&source_path,
|
||||
&destination_path,
|
||||
CopyOptions {
|
||||
recursive: params.recursive,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsCopyResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn watch(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
params: FsWatchParams,
|
||||
) -> Result<FsWatchResponse, JSONRPCErrorError> {
|
||||
self.file_system()?;
|
||||
self.fs_watch_manager.watch(connection_id, params).await
|
||||
}
|
||||
|
||||
pub(crate) async fn unwatch(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
params: FsUnwatchParams,
|
||||
) -> Result<FsUnwatchResponse, JSONRPCErrorError> {
|
||||
self.file_system()?;
|
||||
self.fs_watch_manager.unwatch(connection_id, params).await
|
||||
}
|
||||
}
|
||||
|
||||
fn map_fs_error(err: io::Error) -> JSONRPCErrorError {
|
||||
if err.kind() == io::ErrorKind::InvalidInput {
|
||||
invalid_request(err.to_string())
|
||||
} else {
|
||||
internal_error(err.to_string())
|
||||
}
|
||||
}
|
||||
36
akode-rs/app-server/src/request_processors/git_processor.rs
Normal file
36
akode-rs/app-server/src/request_processors/git_processor.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct GitRequestProcessor;
|
||||
|
||||
impl GitRequestProcessor {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
pub(crate) async fn git_diff_to_remote(
|
||||
&self,
|
||||
params: GitDiffToRemoteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.git_diff_to_origin(params.cwd)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
async fn git_diff_to_origin(
|
||||
&self,
|
||||
cwd: PathBuf,
|
||||
) -> Result<GitDiffToRemoteResponse, JSONRPCErrorError> {
|
||||
git_diff_to_remote(&cwd)
|
||||
.await
|
||||
.map(|value| GitDiffToRemoteResponse {
|
||||
sha: value.sha,
|
||||
diff: value.diff,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"failed to compute git diff to remote for cwd: {cwd:?}"
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use axum::http::HeaderValue;
|
||||
use akode_login::default_client::SetOriginatorError;
|
||||
use akode_login::default_client::USER_AGENT_SUFFIX;
|
||||
use akode_login::default_client::get_codex_user_agent;
|
||||
use akode_login::default_client::set_default_client_residency_requirement;
|
||||
use akode_login::default_client::set_default_originator;
|
||||
use akode_protocol::mcp::ClientMcpExtensions;
|
||||
use akode_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
|
||||
|
||||
use super::*;
|
||||
use crate::message_processor::ConnectionSessionState;
|
||||
use crate::message_processor::InitializedConnectionSessionState;
|
||||
use crate::transport::ConnectionOrigin;
|
||||
|
||||
const NON_ORIGINATING_CLIENT_NAMES: &[&str] = &["akode_app_server_daemon", "codex-backend"];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct InitializeRequestProcessor {
|
||||
gateway_login_control: Arc<akode_login::GatewayLoginControl>,
|
||||
gateway_login_initialized: Arc<std::sync::OnceLock<()>>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
user_verification: Arc<crate::user_verification::Service>,
|
||||
}
|
||||
|
||||
impl InitializeRequestProcessor {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
gateway_login_control: Arc<akode_login::GatewayLoginControl>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
user_verification: Arc<crate::user_verification::Service>,
|
||||
) -> Self {
|
||||
Self {
|
||||
gateway_login_control,
|
||||
gateway_login_initialized: Arc::new(std::sync::OnceLock::new()),
|
||||
outgoing,
|
||||
config,
|
||||
user_verification,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn initialize(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
request_id: RequestId,
|
||||
params: InitializeParams,
|
||||
session: &ConnectionSessionState,
|
||||
// `Some(...)` means the caller wants initialize to immediately mark the
|
||||
// connection outbound-ready. Websocket JSON-RPC calls pass `None` so
|
||||
// lib.rs can deliver connection-scoped initialize notifications first.
|
||||
outbound_initialized: Option<&AtomicBool>,
|
||||
) -> Result<bool, JSONRPCErrorError> {
|
||||
let connection_request_id = ConnectionRequestId {
|
||||
connection_id,
|
||||
request_id,
|
||||
};
|
||||
if session.initialized() {
|
||||
return Err(invalid_request("Already initialized"));
|
||||
}
|
||||
|
||||
// TODO(maxj): Revisit capability scoping for `experimental_api_enabled`.
|
||||
// Current behavior is per-connection. Reviewer feedback notes this can
|
||||
// create odd cross-client behavior (for example dynamic tool calls on a
|
||||
// shared thread when another connected client did not opt into
|
||||
// experimental API). Proposed direction is instance-global first-write-wins
|
||||
// with initialize-time mismatch rejection.
|
||||
let capabilities = params.capabilities.unwrap_or_default();
|
||||
let experimental_api_enabled = capabilities.experimental_api;
|
||||
let extensions = capabilities.extensions.as_ref();
|
||||
let mut client_mcp_extensions = akode_mcp::client_mcp_extensions(
|
||||
extensions,
|
||||
capabilities.mcp_server_openai_form_elicitation,
|
||||
);
|
||||
let opt_out_notification_methods = capabilities
|
||||
.opt_out_notification_methods
|
||||
.unwrap_or_default();
|
||||
let ClientInfo {
|
||||
name,
|
||||
title: _title,
|
||||
version,
|
||||
} = params.client_info;
|
||||
// Validate before committing; set_default_originator validates while
|
||||
// mutating process-global metadata.
|
||||
if HeaderValue::from_str(&name).is_err() {
|
||||
return Err(invalid_request(format!(
|
||||
"Invalid clientInfo.name: '{name}'. Must be a valid HTTP header value."
|
||||
)));
|
||||
}
|
||||
// Activate only the embedded TUI and local desktop host. Client-supplied
|
||||
// extensions cannot opt other hosts into verification.
|
||||
let user_verification_enabled = experimental_api_enabled
|
||||
&& matches!(
|
||||
(session.origin, name.as_str()),
|
||||
(ConnectionOrigin::InProcess, "akode-tui")
|
||||
| (ConnectionOrigin::Stdio, "Codex Desktop")
|
||||
)
|
||||
&& tokio::task::spawn_blocking(self.user_verification.device_supported)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if user_verification_enabled {
|
||||
let mut extensions = client_mcp_extensions
|
||||
.iter()
|
||||
.map(|(id, value)| (id.to_string(), value.clone()))
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
let settings = extensions
|
||||
.entry(OPENAI_ELICITATION_EXTENSION_ID.to_string())
|
||||
.or_insert_with(|| serde_json::json!({}));
|
||||
if !settings.is_object() {
|
||||
*settings = serde_json::json!({});
|
||||
}
|
||||
settings["userVerification"] = serde_json::json!({});
|
||||
client_mcp_extensions = ClientMcpExtensions::new(extensions);
|
||||
}
|
||||
let originator = name.clone();
|
||||
let user_agent_suffix = format!("{name}; {version}");
|
||||
let mutates_global_identity = !NON_ORIGINATING_CLIENT_NAMES.contains(&name.as_str());
|
||||
let codex_home = self.config.codex_home.clone();
|
||||
if session
|
||||
.initialize(InitializedConnectionSessionState {
|
||||
experimental_api_enabled,
|
||||
opted_out_notification_methods: opt_out_notification_methods.into_iter().collect(),
|
||||
app_server_client_name: name.clone(),
|
||||
client_version: version,
|
||||
client_mcp_extensions,
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
return Err(invalid_request("Already initialized"));
|
||||
}
|
||||
if experimental_api_enabled && capabilities.required_human_approval {
|
||||
self.outgoing
|
||||
.enable_human_approval_connection(connection_id)
|
||||
.await;
|
||||
}
|
||||
if user_verification_enabled {
|
||||
self.outgoing
|
||||
.enable_user_verification_connection(connection_id)
|
||||
.await;
|
||||
}
|
||||
|
||||
if capabilities.explicit_gateway_oauth || mutates_global_identity {
|
||||
// Only the first originating client may restore legacy automatic login.
|
||||
// Any explicit opt-in is sticky across subsequent connections.
|
||||
self.gateway_login_initialized.get_or_init(|| {
|
||||
if !capabilities.explicit_gateway_oauth {
|
||||
self.gateway_login_control.allow_automatic_login();
|
||||
}
|
||||
});
|
||||
if capabilities.explicit_gateway_oauth {
|
||||
self.gateway_login_control.require_explicit_login();
|
||||
}
|
||||
}
|
||||
|
||||
if mutates_global_identity {
|
||||
// Only real client initialization may mutate process-global client metadata.
|
||||
if let Err(error) = set_default_originator(originator.clone()) {
|
||||
match error {
|
||||
SetOriginatorError::InvalidHeaderValue => {
|
||||
tracing::warn!(
|
||||
client_info_name = %name,
|
||||
"validated clientInfo.name was rejected while setting originator"
|
||||
);
|
||||
}
|
||||
SetOriginatorError::AlreadyInitialized => {
|
||||
// No-op. This is expected to happen if the originator is already set via env var.
|
||||
// TODO(owen): Once we remove support for AKODE_INTERNAL_ORIGINATOR_OVERRIDE,
|
||||
// this will be an unexpected state and we can return a JSON-RPC error indicating
|
||||
// internal server error.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
set_default_client_residency_requirement(self.config.enforce_residency.value());
|
||||
if mutates_global_identity && let Ok(mut suffix) = USER_AGENT_SUFFIX.lock() {
|
||||
*suffix = Some(user_agent_suffix);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
if matches!(session.origin, ConnectionOrigin::Stdio) && name == "Codex Desktop" {
|
||||
// Uninstall ownership must not depend on account sign-in or sandbox setup.
|
||||
// Keep this bounded attempt ahead of the response; background registration can race uninstall.
|
||||
let home = codex_home.clone();
|
||||
if !matches!(
|
||||
tokio::task::spawn_blocking(move || {
|
||||
akode_windows_sandbox::register_desktop_installation(&home)
|
||||
})
|
||||
.await,
|
||||
Ok(Ok(()))
|
||||
) {
|
||||
tracing::warn!("could not register desktop uninstall ownership");
|
||||
}
|
||||
}
|
||||
|
||||
let user_agent = get_codex_user_agent();
|
||||
let response = InitializeResponse {
|
||||
user_agent,
|
||||
codex_home,
|
||||
platform_family: std::env::consts::FAMILY.to_string(),
|
||||
platform_os: std::env::consts::OS.to_string(),
|
||||
};
|
||||
|
||||
self.outgoing
|
||||
.send_response(connection_request_id, response)
|
||||
.await;
|
||||
|
||||
if let Some(outbound_initialized) = outbound_initialized {
|
||||
outbound_initialized.store(true, Ordering::Release);
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
use super::*;
|
||||
use crate::plugin_config_reload;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct MarketplaceRequestProcessor {
|
||||
config_manager: ConfigManager,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
}
|
||||
|
||||
impl MarketplaceRequestProcessor {
|
||||
pub(crate) fn new(config_manager: ConfigManager, thread_manager: Arc<ThreadManager>) -> Self {
|
||||
Self {
|
||||
config_manager,
|
||||
thread_manager,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn marketplace_add(
|
||||
&self,
|
||||
params: MarketplaceAddParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.marketplace_add_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn marketplace_remove(
|
||||
&self,
|
||||
params: MarketplaceRemoveParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.marketplace_remove_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn marketplace_upgrade(
|
||||
&self,
|
||||
params: MarketplaceUpgradeParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.marketplace_upgrade_response_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
async fn marketplace_remove_inner(
|
||||
&self,
|
||||
params: MarketplaceRemoveParams,
|
||||
) -> Result<MarketplaceRemoveResponse, JSONRPCErrorError> {
|
||||
let config = self.load_global_config().await?;
|
||||
remove_marketplace(
|
||||
config.codex_home.to_path_buf(),
|
||||
config.config_layer_stack,
|
||||
CoreMarketplaceRemoveRequest {
|
||||
marketplace_name: params.marketplace_name,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map(|outcome| MarketplaceRemoveResponse {
|
||||
marketplace_name: outcome.marketplace_name,
|
||||
installed_root: outcome.removed_installed_root,
|
||||
})
|
||||
.map_err(|err| match err {
|
||||
MarketplaceRemoveError::InvalidRequest(message) => invalid_request(message),
|
||||
MarketplaceRemoveError::Internal(message) => internal_error(message),
|
||||
})
|
||||
}
|
||||
|
||||
async fn marketplace_upgrade_response_inner(
|
||||
&self,
|
||||
params: MarketplaceUpgradeParams,
|
||||
) -> Result<MarketplaceUpgradeResponse, JSONRPCErrorError> {
|
||||
let config = self.load_global_config().await?;
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let MarketplaceUpgradeParams { marketplace_name } = params;
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let reload_config = plugin_config_reload::global(self.config_manager.clone());
|
||||
|
||||
let outcome = tokio::task::spawn_blocking(move || {
|
||||
plugins_manager.upgrade_configured_marketplaces_for_config(
|
||||
&plugins_input,
|
||||
marketplace_name.as_deref(),
|
||||
&reload_config,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to upgrade marketplaces: {err}")))?
|
||||
.map_err(invalid_request)?;
|
||||
|
||||
if !outcome.upgraded_roots.is_empty() {
|
||||
self.thread_manager.plugins_manager().clear_cache();
|
||||
self.thread_manager.skills_service().clear_cache();
|
||||
self.thread_manager.invalidate_mcp_runtimes().await;
|
||||
self.thread_manager.refresh_hook_runtimes().await;
|
||||
}
|
||||
|
||||
Ok(MarketplaceUpgradeResponse {
|
||||
selected_marketplaces: outcome.selected_marketplaces,
|
||||
upgraded_roots: outcome.upgraded_roots,
|
||||
errors: outcome
|
||||
.errors
|
||||
.into_iter()
|
||||
.map(|err| MarketplaceUpgradeErrorInfo {
|
||||
marketplace_name: err.marketplace_name,
|
||||
message: err.message,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn marketplace_add_inner(
|
||||
&self,
|
||||
params: MarketplaceAddParams,
|
||||
) -> Result<MarketplaceAddResponse, JSONRPCErrorError> {
|
||||
let config = self.load_global_config().await?;
|
||||
add_marketplace_to_codex_home(
|
||||
config.codex_home.to_path_buf(),
|
||||
config.config_layer_stack.requirements().clone(),
|
||||
MarketplaceAddRequest {
|
||||
source: params.source,
|
||||
ref_name: params.ref_name,
|
||||
sparse_paths: params.sparse_paths.unwrap_or_default(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map(|outcome| MarketplaceAddResponse {
|
||||
marketplace_name: outcome.marketplace_name,
|
||||
installed_root: outcome.installed_root,
|
||||
already_added: outcome.already_added,
|
||||
})
|
||||
.map_err(|err| match err {
|
||||
MarketplaceAddError::InvalidRequest(message) => invalid_request(message),
|
||||
MarketplaceAddError::Internal(message) => internal_error(message),
|
||||
})
|
||||
}
|
||||
|
||||
async fn load_global_config(&self) -> Result<Config, JSONRPCErrorError> {
|
||||
self.config_manager
|
||||
.load_non_project_config()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
}
|
||||
}
|
||||
616
akode-rs/app-server/src/request_processors/mcp_processor.rs
Normal file
616
akode-rs/app-server/src/request_processors/mcp_processor.rs
Normal file
@@ -0,0 +1,616 @@
|
||||
use super::thread_input::ensure_direct_input_allowed;
|
||||
use super::*;
|
||||
use akode_config::types::McpServerAuth;
|
||||
use akode_mcp::McpServerSource;
|
||||
use akode_mcp::ReadResourceRequestParams;
|
||||
use akode_mcp::resolve_oauth_callback;
|
||||
use akode_otel::auth_storage::AuthStorageOriginator;
|
||||
use std::future::Future;
|
||||
|
||||
|
||||
const MCP_THREAD_ID_META_KEY: &str = "threadId";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct McpRequestProcessor {
|
||||
pub(super) auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
pub(super) outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
}
|
||||
|
||||
impl McpRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
outgoing,
|
||||
config_manager,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn mcp_server_oauth_login(
|
||||
&self,
|
||||
params: McpServerOauthLoginParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.mcp_server_oauth_login_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_server_refresh(
|
||||
&self,
|
||||
params: Option<()>,
|
||||
) -> impl Future<Output = Result<Option<ClientResponsePayload>, JSONRPCErrorError>> + Send + '_
|
||||
{
|
||||
// Keep refresh state behind a pointer before returning to the shared request handler.
|
||||
Box::pin(async move {
|
||||
self.mcp_server_refresh_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn mcp_server_status_list(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: ListMcpServerStatusParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.list_mcp_server_status(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn mcp_resource_read(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: McpResourceReadParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.read_mcp_resource(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn mcp_server_tool_call(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: McpServerToolCallParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.call_mcp_server_tool(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
async fn mcp_server_refresh_response(
|
||||
&self,
|
||||
_params: Option<()>,
|
||||
) -> Result<McpServerRefreshResponse, JSONRPCErrorError> {
|
||||
crate::mcp_refresh::reload_mcp_config(&self.thread_manager, &self.config_manager)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to refresh MCP servers: {err}")))?;
|
||||
Ok(McpServerRefreshResponse {})
|
||||
}
|
||||
|
||||
async fn load_global_config(&self) -> Result<Config, JSONRPCErrorError> {
|
||||
self.config_manager
|
||||
.load_non_project_config()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
}
|
||||
|
||||
pub(super) async fn load_thread(
|
||||
&self,
|
||||
thread_id: &str,
|
||||
) -> Result<(ThreadId, Arc<CodexThread>), JSONRPCErrorError> {
|
||||
let thread_id = ThreadId::from_string(thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
|
||||
Ok((thread_id, thread))
|
||||
}
|
||||
|
||||
async fn mcp_server_oauth_login_response(
|
||||
&self,
|
||||
params: McpServerOauthLoginParams,
|
||||
) -> Result<McpServerOauthLoginResponse, JSONRPCErrorError> {
|
||||
let McpServerOauthLoginParams {
|
||||
name,
|
||||
thread_id,
|
||||
client_registration,
|
||||
scopes,
|
||||
timeout_secs,
|
||||
} = params;
|
||||
let auth = self.auth_manager.auth().await;
|
||||
let (mcp_config, runtime_context) = match thread_id.as_deref() {
|
||||
Some(thread_id) => {
|
||||
let (_, thread) = self.load_thread(thread_id).await?;
|
||||
let (config, runtime_context) =
|
||||
thread.current_mcp_config_and_runtime_context().await;
|
||||
((*config).clone(), runtime_context)
|
||||
}
|
||||
None => {
|
||||
let config = self.load_global_config().await?;
|
||||
let mcp_config = self
|
||||
.thread_manager
|
||||
.mcp_manager()
|
||||
.runtime_config(&config)
|
||||
.await;
|
||||
let runtime_context = McpRuntimeContext::new(
|
||||
self.thread_manager.environment_manager(),
|
||||
config.cwd.to_path_buf(),
|
||||
);
|
||||
(mcp_config, runtime_context)
|
||||
}
|
||||
};
|
||||
let effective_servers = akode_mcp::effective_mcp_servers(&mcp_config, auth.as_ref());
|
||||
let Some(server) = effective_servers.get(&name) else {
|
||||
return Err(invalid_request(format!(
|
||||
"No MCP server named '{name}' found."
|
||||
)));
|
||||
};
|
||||
let redirect_mode = if server.is_agent_plugin() {
|
||||
StreamableHttpRedirectMode::AgentPluginV1
|
||||
} else {
|
||||
StreamableHttpRedirectMode::Legacy
|
||||
};
|
||||
let server = server.config();
|
||||
if matches!(server.auth, McpServerAuth::EmaAuth) {
|
||||
return Err(invalid_request(format!(
|
||||
"MCP server '{name}' uses enterprise-managed authorization, which is not supported."
|
||||
)));
|
||||
}
|
||||
let (authorization_url, login_id, completion): (
|
||||
String,
|
||||
String,
|
||||
futures::future::BoxFuture<'static, anyhow::Result<()>>,
|
||||
) = {
|
||||
let (url, http_headers, env_http_headers) = match &server.transport {
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
..
|
||||
} => (url.clone(), http_headers.clone(), env_http_headers.clone()),
|
||||
_ => {
|
||||
return Err(invalid_request(
|
||||
"OAuth login is only supported for streamable HTTP servers.",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let http_client =
|
||||
runtime_context
|
||||
.resolve_http_client(&name, server)
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to resolve MCP server runtime: {err}"))
|
||||
})?;
|
||||
|
||||
let discovered_scopes = if scopes.is_none() && server.scopes.is_none() {
|
||||
discover_supported_scopes(
|
||||
&server.transport,
|
||||
Arc::clone(&http_client),
|
||||
akode_rmcp_client::OAuthDiscoveryTimeout::Requested,
|
||||
redirect_mode,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let resolved_scopes =
|
||||
resolve_oauth_scopes(scopes, server.scopes.clone(), discovered_scopes);
|
||||
let oauth_credential_name = server.oauth_credential_name(&name);
|
||||
let client_registration = match client_registration.unwrap_or_default() {
|
||||
McpServerOauthClientRegistration::Auto => McpOAuthClientRegistration::Auto,
|
||||
McpServerOauthClientRegistration::Cimd => McpOAuthClientRegistration::Cimd,
|
||||
McpServerOauthClientRegistration::Dcr => McpOAuthClientRegistration::Dcr,
|
||||
};
|
||||
let callback_url =
|
||||
resolve_oauth_callback(server, &url, mcp_config.mcp_oauth_callback_url.as_deref())
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to resolve MCP OAuth callback: {err}"))
|
||||
})?;
|
||||
|
||||
let handle = perform_oauth_login_return_url(
|
||||
oauth_credential_name.as_ref(),
|
||||
&url,
|
||||
mcp_config.mcp_oauth_credentials_store_mode,
|
||||
mcp_config.auth_keyring_backend_kind,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
&resolved_scopes.scopes,
|
||||
server.oauth.as_ref(),
|
||||
client_registration,
|
||||
server.oauth_resource.as_deref(),
|
||||
timeout_secs,
|
||||
server.oauth_callback_port(mcp_config.mcp_oauth_callback_port),
|
||||
callback_url.as_deref(),
|
||||
mcp_config.mcp_oauth_callback_url.as_deref(),
|
||||
http_client,
|
||||
redirect_mode,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to login to MCP server '{name}': {err}"))
|
||||
})?;
|
||||
(
|
||||
handle.authorization_url().to_string(),
|
||||
Uuid::now_v7().to_string(),
|
||||
Box::pin(handle.wait()),
|
||||
)
|
||||
};
|
||||
let notification_name = name.clone();
|
||||
let notification_thread_id = thread_id;
|
||||
let notification_login_id = login_id.clone();
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let thread_manager = Arc::clone(&self.thread_manager);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let (success, error) = match completion.await {
|
||||
Ok(()) => (true, None),
|
||||
Err(err) => (false, Some(err.to_string())),
|
||||
};
|
||||
if success {
|
||||
thread_manager.invalidate_mcp_runtimes().await;
|
||||
}
|
||||
|
||||
let notification = ServerNotification::McpServerOauthLoginCompleted(
|
||||
McpServerOauthLoginCompletedNotification {
|
||||
name: notification_name,
|
||||
thread_id: notification_thread_id,
|
||||
login_id: Some(notification_login_id),
|
||||
success,
|
||||
error,
|
||||
},
|
||||
);
|
||||
outgoing.send_server_notification(notification).await;
|
||||
});
|
||||
|
||||
Ok(McpServerOauthLoginResponse {
|
||||
authorization_url,
|
||||
login_id: Some(login_id),
|
||||
})
|
||||
}
|
||||
|
||||
async fn list_mcp_server_status(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: ListMcpServerStatusParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let request = request_id.clone();
|
||||
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let thread = match params.thread_id.as_deref() {
|
||||
Some(thread_id) => Some(self.load_thread(thread_id).await?.1),
|
||||
None => None,
|
||||
};
|
||||
let processor = self.clone();
|
||||
let task = async move {
|
||||
let result = processor
|
||||
.list_mcp_server_status_response(params, thread)
|
||||
.await;
|
||||
outgoing.send_result(request, result).await;
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_mcp_server_status_response(
|
||||
&self,
|
||||
params: ListMcpServerStatusParams,
|
||||
thread: Option<Arc<akode_core::CodexThread>>,
|
||||
) -> Result<ListMcpServerStatusResponse, JSONRPCErrorError> {
|
||||
let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) {
|
||||
McpServerStatusDetail::Full => McpSnapshotDetail::Full,
|
||||
McpServerStatusDetail::ToolsAndAuthOnly => McpSnapshotDetail::ToolsAndAuthOnly,
|
||||
};
|
||||
|
||||
let (mcp_config, snapshot) = if let (Some(thread), Some(server)) =
|
||||
(thread.as_ref(), params.server_name.as_deref())
|
||||
{
|
||||
thread
|
||||
.mcp_server_status_snapshot(server, detail, /*expected_registration*/ None)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
internal_error(format!("failed to read MCP server status: {error:#}"))
|
||||
})?
|
||||
} else {
|
||||
let config = match thread.as_ref() {
|
||||
Some(thread) => {
|
||||
let thread_config = thread.config().await;
|
||||
self.config_manager
|
||||
.load_latest_config_with_session_layers(
|
||||
&thread_config.config_layer_stack,
|
||||
&thread_config.cwd,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?
|
||||
}
|
||||
None => self.load_global_config().await?,
|
||||
};
|
||||
let mcp_manager = thread
|
||||
.as_ref()
|
||||
.map(|thread| thread.mcp_manager())
|
||||
.unwrap_or_else(|| self.thread_manager.mcp_manager());
|
||||
let auth = mcp_manager.auth_manager().auth().await;
|
||||
let (mcp_config, runtime_context) = match thread.as_ref() {
|
||||
Some(thread) => thread.runtime_mcp_config_and_context(&config).await,
|
||||
None => (
|
||||
mcp_manager.runtime_config(&config).await,
|
||||
McpRuntimeContext::new(
|
||||
self.thread_manager.environment_manager(),
|
||||
config.cwd.to_path_buf(),
|
||||
),
|
||||
),
|
||||
};
|
||||
let snapshot = collect_mcp_server_status_snapshot_with_detail(
|
||||
&mcp_config,
|
||||
auth.as_ref(),
|
||||
runtime_context,
|
||||
mcp_manager.tool_catalog_cache(),
|
||||
detail,
|
||||
params.server_name.as_deref(),
|
||||
)
|
||||
.await;
|
||||
(Arc::new(mcp_config), snapshot)
|
||||
};
|
||||
|
||||
let runtime_statuses = match thread {
|
||||
Some(thread) => thread.mcp_connection_statuses(&mcp_config).await,
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let McpServerStatusSnapshot {
|
||||
mut server_infos,
|
||||
mut server_capabilities,
|
||||
mut tool_list_meta,
|
||||
mut tools_by_server,
|
||||
mut tools_errors,
|
||||
mut resources,
|
||||
mut resource_templates,
|
||||
mut auth_statuses,
|
||||
mut server_names,
|
||||
} = snapshot;
|
||||
server_names.extend(runtime_statuses.keys().cloned());
|
||||
server_names.extend(
|
||||
auth_statuses
|
||||
.keys()
|
||||
.cloned()
|
||||
.chain(resources.keys().cloned())
|
||||
.chain(resource_templates.keys().cloned()),
|
||||
);
|
||||
server_names.sort();
|
||||
server_names.dedup();
|
||||
server_names.retain(|name| {
|
||||
params
|
||||
.server_name
|
||||
.as_deref()
|
||||
.is_none_or(|server| name == server)
|
||||
});
|
||||
|
||||
let total = server_names.len();
|
||||
let limit = params.limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let effective_limit = limit.min(total);
|
||||
let start = match params.cursor {
|
||||
Some(cursor) => match cursor.parse::<usize>() {
|
||||
Ok(idx) => idx,
|
||||
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total MCP servers {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
|
||||
let data: Vec<McpServerStatus> = server_names[start..end]
|
||||
.iter()
|
||||
.map(|name| McpServerStatus {
|
||||
name: name.clone(),
|
||||
runtime_status: runtime_statuses.get(name).copied().map(Into::into),
|
||||
plugin_id: mcp_config.mcp_server_catalog.server(name).and_then(
|
||||
|server| match server.source() {
|
||||
McpServerSource::Plugin(plugin)
|
||||
| McpServerSource::SelectedPlugin(plugin) => {
|
||||
Some(plugin.plugin_id().to_owned())
|
||||
}
|
||||
McpServerSource::Config
|
||||
| McpServerSource::Compatibility { .. }
|
||||
| McpServerSource::Extension { .. } => None,
|
||||
},
|
||||
),
|
||||
http_origin: mcp_config
|
||||
.mcp_server_catalog
|
||||
.server(name)
|
||||
.and_then(|server| match &server.config().transport {
|
||||
McpServerTransportConfig::StreamableHttp { url, .. } => {
|
||||
url::Url::parse(url).ok().and_then(|url| {
|
||||
matches!(url.scheme(), "http" | "https")
|
||||
.then(|| url.origin().ascii_serialization())
|
||||
})
|
||||
}
|
||||
McpServerTransportConfig::Stdio { .. } => None,
|
||||
}),
|
||||
server_info: server_infos.remove(name),
|
||||
server_capabilities: server_capabilities.remove(name),
|
||||
tool_list_meta: tool_list_meta.remove(name).map(Arc::unwrap_or_clone),
|
||||
tools: tools_by_server.remove(name).unwrap_or_default(),
|
||||
tools_error: tools_errors.remove(name),
|
||||
resources: resources.remove(name).unwrap_or_default(),
|
||||
resource_templates: resource_templates.remove(name).unwrap_or_default(),
|
||||
auth_status: auth_statuses
|
||||
.remove(name)
|
||||
.unwrap_or(CoreMcpAuthStatus::Unsupported)
|
||||
.into(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let next_cursor = if end < total {
|
||||
Some(end.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(ListMcpServerStatusResponse { data, next_cursor })
|
||||
}
|
||||
|
||||
async fn read_mcp_resource(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: McpResourceReadParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let McpResourceReadParams {
|
||||
meta,
|
||||
thread_id,
|
||||
server,
|
||||
uri,
|
||||
} = params;
|
||||
let mut resource_params = ReadResourceRequestParams::new(uri);
|
||||
let meta = meta.unwrap_or_default();
|
||||
let reserved_key = meta.keys().find(|key| {
|
||||
matches!(
|
||||
key.as_str(),
|
||||
"x-codex-turn-metadata"
|
||||
| MCP_THREAD_ID_META_KEY
|
||||
| akode_mcp::MCP_CONNECTION_LEASE_META_KEY
|
||||
)
|
||||
});
|
||||
if let Some(key) = reserved_key {
|
||||
return Err(invalid_request(format!(
|
||||
"reserved resource read metadata key: {key}"
|
||||
)));
|
||||
}
|
||||
if !meta.is_empty() {
|
||||
resource_params.meta = Some(meta.into());
|
||||
}
|
||||
|
||||
if let Some(thread_id) = thread_id {
|
||||
let (_, thread) = self.load_thread(&thread_id).await?;
|
||||
let request_id = request_id.clone();
|
||||
|
||||
let task = async move {
|
||||
let result = thread.read_mcp_resource(&server, resource_params).await;
|
||||
Self::send_mcp_resource_read_response(outgoing, request_id, result).await;
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let config = self.load_global_config().await?;
|
||||
let mcp_manager = self.thread_manager.mcp_manager();
|
||||
let mcp_config = mcp_manager.runtime_config(&config).await;
|
||||
let tool_catalog_cache = mcp_manager.tool_catalog_cache();
|
||||
let auth = mcp_manager.auth_manager().auth().await;
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
// This threadless resource-read path has no turn cwd or turn-selected
|
||||
// environment. Use config cwd only as the local stdio fallback; named
|
||||
// environment stdio MCPs must declare their own absolute cwd.
|
||||
let runtime_context =
|
||||
McpRuntimeContext::new(Arc::clone(&environment_manager), config.cwd.to_path_buf());
|
||||
let request_id = request_id.clone();
|
||||
|
||||
let task = async move {
|
||||
let result = read_mcp_resource_without_thread(
|
||||
&mcp_config,
|
||||
auth.as_ref(),
|
||||
runtime_context,
|
||||
tool_catalog_cache,
|
||||
&server,
|
||||
resource_params,
|
||||
)
|
||||
.await
|
||||
.and_then(|result| serde_json::to_value(result).map_err(anyhow::Error::from));
|
||||
Self::send_mcp_resource_read_response(outgoing, request_id, result).await;
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_mcp_resource_read_response(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
request_id: ConnectionRequestId,
|
||||
result: anyhow::Result<serde_json::Value>,
|
||||
) {
|
||||
let result = result
|
||||
.map_err(mcp_operation_error)
|
||||
.and_then(|result| {
|
||||
serde_json::from_value::<McpResourceReadResponse>(result).map_err(|error| {
|
||||
internal_error(format!(
|
||||
"failed to deserialize MCP resource read response: {error}"
|
||||
))
|
||||
})
|
||||
});
|
||||
outgoing.send_result(request_id, result).await;
|
||||
}
|
||||
|
||||
async fn call_mcp_server_tool(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: McpServerToolCallParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let thread_id = params.thread_id.clone();
|
||||
let (_, thread) = self.load_thread(&thread_id).await?;
|
||||
ensure_direct_input_allowed(thread.as_ref()).await?;
|
||||
let meta = with_mcp_tool_call_thread_id_meta(params.meta, &thread_id);
|
||||
let request_id = request_id.clone();
|
||||
|
||||
let task = async move {
|
||||
let result = thread
|
||||
.call_mcp_tool(¶ms.server, ¶ms.tool, params.arguments, meta)
|
||||
.await
|
||||
.map(McpServerToolCallResponse::from)
|
||||
.map_err(mcp_operation_error);
|
||||
outgoing.send_result(request_id, result).await;
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp_operation_error(error: anyhow::Error) -> JSONRPCErrorError {
|
||||
match akode_rmcp_client::mcp_error(&error) {
|
||||
Some(error) => JSONRPCErrorError {
|
||||
code: i64::from(error.code.0),
|
||||
message: error.message.to_string(),
|
||||
data: error.data.clone(),
|
||||
},
|
||||
None => internal_error(format!("{error:#}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_mcp_tool_call_thread_id_meta(
|
||||
meta: Option<serde_json::Value>,
|
||||
thread_id: &str,
|
||||
) -> Option<serde_json::Value> {
|
||||
match meta {
|
||||
Some(serde_json::Value::Object(mut map)) => {
|
||||
map.insert(
|
||||
MCP_THREAD_ID_META_KEY.to_string(),
|
||||
serde_json::Value::String(thread_id.to_string()),
|
||||
);
|
||||
Some(serde_json::Value::Object(map))
|
||||
}
|
||||
None => {
|
||||
let mut map = serde_json::Map::new();
|
||||
map.insert(
|
||||
MCP_THREAD_ID_META_KEY.to_string(),
|
||||
serde_json::Value::String(thread_id.to_string()),
|
||||
);
|
||||
Some(serde_json::Value::Object(map))
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
59
akode-rs/app-server/src/request_processors/memory_status.rs
Normal file
59
akode-rs/app-server/src/request_processors/memory_status.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
//! Reports v2 readiness without exposing memory contents or persistence details to clients.
|
||||
|
||||
use super::*;
|
||||
use akode_app_server_protocol::MemoryStatusParams;
|
||||
use akode_app_server_protocol::MemoryStatusResponse;
|
||||
use akode_protocol::MemoryVersion;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn memory_status(
|
||||
&self,
|
||||
params: MemoryStatusParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let minimum = params.min_consolidated_threads.unwrap_or(20);
|
||||
if !(1..=4096).contains(&minimum) {
|
||||
return Err(invalid_params(
|
||||
"minConsolidatedThreads must be between 1 and 4096",
|
||||
));
|
||||
}
|
||||
let db = self
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("sqlite state db unavailable for memory status"))?;
|
||||
let store = db
|
||||
.memories_for_version(MemoryVersion::V2)
|
||||
.await
|
||||
.map_err(|error| internal_error(format!("failed to open v2 memory state: {error}")))?;
|
||||
let count = store
|
||||
.max_consolidated_thread_count()
|
||||
.await
|
||||
.map_err(|error| internal_error(format!("failed to read memory progress: {error}")))?;
|
||||
let root = self
|
||||
.config
|
||||
.codex_home
|
||||
.join(MemoryVersion::V2.directory_name());
|
||||
let summary = tokio::fs::read_to_string(root.join("memory_summary.md"))
|
||||
.await
|
||||
.ok();
|
||||
let has_v1_workspace = tokio::fs::try_exists(
|
||||
self.config
|
||||
.codex_home
|
||||
.join(MemoryVersion::V1.directory_name()),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| internal_error(format!("failed to check v1 memory workspace: {error}")))?;
|
||||
// Fresh profiles can start on V2 without consolidating any V1 history first.
|
||||
let ready = !has_v1_workspace
|
||||
|| count >= minimum
|
||||
&& summary
|
||||
.as_deref()
|
||||
.is_some_and(akode_memories_write::workspace::is_valid_v2_summary);
|
||||
Ok(Some(
|
||||
MemoryStatusResponse {
|
||||
v2_consolidated_threads: count,
|
||||
v2_ready: ready,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::config_types::ApprovalsReviewer;
|
||||
use akode_protocol::models::ActivePermissionProfile;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::ThreadSettingsSnapshot;
|
||||
use akode_rollout::InitialHistory;
|
||||
use akode_rollout::RolloutItem;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct PersistedResumeSettings {
|
||||
pub(super) approval_policy: AskForApproval,
|
||||
pub(super) approvals_reviewer: Option<ApprovalsReviewer>,
|
||||
pub(super) active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub(super) unnamed_permission_profile: Option<PermissionProfile>,
|
||||
}
|
||||
|
||||
impl PersistedResumeSettings {
|
||||
pub(super) fn from_history(history: &[RolloutItem], thread_id: ThreadId) -> Option<Self> {
|
||||
// A running turn can record stale permissions. Prefer a settings update whose
|
||||
// owner is known, including a legacy update following that owner's checkpoint.
|
||||
let mut latest_legacy = None;
|
||||
for item in history.iter().rev() {
|
||||
let RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) = item else {
|
||||
continue;
|
||||
};
|
||||
match event.thread_id {
|
||||
Some(owner) if owner == thread_id => {
|
||||
return Some(Self::from(latest_legacy.unwrap_or(&event.thread_settings)));
|
||||
}
|
||||
Some(_) => latest_legacy = None,
|
||||
None => {
|
||||
latest_legacy.get_or_insert(&event.thread_settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
latest_persisted_resume_settings(history)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&ThreadSettingsSnapshot> for PersistedResumeSettings {
|
||||
fn from(settings: &ThreadSettingsSnapshot) -> Self {
|
||||
Self {
|
||||
approval_policy: settings.approval_policy,
|
||||
approvals_reviewer: Some(
|
||||
settings
|
||||
.requested_approvals_reviewer
|
||||
.unwrap_or(settings.approvals_reviewer),
|
||||
),
|
||||
active_permission_profile: settings.active_permission_profile.clone(),
|
||||
unnamed_permission_profile: settings
|
||||
.active_permission_profile
|
||||
.is_none()
|
||||
.then(|| settings.permission_profile.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn latest_owned_thread_settings(
|
||||
history: &[RolloutItem],
|
||||
thread_id: ThreadId,
|
||||
) -> Option<&ThreadSettingsSnapshot> {
|
||||
history.iter().rev().find_map(|item| match item {
|
||||
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event))
|
||||
if event.thread_id == Some(thread_id) =>
|
||||
{
|
||||
Some(&event.thread_settings)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn latest_persisted_resume_settings(history: &[RolloutItem]) -> Option<PersistedResumeSettings> {
|
||||
history
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find_map(|(index, item)| match item {
|
||||
RolloutItem::TurnContext(turn_context) => Some(PersistedResumeSettings {
|
||||
approval_policy: turn_context.approval_policy,
|
||||
approvals_reviewer: turn_context.approvals_reviewer.or_else(|| {
|
||||
history[..index].iter().rev().find_map(|item| match item {
|
||||
RolloutItem::TurnContext(turn_context) => turn_context.approvals_reviewer,
|
||||
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) => Some(
|
||||
event
|
||||
.thread_settings
|
||||
.requested_approvals_reviewer
|
||||
.unwrap_or(event.thread_settings.approvals_reviewer),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
}),
|
||||
active_permission_profile: turn_context.active_permission_profile.clone(),
|
||||
unnamed_permission_profile: None,
|
||||
}),
|
||||
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) => {
|
||||
// History without an identifiable owner can supply a profile ID, but
|
||||
// its raw filesystem grants may belong to another thread or executor.
|
||||
let settings = &event.thread_settings;
|
||||
Some(PersistedResumeSettings {
|
||||
approval_policy: settings.approval_policy,
|
||||
approvals_reviewer: Some(
|
||||
settings
|
||||
.requested_approvals_reviewer
|
||||
.unwrap_or(settings.approvals_reviewer),
|
||||
),
|
||||
active_permission_profile: settings.active_permission_profile.clone(),
|
||||
unnamed_permission_profile: None,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn latest_persisted_model_settings(
|
||||
history: &InitialHistory,
|
||||
) -> Option<&ThreadSettingsSnapshot> {
|
||||
let InitialHistory::Resumed(history) = history else {
|
||||
return None;
|
||||
};
|
||||
let mut crossed_foreign_snapshot = false;
|
||||
for item in history.history.iter().rev() {
|
||||
let RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) = item else {
|
||||
continue;
|
||||
};
|
||||
match event.thread_id {
|
||||
Some(thread_id) if thread_id == history.conversation_id => {
|
||||
return Some(&event.thread_settings);
|
||||
}
|
||||
Some(_) => crossed_foreign_snapshot = true,
|
||||
None if !crossed_foreign_snapshot => return Some(&event.thread_settings),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "persisted_resume_settings_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,241 @@
|
||||
use super::PersistedResumeSettings;
|
||||
use super::latest_persisted_resume_settings;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::config_types::ApprovalsReviewer;
|
||||
use akode_protocol::config_types::CollaborationMode;
|
||||
use akode_protocol::config_types::ModeKind;
|
||||
use akode_protocol::config_types::Settings;
|
||||
use akode_protocol::models::ActivePermissionProfile;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::ThreadSettingsAppliedEvent;
|
||||
use akode_protocol::protocol::ThreadSettingsSnapshot;
|
||||
use akode_protocol::protocol::TurnContextItem;
|
||||
use akode_rollout::RolloutItem;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn cwd() -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::try_from(std::env::current_dir().expect("current directory"))
|
||||
.expect("absolute current directory")
|
||||
}
|
||||
|
||||
fn settings_item(
|
||||
thread_id: Option<ThreadId>,
|
||||
approval_policy: AskForApproval,
|
||||
approvals_reviewer: ApprovalsReviewer,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(
|
||||
ThreadSettingsAppliedEvent {
|
||||
thread_id,
|
||||
thread_settings: ThreadSettingsSnapshot {
|
||||
disabled_plugin_ids: Vec::new(),
|
||||
model: "gpt-5".to_string(),
|
||||
model_provider_id: "openai".to_string(),
|
||||
service_tier: None,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
requested_approvals_reviewer: None,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile,
|
||||
cwd: cwd(),
|
||||
runtime_workspace_roots: None,
|
||||
reasoning_effort: None,
|
||||
reasoning_summary: None,
|
||||
personality: None,
|
||||
collaboration_mode: CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: "gpt-5".to_string(),
|
||||
reasoning_effort: None,
|
||||
developer_instructions: None,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn turn_context_item(
|
||||
turn_id: &str,
|
||||
approval_policy: AskForApproval,
|
||||
approvals_reviewer: Option<ApprovalsReviewer>,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
) -> RolloutItem {
|
||||
RolloutItem::TurnContext(TurnContextItem {
|
||||
turn_id: Some(turn_id.to_string()),
|
||||
root_turn_id: None,
|
||||
direct_only_tool_namespaces: None,
|
||||
disabled_plugin_ids: None,
|
||||
cwd: cwd(),
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile,
|
||||
model: "gpt-5".to_string(),
|
||||
comp_hash: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
effort: None,
|
||||
summary: Some(akode_protocol::config_types::ReasoningSummary::Auto),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_settings_snapshot_wins() {
|
||||
let expected = PersistedResumeSettings {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
active_permission_profile: Some(ActivePermissionProfile::new("dev")),
|
||||
unnamed_permission_profile: None,
|
||||
};
|
||||
let history = vec![
|
||||
settings_item(
|
||||
/*thread_id*/ None,
|
||||
AskForApproval::Never,
|
||||
ApprovalsReviewer::User,
|
||||
/*active_permission_profile*/ None,
|
||||
),
|
||||
settings_item(
|
||||
/*thread_id*/ None,
|
||||
AskForApproval::OnRequest,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
Some(ActivePermissionProfile::new("dev")),
|
||||
),
|
||||
];
|
||||
|
||||
assert_eq!(latest_persisted_resume_settings(&history), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_turn_context_wins_over_earlier_settings_update() {
|
||||
let expected = PersistedResumeSettings {
|
||||
approval_policy: AskForApproval::UnlessTrusted,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
active_permission_profile: Some(ActivePermissionProfile::read_only()),
|
||||
unnamed_permission_profile: None,
|
||||
};
|
||||
let history = vec![
|
||||
settings_item(
|
||||
/*thread_id*/ None,
|
||||
AskForApproval::Never,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
Some(ActivePermissionProfile::new("dev")),
|
||||
),
|
||||
turn_context_item(
|
||||
"turn-2",
|
||||
AskForApproval::UnlessTrusted,
|
||||
Some(ApprovalsReviewer::User),
|
||||
Some(ActivePermissionProfile::read_only()),
|
||||
),
|
||||
];
|
||||
|
||||
assert_eq!(latest_persisted_resume_settings(&history), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newer_legacy_permissions_only_supersede_their_own_threads_checkpoint() {
|
||||
let thread_id = ThreadId::new();
|
||||
let other_thread_id = ThreadId::new();
|
||||
let workspace = ActivePermissionProfile::new(":workspace");
|
||||
let read_only = ActivePermissionProfile::read_only();
|
||||
let owned = settings_item(
|
||||
Some(thread_id),
|
||||
AskForApproval::Never,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
Some(workspace.clone()),
|
||||
);
|
||||
let legacy = settings_item(
|
||||
/*thread_id*/ None,
|
||||
AskForApproval::OnRequest,
|
||||
ApprovalsReviewer::User,
|
||||
Some(read_only.clone()),
|
||||
);
|
||||
let stale_turn = turn_context_item(
|
||||
"turn",
|
||||
AskForApproval::Never,
|
||||
Some(ApprovalsReviewer::AutoReview),
|
||||
Some(workspace.clone()),
|
||||
);
|
||||
let foreign = settings_item(
|
||||
Some(other_thread_id),
|
||||
AskForApproval::Never,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
Some(workspace.clone()),
|
||||
);
|
||||
let foreign_legacy = settings_item(
|
||||
/*thread_id*/ None,
|
||||
AskForApproval::Never,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
Some(workspace.clone()),
|
||||
);
|
||||
let mut history = vec![owned.clone(), legacy.clone(), stale_turn.clone()];
|
||||
let expected = Some(PersistedResumeSettings {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
active_permission_profile: Some(read_only),
|
||||
unnamed_permission_profile: None,
|
||||
});
|
||||
assert_eq!(
|
||||
PersistedResumeSettings::from_history(&history, thread_id),
|
||||
expected
|
||||
);
|
||||
history.extend([foreign.clone(), foreign_legacy]);
|
||||
assert_eq!(
|
||||
PersistedResumeSettings::from_history(&history, thread_id),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
PersistedResumeSettings::from_history(&[owned, foreign, legacy, stale_turn], thread_id),
|
||||
Some(PersistedResumeSettings {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
active_permission_profile: Some(workspace),
|
||||
unnamed_permission_profile: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_reviewer_is_used_when_latest_turn_context_omits_it() {
|
||||
let history = vec![
|
||||
turn_context_item(
|
||||
"turn-1",
|
||||
AskForApproval::Never,
|
||||
Some(ApprovalsReviewer::AutoReview),
|
||||
/*active_permission_profile*/ None,
|
||||
),
|
||||
turn_context_item(
|
||||
"turn-2",
|
||||
AskForApproval::OnRequest,
|
||||
/*approvals_reviewer*/ None,
|
||||
/*active_permission_profile*/ None,
|
||||
),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
latest_persisted_resume_settings(&history),
|
||||
Some(PersistedResumeSettings {
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
active_permission_profile: None,
|
||||
unnamed_permission_profile: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unattributed_snapshot_does_not_restore_unnamed_permissions() {
|
||||
let history = [settings_item(
|
||||
/*thread_id*/ None,
|
||||
AskForApproval::OnRequest,
|
||||
ApprovalsReviewer::User,
|
||||
/*active_permission_profile*/ None,
|
||||
)];
|
||||
let settings =
|
||||
PersistedResumeSettings::from_history(&history, ThreadId::new()).expect("legacy settings");
|
||||
assert_eq!(settings.unnamed_permission_profile, None);
|
||||
}
|
||||
831
akode-rs/app-server/src/request_processors/plugins.rs
Normal file
831
akode-rs/app-server/src/request_processors/plugins.rs
Normal file
@@ -0,0 +1,831 @@
|
||||
use super::config_processor::reload_user_config;
|
||||
use super::*;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use akode_config::types::McpServerConfig;
|
||||
use akode_core_plugins::PluginListBackgroundTaskOptions;
|
||||
use akode_core_plugins::PluginMarketplaceContext;
|
||||
use akode_core_plugins::loader::load_configured_plugin_mcp_servers;
|
||||
use akode_core_plugins::manifest::is_agent_plugin_manifest;
|
||||
use akode_mcp::McpOAuthLoginSupport;
|
||||
use akode_mcp::McpRuntimeContext;
|
||||
use akode_mcp::oauth_login_support;
|
||||
use akode_mcp::resolve_oauth_callback;
|
||||
use akode_mcp::should_retry_without_scopes;
|
||||
use akode_plugin::PluginId;
|
||||
use akode_rmcp_client::McpOAuthClientRegistration;
|
||||
use akode_rmcp_client::OAuthDiscoveryTimeout;
|
||||
use akode_rmcp_client::StreamableHttpRedirectMode;
|
||||
use akode_rmcp_client::perform_oauth_login_silent;
|
||||
use akode_utils_path_uri::LegacyAppPathString;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
|
||||
mod local;
|
||||
mod search;
|
||||
|
||||
fn plugin_redirect_mode(plugin_root: &Path) -> StreamableHttpRedirectMode {
|
||||
if is_agent_plugin_manifest(plugin_root) {
|
||||
StreamableHttpRedirectMode::AgentPluginV1
|
||||
} else {
|
||||
StreamableHttpRedirectMode::Legacy
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PluginRequestProcessor {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
on_effective_plugins_changed:
|
||||
Arc<dyn Fn(akode_core_plugins::EffectivePluginsChange) + Send + Sync>,
|
||||
}
|
||||
|
||||
fn plugin_skills_to_info<'a>(
|
||||
skills: impl IntoIterator<Item = &'a akode_skills::SkillMetadata>,
|
||||
disabled_skill_paths: &HashSet<PathUri>,
|
||||
) -> Vec<SkillSummary> {
|
||||
skills
|
||||
.into_iter()
|
||||
.map(|skill| SkillSummary {
|
||||
name: skill.name.clone(),
|
||||
description: skill.description.clone(),
|
||||
short_description: skill.short_description.clone(),
|
||||
interface: skill.interface.clone().map(|interface| {
|
||||
akode_app_server_protocol::SkillInterface {
|
||||
display_name: interface.display_name,
|
||||
short_description: interface.short_description,
|
||||
icon_small: interface.icon_small,
|
||||
icon_large: interface.icon_large,
|
||||
|
||||
brand_color: interface.brand_color,
|
||||
default_prompt: interface.default_prompt,
|
||||
}
|
||||
}),
|
||||
path: Some(skill.path_to_skills_md.clone().into()),
|
||||
enabled: !disabled_skill_paths.contains(&skill.path_to_skills_md),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn local_plugin_interface_to_info(interface: PluginManifestInterface) -> PluginInterface {
|
||||
PluginInterface {
|
||||
display_name: interface.display_name,
|
||||
short_description: interface.short_description,
|
||||
long_description: interface.long_description,
|
||||
developer_name: interface.developer_name,
|
||||
category: interface.category,
|
||||
capabilities: interface.capabilities,
|
||||
website_url: interface.website_url,
|
||||
privacy_policy_url: interface.privacy_policy_url,
|
||||
terms_of_service_url: interface.terms_of_service_url,
|
||||
default_prompt: interface.default_prompt,
|
||||
brand_color: interface.brand_color,
|
||||
composer_icon: interface.composer_icon,
|
||||
logo: interface.logo,
|
||||
logo_dark: interface.logo_dark,
|
||||
screenshots: interface.screenshots,
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_plugin_source_to_info(source: MarketplacePluginSource) -> PluginSource {
|
||||
match source {
|
||||
MarketplacePluginSource::Local { path } => PluginSource::Local { path },
|
||||
MarketplacePluginSource::Git {
|
||||
url,
|
||||
path,
|
||||
ref_name,
|
||||
sha,
|
||||
} => PluginSource::Git {
|
||||
url,
|
||||
path,
|
||||
ref_name,
|
||||
sha,
|
||||
},
|
||||
MarketplacePluginSource::Npm {
|
||||
package,
|
||||
version,
|
||||
registry,
|
||||
} => PluginSource::Npm {
|
||||
package,
|
||||
version,
|
||||
registry,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_configured_marketplace_plugin_to_plugin_summary(
|
||||
plugin: akode_core_plugins::ConfiguredMarketplacePlugin,
|
||||
) -> PluginSummary {
|
||||
PluginSummary {
|
||||
id: plugin.id,
|
||||
local_version: plugin.local_version,
|
||||
installed: plugin.installed,
|
||||
enabled: plugin.enabled,
|
||||
name: plugin.name,
|
||||
source: marketplace_plugin_source_to_info(plugin.source),
|
||||
install_policy: plugin.policy.installation.into(),
|
||||
auth_policy: plugin.policy.authentication.into(),
|
||||
interface: plugin.interface.map(local_plugin_interface_to_info),
|
||||
keywords: plugin.keywords,
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
on_effective_plugins_changed: Arc<
|
||||
dyn Fn(akode_core_plugins::EffectivePluginsChange) + Send + Sync,
|
||||
>,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
outgoing,
|
||||
config_manager,
|
||||
on_effective_plugins_changed,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn plugin_list(
|
||||
&self,
|
||||
params: PluginListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.plugin_list_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn plugin_installed(
|
||||
&self,
|
||||
params: PluginInstalledParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.plugin_installed_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn plugin_read(
|
||||
&self,
|
||||
params: PluginReadParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.plugin_read_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn plugin_install(
|
||||
&self,
|
||||
params: PluginInstallParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.plugin_install_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn plugin_uninstall(
|
||||
&self,
|
||||
params: PluginUninstallParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.plugin_uninstall_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) fn effective_plugins_changed_callback(
|
||||
&self,
|
||||
) -> Arc<dyn Fn(akode_core_plugins::EffectivePluginsChange) + Send + Sync> {
|
||||
Arc::clone(&self.on_effective_plugins_changed)
|
||||
}
|
||||
|
||||
async fn on_effective_plugins_changed(&self) {
|
||||
self.clear_plugin_related_caches();
|
||||
self.thread_manager.invalidate_mcp_runtimes().await;
|
||||
self.thread_manager.refresh_hook_runtimes().await;
|
||||
}
|
||||
|
||||
fn clear_plugin_related_caches(&self) {
|
||||
self.thread_manager.plugins_manager().clear_cache();
|
||||
self.thread_manager.skills_service().clear_cache();
|
||||
}
|
||||
|
||||
async fn load_latest_config(
|
||||
&self,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
self.config_manager
|
||||
.load_latest_config(fallback_cwd)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
}
|
||||
|
||||
async fn plugin_list_response(
|
||||
&self,
|
||||
params: PluginListParams,
|
||||
) -> Result<PluginListResponse, JSONRPCErrorError> {
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let PluginListParams {
|
||||
cwds,
|
||||
force_refetch,
|
||||
} = params;
|
||||
let roots = cwds.unwrap_or_default();
|
||||
|
||||
let config = self.load_catalog_config(&roots).await?;
|
||||
let context = self.load_marketplace_context(roots, &config).await;
|
||||
let empty_response = || PluginListResponse {
|
||||
marketplaces: Vec::new(),
|
||||
marketplace_load_errors: Vec::new(),
|
||||
};
|
||||
if !context.plugins_enabled() && context.load_errors.is_empty() {
|
||||
return Ok(empty_response());
|
||||
}
|
||||
if force_refetch
|
||||
&& plugins_manager
|
||||
.refresh_non_curated_plugin_cache_for_context(&context)
|
||||
.await
|
||||
{
|
||||
self.on_effective_plugins_changed().await;
|
||||
}
|
||||
let context_for_marketplace_listing = context.clone();
|
||||
let plugins_manager_for_marketplace_listing = plugins_manager.clone();
|
||||
let (data, marketplace_load_errors, local_marketplaces) =
|
||||
match tokio::task::spawn_blocking(move || {
|
||||
let outcome = plugins_manager_for_marketplace_listing
|
||||
.list_marketplaces_for_context(
|
||||
&context_for_marketplace_listing,
|
||||
/*include_openai_curated*/ true,
|
||||
)?;
|
||||
let local_marketplaces = outcome.marketplaces.clone();
|
||||
Ok::<
|
||||
(
|
||||
Vec<PluginMarketplaceEntry>,
|
||||
Vec<akode_app_server_protocol::MarketplaceLoadErrorInfo>,
|
||||
Vec<akode_core_plugins::ConfiguredMarketplace>,
|
||||
),
|
||||
MarketplaceError,
|
||||
>((
|
||||
outcome
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.map(|marketplace| PluginMarketplaceEntry {
|
||||
name: marketplace.name,
|
||||
path: Some(marketplace.path),
|
||||
interface: marketplace.interface.map(|interface| {
|
||||
MarketplaceInterface {
|
||||
display_name: interface.display_name,
|
||||
}
|
||||
}),
|
||||
plugins: marketplace
|
||||
.plugins
|
||||
.into_iter()
|
||||
.map(convert_configured_marketplace_plugin_to_plugin_summary)
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
outcome
|
||||
.errors
|
||||
.into_iter()
|
||||
.map(|err| akode_app_server_protocol::MarketplaceLoadErrorInfo {
|
||||
marketplace_path: err.path,
|
||||
message: err.message,
|
||||
})
|
||||
.collect(),
|
||||
local_marketplaces,
|
||||
))
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(outcome)) => outcome,
|
||||
Ok(Err(err)) => {
|
||||
return Err(Self::marketplace_error(err, "list marketplace plugins"));
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(internal_error(format!(
|
||||
"failed to list marketplace plugins: {err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
plugins_manager.maybe_start_plugin_list_background_tasks(
|
||||
&context,
|
||||
PluginListBackgroundTaskOptions { local_marketplaces },
|
||||
);
|
||||
|
||||
Ok(PluginListResponse {
|
||||
marketplaces: data,
|
||||
marketplace_load_errors,
|
||||
})
|
||||
}
|
||||
|
||||
async fn plugin_installed_response(
|
||||
&self,
|
||||
params: PluginInstalledParams,
|
||||
) -> Result<PluginInstalledResponse, JSONRPCErrorError> {
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let PluginInstalledParams {
|
||||
cwds,
|
||||
install_suggestion_plugin_names,
|
||||
} = params;
|
||||
let roots = cwds.unwrap_or_default();
|
||||
let install_suggestion_plugin_names = install_suggestion_plugin_names
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
let empty_response = || PluginInstalledResponse {
|
||||
marketplaces: Vec::new(),
|
||||
marketplace_load_errors: Vec::new(),
|
||||
};
|
||||
let config = self.load_catalog_config(&roots).await?;
|
||||
let context = self.load_marketplace_context(roots, &config).await;
|
||||
if !context.plugins_enabled() && context.load_errors.is_empty() {
|
||||
return Ok(empty_response());
|
||||
}
|
||||
let (data, marketplace_load_errors) = self
|
||||
.load_local_installed_and_suggested_plugins(
|
||||
plugins_manager,
|
||||
&context,
|
||||
install_suggestion_plugin_names,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(PluginInstalledResponse {
|
||||
marketplaces: data,
|
||||
marketplace_load_errors,
|
||||
})
|
||||
}
|
||||
|
||||
async fn load_local_installed_and_suggested_plugins(
|
||||
&self,
|
||||
plugins_manager: Arc<akode_core_plugins::PluginsManager>,
|
||||
context: &PluginMarketplaceContext,
|
||||
install_suggestion_plugin_names: HashSet<String>,
|
||||
) -> Result<
|
||||
(
|
||||
Vec<PluginMarketplaceEntry>,
|
||||
Vec<akode_app_server_protocol::MarketplaceLoadErrorInfo>,
|
||||
),
|
||||
JSONRPCErrorError,
|
||||
> {
|
||||
let context = context.clone();
|
||||
match tokio::task::spawn_blocking(move || {
|
||||
let outcome = plugins_manager
|
||||
.list_marketplaces_for_context(&context, /*include_openai_curated*/ true)?;
|
||||
Ok::<
|
||||
(
|
||||
Vec<PluginMarketplaceEntry>,
|
||||
Vec<akode_app_server_protocol::MarketplaceLoadErrorInfo>,
|
||||
),
|
||||
MarketplaceError,
|
||||
>((
|
||||
outcome
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.filter_map(|marketplace| {
|
||||
let plugins = marketplace
|
||||
.plugins
|
||||
.into_iter()
|
||||
.filter(|plugin| {
|
||||
plugin.installed
|
||||
|| install_suggestion_plugin_names.contains(&plugin.name)
|
||||
})
|
||||
.map(convert_configured_marketplace_plugin_to_plugin_summary)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
(!plugins.is_empty()).then_some(PluginMarketplaceEntry {
|
||||
name: marketplace.name,
|
||||
path: Some(marketplace.path),
|
||||
interface: marketplace.interface.map(|interface| {
|
||||
MarketplaceInterface {
|
||||
display_name: interface.display_name,
|
||||
}
|
||||
}),
|
||||
plugins,
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
outcome
|
||||
.errors
|
||||
.into_iter()
|
||||
.map(|err| akode_app_server_protocol::MarketplaceLoadErrorInfo {
|
||||
marketplace_path: err.path,
|
||||
message: err.message,
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(outcome)) => Ok(outcome),
|
||||
Ok(Err(err)) => Err(Self::marketplace_error(
|
||||
err,
|
||||
"list installed and suggested marketplace plugins",
|
||||
)),
|
||||
Err(err) => Err(internal_error(format!(
|
||||
"failed to list installed and suggested plugins: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn plugin_read_response(
|
||||
&self,
|
||||
params: PluginReadParams,
|
||||
) -> Result<PluginReadResponse, JSONRPCErrorError> {
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let PluginReadParams {
|
||||
marketplace_path,
|
||||
plugin_name,
|
||||
} = params;
|
||||
let Some(marketplace_path) = marketplace_path else {
|
||||
return Err(invalid_request("plugin/read requires marketplacePath"));
|
||||
};
|
||||
let config_cwd = marketplace_path.as_path().parent().map(Path::to_path_buf);
|
||||
|
||||
let mut config = self.load_latest_config(config_cwd).await?;
|
||||
if let Some((_auth, factory)) = self.auth_manager.auth_with_http_client_factory().await {
|
||||
config.application_network_policy = factory.network_policy().clone();
|
||||
}
|
||||
let plugins_input = config.plugins_config_input();
|
||||
|
||||
let request = PluginReadRequest {
|
||||
plugin_name,
|
||||
marketplace_path,
|
||||
};
|
||||
let outcome = plugins_manager
|
||||
.read_plugin_for_config(&plugins_input, &request)
|
||||
.await
|
||||
.map_err(|err| Self::marketplace_error(err, "read plugin details"))?;
|
||||
// ChatGPT app declarations are never loaded in aKode.
|
||||
let app_summaries: Vec<AppSummary> = Vec::new();
|
||||
let visible_skills = outcome.plugin.skills.iter().filter(|skill| {
|
||||
skill.matches_product_restriction_for_product(
|
||||
self.thread_manager.session_source().restriction_product(),
|
||||
)
|
||||
});
|
||||
let skills = plugin_skills_to_info(visible_skills, &outcome.plugin.disabled_skill_paths);
|
||||
let onboarding_skill = if outcome.plugin.enabled
|
||||
&& let Some(path) = outcome.plugin.onboarding_skill.as_ref()
|
||||
{
|
||||
let path = PathUri::from_abs_path(path);
|
||||
skills
|
||||
.iter()
|
||||
.find(|skill| {
|
||||
skill.enabled
|
||||
&& skill
|
||||
.path
|
||||
.as_ref()
|
||||
.and_then(LegacyAppPathString::to_inferred_path_uri)
|
||||
.as_ref()
|
||||
== Some(&path)
|
||||
})
|
||||
.cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let plugin = PluginDetail {
|
||||
marketplace_name: outcome.marketplace_name,
|
||||
marketplace_path: outcome.marketplace_path,
|
||||
summary: PluginSummary {
|
||||
id: outcome.plugin.id,
|
||||
local_version: outcome.plugin.local_version,
|
||||
name: outcome.plugin.name,
|
||||
source: marketplace_plugin_source_to_info(outcome.plugin.source),
|
||||
installed: outcome.plugin.installed,
|
||||
enabled: outcome.plugin.enabled,
|
||||
install_policy: outcome.plugin.policy.installation.into(),
|
||||
auth_policy: outcome.plugin.policy.authentication.into(),
|
||||
interface: outcome.plugin.interface.map(local_plugin_interface_to_info),
|
||||
keywords: outcome.plugin.keywords,
|
||||
},
|
||||
description: outcome.plugin.description,
|
||||
skills,
|
||||
onboarding_skill,
|
||||
hooks: outcome
|
||||
.plugin
|
||||
.hooks
|
||||
.into_iter()
|
||||
.map(|hook| akode_app_server_protocol::PluginHookSummary {
|
||||
key: hook.key,
|
||||
event_name: hook.event_name.into(),
|
||||
})
|
||||
.collect(),
|
||||
apps: app_summaries,
|
||||
mcp_servers: outcome.plugin.mcp_server_names,
|
||||
};
|
||||
|
||||
Ok(PluginReadResponse { plugin })
|
||||
}
|
||||
|
||||
async fn plugin_install_response(
|
||||
&self,
|
||||
params: PluginInstallParams,
|
||||
) -> Result<PluginInstallResponse, JSONRPCErrorError> {
|
||||
let PluginInstallParams {
|
||||
marketplace_path,
|
||||
plugin_name,
|
||||
} = params;
|
||||
let Some(marketplace_path) = marketplace_path else {
|
||||
return Err(invalid_request("plugin/install requires marketplacePath"));
|
||||
};
|
||||
let config_cwd = marketplace_path.as_path().parent().map(Path::to_path_buf);
|
||||
let mut config = self.load_latest_config(config_cwd.clone()).await?;
|
||||
if let Some((_auth, factory)) = self.auth_manager.auth_with_http_client_factory().await {
|
||||
config.application_network_policy = factory.network_policy().clone();
|
||||
}
|
||||
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let marketplace_display = marketplace_path.display().to_string();
|
||||
let plugin_name_for_log = plugin_name.clone();
|
||||
let request = PluginInstallRequest {
|
||||
plugin_name,
|
||||
marketplace_path,
|
||||
};
|
||||
|
||||
let result = match plugins_manager
|
||||
.install_plugin(&config.config_layer_stack, request)
|
||||
.await
|
||||
{
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
marketplace = %marketplace_display,
|
||||
plugin_name = %plugin_name_for_log,
|
||||
"failed to install plugin: {err}"
|
||||
);
|
||||
return Err(Self::plugin_install_error(err));
|
||||
}
|
||||
};
|
||||
let config = match self.load_latest_config(config_cwd).await {
|
||||
Ok(mut reloaded_config) => {
|
||||
// Keep the policy captured with this installation's auth snapshot.
|
||||
reloaded_config.application_network_policy = config.application_network_policy;
|
||||
reloaded_config
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to reload config after plugin install, using current config: {err:?}"
|
||||
);
|
||||
config
|
||||
}
|
||||
};
|
||||
|
||||
self.clear_plugin_related_caches();
|
||||
reload_user_config(&self.config_manager, &self.thread_manager).await;
|
||||
self.thread_manager.invalidate_mcp_runtimes().await;
|
||||
self.thread_manager.refresh_hook_runtimes().await;
|
||||
|
||||
let plugin_mcp_servers = load_configured_plugin_mcp_servers(
|
||||
result.installed_path.as_path(),
|
||||
&result.plugin_id,
|
||||
&config.config_layer_stack,
|
||||
config.codex_home.as_path(),
|
||||
)
|
||||
.await;
|
||||
if !plugin_mcp_servers.is_empty() {
|
||||
let redirect_mode = plugin_redirect_mode(result.installed_path.as_path());
|
||||
self.start_plugin_mcp_oauth_logins(
|
||||
&config,
|
||||
&result.plugin_id,
|
||||
plugin_mcp_servers,
|
||||
redirect_mode,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ChatGPT apps never need auth in aKode: the hosted apps MCP server is never used.
|
||||
Ok(PluginInstallResponse {
|
||||
auth_policy: result.auth_policy.into(),
|
||||
apps_needing_auth: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn start_plugin_mcp_oauth_logins(
|
||||
&self,
|
||||
config: &Config,
|
||||
plugin_id: &PluginId,
|
||||
mut plugin_mcp_servers: HashMap<String, McpServerConfig>,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
) {
|
||||
let plugin_id = plugin_id.as_key();
|
||||
config.apply_plugin_mcp_server_requirements(&plugin_id, &mut plugin_mcp_servers);
|
||||
let runtime_context = McpRuntimeContext::new(
|
||||
self.thread_manager.environment_manager(),
|
||||
config.cwd.to_path_buf(),
|
||||
);
|
||||
for (name, server) in plugin_mcp_servers {
|
||||
// EMA uses the account's enterprise grant, never per-plugin OAuth fallback.
|
||||
if !server.enabled || matches!(server.auth, akode_config::types::McpServerAuth::EmaAuth)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !server.is_local_environment() {
|
||||
warn!(
|
||||
plugin = %plugin_id,
|
||||
server = %name,
|
||||
environment_id = %server.environment_id,
|
||||
"skipping plugin MCP OAuth for an unowned environment"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let http_client = match runtime_context.resolve_http_client(&name, &server) {
|
||||
Ok(http_client) => http_client,
|
||||
Err(err) => {
|
||||
warn!("failed to resolve MCP runtime for plugin install {name}: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let login_support = oauth_login_support(
|
||||
&server.transport,
|
||||
Arc::clone(&http_client),
|
||||
OAuthDiscoveryTimeout::LOCAL,
|
||||
redirect_mode,
|
||||
)
|
||||
.await;
|
||||
let oauth_config = match login_support {
|
||||
McpOAuthLoginSupport::Supported(config) => config,
|
||||
McpOAuthLoginSupport::Unsupported => continue,
|
||||
McpOAuthLoginSupport::Unknown(err) => {
|
||||
warn!(
|
||||
"MCP server may or may not require login for plugin install {name}: {err}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let resolved_scopes = resolve_oauth_scopes(
|
||||
/*explicit_scopes*/ None,
|
||||
server.scopes.clone(),
|
||||
oauth_config.discovered_scopes.clone(),
|
||||
);
|
||||
|
||||
let store_mode = config.mcp_oauth_credentials_store_mode;
|
||||
let keyring_backend_kind = config.auth_keyring_backend_kind();
|
||||
let callback_port = server.oauth_callback_port(config.mcp_oauth_callback_port);
|
||||
let callback_url = match resolve_oauth_callback(
|
||||
&server,
|
||||
&oauth_config.url,
|
||||
config.mcp_oauth_callback_url.as_deref(),
|
||||
) {
|
||||
Ok(callback_url) => callback_url,
|
||||
Err(error) => {
|
||||
warn!(
|
||||
"failed to resolve MCP OAuth callback for plugin install {name}: {error}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let notification_name = name.clone();
|
||||
let oauth_credential_name = server.oauth_credential_name(&name).into_owned();
|
||||
let thread_manager = Arc::clone(&self.thread_manager);
|
||||
let http_client = Arc::clone(&http_client);
|
||||
let global_callback_url = config.mcp_oauth_callback_url.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let oauth_client_config = server.oauth.as_ref();
|
||||
let first_attempt = perform_oauth_login_silent(
|
||||
&oauth_credential_name,
|
||||
&oauth_config.url,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
oauth_config.http_headers.clone(),
|
||||
oauth_config.env_http_headers.clone(),
|
||||
&resolved_scopes.scopes,
|
||||
oauth_client_config,
|
||||
McpOAuthClientRegistration::Auto,
|
||||
server.oauth_resource.as_deref(),
|
||||
callback_port,
|
||||
callback_url.as_deref(),
|
||||
global_callback_url.as_deref(),
|
||||
Arc::clone(&http_client),
|
||||
redirect_mode,
|
||||
)
|
||||
.await;
|
||||
|
||||
let final_result = match first_attempt {
|
||||
Err(err) if should_retry_without_scopes(&resolved_scopes, &err) => {
|
||||
perform_oauth_login_silent(
|
||||
&oauth_credential_name,
|
||||
&oauth_config.url,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
oauth_config.http_headers,
|
||||
oauth_config.env_http_headers,
|
||||
&[],
|
||||
oauth_client_config,
|
||||
McpOAuthClientRegistration::Auto,
|
||||
server.oauth_resource.as_deref(),
|
||||
callback_port,
|
||||
callback_url.as_deref(),
|
||||
global_callback_url.as_deref(),
|
||||
http_client,
|
||||
redirect_mode,
|
||||
)
|
||||
.await
|
||||
}
|
||||
result => result,
|
||||
};
|
||||
|
||||
let (success, error) = match final_result {
|
||||
Ok(()) => (true, None),
|
||||
Err(err) => (false, Some(err.to_string())),
|
||||
};
|
||||
if success {
|
||||
thread_manager.invalidate_mcp_runtimes().await;
|
||||
}
|
||||
|
||||
let notification = ServerNotification::McpServerOauthLoginCompleted(
|
||||
McpServerOauthLoginCompletedNotification {
|
||||
name: notification_name,
|
||||
thread_id: None,
|
||||
login_id: None,
|
||||
success,
|
||||
error,
|
||||
},
|
||||
);
|
||||
outgoing.send_server_notification(notification).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn plugin_uninstall_response(
|
||||
&self,
|
||||
params: PluginUninstallParams,
|
||||
) -> Result<PluginUninstallResponse, JSONRPCErrorError> {
|
||||
let PluginUninstallParams { plugin_id } = params;
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
|
||||
plugins_manager
|
||||
.uninstall_plugin(plugin_id)
|
||||
.await
|
||||
.map_err(Self::plugin_uninstall_error)?;
|
||||
match self.load_latest_config(/*fallback_cwd*/ None).await {
|
||||
Ok(_) => self.on_effective_plugins_changed().await,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to reload config after plugin uninstall, clearing plugin-related caches only: {err:?}"
|
||||
);
|
||||
self.clear_plugin_related_caches();
|
||||
}
|
||||
}
|
||||
Ok(PluginUninstallResponse {})
|
||||
}
|
||||
|
||||
fn plugin_install_error(err: CorePluginInstallError) -> JSONRPCErrorError {
|
||||
if err.is_invalid_request() {
|
||||
return invalid_request(err.to_string());
|
||||
}
|
||||
|
||||
match err {
|
||||
CorePluginInstallError::Marketplace(err) => {
|
||||
Self::marketplace_error(err, "install plugin")
|
||||
}
|
||||
CorePluginInstallError::Config(err) => {
|
||||
internal_error(format!("failed to persist installed plugin config: {err}"))
|
||||
}
|
||||
CorePluginInstallError::Join(err) => {
|
||||
internal_error(format!("failed to install plugin: {err}"))
|
||||
}
|
||||
CorePluginInstallError::Store(err) => {
|
||||
internal_error(format!("failed to install plugin: {err}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_uninstall_error(err: CorePluginUninstallError) -> JSONRPCErrorError {
|
||||
if err.is_invalid_request() {
|
||||
return invalid_request(err.to_string());
|
||||
}
|
||||
|
||||
match err {
|
||||
CorePluginUninstallError::Config(err) => {
|
||||
internal_error(format!("failed to clear plugin config: {err}"))
|
||||
}
|
||||
CorePluginUninstallError::Join(err) => {
|
||||
internal_error(format!("failed to uninstall plugin: {err}"))
|
||||
}
|
||||
CorePluginUninstallError::Store(err) => {
|
||||
internal_error(format!("failed to uninstall plugin: {err}"))
|
||||
}
|
||||
CorePluginUninstallError::InvalidPluginId(_) => {
|
||||
unreachable!("invalid plugin ids are classified as invalid requests");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_error(err: MarketplaceError, action: &str) -> JSONRPCErrorError {
|
||||
match err {
|
||||
MarketplaceError::MarketplaceNotFound { .. }
|
||||
| MarketplaceError::InvalidMarketplaceFile { .. }
|
||||
| MarketplaceError::PluginNotFound { .. }
|
||||
| MarketplaceError::PluginNotAvailable { .. }
|
||||
| MarketplaceError::PluginsDisabled
|
||||
| MarketplaceError::InvalidPlugin(_) => invalid_request(err.to_string()),
|
||||
MarketplaceError::Io { .. } => internal_error(format!("failed to {action}: {err}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
82
akode-rs/app-server/src/request_processors/plugins/local.rs
Normal file
82
akode-rs/app-server/src/request_processors/plugins/local.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
use super::*;
|
||||
use akode_core::config::ConfigOverrides;
|
||||
use akode_core_plugins::PluginMarketplaceContext;
|
||||
use akode_core_plugins::PluginMarketplaceScope;
|
||||
use akode_core_plugins::marketplace::MarketplaceListError;
|
||||
use futures::StreamExt;
|
||||
|
||||
const CONFIG_LOAD_CONCURRENCY: usize = 5;
|
||||
|
||||
impl PluginRequestProcessor {
|
||||
pub(super) async fn load_catalog_config(
|
||||
&self,
|
||||
cwds: &[AbsolutePathBuf],
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
if cwds.is_empty() {
|
||||
self.config_manager
|
||||
.load_non_project_config()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
} else {
|
||||
self.load_latest_config(/*fallback_cwd*/ None).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn load_marketplace_context(
|
||||
&self,
|
||||
cwds: Vec<AbsolutePathBuf>,
|
||||
catalog_config: &Config,
|
||||
) -> PluginMarketplaceContext {
|
||||
let global_config = catalog_config.plugins_config_input();
|
||||
if cwds.is_empty() {
|
||||
return PluginMarketplaceContext {
|
||||
global_config: global_config.clone(),
|
||||
scopes: vec![PluginMarketplaceScope {
|
||||
cwd: None,
|
||||
config: global_config,
|
||||
}],
|
||||
load_errors: Vec::new(),
|
||||
};
|
||||
}
|
||||
let outcomes = futures::stream::iter(cwds)
|
||||
.map(|cwd| async move {
|
||||
match self
|
||||
.config_manager
|
||||
.load_with_overrides(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd.to_path_buf()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(config) => Ok(PluginMarketplaceScope {
|
||||
cwd: Some(cwd),
|
||||
config: config.plugins_config_input(),
|
||||
}),
|
||||
Err(err) => Err(MarketplaceListError {
|
||||
path: cwd,
|
||||
message: format!("failed to reload config: {err}"),
|
||||
}),
|
||||
}
|
||||
})
|
||||
.buffered(CONFIG_LOAD_CONCURRENCY)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
let mut scopes = Vec::new();
|
||||
let mut load_errors = Vec::new();
|
||||
for outcome in outcomes {
|
||||
match outcome {
|
||||
Ok(scope) => scopes.push(scope),
|
||||
Err(error) => load_errors.push(error),
|
||||
}
|
||||
}
|
||||
|
||||
PluginMarketplaceContext {
|
||||
global_config,
|
||||
scopes,
|
||||
load_errors,
|
||||
}
|
||||
}
|
||||
}
|
||||
211
akode-rs/app-server/src/request_processors/plugins/search.rs
Normal file
211
akode-rs/app-server/src/request_processors/plugins/search.rs
Normal file
@@ -0,0 +1,211 @@
|
||||
use super::*;
|
||||
use akode_app_server_protocol::PluginSearchParams;
|
||||
use akode_app_server_protocol::PluginSearchResponse;
|
||||
use akode_app_server_protocol::PluginSearchResult;
|
||||
use akode_app_server_protocol::PluginSearchScope;
|
||||
use akode_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
use akode_core_plugins::is_openai_curated_marketplace_name;
|
||||
|
||||
const MAX_LOCAL_PLUGIN_SEARCH_RESULTS: usize = 100;
|
||||
const PLUGIN_SEARCH_NO_MATCH_RANK: usize = 6;
|
||||
|
||||
impl PluginRequestProcessor {
|
||||
pub(crate) async fn plugin_search(
|
||||
&self,
|
||||
params: PluginSearchParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.plugin_search_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
async fn plugin_search_response(
|
||||
&self,
|
||||
params: PluginSearchParams,
|
||||
) -> Result<PluginSearchResponse, JSONRPCErrorError> {
|
||||
let PluginSearchParams {
|
||||
search_term,
|
||||
scope,
|
||||
cwds,
|
||||
cursor,
|
||||
// Pagination limits only applied to the removed remote catalog.
|
||||
limit: _,
|
||||
} = params;
|
||||
let search_term = search_term.trim();
|
||||
let empty_response = || PluginSearchResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
};
|
||||
// All local results are returned on the first page.
|
||||
if search_term.is_empty() || cursor.is_some() {
|
||||
return Ok(empty_response());
|
||||
}
|
||||
|
||||
let config = self
|
||||
.load_catalog_config(cwds.as_deref().unwrap_or_default())
|
||||
.await?;
|
||||
if !config.features.enabled(Feature::Plugins) {
|
||||
return Ok(empty_response());
|
||||
}
|
||||
|
||||
let normalized_search_term = normalize_search_text(search_term);
|
||||
let mut local_results = Vec::new();
|
||||
if scope != Some(PluginSearchScope::Workspace) {
|
||||
let roots = cwds.unwrap_or_default();
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let outcome = tokio::task::spawn_blocking(move || {
|
||||
plugins_manager.list_marketplaces_for_config(
|
||||
&plugins_input,
|
||||
&roots,
|
||||
/*include_openai_curated*/ true,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to list marketplace plugins: {err}")))?
|
||||
.map_err(|err| Self::marketplace_error(err, "list marketplace plugins"))?;
|
||||
|
||||
for error in outcome.errors {
|
||||
warn!(
|
||||
marketplace_path = %error.path.as_path().display(),
|
||||
error = %error.message,
|
||||
"plugin/search skipped a local marketplace that could not be loaded"
|
||||
);
|
||||
}
|
||||
|
||||
for marketplace in outcome.marketplaces {
|
||||
if !marketplace_matches_search_scope(&marketplace.name, scope) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for plugin in marketplace.plugins {
|
||||
let plugin = convert_configured_marketplace_plugin_to_plugin_summary(plugin);
|
||||
local_results.push(plugin_search_result(
|
||||
plugin,
|
||||
marketplace.name.clone(),
|
||||
Some(marketplace.path.clone()),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut local_matches = Vec::new();
|
||||
let mut seen_local_plugin_identities = HashSet::new();
|
||||
for local_result in local_results {
|
||||
if plugin_search_match_rank(&local_result.plugin, &normalized_search_term).is_none() {
|
||||
continue;
|
||||
}
|
||||
let local_identity =
|
||||
if is_openai_curated_marketplace_name(&local_result.marketplace_name) {
|
||||
format!("curated:{}", local_result.plugin.name)
|
||||
} else {
|
||||
format!("plugin:{}", local_result.plugin.id)
|
||||
};
|
||||
if seen_local_plugin_identities.insert(local_identity) {
|
||||
local_matches.push(local_result);
|
||||
}
|
||||
}
|
||||
|
||||
local_matches.sort_by_key(|result| {
|
||||
plugin_search_match_rank(&result.plugin, &normalized_search_term)
|
||||
.unwrap_or(PLUGIN_SEARCH_NO_MATCH_RANK)
|
||||
});
|
||||
local_matches.truncate(MAX_LOCAL_PLUGIN_SEARCH_RESULTS);
|
||||
|
||||
Ok(PluginSearchResponse {
|
||||
data: local_matches,
|
||||
next_cursor: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Plugin discovery does not resolve effective activation, so all results explicitly report
|
||||
/// `enabled: false`, regardless of their source, installation state, or page.
|
||||
fn plugin_search_result(
|
||||
mut plugin: PluginSummary,
|
||||
marketplace_name: String,
|
||||
marketplace_path: Option<AbsolutePathBuf>,
|
||||
) -> PluginSearchResult {
|
||||
plugin.enabled = false;
|
||||
|
||||
PluginSearchResult {
|
||||
plugin,
|
||||
marketplace_name,
|
||||
marketplace_path,
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_matches_search_scope(
|
||||
marketplace_name: &str,
|
||||
scope: Option<PluginSearchScope>,
|
||||
) -> bool {
|
||||
let is_built_in = is_openai_curated_marketplace_name(marketplace_name)
|
||||
|| matches!(
|
||||
marketplace_name,
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME
|
||||
| "openai-bundled-alpha"
|
||||
| "codex-official"
|
||||
| "openai-primary-runtime"
|
||||
);
|
||||
|
||||
match scope {
|
||||
None => true,
|
||||
Some(PluginSearchScope::Global) => is_built_in,
|
||||
Some(PluginSearchScope::Workspace) => false,
|
||||
Some(PluginSearchScope::Personal) => !is_built_in,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_search_text(value: &str) -> String {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
for character in value.to_lowercase().chars() {
|
||||
if character.is_alphanumeric() {
|
||||
normalized.push(character);
|
||||
} else if !normalized.is_empty() && !normalized.ends_with(' ') {
|
||||
normalized.push(' ');
|
||||
}
|
||||
}
|
||||
if normalized.ends_with(' ') {
|
||||
normalized.pop();
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
fn plugin_search_match_rank(plugin: &PluginSummary, normalized_query: &str) -> Option<usize> {
|
||||
if normalized_query.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let visible_name = normalize_search_text(
|
||||
plugin
|
||||
.interface
|
||||
.as_ref()
|
||||
.and_then(|interface| interface.display_name.as_deref())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let internal_name = normalize_search_text(&plugin.name);
|
||||
let names = [&visible_name, &internal_name];
|
||||
let keywords = plugin
|
||||
.keywords
|
||||
.iter()
|
||||
.map(|keyword| normalize_search_text(keyword))
|
||||
.collect::<Vec<_>>();
|
||||
let joined_search_values = normalize_search_text(&format!(
|
||||
"{internal_name} {visible_name} {}",
|
||||
keywords.join(" ")
|
||||
));
|
||||
|
||||
[
|
||||
visible_name == normalized_query,
|
||||
internal_name == normalized_query,
|
||||
names.iter().any(|name| name.starts_with(normalized_query)),
|
||||
names.iter().any(|name| name.contains(normalized_query)),
|
||||
keywords.iter().any(|keyword| keyword == normalized_query),
|
||||
keywords
|
||||
.iter()
|
||||
.any(|keyword| keyword.contains(normalized_query))
|
||||
|| joined_search_values.contains(normalized_query),
|
||||
]
|
||||
.iter()
|
||||
.position(|matches| *matches)
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::ProcessExitedNotification;
|
||||
use akode_app_server_protocol::ProcessKillParams;
|
||||
use akode_app_server_protocol::ProcessKillResponse;
|
||||
use akode_app_server_protocol::ProcessOutputDeltaNotification;
|
||||
use akode_app_server_protocol::ProcessOutputStream;
|
||||
use akode_app_server_protocol::ProcessResizePtyParams;
|
||||
use akode_app_server_protocol::ProcessResizePtyResponse;
|
||||
use akode_app_server_protocol::ProcessSpawnParams;
|
||||
use akode_app_server_protocol::ProcessSpawnResponse;
|
||||
use akode_app_server_protocol::ProcessTerminalSize;
|
||||
use akode_app_server_protocol::ProcessWriteStdinParams;
|
||||
use akode_app_server_protocol::ProcessWriteStdinResponse;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_core::exec::ExecExpiration;
|
||||
use akode_core::exec::ExecExpirationOutcome;
|
||||
use akode_core::exec::IO_DRAIN_TIMEOUT_MS;
|
||||
use akode_exec_server::EnvironmentManager;
|
||||
use akode_protocol::exec_output::bytes_to_string_smart;
|
||||
use akode_protocol::shell_environment::is_non_inheritable_env_var;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
|
||||
use akode_utils_pty::ProcessHandle;
|
||||
use akode_utils_pty::SpawnedProcess;
|
||||
use akode_utils_pty::TerminalSize;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::Instant;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_params;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
|
||||
const EXEC_TIMEOUT_EXIT_CODE: i32 = 124;
|
||||
const OUTPUT_CHUNK_SIZE_HINT: usize = 64 * 1024;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ProcessExecRequestProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
process_exec_manager: ProcessExecManager,
|
||||
}
|
||||
|
||||
impl ProcessExecRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
) -> Self {
|
||||
Self {
|
||||
outgoing,
|
||||
environment_manager,
|
||||
process_exec_manager: ProcessExecManager::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn process_spawn(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ProcessSpawnParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
self.require_local_environment()?;
|
||||
let ProcessSpawnParams {
|
||||
command,
|
||||
process_handle,
|
||||
cwd,
|
||||
tty,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
timeout_ms,
|
||||
env: env_overrides,
|
||||
size,
|
||||
} = params;
|
||||
let method_name = "process/spawn";
|
||||
tracing::debug!("{method_name} command: {command:?}");
|
||||
if command.is_empty() {
|
||||
return Err(invalid_request("command must not be empty"));
|
||||
}
|
||||
if process_handle.is_empty() {
|
||||
return Err(invalid_request("processHandle must not be empty"));
|
||||
}
|
||||
if size.is_some() && !tty {
|
||||
return Err(invalid_params("process/spawn size requires tty: true"));
|
||||
}
|
||||
let mut env = std::env::vars().collect::<HashMap<_, _>>();
|
||||
if let Some(env_overrides) = env_overrides {
|
||||
for (key, value) in env_overrides {
|
||||
match value {
|
||||
Some(value) => {
|
||||
env.insert(key, value);
|
||||
}
|
||||
None => {
|
||||
env.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
env.retain(|name, _| !is_non_inheritable_env_var(name));
|
||||
let expiration = match timeout_ms {
|
||||
Some(Some(timeout_ms)) => match u64::try_from(timeout_ms) {
|
||||
Ok(timeout_ms) => timeout_ms.into(),
|
||||
Err(_) => {
|
||||
return Err(invalid_params(format!(
|
||||
"{method_name} timeoutMs must be non-negative, got {timeout_ms}"
|
||||
)));
|
||||
}
|
||||
},
|
||||
Some(None) => ExecExpiration::Cancellation(CancellationToken::new()),
|
||||
None => ExecExpiration::DefaultTimeout,
|
||||
};
|
||||
let output_bytes_cap = output_bytes_cap.unwrap_or(Some(DEFAULT_OUTPUT_BYTES_CAP));
|
||||
let size = size.map(terminal_size_from_protocol).transpose()?;
|
||||
|
||||
self.process_exec_manager
|
||||
.start(StartProcessParams {
|
||||
outgoing: self.outgoing.clone(),
|
||||
request_id,
|
||||
process_handle,
|
||||
command,
|
||||
cwd,
|
||||
env,
|
||||
expiration,
|
||||
tty,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
size,
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn process_write_stdin(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ProcessWriteStdinParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.process_exec_manager
|
||||
.write_stdin(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn process_resize_pty(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ProcessResizePtyParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.process_exec_manager
|
||||
.resize_pty(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn process_kill(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ProcessKillParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.process_exec_manager
|
||||
.kill(request_id, params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn connection_closed(&self, connection_id: ConnectionId) {
|
||||
self.process_exec_manager
|
||||
.connection_closed(connection_id)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn require_local_environment(&self) -> Result<(), JSONRPCErrorError> {
|
||||
self.environment_manager
|
||||
.try_local_environment()
|
||||
.is_some()
|
||||
.then_some(())
|
||||
.ok_or_else(|| internal_error("local environment is not configured"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct ProcessExecManager {
|
||||
sessions: Arc<Mutex<HashMap<ConnectionProcessHandle, ProcessSession>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
struct ConnectionProcessHandle {
|
||||
connection_id: ConnectionId,
|
||||
process_handle: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ProcessSession {
|
||||
control_tx: mpsc::Sender<ProcessControlRequest>,
|
||||
}
|
||||
|
||||
enum ProcessControl {
|
||||
Write { delta: Vec<u8>, close_stdin: bool },
|
||||
Resize { size: TerminalSize },
|
||||
Kill,
|
||||
}
|
||||
|
||||
struct ProcessControlRequest {
|
||||
control: ProcessControl,
|
||||
response_tx: Option<oneshot::Sender<Result<(), JSONRPCErrorError>>>,
|
||||
}
|
||||
|
||||
struct StartProcessParams {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
request_id: ConnectionRequestId,
|
||||
process_handle: String,
|
||||
command: Vec<String>,
|
||||
cwd: AbsolutePathBuf,
|
||||
env: HashMap<String, String>,
|
||||
expiration: ExecExpiration,
|
||||
tty: bool,
|
||||
stream_stdin: bool,
|
||||
stream_stdout_stderr: bool,
|
||||
output_bytes_cap: Option<usize>,
|
||||
size: Option<TerminalSize>,
|
||||
}
|
||||
|
||||
struct RunProcessParams {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
request_id: ConnectionRequestId,
|
||||
process_handle: String,
|
||||
spawned: SpawnedProcess,
|
||||
control_rx: mpsc::Receiver<ProcessControlRequest>,
|
||||
stream_stdin: bool,
|
||||
stream_stdout_stderr: bool,
|
||||
expiration: ExecExpiration,
|
||||
output_bytes_cap: Option<usize>,
|
||||
}
|
||||
|
||||
struct SpawnProcessOutputParams {
|
||||
connection_id: ConnectionId,
|
||||
process_handle: String,
|
||||
output_rx: mpsc::Receiver<Vec<u8>>,
|
||||
reader: Option<tokio::task::AbortHandle>,
|
||||
process_exited: CancellationToken,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
stream: ProcessOutputStream,
|
||||
stream_output: bool,
|
||||
output_bytes_cap: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProcessOutputCapture {
|
||||
text: String,
|
||||
cap_reached: bool,
|
||||
output_incomplete: bool,
|
||||
}
|
||||
|
||||
impl ProcessExecManager {
|
||||
async fn start(&self, params: StartProcessParams) -> Result<(), JSONRPCErrorError> {
|
||||
let StartProcessParams {
|
||||
outgoing,
|
||||
request_id,
|
||||
process_handle,
|
||||
command,
|
||||
cwd,
|
||||
env,
|
||||
expiration,
|
||||
tty,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
size,
|
||||
} = params;
|
||||
|
||||
let (program, args) = command
|
||||
.split_first()
|
||||
.ok_or_else(|| invalid_request("command must not be empty"))?;
|
||||
let stream_stdin = tty || stream_stdin;
|
||||
let stream_stdout_stderr = tty || stream_stdout_stderr;
|
||||
let arg0 = None;
|
||||
let (control_tx, control_rx) = mpsc::channel(32);
|
||||
let process_key = ConnectionProcessHandle {
|
||||
connection_id: request_id.connection_id,
|
||||
process_handle: process_handle.clone(),
|
||||
};
|
||||
|
||||
{
|
||||
let mut sessions = self.sessions.lock().await;
|
||||
match sessions.entry(process_key.clone()) {
|
||||
Entry::Occupied(_) => {
|
||||
return Err(invalid_request(format!(
|
||||
"duplicate active process handle: {process_handle:?}",
|
||||
)));
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(ProcessSession { control_tx });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let spawned = if tty {
|
||||
akode_utils_pty::spawn_pty_process(
|
||||
program,
|
||||
args,
|
||||
cwd.as_path(),
|
||||
&env,
|
||||
&arg0,
|
||||
size.unwrap_or_default(),
|
||||
akode_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await
|
||||
} else if stream_stdin {
|
||||
akode_utils_pty::spawn_pipe_process(program, args, cwd.as_path(), &env, &arg0, &[])
|
||||
.await
|
||||
} else {
|
||||
akode_utils_pty::spawn_pipe_process_no_stdin(
|
||||
program,
|
||||
args,
|
||||
cwd.as_path(),
|
||||
&env,
|
||||
&arg0,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
};
|
||||
let spawned = match spawned {
|
||||
Ok(spawned) => spawned,
|
||||
Err(err) => {
|
||||
self.sessions.lock().await.remove(&process_key);
|
||||
return Err(internal_error(format!("failed to spawn process: {err}")));
|
||||
}
|
||||
};
|
||||
|
||||
outgoing
|
||||
.send_response(request_id.clone(), ProcessSpawnResponse {})
|
||||
.await;
|
||||
|
||||
let sessions = Arc::clone(&self.sessions);
|
||||
tokio::spawn(async move {
|
||||
run_process(RunProcessParams {
|
||||
outgoing,
|
||||
request_id,
|
||||
process_handle,
|
||||
spawned,
|
||||
control_rx,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
expiration,
|
||||
output_bytes_cap,
|
||||
})
|
||||
.await;
|
||||
sessions.lock().await.remove(&process_key);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_stdin(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ProcessWriteStdinParams,
|
||||
) -> Result<ProcessWriteStdinResponse, JSONRPCErrorError> {
|
||||
if params.delta_base64.is_none() && !params.close_stdin {
|
||||
return Err(invalid_params(
|
||||
"process/writeStdin requires deltaBase64 or closeStdin",
|
||||
));
|
||||
}
|
||||
|
||||
let delta = match params.delta_base64 {
|
||||
Some(delta_base64) => STANDARD
|
||||
.decode(delta_base64)
|
||||
.map_err(|err| invalid_params(format!("invalid deltaBase64: {err}")))?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
|
||||
self.send_control(
|
||||
request_id.connection_id,
|
||||
params.process_handle,
|
||||
ProcessControl::Write {
|
||||
delta,
|
||||
close_stdin: params.close_stdin,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(ProcessWriteStdinResponse {})
|
||||
}
|
||||
|
||||
async fn kill(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ProcessKillParams,
|
||||
) -> Result<ProcessKillResponse, JSONRPCErrorError> {
|
||||
self.send_control(
|
||||
request_id.connection_id,
|
||||
params.process_handle,
|
||||
ProcessControl::Kill,
|
||||
)
|
||||
.await?;
|
||||
Ok(ProcessKillResponse {})
|
||||
}
|
||||
|
||||
async fn resize_pty(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ProcessResizePtyParams,
|
||||
) -> Result<ProcessResizePtyResponse, JSONRPCErrorError> {
|
||||
self.send_control(
|
||||
request_id.connection_id,
|
||||
params.process_handle,
|
||||
ProcessControl::Resize {
|
||||
size: terminal_size_from_protocol(params.size)?,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(ProcessResizePtyResponse {})
|
||||
}
|
||||
|
||||
async fn connection_closed(&self, connection_id: ConnectionId) {
|
||||
let controls = {
|
||||
let mut sessions = self.sessions.lock().await;
|
||||
let process_handles = sessions
|
||||
.keys()
|
||||
.filter(|process_handle| process_handle.connection_id == connection_id)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let mut controls = Vec::with_capacity(process_handles.len());
|
||||
for process_handle in process_handles {
|
||||
if let Some(control) = sessions.remove(&process_handle) {
|
||||
controls.push(control);
|
||||
}
|
||||
}
|
||||
controls
|
||||
};
|
||||
|
||||
for control in controls {
|
||||
let _ = control
|
||||
.control_tx
|
||||
.send(ProcessControlRequest {
|
||||
control: ProcessControl::Kill,
|
||||
response_tx: None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_control(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
process_handle: String,
|
||||
control: ProcessControl,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let process_key = ConnectionProcessHandle {
|
||||
connection_id,
|
||||
process_handle,
|
||||
};
|
||||
let session = self
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.get(&process_key)
|
||||
.cloned()
|
||||
.ok_or_else(|| no_active_process_error(&process_key.process_handle))?;
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
session
|
||||
.control_tx
|
||||
.send(ProcessControlRequest {
|
||||
control,
|
||||
response_tx: Some(response_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| process_no_longer_running_error(&process_key.process_handle))?;
|
||||
response_rx
|
||||
.await
|
||||
.map_err(|_| process_no_longer_running_error(&process_key.process_handle))?
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_process(params: RunProcessParams) {
|
||||
let RunProcessParams {
|
||||
outgoing,
|
||||
request_id,
|
||||
process_handle,
|
||||
spawned,
|
||||
control_rx,
|
||||
stream_stdin,
|
||||
stream_stdout_stderr,
|
||||
expiration,
|
||||
output_bytes_cap,
|
||||
} = params;
|
||||
let mut control_rx = control_rx;
|
||||
let mut control_open = true;
|
||||
let expiration = expiration.wait_with_outcome();
|
||||
tokio::pin!(expiration);
|
||||
let SpawnedProcess {
|
||||
session,
|
||||
stdout_rx,
|
||||
stderr_rx,
|
||||
exit_rx,
|
||||
} = spawned;
|
||||
tokio::pin!(exit_rx);
|
||||
let mut expiration_outcome = None;
|
||||
let process_exited = CancellationToken::new();
|
||||
|
||||
let stdout_handle = collect_spawn_process_output(SpawnProcessOutputParams {
|
||||
connection_id: request_id.connection_id,
|
||||
process_handle: process_handle.clone(),
|
||||
output_rx: stdout_rx,
|
||||
reader: session.stdout_reader(),
|
||||
process_exited: process_exited.clone(),
|
||||
outgoing: Arc::clone(&outgoing),
|
||||
stream: ProcessOutputStream::Stdout,
|
||||
stream_output: stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
});
|
||||
let stderr_handle = collect_spawn_process_output(SpawnProcessOutputParams {
|
||||
connection_id: request_id.connection_id,
|
||||
process_handle: process_handle.clone(),
|
||||
output_rx: stderr_rx,
|
||||
reader: session.stderr_reader(),
|
||||
process_exited: process_exited.clone(),
|
||||
outgoing: Arc::clone(&outgoing),
|
||||
stream: ProcessOutputStream::Stderr,
|
||||
stream_output: stream_stdout_stderr,
|
||||
output_bytes_cap,
|
||||
});
|
||||
|
||||
let exit_code = loop {
|
||||
tokio::select! {
|
||||
control = control_rx.recv(), if control_open => {
|
||||
match control {
|
||||
Some(ProcessControlRequest { control, response_tx }) => {
|
||||
let result = match control {
|
||||
ProcessControl::Write { delta, close_stdin } => {
|
||||
handle_process_write(
|
||||
&session,
|
||||
stream_stdin,
|
||||
delta,
|
||||
close_stdin,
|
||||
).await
|
||||
}
|
||||
ProcessControl::Resize { size } => {
|
||||
handle_process_resize(&session, size)
|
||||
}
|
||||
ProcessControl::Kill => {
|
||||
session.request_terminate();
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
if let Some(response_tx) = response_tx
|
||||
&& response_tx.send(result).is_err()
|
||||
{
|
||||
tracing::debug!(
|
||||
process_handle = %process_handle,
|
||||
"process control response receiver dropped"
|
||||
);
|
||||
}
|
||||
},
|
||||
None => {
|
||||
control_open = false;
|
||||
session.request_terminate();
|
||||
}
|
||||
}
|
||||
}
|
||||
outcome = &mut expiration, if expiration_outcome.is_none() => {
|
||||
expiration_outcome = Some(outcome);
|
||||
session.request_terminate();
|
||||
}
|
||||
exit = &mut exit_rx => {
|
||||
if matches!(expiration_outcome, Some(ExecExpirationOutcome::TimedOut)) {
|
||||
break EXEC_TIMEOUT_EXIT_CODE;
|
||||
} else {
|
||||
break exit.unwrap_or(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
drop(control_rx);
|
||||
process_exited.cancel();
|
||||
let stdout = stdout_handle.await.unwrap_or_default();
|
||||
let stderr = stderr_handle.await.unwrap_or_default();
|
||||
outgoing
|
||||
.send_server_notification_to_connection_and_wait(
|
||||
request_id.connection_id,
|
||||
ServerNotification::ProcessExited(ProcessExitedNotification {
|
||||
process_handle,
|
||||
exit_code,
|
||||
output_drain_timed_out: Some(stdout.output_incomplete || stderr.output_incomplete),
|
||||
stdout: stdout.text,
|
||||
stdout_cap_reached: stdout.cap_reached,
|
||||
stderr: stderr.text,
|
||||
stderr_cap_reached: stderr.cap_reached,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
// On older Windows, ClosePseudoConsole can block until surviving clients disconnect.
|
||||
#[cfg(windows)]
|
||||
tokio::task::spawn_blocking(move || drop(session));
|
||||
}
|
||||
|
||||
fn collect_spawn_process_output(
|
||||
params: SpawnProcessOutputParams,
|
||||
) -> tokio::task::JoinHandle<ProcessOutputCapture> {
|
||||
let SpawnProcessOutputParams {
|
||||
connection_id,
|
||||
process_handle,
|
||||
mut output_rx,
|
||||
reader,
|
||||
process_exited,
|
||||
outgoing,
|
||||
stream,
|
||||
stream_output,
|
||||
output_bytes_cap,
|
||||
} = params;
|
||||
tokio::spawn(async move {
|
||||
let mut buffer: Vec<u8> = Vec::new();
|
||||
let mut observed_num_bytes = 0usize;
|
||||
let mut cap_reached = false;
|
||||
let mut drain_timed_out = false;
|
||||
let mut draining = false;
|
||||
let drain_timer = tokio::time::sleep(Duration::ZERO);
|
||||
tokio::pin!(drain_timer);
|
||||
loop {
|
||||
let chunk = tokio::select! {
|
||||
biased;
|
||||
_ = process_exited.cancelled(), if !draining => {
|
||||
draining = true;
|
||||
drain_timer.as_mut().reset(Instant::now() + Duration::from_millis(IO_DRAIN_TIMEOUT_MS));
|
||||
continue;
|
||||
}
|
||||
_ = &mut drain_timer, if draining && !output_rx.is_closed() => {
|
||||
drain_timed_out = !output_rx.is_closed();
|
||||
output_rx.close();
|
||||
if let Some(reader) = &reader {
|
||||
reader.abort();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
chunk = output_rx.recv() => chunk,
|
||||
};
|
||||
let Some(mut chunk) = chunk else { break };
|
||||
// The byte cap limits delivery. Keep draining until EOF or the post-exit deadline.
|
||||
if cap_reached {
|
||||
continue;
|
||||
}
|
||||
while chunk.len() < OUTPUT_CHUNK_SIZE_HINT
|
||||
&& let Ok(next_chunk) = output_rx.try_recv()
|
||||
{
|
||||
chunk.extend_from_slice(&next_chunk);
|
||||
}
|
||||
let capped_chunk = match output_bytes_cap {
|
||||
Some(output_bytes_cap) => {
|
||||
let capped_chunk_len = output_bytes_cap
|
||||
.saturating_sub(observed_num_bytes)
|
||||
.min(chunk.len());
|
||||
observed_num_bytes += capped_chunk_len;
|
||||
&chunk[0..capped_chunk_len]
|
||||
}
|
||||
None => chunk.as_slice(),
|
||||
};
|
||||
cap_reached = Some(observed_num_bytes) == output_bytes_cap;
|
||||
if stream_output {
|
||||
let write_started = Instant::now();
|
||||
outgoing
|
||||
.send_server_notification_to_connection_and_wait(
|
||||
connection_id,
|
||||
ServerNotification::ProcessOutputDelta(ProcessOutputDeltaNotification {
|
||||
process_handle: process_handle.clone(),
|
||||
stream,
|
||||
delta_base64: STANDARD.encode(capped_chunk),
|
||||
cap_reached,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
// A slow client can take longer than the pipe drain budget to accept one chunk.
|
||||
if draining {
|
||||
let deadline = drain_timer.deadline() + write_started.elapsed();
|
||||
drain_timer.as_mut().reset(deadline);
|
||||
}
|
||||
} else {
|
||||
buffer.extend_from_slice(capped_chunk);
|
||||
}
|
||||
}
|
||||
ProcessOutputCapture {
|
||||
text: bytes_to_string_smart(&buffer),
|
||||
cap_reached,
|
||||
output_incomplete: drain_timed_out && output_bytes_cap != Some(observed_num_bytes),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_process_write(
|
||||
session: &ProcessHandle,
|
||||
stream_stdin: bool,
|
||||
delta: Vec<u8>,
|
||||
close_stdin: bool,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if !stream_stdin {
|
||||
return Err(invalid_request(
|
||||
"stdin streaming is not enabled for this process",
|
||||
));
|
||||
}
|
||||
if !delta.is_empty() {
|
||||
session
|
||||
.writer_sender()
|
||||
.send(delta)
|
||||
.await
|
||||
.map_err(|_| invalid_request("stdin is already closed"))?;
|
||||
}
|
||||
if close_stdin {
|
||||
// Closing drops our sender; the writer task still drains any bytes
|
||||
// accepted above before its receiver observes EOF and closes stdin.
|
||||
session.close_stdin();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_process_resize(
|
||||
session: &ProcessHandle,
|
||||
size: TerminalSize,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
session
|
||||
.resize(size)
|
||||
.map_err(|err| invalid_request(format!("failed to resize PTY: {err}")))
|
||||
}
|
||||
|
||||
fn terminal_size_from_protocol(
|
||||
size: ProcessTerminalSize,
|
||||
) -> Result<TerminalSize, JSONRPCErrorError> {
|
||||
if size.rows == 0 || size.cols == 0 {
|
||||
return Err(invalid_params(
|
||||
"process size rows and cols must be greater than 0",
|
||||
));
|
||||
}
|
||||
Ok(TerminalSize {
|
||||
rows: size.rows,
|
||||
cols: size.cols,
|
||||
})
|
||||
}
|
||||
|
||||
fn no_active_process_error(process_handle: &str) -> JSONRPCErrorError {
|
||||
invalid_request(format!(
|
||||
"no active process for process handle {process_handle:?}"
|
||||
))
|
||||
}
|
||||
|
||||
fn process_no_longer_running_error(process_handle: &str) -> JSONRPCErrorError {
|
||||
invalid_request(format!("process {process_handle:?} is no longer running"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "process_exec_processor_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Coverage for post-exit output delivery over a backpressured connection.
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use crate::outgoing_message::OutgoingEnvelope;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn start_collector(
|
||||
process_exited: CancellationToken,
|
||||
) -> (
|
||||
mpsc::Sender<Vec<u8>>,
|
||||
mpsc::Receiver<OutgoingEnvelope>,
|
||||
tokio::task::JoinHandle<ProcessOutputCapture>,
|
||||
) {
|
||||
let (output_tx, output_rx) = mpsc::channel(2);
|
||||
let (tx, notifications) = mpsc::channel(1);
|
||||
let collector = collect_spawn_process_output(SpawnProcessOutputParams {
|
||||
connection_id: ConnectionId(1),
|
||||
process_handle: "test".to_string(),
|
||||
output_rx,
|
||||
reader: None,
|
||||
process_exited,
|
||||
outgoing: Arc::new(OutgoingMessageSender::new(tx)),
|
||||
stream: ProcessOutputStream::Stdout,
|
||||
stream_output: true,
|
||||
output_bytes_cap: None,
|
||||
});
|
||||
(output_tx, notifications, collector)
|
||||
}
|
||||
|
||||
async fn read_delta(
|
||||
notifications: &mut mpsc::Receiver<OutgoingEnvelope>,
|
||||
) -> (Vec<u8>, oneshot::Sender<()>) {
|
||||
let Some(OutgoingEnvelope::ToConnection {
|
||||
message: OutgoingMessage::AppServerNotification(envelope),
|
||||
write_complete_tx: Some(written),
|
||||
..
|
||||
}) = notifications.recv().await
|
||||
else {
|
||||
panic!("expected an output notification");
|
||||
};
|
||||
let ServerNotification::ProcessOutputDelta(delta) = envelope.notification else {
|
||||
panic!("expected an output delta");
|
||||
};
|
||||
(STANDARD.decode(delta.delta_base64).unwrap(), written)
|
||||
}
|
||||
|
||||
/// A client can take longer than the drain grace to accept each of several final chunks.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slow_writes_deliver_the_entire_tail_after_exit() {
|
||||
let exited = CancellationToken::new();
|
||||
let (output, mut notifications, collector) = start_collector(exited.clone());
|
||||
output.send(vec![1]).await.unwrap();
|
||||
let (first, written) = read_delta(&mut notifications).await;
|
||||
exited.cancel();
|
||||
output.send(vec![2]).await.unwrap();
|
||||
let slow_write = Duration::from_millis(IO_DRAIN_TIMEOUT_MS * 2);
|
||||
tokio::time::advance(slow_write).await;
|
||||
written.send(()).unwrap();
|
||||
|
||||
let (second, written) = read_delta(&mut notifications).await;
|
||||
tokio::time::advance(slow_write).await;
|
||||
// A descendant can still produce bytes while the previous write is blocked.
|
||||
output.send(vec![3]).await.unwrap();
|
||||
written.send(()).unwrap();
|
||||
|
||||
let (third, written) = read_delta(&mut notifications).await;
|
||||
drop(output);
|
||||
written.send(()).unwrap();
|
||||
assert_eq!([first, second, third], [vec![1], vec![2], vec![3]]);
|
||||
let capture = collector.await.unwrap();
|
||||
assert!(!capture.output_incomplete);
|
||||
}
|
||||
|
||||
/// A descendant that holds a pipe open gets one shared grace period across reads.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn inherited_pipe_does_not_restart_the_grace_period_for_each_chunk() {
|
||||
let exited = CancellationToken::new();
|
||||
exited.cancel();
|
||||
let (output, mut notifications, collector) = start_collector(exited);
|
||||
tokio::task::yield_now().await;
|
||||
let grace = Duration::from_millis(IO_DRAIN_TIMEOUT_MS);
|
||||
tokio::time::advance(grace / 2).await;
|
||||
output.send(vec![1]).await.unwrap();
|
||||
let (_, written) = read_delta(&mut notifications).await;
|
||||
written.send(()).unwrap();
|
||||
|
||||
let capture = tokio::time::timeout(grace / 2 + Duration::from_millis(1), collector)
|
||||
.await
|
||||
.expect("the collector must finish within the original drain budget")
|
||||
.unwrap();
|
||||
assert!(capture.output_incomplete);
|
||||
}
|
||||
|
||||
/// Even a capped stream closes its OS reader on a genuine timeout while its sibling stays open.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn timed_out_stderr_closes_while_stdout_is_still_open() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut child = akode_utils_pty::spawn_pipe_process_no_stdin(
|
||||
"/bin/sh",
|
||||
&[
|
||||
"-c".into(),
|
||||
concat!(
|
||||
"printf cap >&2; (while [ ! -f release ]; do sleep 0.05; done; ",
|
||||
"if dd if=/dev/zero bs=65536 count=32 >&2 2>/dev/null; ",
|
||||
"then printf open; else printf closed; fi) &",
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
dir.path(),
|
||||
&HashMap::new(),
|
||||
&None,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (tx, _notifications) = mpsc::channel(1);
|
||||
let process_exited = CancellationToken::new();
|
||||
let collector = collect_spawn_process_output(SpawnProcessOutputParams {
|
||||
connection_id: ConnectionId(1),
|
||||
process_handle: "probe".into(),
|
||||
output_rx: child.stderr_rx,
|
||||
reader: child.session.stderr_reader(),
|
||||
process_exited: process_exited.clone(),
|
||||
outgoing: Arc::new(OutgoingMessageSender::new(tx)),
|
||||
stream: ProcessOutputStream::Stderr,
|
||||
stream_output: false,
|
||||
output_bytes_cap: Some(3),
|
||||
});
|
||||
assert_eq!(child.exit_rx.await.unwrap(), 0);
|
||||
process_exited.cancel();
|
||||
let capture = collector.await.unwrap();
|
||||
assert_eq!(capture.text, "cap");
|
||||
assert!(capture.cap_reached);
|
||||
assert!(!capture.output_incomplete);
|
||||
std::fs::write(dir.path().join("release"), b"").unwrap();
|
||||
let mut stdout = Vec::new();
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
while let Some(bytes) = child.stdout_rx.recv().await {
|
||||
stdout.extend(bytes);
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the descendant must observe the closed stderr pipe");
|
||||
assert_eq!(stdout, b"closed");
|
||||
}
|
||||
|
||||
/// The client must receive the root's exit while a surviving Windows console child can still run.
|
||||
#[cfg(windows)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn windows_terminal_reports_exit_before_closing_the_console() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// Bound the lifetime of the descendant even if the server fails to deliver the exit.
|
||||
std::fs::write(
|
||||
dir.path().join("child.cmd"),
|
||||
concat!(
|
||||
"@echo off\r\n",
|
||||
"for /l %%i in (1,1,30) do (\r\n",
|
||||
" if exist received goto ack\r\n",
|
||||
" ping.exe -n 2 127.0.0.1 >nul\r\n",
|
||||
")\r\nexit /b 1\r\n:ack\r\ntype nul >acknowledged\r\n",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let spawned = akode_utils_pty::spawn_pty_process(
|
||||
"cmd.exe",
|
||||
&[
|
||||
"/d".into(),
|
||||
"/c".into(),
|
||||
"echo complete & start /b cmd.exe /d /c child.cmd".into(),
|
||||
],
|
||||
dir.path(),
|
||||
&std::env::vars().collect(),
|
||||
/*arg0*/ &None,
|
||||
TerminalSize::default(),
|
||||
akode_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_control_tx, control_rx) = mpsc::channel(1);
|
||||
let (tx, mut notifications) = mpsc::channel(1);
|
||||
let process = tokio::spawn(run_process(RunProcessParams {
|
||||
outgoing: Arc::new(OutgoingMessageSender::new(tx)),
|
||||
request_id: ConnectionRequestId {
|
||||
connection_id: ConnectionId(1),
|
||||
request_id: akode_app_server_protocol::RequestId::Integer(1),
|
||||
},
|
||||
process_handle: "console".into(),
|
||||
spawned,
|
||||
control_rx,
|
||||
stream_stdin: true,
|
||||
stream_stdout_stderr: false,
|
||||
expiration: ExecExpiration::DefaultTimeout,
|
||||
output_bytes_cap: None,
|
||||
}));
|
||||
let Some(OutgoingEnvelope::ToConnection {
|
||||
message: OutgoingMessage::AppServerNotification(envelope),
|
||||
write_complete_tx: Some(written),
|
||||
..
|
||||
}) = tokio::time::timeout(Duration::from_secs(15), notifications.recv())
|
||||
.await
|
||||
.expect("exit should arrive while the descendant is still attached")
|
||||
else {
|
||||
panic!("expected an exit notification")
|
||||
};
|
||||
let ServerNotification::ProcessExited(exit) = envelope.notification else {
|
||||
panic!("expected process/exited");
|
||||
};
|
||||
assert_eq!(exit.exit_code, 0);
|
||||
assert!(exit.stdout.contains("complete"));
|
||||
assert_eq!(exit.output_drain_timed_out, Some(true));
|
||||
std::fs::write(dir.path().join("received"), b"").unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !dir.path().join("acknowledged").exists() {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the attached child should still be alive when the client receives process/exited");
|
||||
written.send(()).unwrap();
|
||||
process.await.unwrap();
|
||||
}
|
||||
402
akode-rs/app-server/src/request_processors/projects.rs
Normal file
402
akode-rs/app-server/src/request_processors/projects.rs
Normal file
@@ -0,0 +1,402 @@
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::Project;
|
||||
use akode_app_server_protocol::ProjectChangeType;
|
||||
use akode_app_server_protocol::ProjectChangedNotification;
|
||||
use akode_app_server_protocol::ProjectCreateParams;
|
||||
use akode_app_server_protocol::ProjectCreateResponse;
|
||||
use akode_app_server_protocol::ProjectDeleteParams;
|
||||
use akode_app_server_protocol::ProjectDeleteResponse;
|
||||
use akode_app_server_protocol::ProjectImportParams;
|
||||
use akode_app_server_protocol::ProjectImportResponse;
|
||||
use akode_app_server_protocol::ProjectListParams;
|
||||
use akode_app_server_protocol::ProjectListResponse;
|
||||
use akode_app_server_protocol::ProjectMoveParams;
|
||||
use akode_app_server_protocol::ProjectMoveResponse;
|
||||
use akode_app_server_protocol::ProjectReadParams;
|
||||
use akode_app_server_protocol::ProjectReadResponse;
|
||||
use akode_app_server_protocol::ProjectRoot;
|
||||
use akode_app_server_protocol::ProjectSortKey;
|
||||
use akode_app_server_protocol::ProjectUpdateParams;
|
||||
use akode_app_server_protocol::ProjectUpdateResponse;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::SortDirection;
|
||||
use akode_app_server_protocol::ThreadProjectUpdatedNotification;
|
||||
use akode_thread_store::CreateProjectParams as StoreCreateProjectParams;
|
||||
use akode_thread_store::ListProjectsParams as StoreListProjectsParams;
|
||||
use akode_thread_store::MoveProjectParams as StoreMoveProjectParams;
|
||||
use akode_thread_store::ProjectMoveOutcome;
|
||||
use akode_thread_store::ProjectSortKey as StoreProjectSortKey;
|
||||
use akode_thread_store::SortDirection as StoreSortDirection;
|
||||
use akode_thread_store::StoredProject;
|
||||
use akode_thread_store::StoredProjectRoot;
|
||||
use akode_thread_store::ThreadStore;
|
||||
use akode_thread_store::ThreadStoreError;
|
||||
use akode_thread_store::UpdateProjectParams as StoreUpdateProjectParams;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
|
||||
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
|
||||
use super::thread_processor::THREAD_LIST_MAX_LIMIT;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_params;
|
||||
use crate::error_code::method_not_found;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ProjectRequestProcessor {
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_list_state_permit: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl ProjectRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_list_state_permit: Arc<Semaphore>,
|
||||
) -> Self {
|
||||
Self {
|
||||
thread_store,
|
||||
outgoing,
|
||||
thread_list_state_permit,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn project_list(
|
||||
&self,
|
||||
params: ProjectListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
if params.sort_key.is_none() && params.sort_direction.is_some() {
|
||||
return Err(invalid_params("sortDirection requires sortKey"));
|
||||
}
|
||||
let sort_key = match params.sort_key.unwrap_or(ProjectSortKey::Position) {
|
||||
ProjectSortKey::Position => StoreProjectSortKey::Position,
|
||||
ProjectSortKey::RecencyAt => StoreProjectSortKey::RecencyAt,
|
||||
};
|
||||
let sort_direction = match params.sort_direction {
|
||||
Some(SortDirection::Asc) => StoreSortDirection::Asc,
|
||||
Some(SortDirection::Desc) => StoreSortDirection::Desc,
|
||||
None => match sort_key {
|
||||
StoreProjectSortKey::Position => StoreSortDirection::Asc,
|
||||
StoreProjectSortKey::RecencyAt => StoreSortDirection::Desc,
|
||||
},
|
||||
};
|
||||
let page = self
|
||||
.thread_store
|
||||
.list_projects(StoreListProjectsParams {
|
||||
cursor: params.cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
limit: params
|
||||
.limit
|
||||
.map(|limit| limit as usize)
|
||||
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
|
||||
.clamp(1, THREAD_LIST_MAX_LIMIT),
|
||||
})
|
||||
.await
|
||||
.map_err(|error| project_store_error("project/list", error))?;
|
||||
Ok(Some(
|
||||
ProjectListResponse {
|
||||
data: page
|
||||
.projects
|
||||
.into_iter()
|
||||
.map(api_project)
|
||||
.collect::<Result<_, _>>()?,
|
||||
next_cursor: page.next_cursor,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn project_read(
|
||||
&self,
|
||||
params: ProjectReadParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let project = self
|
||||
.thread_store
|
||||
.read_project(params.project_id.clone())
|
||||
.await
|
||||
.map_err(|error| project_store_error("project/read", error))?
|
||||
.ok_or_else(|| invalid_params(format!("project not found: {}", params.project_id)))?;
|
||||
Ok(Some(
|
||||
ProjectReadResponse {
|
||||
project: api_project(project)?,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn project_create(
|
||||
&self,
|
||||
params: ProjectCreateParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let (project, created, _) = self
|
||||
.create_project(
|
||||
params.name,
|
||||
params.roots,
|
||||
params.metadata,
|
||||
Vec::new(),
|
||||
params.idempotency_key,
|
||||
"project/create",
|
||||
)
|
||||
.await?;
|
||||
if created {
|
||||
self.notify_project_changed(&project.id, ProjectChangeType::Created)
|
||||
.await;
|
||||
}
|
||||
Ok(Some(ProjectCreateResponse { project }.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn project_import(
|
||||
&self,
|
||||
params: ProjectImportParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let _thread_list_state_permit = self.acquire_thread_list_state_permit().await?;
|
||||
let (project, created, thread_ids) = self
|
||||
.create_project(
|
||||
params.name,
|
||||
params.roots,
|
||||
params.metadata,
|
||||
params.threads.unwrap_or_default(),
|
||||
params.idempotency_key,
|
||||
"project/import",
|
||||
)
|
||||
.await?;
|
||||
if created {
|
||||
self.notify_project_changed(&project.id, ProjectChangeType::Created)
|
||||
.await;
|
||||
self.notify_thread_projects(thread_ids, Some(project.id.clone()))
|
||||
.await;
|
||||
}
|
||||
Ok(Some(ProjectImportResponse { project }.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn project_update(
|
||||
&self,
|
||||
params: ProjectUpdateParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let name = params.name.map(validate_name).transpose()?;
|
||||
let roots = params.roots.map(validate_roots).transpose()?;
|
||||
let updated = self
|
||||
.thread_store
|
||||
.update_project(StoreUpdateProjectParams {
|
||||
project_id: params.project_id.clone(),
|
||||
name,
|
||||
roots,
|
||||
metadata: params.metadata,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| project_store_error("project/update", error))?
|
||||
.ok_or_else(|| invalid_params(format!("project not found: {}", params.project_id)))?;
|
||||
let project = api_project(updated.project)?;
|
||||
if updated.changed {
|
||||
self.notify_project_changed(&project.id, ProjectChangeType::Updated)
|
||||
.await;
|
||||
}
|
||||
Ok(Some(ProjectUpdateResponse { project }.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn project_move(
|
||||
&self,
|
||||
params: ProjectMoveParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let project_id = params.project_id;
|
||||
let outcome = self
|
||||
.thread_store
|
||||
.move_project(StoreMoveProjectParams {
|
||||
project_id: project_id.clone(),
|
||||
before_project_id: params.before_project_id,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| project_store_error("project/move", error))?
|
||||
.ok_or_else(|| invalid_params(format!("project not found: {project_id}")))?;
|
||||
if outcome == ProjectMoveOutcome::Moved {
|
||||
self.notify_project_changed(&project_id, ProjectChangeType::Updated)
|
||||
.await;
|
||||
}
|
||||
Ok(Some(ProjectMoveResponse {}.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn project_delete(
|
||||
&self,
|
||||
params: ProjectDeleteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let _thread_list_state_permit = self.acquire_thread_list_state_permit().await?;
|
||||
let deleted = self
|
||||
.thread_store
|
||||
.delete_project(params.project_id.clone())
|
||||
.await
|
||||
.map_err(|error| project_store_error("project/delete", error))?
|
||||
.ok_or_else(|| invalid_params(format!("project not found: {}", params.project_id)))?;
|
||||
self.notify_project_changed(¶ms.project_id, ProjectChangeType::Deleted)
|
||||
.await;
|
||||
self.notify_thread_projects(deleted.affected_active_thread_ids, /*project_id*/ None)
|
||||
.await;
|
||||
Ok(Some(ProjectDeleteResponse {}.into()))
|
||||
}
|
||||
|
||||
async fn create_project(
|
||||
&self,
|
||||
name: String,
|
||||
roots: Vec<ProjectRoot>,
|
||||
metadata: Option<std::collections::BTreeMap<String, String>>,
|
||||
thread_ids: Vec<String>,
|
||||
idempotency_key: String,
|
||||
operation: &'static str,
|
||||
) -> Result<(Project, bool, Vec<String>), JSONRPCErrorError> {
|
||||
let idempotency_key = validate_idempotency_key(idempotency_key)?;
|
||||
let thread_ids = validate_thread_ids(thread_ids)?;
|
||||
let created = self
|
||||
.thread_store
|
||||
.create_project(StoreCreateProjectParams {
|
||||
name: validate_name(name)?,
|
||||
roots: validate_roots(roots)?,
|
||||
metadata: metadata.unwrap_or_default(),
|
||||
thread_ids: thread_ids.clone(),
|
||||
idempotency_key,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| project_store_error(operation, error))?;
|
||||
Ok((api_project(created.project)?, created.created, thread_ids))
|
||||
}
|
||||
|
||||
async fn notify_project_changed(&self, project_id: &str, change_type: ProjectChangeType) {
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ProjectChanged(
|
||||
ProjectChangedNotification {
|
||||
project_id: project_id.to_string(),
|
||||
change_type,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn notify_thread_projects(&self, thread_ids: Vec<String>, project_id: Option<String>) {
|
||||
for thread_id in thread_ids {
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ThreadProjectUpdated(
|
||||
ThreadProjectUpdatedNotification {
|
||||
thread_id,
|
||||
project_id: project_id.clone(),
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn acquire_thread_list_state_permit(
|
||||
&self,
|
||||
) -> Result<SemaphorePermit<'_>, JSONRPCErrorError> {
|
||||
self.thread_list_state_permit
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to acquire thread list state permit: {err}"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_name(name: String) -> Result<String, JSONRPCErrorError> {
|
||||
let name = name.trim().to_string();
|
||||
if name.is_empty() {
|
||||
return Err(invalid_params("project name must not be empty"));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn validate_idempotency_key(key: String) -> Result<String, JSONRPCErrorError> {
|
||||
if key.trim().is_empty() {
|
||||
return Err(invalid_params("idempotencyKey must not be empty"));
|
||||
}
|
||||
if key.len() > 512 {
|
||||
return Err(invalid_params("idempotencyKey must be at most 512 bytes"));
|
||||
}
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
fn validate_roots(roots: Vec<ProjectRoot>) -> Result<Vec<StoredProjectRoot>, JSONRPCErrorError> {
|
||||
let mut logical = HashSet::new();
|
||||
let mut canonical = HashSet::new();
|
||||
roots
|
||||
.into_iter()
|
||||
.map(|root| {
|
||||
let path = akode_utils_absolute_path::AbsolutePathBuf::from_absolute_path_checked(
|
||||
root.path.into_path_buf(),
|
||||
)
|
||||
.map_err(|error| invalid_params(format!("invalid project root: {error}")))?
|
||||
.into_path_buf();
|
||||
if !logical.insert(path.clone()) {
|
||||
return Err(invalid_params(format!(
|
||||
"duplicate project root: {}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
if let Ok(resolved) = std::fs::canonicalize(&path)
|
||||
&& !canonical.insert(resolved)
|
||||
{
|
||||
return Err(invalid_params(format!(
|
||||
"duplicate resolved project root: {}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
Ok(StoredProjectRoot {
|
||||
path: path.display().to_string(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn validate_thread_ids(thread_ids: Vec<String>) -> Result<Vec<String>, JSONRPCErrorError> {
|
||||
let mut seen = HashSet::new();
|
||||
for thread_id in &thread_ids {
|
||||
if !seen.insert(thread_id.clone()) {
|
||||
return Err(invalid_params(format!("duplicate thread id: {thread_id}")));
|
||||
}
|
||||
}
|
||||
Ok(thread_ids)
|
||||
}
|
||||
|
||||
fn api_project(project: StoredProject) -> Result<Project, JSONRPCErrorError> {
|
||||
Ok(Project {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
roots: project
|
||||
.roots
|
||||
.into_iter()
|
||||
.map(|root| {
|
||||
Ok(ProjectRoot {
|
||||
path: akode_utils_absolute_path::AbsolutePathBuf::from_absolute_path(root.path)
|
||||
.map_err(|error| {
|
||||
internal_error(format!("stored project root is not absolute: {error}"))
|
||||
})?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, JSONRPCErrorError>>()?,
|
||||
metadata: project.metadata,
|
||||
position: project.position,
|
||||
created_at: project.created_at_ms / 1000,
|
||||
updated_at: project.updated_at_ms / 1000,
|
||||
recency_at: project
|
||||
.recency_at_ms
|
||||
.map(|timestamp| timestamp.div_euclid(/*rhs*/ 1000)),
|
||||
})
|
||||
}
|
||||
|
||||
fn project_store_error(operation: &'static str, error: ThreadStoreError) -> JSONRPCErrorError {
|
||||
match error {
|
||||
ThreadStoreError::Unsupported { .. } => {
|
||||
method_not_found(format!("{operation} is unavailable without sqlite state"))
|
||||
}
|
||||
ThreadStoreError::InvalidRequest { message } => invalid_params(message),
|
||||
ThreadStoreError::Internal { message }
|
||||
if message.contains("thread not found") || message.contains("project not found") =>
|
||||
{
|
||||
invalid_params(message)
|
||||
}
|
||||
error => internal_error(format!("failed to run {operation}: {error}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::transport::RemoteControlEnableError;
|
||||
use crate::transport::RemoteControlHandle;
|
||||
use crate::transport::RemoteControlUnavailable;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::RemoteControlClientsListParams;
|
||||
use akode_app_server_protocol::RemoteControlClientsListResponse;
|
||||
use akode_app_server_protocol::RemoteControlClientsRevokeParams;
|
||||
use akode_app_server_protocol::RemoteControlClientsRevokeResponse;
|
||||
use akode_app_server_protocol::RemoteControlDisableResponse;
|
||||
use akode_app_server_protocol::RemoteControlEnableResponse;
|
||||
use akode_app_server_protocol::RemoteControlPairingStartParams;
|
||||
use akode_app_server_protocol::RemoteControlPairingStartResponse;
|
||||
use akode_app_server_protocol::RemoteControlPairingStatusParams;
|
||||
use akode_app_server_protocol::RemoteControlPairingStatusResponse;
|
||||
use akode_app_server_protocol::RemoteControlStatusReadResponse;
|
||||
use akode_core::path_utils::write_atomically;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::fs::OpenOptions;
|
||||
use std::fs::TryLockError;
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RemoteControlRequestProcessor {
|
||||
remote_control_handle: Option<RemoteControlHandle>,
|
||||
pub(crate) daemon_settings_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl RemoteControlRequestProcessor {
|
||||
pub(crate) fn new(remote_control_handle: Option<RemoteControlHandle>) -> Self {
|
||||
Self {
|
||||
remote_control_handle,
|
||||
daemon_settings_file: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn enable(
|
||||
&self,
|
||||
ephemeral: bool,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Result<RemoteControlEnableResponse, JSONRPCErrorError> {
|
||||
let handle = self.handle()?;
|
||||
let status = if ephemeral {
|
||||
handle.enable_ephemeral().map_err(map_enable_error)?
|
||||
} else {
|
||||
handle
|
||||
.enable(app_server_client_name)
|
||||
.await
|
||||
.map_err(map_update_error)?
|
||||
};
|
||||
if !ephemeral {
|
||||
self.persist_daemon_preference(/*enabled*/ true)
|
||||
.await
|
||||
.map_err(map_update_error)?;
|
||||
}
|
||||
Ok(RemoteControlEnableResponse::from(status))
|
||||
}
|
||||
|
||||
pub(crate) async fn disable(
|
||||
&self,
|
||||
ephemeral: bool,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Result<RemoteControlDisableResponse, JSONRPCErrorError> {
|
||||
let handle = self.handle()?;
|
||||
let status = if ephemeral {
|
||||
handle.disable_ephemeral().await
|
||||
} else {
|
||||
handle
|
||||
.disable(app_server_client_name)
|
||||
.await
|
||||
.map_err(map_update_error)?
|
||||
};
|
||||
if !ephemeral {
|
||||
self.persist_daemon_preference(/*enabled*/ false)
|
||||
.await
|
||||
.map_err(map_update_error)?;
|
||||
}
|
||||
Ok(RemoteControlDisableResponse::from(status))
|
||||
}
|
||||
|
||||
async fn persist_daemon_preference(&self, enabled: bool) -> io::Result<()> {
|
||||
let Some(path) = self.daemon_settings_file.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let lock = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path.with_file_name("daemon.lock"))?;
|
||||
// The daemon may be waiting for this RPC during shutdown. Never wait
|
||||
// for it: a concurrent lifecycle operation wins over RPC persistence.
|
||||
match lock.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(TryLockError::WouldBlock) => return Ok(()),
|
||||
Err(TryLockError::Error(err)) => return Err(err),
|
||||
}
|
||||
let mut settings: Map<String, Value> = match fs::read(&path) {
|
||||
Ok(contents) => serde_json::from_slice(&contents)?,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Map::new(),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
settings.insert("remoteControlEnabled".to_string(), Value::Bool(enabled));
|
||||
write_atomically(&path, &serde_json::to_string_pretty(&settings)?)
|
||||
})
|
||||
.await
|
||||
.map_err(io::Error::other)?
|
||||
}
|
||||
|
||||
pub(crate) fn status_read(&self) -> Result<RemoteControlStatusReadResponse, JSONRPCErrorError> {
|
||||
let status = self.handle()?.status();
|
||||
Ok(RemoteControlStatusReadResponse {
|
||||
status: status.status,
|
||||
server_name: status.server_name,
|
||||
installation_id: status.installation_id,
|
||||
environment_id: status.environment_id,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn pairing_start(
|
||||
&self,
|
||||
params: RemoteControlPairingStartParams,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Result<RemoteControlPairingStartResponse, JSONRPCErrorError> {
|
||||
self.handle()?
|
||||
.start_pairing(params, app_server_client_name)
|
||||
.await
|
||||
.map_err(map_pairing_start_error)
|
||||
}
|
||||
|
||||
pub(crate) async fn pairing_status(
|
||||
&self,
|
||||
params: RemoteControlPairingStatusParams,
|
||||
) -> Result<RemoteControlPairingStatusResponse, JSONRPCErrorError> {
|
||||
validate_pairing_status_params(¶ms)?;
|
||||
let handle = self.handle()?;
|
||||
handle
|
||||
.pairing_status(params)
|
||||
.await
|
||||
.map_err(map_pairing_start_error)
|
||||
}
|
||||
|
||||
pub(crate) async fn clients_list(
|
||||
&self,
|
||||
params: RemoteControlClientsListParams,
|
||||
) -> Result<RemoteControlClientsListResponse, JSONRPCErrorError> {
|
||||
self.handle()?
|
||||
.list_clients(params)
|
||||
.await
|
||||
.map_err(map_client_management_error)
|
||||
}
|
||||
|
||||
pub(crate) async fn clients_revoke(
|
||||
&self,
|
||||
params: RemoteControlClientsRevokeParams,
|
||||
) -> Result<RemoteControlClientsRevokeResponse, JSONRPCErrorError> {
|
||||
self.handle()?
|
||||
.revoke_client(params)
|
||||
.await
|
||||
.map_err(map_client_management_error)
|
||||
}
|
||||
|
||||
fn handle(&self) -> Result<&RemoteControlHandle, JSONRPCErrorError> {
|
||||
let handle = self
|
||||
.remote_control_handle
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("remote control is unavailable for this app-server"))?;
|
||||
handle
|
||||
.ensure_remote_control_allowed()
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
Ok(handle)
|
||||
}
|
||||
}
|
||||
|
||||
fn map_enable_error(err: RemoteControlEnableError) -> JSONRPCErrorError {
|
||||
match err {
|
||||
RemoteControlEnableError::Unavailable(err) => map_unavailable(err),
|
||||
RemoteControlEnableError::DisabledByRequirements(err) => invalid_request(err.to_string()),
|
||||
RemoteControlEnableError::AuthenticationChanged => internal_error(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_unavailable(err: RemoteControlUnavailable) -> JSONRPCErrorError {
|
||||
invalid_request(err.to_string())
|
||||
}
|
||||
|
||||
fn map_update_error(err: io::Error) -> JSONRPCErrorError {
|
||||
if matches!(
|
||||
err.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
|
||||
) {
|
||||
invalid_request(err.to_string())
|
||||
} else {
|
||||
internal_error(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn map_pairing_start_error(err: io::Error) -> JSONRPCErrorError {
|
||||
if err.kind() == io::ErrorKind::InvalidInput {
|
||||
invalid_request(err.to_string())
|
||||
} else {
|
||||
internal_error(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_pairing_status_params(
|
||||
params: &RemoteControlPairingStatusParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
match (¶ms.pairing_code, ¶ms.manual_pairing_code) {
|
||||
(Some(_), None) | (None, Some(_)) => Ok(()),
|
||||
(Some(_), Some(_)) => Err(invalid_request(
|
||||
"remoteControl/pairing/status accepts either pairingCode or manualPairingCode, not both",
|
||||
)),
|
||||
(None, None) => Err(invalid_request(
|
||||
"remoteControl/pairing/status requires pairingCode or manualPairingCode",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_client_management_error(err: io::Error) -> JSONRPCErrorError {
|
||||
match err.kind() {
|
||||
io::ErrorKind::InvalidInput
|
||||
| io::ErrorKind::NotFound
|
||||
| io::ErrorKind::PermissionDenied
|
||||
| io::ErrorKind::WouldBlock => invalid_request(err.to_string()),
|
||||
_ => internal_error(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod remote_control_processor_tests;
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::*;
|
||||
use crate::error_code::INTERNAL_ERROR_CODE;
|
||||
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn pairing_start_returns_internal_error_when_remote_control_is_unavailable() {
|
||||
let err = RemoteControlRequestProcessor::new(/*remote_control_handle*/ None)
|
||||
.pairing_start(
|
||||
RemoteControlPairingStartParams::default(),
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect_err("missing remote control should fail pairing");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
JSONRPCErrorError {
|
||||
code: INTERNAL_ERROR_CODE,
|
||||
data: None,
|
||||
message: "remote control is unavailable for this app-server".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pairing_status_returns_internal_error_when_remote_control_is_unavailable() {
|
||||
let err = RemoteControlRequestProcessor::new(/*remote_control_handle*/ None)
|
||||
.pairing_status(RemoteControlPairingStatusParams {
|
||||
pairing_code: Some("pairing-code".to_string()),
|
||||
manual_pairing_code: None,
|
||||
})
|
||||
.await
|
||||
.expect_err("missing remote control should fail pairing status");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
JSONRPCErrorError {
|
||||
code: INTERNAL_ERROR_CODE,
|
||||
data: None,
|
||||
message: "remote control is unavailable for this app-server".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pairing_status_rejects_missing_pairing_codes() {
|
||||
assert_eq!(
|
||||
validate_pairing_status_params(&RemoteControlPairingStatusParams {
|
||||
pairing_code: None,
|
||||
manual_pairing_code: None,
|
||||
}),
|
||||
Err(JSONRPCErrorError {
|
||||
code: INVALID_REQUEST_ERROR_CODE,
|
||||
data: None,
|
||||
message: "remoteControl/pairing/status requires pairingCode or manualPairingCode"
|
||||
.to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pairing_status_rejects_conflicting_pairing_codes() {
|
||||
assert_eq!(
|
||||
validate_pairing_status_params(&RemoteControlPairingStatusParams {
|
||||
pairing_code: Some("pairing-code".to_string()),
|
||||
manual_pairing_code: Some("ABCD-EFGH".to_string()),
|
||||
}),
|
||||
Err(JSONRPCErrorError {
|
||||
code: INVALID_REQUEST_ERROR_CODE,
|
||||
data: None,
|
||||
message:
|
||||
"remoteControl/pairing/status accepts either pairingCode or manualPairingCode, not both"
|
||||
.to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pairing_start_maps_invalid_input_to_invalid_request() {
|
||||
assert_eq!(
|
||||
map_pairing_start_error(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"remote control pairing is unavailable",
|
||||
)),
|
||||
JSONRPCErrorError {
|
||||
code: INVALID_REQUEST_ERROR_CODE,
|
||||
data: None,
|
||||
message: "remote control pairing is unavailable".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pairing_start_maps_backend_failures_to_internal_error() {
|
||||
assert_eq!(
|
||||
map_pairing_start_error(io::Error::other("remote control pairing failed")),
|
||||
JSONRPCErrorError {
|
||||
code: INTERNAL_ERROR_CODE,
|
||||
data: None,
|
||||
message: "remote control pairing failed".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_management_maps_user_actionable_errors_to_invalid_request() {
|
||||
for kind in [
|
||||
io::ErrorKind::InvalidInput,
|
||||
io::ErrorKind::NotFound,
|
||||
io::ErrorKind::PermissionDenied,
|
||||
io::ErrorKind::WouldBlock,
|
||||
] {
|
||||
assert_eq!(
|
||||
map_client_management_error(io::Error::new(kind, "client management unavailable")),
|
||||
JSONRPCErrorError {
|
||||
code: INVALID_REQUEST_ERROR_CODE,
|
||||
data: None,
|
||||
message: "client management unavailable".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_management_maps_backend_failures_to_internal_error() {
|
||||
assert_eq!(
|
||||
map_client_management_error(io::Error::other("client management failed")),
|
||||
JSONRPCErrorError {
|
||||
code: INTERNAL_ERROR_CODE,
|
||||
data: None,
|
||||
message: "client management failed".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use super::*;
|
||||
use akode_protocol::error::CodexErrorDetails;
|
||||
|
||||
pub(super) fn environment_selection_error(err: CodexErr) -> JSONRPCErrorError {
|
||||
match err.details() {
|
||||
CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()),
|
||||
_ => internal_error(format!("failed to validate environment selections: {err}")),
|
||||
}
|
||||
}
|
||||
24
akode-rs/app-server/src/request_processors/rollout.rs
Normal file
24
akode-rs/app-server/src/request_processors/rollout.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
//! Triggers local rollout maintenance without waiting for the background pass.
|
||||
|
||||
use super::ThreadRequestProcessor;
|
||||
use super::thread_processor::unsupported_thread_store_operation;
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::RolloutCompressResponse;
|
||||
use akode_thread_store::LocalThreadStore;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) fn rollout_compress(
|
||||
&self,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
if !self.thread_store.as_any().is::<LocalThreadStore>() {
|
||||
return Err(unsupported_thread_store_operation("rollout/compress"));
|
||||
}
|
||||
|
||||
akode_rollout::spawn_rollout_compression_worker(
|
||||
self.config.codex_home.to_path_buf(),
|
||||
akode_rollout::RolloutCompressionTrigger::Rpc,
|
||||
);
|
||||
Ok(Some(RolloutCompressResponse {}.into()))
|
||||
}
|
||||
}
|
||||
134
akode-rs/app-server/src/request_processors/search.rs
Normal file
134
akode-rs/app-server/src/request_processors/search.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::fuzzy_file_search::FuzzyFileSearchSession;
|
||||
use crate::fuzzy_file_search::run_fuzzy_file_search;
|
||||
use crate::fuzzy_file_search::start_fuzzy_file_search_session;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use akode_app_server_protocol::FuzzyFileSearchParams;
|
||||
use akode_app_server_protocol::FuzzyFileSearchResponse;
|
||||
use akode_app_server_protocol::FuzzyFileSearchSessionStartParams;
|
||||
use akode_app_server_protocol::FuzzyFileSearchSessionStartResponse;
|
||||
use akode_app_server_protocol::FuzzyFileSearchSessionStopParams;
|
||||
use akode_app_server_protocol::FuzzyFileSearchSessionStopResponse;
|
||||
use akode_app_server_protocol::FuzzyFileSearchSessionUpdateParams;
|
||||
use akode_app_server_protocol::FuzzyFileSearchSessionUpdateResponse;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SearchRequestProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
pending_fuzzy_searches: Arc<Mutex<HashMap<String, Arc<AtomicBool>>>>,
|
||||
fuzzy_search_sessions: Arc<Mutex<HashMap<String, FuzzyFileSearchSession>>>,
|
||||
}
|
||||
|
||||
impl SearchRequestProcessor {
|
||||
pub(crate) fn new(outgoing: Arc<OutgoingMessageSender>) -> Self {
|
||||
Self {
|
||||
outgoing,
|
||||
pending_fuzzy_searches: Arc::new(Mutex::new(HashMap::new())),
|
||||
fuzzy_search_sessions: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn fuzzy_file_search(
|
||||
&self,
|
||||
params: FuzzyFileSearchParams,
|
||||
) -> Result<FuzzyFileSearchResponse, JSONRPCErrorError> {
|
||||
let FuzzyFileSearchParams {
|
||||
query,
|
||||
roots,
|
||||
cancellation_token,
|
||||
} = params;
|
||||
|
||||
let cancel_flag = match cancellation_token.clone() {
|
||||
Some(token) => {
|
||||
let mut pending_fuzzy_searches = self.pending_fuzzy_searches.lock().await;
|
||||
// if a cancellation_token is provided and a pending_request exists for
|
||||
// that token, cancel it
|
||||
if let Some(existing) = pending_fuzzy_searches.get(&token) {
|
||||
existing.store(true, Ordering::Relaxed);
|
||||
}
|
||||
let flag = Arc::new(AtomicBool::new(false));
|
||||
pending_fuzzy_searches.insert(token.clone(), flag.clone());
|
||||
flag
|
||||
}
|
||||
None => Arc::new(AtomicBool::new(false)),
|
||||
};
|
||||
|
||||
let results = match query.as_str() {
|
||||
"" => vec![],
|
||||
_ => run_fuzzy_file_search(query, roots, cancel_flag.clone()).await,
|
||||
};
|
||||
|
||||
if let Some(token) = cancellation_token {
|
||||
let mut pending_fuzzy_searches = self.pending_fuzzy_searches.lock().await;
|
||||
if let Some(current_flag) = pending_fuzzy_searches.get(&token)
|
||||
&& Arc::ptr_eq(current_flag, &cancel_flag)
|
||||
{
|
||||
pending_fuzzy_searches.remove(&token);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(FuzzyFileSearchResponse { files: results })
|
||||
}
|
||||
|
||||
pub(crate) async fn fuzzy_file_search_session_start_response(
|
||||
&self,
|
||||
params: FuzzyFileSearchSessionStartParams,
|
||||
) -> Result<FuzzyFileSearchSessionStartResponse, JSONRPCErrorError> {
|
||||
let FuzzyFileSearchSessionStartParams { session_id, roots } = params;
|
||||
if session_id.is_empty() {
|
||||
return Err(invalid_request("sessionId must not be empty"));
|
||||
}
|
||||
|
||||
let session =
|
||||
start_fuzzy_file_search_session(session_id.clone(), roots, self.outgoing.clone())
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to start fuzzy file search session: {err}"))
|
||||
})?;
|
||||
self.fuzzy_search_sessions
|
||||
.lock()
|
||||
.await
|
||||
.insert(session_id, session);
|
||||
Ok(FuzzyFileSearchSessionStartResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn fuzzy_file_search_session_update_response(
|
||||
&self,
|
||||
params: FuzzyFileSearchSessionUpdateParams,
|
||||
) -> Result<FuzzyFileSearchSessionUpdateResponse, JSONRPCErrorError> {
|
||||
let FuzzyFileSearchSessionUpdateParams { session_id, query } = params;
|
||||
let found = {
|
||||
let sessions = self.fuzzy_search_sessions.lock().await;
|
||||
if let Some(session) = sessions.get(&session_id) {
|
||||
session.update_query(query);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
if !found {
|
||||
return Err(invalid_request(format!(
|
||||
"fuzzy file search session not found: {session_id}"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(FuzzyFileSearchSessionUpdateResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn fuzzy_file_search_session_stop(
|
||||
&self,
|
||||
params: FuzzyFileSearchSessionStopParams,
|
||||
) -> Result<FuzzyFileSearchSessionStopResponse, JSONRPCErrorError> {
|
||||
let FuzzyFileSearchSessionStopParams { session_id } = params;
|
||||
self.fuzzy_search_sessions.lock().await.remove(&session_id);
|
||||
|
||||
Ok(FuzzyFileSearchSessionStopResponse {})
|
||||
}
|
||||
}
|
||||
294
akode-rs/app-server/src/request_processors/thread_attachments.rs
Normal file
294
akode-rs/app-server/src/request_processors/thread_attachments.rs
Normal file
@@ -0,0 +1,294 @@
|
||||
//! Attachment RPC handling; committed mutations respond before broadcasting updates.
|
||||
|
||||
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
|
||||
use super::thread_processor::ThreadRequestProcessor;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_params;
|
||||
use crate::error_code::method_not_found;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ThreadAttachment;
|
||||
use akode_app_server_protocol::ThreadAttachmentAddOutcome;
|
||||
use akode_app_server_protocol::ThreadAttachmentAddParams;
|
||||
use akode_app_server_protocol::ThreadAttachmentAddResponse;
|
||||
use akode_app_server_protocol::ThreadAttachmentListParams;
|
||||
use akode_app_server_protocol::ThreadAttachmentListResponse;
|
||||
use akode_app_server_protocol::ThreadAttachmentOperation;
|
||||
use akode_app_server_protocol::ThreadAttachmentOwner;
|
||||
use akode_app_server_protocol::ThreadAttachmentOwnerListParams;
|
||||
use akode_app_server_protocol::ThreadAttachmentOwnerListResponse;
|
||||
use akode_app_server_protocol::ThreadAttachmentRemoveParams;
|
||||
use akode_app_server_protocol::ThreadAttachmentRemoveResponse;
|
||||
use akode_app_server_protocol::ThreadAttachmentUpdatedNotification;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_state::MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES;
|
||||
use akode_state::MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE;
|
||||
use akode_state::MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES;
|
||||
use akode_state::MAX_THREAD_ATTACHMENT_TYPE_BYTES;
|
||||
use akode_thread_store::AddThreadAttachmentOutcome;
|
||||
use akode_thread_store::AddThreadAttachmentParams;
|
||||
use akode_thread_store::ListThreadAttachmentThreadsParams;
|
||||
use akode_thread_store::ListThreadAttachmentsParams;
|
||||
use akode_thread_store::RemoveThreadAttachmentOutcome;
|
||||
use akode_thread_store::RemoveThreadAttachmentParams;
|
||||
use akode_thread_store::ThreadAttachment as StoredThreadAttachment;
|
||||
use akode_thread_store::ThreadAttachmentArchiveFilter;
|
||||
use akode_thread_store::ThreadStoreError;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn thread_attachment_add(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ThreadAttachmentAddParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "thread/attachment/add";
|
||||
self.ensure_thread_attachments_supported(OPERATION)?;
|
||||
validate_attachment_identity(¶ms.attachment_type, ¶ms.identity_key)?;
|
||||
let payload_bytes = serde_json::to_vec(¶ms.payload)
|
||||
.map_err(|error| invalid_params(format!("invalid attachment payload: {error}")))?;
|
||||
if payload_bytes.len() > MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES {
|
||||
return Err(invalid_params(format!(
|
||||
"attachment payload must not exceed {MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
|
||||
let thread_id = parse_attachment_thread_id(¶ms.thread_id)?;
|
||||
let result = self
|
||||
.thread_store
|
||||
.add_thread_attachment(AddThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: params.attachment_type,
|
||||
identity_key: params.identity_key,
|
||||
payload: params.payload,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
|
||||
|
||||
let (response, notification) = match result {
|
||||
AddThreadAttachmentOutcome::Created(attachment) => {
|
||||
let notification = ThreadAttachmentUpdatedNotification {
|
||||
thread_id: attachment.thread_id.to_string(),
|
||||
attachment_type: attachment.attachment_type.clone(),
|
||||
identity_key: attachment.identity_key.clone(),
|
||||
attachment_id: attachment.id.clone(),
|
||||
operation: ThreadAttachmentOperation::Created,
|
||||
};
|
||||
(
|
||||
ThreadAttachmentAddResponse {
|
||||
outcome: ThreadAttachmentAddOutcome::Created,
|
||||
attachment: api_thread_attachment(attachment),
|
||||
},
|
||||
Some(notification),
|
||||
)
|
||||
}
|
||||
AddThreadAttachmentOutcome::Existing(attachment) => (
|
||||
ThreadAttachmentAddResponse {
|
||||
outcome: ThreadAttachmentAddOutcome::Existing,
|
||||
attachment: api_thread_attachment(attachment),
|
||||
},
|
||||
None,
|
||||
),
|
||||
};
|
||||
|
||||
self.outgoing.send_response(request_id, response).await;
|
||||
if let Some(notification) = notification {
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ThreadAttachmentUpdated(notification))
|
||||
.await;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_attachment_list(
|
||||
&self,
|
||||
params: ThreadAttachmentListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "thread/attachment/list";
|
||||
self.ensure_thread_attachments_supported(OPERATION)?;
|
||||
let thread_id = parse_attachment_thread_id(¶ms.thread_id)?;
|
||||
let limit = params
|
||||
.limit
|
||||
.map(|limit| limit as usize)
|
||||
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
|
||||
.clamp(1, MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE);
|
||||
let page = self
|
||||
.thread_store
|
||||
.list_thread_attachments(ListThreadAttachmentsParams {
|
||||
thread_id,
|
||||
cursor: params.cursor,
|
||||
limit,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
|
||||
|
||||
Ok(Some(
|
||||
ThreadAttachmentListResponse {
|
||||
data: page
|
||||
.attachments
|
||||
.into_iter()
|
||||
.map(api_thread_attachment)
|
||||
.collect(),
|
||||
next_cursor: page.next_cursor,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_attachment_owner_list(
|
||||
&self,
|
||||
params: ThreadAttachmentOwnerListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "thread/attachmentOwner/list";
|
||||
self.ensure_thread_attachments_supported(OPERATION)?;
|
||||
validate_attachment_identity(¶ms.attachment_type, ¶ms.identity_key)?;
|
||||
let limit = params
|
||||
.limit
|
||||
.map(|limit| limit as usize)
|
||||
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
|
||||
.clamp(1, MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE);
|
||||
let page = self
|
||||
.thread_store
|
||||
.list_thread_attachment_threads(ListThreadAttachmentThreadsParams {
|
||||
attachment_type: params.attachment_type,
|
||||
identity_key: params.identity_key,
|
||||
archive_filter: match params.archived {
|
||||
None => ThreadAttachmentArchiveFilter::All,
|
||||
Some(false) => ThreadAttachmentArchiveFilter::NonArchived,
|
||||
Some(true) => ThreadAttachmentArchiveFilter::Archived,
|
||||
},
|
||||
cursor: params.cursor,
|
||||
limit,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
|
||||
Ok(Some(
|
||||
ThreadAttachmentOwnerListResponse {
|
||||
data: page
|
||||
.threads
|
||||
.into_iter()
|
||||
.map(|thread| ThreadAttachmentOwner {
|
||||
thread_id: thread.thread_id.to_string(),
|
||||
archived: thread.archived,
|
||||
})
|
||||
.collect(),
|
||||
next_cursor: page.next_cursor,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_attachment_remove(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ThreadAttachmentRemoveParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "thread/attachment/remove";
|
||||
self.ensure_thread_attachments_supported(OPERATION)?;
|
||||
validate_attachment_identity(¶ms.attachment_type, ¶ms.identity_key)?;
|
||||
let thread_id = parse_attachment_thread_id(¶ms.thread_id)?;
|
||||
let result = self
|
||||
.thread_store
|
||||
.remove_thread_attachment(RemoveThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: params.attachment_type,
|
||||
identity_key: params.identity_key,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| thread_attachment_store_error(OPERATION, error))?;
|
||||
|
||||
self.outgoing
|
||||
.send_response(request_id, ThreadAttachmentRemoveResponse {})
|
||||
.await;
|
||||
if let RemoveThreadAttachmentOutcome::Removed(attachment) = result {
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ThreadAttachmentUpdated(
|
||||
ThreadAttachmentUpdatedNotification {
|
||||
thread_id: attachment.thread_id.to_string(),
|
||||
attachment_type: attachment.attachment_type,
|
||||
identity_key: attachment.identity_key,
|
||||
attachment_id: attachment.id,
|
||||
operation: ThreadAttachmentOperation::Deleted,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn ensure_thread_attachments_supported(
|
||||
&self,
|
||||
operation: &'static str,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if self.thread_store.supports_thread_attachments() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(unsupported_thread_attachment_operation(operation))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_attachment_identity(
|
||||
attachment_type: &str,
|
||||
identity_key: &str,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if attachment_type.trim().is_empty() {
|
||||
return Err(invalid_params("attachmentType must not be empty"));
|
||||
}
|
||||
if attachment_type.len() > MAX_THREAD_ATTACHMENT_TYPE_BYTES {
|
||||
return Err(invalid_params(format!(
|
||||
"attachmentType must not exceed {MAX_THREAD_ATTACHMENT_TYPE_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
if identity_key.trim().is_empty() {
|
||||
return Err(invalid_params("identityKey must not be empty"));
|
||||
}
|
||||
if identity_key.len() > MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES {
|
||||
return Err(invalid_params(format!(
|
||||
"identityKey must not exceed {MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_attachment_thread_id(thread_id: &str) -> Result<ThreadId, JSONRPCErrorError> {
|
||||
ThreadId::from_string(thread_id)
|
||||
.map_err(|error| invalid_params(format!("invalid thread id: {error}")))
|
||||
}
|
||||
|
||||
fn api_thread_attachment(attachment: StoredThreadAttachment) -> ThreadAttachment {
|
||||
ThreadAttachment {
|
||||
id: attachment.id,
|
||||
attachment_type: attachment.attachment_type,
|
||||
identity_key: attachment.identity_key,
|
||||
payload: attachment.payload,
|
||||
created_at: attachment.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_thread_attachment_operation(operation: &'static str) -> JSONRPCErrorError {
|
||||
method_not_found(format!(
|
||||
"{operation} is not supported by the configured thread store"
|
||||
))
|
||||
}
|
||||
|
||||
fn thread_attachment_store_error(
|
||||
operation: &'static str,
|
||||
error: ThreadStoreError,
|
||||
) -> JSONRPCErrorError {
|
||||
match error {
|
||||
ThreadStoreError::Unsupported { .. } => unsupported_thread_attachment_operation(operation),
|
||||
ThreadStoreError::InvalidRequest { message } => invalid_params(message),
|
||||
ThreadStoreError::ThreadNotFound { thread_id } => {
|
||||
invalid_params(format!("thread not found: {thread_id}"))
|
||||
}
|
||||
error @ (ThreadStoreError::Conflict { .. }
|
||||
| ThreadStoreError::Retryable { .. }
|
||||
| ThreadStoreError::OutcomeUnknown { .. }
|
||||
| ThreadStoreError::Internal { .. }) => {
|
||||
internal_error(format!("failed to process {operation}: {error}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
163
akode-rs/app-server/src/request_processors/thread_delete.rs
Normal file
163
akode-rs/app-server/src/request_processors/thread_delete.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
//! `thread/delete` request handling.
|
||||
|
||||
use super::thread_processor::unsupported_thread_store_operation;
|
||||
use super::*;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn thread_delete(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ThreadDeleteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let mut deleted_thread_ids = Vec::new();
|
||||
let result = {
|
||||
let _thread_list_state_permit = self.acquire_thread_list_state_permit().await?;
|
||||
self.thread_delete_response(params, &mut deleted_thread_ids)
|
||||
.await
|
||||
};
|
||||
match result {
|
||||
Ok(response) => {
|
||||
self.outgoing
|
||||
.send_response(request_id.clone(), response)
|
||||
.await;
|
||||
self.send_thread_deleted_notifications(deleted_thread_ids)
|
||||
.await;
|
||||
Ok(None)
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
async fn thread_delete_response(
|
||||
&self,
|
||||
params: ThreadDeleteParams,
|
||||
deleted_thread_ids: &mut Vec<String>,
|
||||
) -> Result<ThreadDeleteResponse, JSONRPCErrorError> {
|
||||
let thread_id = ThreadId::from_string(¶ms.thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
|
||||
let thread_ids = self.state_db_spawn_subtree_thread_ids(thread_id).await?;
|
||||
|
||||
self.validate_root_thread_delete(thread_id, thread_ids.len() > 1)
|
||||
.await?;
|
||||
if let Some(store) = self
|
||||
.thread_store
|
||||
.as_any()
|
||||
.downcast_ref::<LocalThreadStore>()
|
||||
{
|
||||
store
|
||||
.ensure_no_attached_threads(&thread_ids)
|
||||
.await
|
||||
.map_err(thread_store_delete_error)?;
|
||||
}
|
||||
for thread_id_to_delete in thread_ids.iter().copied() {
|
||||
self.prepare_thread_for_delete(thread_id_to_delete).await?;
|
||||
}
|
||||
|
||||
let mut delete_order: Vec<_> = thread_ids.iter().skip(1).rev().copied().collect();
|
||||
delete_order.push(thread_id);
|
||||
|
||||
self.thread_store
|
||||
.delete_threads(StoreDeleteThreadsParams {
|
||||
thread_ids: delete_order.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(thread_store_delete_error)?;
|
||||
|
||||
deleted_thread_ids.extend(
|
||||
delete_order
|
||||
.into_iter()
|
||||
.map(|thread_id| thread_id.to_string()),
|
||||
);
|
||||
Ok(ThreadDeleteResponse {})
|
||||
}
|
||||
|
||||
async fn send_thread_deleted_notifications(&self, deleted_thread_ids: Vec<String>) {
|
||||
for thread_id in deleted_thread_ids {
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ThreadDeleted(
|
||||
ThreadDeletedNotification { thread_id },
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_root_thread_delete(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
has_descendants: bool,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
|
||||
if !thread.config_snapshot().await.ephemeral {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(invalid_request(format!(
|
||||
"thread is not persisted and cannot be deleted: {thread_id}"
|
||||
)));
|
||||
}
|
||||
match self
|
||||
.thread_store
|
||||
.read_thread(StoreReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(()),
|
||||
Err(ThreadStoreError::ThreadNotFound { .. }) => {
|
||||
if has_descendants {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(state_db) = self.state_db.as_ref() else {
|
||||
return Err(thread_store_delete_error(
|
||||
ThreadStoreError::ThreadNotFound { thread_id },
|
||||
));
|
||||
};
|
||||
if state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to read app-server state for {thread_id}: {err}"
|
||||
))
|
||||
})?
|
||||
.is_some()
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(thread_store_delete_error(
|
||||
ThreadStoreError::ThreadNotFound { thread_id },
|
||||
))
|
||||
}
|
||||
}
|
||||
Err(err) => Err(thread_store_delete_error(err)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare_thread_for_delete(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
self.prepare_thread_for_removal(thread_id, "delete").await?;
|
||||
if let Some(log_db) = self.log_db.as_ref() {
|
||||
log_db.flush().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_store_delete_error(err: ThreadStoreError) -> JSONRPCErrorError {
|
||||
match err {
|
||||
ThreadStoreError::ThreadNotFound { thread_id } => {
|
||||
invalid_request(format!("thread not found: {thread_id}"))
|
||||
}
|
||||
ThreadStoreError::InvalidRequest { message } | ThreadStoreError::Conflict { message } => {
|
||||
invalid_request(message)
|
||||
}
|
||||
ThreadStoreError::Unsupported { operation } => {
|
||||
unsupported_thread_store_operation(operation)
|
||||
}
|
||||
err => internal_error(format!("failed to delete thread: {err}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
use super::apply_live_thread_settings;
|
||||
use super::thread_input::can_accept_direct_input;
|
||||
use crate::thread_status::ThreadWatchManager;
|
||||
use crate::thread_status::resolve_thread_status;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_core::ThreadManager;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::AgentStatus;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(super) async fn enrich_loaded_threads<T>(
|
||||
thread_manager: &ThreadManager,
|
||||
thread_watch_manager: &ThreadWatchManager,
|
||||
threads: &mut [T],
|
||||
mut as_thread: impl FnMut(&mut T) -> &mut Thread,
|
||||
) {
|
||||
let statuses = thread_watch_manager
|
||||
.loaded_statuses_for_threads(
|
||||
threads
|
||||
.iter_mut()
|
||||
.map(&mut as_thread)
|
||||
.map(|thread| thread.id.clone()),
|
||||
)
|
||||
.await;
|
||||
|
||||
futures::future::join_all(
|
||||
threads
|
||||
.iter_mut()
|
||||
.map(as_thread)
|
||||
.map(|thread| enrich_loaded_thread(thread_manager, &statuses, thread)),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn enrich_loaded_thread(
|
||||
thread_manager: &ThreadManager,
|
||||
statuses: &HashMap<String, ThreadStatus>,
|
||||
thread: &mut Thread,
|
||||
) {
|
||||
let watched_status = statuses.get(&thread.id);
|
||||
if let Some(status) = watched_status {
|
||||
thread.status = status.clone();
|
||||
}
|
||||
|
||||
if matches!(watched_status, Some(ThreadStatus::NotLoaded)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Ok(thread_id) = ThreadId::from_string(&thread.id) else {
|
||||
return;
|
||||
};
|
||||
let Ok(loaded_thread) = thread_manager.get_thread(thread_id).await else {
|
||||
return;
|
||||
};
|
||||
let config_snapshot = loaded_thread.config_snapshot().await;
|
||||
apply_live_thread_settings(thread, &config_snapshot);
|
||||
if !matches!(
|
||||
&thread.source,
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
|
||||
) {
|
||||
return;
|
||||
}
|
||||
match loaded_thread.agent_status().await {
|
||||
AgentStatus::Running => {
|
||||
if watched_status.is_none() {
|
||||
thread.status =
|
||||
resolve_thread_status(ThreadStatus::Idle, /*has_in_progress_turn*/ true);
|
||||
}
|
||||
}
|
||||
AgentStatus::PendingInit | AgentStatus::Interrupted | AgentStatus::Completed(_) => {
|
||||
if watched_status.is_none() {
|
||||
thread.status = ThreadStatus::Idle;
|
||||
}
|
||||
}
|
||||
AgentStatus::Errored(_) => {
|
||||
thread.status = ThreadStatus::SystemError;
|
||||
}
|
||||
AgentStatus::Shutdown | AgentStatus::NotFound => {
|
||||
thread.status = ThreadStatus::NotLoaded;
|
||||
return;
|
||||
}
|
||||
}
|
||||
thread.can_accept_direct_input = Some(can_accept_direct_input(
|
||||
loaded_thread.multi_agent_version(),
|
||||
&config_snapshot.session_source,
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::validate_thread_goal_objective;
|
||||
use akode_state::StateRuntime;
|
||||
|
||||
pub(super) async fn inherit_thread_goal_snapshot(
|
||||
state_db: &StateRuntime,
|
||||
source_thread_id: ThreadId,
|
||||
target_thread_id: ThreadId,
|
||||
) -> anyhow::Result<bool> {
|
||||
let Some(mut goal) = state_db
|
||||
.thread_goals()
|
||||
.get_thread_goal(source_thread_id)
|
||||
.await?
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if let Err(err) = validate_thread_goal_objective(&goal.objective) {
|
||||
tracing::warn!(%source_thread_id, "skipping invalid inherited thread goal: {err}");
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
goal.thread_id = target_thread_id;
|
||||
state_db
|
||||
.thread_goals()
|
||||
.replace_thread_goal_snapshot(&goal)
|
||||
.await?;
|
||||
Ok(true)
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
use super::thread_input::DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR;
|
||||
use super::thread_input::can_accept_direct_input;
|
||||
use super::thread_input::ensure_direct_input_allowed;
|
||||
use super::*;
|
||||
use akode_app_server_protocol::ThreadGoalMutationOrigin;
|
||||
use akode_core::context::UserGoalUpdate;
|
||||
use akode_goal_extension::GoalObjectiveUpdate;
|
||||
use akode_goal_extension::GoalService;
|
||||
use akode_goal_extension::GoalServiceError;
|
||||
use akode_goal_extension::GoalSetRequest;
|
||||
use akode_goal_extension::GoalTokenBudgetUpdate;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_rollout::RolloutRecorder;
|
||||
use akode_rollout::WriterLockCoordinator;
|
||||
|
||||
#[path = "thread_goal_user_context.rs"]
|
||||
mod user_context;
|
||||
|
||||
enum GoalAccess {
|
||||
Read,
|
||||
Mutate,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ThreadGoalRequestProcessor {
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
state_db: Option<StateDbHandle>,
|
||||
goal_service: Arc<GoalService>,
|
||||
config_manager: ConfigManager,
|
||||
writer_locks: Arc<WriterLockCoordinator>,
|
||||
}
|
||||
|
||||
impl ThreadGoalRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
state_db: Option<StateDbHandle>,
|
||||
goal_service: Arc<GoalService>,
|
||||
config_manager: ConfigManager,
|
||||
) -> Self {
|
||||
let writer_locks = Arc::new(WriterLockCoordinator::new(&config.codex_home));
|
||||
Self {
|
||||
thread_manager,
|
||||
outgoing,
|
||||
config,
|
||||
thread_state_manager,
|
||||
state_db,
|
||||
goal_service,
|
||||
config_manager,
|
||||
writer_locks,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_goal_set(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ThreadGoalSetParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.thread_goal_set_inner(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_goal_get(
|
||||
&self,
|
||||
params: ThreadGoalGetParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.thread_goal_get_inner(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_goal_clear(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ThreadGoalClearParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.thread_goal_clear_inner(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
pub(crate) async fn emit_resume_goal_snapshot(&self, thread_id: ThreadId) {
|
||||
if !self.config.features.enabled(Feature::Goals) {
|
||||
return;
|
||||
}
|
||||
self.emit_thread_goal_snapshot(thread_id).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn pending_resume_goal_state(
|
||||
&self,
|
||||
thread: &CodexThread,
|
||||
) -> (bool, Option<StateDbHandle>) {
|
||||
let emit_thread_goal_update = self.config.features.enabled(Feature::Goals);
|
||||
let thread_goal_state_db = if emit_thread_goal_update {
|
||||
if let Some(state_db) = thread.state_db() {
|
||||
Some(state_db)
|
||||
} else {
|
||||
self.state_db.clone()
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(emit_thread_goal_update, thread_goal_state_db)
|
||||
}
|
||||
|
||||
pub(crate) async fn restore_inherited_goal_runtime(&self, thread_id: ThreadId) {
|
||||
if let Err(err) = self
|
||||
.goal_service
|
||||
.restore_thread_runtime_after_resume(thread_id)
|
||||
.await
|
||||
{
|
||||
warn!("failed to restore inherited goal runtime for {thread_id}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn flush_goal_progress_for_fork(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<(), String> {
|
||||
self.goal_service
|
||||
.flush_thread_goal_progress_for_fork(thread_id)
|
||||
.await
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
|
||||
async fn thread_goal_set_inner(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ThreadGoalSetParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if !self.config.features.enabled(Feature::Goals) {
|
||||
return Err(invalid_request("goals feature is disabled"));
|
||||
}
|
||||
|
||||
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
|
||||
let _goal_resume_guard = self.thread_state_manager.lock_goal_resume(thread_id).await;
|
||||
let state_db = self
|
||||
.state_db_for_materialized_thread(thread_id, GoalAccess::Mutate)
|
||||
.await?;
|
||||
self.reconcile_thread_goal_rollout(thread_id, &state_db)
|
||||
.await?;
|
||||
// Active goals can immediately inject an objective or start an idle turn.
|
||||
// Stopping a goal must remain possible after managed policy changes.
|
||||
let existing_goal = self
|
||||
.goal_service
|
||||
.get_thread_goal(&state_db, thread_id)
|
||||
.await
|
||||
.map_err(goal_service_error)?;
|
||||
let resulting_status = params
|
||||
.status
|
||||
.map(ThreadGoalStatus::to_core)
|
||||
.or_else(|| existing_goal.as_ref().map(|goal| goal.status))
|
||||
.unwrap_or(akode_protocol::protocol::ThreadGoalStatus::Active);
|
||||
if resulting_status == akode_protocol::protocol::ThreadGoalStatus::Active
|
||||
&& let Ok(thread) = self.thread_manager.get_thread(thread_id).await
|
||||
{
|
||||
self.config_manager
|
||||
.check_thread_model_provider(thread.config().await.as_ref())
|
||||
.await
|
||||
.map_err(|error| config_load_error(&error))?;
|
||||
}
|
||||
let max_goal_token_budget = match self.thread_manager.get_thread(thread_id).await {
|
||||
Ok(thread) => thread.config().await.max_goal_token_budget,
|
||||
Err(_) => self.config.max_goal_token_budget,
|
||||
};
|
||||
|
||||
let listener_command_tx = {
|
||||
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
|
||||
let thread_state = thread_state.lock().await;
|
||||
thread_state.listener_command_tx()
|
||||
};
|
||||
let status = params.status.map(ThreadGoalStatus::to_core);
|
||||
let objective = params.objective.as_deref().map(str::trim);
|
||||
|
||||
let outcome = self
|
||||
.goal_service
|
||||
.set_thread_goal(
|
||||
&state_db,
|
||||
GoalSetRequest {
|
||||
thread_id,
|
||||
objective: objective
|
||||
.map(GoalObjectiveUpdate::Set)
|
||||
.unwrap_or(GoalObjectiveUpdate::Keep),
|
||||
status,
|
||||
token_budget: match params.token_budget {
|
||||
Some(token_budget) => GoalTokenBudgetUpdate::Set(token_budget),
|
||||
None => GoalTokenBudgetUpdate::Keep,
|
||||
},
|
||||
max_goal_token_budget,
|
||||
},
|
||||
Box::pin(async {
|
||||
if params.origin == Some(ThreadGoalMutationOrigin::User)
|
||||
&& (objective.is_some() || status.is_some())
|
||||
{
|
||||
self.record_user_goal_update(
|
||||
thread_id,
|
||||
UserGoalUpdate::Set {
|
||||
objective: objective.map(str::to_owned),
|
||||
status,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map_err(goal_service_error)?;
|
||||
let goal = ThreadGoal::from(outcome.goal.clone());
|
||||
|
||||
let persist_result = match self.thread_manager.get_thread(thread_id).await {
|
||||
Ok(thread) => {
|
||||
let needs_settings_checkpoint = match thread.rollout_path() {
|
||||
Some(path) => akode_rollout::existing_rollout_path(&path).await.is_none(),
|
||||
None => false,
|
||||
};
|
||||
match thread
|
||||
.append_rollout_items(&[outcome.thread_goal_updated_item()])
|
||||
.await
|
||||
{
|
||||
// Automatic and legacy callers still need goal-first settings persisted,
|
||||
// even though they do not record a user instruction.
|
||||
Ok(()) if needs_settings_checkpoint => {
|
||||
thread.checkpoint_thread_settings().await
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
Err(_) => Ok(()),
|
||||
};
|
||||
if let Err(err) = persist_result {
|
||||
warn!("failed to persist goal update for live thread {thread_id}: {err}");
|
||||
}
|
||||
|
||||
self.outgoing
|
||||
.send_response(
|
||||
request_id.clone(),
|
||||
ThreadGoalSetResponse { goal: goal.clone() },
|
||||
)
|
||||
.await;
|
||||
self.emit_thread_goal_updated_ordered(thread_id, goal, listener_command_tx)
|
||||
.await;
|
||||
outcome.apply_runtime_effects(&self.goal_service).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn thread_goal_get_inner(
|
||||
&self,
|
||||
params: ThreadGoalGetParams,
|
||||
) -> Result<ThreadGoalGetResponse, JSONRPCErrorError> {
|
||||
if !self.config.features.enabled(Feature::Goals) {
|
||||
return Err(invalid_request("goals feature is disabled"));
|
||||
}
|
||||
|
||||
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
|
||||
let state_db = self
|
||||
.state_db_for_materialized_thread(thread_id, GoalAccess::Read)
|
||||
.await?;
|
||||
let goal = self
|
||||
.goal_service
|
||||
.get_thread_goal(&state_db, thread_id)
|
||||
.await
|
||||
.map_err(goal_service_error)?
|
||||
.map(ThreadGoal::from);
|
||||
Ok(ThreadGoalGetResponse { goal })
|
||||
}
|
||||
|
||||
async fn thread_goal_clear_inner(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ThreadGoalClearParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if !self.config.features.enabled(Feature::Goals) {
|
||||
return Err(invalid_request("goals feature is disabled"));
|
||||
}
|
||||
|
||||
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
|
||||
let _goal_resume_guard = self.thread_state_manager.lock_goal_resume(thread_id).await;
|
||||
let state_db = self
|
||||
.state_db_for_materialized_thread(thread_id, GoalAccess::Mutate)
|
||||
.await?;
|
||||
self.reconcile_thread_goal_rollout(thread_id, &state_db)
|
||||
.await?;
|
||||
|
||||
let listener_command_tx = {
|
||||
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
|
||||
let thread_state = thread_state.lock().await;
|
||||
thread_state.listener_command_tx()
|
||||
};
|
||||
let cleared = self
|
||||
.goal_service
|
||||
.clear_thread_goal(
|
||||
&state_db,
|
||||
thread_id,
|
||||
Box::pin(async {
|
||||
if params.origin == Some(ThreadGoalMutationOrigin::User) {
|
||||
self.record_user_goal_update(thread_id, UserGoalUpdate::Clear)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map_err(goal_service_error)?;
|
||||
|
||||
self.outgoing
|
||||
.send_response(request_id, ThreadGoalClearResponse { cleared })
|
||||
.await;
|
||||
if cleared {
|
||||
self.emit_thread_goal_cleared_ordered(thread_id, listener_command_tx)
|
||||
.await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn state_db_for_materialized_thread(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
access: GoalAccess,
|
||||
) -> Result<StateDbHandle, JSONRPCErrorError> {
|
||||
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
|
||||
if matches!(access, GoalAccess::Mutate) {
|
||||
ensure_direct_input_allowed(thread.as_ref()).await?;
|
||||
}
|
||||
if thread.rollout_path().is_none() {
|
||||
return Err(invalid_request(format!(
|
||||
"ephemeral thread does not support goals: {thread_id}"
|
||||
)));
|
||||
}
|
||||
if let Some(state_db) = thread.state_db() {
|
||||
return Ok(state_db);
|
||||
}
|
||||
} else {
|
||||
let rollout_path = akode_rollout::find_thread_path_by_id_str(
|
||||
&self.config.codex_home,
|
||||
&thread_id.to_string(),
|
||||
self.state_db.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to locate thread id {thread_id}: {err}"))
|
||||
})?
|
||||
.ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
if matches!(access, GoalAccess::Mutate) {
|
||||
let session_meta = akode_rollout::read_session_meta_line(&rollout_path)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to read thread ownership: {err}"))
|
||||
})?;
|
||||
if session_meta.meta.id != thread_id {
|
||||
return Err(invalid_request(
|
||||
"thread metadata does not match requested id",
|
||||
));
|
||||
}
|
||||
if matches!(
|
||||
session_meta.meta.source,
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
|
||||
) {
|
||||
// Match resume's latest version metadata, including legacy TurnContext
|
||||
// fallback, rather than trusting only the initial session header.
|
||||
let history = RolloutRecorder::get_rollout_history(&rollout_path)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to read thread ownership: {err}"))
|
||||
})?;
|
||||
if !can_accept_direct_input(
|
||||
history.get_multi_agent_version(),
|
||||
&session_meta.meta.source,
|
||||
) {
|
||||
return Err(invalid_request(
|
||||
DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.state_db
|
||||
.clone()
|
||||
.ok_or_else(|| internal_error("sqlite state db unavailable for thread goals"))
|
||||
}
|
||||
|
||||
async fn reconcile_thread_goal_rollout(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
state_db: &StateDbHandle,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let running_thread = self.thread_manager.get_thread(thread_id).await.ok();
|
||||
let rollout_path = match running_thread.as_ref() {
|
||||
Some(thread) => thread.rollout_path().ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"ephemeral thread does not support goals: {thread_id}"
|
||||
))
|
||||
})?,
|
||||
None => akode_rollout::find_thread_path_by_id_str(
|
||||
&self.config.codex_home,
|
||||
&thread_id.to_string(),
|
||||
self.state_db.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to locate thread id {thread_id}: {err}"))
|
||||
})?
|
||||
.ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?,
|
||||
};
|
||||
|
||||
if let Ok(Some(metadata)) = state_db.get_thread(thread_id).await
|
||||
&& akode_rollout::plain_rollout_path(metadata.rollout_path.as_path())
|
||||
== akode_rollout::plain_rollout_path(rollout_path.as_path())
|
||||
&& let Some(existing_path) =
|
||||
akode_rollout::existing_rollout_path(metadata.rollout_path.as_path()).await
|
||||
&& akode_rollout::read_session_meta_line(existing_path.as_path())
|
||||
.await
|
||||
.is_ok_and(|session_meta| session_meta.meta.id == thread_id)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
reconcile_rollout(
|
||||
Some(state_db),
|
||||
rollout_path.as_path(),
|
||||
self.config.model_provider_id.as_str(),
|
||||
/*builder*/ None,
|
||||
&[],
|
||||
/*archived_only*/ None,
|
||||
/*new_thread_memory_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn emit_thread_goal_snapshot(&self, thread_id: ThreadId) {
|
||||
let state_db = match self
|
||||
.state_db_for_materialized_thread(thread_id, GoalAccess::Read)
|
||||
.await
|
||||
{
|
||||
Ok(state_db) => state_db,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to open state db before emitting thread goal resume snapshot for {thread_id}: {}",
|
||||
err.message
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let listener_command_tx = {
|
||||
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
|
||||
let thread_state = thread_state.lock().await;
|
||||
thread_state.listener_command_tx()
|
||||
};
|
||||
if let Some(listener_command_tx) = listener_command_tx {
|
||||
let command = crate::thread_state::ThreadListenerCommand::EmitThreadGoalSnapshot {
|
||||
state_db: state_db.clone(),
|
||||
};
|
||||
if listener_command_tx.send(command).is_ok() {
|
||||
return;
|
||||
}
|
||||
warn!(
|
||||
"failed to enqueue thread goal snapshot for {thread_id}: listener command channel is closed"
|
||||
);
|
||||
}
|
||||
send_thread_goal_snapshot_notification(&self.outgoing, thread_id, &state_db).await;
|
||||
}
|
||||
|
||||
async fn emit_thread_goal_updated_ordered(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
goal: ThreadGoal,
|
||||
listener_command_tx: Option<tokio::sync::mpsc::UnboundedSender<ThreadListenerCommand>>,
|
||||
) {
|
||||
if let Some(listener_command_tx) = listener_command_tx {
|
||||
let command = crate::thread_state::ThreadListenerCommand::EmitThreadGoalUpdated {
|
||||
turn_id: None,
|
||||
goal: goal.clone(),
|
||||
};
|
||||
if listener_command_tx.send(command).is_ok() {
|
||||
return;
|
||||
}
|
||||
warn!(
|
||||
"failed to enqueue thread goal update for {thread_id}: listener command channel is closed"
|
||||
);
|
||||
}
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ThreadGoalUpdated(
|
||||
ThreadGoalUpdatedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: None,
|
||||
goal,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn emit_thread_goal_cleared_ordered(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
listener_command_tx: Option<tokio::sync::mpsc::UnboundedSender<ThreadListenerCommand>>,
|
||||
) {
|
||||
if let Some(listener_command_tx) = listener_command_tx {
|
||||
let command = crate::thread_state::ThreadListenerCommand::EmitThreadGoalCleared;
|
||||
if listener_command_tx.send(command).is_ok() {
|
||||
return;
|
||||
}
|
||||
warn!(
|
||||
"failed to enqueue thread goal clear for {thread_id}: listener command channel is closed"
|
||||
);
|
||||
}
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ThreadGoalCleared(
|
||||
ThreadGoalClearedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn api_thread_goal_from_state(goal: akode_state::ThreadGoal) -> ThreadGoal {
|
||||
ThreadGoal {
|
||||
thread_id: goal.thread_id.to_string(),
|
||||
objective: goal.objective,
|
||||
status: api_thread_goal_status_from_state(goal.status),
|
||||
token_budget: goal.token_budget,
|
||||
tokens_used: goal.tokens_used,
|
||||
time_used_seconds: goal.time_used_seconds,
|
||||
created_at: goal.created_at.timestamp(),
|
||||
updated_at: goal.updated_at.timestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
fn api_thread_goal_status_from_state(status: akode_state::ThreadGoalStatus) -> ThreadGoalStatus {
|
||||
match status {
|
||||
akode_state::ThreadGoalStatus::Active => ThreadGoalStatus::Active,
|
||||
akode_state::ThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
|
||||
akode_state::ThreadGoalStatus::Blocked => ThreadGoalStatus::Blocked,
|
||||
akode_state::ThreadGoalStatus::UsageLimited => ThreadGoalStatus::UsageLimited,
|
||||
akode_state::ThreadGoalStatus::BudgetLimited => ThreadGoalStatus::BudgetLimited,
|
||||
akode_state::ThreadGoalStatus::Complete => ThreadGoalStatus::Complete,
|
||||
}
|
||||
}
|
||||
|
||||
fn goal_service_error(err: GoalServiceError) -> JSONRPCErrorError {
|
||||
match err {
|
||||
GoalServiceError::InvalidRequest(message) => invalid_request(message),
|
||||
GoalServiceError::Internal(message) => internal_error(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_thread_id_for_request(thread_id: &str) -> Result<ThreadId, JSONRPCErrorError> {
|
||||
ThreadId::from_string(thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Persists explicit user goal mutations with user provenance before goal work resumes.
|
||||
//! Unloaded threads receive the same item on replay; tool-created goals never use this path.
|
||||
|
||||
use super::*;
|
||||
use akode_core::context::ContextualUserFragment;
|
||||
use akode_core::context::UserGoalUpdate;
|
||||
use akode_rollout::RolloutRecorderParams;
|
||||
|
||||
impl ThreadGoalRequestProcessor {
|
||||
pub(super) async fn record_user_goal_update(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
update: UserGoalUpdate,
|
||||
) -> Result<(), GoalServiceError> {
|
||||
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
|
||||
return thread.record_user_goal_update(update).await.map_err(|err| {
|
||||
GoalServiceError::Internal(format!("failed to record goal instruction: {err}"))
|
||||
});
|
||||
}
|
||||
let item = ContextualUserFragment::into(update);
|
||||
let record_error =
|
||||
|err| GoalServiceError::Internal(format!("failed to record goal instruction: {err}"));
|
||||
let writer_lock = Arc::new(self.writer_locks.acquire(thread_id).map_err(record_error)?);
|
||||
let path = akode_rollout::find_thread_path_by_id_str(
|
||||
&self.config.codex_home,
|
||||
&thread_id.to_string(),
|
||||
self.state_db.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
GoalServiceError::Internal(format!("failed to locate thread id {thread_id}: {err}"))
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
GoalServiceError::InvalidRequest(format!("thread not found: {thread_id}"))
|
||||
})?;
|
||||
// The writer owns the lock through background IO, even if this RPC is cancelled.
|
||||
let recorder = RolloutRecorder::new_with_writer_lock(
|
||||
self.config.as_ref(),
|
||||
RolloutRecorderParams::resume(path),
|
||||
writer_lock,
|
||||
)
|
||||
.await
|
||||
.map_err(record_error)?;
|
||||
recorder
|
||||
.record_canonical_items(&[RolloutItem::ResponseItem(item.into())])
|
||||
.await
|
||||
.map_err(record_error)?;
|
||||
// Shutdown flushes queued items before acknowledging the goal mutation.
|
||||
recorder.shutdown().await.map_err(record_error)
|
||||
}
|
||||
}
|
||||
37
akode-rs/app-server/src/request_processors/thread_input.rs
Normal file
37
akode-rs/app-server/src/request_processors/thread_input.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use super::invalid_request;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_core::CodexThread;
|
||||
use akode_protocol::protocol::MultiAgentVersion;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
|
||||
pub(super) const DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR: &str =
|
||||
"direct app-server input is not allowed for multi-agent v2 sub-agents";
|
||||
|
||||
/// Mirrors the ownership policy in request validation and thread capability responses.
|
||||
pub(super) fn can_accept_direct_input(
|
||||
multi_agent_version: Option<MultiAgentVersion>,
|
||||
session_source: &SessionSource,
|
||||
) -> bool {
|
||||
multi_agent_version != Some(MultiAgentVersion::V2)
|
||||
|| !matches!(
|
||||
session_source,
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn ensure_direct_input_allowed(
|
||||
thread: &CodexThread,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let config_snapshot = thread.config_snapshot().await;
|
||||
if !can_accept_direct_input(
|
||||
thread.multi_agent_version(),
|
||||
&config_snapshot.session_source,
|
||||
) {
|
||||
return Err(invalid_request(
|
||||
DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
1442
akode-rs/app-server/src/request_processors/thread_lifecycle.rs
Normal file
1442
akode-rs/app-server/src/request_processors/thread_lifecycle.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,259 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Checks runtime release and notification delivery around listener shutdown.
|
||||
|
||||
use super::super::thread_goal_processor::ThreadGoalRequestProcessor;
|
||||
use super::super::thread_processor::ThreadRequestProcessor;
|
||||
use super::super::thread_processor::ThreadResumeTarget;
|
||||
use super::*;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::outgoing_message::OutgoingEnvelope;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::thread_sample::SampleResponseRegistry;
|
||||
use crate::thread_state::PendingNetworkApproval;
|
||||
use crate::thread_state::resolve_server_request_on_thread_listener;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::ThreadResumeParams;
|
||||
use akode_app_server_protocol::ThreadUnsubscribeParams;
|
||||
use akode_app_server_protocol::ThreadUnsubscribeResponse;
|
||||
use akode_app_server_protocol::ThreadUnsubscribeStatus;
|
||||
use akode_arg0::Arg0DispatchPaths;
|
||||
use akode_goal_extension::GoalService;
|
||||
use akode_login::AuthManager;
|
||||
use akode_thread_store::PersistContext;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[test_case(true; "listener attached before shutdown")]
|
||||
#[test_case(false; "listener attached after shutdown")]
|
||||
#[tokio::test]
|
||||
async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers(
|
||||
attach_before_shutdown: bool,
|
||||
) -> Result<()> {
|
||||
let server = wiremock::MockServer::start().await;
|
||||
let test = test_codex().build_with_auto_env(&server).await?;
|
||||
let thread_id = test.session_configured.thread_id;
|
||||
test.thread_store
|
||||
.persist_thread(thread_id, PersistContext::Standard)
|
||||
.await?;
|
||||
let thread = test.codex;
|
||||
let runtime = Arc::downgrade(&thread);
|
||||
let config = Arc::new(test.config.clone());
|
||||
let auth =
|
||||
AuthManager::shared_from_config(config.as_ref(), /*enable_codex_api_key_env*/ false)
|
||||
.await?;
|
||||
let config_manager =
|
||||
ConfigManager::without_managed_config_for_tests(config.codex_home.to_path_buf());
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 16);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx));
|
||||
let thread_state_manager = ThreadStateManager::new();
|
||||
let thread_watch_manager = ThreadWatchManager::new_with_outgoing(outgoing.clone());
|
||||
let skills_watcher = SkillsWatcher::new(
|
||||
test.thread_manager.skills_service(),
|
||||
&config.codex_home,
|
||||
outgoing.clone(),
|
||||
);
|
||||
let thread_goal_processor = ThreadGoalRequestProcessor::new(
|
||||
test.thread_manager.clone(),
|
||||
outgoing.clone(),
|
||||
config.clone(),
|
||||
thread_state_manager.clone(),
|
||||
/*state_db*/ None,
|
||||
Arc::new(GoalService::new()),
|
||||
config_manager.clone(),
|
||||
);
|
||||
let processor = ThreadRequestProcessor::new(
|
||||
auth,
|
||||
test.thread_manager.clone(),
|
||||
outgoing,
|
||||
Arg0DispatchPaths::default(),
|
||||
config,
|
||||
config_manager,
|
||||
test.thread_store.clone(),
|
||||
Default::default(),
|
||||
thread_state_manager.clone(),
|
||||
thread_watch_manager.clone(),
|
||||
Arc::new(Semaphore::new(/*permits*/ 1)),
|
||||
thread_goal_processor,
|
||||
/*state_db*/ None,
|
||||
/*log_db*/ None,
|
||||
skills_watcher.clone(),
|
||||
Vec::new(),
|
||||
Arc::new(SampleResponseRegistry::default()),
|
||||
);
|
||||
let connection_id = ConnectionId(1);
|
||||
let disconnecting_connection_id = ConnectionId(2);
|
||||
let remaining_connection_id = ConnectionId(3);
|
||||
let connection_ids = vec![
|
||||
connection_id,
|
||||
disconnecting_connection_id,
|
||||
remaining_connection_id,
|
||||
];
|
||||
for &connection_id in &connection_ids {
|
||||
processor
|
||||
.connection_initialized(connection_id)
|
||||
.await;
|
||||
}
|
||||
let network_request_id = RequestId::Integer(4);
|
||||
if attach_before_shutdown {
|
||||
processor
|
||||
.try_attach_thread_listener(thread_id, Arc::clone(&thread), connection_ids.clone())
|
||||
.await;
|
||||
// Leave the prompt outstanding so shutdown runs before the proxy waiter resolves it.
|
||||
let permission_guard = thread_watch_manager
|
||||
.note_permission_requested(&thread_id.to_string())
|
||||
.await;
|
||||
thread_state_manager
|
||||
.thread_state(thread_id)
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.network_approvals
|
||||
.insert(
|
||||
"network-approval".to_string(),
|
||||
PendingNetworkApproval {
|
||||
request_id: network_request_id.clone(),
|
||||
permission_guard,
|
||||
},
|
||||
);
|
||||
}
|
||||
thread.shutdown_and_wait().await?;
|
||||
let shutdown_result = tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
|
||||
let resume = processor
|
||||
.thread_resume(
|
||||
ThreadResumeTarget::Client(ConnectionRequestId {
|
||||
connection_id,
|
||||
request_id: RequestId::Integer(1),
|
||||
}),
|
||||
ThreadResumeParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
exclude_turns: true,
|
||||
..Default::default()
|
||||
},
|
||||
/*app_server_client_name*/ None,
|
||||
/*app_server_client_version*/ None,
|
||||
/*client_mcp_extensions*/ Default::default(),
|
||||
)
|
||||
.await;
|
||||
test.thread_manager.remove_thread(&thread_id).await;
|
||||
if !attach_before_shutdown {
|
||||
processor
|
||||
.try_attach_thread_listener(thread_id, Arc::clone(&thread), connection_ids)
|
||||
.await;
|
||||
}
|
||||
let mut network_resolved = false;
|
||||
loop {
|
||||
match outgoing_rx.recv().await.expect("outgoing channel closed") {
|
||||
OutgoingEnvelope::ToConnection {
|
||||
connection_id: recipient,
|
||||
message: OutgoingMessage::AppServerNotification(notification),
|
||||
..
|
||||
} if recipient == connection_id
|
||||
&& matches!(
|
||||
¬ification.notification,
|
||||
ServerNotification::ServerRequestResolved(resolved)
|
||||
if resolved.request_id == network_request_id
|
||||
) =>
|
||||
{
|
||||
assert!(!network_resolved, "duplicate network prompt resolution");
|
||||
network_resolved = true;
|
||||
}
|
||||
OutgoingEnvelope::Broadcast {
|
||||
message: OutgoingMessage::AppServerNotification(notification),
|
||||
} if matches!(
|
||||
¬ification.notification,
|
||||
ServerNotification::ThreadStatusChanged(status)
|
||||
if status.status == ThreadStatus::NotLoaded
|
||||
) =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(network_resolved, attach_before_shutdown);
|
||||
drop(thread);
|
||||
while runtime.upgrade().is_some() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let Some(ClientResponsePayload::ThreadUnsubscribe(unsubscribe)) = processor
|
||||
.thread_unsubscribe(
|
||||
&ConnectionRequestId {
|
||||
connection_id,
|
||||
request_id: RequestId::Integer(2),
|
||||
},
|
||||
ThreadUnsubscribeParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("unsubscribe failed")
|
||||
else {
|
||||
panic!("unsubscribe response missing");
|
||||
};
|
||||
assert_eq!(
|
||||
unsubscribe,
|
||||
ThreadUnsubscribeResponse {
|
||||
status: ThreadUnsubscribeStatus::NotLoaded,
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
thread_state_manager
|
||||
.subscribed_connection_ids(thread_id)
|
||||
.await
|
||||
.into_iter()
|
||||
.collect::<HashSet<_>>(),
|
||||
HashSet::from([disconnecting_connection_id, remaining_connection_id]),
|
||||
);
|
||||
processor
|
||||
.connection_closed(disconnecting_connection_id)
|
||||
.await;
|
||||
assert_eq!(
|
||||
thread_state_manager
|
||||
.subscribed_connection_ids(thread_id)
|
||||
.await,
|
||||
vec![remaining_connection_id],
|
||||
);
|
||||
resolve_server_request_on_thread_listener(
|
||||
&thread_state_manager.thread_state(thread_id).await,
|
||||
RequestId::Integer(3),
|
||||
)
|
||||
.await;
|
||||
loop {
|
||||
if let OutgoingEnvelope::ToConnection {
|
||||
connection_id: recipient,
|
||||
message: OutgoingMessage::AppServerNotification(notification),
|
||||
..
|
||||
} = outgoing_rx.recv().await.expect("outgoing channel closed")
|
||||
&& recipient == remaining_connection_id
|
||||
&& matches!(
|
||||
¬ification.notification,
|
||||
ServerNotification::ServerRequestResolved(resolved)
|
||||
if resolved.request_id == RequestId::Integer(3)
|
||||
)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
resume
|
||||
})
|
||||
.await;
|
||||
thread_state_manager.clear_all_listeners().await;
|
||||
skills_watcher.shutdown();
|
||||
|
||||
let resume = shutdown_result.context("terminal listener did not release or relay")?;
|
||||
assert_eq!(
|
||||
resume.expect_err("resume accepted a terminated runtime"),
|
||||
invalid_request(format!(
|
||||
"thread {thread_id} is closing; retry thread/resume after the thread is closed"
|
||||
)),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
30
akode-rs/app-server/src/request_processors/thread_memory.rs
Normal file
30
akode-rs/app-server/src/request_processors/thread_memory.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
//! Reads memory context from the loaded thread's resolved version, without fallback.
|
||||
|
||||
use super::*;
|
||||
use akode_app_server_protocol::ThreadMemoryReadParams;
|
||||
use akode_app_server_protocol::ThreadMemoryReadResponse;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn thread_memory_read(
|
||||
&self,
|
||||
params: ThreadMemoryReadParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let (_, thread) = self.load_thread(¶ms.thread_id).await?;
|
||||
let config = thread.config().await;
|
||||
let summary =
|
||||
if config.features.enabled(Feature::MemoryTool) && config.memories.use_memories {
|
||||
tokio::fs::read_to_string(
|
||||
config
|
||||
.codex_home
|
||||
.join(config.memories.version.directory_name())
|
||||
.join("memory_summary.md"),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.filter(|summary| !summary.trim().is_empty())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Some(ThreadMemoryReadResponse { summary }.into()))
|
||||
}
|
||||
}
|
||||
6930
akode-rs/app-server/src/request_processors/thread_processor.rs
Normal file
6930
akode-rs/app-server/src/request_processors/thread_processor.rs
Normal file
File diff suppressed because it is too large
Load Diff
1344
akode-rs/app-server/src/request_processors/thread_processor_tests.rs
Normal file
1344
akode-rs/app-server/src/request_processors/thread_processor_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,355 @@
|
||||
use crate::config_manager::ConfigManager;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::QueuedSubmission;
|
||||
use akode_app_server_protocol::ThreadQueueAddParams;
|
||||
use akode_app_server_protocol::ThreadQueueAddResponse;
|
||||
use akode_app_server_protocol::ThreadQueueDeleteParams;
|
||||
use akode_app_server_protocol::ThreadQueueDeleteResponse;
|
||||
use akode_app_server_protocol::ThreadQueueListParams;
|
||||
use akode_app_server_protocol::ThreadQueueListResponse;
|
||||
use akode_app_server_protocol::ThreadQueueReorderParams;
|
||||
use akode_app_server_protocol::ThreadQueueReorderResponse;
|
||||
use akode_app_server_protocol::ThreadQueueStartParams;
|
||||
use akode_app_server_protocol::ThreadQueueStartResponse;
|
||||
use akode_app_server_protocol::ThreadQueueUpdateParams;
|
||||
use akode_app_server_protocol::ThreadQueueUpdateResponse;
|
||||
use akode_app_server_protocol::Turn;
|
||||
use akode_app_server_protocol::TurnItemsView;
|
||||
use akode_app_server_protocol::TurnStatus;
|
||||
use akode_app_server_protocol::UserInput;
|
||||
use akode_core::CodexThread;
|
||||
use akode_core::NotSubmittedReason;
|
||||
use akode_core::StartIfIdleSubmission;
|
||||
use akode_core::ThreadManager;
|
||||
use akode_core::TurnInput;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_queue_extension::QueueServiceError;
|
||||
use akode_queue_extension::QueuedItem;
|
||||
use akode_queue_extension::QueuedItemService;
|
||||
use akode_thread_store::ReadThreadParams;
|
||||
use akode_thread_store::ThreadStore;
|
||||
use akode_thread_store::ThreadStoreError;
|
||||
|
||||
use super::TurnRequestProcessor;
|
||||
use super::config_load_error;
|
||||
use super::thread_input::DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR;
|
||||
use super::thread_input::can_accept_direct_input;
|
||||
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
|
||||
use super::thread_processor::THREAD_LIST_MAX_LIMIT;
|
||||
use super::turn_processor::validate_user_input_image_urls;
|
||||
|
||||
const DIRECT_INPUT_TO_UNLOADED_SUBAGENT_ERROR: &str =
|
||||
"direct app-server input is not allowed for unloaded spawned sub-agents";
|
||||
|
||||
pub(crate) struct ThreadQueueRequestProcessor {
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
service: Option<Arc<QueuedItemService>>,
|
||||
}
|
||||
|
||||
impl ThreadQueueRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
service: Option<Arc<QueuedItemService>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
thread_manager,
|
||||
thread_store,
|
||||
outgoing,
|
||||
config_manager,
|
||||
service,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn add(
|
||||
&self,
|
||||
params: ThreadQueueAddParams,
|
||||
) -> Result<ThreadQueueAddResponse, JSONRPCErrorError> {
|
||||
validate_user_input_image_urls(¶ms.input)?;
|
||||
let (thread_id, loaded_thread, source) = self.require_thread(¶ms.thread_id).await?;
|
||||
ensure_direct_input_allowed(loaded_thread.as_deref(), &source)?;
|
||||
let queued_item = self
|
||||
.service()?
|
||||
.enqueue_with_metadata(
|
||||
thread_id,
|
||||
submission_into_turn_input(params.input, Some(params.client_user_message_id)),
|
||||
params.responsesapi_client_metadata,
|
||||
)
|
||||
.await
|
||||
.map_err(queue_error)?;
|
||||
Ok(ThreadQueueAddResponse {
|
||||
queued_submission: api_queued_submission(queued_item)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn list(
|
||||
&self,
|
||||
params: ThreadQueueListParams,
|
||||
) -> Result<ThreadQueueListResponse, JSONRPCErrorError> {
|
||||
let (thread_id, _, _) = self.require_thread(¶ms.thread_id).await?;
|
||||
let offset = params
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(str::parse::<usize>)
|
||||
.transpose()
|
||||
.map_err(|error| invalid_request(format!("invalid queue pagination cursor: {error}")))?
|
||||
.unwrap_or_default();
|
||||
let limit = params
|
||||
.limit
|
||||
.map(|value| value as usize)
|
||||
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
|
||||
.clamp(1, THREAD_LIST_MAX_LIMIT);
|
||||
let mut items = self
|
||||
.service()?
|
||||
.list_page(thread_id, offset, limit.saturating_add(1))
|
||||
.await
|
||||
.map_err(queue_error)?;
|
||||
let next_cursor = if items.len() > limit {
|
||||
items.truncate(limit);
|
||||
Some(offset.saturating_add(limit).to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ThreadQueueListResponse {
|
||||
data: items
|
||||
.into_iter()
|
||||
.map(api_queued_submission)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
next_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn update(
|
||||
&self,
|
||||
params: ThreadQueueUpdateParams,
|
||||
) -> Result<ThreadQueueUpdateResponse, JSONRPCErrorError> {
|
||||
validate_user_input_image_urls(¶ms.input)?;
|
||||
let (thread_id, loaded_thread, source) = self.require_thread(¶ms.thread_id).await?;
|
||||
ensure_direct_input_allowed(loaded_thread.as_deref(), &source)?;
|
||||
let queued_item = self
|
||||
.service()?
|
||||
.update_with_metadata(
|
||||
thread_id,
|
||||
params.queued_submission_id.clone(),
|
||||
submission_into_turn_input(params.input, /*client_user_message_id*/ None),
|
||||
params.responsesapi_client_metadata,
|
||||
)
|
||||
.await
|
||||
.map_err(queue_error)?
|
||||
.ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"queued submission not found: {}",
|
||||
params.queued_submission_id
|
||||
))
|
||||
})?;
|
||||
Ok(ThreadQueueUpdateResponse {
|
||||
queued_submission: api_queued_submission(queued_item)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn delete(
|
||||
&self,
|
||||
params: ThreadQueueDeleteParams,
|
||||
) -> Result<ThreadQueueDeleteResponse, JSONRPCErrorError> {
|
||||
let (thread_id, _, _) = self.require_thread(¶ms.thread_id).await?;
|
||||
let deleted = self
|
||||
.service()?
|
||||
.delete(thread_id, params.queued_submission_id)
|
||||
.await
|
||||
.map_err(queue_error)?;
|
||||
Ok(ThreadQueueDeleteResponse { deleted })
|
||||
}
|
||||
|
||||
pub(crate) async fn reorder(
|
||||
&self,
|
||||
params: ThreadQueueReorderParams,
|
||||
) -> Result<ThreadQueueReorderResponse, JSONRPCErrorError> {
|
||||
let (thread_id, _, _) = self.require_thread(¶ms.thread_id).await?;
|
||||
self.service()?
|
||||
.reorder(thread_id, params.queued_submission_ids)
|
||||
.await
|
||||
.map_err(queue_error)?;
|
||||
Ok(ThreadQueueReorderResponse {})
|
||||
}
|
||||
|
||||
pub(crate) async fn start(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: ThreadQueueStartParams,
|
||||
) -> Result<ThreadQueueStartResponse, JSONRPCErrorError> {
|
||||
let (_, loaded_thread, source) = self.require_thread(¶ms.thread_id).await?;
|
||||
ensure_direct_input_allowed(loaded_thread.as_deref(), &source)?;
|
||||
let thread = loaded_thread
|
||||
.ok_or_else(|| invalid_request("resume the thread before starting a queued message"))?;
|
||||
self.config_manager
|
||||
.check_thread_model_provider(thread.config().await.as_ref())
|
||||
.await
|
||||
.map_err(|error| config_load_error(&error))?;
|
||||
let submission = self
|
||||
.service()?
|
||||
.start(
|
||||
thread.as_ref(),
|
||||
params.queued_submission_id,
|
||||
self.outgoing.request_trace_context(request_id).await,
|
||||
)
|
||||
.await
|
||||
.map_err(queue_error)?;
|
||||
let (turn_id, root_turn_id) = match submission {
|
||||
StartIfIdleSubmission::Started {
|
||||
turn_id,
|
||||
root_turn_id,
|
||||
} => (turn_id, root_turn_id),
|
||||
StartIfIdleSubmission::NotSubmitted {
|
||||
reason: NotSubmittedReason::ServerDraining,
|
||||
} => return Err(crate::error_code::server_draining_error()),
|
||||
StartIfIdleSubmission::NotSubmitted {
|
||||
reason: NotSubmittedReason::NotIdle | NotSubmittedReason::PendingTriggerTurn,
|
||||
} => {
|
||||
return Err(invalid_request(
|
||||
"thread already has an active or pending turn",
|
||||
));
|
||||
}
|
||||
StartIfIdleSubmission::NotSubmitted { reason } => {
|
||||
return Err(internal_error(format!(
|
||||
"Core declined to start queued user message: {reason:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
self.outgoing
|
||||
.record_request_turn_id(request_id, &turn_id)
|
||||
.await;
|
||||
Ok(ThreadQueueStartResponse {
|
||||
turn: Turn {
|
||||
id: turn_id,
|
||||
root_turn_id: Some(root_turn_id),
|
||||
items: vec![],
|
||||
items_view: TurnItemsView::NotLoaded,
|
||||
error: None,
|
||||
status: TurnStatus::InProgress,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn service(&self) -> Result<&QueuedItemService, JSONRPCErrorError> {
|
||||
self.service
|
||||
.as_deref()
|
||||
.ok_or_else(|| invalid_request("user message queue is unavailable"))
|
||||
}
|
||||
|
||||
async fn require_thread(
|
||||
&self,
|
||||
raw_thread_id: &str,
|
||||
) -> Result<(ThreadId, Option<Arc<CodexThread>>, SessionSource), JSONRPCErrorError> {
|
||||
let thread_id = ThreadId::from_string(raw_thread_id)
|
||||
.map_err(|error| invalid_request(format!("invalid thread id: {error}")))?;
|
||||
let (loaded_thread, source) = if let Ok(thread) =
|
||||
self.thread_manager.get_thread(thread_id).await
|
||||
{
|
||||
let snapshot = thread.config_snapshot().await;
|
||||
if snapshot.ephemeral {
|
||||
return Err(invalid_request(format!(
|
||||
"ephemeral thread does not support queued submissions: {thread_id}"
|
||||
)));
|
||||
}
|
||||
(Some(thread), snapshot.session_source)
|
||||
} else {
|
||||
let stored = self
|
||||
.thread_store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
ThreadStoreError::ThreadNotFound { .. } => {
|
||||
invalid_request(format!("thread not found: {thread_id}"))
|
||||
}
|
||||
error => internal_error(format!("failed to read thread: {error}")),
|
||||
})?;
|
||||
if stored.archived_at.is_some() {
|
||||
return Err(invalid_request(format!(
|
||||
"session {thread_id} is archived. Run `akode unarchive {thread_id}` to unarchive it first."
|
||||
)));
|
||||
}
|
||||
(None, stored.source)
|
||||
};
|
||||
|
||||
Ok((thread_id, loaded_thread, source))
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_direct_input_allowed(
|
||||
loaded_thread: Option<&CodexThread>,
|
||||
source: &SessionSource,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
match loaded_thread {
|
||||
Some(thread) if !can_accept_direct_input(thread.multi_agent_version(), source) => Err(
|
||||
invalid_request(DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR),
|
||||
),
|
||||
None if matches!(
|
||||
source,
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
|
||||
) =>
|
||||
{
|
||||
Err(invalid_request(DIRECT_INPUT_TO_UNLOADED_SUBAGENT_ERROR))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn submission_into_turn_input(
|
||||
input: Vec<UserInput>,
|
||||
client_user_message_id: Option<String>,
|
||||
) -> TurnInput {
|
||||
TurnInput::UserInput {
|
||||
content: input.into_iter().map(UserInput::into_core).collect(),
|
||||
client_id: client_user_message_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn queue_error(error: QueueServiceError) -> JSONRPCErrorError {
|
||||
match error {
|
||||
QueueServiceError::InputTooLarge { actual_chars } => {
|
||||
TurnRequestProcessor::input_too_large_error(actual_chars)
|
||||
}
|
||||
error @ (QueueServiceError::InvalidInput | QueueServiceError::InvalidAttachment(_)) => {
|
||||
invalid_request(error.to_string())
|
||||
}
|
||||
QueueServiceError::Storage(ThreadStoreError::InvalidRequest { message }) => {
|
||||
invalid_request(message)
|
||||
}
|
||||
error => internal_error(format!("queued submission operation failed: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn api_queued_submission(value: QueuedItem) -> Result<QueuedSubmission, JSONRPCErrorError> {
|
||||
let TurnInput::UserInput { content, client_id } = value.input else {
|
||||
return Err(internal_error(
|
||||
"queued submission does not contain user input",
|
||||
));
|
||||
};
|
||||
Ok(QueuedSubmission {
|
||||
id: value.id,
|
||||
responsesapi_client_metadata: value.responsesapi_client_metadata,
|
||||
input: content.into_iter().map(Into::into).collect(),
|
||||
client_user_message_id: client_id
|
||||
.ok_or_else(|| internal_error("queued submission is missing its client message id"))?,
|
||||
})
|
||||
}
|
||||
205
akode-rs/app-server/src/request_processors/thread_read_state.rs
Normal file
205
akode-rs/app-server/src/request_processors/thread_read_state.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
//! Read state for durable local threads. Receipt changes use the thread's usual subscribers.
|
||||
|
||||
use super::*;
|
||||
use crate::error_code::method_not_found;
|
||||
use akode_app_server_protocol::ThreadReadState;
|
||||
use akode_app_server_protocol::ThreadReadStateChangedNotification;
|
||||
use akode_app_server_protocol::ThreadReadStateOperation;
|
||||
use akode_app_server_protocol::ThreadReadStateUpdateParams;
|
||||
use akode_app_server_protocol::ThreadReadStateUpdateResponse;
|
||||
use akode_app_server_protocol::ThreadUnreadPosition;
|
||||
use akode_state::ReadStateOperation;
|
||||
use akode_state::ReadStateUpdate;
|
||||
|
||||
// These scopes have product notification policy the local server cannot resolve.
|
||||
// Do not advertise read state for them until their policy reaches this publisher.
|
||||
fn eligible(thread: &Thread) -> bool {
|
||||
!thread.ephemeral
|
||||
&& !matches!(
|
||||
thread.source,
|
||||
akode_app_server_protocol::SessionSource::SubAgent(_)
|
||||
| akode_app_server_protocol::SessionSource::Unknown
|
||||
)
|
||||
&& matches!(
|
||||
thread.thread_source,
|
||||
None | Some(akode_app_server_protocol::ThreadSource::User)
|
||||
)
|
||||
}
|
||||
|
||||
fn to_api(state: akode_state::ThreadReadState) -> ThreadReadState {
|
||||
ThreadReadState {
|
||||
first_unread: state.first_unread_turn.map(|turn_id| {
|
||||
if turn_id.is_empty() {
|
||||
ThreadUnreadPosition::ThreadStart
|
||||
} else {
|
||||
ThreadUnreadPosition::Turn { turn_id }
|
||||
}
|
||||
}),
|
||||
revision: state.revision,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read receipts only for the local store's list/read results, in one bounded batch.
|
||||
pub(super) async fn snapshots(
|
||||
db: Option<&StateDbHandle>,
|
||||
threads: &[Thread],
|
||||
) -> Option<HashMap<String, ThreadReadState>> {
|
||||
let db = db?;
|
||||
let ids = threads
|
||||
.iter()
|
||||
.filter(|t| eligible(t))
|
||||
.filter_map(|t| ThreadId::from_string(&t.id).ok())
|
||||
.collect::<Vec<_>>();
|
||||
match db.thread_read_states(&ids).await {
|
||||
Ok(states) => Some(
|
||||
states
|
||||
.into_iter()
|
||||
.map(|(id, state)| (id.to_string(), to_api(state)))
|
||||
.collect(),
|
||||
),
|
||||
Err(err) => {
|
||||
tracing::warn!("thread read state unavailable: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn notify(
|
||||
db: &StateDbHandle,
|
||||
manager: &ThreadStateManager,
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
id: ThreadId,
|
||||
) {
|
||||
match db.thread_read_states(&[id]).await {
|
||||
Ok(mut states) => {
|
||||
if let Some(state) = states.remove(&id) {
|
||||
let subscribers = manager.subscribed_connection_ids(id).await;
|
||||
ThreadScopedOutgoingMessageSender::new(Arc::clone(outgoing), subscribers, id)
|
||||
.send_server_notification(ServerNotification::ThreadReadStateChanged(
|
||||
ThreadReadStateChangedNotification {
|
||||
thread_id: id.to_string(),
|
||||
read_state: to_api(state),
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(err) => tracing::warn!("could not project committed read state: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs only on newly delivered Core events, never on history decoding or replay.
|
||||
pub(super) async fn publish(
|
||||
event: &akode_protocol::protocol::Event,
|
||||
id: ThreadId,
|
||||
conversation: &Arc<CodexThread>,
|
||||
summary: &crate::thread_state::TurnSummary,
|
||||
) -> Option<StateDbHandle> {
|
||||
let db = conversation.state_db()?;
|
||||
let config = conversation.config_snapshot().await;
|
||||
if config.ephemeral
|
||||
|| matches!(
|
||||
config.session_source,
|
||||
akode_protocol::protocol::SessionSource::SubAgent(_)
|
||||
| akode_protocol::protocol::SessionSource::Internal(_)
|
||||
| akode_protocol::protocol::SessionSource::Unknown
|
||||
)
|
||||
|| !matches!(
|
||||
config.thread_source,
|
||||
None | Some(akode_protocol::protocol::ThreadSource::User)
|
||||
)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let has_error = summary.last_error.is_some();
|
||||
let final_text = match summary
|
||||
.last_agent_message
|
||||
.as_ref()
|
||||
.map(|message| &message.payload)
|
||||
{
|
||||
Some(ThreadItemPayload::AgentMessage { text, .. }) => Some(text.as_str()),
|
||||
_ => None,
|
||||
};
|
||||
let visible = match &event.msg {
|
||||
EventMsg::TurnComplete(_) if has_error => true,
|
||||
EventMsg::TurnComplete(_) => {
|
||||
let text = final_text?;
|
||||
if text.contains("<decision>DONT_NOTIFY</decision>") {
|
||||
return None;
|
||||
}
|
||||
// An unfinished goal will resume automatically; it is not a terminal result.
|
||||
match db.thread_goals().get_thread_goal(id).await {
|
||||
Ok(Some(goal)) if goal.status == akode_state::ThreadGoalStatus::Active => false,
|
||||
Ok(_) => !text.trim().is_empty(),
|
||||
Err(err) => {
|
||||
tracing::warn!("could not resolve terminal attention policy: {err}");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
EventMsg::TurnAborted(aborted) => {
|
||||
aborted.error.is_some() || has_error || final_text.is_some()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if visible {
|
||||
if let Err(err) = conversation.flush_rollout().await {
|
||||
tracing::warn!("cannot publish attention before the terminal result is durable: {err}");
|
||||
return None;
|
||||
}
|
||||
match db.publish_thread_attention(id, &event.id).await {
|
||||
Ok(true) => return Some(db),
|
||||
Ok(false) => {}
|
||||
Err(err) => tracing::warn!("failed to publish terminal attention: {err}"),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn thread_read_state_update(
|
||||
&self,
|
||||
params: ThreadReadStateUpdateParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let id = ThreadId::from_string(¶ms.thread_id)
|
||||
.map_err(|err| invalid_params(format!("invalid thread id: {err}")))?;
|
||||
let db = self
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| method_not_found("durable thread read state unavailable"))?;
|
||||
let thread = self
|
||||
.read_thread_view(id, /*include_turns*/ false)
|
||||
.await
|
||||
.map_err(super::thread_processor::thread_read_view_error)?;
|
||||
if !eligible(&thread) {
|
||||
return Err(invalid_request("thread read state unavailable"));
|
||||
}
|
||||
let operation = match params.operation {
|
||||
ThreadReadStateOperation::Read => ReadStateOperation::Read,
|
||||
ThreadReadStateOperation::Unread => ReadStateOperation::Unread,
|
||||
};
|
||||
let outcome = db
|
||||
.update_thread_read_state(id, ¶ms.expected_revision, operation)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("read state was not saved: {err}")))?;
|
||||
match outcome {
|
||||
ReadStateUpdate::Applied(state) => {
|
||||
notify(db, &self.thread_state_manager, &self.outgoing, id).await;
|
||||
Ok(Some(
|
||||
ThreadReadStateUpdateResponse {
|
||||
read_state: to_api(state),
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
ReadStateUpdate::Conflict(state) => {
|
||||
let mut error = invalid_request("read state changed");
|
||||
error.data = Some(
|
||||
serde_json::json!({ "reason": "readStateConflict", "readState": to_api(state) }),
|
||||
);
|
||||
Err(error)
|
||||
}
|
||||
ReadStateUpdate::Unavailable => Err(invalid_request("thread read state unavailable")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
#[cfg(test)]
|
||||
use akode_app_server_protocol::GeneratedImageRef;
|
||||
use akode_app_server_protocol::McpToolCallResult;
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
use akode_app_server_protocol::Turn;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
// Temporary bandaid for remote clients: thread/resume can include large MCP and
|
||||
// image-generation payloads. Keep this response-only so persisted rollout
|
||||
// history, model resume history, and other APIs stay unchanged.
|
||||
const REDACTED_PAYLOAD: &str = "[redacted]";
|
||||
const CHATGPT_REMOTE_CLIENT_NAMES: &[&str] =
|
||||
&["codex_chatgpt_android_remote", "codex_chatgpt_ios_remote"];
|
||||
|
||||
pub(super) fn should_redact_thread_resume_payloads(client_name: Option<&str>) -> bool {
|
||||
client_name.is_some_and(|client_name| CHATGPT_REMOTE_CLIENT_NAMES.contains(&client_name))
|
||||
}
|
||||
|
||||
pub(super) fn redact_thread_resume_payloads(turns: &mut [Turn]) {
|
||||
for turn in turns {
|
||||
turn.items.retain_mut(|entry| match &mut entry.payload {
|
||||
ThreadItemPayload::McpToolCall {
|
||||
arguments,
|
||||
result,
|
||||
error,
|
||||
..
|
||||
} => {
|
||||
*arguments = JsonValue::String(REDACTED_PAYLOAD.to_string());
|
||||
if result.is_some() {
|
||||
*result = Some(Box::new(redacted_mcp_tool_call_result()));
|
||||
}
|
||||
if let Some(error) = error {
|
||||
error.message = REDACTED_PAYLOAD.to_string();
|
||||
}
|
||||
true
|
||||
}
|
||||
ThreadItemPayload::ImageGeneration(_) => false,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn redacted_mcp_tool_call_result() -> McpToolCallResult {
|
||||
McpToolCallResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "text",
|
||||
"text": REDACTED_PAYLOAD,
|
||||
})],
|
||||
structured_content: None,
|
||||
meta: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_app_server_protocol::ImageGenerationItem;
|
||||
use akode_app_server_protocol::McpToolCallAppContext;
|
||||
use akode_app_server_protocol::McpToolCallError;
|
||||
use akode_app_server_protocol::McpToolCallStatus;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadItem;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_app_server_protocol::TurnItemsView;
|
||||
use akode_app_server_protocol::TurnStatus;
|
||||
use akode_utils_absolute_path::test_support::PathBufExt;
|
||||
use akode_utils_absolute_path::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn redacts_mcp_success_result_and_removes_image_generation() {
|
||||
let mut thread = test_thread(vec![
|
||||
ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "agent-1".to_string(),
|
||||
text: "kept".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
},
|
||||
ThreadItemPayload::McpToolCall {
|
||||
id: "mcp-1".to_string(),
|
||||
server: "docs".to_string(),
|
||||
tool: "lookup".to_string(),
|
||||
status: McpToolCallStatus::Completed,
|
||||
arguments: serde_json::json!({"secret":"argument"}),
|
||||
app_context: Some(McpToolCallAppContext {
|
||||
connector_id: "calendar".to_string(),
|
||||
link_id: Some("link_calendar".to_string()),
|
||||
resource_uri: Some("ui://widget/lookup.html".to_string()),
|
||||
app_name: Some("Calendar".to_string()),
|
||||
action_name: Some("lookup".to_string()),
|
||||
}),
|
||||
mcp_app_resource_uri: Some("ui://widget/lookup.html".to_string()),
|
||||
mcp_app_ui: None,
|
||||
plugin_id: Some("sample@test".to_string()),
|
||||
read_only_hint: None,
|
||||
result: Some(Box::new(McpToolCallResult {
|
||||
content: vec![serde_json::json!({
|
||||
"type": "text",
|
||||
"text": "secret result"
|
||||
})],
|
||||
structured_content: Some(serde_json::json!({"secret":"structured"})),
|
||||
meta: Some(serde_json::json!({"secret":"meta"})),
|
||||
})),
|
||||
error: None,
|
||||
duration_ms: Some(8),
|
||||
},
|
||||
ThreadItemPayload::ImageGeneration(ImageGenerationItem {
|
||||
id: "ig-1".to_string(),
|
||||
status: "completed".to_string(),
|
||||
revised_prompt: Some("revised".to_string()),
|
||||
image: GeneratedImageRef::Inline {
|
||||
result: "base64-result".to_string(),
|
||||
},
|
||||
transparent_background: None,
|
||||
failure: None,
|
||||
saved_path: Some(test_path_buf("/tmp/ig-1.png").abs()),
|
||||
input_images: Vec::new(),
|
||||
imagegen_request_id: None,
|
||||
generation_id: None,
|
||||
}),
|
||||
]);
|
||||
thread.turns[0].items[1].started_at_ms = Some(123);
|
||||
thread.turns[0].items[2].started_at_ms = Some(456);
|
||||
|
||||
redact_thread_resume_payloads(&mut thread.turns);
|
||||
|
||||
assert_eq!(thread.turns[0].items.len(), 2);
|
||||
assert_eq!(thread.turns[0].items[1].started_at_ms, Some(123));
|
||||
assert_eq!(
|
||||
thread.turns[0].items[0].payload,
|
||||
ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "agent-1".to_string(),
|
||||
text: "kept".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
thread.turns[0].items[1].payload,
|
||||
ThreadItemPayload::McpToolCall {
|
||||
id: "mcp-1".to_string(),
|
||||
server: "docs".to_string(),
|
||||
tool: "lookup".to_string(),
|
||||
status: McpToolCallStatus::Completed,
|
||||
arguments: JsonValue::String(REDACTED_PAYLOAD.to_string()),
|
||||
app_context: Some(McpToolCallAppContext {
|
||||
connector_id: "calendar".to_string(),
|
||||
link_id: Some("link_calendar".to_string()),
|
||||
resource_uri: Some("ui://widget/lookup.html".to_string()),
|
||||
app_name: Some("Calendar".to_string()),
|
||||
action_name: Some("lookup".to_string()),
|
||||
}),
|
||||
mcp_app_resource_uri: Some("ui://widget/lookup.html".to_string()),
|
||||
mcp_app_ui: None,
|
||||
plugin_id: Some("sample@test".to_string()),
|
||||
read_only_hint: None,
|
||||
result: Some(Box::new(redacted_mcp_tool_call_result())),
|
||||
error: None,
|
||||
duration_ms: Some(8),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacts_mcp_error_message() {
|
||||
let mut thread = test_thread(vec![ThreadItemPayload::McpToolCall {
|
||||
id: "mcp-1".to_string(),
|
||||
server: "docs".to_string(),
|
||||
tool: "lookup".to_string(),
|
||||
status: McpToolCallStatus::Failed,
|
||||
arguments: serde_json::json!({"secret":"argument"}),
|
||||
app_context: None,
|
||||
mcp_app_resource_uri: None,
|
||||
mcp_app_ui: None,
|
||||
plugin_id: None,
|
||||
read_only_hint: None,
|
||||
result: None,
|
||||
error: Some(McpToolCallError {
|
||||
message: "secret error".to_string(),
|
||||
}),
|
||||
duration_ms: Some(8),
|
||||
}]);
|
||||
|
||||
redact_thread_resume_payloads(&mut thread.turns);
|
||||
|
||||
assert_eq!(
|
||||
thread.turns[0].items[0].payload,
|
||||
ThreadItemPayload::McpToolCall {
|
||||
id: "mcp-1".to_string(),
|
||||
server: "docs".to_string(),
|
||||
tool: "lookup".to_string(),
|
||||
status: McpToolCallStatus::Failed,
|
||||
arguments: JsonValue::String(REDACTED_PAYLOAD.to_string()),
|
||||
app_context: None,
|
||||
mcp_app_resource_uri: None,
|
||||
mcp_app_ui: None,
|
||||
plugin_id: None,
|
||||
read_only_hint: None,
|
||||
result: None,
|
||||
error: Some(McpToolCallError {
|
||||
message: REDACTED_PAYLOAD.to_string(),
|
||||
}),
|
||||
duration_ms: Some(8),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn test_thread(items: Vec<ThreadItemPayload>) -> Thread {
|
||||
Thread {
|
||||
originator: None,
|
||||
environments: None,
|
||||
id: "thread-1".to_string(),
|
||||
extra: None,
|
||||
session_id: "session-1".to_string(),
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
preview: "preview".to_string(),
|
||||
ephemeral: false,
|
||||
section: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
history_mode: Default::default(),
|
||||
model_provider: "mock_provider".to_string(),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
recency_at: Some(0),
|
||||
status: ThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: SessionSource::Cli,
|
||||
can_accept_direct_input: None,
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
git_info: None,
|
||||
name: None,
|
||||
turns: vec![Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items: items.into_iter().map(ThreadItem::untimed).collect(),
|
||||
items_view: TurnItemsView::Full,
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
}
|
||||
236
akode-rs/app-server/src/request_processors/thread_sections.rs
Normal file
236
akode-rs/app-server/src/request_processors/thread_sections.rs
Normal file
@@ -0,0 +1,236 @@
|
||||
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
|
||||
use super::thread_processor::THREAD_LIST_MAX_LIMIT;
|
||||
use super::thread_processor::ThreadRequestProcessor;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_params;
|
||||
use crate::error_code::method_not_found;
|
||||
use akode_app_server_protocol::ClientResponsePayload;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::ThreadSection;
|
||||
use akode_app_server_protocol::ThreadSectionAppearance;
|
||||
use akode_app_server_protocol::ThreadSectionCreateParams;
|
||||
use akode_app_server_protocol::ThreadSectionCreateResponse;
|
||||
use akode_app_server_protocol::ThreadSectionDeleteParams;
|
||||
use akode_app_server_protocol::ThreadSectionDeleteResponse;
|
||||
use akode_app_server_protocol::ThreadSectionListParams;
|
||||
use akode_app_server_protocol::ThreadSectionListResponse;
|
||||
use akode_app_server_protocol::ThreadSectionUpdateParams;
|
||||
use akode_app_server_protocol::ThreadSectionUpdateResponse;
|
||||
use akode_state::PINNED_THREAD_SECTION_ID;
|
||||
use akode_thread_store::CreateThreadSectionParams as StoreCreateThreadSectionParams;
|
||||
use akode_thread_store::DeleteThreadSectionParams as StoreDeleteThreadSectionParams;
|
||||
use akode_thread_store::ListThreadSectionsParams as StoreListThreadSectionsParams;
|
||||
use akode_thread_store::RenameThreadSectionParams as StoreRenameThreadSectionParams;
|
||||
use akode_thread_store::StoredThreadSection;
|
||||
use akode_thread_store::ThreadStoreError;
|
||||
|
||||
const MAX_THREAD_SECTION_APPEARANCE_FIELD_BYTES: usize = 64;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn thread_section_list(
|
||||
&self,
|
||||
params: ThreadSectionListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "threadSection/list";
|
||||
self.ensure_thread_sections_supported(OPERATION)?;
|
||||
let limit = params
|
||||
.limit
|
||||
.map(|value| value as usize)
|
||||
.unwrap_or(THREAD_LIST_DEFAULT_LIMIT)
|
||||
.clamp(1, THREAD_LIST_MAX_LIMIT);
|
||||
let page = self
|
||||
.thread_store
|
||||
.list_thread_sections(StoreListThreadSectionsParams {
|
||||
cursor: params.cursor,
|
||||
limit,
|
||||
})
|
||||
.await
|
||||
.map_err(|err| thread_section_store_error(OPERATION, err))?;
|
||||
|
||||
Ok(Some(
|
||||
ThreadSectionListResponse {
|
||||
data: page.sections.into_iter().map(api_thread_section).collect(),
|
||||
next_cursor: page.next_cursor,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_section_create(
|
||||
&self,
|
||||
params: ThreadSectionCreateParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "threadSection/create";
|
||||
self.ensure_thread_sections_supported(OPERATION)?;
|
||||
let name = params.name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(invalid_params("section name must not be empty"));
|
||||
}
|
||||
if let Some(appearance) = params.appearance.as_ref() {
|
||||
validate_thread_section_appearance(appearance)?;
|
||||
}
|
||||
let section = self
|
||||
.thread_store
|
||||
.create_thread_section(StoreCreateThreadSectionParams {
|
||||
name: name.to_string(),
|
||||
appearance: params.appearance.map(state_thread_section_appearance),
|
||||
})
|
||||
.await
|
||||
.map_err(|err| thread_section_store_error(OPERATION, err))?;
|
||||
|
||||
Ok(Some(
|
||||
ThreadSectionCreateResponse {
|
||||
section: api_thread_section(section),
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_section_update(
|
||||
&self,
|
||||
params: ThreadSectionUpdateParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "threadSection/update";
|
||||
self.ensure_thread_sections_supported(OPERATION)?;
|
||||
let name = params.name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(invalid_params("section name must not be empty"));
|
||||
}
|
||||
if params.section_id.trim().is_empty() {
|
||||
return Err(invalid_params("sectionId must not be empty"));
|
||||
}
|
||||
if params.section_id == PINNED_THREAD_SECTION_ID {
|
||||
return Err(invalid_params(
|
||||
"the built-in pinned section cannot be renamed",
|
||||
));
|
||||
}
|
||||
if let Some(Some(appearance)) = params.appearance.as_ref() {
|
||||
validate_thread_section_appearance(appearance)?;
|
||||
}
|
||||
let section = self
|
||||
.thread_store
|
||||
.rename_thread_section(StoreRenameThreadSectionParams {
|
||||
section_id: params.section_id.clone(),
|
||||
name: name.to_string(),
|
||||
appearance: params
|
||||
.appearance
|
||||
.map(|appearance| appearance.map(state_thread_section_appearance)),
|
||||
})
|
||||
.await
|
||||
.map_err(|err| thread_section_store_error(OPERATION, err))?
|
||||
.ok_or_else(|| {
|
||||
invalid_params(format!("thread section not found: {}", params.section_id))
|
||||
})?;
|
||||
|
||||
Ok(Some(
|
||||
ThreadSectionUpdateResponse {
|
||||
section: api_thread_section(section),
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_section_delete(
|
||||
&self,
|
||||
params: ThreadSectionDeleteParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
const OPERATION: &str = "threadSection/delete";
|
||||
self.ensure_thread_sections_supported(OPERATION)?;
|
||||
if params.section_id.trim().is_empty() {
|
||||
return Err(invalid_params("sectionId must not be empty"));
|
||||
}
|
||||
if params.section_id == PINNED_THREAD_SECTION_ID {
|
||||
return Err(invalid_params(
|
||||
"the built-in pinned section cannot be deleted",
|
||||
));
|
||||
}
|
||||
let deleted = self
|
||||
.thread_store
|
||||
.delete_thread_section(StoreDeleteThreadSectionParams {
|
||||
section_id: params.section_id.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(|err| thread_section_store_error(OPERATION, err))?;
|
||||
if !deleted {
|
||||
return Err(invalid_params(format!(
|
||||
"thread section not found: {}",
|
||||
params.section_id
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(Some(ThreadSectionDeleteResponse {}.into()))
|
||||
}
|
||||
|
||||
fn ensure_thread_sections_supported(
|
||||
&self,
|
||||
operation: &'static str,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if self.thread_store.supports_thread_sections() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(unsupported_thread_section_operation(operation))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_thread_section_appearance(
|
||||
appearance: &ThreadSectionAppearance,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
for (field, value) in [
|
||||
("icon", appearance.icon.as_ref()),
|
||||
("color", appearance.color.as_ref()),
|
||||
] {
|
||||
if value.is_some_and(|value| value.len() > MAX_THREAD_SECTION_APPEARANCE_FIELD_BYTES) {
|
||||
return Err(invalid_params(format!(
|
||||
"section appearance {field} must not exceed {MAX_THREAD_SECTION_APPEARANCE_FIELD_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn api_thread_section(section: StoredThreadSection) -> ThreadSection {
|
||||
ThreadSection {
|
||||
id: section.id,
|
||||
name: section.name,
|
||||
appearance: section
|
||||
.appearance
|
||||
.map(|appearance| ThreadSectionAppearance {
|
||||
icon: appearance.icon,
|
||||
color: appearance.color,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn state_thread_section_appearance(
|
||||
appearance: ThreadSectionAppearance,
|
||||
) -> akode_state::ThreadSectionAppearance {
|
||||
akode_state::ThreadSectionAppearance {
|
||||
icon: appearance.icon,
|
||||
color: appearance.color,
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_thread_section_operation(operation: &'static str) -> JSONRPCErrorError {
|
||||
method_not_found(format!("{operation} is unavailable without sqlite state"))
|
||||
}
|
||||
|
||||
fn thread_section_store_error(
|
||||
operation: &'static str,
|
||||
error: ThreadStoreError,
|
||||
) -> JSONRPCErrorError {
|
||||
match error {
|
||||
ThreadStoreError::Unsupported { .. } => unsupported_thread_section_operation(operation),
|
||||
ThreadStoreError::InvalidRequest { message } => invalid_params(message),
|
||||
error @ (ThreadStoreError::ThreadNotFound { .. }
|
||||
| ThreadStoreError::Conflict { .. }
|
||||
| ThreadStoreError::Retryable { .. }
|
||||
| ThreadStoreError::OutcomeUnknown { .. }
|
||||
| ThreadStoreError::Internal { .. }) => {
|
||||
let action = operation
|
||||
.strip_prefix("threadSection/")
|
||||
.unwrap_or(operation);
|
||||
internal_error(format!("failed to {action} thread section: {error}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
301
akode-rs/app-server/src/request_processors/thread_summary.rs
Normal file
301
akode-rs/app-server/src/request_processors/thread_summary.rs
Normal file
@@ -0,0 +1,301 @@
|
||||
use super::*;
|
||||
#[cfg(test)]
|
||||
use std::io::Error as IoError;
|
||||
#[cfg(test)]
|
||||
use chrono::DateTime;
|
||||
#[cfg(test)]
|
||||
use chrono::Utc;
|
||||
use akode_protocol::config_types::MultiAgentMode;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn read_summary_from_rollout(
|
||||
path: &Path,
|
||||
fallback_provider: &str,
|
||||
) -> std::io::Result<ConversationSummary> {
|
||||
let head = read_head_for_summary(path).await?;
|
||||
|
||||
let Some(first) = head.first() else {
|
||||
return Err(IoError::other(format!(
|
||||
"rollout at {} is empty",
|
||||
path.display()
|
||||
)));
|
||||
};
|
||||
|
||||
let session_meta_line =
|
||||
serde_json::from_value::<SessionMetaLine>(first.clone()).map_err(|_| {
|
||||
IoError::other(format!(
|
||||
"rollout at {} does not start with session metadata",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
let SessionMetaLine {
|
||||
meta: session_meta,
|
||||
git,
|
||||
} = session_meta_line;
|
||||
let mut session_meta = session_meta;
|
||||
session_meta.source = with_thread_spawn_agent_metadata(
|
||||
session_meta.source.clone(),
|
||||
session_meta.agent_nickname.clone(),
|
||||
session_meta.agent_role.clone(),
|
||||
);
|
||||
|
||||
let created_at = if session_meta.timestamp.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(session_meta.timestamp.as_str())
|
||||
};
|
||||
let updated_at = read_updated_at(path, created_at).await;
|
||||
if let Some(summary) = extract_conversation_summary(
|
||||
path.to_path_buf(),
|
||||
&head,
|
||||
&session_meta,
|
||||
git.as_ref(),
|
||||
fallback_provider,
|
||||
updated_at.clone(),
|
||||
) {
|
||||
return Ok(summary);
|
||||
}
|
||||
|
||||
let timestamp = if session_meta.timestamp.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(session_meta.timestamp.clone())
|
||||
};
|
||||
let model_provider = session_meta
|
||||
.model_provider
|
||||
.clone()
|
||||
.unwrap_or_else(|| fallback_provider.to_string());
|
||||
let git_info = git.as_ref().map(map_git_info);
|
||||
let updated_at = updated_at.or_else(|| timestamp.clone());
|
||||
|
||||
Ok(ConversationSummary {
|
||||
conversation_id: session_meta.id,
|
||||
timestamp,
|
||||
updated_at,
|
||||
path: path.to_path_buf(),
|
||||
preview: String::new(),
|
||||
model_provider,
|
||||
cwd: session_meta.cwd,
|
||||
cli_version: session_meta.cli_version,
|
||||
source: session_meta.source,
|
||||
git_info,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn extract_conversation_summary(
|
||||
path: PathBuf,
|
||||
head: &[serde_json::Value],
|
||||
session_meta: &SessionMeta,
|
||||
git: Option<&CoreGitInfo>,
|
||||
fallback_provider: &str,
|
||||
updated_at: Option<String>,
|
||||
) -> Option<ConversationSummary> {
|
||||
let preview = head
|
||||
.iter()
|
||||
.filter_map(|value| serde_json::from_value::<ResponseItem>(value.clone()).ok())
|
||||
.find_map(|item| match akode_core::parse_turn_item(&item) {
|
||||
Some(TurnItem::UserMessage(user)) => Some(user.message()),
|
||||
_ => None,
|
||||
})?;
|
||||
|
||||
let preview = strip_user_message_prefix(preview.as_str());
|
||||
|
||||
let timestamp = if session_meta.timestamp.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(session_meta.timestamp.clone())
|
||||
};
|
||||
let conversation_id = session_meta.id;
|
||||
let model_provider = session_meta
|
||||
.model_provider
|
||||
.clone()
|
||||
.unwrap_or_else(|| fallback_provider.to_string());
|
||||
let git_info = git.map(map_git_info);
|
||||
let updated_at = updated_at.or_else(|| timestamp.clone());
|
||||
|
||||
Some(ConversationSummary {
|
||||
conversation_id,
|
||||
timestamp,
|
||||
updated_at,
|
||||
path,
|
||||
preview: preview.to_string(),
|
||||
model_provider,
|
||||
cwd: session_meta.cwd.clone(),
|
||||
cli_version: session_meta.cli_version.clone(),
|
||||
source: session_meta.source.clone(),
|
||||
git_info,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn map_git_info(git_info: &CoreGitInfo) -> ConversationGitInfo {
|
||||
ConversationGitInfo {
|
||||
sha: git_info.commit_hash.as_ref().map(|sha| sha.0.clone()),
|
||||
branch: git_info.branch.clone(),
|
||||
origin_url: git_info.repository_url.clone().map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn with_thread_spawn_agent_metadata(
|
||||
source: akode_protocol::protocol::SessionSource,
|
||||
agent_nickname: Option<String>,
|
||||
agent_role: Option<String>,
|
||||
) -> akode_protocol::protocol::SessionSource {
|
||||
if agent_nickname.is_none() && agent_role.is_none() {
|
||||
return source;
|
||||
}
|
||||
|
||||
match source {
|
||||
akode_protocol::protocol::SessionSource::SubAgent(
|
||||
akode_protocol::protocol::SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth,
|
||||
agent_path,
|
||||
agent_nickname: existing_agent_nickname,
|
||||
agent_role: existing_agent_role,
|
||||
},
|
||||
) => akode_protocol::protocol::SessionSource::SubAgent(
|
||||
akode_protocol::protocol::SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth,
|
||||
agent_path,
|
||||
agent_nickname: agent_nickname.or(existing_agent_nickname),
|
||||
agent_role: agent_role.or(existing_agent_role),
|
||||
},
|
||||
),
|
||||
_ => source,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn thread_response_active_permission_profile(
|
||||
active_permission_profile: Option<akode_protocol::models::ActivePermissionProfile>,
|
||||
) -> Option<akode_app_server_protocol::ActivePermissionProfile> {
|
||||
active_permission_profile.map(Into::into)
|
||||
}
|
||||
|
||||
pub(crate) fn thread_settings_from_config_snapshot(
|
||||
config_snapshot: &ThreadConfigSnapshot,
|
||||
) -> ThreadSettings {
|
||||
ThreadSettings {
|
||||
disabled_plugin_ids: config_snapshot.disabled_plugin_ids.clone(),
|
||||
cwd: config_snapshot.cwd().clone(),
|
||||
approval_policy: config_snapshot.approval_policy.into(),
|
||||
approvals_reviewer: config_snapshot.approvals_reviewer.into(),
|
||||
sandbox_policy: config_snapshot.sandbox_policy().into(),
|
||||
active_permission_profile: thread_response_active_permission_profile(
|
||||
config_snapshot.active_permission_profile.clone(),
|
||||
),
|
||||
model: config_snapshot.model.clone(),
|
||||
model_provider: config_snapshot.model_provider_id.clone(),
|
||||
service_tier: config_snapshot.service_tier.clone(),
|
||||
effort: config_snapshot.reasoning_effort.clone(),
|
||||
summary: config_snapshot.reasoning_summary,
|
||||
collaboration_mode: config_snapshot.collaboration_mode.clone(),
|
||||
multi_agent_mode: MultiAgentMode::ExplicitRequestOnly,
|
||||
personality: config_snapshot.personality,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn parse_datetime(timestamp: Option<&str>) -> Option<DateTime<Utc>> {
|
||||
timestamp.and_then(|ts| {
|
||||
chrono::DateTime::parse_from_rfc3339(ts)
|
||||
.ok()
|
||||
.map(|dt| dt.with_timezone(&chrono::Utc))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
async fn read_updated_at(path: &Path, created_at: Option<&str>) -> Option<String> {
|
||||
let updated_at = tokio::fs::metadata(path)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|meta| meta.modified().ok())
|
||||
.map(|modified| {
|
||||
let updated_at: DateTime<Utc> = modified.into();
|
||||
updated_at.to_rfc3339_opts(SecondsFormat::Millis, true)
|
||||
});
|
||||
updated_at.or_else(|| created_at.map(str::to_string))
|
||||
}
|
||||
|
||||
pub(super) fn thread_started_notification(mut thread: Thread) -> ThreadStartedNotification {
|
||||
thread.turns.clear();
|
||||
ThreadStartedNotification { thread }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn summary_to_thread(
|
||||
summary: ConversationSummary,
|
||||
fallback_cwd: &AbsolutePathBuf,
|
||||
) -> Thread {
|
||||
let ConversationSummary {
|
||||
conversation_id,
|
||||
path,
|
||||
preview,
|
||||
timestamp,
|
||||
updated_at,
|
||||
model_provider,
|
||||
cwd,
|
||||
cli_version,
|
||||
source,
|
||||
git_info,
|
||||
} = summary;
|
||||
|
||||
let created_at = parse_datetime(timestamp.as_deref());
|
||||
let updated_at = parse_datetime(updated_at.as_deref()).or(created_at);
|
||||
let git_info = git_info.map(|info| ApiGitInfo {
|
||||
sha: info.sha,
|
||||
branch: info.branch,
|
||||
origin_url: info.origin_url,
|
||||
});
|
||||
let cwd =
|
||||
AbsolutePathBuf::relative_to_current_dir(path_utils::normalize_for_native_workdir(cwd))
|
||||
.unwrap_or_else(|err| {
|
||||
warn!(
|
||||
conversation_id = %conversation_id,
|
||||
path = %path.display(),
|
||||
"failed to normalize thread cwd while summarizing thread: {err}"
|
||||
);
|
||||
fallback_cwd.clone()
|
||||
});
|
||||
|
||||
let thread_id = conversation_id.to_string();
|
||||
Thread {
|
||||
originator: None,
|
||||
environments: None,
|
||||
id: thread_id.clone(),
|
||||
extra: None,
|
||||
session_id: thread_id,
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
preview,
|
||||
ephemeral: false,
|
||||
section: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
model_provider,
|
||||
created_at: created_at.map(|dt| dt.timestamp()).unwrap_or(0),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
updated_at: updated_at.map(|dt| dt.timestamp()).unwrap_or(0),
|
||||
recency_at: updated_at.map(|dt| dt.timestamp()),
|
||||
status: ThreadStatus::NotLoaded,
|
||||
path: (!path.as_os_str().is_empty()).then_some(path),
|
||||
cwd,
|
||||
cli_version,
|
||||
agent_nickname: source.get_nickname(),
|
||||
agent_role: source.get_agent_role(),
|
||||
source: source.into(),
|
||||
can_accept_direct_input: None,
|
||||
thread_source: None,
|
||||
git_info,
|
||||
name: None,
|
||||
turns: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "thread_summary_tests.rs"]
|
||||
mod thread_summary_tests;
|
||||
@@ -0,0 +1,70 @@
|
||||
use super::*;
|
||||
|
||||
use anyhow::Result;
|
||||
use akode_protocol::protocol::USER_MESSAGE_BEGIN;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn extract_conversation_summary_prefers_plain_user_messages() -> Result<()> {
|
||||
let conversation_id = ThreadId::from_string("3f941c35-29b3-493b-b0a4-e25800d9aeb0")?;
|
||||
let timestamp = Some("2025-09-05T16:53:11.850Z".to_string());
|
||||
let path = PathBuf::from("rollout.jsonl");
|
||||
|
||||
let head = vec![
|
||||
json!({
|
||||
"session_id": conversation_id.to_string(),
|
||||
"id": conversation_id.to_string(),
|
||||
"timestamp": timestamp,
|
||||
"cwd": "/",
|
||||
"originator": "codex",
|
||||
"cli_version": "0.0.0",
|
||||
"model_provider": "test-provider"
|
||||
}),
|
||||
json!({
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "input_text",
|
||||
"text": "# AGENTS.md instructions for project\n\n<INSTRUCTIONS>\n<AGENTS.md contents>\n</INSTRUCTIONS>".to_string(),
|
||||
}],
|
||||
}),
|
||||
json!({
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "input_text",
|
||||
"text": format!("<prior context> {USER_MESSAGE_BEGIN}Count to 5"),
|
||||
}],
|
||||
}),
|
||||
];
|
||||
|
||||
let session_meta = serde_json::from_value::<SessionMeta>(head[0].clone())?;
|
||||
|
||||
let summary = extract_conversation_summary(
|
||||
path.clone(),
|
||||
&head,
|
||||
&session_meta,
|
||||
/*git*/ None,
|
||||
"test-provider",
|
||||
timestamp.clone(),
|
||||
)
|
||||
.expect("summary");
|
||||
|
||||
let expected = ConversationSummary {
|
||||
conversation_id,
|
||||
timestamp: timestamp.clone(),
|
||||
updated_at: timestamp,
|
||||
path,
|
||||
preview: "Count to 5".to_string(),
|
||||
model_provider: "test-provider".to_string(),
|
||||
cwd: PathBuf::from("/"),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: akode_protocol::protocol::SessionSource::VSCode,
|
||||
git_info: None,
|
||||
};
|
||||
|
||||
assert_eq!(summary, expected);
|
||||
Ok(())
|
||||
}
|
||||
201
akode-rs/app-server/src/request_processors/token_usage_replay.rs
Normal file
201
akode-rs/app-server/src/request_processors/token_usage_replay.rs
Normal file
@@ -0,0 +1,201 @@
|
||||
//! Replays persisted token usage snapshots when a client attaches to an existing thread.
|
||||
//!
|
||||
//! The message processor decides when replay is allowed and preserves JSON-RPC response
|
||||
//! ordering. This module owns notification construction and the attribution rules that
|
||||
//! map the latest persisted `TokenCount` back to a v2 turn id.
|
||||
//!
|
||||
//! Rollout histories can contain explicit turn ids or generated turn ids. When explicit
|
||||
//! ids do not match the rebuilt thread, replay falls back to the active turn position at
|
||||
//! the time the `TokenCount` was persisted so the notification still targets the
|
||||
//! corresponding rebuilt turn.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ThreadHistoryBuilder;
|
||||
use akode_app_server_protocol::ThreadTokenUsage;
|
||||
use akode_app_server_protocol::ThreadTokenUsageUpdatedNotification;
|
||||
use akode_app_server_protocol::Turn;
|
||||
use akode_app_server_protocol::TurnStatus;
|
||||
use akode_core::CodexThread;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_rollout::RolloutItem;
|
||||
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
|
||||
/// Sends a restored token usage update to the connection that attached to a thread.
|
||||
///
|
||||
/// This is lifecycle replay rather than a model event: the rollout already contains
|
||||
/// the original `TokenCount`, and emitting through `send_event` here would duplicate
|
||||
/// persisted usage records. Keeping replay connection-scoped also avoids
|
||||
/// surprising other subscribers with a historical usage update while they may be
|
||||
/// rendering live turn events.
|
||||
pub(super) async fn send_thread_token_usage_update_to_connection(
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
connection_id: ConnectionId,
|
||||
thread_id: ThreadId,
|
||||
conversation: &CodexThread,
|
||||
token_usage_turn_id: String,
|
||||
) {
|
||||
if token_usage_turn_id.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(info) = conversation.token_usage_info().await else {
|
||||
return;
|
||||
};
|
||||
let notification = ThreadTokenUsageUpdatedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: token_usage_turn_id,
|
||||
token_usage: ThreadTokenUsage::from(info),
|
||||
};
|
||||
outgoing
|
||||
.send_server_notification_to_connections(
|
||||
&[connection_id],
|
||||
ServerNotification::ThreadTokenUsageUpdated(notification),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) fn restored_token_usage_turn_id(
|
||||
rollout_items: &[RolloutItem],
|
||||
turns: &[Turn],
|
||||
) -> String {
|
||||
latest_token_usage_turn_id_from_rollout_items(rollout_items, turns)
|
||||
.unwrap_or_else(|| latest_token_usage_turn_id(turns))
|
||||
}
|
||||
|
||||
/// Identifies the turn that was active when the latest `TokenCount` record appeared.
|
||||
///
|
||||
/// The id is preferred when it still appears in the rebuilt thread. The position is a
|
||||
/// fallback for histories whose implicit turn ids are regenerated during reconstruction.
|
||||
fn latest_token_usage_turn_id_from_rollout_items(
|
||||
rollout_items: &[RolloutItem],
|
||||
turns: &[Turn],
|
||||
) -> Option<String> {
|
||||
let token_count_index = rollout_items
|
||||
.iter()
|
||||
.rposition(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TokenCount(_))))?;
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
for item in &rollout_items[..token_count_index] {
|
||||
builder.handle_rollout_item(item);
|
||||
}
|
||||
|
||||
if turns.is_empty() {
|
||||
return builder.active_turn_id_if_explicit();
|
||||
}
|
||||
|
||||
let active_turn_id = builder.active_turn_id()?;
|
||||
if turns.iter().any(|turn| turn.id == active_turn_id) {
|
||||
Some(active_turn_id.to_string())
|
||||
} else {
|
||||
builder
|
||||
.active_turn_position()
|
||||
.and_then(|position| turns.get(position))
|
||||
.map(|turn| turn.id.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Chooses a fallback turn id that should own a replayed token usage update.
|
||||
///
|
||||
/// Normal replay derives the owner from the rollout position of the latest
|
||||
/// `TokenCount` event. This fallback only preserves a stable wire shape for
|
||||
/// unusual histories where that rollout information cannot be read.
|
||||
fn latest_token_usage_turn_id(turns: &[Turn]) -> String {
|
||||
turns
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|turn| matches!(turn.status, TurnStatus::Completed | TurnStatus::Failed))
|
||||
.or_else(|| turns.last())
|
||||
.map(|turn| turn.id.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_app_server_protocol::build_turns_from_rollout_items;
|
||||
use akode_protocol::protocol::AgentMessageEvent;
|
||||
use akode_protocol::protocol::TokenCountEvent;
|
||||
use akode_protocol::protocol::UserMessageEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn replay_attribution_uses_already_loaded_history() {
|
||||
let rollout_items = token_usage_history();
|
||||
let turns = build_turns_from_rollout_items(&rollout_items);
|
||||
|
||||
assert_eq!(
|
||||
latest_token_usage_turn_id_from_rollout_items(&rollout_items, turns.as_slice()),
|
||||
Some(turns[0].id.clone())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_attribution_falls_back_to_rebuilt_turn_position() {
|
||||
let rollout_items = token_usage_history();
|
||||
let mut turns = build_turns_from_rollout_items(&rollout_items);
|
||||
turns[0].id = "rebuilt-turn-id".to_string();
|
||||
|
||||
assert_eq!(
|
||||
latest_token_usage_turn_id_from_rollout_items(&rollout_items, turns.as_slice()),
|
||||
Some("rebuilt-turn-id".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_attribution_rejects_suffix_generated_turn_ids() {
|
||||
let rollout_items = token_usage_history();
|
||||
|
||||
assert_eq!(
|
||||
latest_token_usage_turn_id_from_rollout_items(&rollout_items, /*turns*/ &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_attribution_uses_latest_token_count_and_ignores_tail_turn() {
|
||||
let mut rollout_items = token_usage_history();
|
||||
rollout_items.extend(token_usage_history());
|
||||
let turns = build_turns_from_rollout_items(&rollout_items);
|
||||
|
||||
assert_eq!(
|
||||
latest_token_usage_turn_id_from_rollout_items(&rollout_items, turns.as_slice()),
|
||||
Some(turns[2].id.clone())
|
||||
);
|
||||
}
|
||||
|
||||
fn token_usage_history() -> Vec<RolloutItem> {
|
||||
vec![
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: "first turn".to_string(),
|
||||
images: None,
|
||||
local_images: Vec::new(),
|
||||
text_elements: Vec::new(),
|
||||
..Default::default()
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::AgentMessage(AgentMessageEvent {
|
||||
moderation: None,
|
||||
message: "first answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
|
||||
info: None,
|
||||
rate_limits: None,
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: "second turn".to_string(),
|
||||
images: None,
|
||||
local_images: Vec::new(),
|
||||
text_elements: Vec::new(),
|
||||
..Default::default()
|
||||
})),
|
||||
]
|
||||
}
|
||||
}
|
||||
1495
akode-rs/app-server/src/request_processors/turn_processor.rs
Normal file
1495
akode-rs/app-server/src/request_processors/turn_processor.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,427 @@
|
||||
use super::*;
|
||||
#[cfg(target_os = "windows")]
|
||||
use anyhow::Context as _;
|
||||
use akode_protocol::sandbox::SandboxType;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct WindowsSandboxRequestProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
#[cfg(target_os = "windows")]
|
||||
registration_refresh: Arc<tokio::sync::OnceCell<()>>,
|
||||
}
|
||||
|
||||
impl WindowsSandboxRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
) -> Self {
|
||||
akode_core::windows_sandbox::log_windows_sandbox_startup(&config);
|
||||
Self {
|
||||
outgoing,
|
||||
config,
|
||||
config_manager,
|
||||
#[cfg(target_os = "windows")]
|
||||
registration_refresh: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn windows_sandbox_readiness(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
#[cfg(target_os = "windows")]
|
||||
if akode_windows_sandbox::registered_core_requested()
|
||||
&& self.config.effective_local_windows_sandbox_type() != SandboxType::WindowsMxc
|
||||
&& matches!(
|
||||
WindowsSandboxLevel::from_config(&self.config),
|
||||
WindowsSandboxLevel::Elevated
|
||||
)
|
||||
&& !akode_login::is_workload_identity_selected()
|
||||
{
|
||||
let processor = self.clone();
|
||||
let request_id = request_id.clone();
|
||||
// Deployment must not hold up unrelated RPCs in the serial dispatcher.
|
||||
tokio::spawn(async move {
|
||||
// Coalesce readiness requests. A failed refresh leaves manual setup available.
|
||||
processor.registration_refresh.get_or_init(|| async {
|
||||
let config = Arc::clone(&processor.config);
|
||||
let result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
if !akode_windows_sandbox::registered_core_needs_refresh(&config.codex_home)? {
|
||||
return Ok(());
|
||||
}
|
||||
let env_map = std::env::vars().collect();
|
||||
let policy = config.permissions.effective_permission_profile();
|
||||
let (settings, listeners) = match config.permissions.network.as_ref() {
|
||||
Some(network) => network.windows_sandbox_proxy_listeners()?,
|
||||
None => (
|
||||
akode_windows_sandbox::WindowsSandboxProvisioningSettings::from_environment(&policy, &env_map),
|
||||
akode_windows_sandbox::WindowsSandboxProxyListeners::from_environment(&policy, &env_map),
|
||||
),
|
||||
};
|
||||
akode_windows_sandbox::refresh_registered_core_via_service(
|
||||
&config.codex_home, settings, listeners,
|
||||
)?;
|
||||
Ok(())
|
||||
}).await.map_err(anyhow::Error::from).and_then(std::convert::identity);
|
||||
if let Err(error) = result {
|
||||
warn!("Registered Core startup refresh requires manual setup: {error:#}");
|
||||
}
|
||||
}).await;
|
||||
processor
|
||||
.outgoing
|
||||
.send_response(
|
||||
request_id,
|
||||
determine_windows_sandbox_readiness(&processor.config),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
return Ok(None);
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let _ = request_id;
|
||||
Ok(Some(
|
||||
determine_windows_sandbox_readiness(&self.config).into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn windows_sandbox_setup_start(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: WindowsSandboxSetupStartParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.windows_sandbox_setup_start_inner(request_id, params)
|
||||
.await
|
||||
.map(|()| None)
|
||||
}
|
||||
|
||||
async fn windows_sandbox_setup_start_inner(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: WindowsSandboxSetupStartParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
// Validate requirements before acknowledging setup so callers do not get a
|
||||
// `started` response for a Windows sandbox mode that cannot be persisted.
|
||||
let (config, command_cwd) = load_setup_config(
|
||||
&self.config_manager,
|
||||
self.config.cwd.as_path(),
|
||||
params.cwd.map(PathBuf::from),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
let setup_mode = resolve_allowed_windows_sandbox_setup_mode(
|
||||
config.config_layer_stack.requirements(),
|
||||
params.mode,
|
||||
)?;
|
||||
|
||||
// Provisioning installs native Windows filesystem permissions. Validate
|
||||
// this boundary before acknowledging that setup has started.
|
||||
let workspace_roots = config
|
||||
.effective_workspace_roots()
|
||||
.iter()
|
||||
.map(PathUri::to_abs_path)
|
||||
.collect::<std::io::Result<Vec<_>>>()
|
||||
.map_err(|err| {
|
||||
invalid_request(format!(
|
||||
"workspace roots are not native to this host: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
self.outgoing
|
||||
.send_response(
|
||||
request_id.clone(),
|
||||
WindowsSandboxSetupStartResponse { started: true },
|
||||
)
|
||||
.await;
|
||||
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let connection_id = request_id.connection_id;
|
||||
|
||||
tokio::spawn(async move {
|
||||
let setup_request = WindowsSandboxSetupRequest {
|
||||
mode: setup_mode,
|
||||
permission_profile: config.permissions.effective_permission_profile(),
|
||||
workspace_roots,
|
||||
command_cwd,
|
||||
env_map: std::env::vars().collect(),
|
||||
codex_home: config.codex_home.to_path_buf(),
|
||||
};
|
||||
let setup_result = async {
|
||||
// Workload identity is process-local, so use the existing helper path with
|
||||
// the caller's resolved configuration instead of loading auth in the service.
|
||||
#[cfg(target_os = "windows")]
|
||||
if setup_mode == CoreWindowsSandboxSetupMode::Elevated
|
||||
&& (akode_windows_sandbox::registered_core_requested()
|
||||
|| config.features.enabled(Feature::WindowsSandboxService))
|
||||
&& !akode_login::is_workload_identity_selected()
|
||||
{
|
||||
let provisioning = match config
|
||||
.permissions
|
||||
.network
|
||||
.as_ref()
|
||||
.map_or_else(
|
||||
|| {
|
||||
Ok((
|
||||
akode_windows_sandbox::WindowsSandboxProvisioningSettings::from_environment(
|
||||
&setup_request.permission_profile,
|
||||
&setup_request.env_map,
|
||||
),
|
||||
akode_windows_sandbox::WindowsSandboxProxyListeners::from_environment(
|
||||
&setup_request.permission_profile,
|
||||
&setup_request.env_map,
|
||||
),
|
||||
))
|
||||
},
|
||||
akode_core::config::NetworkProxySpec::windows_sandbox_proxy_listeners,
|
||||
)
|
||||
{
|
||||
Ok(provisioning) => Some(provisioning),
|
||||
Err(error) => {
|
||||
if akode_windows_sandbox::registered_core_requested() {
|
||||
return Err(error).context("registered Core requires service-compatible proxy settings");
|
||||
}
|
||||
warn!(
|
||||
"Windows sandbox service does not support the configured proxy listeners; falling back to elevated setup: {error}"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some((settings, listeners)) = provisioning {
|
||||
let service_setup_request = setup_request.clone();
|
||||
let service_setup_start = Instant::now();
|
||||
tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
|
||||
if matches!(
|
||||
&service_setup_request.permission_profile,
|
||||
akode_protocol::models::PermissionProfile::Disabled
|
||||
) {
|
||||
// Only registered Core needs service provisioning for full access;
|
||||
// legacy setup keeps using the shared setup path below.
|
||||
if !akode_windows_sandbox::registered_core_requested() {
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
let Ok(permissions) = akode_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
|
||||
&service_setup_request.permission_profile,
|
||||
&service_setup_request.workspace_roots,
|
||||
) else {
|
||||
anyhow::ensure!(!akode_windows_sandbox::registered_core_requested(),
|
||||
"registered Core requires a service-compatible sandbox policy");
|
||||
// The existing setup path can still succeed for completed
|
||||
// provisioning without resolving the current profile.
|
||||
return Ok(());
|
||||
};
|
||||
permissions.validate_elevated_filesystem_policy(
|
||||
&service_setup_request.command_cwd,
|
||||
)?;
|
||||
}
|
||||
if akode_windows_sandbox::registered_core_requested() {
|
||||
akode_windows_sandbox::start_windows_sandbox_service_for_setup()?;
|
||||
}
|
||||
// The shared setup path below handles helper fallback and
|
||||
// refreshes workspace ACLs after provisioning.
|
||||
akode_windows_sandbox::provision_windows_sandbox_via_service(
|
||||
&service_setup_request.codex_home,
|
||||
settings,
|
||||
listeners,
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| {
|
||||
anyhow::anyhow!(
|
||||
"Windows sandbox service provisioning task failed: {error}"
|
||||
)
|
||||
})
|
||||
.and_then(std::convert::identity)
|
||||
.inspect_err(|error| {
|
||||
akode_core::windows_sandbox::emit_windows_sandbox_setup_failure_metrics(
|
||||
setup_mode,
|
||||
service_setup_start.elapsed(),
|
||||
error,
|
||||
);
|
||||
})?;
|
||||
}
|
||||
}
|
||||
akode_core::windows_sandbox::run_windows_sandbox_setup(setup_request).await
|
||||
}
|
||||
.await;
|
||||
let notification = WindowsSandboxSetupCompletedNotification {
|
||||
mode: match setup_mode {
|
||||
CoreWindowsSandboxSetupMode::Elevated => WindowsSandboxSetupMode::Elevated,
|
||||
CoreWindowsSandboxSetupMode::Unelevated => WindowsSandboxSetupMode::Unelevated,
|
||||
},
|
||||
success: setup_result.is_ok(),
|
||||
error: setup_result.err().map(|err| err.to_string()),
|
||||
};
|
||||
outgoing
|
||||
.send_server_notification_to_connections(
|
||||
&[connection_id],
|
||||
ServerNotification::WindowsSandboxSetupCompleted(notification),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_setup_config(
|
||||
manager: &ConfigManager,
|
||||
fallback_cwd: &std::path::Path,
|
||||
requested_cwd: Option<PathBuf>,
|
||||
) -> std::io::Result<(Config, PathBuf)> {
|
||||
// Setup without a project must not grant writes to the app's install directory.
|
||||
let workspace_roots = requested_cwd.is_none().then(Vec::new);
|
||||
let cwd = requested_cwd.unwrap_or_else(|| fallback_cwd.to_path_buf());
|
||||
let config = manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd.clone()),
|
||||
workspace_roots,
|
||||
..Default::default()
|
||||
},
|
||||
Some(cwd.clone()),
|
||||
)
|
||||
.await?;
|
||||
Ok((config, cwd))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_sandbox_setup_config_tests.rs"]
|
||||
mod setup_config_tests;
|
||||
|
||||
/// Resolves the requested API mode after checking that managed requirements allow it.
|
||||
fn resolve_allowed_windows_sandbox_setup_mode(
|
||||
requirements: &akode_config::ConfigRequirements,
|
||||
requested_mode: WindowsSandboxSetupMode,
|
||||
) -> Result<CoreWindowsSandboxSetupMode, JSONRPCErrorError> {
|
||||
let (setup_mode, config_mode) = match requested_mode {
|
||||
WindowsSandboxSetupMode::Elevated => (
|
||||
CoreWindowsSandboxSetupMode::Elevated,
|
||||
akode_config::types::WindowsSandboxModeToml::Elevated,
|
||||
),
|
||||
WindowsSandboxSetupMode::Unelevated => (
|
||||
CoreWindowsSandboxSetupMode::Unelevated,
|
||||
akode_config::types::WindowsSandboxModeToml::Unelevated,
|
||||
),
|
||||
};
|
||||
requirements
|
||||
.windows_sandbox_mode
|
||||
.can_set(&Some(config_mode))
|
||||
.map_err(|err| invalid_request(format!("invalid Windows sandbox setup mode: {err}")))?;
|
||||
Ok(setup_mode)
|
||||
}
|
||||
|
||||
fn determine_windows_sandbox_readiness(config: &Config) -> WindowsSandboxReadinessResponse {
|
||||
if !cfg!(windows) {
|
||||
return WindowsSandboxReadinessResponse {
|
||||
status: WindowsSandboxReadiness::NotConfigured,
|
||||
};
|
||||
}
|
||||
|
||||
if config.effective_local_windows_sandbox_type() == SandboxType::WindowsMxc {
|
||||
return WindowsSandboxReadinessResponse {
|
||||
status: WindowsSandboxReadiness::Ready,
|
||||
};
|
||||
}
|
||||
|
||||
determine_windows_sandbox_readiness_from_state(
|
||||
WindowsSandboxLevel::from_config(config),
|
||||
sandbox_setup_is_complete(config.codex_home.as_path()),
|
||||
)
|
||||
}
|
||||
|
||||
fn determine_windows_sandbox_readiness_from_state(
|
||||
windows_sandbox_level: WindowsSandboxLevel,
|
||||
sandbox_setup_is_complete: bool,
|
||||
) -> WindowsSandboxReadinessResponse {
|
||||
let status = match windows_sandbox_level {
|
||||
WindowsSandboxLevel::Disabled => WindowsSandboxReadiness::NotConfigured,
|
||||
WindowsSandboxLevel::RestrictedToken => WindowsSandboxReadiness::Ready,
|
||||
WindowsSandboxLevel::Elevated => {
|
||||
if sandbox_setup_is_complete {
|
||||
WindowsSandboxReadiness::Ready
|
||||
} else {
|
||||
WindowsSandboxReadiness::UpdateRequired
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
WindowsSandboxReadinessResponse { status }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
|
||||
use akode_config::ConfigRequirements;
|
||||
use akode_config::Constrained;
|
||||
use akode_config::ConstrainedWithSource;
|
||||
use akode_config::types::WindowsSandboxModeToml;
|
||||
|
||||
#[test]
|
||||
fn resolve_allowed_windows_sandbox_setup_mode_rejects_disallowed_mode() {
|
||||
let requirements = ConfigRequirements {
|
||||
windows_sandbox_mode: ConstrainedWithSource::new(
|
||||
Constrained::allow_only(Some(WindowsSandboxModeToml::Elevated)),
|
||||
/*source*/ None,
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let err = resolve_allowed_windows_sandbox_setup_mode(
|
||||
&requirements,
|
||||
WindowsSandboxSetupMode::Unelevated,
|
||||
)
|
||||
.expect_err("unelevated setup should be rejected");
|
||||
|
||||
assert_eq!(err.code, INVALID_REQUEST_ERROR_CODE);
|
||||
assert!(
|
||||
err.message.contains("invalid Windows sandbox setup mode"),
|
||||
"{err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn determine_windows_sandbox_readiness_reports_not_configured_when_disabled() {
|
||||
let response = determine_windows_sandbox_readiness_from_state(
|
||||
WindowsSandboxLevel::Disabled,
|
||||
/*sandbox_setup_is_complete*/ false,
|
||||
);
|
||||
|
||||
assert_eq!(response.status, WindowsSandboxReadiness::NotConfigured);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn determine_windows_sandbox_readiness_reports_ready_for_unelevated_mode() {
|
||||
let response = determine_windows_sandbox_readiness_from_state(
|
||||
WindowsSandboxLevel::RestrictedToken,
|
||||
/*sandbox_setup_is_complete*/ false,
|
||||
);
|
||||
|
||||
assert_eq!(response.status, WindowsSandboxReadiness::Ready);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn determine_windows_sandbox_readiness_reports_ready_for_complete_elevated_mode() {
|
||||
let response = determine_windows_sandbox_readiness_from_state(
|
||||
WindowsSandboxLevel::Elevated,
|
||||
/*sandbox_setup_is_complete*/ true,
|
||||
);
|
||||
|
||||
assert_eq!(response.status, WindowsSandboxReadiness::Ready);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn determine_windows_sandbox_readiness_reports_update_required_when_elevated_setup_is_stale() {
|
||||
let response = determine_windows_sandbox_readiness_from_state(
|
||||
WindowsSandboxLevel::Elevated,
|
||||
/*sandbox_setup_is_complete*/ false,
|
||||
);
|
||||
|
||||
assert_eq!(response.status, WindowsSandboxReadiness::UpdateRequired);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Exercise the setup RPC's real configuration loading without changing Windows accounts or ACLs.
|
||||
|
||||
use super::ConfigManager;
|
||||
use super::load_setup_config;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn omitted_cwd_does_not_make_the_server_directory_a_workspace() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let install = tempfile::tempdir()?;
|
||||
let manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
|
||||
let (config, command_cwd) =
|
||||
load_setup_config(&manager, install.path(), /*requested_cwd*/ None).await?;
|
||||
|
||||
assert_eq!(
|
||||
(command_cwd, config.effective_workspace_roots()),
|
||||
(install.path().to_path_buf(), Vec::new()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_cwd_remains_the_setup_workspace() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let install = tempfile::tempdir()?;
|
||||
let project = tempfile::tempdir()?;
|
||||
let manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
|
||||
let (config, command_cwd) =
|
||||
load_setup_config(&manager, install.path(), Some(project.path().to_path_buf())).await?;
|
||||
let expected = AbsolutePathBuf::from_absolute_path(project.path())?;
|
||||
|
||||
assert_eq!(
|
||||
(command_cwd, config.effective_workspace_roots()),
|
||||
(
|
||||
project.path().to_path_buf(),
|
||||
vec![PathUri::from_abs_path(&expected)],
|
||||
),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user