Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
codex-rs/app-server/src/external_agent_migration/mod.rs
Normal file
6
codex-rs/app-server/src/external_agent_migration/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
mod processor;
|
||||
mod protocol;
|
||||
mod session_importer;
|
||||
|
||||
pub(crate) use processor::ExternalAgentConfigRequestProcessor;
|
||||
pub(crate) use processor::ExternalAgentConfigRequestProcessorArgs;
|
||||
795
codex-rs/app-server/src/external_agent_migration/processor.rs
Normal file
795
codex-rs/app-server/src/external_agent_migration/processor.rs
Normal file
@@ -0,0 +1,795 @@
|
||||
use codex_protocol::MemoryVersion;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::request_processors::ConfigRequestProcessor;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::ExternalAgentConfigImportCompletedInput;
|
||||
use codex_analytics::ExternalAgentConfigImportFailureInput;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistoriesReadResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistoryRecordParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistoryRecordResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeFailure as ProtocolImportFailure;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeSuccess as ProtocolImportSuccess;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportProgressNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportTypeResult as ProtocolImportTypeResult;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItemType;
|
||||
use codex_app_server_protocol::ExternalAgentImportedConnectorCandidate;
|
||||
use codex_app_server_protocol::ExternalAgentImportedConnectorSource;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_external_agent_migration::DetectedConnectorCandidate;
|
||||
use codex_external_agent_migration::ExternalAgentConfigDetectOptions;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportItemResult as CoreImportItemResult;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportOutcome as CoreImportOutcome;
|
||||
use codex_external_agent_migration::ExternalAgentConfigMigrationItemType as CoreMigrationItemType;
|
||||
use codex_external_agent_migration::ExternalAgentConfigService;
|
||||
use codex_external_agent_migration::ExternalAgentSessionImportLimits;
|
||||
use codex_external_agent_migration::PluginImportOutcome;
|
||||
use codex_external_agent_migration::record_import_error;
|
||||
use codex_external_agent_migration::sessions::ExternalAgentSessionMigration as CoreSessionMigration;
|
||||
use codex_external_agent_migration::sessions::read_imported_connector_candidates;
|
||||
use codex_external_agent_migration::sessions::record_detected_session_connectors;
|
||||
use codex_features::Feature;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_state::ExternalAgentConfigImportFailureRecord;
|
||||
use codex_state::ExternalAgentConfigImportSuccessRecord;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::protocol::completed_notification;
|
||||
use super::protocol::core_migration_items;
|
||||
use super::protocol::detect_response;
|
||||
use super::protocol::protocol_import_history;
|
||||
use super::protocol::protocol_import_type_result;
|
||||
use super::session_importer::ExternalAgentSessionImporter;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ExternalAgentConfigRequestProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
migration_service: ExternalAgentConfigService,
|
||||
session_importer: ExternalAgentSessionImporter,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
config_processor: ConfigRequestProcessor,
|
||||
state_db: Option<StateDbHandle>,
|
||||
analytics_events_client: AnalyticsEventsClient,
|
||||
}
|
||||
|
||||
pub(crate) struct ExternalAgentConfigRequestProcessorArgs {
|
||||
pub(crate) outgoing: Arc<OutgoingMessageSender>,
|
||||
pub(crate) thread_manager: Arc<ThreadManager>,
|
||||
pub(crate) thread_store: Arc<dyn ThreadStore>,
|
||||
pub(crate) config_manager: ConfigManager,
|
||||
pub(crate) config_processor: ConfigRequestProcessor,
|
||||
pub(crate) state_db: Option<StateDbHandle>,
|
||||
pub(crate) analytics_events_client: AnalyticsEventsClient,
|
||||
pub(crate) arg0_paths: Arg0DispatchPaths,
|
||||
pub(crate) codex_home: PathBuf,
|
||||
}
|
||||
|
||||
impl ExternalAgentConfigRequestProcessor {
|
||||
pub(crate) fn new(args: ExternalAgentConfigRequestProcessorArgs) -> Self {
|
||||
let ExternalAgentConfigRequestProcessorArgs {
|
||||
outgoing,
|
||||
thread_manager,
|
||||
thread_store,
|
||||
config_manager,
|
||||
config_processor,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
arg0_paths,
|
||||
codex_home,
|
||||
} = args;
|
||||
let migration_service = ExternalAgentConfigService::new(
|
||||
codex_home.clone(),
|
||||
thread_manager.auth_manager(),
|
||||
analytics_events_client.clone(),
|
||||
state_db.clone(),
|
||||
);
|
||||
let session_importer = ExternalAgentSessionImporter::new(
|
||||
codex_home,
|
||||
migration_service.connector_metadata_roots().to_vec(),
|
||||
Arc::clone(&thread_manager),
|
||||
thread_store,
|
||||
config_manager.clone(),
|
||||
arg0_paths,
|
||||
);
|
||||
Self {
|
||||
outgoing,
|
||||
migration_service,
|
||||
session_importer,
|
||||
thread_manager,
|
||||
config_manager,
|
||||
config_processor,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn detect(
|
||||
&self,
|
||||
params: ExternalAgentConfigDetectParams,
|
||||
) -> Result<ExternalAgentConfigDetectResponse, JSONRPCErrorError> {
|
||||
let (include_memory, memory_version) = self.memory_import_settings().await;
|
||||
let migration_service = self
|
||||
.migration_service
|
||||
.with_migration_source(params.migration_source.as_deref())
|
||||
.with_memory_version(memory_version);
|
||||
let default_session_import_limits = ExternalAgentSessionImportLimits::default();
|
||||
let migration_service =
|
||||
migration_service.with_session_import_limits(ExternalAgentSessionImportLimits {
|
||||
max_age: params
|
||||
.max_session_age_days
|
||||
.map(|days| Duration::from_secs(u64::from(days) * 24 * 60 * 60))
|
||||
.unwrap_or(default_session_import_limits.max_age),
|
||||
max_sessions: params
|
||||
.max_sessions
|
||||
.map(|max_sessions| max_sessions as usize)
|
||||
.unwrap_or(default_session_import_limits.max_sessions),
|
||||
});
|
||||
let options = ExternalAgentConfigDetectOptions {
|
||||
include_home: params.include_home,
|
||||
include_memory,
|
||||
cwds: params.cwds,
|
||||
};
|
||||
let items = migration_service
|
||||
.detect(options)
|
||||
.await
|
||||
.map_err(|err| internal_error(err.to_string()))?;
|
||||
let sessions = items
|
||||
.iter()
|
||||
.filter_map(|item| item.details.as_ref())
|
||||
.flat_map(|details| details.sessions.iter().cloned())
|
||||
.collect::<Vec<_>>();
|
||||
let (connector_names_by_source_path, connectors) =
|
||||
detected_session_connectors(&migration_service, &sessions);
|
||||
record_detected_session_connectors(
|
||||
self.migration_service.codex_home(),
|
||||
connector_names_by_source_path,
|
||||
)
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to record detected connector candidates: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(detect_response(items, connectors))
|
||||
}
|
||||
|
||||
pub(crate) async fn import(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
params: ExternalAgentConfigImportParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let (include_memory, memory_version) = self.memory_import_settings().await;
|
||||
if params
|
||||
.migration_items
|
||||
.iter()
|
||||
.any(|item| item.item_type == ExternalAgentConfigMigrationItemType::Memory)
|
||||
&& !include_memory
|
||||
{
|
||||
return Err(invalid_request("external agent memory import is disabled"));
|
||||
}
|
||||
if params.migration_items.iter().any(|item| {
|
||||
item.item_type == ExternalAgentConfigMigrationItemType::Memory
|
||||
&& item
|
||||
.details
|
||||
.as_ref()
|
||||
.is_none_or(|details| details.memory.is_empty())
|
||||
}) {
|
||||
return Err(invalid_request(
|
||||
"memory import requires at least one selected memory",
|
||||
));
|
||||
}
|
||||
let import_id = Uuid::new_v4().to_string();
|
||||
let analytics_source = params.source.clone().unwrap_or_default();
|
||||
let provider_id = params.provider_id.clone();
|
||||
let migration_service = self
|
||||
.migration_service
|
||||
.with_migration_source(params.migration_source.as_deref())
|
||||
.with_memory_version(memory_version);
|
||||
let needs_runtime_refresh = migration_items_need_runtime_refresh(¶ms.migration_items);
|
||||
let has_migration_items = !params.migration_items.is_empty();
|
||||
let has_plugin_imports = params.migration_items.iter().any(|item| {
|
||||
matches!(
|
||||
item.item_type,
|
||||
ExternalAgentConfigMigrationItemType::Plugins
|
||||
)
|
||||
});
|
||||
let (pending_session_imports, session_validation_result) =
|
||||
self.validate_pending_session_imports(¶ms, &migration_service);
|
||||
let import_outcome = self
|
||||
.import_external_agent_config(params, &migration_service)
|
||||
.await;
|
||||
if needs_runtime_refresh {
|
||||
self.config_processor.handle_config_mutation().await;
|
||||
}
|
||||
self.outgoing
|
||||
.send_response(
|
||||
request_id,
|
||||
ExternalAgentConfigImportResponse {
|
||||
import_id: import_id.clone(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
if !has_migration_items {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut completed_item_results = Vec::new();
|
||||
if let Some(session_validation_result) = session_validation_result {
|
||||
send_import_progress(&self.outgoing, &import_id, &session_validation_result).await;
|
||||
completed_item_results.push(session_validation_result);
|
||||
}
|
||||
for item_result in import_outcome.item_results {
|
||||
send_import_progress(&self.outgoing, &import_id, &item_result).await;
|
||||
completed_item_results.push(item_result);
|
||||
}
|
||||
|
||||
let has_background_imports = !import_outcome.pending_plugin_imports.is_empty()
|
||||
|| !pending_session_imports.is_empty();
|
||||
if !has_background_imports {
|
||||
send_completed_import_notification(
|
||||
&self.outgoing,
|
||||
self.state_db.as_ref(),
|
||||
&self.analytics_events_client,
|
||||
import_id,
|
||||
analytics_source,
|
||||
provider_id,
|
||||
&completed_item_results,
|
||||
)
|
||||
.await;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let session_importer = self.session_importer.clone();
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let state_db = self.state_db.clone();
|
||||
let analytics_events_client = self.analytics_events_client.clone();
|
||||
let thread_manager = Arc::clone(&self.thread_manager);
|
||||
let session_metadata_mode = migration_service.session_metadata_mode();
|
||||
let plugin_migration_service = migration_service;
|
||||
let session_import_result = (!pending_session_imports.is_empty()).then(|| {
|
||||
CoreImportItemResult::new(
|
||||
CoreMigrationItemType::Sessions,
|
||||
"Import sessions".to_string(),
|
||||
/*cwd*/ None,
|
||||
)
|
||||
});
|
||||
let pending_plugin_imports = import_outcome.pending_plugin_imports;
|
||||
tokio::spawn(async move {
|
||||
let connector_names_by_source_path =
|
||||
detected_session_connectors(&plugin_migration_service, &pending_session_imports).0;
|
||||
let session_progress_outgoing = Arc::clone(&outgoing);
|
||||
let session_import_id = import_id.clone();
|
||||
let session_imports = async move {
|
||||
let session_import_result = session_import_result?;
|
||||
let item_result = session_importer
|
||||
.import_sessions(
|
||||
pending_session_imports,
|
||||
session_import_result,
|
||||
session_metadata_mode,
|
||||
connector_names_by_source_path,
|
||||
)
|
||||
.await;
|
||||
send_import_progress(&session_progress_outgoing, &session_import_id, &item_result)
|
||||
.await;
|
||||
Some(item_result)
|
||||
};
|
||||
let plugin_progress_outgoing = Arc::clone(&outgoing);
|
||||
let plugin_import_id = import_id.clone();
|
||||
let plugin_imports = async move {
|
||||
let mut item_results = Vec::new();
|
||||
for pending_plugin_import in pending_plugin_imports {
|
||||
let mut item_result = CoreImportItemResult::new(
|
||||
CoreMigrationItemType::Plugins,
|
||||
pending_plugin_import.description.clone(),
|
||||
pending_plugin_import.cwd.clone(),
|
||||
);
|
||||
match plugin_migration_service
|
||||
.import_plugins(
|
||||
pending_plugin_import.cwd.as_deref(),
|
||||
Some(pending_plugin_import.details),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plugin_outcome) => {
|
||||
apply_plugin_outcome_to_item_result(&mut item_result, plugin_outcome);
|
||||
}
|
||||
Err(error) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"plugin_import",
|
||||
/*sub_error_type*/ None,
|
||||
error.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
}
|
||||
}
|
||||
send_import_progress(
|
||||
&plugin_progress_outgoing,
|
||||
&plugin_import_id,
|
||||
&item_result,
|
||||
)
|
||||
.await;
|
||||
item_results.push(item_result);
|
||||
}
|
||||
item_results
|
||||
};
|
||||
let (session_result, plugin_results) = tokio::join!(session_imports, plugin_imports);
|
||||
let mut background_item_results = Vec::new();
|
||||
if let Some(session_result) = session_result {
|
||||
background_item_results.push(session_result);
|
||||
}
|
||||
background_item_results.extend(plugin_results);
|
||||
completed_item_results.extend(background_item_results);
|
||||
if has_plugin_imports {
|
||||
thread_manager.plugins_manager().clear_cache();
|
||||
thread_manager.skills_service().clear_cache();
|
||||
}
|
||||
send_completed_import_notification(
|
||||
&outgoing,
|
||||
state_db.as_ref(),
|
||||
&analytics_events_client,
|
||||
import_id,
|
||||
analytics_source,
|
||||
provider_id,
|
||||
&completed_item_results,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn memory_import_settings(&self) -> (bool, MemoryVersion) {
|
||||
let config = match self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
error = %err,
|
||||
"failed to reload config for external agent memory import detection"
|
||||
);
|
||||
return (false, MemoryVersion::V1);
|
||||
}
|
||||
};
|
||||
(
|
||||
config.features.enabled(Feature::ExternalAgentMemoryImport),
|
||||
config.memories.version,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn read_import_histories(
|
||||
&self,
|
||||
) -> Result<ExternalAgentConfigImportHistoriesReadResponse, JSONRPCErrorError> {
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("state database is unavailable"))?;
|
||||
let histories = state_db
|
||||
.external_agent_config_import_history_records()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to read import histories: {err}")))?;
|
||||
let data = histories
|
||||
.into_iter()
|
||||
.map(protocol_import_history)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let connectors = read_imported_connector_candidates(self.migration_service.codex_home())
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to read imported connector candidates: {err}"
|
||||
))
|
||||
})?
|
||||
.into_iter()
|
||||
.map(|candidate| ExternalAgentImportedConnectorCandidate {
|
||||
name: candidate.name,
|
||||
session_count: candidate.session_count,
|
||||
source: ExternalAgentImportedConnectorSource::RemoteMcpServersConfig,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ExternalAgentConfigImportHistoriesReadResponse { data, connectors })
|
||||
}
|
||||
|
||||
pub(crate) async fn record_import_history(
|
||||
&self,
|
||||
params: ExternalAgentConfigImportHistoryRecordParams,
|
||||
) -> Result<ExternalAgentConfigImportHistoryRecordResponse, JSONRPCErrorError> {
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("state database is unavailable"))?;
|
||||
let import_id = Uuid::new_v4().to_string();
|
||||
let item_type_results = params
|
||||
.item_type_results
|
||||
.into_iter()
|
||||
.map(|type_result| ProtocolImportTypeResult {
|
||||
item_type: type_result.item_type,
|
||||
successes: type_result
|
||||
.successes
|
||||
.into_iter()
|
||||
.map(|success| ProtocolImportSuccess {
|
||||
item_type: success.item_type,
|
||||
cwd: success.cwd,
|
||||
source: success.source,
|
||||
target: success.target,
|
||||
title: success.title,
|
||||
})
|
||||
.collect(),
|
||||
failures: type_result.failures,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
record_import_history(
|
||||
state_db,
|
||||
import_id.as_str(),
|
||||
Some(params.provider_id.as_str()),
|
||||
&item_type_results,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to record import history: {err}")))?;
|
||||
|
||||
Ok(ExternalAgentConfigImportHistoryRecordResponse { import_id })
|
||||
}
|
||||
|
||||
fn validate_pending_session_imports(
|
||||
&self,
|
||||
params: &ExternalAgentConfigImportParams,
|
||||
migration_service: &ExternalAgentConfigService,
|
||||
) -> (Vec<CoreSessionMigration>, Option<CoreImportItemResult>) {
|
||||
let sessions = params
|
||||
.migration_items
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
matches!(
|
||||
item.item_type,
|
||||
ExternalAgentConfigMigrationItemType::Sessions
|
||||
)
|
||||
})
|
||||
.filter_map(|item| item.details.as_ref())
|
||||
.flat_map(|details| details.sessions.clone())
|
||||
.map(|session| CoreSessionMigration {
|
||||
path: session.path,
|
||||
cwd: session.cwd,
|
||||
title: session.title,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if sessions.is_empty() {
|
||||
return (Vec::new(), None);
|
||||
}
|
||||
let mut item_result = CoreImportItemResult::new(
|
||||
CoreMigrationItemType::Sessions,
|
||||
"Validate session imports".to_string(),
|
||||
/*cwd*/ None,
|
||||
);
|
||||
let mut selected_session_paths = HashSet::new();
|
||||
let mut selected_sessions = Vec::new();
|
||||
for session in sessions {
|
||||
let canonical_path =
|
||||
match migration_service.external_agent_session_source_path(&session.path) {
|
||||
Ok(Some(canonical_path)) => canonical_path,
|
||||
Ok(None) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_missing",
|
||||
Some("session_not_detected"),
|
||||
format!(
|
||||
"external agent session was not detected for import: {}",
|
||||
session.path.display()
|
||||
),
|
||||
Some(session.path.display().to_string()),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(err) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_source_path",
|
||||
Some("failed_to_resolve_session_source_path"),
|
||||
err.to_string(),
|
||||
Some(session.path.display().to_string()),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if selected_session_paths.insert(canonical_path) {
|
||||
selected_sessions.push(session);
|
||||
}
|
||||
}
|
||||
(selected_sessions, Some(item_result))
|
||||
}
|
||||
|
||||
async fn import_external_agent_config(
|
||||
&self,
|
||||
params: ExternalAgentConfigImportParams,
|
||||
migration_service: &ExternalAgentConfigService,
|
||||
) -> CoreImportOutcome {
|
||||
migration_service
|
||||
.import(core_migration_items(
|
||||
params
|
||||
.migration_items
|
||||
.into_iter()
|
||||
.filter(|item| item.item_type != ExternalAgentConfigMigrationItemType::Sessions)
|
||||
.collect(),
|
||||
))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_import_progress(
|
||||
outgoing: &OutgoingMessageSender,
|
||||
import_id: &str,
|
||||
item_result: &CoreImportItemResult,
|
||||
) {
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ExternalAgentConfigImportProgress(
|
||||
ExternalAgentConfigImportProgressNotification {
|
||||
import_id: import_id.to_string(),
|
||||
item_type_results: vec![protocol_import_type_result(item_result)],
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn send_completed_import_notification(
|
||||
outgoing: &OutgoingMessageSender,
|
||||
state_db: Option<&StateDbHandle>,
|
||||
analytics_events_client: &AnalyticsEventsClient,
|
||||
import_id: String,
|
||||
analytics_source: String,
|
||||
provider_id: Option<String>,
|
||||
item_results: &[CoreImportItemResult],
|
||||
) {
|
||||
let notification = completed_notification(import_id, item_results);
|
||||
log_completed_import_failures(¬ification);
|
||||
track_completed_import_notification(
|
||||
analytics_events_client,
|
||||
&analytics_source,
|
||||
provider_id.as_deref().unwrap_or_default(),
|
||||
¬ification,
|
||||
);
|
||||
if let Some(state_db) = state_db
|
||||
&& let Err(err) =
|
||||
record_completed_import_notification(state_db, provider_id.as_deref(), ¬ification)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
import_id = %notification.import_id,
|
||||
error = %err,
|
||||
"failed to record external agent config import completion"
|
||||
);
|
||||
}
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ExternalAgentConfigImportCompleted(
|
||||
notification,
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
fn log_completed_import_failures(notification: &ExternalAgentConfigImportCompletedNotification) {
|
||||
for type_result in ¬ification.item_type_results {
|
||||
for failure in &type_result.failures {
|
||||
let error_type = import_failure_error_type(failure);
|
||||
tracing::warn!(
|
||||
import_id = %notification.import_id,
|
||||
item_type = ?failure.item_type,
|
||||
error_type = %error_type,
|
||||
failure_stage = %failure.failure_stage,
|
||||
cwd = ?failure.cwd,
|
||||
source = ?failure.source,
|
||||
error = %failure.message,
|
||||
"external agent config migration item failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn track_completed_import_notification(
|
||||
analytics_events_client: &AnalyticsEventsClient,
|
||||
analytics_source: &str,
|
||||
provider_id: &str,
|
||||
notification: &ExternalAgentConfigImportCompletedNotification,
|
||||
) {
|
||||
for type_result in ¬ification.item_type_results {
|
||||
let item_type = analytics_migration_item_type(type_result.item_type).to_string();
|
||||
analytics_events_client.track_external_agent_config_import_completed(
|
||||
ExternalAgentConfigImportCompletedInput {
|
||||
import_id: notification.import_id.clone(),
|
||||
source: analytics_source.to_string(),
|
||||
provider_id: provider_id.to_string(),
|
||||
item_type: item_type.clone(),
|
||||
success_count: type_result.successes.len(),
|
||||
failed_count: type_result.failures.len(),
|
||||
},
|
||||
);
|
||||
for failure in &type_result.failures {
|
||||
analytics_events_client.track_external_agent_config_import_failure(
|
||||
ExternalAgentConfigImportFailureInput {
|
||||
import_id: notification.import_id.clone(),
|
||||
source: analytics_source.to_string(),
|
||||
provider_id: provider_id.to_string(),
|
||||
item_type: item_type.clone(),
|
||||
failure_stage: failure.failure_stage.clone(),
|
||||
error_type: import_failure_error_type(failure),
|
||||
sub_error_type: failure.sub_error_type.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn import_failure_error_type(failure: &ProtocolImportFailure) -> String {
|
||||
failure
|
||||
.error_type
|
||||
.clone()
|
||||
.unwrap_or_else(|| failure.failure_stage.clone())
|
||||
}
|
||||
|
||||
fn analytics_migration_item_type(item_type: ExternalAgentConfigMigrationItemType) -> &'static str {
|
||||
match item_type {
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => "AGENTS_MD",
|
||||
ExternalAgentConfigMigrationItemType::Config => "CONFIG",
|
||||
ExternalAgentConfigMigrationItemType::Skills => "SKILLS",
|
||||
ExternalAgentConfigMigrationItemType::Plugins => "PLUGINS",
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => "MCP_SERVER_CONFIG",
|
||||
ExternalAgentConfigMigrationItemType::Subagents => "SUBAGENTS",
|
||||
ExternalAgentConfigMigrationItemType::Hooks => "HOOKS",
|
||||
ExternalAgentConfigMigrationItemType::Commands => "COMMANDS",
|
||||
ExternalAgentConfigMigrationItemType::Memory => "MEMORY",
|
||||
ExternalAgentConfigMigrationItemType::Sessions => "SESSIONS",
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_completed_import_notification(
|
||||
state_db: &StateDbHandle,
|
||||
provider_id: Option<&str>,
|
||||
notification: &ExternalAgentConfigImportCompletedNotification,
|
||||
) -> anyhow::Result<()> {
|
||||
record_import_history(
|
||||
state_db,
|
||||
notification.import_id.as_str(),
|
||||
provider_id,
|
||||
¬ification.item_type_results,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn record_import_history(
|
||||
state_db: &StateDbHandle,
|
||||
import_id: &str,
|
||||
provider_id: Option<&str>,
|
||||
item_type_results: &[ProtocolImportTypeResult],
|
||||
) -> anyhow::Result<()> {
|
||||
let successes = item_type_results
|
||||
.iter()
|
||||
.flat_map(|type_result| type_result.successes.iter())
|
||||
.map(|success| {
|
||||
Ok(ExternalAgentConfigImportSuccessRecord {
|
||||
item_type: serde_json::from_value(serde_json::to_value(success.item_type)?)?,
|
||||
cwd: success.cwd.clone(),
|
||||
source: success.source.clone(),
|
||||
target: success.target.clone(),
|
||||
title: success.title.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
let failures = item_type_results
|
||||
.iter()
|
||||
.flat_map(|type_result| type_result.failures.iter())
|
||||
.map(|failure| {
|
||||
Ok(ExternalAgentConfigImportFailureRecord {
|
||||
item_type: serde_json::from_value(serde_json::to_value(failure.item_type)?)?,
|
||||
error_type: failure.error_type.clone(),
|
||||
sub_error_type: failure.sub_error_type.clone(),
|
||||
failure_stage: failure.failure_stage.clone(),
|
||||
message: failure.message.clone(),
|
||||
cwd: failure.cwd.clone(),
|
||||
source: failure.source.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
state_db
|
||||
.record_external_agent_config_import_completed(
|
||||
import_id,
|
||||
provider_id,
|
||||
&successes,
|
||||
&failures,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn detected_session_connectors(
|
||||
migration_service: &ExternalAgentConfigService,
|
||||
sessions: &[CoreSessionMigration],
|
||||
) -> (
|
||||
BTreeMap<PathBuf, Vec<String>>,
|
||||
Vec<DetectedConnectorCandidate>,
|
||||
) {
|
||||
let mut connector_names_by_source_path = BTreeMap::new();
|
||||
let mut connectors_by_name = BTreeMap::<String, DetectedConnectorCandidate>::new();
|
||||
let sessions = sessions
|
||||
.iter()
|
||||
.filter(|session| session.path.is_file())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
for (source_path, session_connectors) in
|
||||
migration_service.detect_session_connectors_by_source_path(&sessions)
|
||||
{
|
||||
connector_names_by_source_path.insert(
|
||||
source_path,
|
||||
session_connectors
|
||||
.iter()
|
||||
.map(|candidate| candidate.name.clone())
|
||||
.collect(),
|
||||
);
|
||||
for candidate in session_connectors {
|
||||
let key = candidate.name.to_lowercase();
|
||||
let session_count = candidate.session_count;
|
||||
let connector = connectors_by_name.entry(key).or_insert_with(|| {
|
||||
let mut connector = candidate;
|
||||
connector.session_count = 0;
|
||||
connector
|
||||
});
|
||||
connector.session_count = connector.session_count.saturating_add(session_count);
|
||||
}
|
||||
}
|
||||
(
|
||||
connector_names_by_source_path,
|
||||
connectors_by_name.into_values().collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn apply_plugin_outcome_to_item_result(
|
||||
item_result: &mut CoreImportItemResult,
|
||||
plugin_outcome: PluginImportOutcome,
|
||||
) {
|
||||
for plugin_id in plugin_outcome.succeeded_plugin_ids {
|
||||
item_result.record_success(
|
||||
Some(plugin_id.clone()),
|
||||
Some(plugin_id),
|
||||
/*title*/ None,
|
||||
);
|
||||
}
|
||||
for raw_error in plugin_outcome.raw_errors {
|
||||
item_result.record_error(raw_error);
|
||||
}
|
||||
}
|
||||
|
||||
fn migration_items_need_runtime_refresh(items: &[ExternalAgentConfigMigrationItem]) -> bool {
|
||||
items.iter().any(|item| {
|
||||
matches!(
|
||||
item.item_type,
|
||||
ExternalAgentConfigMigrationItemType::Config
|
||||
| ExternalAgentConfigMigrationItemType::Skills
|
||||
| ExternalAgentConfigMigrationItemType::McpServerConfig
|
||||
| ExternalAgentConfigMigrationItemType::Hooks
|
||||
| ExternalAgentConfigMigrationItemType::Commands
|
||||
| ExternalAgentConfigMigrationItemType::Plugins
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "processor_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,40 @@
|
||||
use super::*;
|
||||
|
||||
fn migration_item(
|
||||
item_type: ExternalAgentConfigMigrationItemType,
|
||||
) -> ExternalAgentConfigMigrationItem {
|
||||
ExternalAgentConfigMigrationItem {
|
||||
item_type,
|
||||
description: String::new(),
|
||||
cwd: None,
|
||||
details: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_items_that_update_runtime_sources_trigger_refresh() {
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Config,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Skills,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Hooks,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Commands,
|
||||
)]));
|
||||
assert!(migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Plugins,
|
||||
)]));
|
||||
assert!(!migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Memory,
|
||||
)]));
|
||||
assert!(!migration_items_need_runtime_refresh(&[migration_item(
|
||||
ExternalAgentConfigMigrationItemType::Sessions,
|
||||
)]));
|
||||
}
|
||||
366
codex-rs/app-server/src/external_agent_migration/protocol.rs
Normal file
366
codex-rs/app-server/src/external_agent_migration/protocol.rs
Normal file
@@ -0,0 +1,366 @@
|
||||
use crate::error_code::internal_error;
|
||||
use codex_app_server_protocol::CommandMigration;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistory;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeFailure as ProtocolImportFailure;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeSuccess as ProtocolImportSuccess;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportTypeResult as ProtocolImportTypeResult;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItemType;
|
||||
use codex_app_server_protocol::ExternalAgentDetectedConnectorCandidate;
|
||||
use codex_app_server_protocol::ExternalAgentDetectedConnectorSource;
|
||||
use codex_app_server_protocol::HookMigration;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::McpServerMigration;
|
||||
use codex_app_server_protocol::MigrationDetails;
|
||||
use codex_app_server_protocol::PluginsMigration;
|
||||
use codex_app_server_protocol::SkillMigration;
|
||||
use codex_app_server_protocol::SubagentMigration;
|
||||
use codex_external_agent_migration::DetectedConnectorCandidate as CoreDetectedConnectorCandidate;
|
||||
use codex_external_agent_migration::DetectedConnectorSource as CoreDetectedConnectorSource;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportItemResult as CoreImportItemResult;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportRawError as CoreImportRawError;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportSuccess;
|
||||
use codex_external_agent_migration::ExternalAgentConfigMigrationItem as CoreMigrationItem;
|
||||
use codex_external_agent_migration::ExternalAgentConfigMigrationItemType as CoreMigrationItemType;
|
||||
use codex_external_agent_migration::MigrationDetails as CoreMigrationDetails;
|
||||
use codex_external_agent_migration::NamedMigration;
|
||||
use codex_external_agent_migration::PluginsMigration as CorePluginsMigration;
|
||||
use codex_external_agent_migration::sessions::ExternalAgentSessionMigration;
|
||||
use codex_state::ExternalAgentConfigImportFailureRecord;
|
||||
use codex_state::ExternalAgentConfigImportSuccessRecord;
|
||||
|
||||
pub(super) fn detect_response(
|
||||
items: Vec<CoreMigrationItem>,
|
||||
connectors: Vec<CoreDetectedConnectorCandidate>,
|
||||
) -> ExternalAgentConfigDetectResponse {
|
||||
ExternalAgentConfigDetectResponse {
|
||||
items: items.into_iter().map(protocol_migration_item).collect(),
|
||||
connectors: connectors
|
||||
.into_iter()
|
||||
.map(|candidate| ExternalAgentDetectedConnectorCandidate {
|
||||
name: candidate.name,
|
||||
session_count: candidate.session_count,
|
||||
source: match candidate.source {
|
||||
CoreDetectedConnectorSource::RemoteMcpServersConfig => {
|
||||
ExternalAgentDetectedConnectorSource::RemoteMcpServersConfig
|
||||
}
|
||||
CoreDetectedConnectorSource::SessionToolUse => {
|
||||
ExternalAgentDetectedConnectorSource::SessionToolUse
|
||||
}
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_migration_item(item: CoreMigrationItem) -> ExternalAgentConfigMigrationItem {
|
||||
ExternalAgentConfigMigrationItem {
|
||||
item_type: protocol_migration_item_type(item.item_type),
|
||||
description: item.description,
|
||||
cwd: item.cwd,
|
||||
details: item.details.map(protocol_migration_details),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_migration_details(details: CoreMigrationDetails) -> MigrationDetails {
|
||||
MigrationDetails {
|
||||
plugins: details
|
||||
.plugins
|
||||
.into_iter()
|
||||
.map(|plugin| PluginsMigration {
|
||||
marketplace_name: plugin.marketplace_name,
|
||||
plugin_names: plugin.plugin_names,
|
||||
})
|
||||
.collect(),
|
||||
skills: details
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| SkillMigration { name: skill.name })
|
||||
.collect(),
|
||||
sessions: details
|
||||
.sessions
|
||||
.into_iter()
|
||||
.map(|session| codex_app_server_protocol::SessionMigration {
|
||||
path: session.path,
|
||||
cwd: session.cwd,
|
||||
title: session.title,
|
||||
})
|
||||
.collect(),
|
||||
mcp_servers: details
|
||||
.mcp_servers
|
||||
.into_iter()
|
||||
.map(|server| McpServerMigration { name: server.name })
|
||||
.collect(),
|
||||
hooks: details
|
||||
.hooks
|
||||
.into_iter()
|
||||
.map(|hook| HookMigration { name: hook.name })
|
||||
.collect(),
|
||||
subagents: details
|
||||
.subagents
|
||||
.into_iter()
|
||||
.map(|subagent| SubagentMigration {
|
||||
name: subagent.name,
|
||||
})
|
||||
.collect(),
|
||||
commands: details
|
||||
.commands
|
||||
.into_iter()
|
||||
.map(|command| CommandMigration { name: command.name })
|
||||
.collect(),
|
||||
memory: details.memory,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn core_migration_items(
|
||||
items: Vec<ExternalAgentConfigMigrationItem>,
|
||||
) -> Vec<CoreMigrationItem> {
|
||||
items
|
||||
.into_iter()
|
||||
.map(|item| CoreMigrationItem {
|
||||
item_type: core_migration_item_type(item.item_type),
|
||||
description: item.description,
|
||||
cwd: item.cwd,
|
||||
details: item.details.map(core_migration_details),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn core_migration_details(details: MigrationDetails) -> CoreMigrationDetails {
|
||||
CoreMigrationDetails {
|
||||
plugins: details
|
||||
.plugins
|
||||
.into_iter()
|
||||
.map(|plugin| CorePluginsMigration {
|
||||
marketplace_name: plugin.marketplace_name,
|
||||
plugin_names: plugin.plugin_names,
|
||||
})
|
||||
.collect(),
|
||||
skills: details
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| NamedMigration { name: skill.name })
|
||||
.collect(),
|
||||
sessions: details
|
||||
.sessions
|
||||
.into_iter()
|
||||
.map(|session| ExternalAgentSessionMigration {
|
||||
path: session.path,
|
||||
cwd: session.cwd,
|
||||
title: session.title,
|
||||
})
|
||||
.collect(),
|
||||
mcp_servers: details
|
||||
.mcp_servers
|
||||
.into_iter()
|
||||
.map(|server| NamedMigration { name: server.name })
|
||||
.collect(),
|
||||
hooks: details
|
||||
.hooks
|
||||
.into_iter()
|
||||
.map(|hook| NamedMigration { name: hook.name })
|
||||
.collect(),
|
||||
subagents: details
|
||||
.subagents
|
||||
.into_iter()
|
||||
.map(|subagent| NamedMigration {
|
||||
name: subagent.name,
|
||||
})
|
||||
.collect(),
|
||||
commands: details
|
||||
.commands
|
||||
.into_iter()
|
||||
.map(|command| NamedMigration { name: command.name })
|
||||
.collect(),
|
||||
memory: details.memory,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn protocol_migration_item_type(
|
||||
item_type: CoreMigrationItemType,
|
||||
) -> ExternalAgentConfigMigrationItemType {
|
||||
match item_type {
|
||||
CoreMigrationItemType::Config => ExternalAgentConfigMigrationItemType::Config,
|
||||
CoreMigrationItemType::Skills => ExternalAgentConfigMigrationItemType::Skills,
|
||||
CoreMigrationItemType::AgentsMd => ExternalAgentConfigMigrationItemType::AgentsMd,
|
||||
CoreMigrationItemType::Plugins => ExternalAgentConfigMigrationItemType::Plugins,
|
||||
CoreMigrationItemType::McpServerConfig => {
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig
|
||||
}
|
||||
CoreMigrationItemType::Subagents => ExternalAgentConfigMigrationItemType::Subagents,
|
||||
CoreMigrationItemType::Hooks => ExternalAgentConfigMigrationItemType::Hooks,
|
||||
CoreMigrationItemType::Commands => ExternalAgentConfigMigrationItemType::Commands,
|
||||
CoreMigrationItemType::Memory => ExternalAgentConfigMigrationItemType::Memory,
|
||||
CoreMigrationItemType::Sessions => ExternalAgentConfigMigrationItemType::Sessions,
|
||||
}
|
||||
}
|
||||
|
||||
fn core_migration_item_type(
|
||||
item_type: ExternalAgentConfigMigrationItemType,
|
||||
) -> CoreMigrationItemType {
|
||||
match item_type {
|
||||
ExternalAgentConfigMigrationItemType::Config => CoreMigrationItemType::Config,
|
||||
ExternalAgentConfigMigrationItemType::Skills => CoreMigrationItemType::Skills,
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => CoreMigrationItemType::AgentsMd,
|
||||
ExternalAgentConfigMigrationItemType::Plugins => CoreMigrationItemType::Plugins,
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => {
|
||||
CoreMigrationItemType::McpServerConfig
|
||||
}
|
||||
ExternalAgentConfigMigrationItemType::Subagents => CoreMigrationItemType::Subagents,
|
||||
ExternalAgentConfigMigrationItemType::Hooks => CoreMigrationItemType::Hooks,
|
||||
ExternalAgentConfigMigrationItemType::Commands => CoreMigrationItemType::Commands,
|
||||
ExternalAgentConfigMigrationItemType::Memory => CoreMigrationItemType::Memory,
|
||||
ExternalAgentConfigMigrationItemType::Sessions => CoreMigrationItemType::Sessions,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn protocol_import_history(
|
||||
record: codex_state::ExternalAgentConfigImportHistoryRecord,
|
||||
) -> Result<ExternalAgentConfigImportHistory, JSONRPCErrorError> {
|
||||
let successes = record
|
||||
.successes
|
||||
.into_iter()
|
||||
.map(protocol_import_success_record)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let failures = record
|
||||
.failures
|
||||
.into_iter()
|
||||
.map(protocol_import_failure_record)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(ExternalAgentConfigImportHistory {
|
||||
import_id: record.import_id,
|
||||
provider_id: record.provider_id,
|
||||
completed_at_ms: record.completed_at_ms,
|
||||
successes,
|
||||
failures,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_success_record(
|
||||
record: ExternalAgentConfigImportSuccessRecord,
|
||||
) -> Result<ProtocolImportSuccess, JSONRPCErrorError> {
|
||||
Ok(ProtocolImportSuccess {
|
||||
item_type: protocol_import_record_item_type(record.item_type)?,
|
||||
cwd: record.cwd,
|
||||
source: record.source,
|
||||
target: record.target,
|
||||
title: record.title,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_failure_record(
|
||||
record: ExternalAgentConfigImportFailureRecord,
|
||||
) -> Result<ProtocolImportFailure, JSONRPCErrorError> {
|
||||
Ok(ProtocolImportFailure {
|
||||
item_type: protocol_import_record_item_type(record.item_type)?,
|
||||
error_type: record.error_type,
|
||||
sub_error_type: record.sub_error_type,
|
||||
failure_stage: record.failure_stage,
|
||||
message: record.message,
|
||||
cwd: record.cwd,
|
||||
source: record.source,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_record_item_type(
|
||||
item_type: String,
|
||||
) -> Result<ExternalAgentConfigMigrationItemType, JSONRPCErrorError> {
|
||||
serde_json::from_value(serde_json::Value::String(item_type.clone())).map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to decode import item type {item_type}: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn completed_notification(
|
||||
import_id: String,
|
||||
item_results: &[CoreImportItemResult],
|
||||
) -> ExternalAgentConfigImportCompletedNotification {
|
||||
let mut protocol_type_results: Vec<ProtocolImportTypeResult> = Vec::new();
|
||||
for item_result in item_results {
|
||||
let item_raw_errors = item_result
|
||||
.raw_errors
|
||||
.iter()
|
||||
.map(protocol_import_raw_error)
|
||||
.collect::<Vec<_>>();
|
||||
let item_successes = item_result
|
||||
.successes
|
||||
.iter()
|
||||
.map(protocol_import_success)
|
||||
.collect::<Vec<_>>();
|
||||
let item_type = protocol_migration_item_type(item_result.item_type);
|
||||
if let Some(type_result) = protocol_type_results
|
||||
.iter_mut()
|
||||
.find(|type_result| type_result.item_type == item_type)
|
||||
{
|
||||
type_result.successes.extend(item_successes);
|
||||
type_result.failures.extend(item_raw_errors);
|
||||
} else {
|
||||
protocol_type_results.push(ProtocolImportTypeResult {
|
||||
item_type,
|
||||
successes: item_successes,
|
||||
failures: item_raw_errors,
|
||||
});
|
||||
}
|
||||
}
|
||||
protocol_type_results.sort_by_key(|type_result| match type_result.item_type {
|
||||
ExternalAgentConfigMigrationItemType::Config => 0,
|
||||
ExternalAgentConfigMigrationItemType::Skills => 1,
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => 2,
|
||||
ExternalAgentConfigMigrationItemType::Plugins => 3,
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => 4,
|
||||
ExternalAgentConfigMigrationItemType::Subagents => 5,
|
||||
ExternalAgentConfigMigrationItemType::Hooks => 6,
|
||||
ExternalAgentConfigMigrationItemType::Commands => 7,
|
||||
ExternalAgentConfigMigrationItemType::Sessions => 8,
|
||||
ExternalAgentConfigMigrationItemType::Memory => 9,
|
||||
});
|
||||
|
||||
ExternalAgentConfigImportCompletedNotification {
|
||||
import_id,
|
||||
item_type_results: protocol_type_results,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn protocol_import_type_result(
|
||||
item_result: &CoreImportItemResult,
|
||||
) -> ProtocolImportTypeResult {
|
||||
ProtocolImportTypeResult {
|
||||
item_type: protocol_migration_item_type(item_result.item_type),
|
||||
successes: item_result
|
||||
.successes
|
||||
.iter()
|
||||
.map(protocol_import_success)
|
||||
.collect(),
|
||||
failures: item_result
|
||||
.raw_errors
|
||||
.iter()
|
||||
.map(protocol_import_raw_error)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_import_success(success: &ExternalAgentConfigImportSuccess) -> ProtocolImportSuccess {
|
||||
ProtocolImportSuccess {
|
||||
item_type: protocol_migration_item_type(success.item_type),
|
||||
cwd: success.cwd.clone(),
|
||||
source: success.source.clone(),
|
||||
target: success.target.clone(),
|
||||
title: success.title.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_import_raw_error(raw_error: &CoreImportRawError) -> ProtocolImportFailure {
|
||||
ProtocolImportFailure {
|
||||
item_type: protocol_migration_item_type(raw_error.item_type),
|
||||
error_type: raw_error.error_type.clone(),
|
||||
sub_error_type: raw_error.sub_error_type.clone(),
|
||||
failure_stage: raw_error.failure_stage.clone(),
|
||||
message: raw_error.message.clone(),
|
||||
cwd: raw_error.cwd.clone(),
|
||||
source: raw_error.source.clone(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,624 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_external_agent_migration::ExternalAgentConfigImportItemResult;
|
||||
use codex_external_agent_migration::record_import_error;
|
||||
use codex_external_agent_migration::sessions::CompletedExternalAgentSessionImport;
|
||||
use codex_external_agent_migration::sessions::ExistingSessionAppend;
|
||||
use codex_external_agent_migration::sessions::ExternalAgentSessionMigration;
|
||||
use codex_external_agent_migration::sessions::ImportedExternalAgentSession;
|
||||
use codex_external_agent_migration::sessions::ImportedSessionConnectorAttribution;
|
||||
use codex_external_agent_migration::sessions::PendingSessionImport;
|
||||
use codex_external_agent_migration::sessions::SessionImportTarget;
|
||||
use codex_external_agent_migration::sessions::SessionMetadataMode;
|
||||
use codex_external_agent_migration::sessions::append_existing_session;
|
||||
use codex_external_agent_migration::sessions::append_imported_session_connector_names;
|
||||
use codex_external_agent_migration::sessions::detect_imported_cla_session_connectors_by_source_path;
|
||||
use codex_external_agent_migration::sessions::prepare_validated_session_import_with_metadata_mode;
|
||||
use codex_external_agent_migration::sessions::record_completed_session_imports;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_prompts::render_model_instructions;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::BaseInstructionsProvenance;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::into_persisted_rollout_items;
|
||||
use codex_thread_store::AppendThreadItemsParams;
|
||||
use codex_thread_store::CreateThreadParams;
|
||||
use codex_thread_store::PersistContext;
|
||||
use codex_thread_store::ThreadMetadataPatch;
|
||||
use codex_thread_store::ThreadPersistenceMetadata;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use codex_thread_store::UpdateThreadMetadataParams;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
|
||||
const SESSION_IMPORT_CONCURRENCY: usize = 5;
|
||||
|
||||
struct CompletedSessionImport {
|
||||
cwd: PathBuf,
|
||||
import: CompletedExternalAgentSessionImport,
|
||||
connector_attribution: Option<ImportedSessionConnectorAttribution>,
|
||||
}
|
||||
|
||||
enum SessionImportOutcome {
|
||||
Created(CompletedSessionImport),
|
||||
Appended {
|
||||
cwd: PathBuf,
|
||||
source_path: PathBuf,
|
||||
imported_thread_id: ThreadId,
|
||||
title: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ExternalAgentSessionImporter {
|
||||
codex_home: PathBuf,
|
||||
connector_metadata_roots: Vec<PathBuf>,
|
||||
permits: Arc<Semaphore>,
|
||||
append_checkpoint_permits: Arc<Semaphore>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
config_manager: ConfigManager,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
}
|
||||
|
||||
impl ExternalAgentSessionImporter {
|
||||
pub(super) fn new(
|
||||
codex_home: PathBuf,
|
||||
connector_metadata_roots: Vec<PathBuf>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
config_manager: ConfigManager,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
) -> Self {
|
||||
Self {
|
||||
codex_home,
|
||||
connector_metadata_roots,
|
||||
permits: Arc::new(Semaphore::new(1)),
|
||||
append_checkpoint_permits: Arc::new(Semaphore::new(1)),
|
||||
thread_manager,
|
||||
thread_store,
|
||||
config_manager,
|
||||
arg0_paths,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn import_sessions(
|
||||
&self,
|
||||
sessions: Vec<ExternalAgentSessionMigration>,
|
||||
mut item_result: ExternalAgentConfigImportItemResult,
|
||||
metadata_mode: SessionMetadataMode,
|
||||
mut connector_names_by_source_path: BTreeMap<PathBuf, Vec<String>>,
|
||||
) -> ExternalAgentConfigImportItemResult {
|
||||
if sessions.is_empty() {
|
||||
return item_result;
|
||||
}
|
||||
let Ok(_permit) = self.permits.acquire().await else {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_permit",
|
||||
Some("failed_to_acquire_import_permit"),
|
||||
"external agent session import permit could not be acquired",
|
||||
/*source*/ None,
|
||||
);
|
||||
return item_result;
|
||||
};
|
||||
let import_results = futures::stream::iter(sessions)
|
||||
.map(|session| {
|
||||
let importer = self.clone();
|
||||
async move {
|
||||
importer
|
||||
.import_requested_session(session, metadata_mode)
|
||||
.await
|
||||
}
|
||||
})
|
||||
.buffer_unordered(SESSION_IMPORT_CONCURRENCY);
|
||||
futures::pin_mut!(import_results);
|
||||
|
||||
let mut completed_imports = Vec::new();
|
||||
let mut appended_connector_names_by_source_path = BTreeMap::new();
|
||||
while let Some(result) = import_results.next().await {
|
||||
match result {
|
||||
Ok(Some(SessionImportOutcome::Created(completed_import))) => {
|
||||
item_result.record_success_with_cwd(
|
||||
Some(completed_import.cwd.clone()),
|
||||
Some(completed_import.import.source_path.display().to_string()),
|
||||
Some(completed_import.import.imported_thread_id.to_string()),
|
||||
completed_import.import.title.clone(),
|
||||
);
|
||||
completed_imports.push(completed_import);
|
||||
}
|
||||
Ok(Some(SessionImportOutcome::Appended {
|
||||
cwd,
|
||||
source_path,
|
||||
imported_thread_id,
|
||||
title,
|
||||
})) => {
|
||||
item_result.record_success_with_cwd(
|
||||
Some(cwd),
|
||||
Some(source_path.display().to_string()),
|
||||
Some(imported_thread_id.to_string()),
|
||||
title,
|
||||
);
|
||||
if let Some(connector_names) =
|
||||
connector_names_by_source_path.remove(&source_path)
|
||||
{
|
||||
appended_connector_names_by_source_path
|
||||
.insert(source_path, connector_names);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(failure) => {
|
||||
let SessionImportFailure {
|
||||
source_path,
|
||||
message,
|
||||
stage,
|
||||
sub_error_type,
|
||||
} = failure;
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
stage,
|
||||
Some(sub_error_type.as_str()),
|
||||
message,
|
||||
Some(source_path.display().to_string()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(err) = append_imported_session_connector_names(
|
||||
&self.codex_home,
|
||||
appended_connector_names_by_source_path,
|
||||
) {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_ledger_update",
|
||||
Some("failed_to_update_session_connector_metadata"),
|
||||
err.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
}
|
||||
if completed_imports.is_empty() {
|
||||
return item_result;
|
||||
}
|
||||
let connector_attributions_by_source_path = completed_imports
|
||||
.iter()
|
||||
.filter_map(|completed_import| {
|
||||
completed_import
|
||||
.connector_attribution
|
||||
.clone()
|
||||
.map(|attribution| (completed_import.import.source_path.clone(), attribution))
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let connector_metadata_roots = self.connector_metadata_roots.clone();
|
||||
let mut attributed_connector_names_by_source_path =
|
||||
match tokio::task::spawn_blocking(move || {
|
||||
detect_imported_cla_session_connectors_by_source_path(
|
||||
&connector_attributions_by_source_path,
|
||||
&connector_metadata_roots,
|
||||
)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(connector_names_by_source_path) => connector_names_by_source_path,
|
||||
Err(err) => {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_connector_detection_task",
|
||||
Some("session_connector_detection_task_failed"),
|
||||
err.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
Default::default()
|
||||
}
|
||||
};
|
||||
for completed_import in &mut completed_imports {
|
||||
completed_import.import.connector_names = attributed_connector_names_by_source_path
|
||||
.remove(&completed_import.import.source_path)
|
||||
.unwrap_or_default();
|
||||
}
|
||||
for completed_import in &mut completed_imports {
|
||||
let Some(connector_names) =
|
||||
connector_names_by_source_path.remove(&completed_import.import.source_path)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
completed_import
|
||||
.import
|
||||
.connector_names
|
||||
.extend(connector_names);
|
||||
}
|
||||
let completed_imports = completed_imports
|
||||
.into_iter()
|
||||
.map(|completed_import| completed_import.import)
|
||||
.collect();
|
||||
if let Err(err) = record_completed_session_imports(&self.codex_home, completed_imports) {
|
||||
record_import_error(
|
||||
&mut item_result,
|
||||
"session_ledger_update",
|
||||
Some("failed_to_update_session_ledger"),
|
||||
err.to_string(),
|
||||
/*source*/ None,
|
||||
);
|
||||
}
|
||||
item_result
|
||||
}
|
||||
|
||||
async fn import_requested_session(
|
||||
&self,
|
||||
session: ExternalAgentSessionMigration,
|
||||
metadata_mode: SessionMetadataMode,
|
||||
) -> Result<Option<SessionImportOutcome>, SessionImportFailure> {
|
||||
let source_path = session.path.clone();
|
||||
let Some(pending_import) = self
|
||||
.prepare_session_import(session, metadata_mode)
|
||||
.await
|
||||
.map_err(|failure| SessionImportFailure {
|
||||
source_path: source_path.clone(),
|
||||
message: failure.message,
|
||||
stage: "session_prepare",
|
||||
sub_error_type: failure.sub_error_type,
|
||||
})?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let PendingSessionImport {
|
||||
source_path,
|
||||
source_content_sha256,
|
||||
target,
|
||||
attributed_mcp_server_ids,
|
||||
session,
|
||||
} = pending_import;
|
||||
match target {
|
||||
SessionImportTarget::New => self
|
||||
.create_session_import(
|
||||
source_path,
|
||||
source_content_sha256,
|
||||
attributed_mcp_server_ids,
|
||||
session,
|
||||
)
|
||||
.await
|
||||
.map(SessionImportOutcome::Created)
|
||||
.map(Some),
|
||||
SessionImportTarget::Existing {
|
||||
thread_id,
|
||||
expected_source_content_sha256,
|
||||
} => {
|
||||
let cwd = session.cwd.clone();
|
||||
let title = session.title.clone();
|
||||
let appended = append_existing_session(
|
||||
&self.codex_home,
|
||||
self.append_checkpoint_permits.as_ref(),
|
||||
self.thread_manager.as_ref(),
|
||||
self.thread_store.as_ref(),
|
||||
ExistingSessionAppend {
|
||||
source_path: &source_path,
|
||||
source_content_sha256: &source_content_sha256,
|
||||
expected_source_content_sha256: &expected_source_content_sha256,
|
||||
thread_id,
|
||||
source_items: &session.rollout_items,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
Ok(appended.then_some(SessionImportOutcome::Appended {
|
||||
cwd,
|
||||
source_path,
|
||||
imported_thread_id: thread_id,
|
||||
title,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_session_import(
|
||||
&self,
|
||||
source_path: PathBuf,
|
||||
source_content_sha256: String,
|
||||
attributed_mcp_server_ids: BTreeSet<String>,
|
||||
session: ImportedExternalAgentSession,
|
||||
) -> Result<CompletedSessionImport, SessionImportFailure> {
|
||||
let connector_attribution = source_path
|
||||
.file_stem()
|
||||
.and_then(|stem| stem.to_str())
|
||||
.map(str::trim)
|
||||
.filter(|session_id| !session_id.is_empty())
|
||||
.map(|session_id| ImportedSessionConnectorAttribution {
|
||||
session_id: session_id.to_string(),
|
||||
server_ids: attributed_mcp_server_ids,
|
||||
});
|
||||
let cwd = session.cwd.clone();
|
||||
let title = session.title.clone();
|
||||
let imported_thread_id =
|
||||
self.persist_session(session)
|
||||
.await
|
||||
.map_err(|failure| SessionImportFailure {
|
||||
source_path: source_path.clone(),
|
||||
message: failure.message,
|
||||
stage: "session_persist",
|
||||
sub_error_type: failure.sub_error_type,
|
||||
})?;
|
||||
Ok(CompletedSessionImport {
|
||||
cwd,
|
||||
import: CompletedExternalAgentSessionImport {
|
||||
source_path,
|
||||
source_content_sha256,
|
||||
imported_thread_id,
|
||||
connector_names: Vec::new(),
|
||||
title,
|
||||
},
|
||||
connector_attribution,
|
||||
})
|
||||
}
|
||||
|
||||
async fn prepare_session_import(
|
||||
&self,
|
||||
session: ExternalAgentSessionMigration,
|
||||
metadata_mode: SessionMetadataMode,
|
||||
) -> Result<Option<PendingSessionImport>, SessionImportStepFailure> {
|
||||
let codex_home = self.codex_home.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
prepare_validated_session_import_with_metadata_mode(&codex_home, session, metadata_mode)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"session_preparation_task_failed",
|
||||
format!("external agent session preparation task failed: {err}"),
|
||||
)
|
||||
})?
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_prepare_session",
|
||||
format!("failed to prepare external agent session: {err}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn persist_session(
|
||||
&self,
|
||||
session: ImportedExternalAgentSession,
|
||||
) -> Result<ThreadId, SessionImportStepFailure> {
|
||||
let ImportedExternalAgentSession {
|
||||
cwd,
|
||||
title,
|
||||
first_user_message,
|
||||
mut rollout_items,
|
||||
} = session;
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_with_overrides(
|
||||
/*request_overrides*/ None,
|
||||
ConfigOverrides {
|
||||
cwd: Some(cwd),
|
||||
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
let io_kind = match err.kind() {
|
||||
ErrorKind::NotFound => "not_found",
|
||||
ErrorKind::PermissionDenied => "permission_denied",
|
||||
ErrorKind::AlreadyExists => "already_exists",
|
||||
ErrorKind::InvalidInput => "invalid_input",
|
||||
ErrorKind::InvalidData => "invalid_data",
|
||||
ErrorKind::IsADirectory => "is_a_directory",
|
||||
ErrorKind::NotADirectory => "not_a_directory",
|
||||
ErrorKind::TimedOut => "timed_out",
|
||||
ErrorKind::WriteZero => "write_zero",
|
||||
ErrorKind::UnexpectedEof => "unexpected_eof",
|
||||
ErrorKind::StorageFull => "storage_full",
|
||||
ErrorKind::QuotaExceeded => "quota_exceeded",
|
||||
ErrorKind::FileTooLarge => "file_too_large",
|
||||
ErrorKind::ReadOnlyFilesystem => "read_only_filesystem",
|
||||
_ => "other",
|
||||
};
|
||||
SessionImportStepFailure::new(
|
||||
format!("failed_to_load_session_config_{io_kind}"),
|
||||
format!("failed to load imported session config: {err}"),
|
||||
)
|
||||
})?;
|
||||
let models_manager = self.thread_manager.get_models_manager();
|
||||
let model = models_manager
|
||||
.get_default_model(
|
||||
&config.model,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
RefreshStrategy::Offline,
|
||||
config.http_client_factory(),
|
||||
)
|
||||
.await;
|
||||
let model_info = models_manager
|
||||
.get_model_info(model.as_str(), &config.to_models_manager_config())
|
||||
.await;
|
||||
let thread_id = ThreadId::new();
|
||||
let source = self.thread_manager.session_source();
|
||||
let cwd = config.cwd.to_path_buf();
|
||||
let model_provider = config.model_provider_id.clone();
|
||||
let memory_mode = if config.memories.generate_memories {
|
||||
ThreadMemoryMode::Enabled
|
||||
} else {
|
||||
ThreadMemoryMode::Disabled
|
||||
};
|
||||
let now = Utc::now();
|
||||
let create_params = CreateThreadParams {
|
||||
attached_thread: false,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
session_id: thread_id.into(),
|
||||
thread_id,
|
||||
extra_config: None,
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
source: source.clone(),
|
||||
thread_source: None,
|
||||
originator: codex_login::default_client::originator().value,
|
||||
base_instructions: BaseInstructions {
|
||||
text: config
|
||||
.base_instructions
|
||||
.clone()
|
||||
.unwrap_or_else(|| render_model_instructions(&model_info)),
|
||||
provenance: Some(config.base_instructions_provenance.clone().unwrap_or_else(
|
||||
|| {
|
||||
if config.base_instructions.is_some() {
|
||||
BaseInstructionsProvenance::Custom
|
||||
} else {
|
||||
BaseInstructionsProvenance::Model {
|
||||
model: model_info.slug.clone(),
|
||||
}
|
||||
}
|
||||
},
|
||||
)),
|
||||
},
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
runtime_workspace_roots: None,
|
||||
multi_agent_version: Some(MultiAgentVersion::V1),
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
initial_window_id: codex_protocol::ContextWindowId::new_uuid_v7().to_string(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(cwd.clone()),
|
||||
model_provider: model_provider.clone(),
|
||||
memory_mode,
|
||||
},
|
||||
};
|
||||
rollout_items = into_persisted_rollout_items(rollout_items, ThreadHistoryMode::Legacy);
|
||||
let (created_at, updated_at) = rollout_items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => event.started_at,
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => event.completed_at,
|
||||
_ => None,
|
||||
})
|
||||
.fold(None, |chronology: Option<(i64, i64)>, timestamp| {
|
||||
Some(match chronology {
|
||||
Some((created_at, updated_at)) => {
|
||||
(created_at.min(timestamp), updated_at.max(timestamp))
|
||||
}
|
||||
None => (timestamp, timestamp),
|
||||
})
|
||||
})
|
||||
.and_then(|(created_at, updated_at)| {
|
||||
Some((
|
||||
DateTime::from_timestamp(created_at, /*nsecs*/ 0)?,
|
||||
DateTime::from_timestamp(updated_at, /*nsecs*/ 0)?,
|
||||
))
|
||||
})
|
||||
.unwrap_or((now, now));
|
||||
let title = title
|
||||
.as_deref()
|
||||
.and_then(codex_core::util::normalize_thread_name);
|
||||
let metadata = ThreadMetadataPatch {
|
||||
title,
|
||||
preview: first_user_message.clone(),
|
||||
model_provider: Some(model_provider),
|
||||
created_at: Some(created_at),
|
||||
updated_at: Some(updated_at),
|
||||
advance_recency_at: Some(updated_at),
|
||||
source: Some(source.clone()),
|
||||
thread_source: Some(None),
|
||||
agent_nickname: Some(source.get_nickname()),
|
||||
agent_role: Some(source.get_agent_role()),
|
||||
agent_path: Some(source.get_agent_path().map(Into::into)),
|
||||
cwd: Some(cwd),
|
||||
cli_version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
||||
first_user_message,
|
||||
memory_mode: Some(memory_mode),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.thread_store
|
||||
.create_thread(create_params)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_create_thread",
|
||||
format!("failed to import session: {err}"),
|
||||
)
|
||||
})?;
|
||||
if !rollout_items.is_empty()
|
||||
&& let Err(err) = self
|
||||
.thread_store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id,
|
||||
items: rollout_items,
|
||||
})
|
||||
.await
|
||||
{
|
||||
let _ = self.thread_store.discard_thread(thread_id).await;
|
||||
return Err(SessionImportStepFailure::new(
|
||||
"failed_to_append_thread_items",
|
||||
format!("failed to import session: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
self.thread_store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: metadata,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_update_thread_metadata",
|
||||
format!("failed to update imported session: {err}"),
|
||||
)
|
||||
})?;
|
||||
self.thread_store
|
||||
.persist_thread(thread_id, PersistContext::Standard)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_persist_thread",
|
||||
format!("failed to persist imported session: {err}"),
|
||||
)
|
||||
})?;
|
||||
self.thread_store
|
||||
.shutdown_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
SessionImportStepFailure::new(
|
||||
"failed_to_shutdown_thread",
|
||||
format!("failed to shutdown imported session: {err}"),
|
||||
)
|
||||
})?;
|
||||
Ok(thread_id)
|
||||
}
|
||||
}
|
||||
|
||||
struct SessionImportFailure {
|
||||
source_path: PathBuf,
|
||||
message: String,
|
||||
stage: &'static str,
|
||||
sub_error_type: String,
|
||||
}
|
||||
|
||||
struct SessionImportStepFailure {
|
||||
sub_error_type: String,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl SessionImportStepFailure {
|
||||
fn new(sub_error_type: impl Into<String>, message: String) -> Self {
|
||||
Self {
|
||||
sub_error_type: sub_error_type.into(),
|
||||
message,
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user