Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
//! Runs a thread for its owner's chosen lifetime, including cancellation during startup.
//! Cleanup remains tracked when the caller drops its startup future or stops waiting.
use std::future::Future;
use std::sync::Arc;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use super::NewThread;
use super::StartThreadOptions;
use super::ThreadManager;
use crate::session::startup::SessionStartup;
impl ThreadManager {
/// Starts a new isolated thread and owns it until `until` completes or the thread exits.
/// Dropping the startup future also cancels initialization. `tasks` tracks the
/// entire lifetime, including partial startup cleanup and deregistration.
/// Cleanup waits for any in-flight persistence acquisition before releasing its writer.
/// Once the session runtime starts, cleanup follows normal shutdown history rules,
/// even if the caller has not received the thread yet.
/// Resumed threads are excluded because they can refer to another owner's live runtime.
pub async fn start_thread_until(
self: &Arc<Self>,
options: StartThreadOptions,
until: impl Future<Output = ()> + Send + 'static,
tasks: &TaskTracker,
) -> CodexResult<NewThread> {
if matches!(
options.initial_history,
codex_history::InitialHistory::Resumed(_)
) {
return Err(CodexErr::InvalidRequest(
"owned thread startup requires new or forked history".to_owned(),
));
}
if options
.thread_extension_init
.get::<codex_extension_api::SessionIsolation>()
.as_deref()
!= Some(&codex_extension_api::SessionIsolation::Isolated)
{
return Err(CodexErr::InvalidRequest(
"owned thread startup requires explicit session isolation".to_owned(),
));
}
let task = tasks.token();
let manager = Arc::clone(self);
let state = Arc::downgrade(&self.state);
let (sender, receiver) = oneshot::channel();
let abandoned = CancellationToken::new();
let handoff = abandoned.clone().drop_guard();
tokio::spawn(async move {
let _task = task;
let startup = Arc::new(SessionStartup::default());
tokio::pin!(until);
// Drop initialization before cleanup; startup still owns any unfinished acquisition.
let result = {
let start = manager.start_thread_inner(
options,
/*forked_from_thread_id*/ None,
Some(Arc::clone(&startup)),
);
tokio::select! {
biased;
_ = &mut until => Err(CodexErr::TurnAborted),
_ = abandoned.cancelled() => Err(CodexErr::TurnAborted),
result = start => result,
}
};
// The lifetime task must not keep the manager and its parent threads alive.
drop(manager);
match result {
Ok(thread) => {
let running = Arc::clone(&thread.thread);
if sender.send(Ok(thread)).is_ok() {
tokio::select! {
_ = abandoned.cancelled() => {}
_ = &mut until => {}
_ = running.wait_until_terminated() => {}
}
}
}
Err(error) => {
let _ = sender.send(Err(error));
}
}
startup.cleanup().await;
if let Some(state) = state.upgrade()
&& let Some(session) = startup.session.get()
{
let mut threads = state.threads.write().await;
let thread_id = session.thread_id();
if threads
.get(&thread_id)
.is_some_and(|thread| Arc::ptr_eq(&thread.session, session))
{
threads.remove(&thread_id);
}
}
});
let thread = receiver.await.map_err(|_| CodexErr::InternalAgentDied)??;
handoff.disarm();
Ok(thread)
}
}

View File

@@ -0,0 +1,189 @@
//! Keep each catalog bound to its provider and auth owner while preserving host cache policy.
use crate::config::Config;
use crate::runtime_auth::RuntimeAuthSlot;
use crate::runtime_auth::runtime_for_config;
use codex_features::Feature;
use codex_features::RuntimeAuthMode;
use codex_login::AuthManager;
use codex_model_provider::ModelCatalogFactory;
use codex_model_provider::ProviderAuthContext;
use codex_model_provider_info::ModelProviderInfo;
use codex_models_manager::manager::ModelCatalogSettings;
use codex_models_manager::manager::SharedModelsManager;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::protocol::SessionSource;
use codex_runtime_agent_instance::RuntimeAuthManager;
use std::sync::Arc;
/// The startup catalog and the credential/runtime owner used to construct it.
pub struct StartupModels {
pub(super) credentials: Arc<AuthManager>,
pub(super) runtime_auth: RuntimeAuthSlot,
pub(super) installation_id: String,
pub(super) catalog: ThreadModelCatalog,
}
impl StartupModels {
/// Share the startup catalog with host discovery and prefetch callers.
pub fn models_manager(&self) -> SharedModelsManager {
Arc::clone(&self.catalog.manager)
}
}
/// Construct the catalog and runtime owner together using the host's catalog factory.
/// Use `ModelCatalogSettings` for standard provider catalogs with a disk, custom, or no cache.
/// Runtime registration remains lazy; this does not register an instance or generate a key.
pub fn build_startup_models(
config: &Config,
credentials: Arc<AuthManager>,
installation_id: String,
factory: Arc<dyn ModelCatalogFactory>,
) -> StartupModels {
let runtime_auth = RuntimeAuthSlot::default();
let runtime = runtime_for_config(
&runtime_auth,
config,
Arc::clone(&credentials),
&installation_id,
);
let catalog = ThreadModelCatalog::new(
config.model_provider.clone(),
config.model_catalog.clone(),
factory,
config.features.enabled(Feature::ApiKeyModelDiscovery),
ProviderAuthContext {
credentials: Arc::clone(&credentials),
runtime_auth: runtime.map(|runtime| (runtime, config.runtime_auth_mode)),
},
);
StartupModels {
credentials,
runtime_auth,
installation_id,
catalog,
}
}
pub(super) struct ThreadModelCatalog {
pub(super) manager: SharedModelsManager,
provider: ModelProviderInfo,
catalog: Option<ModelsResponse>,
factory: Arc<dyn ModelCatalogFactory>,
api_key_model_discovery_default: bool,
runtime_mode: Option<RuntimeAuthMode>,
}
pub fn build_models_manager(
config: &Config,
credentials: Arc<AuthManager>,
runtime: Option<Arc<RuntimeAuthManager>>,
) -> SharedModelsManager {
let auth = ProviderAuthContext {
credentials,
runtime_auth: runtime
.filter(|_| config.features.enabled(Feature::RuntimeAgentInstances))
.map(|runtime| (runtime, config.runtime_auth_mode)),
};
ModelCatalogSettings::disk(config.codex_home.to_path_buf()).build(
auth.model_provider(config.model_provider.clone()),
config.model_catalog.clone(),
config.features.enabled(Feature::ApiKeyModelDiscovery),
)
}
impl ThreadModelCatalog {
pub(super) fn new(
provider: ModelProviderInfo,
catalog: Option<ModelsResponse>,
factory: Arc<dyn ModelCatalogFactory>,
api_key_model_discovery_default: bool,
auth: ProviderAuthContext,
) -> Self {
let runtime_mode = auth.runtime_auth.as_ref().map(|(_, mode)| *mode);
let manager = factory.build(
auth.model_provider(provider.clone()),
catalog.clone(),
api_key_model_discovery_default,
);
Self {
manager,
provider,
catalog,
factory,
api_key_model_discovery_default,
runtime_mode,
}
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn for_thread(
&self,
config: &Config,
credentials: Arc<AuthManager>,
runtime: Option<Arc<RuntimeAuthManager>>,
same_owner: bool,
originator: &str,
session_source: &SessionSource,
) -> SharedModelsManager {
let models = config.model_catalog.as_ref().or_else(|| {
self.catalog
.as_ref()
.filter(|_| self.matches_catalog_provider(&config.model_provider))
});
let auth = ProviderAuthContext {
credentials,
runtime_auth: runtime.map(|runtime| (runtime, config.runtime_auth_mode)),
};
let manager = self.for_config(config, models, auth, same_owner);
let manager = manager.for_originator(originator).unwrap_or(manager);
if session_source.is_non_root_agent() {
// The final provider/auth/originator catalog may be new even when the base
// manager was reused. Preserve loaded snapshots, including unsaved updates.
manager
.ensure_initialized(config.http_client_factory())
.await;
}
manager
}
pub(super) fn for_config(
&self,
config: &Config,
models: Option<&ModelsResponse>,
auth: ProviderAuthContext,
same_owner: bool,
) -> SharedModelsManager {
let api_key_model_discovery_default =
config.features.enabled(Feature::ApiKeyModelDiscovery);
if same_owner
&& self.runtime_mode == auth.runtime_auth.as_ref().map(|(_, mode)| *mode)
&& self.matches_catalog_provider(&config.model_provider)
&& self.catalog.as_ref() == models
&& self.api_key_model_discovery_default == api_key_model_discovery_default
{
return Arc::clone(&self.manager);
}
self.factory.build(
auth.model_provider(config.model_provider.clone()),
models.cloned(),
api_key_model_discovery_default,
)
}
fn matches_catalog_provider(&self, provider: &ModelProviderInfo) -> bool {
// Guardian overrides inference transport and retries without changing the catalog.
// Keep all other provider fields, including routing and headers, in the comparison.
self.provider
== ModelProviderInfo {
request_max_retries: self.provider.request_max_retries,
stream_max_retries: self.provider.stream_max_retries,
supports_websockets: self.provider.supports_websockets,
..provider.clone()
}
}
pub(super) fn set_api_key_model_discovery_enabled(&self, enabled: bool) {
self.factory.set_api_key_model_discovery_enabled(enabled);
}
}

View File

@@ -0,0 +1,118 @@
//! Keeps one replaceable instruction provider per root while its agent tree is alive.
//! Reusing the shared wrapper must never make it delegate to itself.
use codex_extension_api::Instructions;
use codex_extension_api::LoadInstructionsFuture;
use codex_extension_api::LoadedUserInstructions;
use codex_extension_api::ThreadInstructionsProvider;
use codex_protocol::ThreadId;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Weak;
#[derive(Default)]
pub(super) struct SharedThreadInstructionsProviders {
roots: Mutex<HashMap<ThreadId, Weak<SharedThreadInstructionsProvider>>>,
}
impl SharedThreadInstructionsProviders {
pub(super) fn for_root(
&self,
root: ThreadId,
provider: Option<Arc<dyn ThreadInstructionsProvider>>,
) -> Option<Arc<dyn ThreadInstructionsProvider>> {
let mut roots = self
.roots
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
roots.retain(|_, provider| provider.strong_count() > 0);
let existing = roots.get(&root).and_then(Weak::upgrade);
if provider
.as_ref()
.is_some_and(|provider| !provider.share_with_subagents())
{
if let Some(existing) = existing {
existing.replace(/*provider*/ None);
}
return provider;
}
match (existing, provider) {
(Some(existing), provider) => {
// An unloaded root can inherit this wrapper from its surviving children.
let shared: Arc<dyn ThreadInstructionsProvider> = existing.clone();
if provider
.as_ref()
.is_some_and(|provider| !Arc::ptr_eq(provider, &shared))
{
existing.replace(provider);
}
Some(shared)
}
(None, Some(provider)) => {
let shared = Arc::new(SharedThreadInstructionsProvider(Mutex::new(
ProviderState {
provider: Some(provider),
last: None,
},
)));
roots.insert(root, Arc::downgrade(&shared));
Some(shared)
}
(None, None) => None,
}
}
}
struct SharedThreadInstructionsProvider(Mutex<ProviderState>);
struct ProviderState {
provider: Option<Arc<dyn ThreadInstructionsProvider>>,
last: Option<Instructions>,
}
impl SharedThreadInstructionsProvider {
fn replace(&self, provider: Option<Arc<dyn ThreadInstructionsProvider>>) {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.provider = provider;
}
}
impl ThreadInstructionsProvider for SharedThreadInstructionsProvider {
fn share_with_subagents(&self) -> bool {
true
}
fn load_thread_instructions(&self) -> LoadInstructionsFuture<'_> {
Box::pin(async move {
let (provider, last) = {
let state = self
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
(state.provider.clone(), state.last.clone())
};
let Some(provider) = provider else {
return LoadedUserInstructions {
instructions: last,
warnings: Vec::new(),
};
};
let loaded = provider.load_thread_instructions().await;
let mut state = self
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state
.provider
.as_ref()
.is_some_and(|current| Arc::ptr_eq(current, &provider))
{
state.last = loaded.instructions.clone();
}
loaded
})
}
}

View File

@@ -0,0 +1,171 @@
//! Unloads locally controlled idle MAv2 children and exposes tracked agent-tree teardown.
use super::ThreadManager;
use crate::agent::control::AgentTreeShutdownState;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_thread_store::ThreadStoreError;
use std::fmt;
use std::sync::Arc;
use uuid::Uuid;
/// Return a stable, payload-free category for a thread-store error.
pub(crate) fn thread_store_error_kind(error: &ThreadStoreError) -> &'static str {
match error {
ThreadStoreError::ThreadNotFound { .. } => "thread_store_not_found",
ThreadStoreError::InvalidRequest { .. } => "thread_store_invalid_request",
ThreadStoreError::Conflict { .. } => "thread_store_conflict",
ThreadStoreError::Unsupported { .. } => "thread_store_unsupported",
ThreadStoreError::Retryable { .. } => "thread_store_retryable",
ThreadStoreError::OutcomeUnknown { .. } => "thread_store_outcome_unknown",
ThreadStoreError::Internal { .. } => "thread_store_internal",
}
}
/// A safely loggable reason that a tracked part of an agent tree failed to shut down.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AgentTreeShutdownFailureReason {
/// An operation returned an error at a specific step. The kind is a stable,
/// non-sensitive classification.
OperationFailed {
phase: &'static str,
error_kind: &'static str,
},
/// A tracked operation was dropped before it could report that its work completed.
GuardAbandoned,
}
/// One failure observed during the lifetime or teardown of an agent tree.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AgentTreeShutdownFailure {
pub operation: &'static str,
pub thread_id: Option<ThreadId>,
pub reason: AgentTreeShutdownFailureReason,
}
impl AgentTreeShutdownFailure {
/// Classifies an operation failure without retaining arbitrary error messages.
pub fn operation_failed(
operation: &'static str,
phase: &'static str,
thread_id: Option<ThreadId>,
error_kind: &'static str,
) -> Self {
Self {
operation,
thread_id,
reason: AgentTreeShutdownFailureReason::OperationFailed { phase, error_kind },
}
}
}
/// The bounded set of failures observed for one local agent-tree instance.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AgentTreeShutdownReport {
/// Correlation ID for this runtime instance; this is not a thread's ID.
pub tree_id: Uuid,
/// Failures retained in recording order. Each failure is also logged when recorded.
pub failures: Vec<AgentTreeShutdownFailure>,
/// Number of additional failures omitted after the retention limit was reached.
pub omitted_failures: usize,
}
impl fmt::Display for AgentTreeShutdownReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"agent tree shutdown did not complete cleanly: tree_id={}, failures=[",
self.tree_id
)?;
for (index, failure) in self.failures.iter().enumerate() {
if index > 0 {
write!(f, ", ")?;
}
write!(f, "{{operation={}", failure.operation)?;
if let AgentTreeShutdownFailureReason::OperationFailed { phase, .. } = &failure.reason {
write!(f, ", phase={phase}")?;
}
if let Some(thread_id) = failure.thread_id {
write!(f, ", thread_id={thread_id}")?;
}
match &failure.reason {
AgentTreeShutdownFailureReason::OperationFailed { error_kind, .. } => {
write!(f, ", reason=operation_failed, error_kind={error_kind}")?;
}
AgentTreeShutdownFailureReason::GuardAbandoned => {
write!(f, ", reason=guard_abandoned")?;
}
}
write!(f, "}}")?;
}
write!(f, "]; omitted_failures={}", self.omitted_failures)
}
}
impl std::error::Error for AgentTreeShutdownReport {}
/// Completion handle for one exact local agent tree.
#[derive(Clone, Debug)]
#[must_use = "agent-tree shutdown is not complete until wait() finishes"]
pub struct AgentTreeShutdown {
state: Arc<AgentTreeShutdownState>,
}
impl AgentTreeShutdown {
/// Waits for every operation and session admitted before the shutdown fence to finish.
/// Returns an error if cleanup or persistence writer termination failed. Registry removal and
/// caller-owned persistence handoff remain with the caller. Dropping this future does not
/// cancel shutdown.
pub async fn wait(&self) -> CodexResult<()> {
self.state.wait().await
}
/// Waits for the tree and returns its recorded failure report if cleanup was unsuccessful.
/// Each call observes the same completed report. Dropping the future does not cancel shutdown.
pub async fn wait_detailed(&self) -> Result<(), AgentTreeShutdownReport> {
self.state.wait_detailed().await
}
}
impl ThreadManager {
/// Unloads this exact idle MAv2 child using the manager's local controller backend,
/// preserving mail and environments for reloading. Host controllers own their eviction
/// and recovery; managers configured with a host controller factory are rejected.
/// Dropping the future after shutdown starts does not cancel cleanup.
pub async fn try_evict_v2_thread(
&self,
thread: Arc<crate::CodexThread>,
) -> CodexResult<crate::ThreadEvictionOutcome> {
// Backend selection is fixed before the manager is shared or starts any threads.
if self.state.agent_control_factory.is_some() {
return Err(CodexErr::InvalidRequest(
"idle eviction requires the local agent controller".to_owned(),
));
}
let Ok(membership) = thread.session.services.local_agent_runtime.admit_start() else {
return Ok(crate::ThreadEvictionOutcome::Busy);
};
self.state.try_evict_v2_thread(thread, &membership).await
}
/// Requests shutdown of a loaded thread and every session sharing its local runtime.
///
/// Returns after fencing new starts and signalling admitted sessions. Callers can wait on the
/// returned handle before completing registry cleanup or a persistence handoff. This fences
/// only starts sharing the current runtime; callers must separately serialize top-level loads
/// or resumes of the same thread ID through that handoff.
pub async fn request_agent_tree_shutdown(
&self,
thread_id: ThreadId,
) -> CodexResult<AgentTreeShutdown> {
let thread = self.get_thread(thread_id).await?;
Ok(AgentTreeShutdown {
state: thread
.session
.services
.local_agent_runtime
.request_shutdown(),
})
}
}