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:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,329 @@
//! Implements shared controller operations using the existing local runtime helpers.
//! Runtime loading, message delivery and shared state remain in their existing modules.
use super::LocalAgentControl;
use super::spawn::SpawnInitialInput;
use crate::agent::api::AgentConfigUpdate;
use crate::agent::api::AgentControl;
use crate::agent::api::AgentInfo;
use crate::agent::api::AgentInput;
use crate::agent::api::AgentTarget;
use crate::agent::api::AgentTurnOutcome;
use crate::agent::api::DeliveryReceipt;
use crate::agent::api::SendRequest;
use crate::agent::api::SpawnRequest;
use crate::agent::types::AgentExecutionGuard;
use crate::agent::types::LiveAgent;
use crate::agent::types::MessageDeliveryMode;
use crate::agent_communication::AgentCommunicationContext;
use crate::agent_communication::AgentCommunicationKind;
use crate::codex_thread::GuardianRootSnapshot;
use crate::codex_thread::ThreadConfigSnapshot;
use crate::rollout_budget::RolloutBudgetReminder;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use akode_protocol::protocol::MultiAgentVersion;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::TokenUsage;
use akode_rollout_trace::ThreadTraceContext;
use futures::future::BoxFuture;
use std::collections::HashSet;
impl AgentControl for LocalAgentControl {
fn identity(&self) -> SessionId {
self.session_id()
}
fn resolve<'a>(
&'a self,
caller: ThreadId,
parent: Option<ThreadId>,
source: &'a SessionSource,
target: &'a str,
) -> BoxFuture<'a, Result<ThreadId>> {
Box::pin(async move {
self.runtime.register_session_root(caller, parent);
if let Ok(thread_id) = ThreadId::from_string(target) {
return Ok(thread_id);
}
self.runtime
.resolve_agent_reference(caller, source, target)
.await
})
}
fn spawn(
&self,
request: SpawnRequest,
) -> BoxFuture<'_, Result<(LiveAgent, ThreadConfigSnapshot)>> {
Box::pin(async move {
let SpawnRequest {
caller,
config,
input,
source,
options,
} = request;
let input = match input {
AgentInput::UserInput(input) => SpawnInitialInput::UserInput(input),
AgentInput::Message { message, mode } => {
if mode != MessageDeliveryMode::TriggerTurn {
return Err(CodexErr::InvalidRequest(
"spawn input must start the child turn".to_string(),
));
}
let recipient = source.get_agent_path().ok_or_else(|| {
CodexErr::InvalidRequest(
"spawned agent is missing a canonical task name".to_string(),
)
})?;
let author = recipient
.as_str()
.rsplit_once('/')
.and_then(|(parent, _)| AgentPath::try_from(parent).ok())
.ok_or_else(|| {
CodexErr::InvalidRequest("spawn input needs a child path".to_string())
})?;
SpawnInitialInput::InterAgentCommunication(
message.into_communication(author, recipient, mode),
AgentCommunicationContext::new(AgentCommunicationKind::Spawn, caller),
)
}
};
Box::pin(self.spawn_agent_internal(config, input, Some(source), options)).await
})
}
fn send(&self, request: SendRequest) -> BoxFuture<'_, Result<DeliveryReceipt>> {
Box::pin(async move {
let SendRequest {
caller,
target,
resume_config,
input,
mut start_options,
} = request;
let target = self.resolve_target(caller, &target)?;
let (metadata, submission_id) = match input {
AgentInput::UserInput(input) => {
let receiver = self.get_agent_metadata(target);
let _residency_pin = if receiver.is_some() {
self.ensure_v2_agent_loaded(resume_config, target, /*parent*/ None)
.await?
} else {
None
};
let submission_id = self.send_input(target, input, start_options).await?;
(receiver.unwrap_or_default(), submission_id)
}
AgentInput::Message { message, mode } => {
let receiver = self.runtime.ensure_agent_known(target)?;
let author = self
.runtime
.ensure_agent_known(caller)?
.agent_path
.unwrap_or_else(AgentPath::root);
if mode == MessageDeliveryMode::TriggerTurn
&& receiver.agent_path.as_ref().is_some_and(AgentPath::is_root)
{
return Err(CodexErr::UnsupportedOperation(
"Follow-up tasks can't target the root agent".to_string(),
));
}
let receiver_path = receiver.agent_path.clone().ok_or_else(|| {
CodexErr::UnsupportedOperation(
"target agent is missing an agent_path".to_string(),
)
})?;
// Cold-restored children still reload lazily on any message. Only
// locally evicted recipients can retain mail without reloading.
// Loaded recipients go straight to delivery, which rejects sends
// racing an in-progress eviction when it acquires the residency pin.
let _residency_pin = if mode == MessageDeliveryMode::TriggerTurn
|| (self.runtime.upgrade()?.get_thread(target).await.is_err()
&& self.runtime.registry.evicted_environments(target).is_none())
{
self.ensure_v2_agent_loaded(resume_config, target, /*parent*/ None)
.await?
} else {
None
};
let communication = message.into_communication(author, receiver_path, mode);
let kind = match mode {
MessageDeliveryMode::QueueOnly => {
start_options.parent_turn_id = None;
AgentCommunicationKind::Message
}
MessageDeliveryMode::TriggerTurn => AgentCommunicationKind::Followup,
};
let submission_id = self
.send_inter_agent_communication(
target,
communication,
AgentCommunicationContext::new(kind, caller),
start_options,
)
.await?;
(receiver, submission_id)
}
};
Ok(DeliveryReceipt {
thread_id: target,
metadata,
submission_id,
})
})
}
fn take_mailbox(&self, agent: ThreadId) -> Vec<crate::PendingAgentMessage> {
self.runtime.mailboxes.take(agent)
}
fn watch_mailbox(&self, agent: ThreadId) -> tokio::sync::watch::Receiver<bool> {
self.runtime.mailboxes.watch(agent)
}
fn ensure_child_loaded(&self, parent: ThreadId, child: ThreadId) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
let parent = self.runtime.upgrade()?.get_thread(parent).await?;
let config = parent.session.get_config().await.as_ref().clone();
self.ensure_v2_agent_loaded(config, child, Some(parent))
.await
.map(drop)
})
}
fn interrupt(
&self,
caller: ThreadId,
target: AgentTarget,
version: MultiAgentVersion,
) -> BoxFuture<'_, Result<AgentInfo>> {
Box::pin(async move {
let target = self.resolve_target(caller, &target)?;
match version {
MultiAgentVersion::Disabled | MultiAgentVersion::V1 => {
let snapshot = self.inspect_agent(target).await?;
self.interrupt_agent(target).await?;
Ok(snapshot)
}
MultiAgentVersion::V2 => self.interrupt_spawned_agent(caller, target).await,
}
})
}
fn list<'a>(
&'a self,
caller: ThreadId,
parent: Option<ThreadId>,
source: &'a SessionSource,
path_prefix: Option<&'a str>,
) -> BoxFuture<'a, Result<Vec<LiveAgent>>> {
Box::pin(async move {
self.runtime.register_session_root(caller, parent);
self.list_agents(source, path_prefix).await
})
}
fn child_agent_paths(&self, parent: ThreadId) -> BoxFuture<'_, Vec<AgentPath>> {
Box::pin(async move {
let Some(parent_path) = self
.runtime
.registry
.agent_metadata_for_thread(parent)
.and_then(|metadata| metadata.agent_path)
else {
return Vec::new();
};
let parent_prefix = format!("{parent_path}/");
let mut agent_paths = self
.runtime
.registry
.live_agents()
.into_iter()
.filter_map(|metadata| metadata.agent_path)
.filter(|path| {
path.as_str()
.strip_prefix(&parent_prefix)
.is_some_and(|name| !name.contains('/'))
})
.collect::<Vec<_>>();
let loaded_paths = self
.runtime
.open_thread_spawn_children(parent)
.await
.unwrap_or_default()
.into_iter()
.filter_map(|(_, metadata)| metadata.agent_path)
.collect::<HashSet<_>>();
agent_paths.sort();
// Stable sorting preserves alphabetical order within each group.
agent_paths.sort_by_key(|path| !loaded_paths.contains(path));
agent_paths
})
}
fn check_turn_admission(
&self,
version: MultiAgentVersion,
source: &SessionSource,
) -> Result<()> {
self.ensure_execution_capacity(version, source)
}
fn admit_turn(
&self,
version: MultiAgentVersion,
source: &SessionSource,
) -> Option<AgentExecutionGuard> {
self.execution_guard(version, source)
}
fn record_usage(&self, usage: TokenUsage) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { self.record_rollout_budget_usage(&usage) })
}
fn turn_finished<'a>(
&'a self,
outcome: AgentTurnOutcome,
trace: &'a ThreadTraceContext,
) -> BoxFuture<'a, ()> {
Box::pin(self.notify_parent_of_terminal_turn(outcome, trace))
}
fn service_tier(&self) -> Option<String> {
self.root_service_tier()
}
fn propagate_config_update(&self, update: AgentConfigUpdate) {
match update {
AgentConfigUpdate::ServiceTier(tier) => self.set_root_service_tier(tier),
}
}
fn get_guardian_package(&self, agent: ThreadId) -> BoxFuture<'_, Option<GuardianRootSnapshot>> {
Box::pin(self.root_user_authorization(agent))
}
fn pending_budget_reminder<'a>(
&'a self,
agent: ThreadId,
window: &'a str,
) -> BoxFuture<'a, Option<RolloutBudgetReminder>> {
Box::pin(async move { LocalAgentControl::pending_budget_reminder(self, agent, window) })
}
fn mark_budget_reminder_delivered<'a>(
&'a self,
agent: ThreadId,
window: &'a str,
reminder: RolloutBudgetReminder,
) -> BoxFuture<'a, ()> {
Box::pin(async move {
LocalAgentControl::mark_budget_reminder_delivered(self, agent, window, reminder);
})
}
}

View File

@@ -0,0 +1,39 @@
//! Keeps shared rollout-budget accounting and reminder state behind the controller.
//! Callers acknowledge a reminder only after it has been added to conversation history.
use super::LocalAgentControl;
use crate::rollout_budget::RolloutBudgetReminder;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::TokenUsage;
impl LocalAgentControl {
pub(crate) fn record_rollout_budget_usage(&self, usage: &TokenUsage) -> CodexResult<()> {
if self.runtime.rollout_budget.record_usage(usage)? {
return Err(CodexErr::SessionBudgetExceeded);
}
Ok(())
}
pub(crate) fn pending_budget_reminder(
&self,
thread_id: ThreadId,
window_id: &str,
) -> Option<RolloutBudgetReminder> {
self.runtime
.rollout_budget
.pending_reminder(thread_id, window_id)
}
pub(crate) fn mark_budget_reminder_delivered(
&self,
thread_id: ThreadId,
window_id: &str,
reminder: RolloutBudgetReminder,
) {
self.runtime
.rollout_budget
.mark_reminder_delivered(thread_id, window_id, reminder);
}
}

View File

@@ -0,0 +1,155 @@
//! Delivers terminal child results and completion activity to the agent tree.
//!
//! Sessions capture terminal state; the controller owns routing and queue-only delivery.
//! Delivery remains best effort; metrics distinguish queue acceptance from delivery failure.
use super::LocalAgentControl;
use crate::TurnStartOptions;
use crate::agent::api::AgentTurnOutcome;
use crate::agent_communication::AgentCommunicationContext;
use crate::agent_communication::AgentCommunicationKind;
use crate::session_prefix::format_guardian_interruption_message;
use crate::session_prefix::format_inter_agent_completion_message;
use akode_protocol::AgentPath;
use akode_protocol::items::SubAgentActivityItem;
use akode_protocol::protocol::AgentStatus;
use akode_protocol::protocol::CodexErrorInfo;
use akode_protocol::protocol::InterAgentCommunication;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentActivityKind;
use akode_protocol::protocol::SubAgentSource;
use akode_rollout_trace::AgentResultTracePayload;
use akode_rollout_trace::ThreadTraceContext;
use tracing::debug;
impl LocalAgentControl {
/// Routes a captured terminal outcome without retaining the child's live turn context.
pub(crate) async fn notify_parent_of_terminal_turn(
&self,
outcome: AgentTurnOutcome,
trace: &ThreadTraceContext,
) {
let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id,
agent_path: Some(child_agent_path),
..
}) = &outcome.source
else {
return;
};
let parent_thread_id = *parent_thread_id;
let status = outcome.status;
let Some(parent_agent_path) = child_agent_path
.as_str()
.rsplit_once('/')
.and_then(|(parent, _)| AgentPath::try_from(parent).ok())
else {
return;
};
if matches!(status, AgentStatus::Completed(_))
&& let Some(parent_turn_id) = outcome.parent_turn_id
{
let initiating_thread_id = match outcome.initiating_agent_path.as_ref() {
Some(initiating_agent_path) if initiating_agent_path != &parent_agent_path => {
self.runtime.resolve_agent_reference(
outcome.thread_id,
&outcome.source,
initiating_agent_path.as_str(),
)
.await
.inspect_err(|err| {
debug!(
"failed to resolve completed activity initiator {initiating_agent_path}: {err}"
);
})
.ok()
}
_ => Some(parent_thread_id),
};
if let Some(initiating_thread_id) = initiating_thread_id
&& let Err(err) = self
.emit_sub_agent_activity(
initiating_thread_id,
parent_turn_id,
SubAgentActivityItem {
model: None,
reasoning_effort: None,
id: format!("subagent-completed-{}", outcome.turn_id),
kind: SubAgentActivityKind::Completed,
agent_thread_id: outcome.thread_id,
agent_path: child_agent_path.clone(),
},
)
.await
{
debug!(
"failed to emit completed activity to initiating thread {initiating_thread_id}: {err}"
);
}
}
let message = match (&status, outcome.error_info) {
(AgentStatus::Errored(error), Some(CodexErrorInfo::TooManyDenials)) => {
Some(format_guardian_interruption_message(
parent_agent_path.clone(),
child_agent_path.clone(),
error,
))
}
_ => format_inter_agent_completion_message(
parent_agent_path.clone(),
child_agent_path.clone(),
&status,
),
};
let Some(message) = message else {
return;
};
// `communication` owns the message. Keep a second copy only when the
// recorder will actually need it after parent delivery succeeds.
let trace_message = trace.is_enabled().then(|| message.clone());
let communication = InterAgentCommunication::new(
child_agent_path.clone(),
parent_agent_path,
Vec::new(),
message,
/*trigger_turn*/ false,
);
let context =
AgentCommunicationContext::new(AgentCommunicationKind::Result, outcome.thread_id);
let delivery = self
.send_inter_agent_communication(
parent_thread_id,
communication,
context,
TurnStartOptions::default(),
)
.await;
if let Some(metrics) = akode_otel::global() {
let _ = metrics.counter(
"codex.multi_agent.result_delivery",
/*inc*/ 1,
&[(
"outcome",
if delivery.is_ok() { "queued" } else { "failed" },
)],
);
}
if let Err(err) = delivery {
debug!("failed to notify parent thread {parent_thread_id}: {err}");
return;
}
if let Some(message) = trace_message {
trace.record_agent_result_interaction(
outcome.turn_id.as_str(),
parent_thread_id,
&AgentResultTracePayload {
child_agent_path: child_agent_path.as_str(),
message: &message,
status: &status,
},
);
}
}
}

View File

@@ -0,0 +1,45 @@
//! Converts agent messages into attributed input while preserving their wake mode.
use crate::agent::types::AgentMessage;
use crate::agent::types::MessageDeliveryMode;
use crate::context::ContextualUserFragment;
use crate::context::InterAgentMessage;
use crate::context::InterAgentMessageType;
use akode_protocol::AgentPath;
use akode_protocol::protocol::InterAgentCommunication;
impl AgentMessage {
pub(crate) fn into_communication(
self,
author: AgentPath,
recipient: AgentPath,
mode: MessageDeliveryMode,
) -> InterAgentCommunication {
let trigger_turn = mode == MessageDeliveryMode::TriggerTurn;
match self {
Self::Encrypted(message) => InterAgentCommunication::new_encrypted(
author,
recipient,
Vec::new(),
message,
trigger_turn,
),
Self::Plaintext(message) => {
let message_type = match mode {
MessageDeliveryMode::QueueOnly => InterAgentMessageType::Message,
MessageDeliveryMode::TriggerTurn => InterAgentMessageType::NewTask,
};
let content = InterAgentMessage::new(
message_type,
recipient.clone(),
author.clone(),
message,
)
.render()
.into_text()
.unwrap_or_default();
InterAgentCommunication::new(author, recipient, Vec::new(), content, trigger_turn)
}
}
}
}

View File

@@ -0,0 +1,92 @@
//! Tracks local running capacity and releases reservations through the shared guard.
//! The local permit owns the running count; root and MAv1 turns remain unrestricted.
use super::LocalAgentControl;
use crate::agent::types::AgentExecutionGuard;
use akode_protocol::error::AgentErrorContext;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::MultiAgentVersion;
use akode_protocol::protocol::SessionSource;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
#[derive(Default)]
pub(super) struct AgentExecutionLimiter {
active: AtomicUsize,
max_threads: OnceLock<usize>,
}
struct LocalExecutionPermit {
limiter: Arc<AgentExecutionLimiter>,
}
impl Drop for LocalExecutionPermit {
fn drop(&mut self) {
self.limiter.active.fetch_sub(1, Ordering::AcqRel);
}
}
impl LocalAgentControl {
pub(crate) fn ensure_execution_capacity(
&self,
multi_agent_version: MultiAgentVersion,
session_source: &SessionSource,
) -> CodexResult<()> {
if !is_execution_limited(multi_agent_version, session_source) {
return Ok(());
}
let max_threads = self.runtime.agent_execution_limiter.max_threads();
if self.runtime.agent_execution_limiter.has_capacity() {
Ok(())
} else {
Err(
CodexErr::new(CodexErrorDetails::AgentLimitReached { max_threads })
.with_agent_context(AgentErrorContext::ExecutionCapacity),
)
}
}
pub(crate) fn execution_guard(
&self,
multi_agent_version: MultiAgentVersion,
session_source: &SessionSource,
) -> Option<AgentExecutionGuard> {
is_execution_limited(multi_agent_version, session_source)
.then(|| Arc::clone(&self.runtime.agent_execution_limiter).guard())
}
}
impl AgentExecutionLimiter {
pub(super) fn initialize(&self, max_threads: usize) {
self.max_threads.get_or_init(|| max_threads);
}
fn max_threads(&self) -> usize {
self.max_threads.get().copied().unwrap_or(usize::MAX)
}
fn has_capacity(&self) -> bool {
self.active.load(Ordering::Acquire) < self.max_threads()
}
fn guard(self: Arc<Self>) -> AgentExecutionGuard {
self.active.fetch_add(1, Ordering::AcqRel);
AgentExecutionGuard::new(LocalExecutionPermit { limiter: self })
}
}
fn is_execution_limited(
multi_agent_version: MultiAgentVersion,
session_source: &SessionSource,
) -> bool {
multi_agent_version == MultiAgentVersion::V2
&& matches!(session_source, SessionSource::SubAgent(_))
}
#[cfg(test)]
#[path = "execution_tests.rs"]
mod tests;

View File

@@ -0,0 +1,64 @@
use crate::agent::LocalAgentControl;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::protocol::MultiAgentVersion;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
use pretty_assertions::assert_eq;
fn control_with_limit(max_threads: usize) -> LocalAgentControl {
let control = LocalAgentControl::default();
control
.runtime
.agent_execution_limiter
.initialize(max_threads);
control
}
#[test]
fn execution_guards_count_active_v2_subagent_turns() {
let control = control_with_limit(/*max_threads*/ 1);
// Child role configs cannot replace the root-derived session limit.
control
.runtime
.agent_execution_limiter
.initialize(/*max_threads*/ 2);
let source = SessionSource::SubAgent(SubAgentSource::Other("worker".to_string()));
control
.ensure_execution_capacity(MultiAgentVersion::V2, &source)
.expect("first active turn should fit");
let first = control
.execution_guard(MultiAgentVersion::V2, &source)
.expect("v2 subagent execution should be counted");
let Err(err) = control.ensure_execution_capacity(MultiAgentVersion::V2, &source) else {
panic!("second active turn should exceed the derived non-root cap");
};
let CodexErrorDetails::AgentLimitReached { max_threads } = err.details() else {
panic!("expected AgentLimitReached");
};
assert_eq!(*max_threads, 1);
drop(first);
control
.ensure_execution_capacity(MultiAgentVersion::V2, &source)
.expect("capacity should be released when the running task drops");
}
#[test]
fn execution_guards_ignore_root_and_v1_turns() {
let control = control_with_limit(/*max_threads*/ 0);
assert!(
control
.execution_guard(MultiAgentVersion::V2, &SessionSource::Cli)
.is_none()
);
assert!(
control
.execution_guard(
MultiAgentVersion::V1,
&SessionSource::SubAgent(SubAgentSource::Other("worker".to_string())),
)
.is_none()
);
}

View File

@@ -0,0 +1,32 @@
//! Reads registered agent identity, status and settings without restoring a runtime.
//! Known unloaded agents stay distinct from missing identities and backend failures.
use super::LocalAgentControl;
use crate::agent::api::AgentInfo;
use crate::agent::types::LiveAgent;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::Result as CodexResult;
impl LocalAgentControl {
pub(super) async fn inspect_agent(&self, thread_id: ThreadId) -> CodexResult<AgentInfo> {
let manager = self.runtime.upgrade()?;
let thread = match manager.get_thread(thread_id).await {
Ok(thread) => thread,
Err(err) if matches!(err.details(), CodexErrorDetails::ThreadNotFound(_)) => {
return Ok(AgentInfo::Unloaded(
self.runtime.ensure_agent_known(thread_id)?,
));
}
Err(err) => return Err(err),
};
Ok(AgentInfo::Loaded {
agent: LiveAgent {
thread_id,
metadata: self.get_agent_metadata(thread_id).unwrap_or_default(),
status: thread.agent_status().await,
},
config: Box::new(thread.config_snapshot().await),
})
}
}

View File

@@ -0,0 +1,52 @@
//! Applies V2 interruption rules to a registered agent without loading its runtime.
//!
//! Root and self targets are rejected. An unloaded or already-dead runtime is a successful
//! interruption; this operation never reloads it.
use super::LocalAgentControl;
use crate::agent::api::AgentInfo;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::Result as CodexResult;
impl LocalAgentControl {
/// Interrupts a spawned agent's current task, preserving the status observed before dispatch.
pub(crate) async fn interrupt_spawned_agent(
&self,
caller: ThreadId,
target: ThreadId,
) -> CodexResult<AgentInfo> {
let receiver_agent = self.runtime.ensure_agent_known(target)?;
if receiver_agent
.agent_path
.as_ref()
.is_some_and(AgentPath::is_root)
{
return Err(CodexErr::UnsupportedOperation(
"root is not a spawned agent".to_string(),
));
}
if target == caller {
return Err(CodexErr::UnsupportedOperation(
"an agent cannot interrupt itself; return your result and let the parent interrupt you if needed"
.to_string(),
));
}
receiver_agent.agent_path.as_ref().ok_or_else(|| {
CodexErr::UnsupportedOperation("target agent is missing an agent_path".to_string())
})?;
let snapshot = self.inspect_agent(target).await?;
match self.interrupt_agent(target).await {
Ok(_) => {}
Err(err)
if matches!(
err.details(),
CodexErrorDetails::ThreadNotFound(_) | CodexErrorDetails::InternalAgentDied
) => {}
Err(err) => return Err(err),
}
Ok(snapshot)
}
}

View File

@@ -0,0 +1,127 @@
use super::*;
use crate::agent::api::AgentInfo;
use akode_protocol::error::CodexErrorDetails;
use akode_thread_store::PersistContext;
impl LocalAgentControl {
/// Submit a shutdown request for a live agent without marking it explicitly closed in
/// persisted spawn-edge state.
pub(crate) async fn shutdown_live_agent(&self, agent_id: ThreadId) -> CodexResult<String> {
let state = self.runtime.upgrade()?;
let result = if let Ok(thread) = state.get_thread(agent_id).await {
thread
.session
.ensure_rollout_materialized(PersistContext::Standard)
.await;
thread.session.flush_rollout().await?;
let result = if matches!(thread.agent_status().await, AgentStatus::Shutdown) {
Ok(String::new())
} else {
state
.send_op(
agent_id,
Op::Shutdown {},
/*parent_turn_id*/ None,
/*root_turn_id*/ None,
/*message_delivery*/ None,
)
.await
};
thread.wait_until_terminated().await;
result
} else {
state
.send_op(
agent_id,
Op::Shutdown {},
/*parent_turn_id*/ None,
/*root_turn_id*/ None,
/*message_delivery*/ None,
)
.await
};
let _ = state.remove_thread(&agent_id).await;
self.forget_v2_residency(agent_id);
self.runtime.registry.release_spawned_thread(agent_id);
self.runtime.mailboxes.remove(agent_id);
result
}
/// Mark `agent_id` as explicitly closed in persisted spawn-edge state, then shut down the
/// agent and any live descendants reached from the in-memory tree.
pub(crate) async fn close_agent(&self, agent_id: ThreadId) -> CodexResult<AgentInfo> {
let state = self.runtime.upgrade()?;
let metadata = self.get_agent_metadata(agent_id);
let known_agent = metadata.is_some();
let snapshot = match state.get_thread(agent_id).await {
Ok(thread) => {
let agent = LiveAgent {
thread_id: agent_id,
metadata: metadata.unwrap_or_default(),
status: thread.agent_status().await,
};
let config = Box::new(thread.config_snapshot().await);
if !config.ephemeral
&& let Some(agent_graph_store) = state.agent_graph_store()
&& let Err(err) = agent_graph_store
.set_thread_spawn_edge_status(
agent_id,
akode_agent_graph_store::ThreadSpawnEdgeStatus::Closed,
)
.await
{
warn!("failed to persist thread-spawn edge status for {agent_id}: {err}");
}
AgentInfo::Loaded { agent, config }
}
Err(err)
if known_agent && matches!(err.details(), CodexErrorDetails::ThreadNotFound(_)) =>
{
if let Some(agent_graph_store) = state.agent_graph_store()
&& let Err(err) = agent_graph_store
.set_thread_spawn_edge_status(
agent_id,
akode_agent_graph_store::ThreadSpawnEdgeStatus::Closed,
)
.await
{
return Err(CodexErr::Fatal(format!(
"failed to persist stale thread-spawn edge status for {agent_id}: {err}"
)));
}
AgentInfo::Unloaded(metadata.unwrap_or_default())
}
Err(err) => return Err(err),
};
match Box::pin(self.shutdown_agent_tree(agent_id)).await {
Err(err)
if known_agent
&& matches!(
err.details(),
CodexErrorDetails::ThreadNotFound(_) | CodexErrorDetails::InternalAgentDied
) =>
{
Ok(snapshot)
}
result => result.map(|_| snapshot),
}
}
/// Shut down `agent_id` and any live descendants reachable from the in-memory spawn tree.
pub(crate) async fn shutdown_agent_tree(&self, agent_id: ThreadId) -> CodexResult<String> {
let descendant_ids = self.runtime.live_thread_spawn_descendants(agent_id).await?;
let result = self.shutdown_live_agent(agent_id).await;
for descendant_id in descendant_ids {
match self.shutdown_live_agent(descendant_id).await {
Ok(_) => {}
Err(err)
if matches!(
err.details(),
CodexErrorDetails::ThreadNotFound(_) | CodexErrorDetails::InternalAgentDied
) => {}
Err(err) => return Err(err),
}
}
result
}
}

View File

@@ -0,0 +1,116 @@
//! Retains queue-only mail while local sessions are unloaded.
//! Eviction transfers mail before releasing the recipient's residency guard.
use crate::PendingAgentMessage;
use crate::agent_communication::PENDING_MAILBOX_MESSAGES;
use akode_diagnostics::GaugeGuard;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::PoisonError;
use tokio::sync::watch;
pub(super) struct Mailboxes(Mutex<Option<HashMap<ThreadId, Mailbox>>>);
impl Default for Mailboxes {
fn default() -> Self {
Self(Mutex::new(Some(HashMap::new())))
}
}
#[derive(Default)]
struct Mailbox {
pending: Vec<StoredMail>,
state: watch::Sender<bool>,
}
struct StoredMail {
id: Option<String>,
communication: PendingAgentMessage,
_diagnostics_guard: GaugeGuard,
}
impl Mailboxes {
pub(super) fn enqueue(
&self,
agent: ThreadId,
id: Option<String>,
messages: Vec<PendingAgentMessage>,
) -> Result<()> {
let mut mailboxes = self.0.lock().unwrap_or_else(PoisonError::into_inner);
let mailbox = mailboxes
.as_mut()
.ok_or_else(|| CodexErr::InvalidRequest("agent runtime is shutting down".into()))?
.entry(agent)
.or_default();
mailbox
.pending
.extend(messages.into_iter().map(|communication| StoredMail {
id: id.clone(),
communication,
_diagnostics_guard: PENDING_MAILBOX_MESSAGES.track(),
}));
mailbox.state.send_replace(!mailbox.pending.is_empty());
Ok(())
}
pub(super) fn take(&self, agent: ThreadId) -> Vec<PendingAgentMessage> {
let mut mailboxes = self.0.lock().unwrap_or_else(PoisonError::into_inner);
let Some(mailbox) = mailboxes
.as_mut()
.and_then(|mailboxes| mailboxes.get_mut(&agent))
else {
return Vec::new();
};
let pending = std::mem::take(&mut mailbox.pending);
mailbox.state.send_if_modified(std::mem::take);
pending
.into_iter()
.map(|mail| {
// Mail transferred during eviction was already received by the old session.
if let Some(id) = mail.id {
crate::agent_communication::emit_agent_communication_receive(&id);
}
mail.communication
})
.collect()
}
pub(super) fn watch(&self, agent: ThreadId) -> watch::Receiver<bool> {
let mut mailboxes = self.0.lock().unwrap_or_else(PoisonError::into_inner);
match mailboxes.as_mut() {
Some(mailboxes) => {
// Private delegates and cancelled startups can stop without explicit removal.
// Retain unread mail and live subscriptions, but reclaim abandoned empty entries.
mailboxes.retain(|_, mailbox| {
!mailbox.pending.is_empty() || mailbox.state.receiver_count() != 0
});
mailboxes.entry(agent).or_default().state.subscribe()
}
None => watch::channel(/*init*/ false).1,
}
}
pub(super) fn remove(&self, agent: ThreadId) {
// Dropping pending mail can run extension destructors. Release the lock first.
let mailbox = self
.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.as_mut()
.and_then(|mailboxes| mailboxes.remove(&agent));
drop(mailbox);
}
pub(super) fn close(&self) {
// Detach under the lock, then notify readers and drop pending mail outside it.
let mailboxes = self.0.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(mailboxes) = mailboxes {
for mailbox in mailboxes.values() {
mailbox.state.send_replace(false);
}
}
}
}

View File

@@ -0,0 +1,350 @@
//! Accounts for resident MAv2 children and unloads exact idle runtimes while preserving their state.
use super::LocalAgentControl;
use super::LocalAgentRuntime;
use super::runtime::AgentTreeMembership;
use crate::agent::AgentStatus;
use crate::agent::host::AgentRuntimeServices;
use crate::agent::registry::EvictedEnvironments;
use crate::codex_thread::CodexThread;
use crate::config::Config;
use crate::thread_manager::ThreadManagerState;
use akode_protocol::ThreadId;
use akode_protocol::error::AgentErrorContext;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrKind;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::MultiAgentVersion;
use akode_protocol::protocol::SessionSource;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use tracing::warn;
/// The result of trying to unload one exact MAv2 child runtime.
#[derive(Debug, PartialEq, Eq)]
pub enum ThreadEvictionOutcome {
/// Work or another teardown owns the runtime; retry later.
Busy,
/// This operation stopped and removed the runtime.
Evicted,
/// The runtime was removed or replaced; leave its replacement alone.
NotCurrent,
}
impl ThreadManagerState {
pub(crate) async fn try_evict_v2_thread(
self: &Arc<Self>,
thread: Arc<CodexThread>,
membership: &AgentTreeMembership,
) -> CodexResult<ThreadEvictionOutcome> {
let Ok(residency_guard) = Arc::clone(&thread.residency_gate).try_write_owned() else {
return Ok(ThreadEvictionOutcome::Busy);
};
let thread_id = thread.session.thread_id;
if !self
.get_thread(thread_id)
.await
.is_ok_and(|registered| Arc::ptr_eq(&registered, &thread))
{
return Ok(ThreadEvictionOutcome::NotCurrent);
}
if !is_resident_candidate(&thread) || !is_unloadable(&thread).await {
return Ok(ThreadEvictionOutcome::Busy);
}
let manager = Arc::clone(self);
let teardown = membership
.clone()
.into_teardown_guard("resident_eviction", Some(thread_id));
// Once shutdown is submitted, cancellation cannot release delivery or capacity early.
tokio::spawn(async move {
let _residency_guard = residency_guard;
thread.ensure_rollout_materialized().await;
if let Err(err) = thread.shutdown_and_wait().await {
teardown.record_shutdown_failure("stop_resident", CodexErrKind::from(&err).into());
teardown.complete();
return Err(err);
}
// Dispatch has stopped and the residency guard excludes senders. A tree
// shutdown deliberately discards its mailbox instead of retaining it.
let mail = thread
.session
.input_queue
.drain_mailbox()
.await
.into_iter()
.map(|mail| mail.communication)
.collect();
let runtime = &thread.session.services.local_agent_runtime;
let _ = runtime.mailboxes.enqueue(thread_id, /*id*/ None, mail);
// Reuse the same effective configuration snapshot as a fork. This includes live
// permissions and network restrictions that a profile name cannot reconstruct.
let (config, ..) = thread.session.fork_config().await;
// Preserve configured bindings across eviction without retaining turn-only attachments.
// Raw bindings keep the original pending owner configuration alive.
let environments = EvictedEnvironments {
config: Arc::new(config),
has_independent_service_tier: matches!(
&thread.session.agent_runtime,
AgentRuntimeServices::Host(services) if services.service_tier.is_none()
),
selections: thread.environment_selections().await,
bindings: thread
.session
.services
.turn_environments
.configured_snapshot_now(),
};
let mut threads = manager.threads.write().await;
if threads
.get(&thread_id)
.is_some_and(|registered| !Arc::ptr_eq(registered, &thread))
{
teardown.complete();
return Ok(ThreadEvictionOutcome::NotCurrent);
}
runtime
.registry
.save_evicted_environments(thread_id, environments);
let removed = threads.remove(&thread_id).is_some();
runtime.residency.remove(thread_id);
teardown.complete();
Ok(if removed {
ThreadEvictionOutcome::Evicted
} else {
ThreadEvictionOutcome::NotCurrent
})
})
.await?
}
}
#[derive(Default)]
pub(super) struct V2Residency {
state: Mutex<V2ResidencyState>,
}
#[derive(Default)]
struct V2ResidencyState {
residents: VecDeque<ThreadId>,
pending_slots: usize,
}
pub(super) struct V2ResidencySlot {
residency: Arc<V2Residency>,
active: bool,
}
impl V2ResidencySlot {
pub(super) fn commit(mut self, thread_id: ThreadId) {
self.residency.commit_slot(thread_id);
self.active = false;
}
}
impl Drop for V2ResidencySlot {
fn drop(&mut self) {
if self.active {
self.residency.release_pending_slot();
}
}
}
impl LocalAgentControl {
pub(super) async fn reserve_v2_residency_slot(
&self,
state: &Arc<ThreadManagerState>,
config: &Config,
membership: &AgentTreeMembership,
protected_thread_id: Option<ThreadId>,
) -> CodexResult<V2ResidencySlot> {
let capacity = config
.effective_agent_max_threads(MultiAgentVersion::V2)
.unwrap_or(usize::MAX);
Arc::clone(&self.runtime.residency)
.reserve_slot(state, capacity, membership, protected_thread_id)
.await
}
pub(super) fn forget_v2_residency(&self, thread_id: ThreadId) {
self.runtime.residency.remove(thread_id);
}
}
impl LocalAgentRuntime {
/// Pins and touches the registered runtime without waiting for unrelated eviction.
pub(crate) async fn pin_v2_residency(
&self,
thread: &CodexThread,
) -> CodexResult<Option<tokio::sync::OwnedRwLockReadGuard<()>>> {
if !is_resident_candidate(thread) {
return Ok(None);
}
let guard = Arc::clone(&thread.residency_gate).read_owned().await;
let thread_id = thread.session.thread_id;
let registered = self.upgrade()?.get_thread(thread_id).await?;
if !std::ptr::eq(thread, registered.as_ref()) {
return Err(CodexErr::ThreadNotFound(thread_id));
}
self.residency.touch(thread_id);
Ok(Some(guard))
}
}
impl V2Residency {
async fn reserve_slot(
self: Arc<Self>,
manager: &Arc<ThreadManagerState>,
capacity: usize,
membership: &AgentTreeMembership,
protected_thread_id: Option<ThreadId>,
) -> CodexResult<V2ResidencySlot> {
loop {
if self.try_reserve_pending_slot(capacity) {
return Ok(V2ResidencySlot {
residency: self,
active: true,
});
}
if !self
.try_unload_one_resident(manager, membership, protected_thread_id)
.await
{
return Err(CodexErr::new(CodexErrorDetails::AgentLimitReached {
max_threads: capacity,
})
.with_agent_context(AgentErrorContext::ResidencyCapacity));
}
}
}
fn try_reserve_pending_slot(&self, capacity: usize) -> bool {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.residents.len().saturating_add(state.pending_slots) >= capacity {
return false;
}
state.pending_slots += 1;
true
}
async fn try_unload_one_resident(
self: &Arc<Self>,
manager: &Arc<ThreadManagerState>,
membership: &AgentTreeMembership,
protected_thread_id: Option<ThreadId>,
) -> bool {
// Keep shutting-down workers counted until removal. Each runtime's write guard
// excludes delivery and competing evictions without blocking unrelated workers.
let candidates = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.residents
.clone();
for candidate_thread_id in candidates {
if Some(candidate_thread_id) == protected_thread_id {
continue;
}
let candidate_thread = {
let threads = manager.threads.read().await;
match threads.get(&candidate_thread_id) {
Some(thread) if is_resident_candidate(thread) => Arc::clone(thread),
Some(_) | None => {
// A reload cannot publish between the lookup and stale-entry removal.
self.remove(candidate_thread_id);
return true;
}
}
};
// Capacity eviction keeps its existing policy of retaining unstarted workers.
if matches!(
candidate_thread.agent_status().await,
AgentStatus::PendingInit
) {
continue;
}
match manager
.try_evict_v2_thread(candidate_thread, membership)
.await
{
Ok(ThreadEvictionOutcome::Evicted | ThreadEvictionOutcome::NotCurrent) => {
return true;
}
Ok(ThreadEvictionOutcome::Busy) => {}
Err(err) => warn!("v2 resident eviction failed: {err}"),
}
}
false
}
fn touch(&self, thread_id: ThreadId) {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
touch_resident(&mut state.residents, thread_id);
}
fn remove(&self, thread_id: ThreadId) {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.residents
.retain(|resident_thread_id| *resident_thread_id != thread_id);
}
fn commit_slot(&self, thread_id: ThreadId) {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.pending_slots = state.pending_slots.saturating_sub(1);
touch_resident(&mut state.residents, thread_id);
}
fn release_pending_slot(&self) {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.pending_slots = state.pending_slots.saturating_sub(1);
}
}
fn touch_resident(residents: &mut VecDeque<ThreadId>, thread_id: ThreadId) {
residents.retain(|resident_thread_id| *resident_thread_id != thread_id);
residents.push_back(thread_id);
}
fn is_resident_candidate(thread: &CodexThread) -> bool {
thread.multi_agent_version() == Some(MultiAgentVersion::V2)
&& is_v2_resident_session_source(&thread.session_source)
}
pub(super) fn is_v2_resident_session_source(session_source: &SessionSource) -> bool {
matches!(session_source, SessionSource::SubAgent(_))
}
async fn is_unloadable(thread: &CodexThread) -> bool {
matches!(
thread.agent_status().await,
AgentStatus::PendingInit
| AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Interrupted
) && thread.session.active_turn.lock().await.is_none()
&& !thread.session.has_outstanding_durable_sleep()
&& !thread
.session
.input_queue
.has_trigger_turn_mailbox_items()
.await
}
#[cfg(test)]
#[path = "residency_tests.rs"]
mod tests;

View File

@@ -0,0 +1,267 @@
use crate::StartThreadOptions;
use crate::ThreadManager;
use crate::agent::LocalAgentControl;
use crate::codex_thread::CodexThread;
use crate::config::Config;
use crate::config::test_config;
use crate::thread_manager::ThreadManagerState;
use akode_features::Feature;
use akode_login::CodexAuth;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::InterAgentCommunication;
use akode_protocol::protocol::Op;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
use akode_protocol::protocol::ThreadSettingsOverrides;
use akode_protocol::protocol::ThreadSource;
use akode_protocol::protocol::TurnAbortReason;
use akode_protocol::protocol::TurnAbortedEvent;
use akode_protocol::protocol::TurnCompleteEvent;
use pretty_assertions::assert_eq;
use std::sync::Arc;
#[tokio::test]
async fn residency_slot_reservation_unloads_oldest_idle_v2_agent() {
let mut config = test_config().await;
let _ = config.features.enable(Feature::MultiAgentV2);
config.multi_agent_v2.max_concurrent_threads_per_session = 2;
let temp_home = tempfile::tempdir().expect("create temp home");
config.codex_home = temp_home.path().to_path_buf().try_into().unwrap();
config.cwd = temp_home.path().to_path_buf().try_into().unwrap();
let manager = ThreadManager::with_models_provider_and_home_for_tests(
CodexAuth::from_api_key("dummy"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(akode_exec_server::EnvironmentManager::default_for_tests()),
);
let root = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start root thread");
let control = manager.agent_control();
let state = control
.runtime
.upgrade()
.expect("thread manager should be live");
let membership = control.runtime.admit_start().expect("admit residency work");
let first_slot = control
.reserve_v2_residency_slot(
&state,
&config,
&membership,
/*protected_thread_id*/ None,
)
.await
.expect("first resident slot");
let first =
spawn_v2_subagent(&control, &state, config.clone(), root.thread_id, "worker-1").await;
first_slot.commit(first.thread_id);
mark_thread_completed(first.thread.as_ref()).await;
// Public message submission must honor the same eviction gate as MAv2 sends.
let eviction_gate = Arc::clone(&first.thread.residency_gate).write_owned().await;
let communication = InterAgentCommunication::new(
AgentPath::root(),
AgentPath::try_from("/root/worker_1").unwrap(),
Vec::new(),
"queued notice".into(),
/*trigger_turn*/ false,
);
let delivery = first.thread.submit(Op::InterAgentCommunication {
communication: communication.clone(),
start_options: Default::default(),
});
tokio::pin!(delivery);
assert!(futures::poll!(delivery.as_mut()).is_pending());
drop(eviction_gate);
delivery.await.expect("submit after eviction gate releases");
first
.thread
.update_thread_settings(ThreadSettingsOverrides::default())
.await
.expect("dispatch queued notice before eviction");
let second_slot = control
.reserve_v2_residency_slot(
&state,
&config,
&membership,
/*protected_thread_id*/ None,
)
.await
.expect("second resident slot should evict the first idle agent");
match manager.get_thread(first.thread_id).await {
Err(err) => match err.details() {
CodexErrorDetails::ThreadNotFound(thread_id) => assert_eq!(*thread_id, first.thread_id),
_ => panic!("expected evicted thread to be missing, got {err:?}"),
},
Ok(_) => panic!("expected evicted thread to be missing"),
}
let retained = first
.thread
.session
.services
.local_agent_runtime
.mailboxes
.take(first.thread_id);
assert_eq!(retained, vec![communication.into()]);
let second = spawn_v2_subagent(&control, &state, config, root.thread_id, "worker-2").await;
second_slot.commit(second.thread_id);
assert!(manager.get_thread(root.thread_id).await.is_ok());
assert!(manager.get_thread(second.thread_id).await.is_ok());
}
#[tokio::test]
async fn interrupted_v2_agent_is_lost_after_residency_eviction() {
let mut config = test_config().await;
let _ = config.features.enable(Feature::MultiAgentV2);
config.multi_agent_v2.max_concurrent_threads_per_session = 2;
let temp_home = tempfile::tempdir().expect("create temp home");
config.codex_home = temp_home.path().to_path_buf().try_into().unwrap();
config.cwd = temp_home.path().to_path_buf().try_into().unwrap();
let manager = ThreadManager::with_models_provider_and_home_for_tests(
CodexAuth::from_api_key("dummy"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(akode_exec_server::EnvironmentManager::default_for_tests()),
);
let root = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start root thread");
let control = manager.agent_control();
let state = control
.runtime
.upgrade()
.expect("thread manager should be live");
let membership = control.runtime.admit_start().expect("admit residency work");
let first_slot = control
.reserve_v2_residency_slot(
&state,
&config,
&membership,
/*protected_thread_id*/ None,
)
.await
.expect("first resident slot");
let first =
spawn_v2_subagent(&control, &state, config.clone(), root.thread_id, "worker-1").await;
first_slot.commit(first.thread_id);
mark_thread_interrupted(first.thread.as_ref()).await;
let second_slot = control
.reserve_v2_residency_slot(
&state,
&config,
&membership,
/*protected_thread_id*/ None,
)
.await
.expect("second resident slot should evict the first interrupted idle agent");
match manager.get_thread(first.thread_id).await {
Err(err) => match err.details() {
CodexErrorDetails::ThreadNotFound(thread_id) => assert_eq!(*thread_id, first.thread_id),
_ => panic!("expected evicted thread to be missing, got {err:?}"),
},
Ok(_) => panic!("expected evicted thread to be missing"),
}
let second =
spawn_v2_subagent(&control, &state, config.clone(), root.thread_id, "worker-2").await;
second_slot.commit(second.thread_id);
mark_thread_completed(second.thread.as_ref()).await;
let err = control
.ensure_v2_agent_loaded(config, first.thread_id, /*parent*/ None)
.await
.expect_err("evicted interrupted agent should stay lost");
match err.details() {
CodexErrorDetails::ThreadNotFound(thread_id) => assert_eq!(*thread_id, first.thread_id),
_ => panic!("expected ThreadNotFound, got {err:?}"),
}
assert!(manager.get_thread(root.thread_id).await.is_ok());
assert!(manager.get_thread(second.thread_id).await.is_ok());
match manager.get_thread(first.thread_id).await {
Err(err) => match err.details() {
CodexErrorDetails::ThreadNotFound(thread_id) => assert_eq!(*thread_id, first.thread_id),
_ => panic!("expected evicted thread to be missing, got {err:?}"),
},
Ok(_) => panic!("expected evicted thread to be missing"),
}
}
async fn spawn_v2_subagent(
control: &LocalAgentControl,
state: &Arc<ThreadManagerState>,
config: Config,
parent_thread_id: ThreadId,
label: &str,
) -> crate::thread_manager::NewThread {
state
.spawn_child_thread(
crate::thread_manager::StartThreadOptions {
session_source: Some(SessionSource::SubAgent(SubAgentSource::Other(
label.to_string(),
))),
thread_source: Some(ThreadSource::Subagent),
..crate::thread_manager::StartThreadOptions::new(config)
},
control.clone(),
Some(parent_thread_id),
/*inherited_exec_policy*/ None,
)
.await
.expect("spawn v2 subagent")
}
async fn mark_thread_completed(thread: &CodexThread) {
let turn = thread.session.new_default_turn().await;
thread
.session
.send_event(
turn.as_ref(),
EventMsg::TurnComplete(TurnCompleteEvent {
root_turn_id: None,
turn_id: turn.sub_id.clone(),
started_at: None,
last_agent_message: Some("done".to_string()),
error: None,
completed_at: None,
duration_ms: None,
time_to_first_token_ms: None,
}),
)
.await;
clear_active_turn(thread).await;
}
async fn mark_thread_interrupted(thread: &CodexThread) {
let turn = thread.session.new_default_turn().await;
thread
.session
.send_event(
turn.as_ref(),
EventMsg::TurnAborted(TurnAbortedEvent {
root_turn_id: None,
turn_id: Some(turn.sub_id.clone()),
started_at: None,
reason: TurnAbortReason::Interrupted,
error: None,
completed_at: None,
duration_ms: None,
}),
)
.await;
clear_active_turn(thread).await;
}
async fn clear_active_turn(thread: &CodexThread) {
// The fixture has no task runner to clear the turn after the terminal event.
*thread.session.active_turn.lock().await = None;
}

View File

@@ -0,0 +1,37 @@
//! Reopens an agent only when its runtime is absent, then returns its effective state.
//! Rollout and descendant restoration remain in the existing local startup path.
use super::LocalAgentControl;
use crate::agent::types::LiveAgent;
use crate::codex_thread::ThreadConfigSnapshot;
use crate::config::Config;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::SessionSource;
impl LocalAgentControl {
pub(crate) async fn resume_agent(
&self,
config: Config,
thread_id: ThreadId,
source: SessionSource,
) -> CodexResult<(LiveAgent, ThreadConfigSnapshot)> {
let manager = self.runtime.upgrade()?;
let thread = match manager.get_thread(thread_id).await {
Ok(thread) => thread,
Err(err) if matches!(err.details(), CodexErrorDetails::ThreadNotFound(_)) => {
Box::pin(self.resume_agent_from_rollout(config, thread_id, source)).await?;
manager.get_thread(thread_id).await?
}
Err(err) => return Err(err),
};
let agent = LiveAgent {
thread_id,
metadata: self.get_agent_metadata(thread_id).unwrap_or_default(),
status: thread.agent_status().await,
};
let config = thread.config_snapshot().await;
Ok((agent, config))
}
}

View File

@@ -0,0 +1,103 @@
//! Best-effort handoff windows plus recent root context, without saved handoff state.
//! History position approximates dispatch order; absent calls leave the existing context unchanged.
//! User inputs bypass relevance filtering; only assistant context is narrowed.
use akode_history::ResponseItemEnvelope;
use akode_history::RetainedContextOrder;
use akode_protocol::AgentPath;
use akode_protocol::ToolName;
use akode_protocol::models::ExecutedToolCallArguments;
use akode_protocol::models::ResponseItem;
pub(super) fn handoff_boundaries(
history: &[ResponseItemEnvelope],
worker: &AgentPath,
tool_namespace: Option<&str>,
) -> Vec<RetainedContextOrder> {
let configured_handoff_names = ["spawn_agent", "send_message", "followup_task"].map(|name| {
(
akode_tools::code_mode_name_for_tool_name(&ToolName::new(
tool_namespace.map(str::to_owned),
name,
)),
name,
)
});
let mut boundaries = Vec::new();
let mut preceding_order = None;
for envelope in history {
if let Some(order) = envelope.metadata.as_ref().and_then(|metadata| {
(!metadata.inherited_user_message)
.then_some(metadata.user_input_order)
.flatten()
}) {
preceding_order = Some(RetainedContextOrder::Local(order));
}
let direct = match &envelope.item {
ResponseItem::FunctionCall {
name,
namespace,
arguments,
..
} if namespace.as_deref().is_none_or(|namespace| {
namespace == "collaboration"
|| Some(namespace) == tool_namespace
|| namespace == akode_protocol::DEFAULT_FUNCTION_NAMESPACE
}) =>
{
serde_json::from_str(arguments)
.ok()
.is_some_and(|args| is_handoff(name, &args, worker))
}
_ => false,
};
// Recorded nested calls are usable when present. Never parse JavaScript to infer sends.
let nested = envelope
.item
.executed_tool_call_metadata()
.is_some_and(|metadata| {
metadata.executed_tool_calls.iter().flatten().any(|call| {
let ExecutedToolCallArguments::Raw(args) = call.arguments() else {
return false;
};
let name = configured_handoff_names
.iter()
.find_map(|(recorded_name, name)| {
(recorded_name == &call.name).then_some(*name)
})
.unwrap_or(&call.name);
is_handoff(name, args, worker)
})
});
if (direct || nested)
&& let Some(boundary) = preceding_order
{
boundaries.push(boundary);
}
}
boundaries
}
fn is_handoff(name: &str, args: &serde_json::Value, worker: &AgentPath) -> bool {
let name = name
.strip_prefix("collaboration.")
.or_else(|| name.strip_prefix("collaboration__"))
.unwrap_or(name);
let field = match name {
"spawn_agent" => "task_name",
"send_message" | "followup_task" => "target",
_ => return false,
};
let Some(recipient) = args[field]
.as_str()
.and_then(|target| AgentPath::root().resolve(target).ok())
.filter(|path| !path.is_root())
else {
return false;
};
worker == &recipient
|| worker
.as_str()
.strip_prefix(recipient.as_str())
.is_some_and(|suffix| suffix.starts_with('/'))
}

View File

@@ -0,0 +1,385 @@
//! Shared state and startup bindings for one local agent tree.
//! Registry identity is allocation identity; cloning this handle preserves ownership checks.
use super::LocalAgentControl;
use super::execution::AgentExecutionLimiter;
use super::residency::V2Residency;
use crate::agent::api::AgentControl;
use crate::agent::registry::AgentRegistry;
use crate::config::RolloutBudgetConfig;
use crate::rollout_budget::RolloutBudget;
use crate::session::session::Session;
use crate::state::ContextWindowIdGenerator;
use crate::thread_manager::AgentTreeShutdownFailure;
use crate::thread_manager::AgentTreeShutdownFailureReason;
use crate::thread_manager::AgentTreeShutdownReport;
use crate::thread_manager::ThreadIdGenerator;
use crate::thread_manager::ThreadManagerState;
use arc_swap::ArcSwapOption;
use akode_extension_api::ThreadInstructionsProvider;
use akode_protocol::AgentPath;
use akode_protocol::ItemIdGenerator;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::AgentErrorContext;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
use akode_rollout_trace::ThreadTraceContext;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::PoisonError;
use std::sync::Weak;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tokio_util::task::task_tracker::TaskTrackerToken;
use uuid::Uuid;
// Avoid retaining an unbounded number of failures during a long-lived tree's lifetime.
const MAX_RETAINED_SHUTDOWN_FAILURES: usize = 64;
#[derive(Debug)]
pub(crate) struct AgentTreeShutdownState {
members: TaskTracker,
report: Mutex<AgentTreeShutdownReport>,
}
impl Default for AgentTreeShutdownState {
fn default() -> Self {
Self {
members: TaskTracker::new(),
report: Mutex::new(AgentTreeShutdownReport {
tree_id: Uuid::now_v7(),
failures: Vec::new(),
omitted_failures: 0,
}),
}
}
}
impl AgentTreeShutdownState {
pub(crate) async fn wait(&self) -> CodexResult<()> {
self.wait_detailed()
.await
.map_err(|_| CodexErr::Fatal("agent tree shutdown did not complete cleanly".to_owned()))
}
pub(crate) async fn wait_detailed(&self) -> Result<(), AgentTreeShutdownReport> {
self.members.wait().await;
// Reporters hold a membership until after recording failures. Once the tracker drains,
// no admitted operation can add a failure after the snapshot.
let report = self
.report
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
if report.failures.is_empty() && report.omitted_failures == 0 {
Ok(())
} else {
Err(report)
}
}
fn record_failure(&self, failure: AgentTreeShutdownFailure) {
let tree_id = {
let mut report = self.report.lock().unwrap_or_else(PoisonError::into_inner);
if report.failures.len() < MAX_RETAINED_SHUTDOWN_FAILURES {
report.failures.push(failure.clone());
} else {
report.omitted_failures = report.omitted_failures.saturating_add(/*rhs*/ 1);
}
report.tree_id
};
let (reason, phase, error_kind) = match &failure.reason {
AgentTreeShutdownFailureReason::OperationFailed { phase, error_kind } => {
("operation_failed", Some(*phase), Some(*error_kind))
}
AgentTreeShutdownFailureReason::GuardAbandoned => ("guard_abandoned", None, None),
};
let thread_id = failure.thread_id.map(tracing::field::display);
tracing::warn!(
%tree_id,
operation = failure.operation,
phase,
thread_id,
reason,
error_kind,
"agent tree shutdown failure recorded"
);
}
}
#[derive(Clone)]
pub(crate) struct AgentTreeMembership {
state: Arc<AgentTreeShutdownState>,
_member: TaskTrackerToken,
}
impl AgentTreeMembership {
pub(crate) fn into_teardown_guard(
self,
operation: &'static str,
thread_id: Option<ThreadId>,
) -> AgentTreeTeardownGuard {
AgentTreeTeardownGuard {
membership: self,
operation,
thread_id,
completed: false,
}
}
}
/// Marks tree shutdown as failed if teardown work exits without completing.
pub(crate) struct AgentTreeTeardownGuard {
membership: AgentTreeMembership,
operation: &'static str,
thread_id: Option<ThreadId>,
completed: bool,
}
impl AgentTreeTeardownGuard {
pub(crate) fn clone_for_teardown(
&self,
operation: &'static str,
thread_id: Option<ThreadId>,
) -> Self {
self.membership
.clone()
.into_teardown_guard(operation, thread_id)
}
pub(crate) fn set_thread_id(&mut self, thread_id: ThreadId) {
self.thread_id = Some(thread_id);
}
pub(crate) fn record_shutdown_failure(&self, phase: &'static str, error_kind: &'static str) {
self.membership
.state
.record_failure(AgentTreeShutdownFailure::operation_failed(
self.operation,
phase,
self.thread_id,
error_kind,
));
}
pub(crate) fn complete(mut self) {
self.completed = true;
}
}
impl Drop for AgentTreeTeardownGuard {
fn drop(&mut self) {
if !self.completed {
// Record before membership is dropped, so a waiter cannot snapshot first.
self.membership
.state
.record_failure(AgentTreeShutdownFailure {
operation: self.operation,
thread_id: self.thread_id,
reason: AgentTreeShutdownFailureReason::GuardAbandoned,
});
}
}
}
/// Local tree state, kept separate from the shared agent operation interface.
#[derive(Clone)]
pub(crate) struct LocalAgentRuntime {
/// Weak handle back to the global thread registry/state.
/// This is `Weak` to avoid reference cycles and shadow persistence of the form
/// `ThreadManagerState -> CodexThread -> Session -> SessionServices -> ThreadManagerState`.
pub(super) manager: Weak<ThreadManagerState>,
/// Captured at construction so delegates retain their manager's allocation policy.
pub(super) thread_id_generator: ThreadIdGenerator,
pub(crate) item_id_generator: ItemIdGenerator,
pub(crate) context_window_id_generator: ContextWindowIdGenerator,
pub(super) agent_execution_limiter: Arc<AgentExecutionLimiter>,
/// Session-scoped state shared by the root thread and every cloned sub-agent control handle.
pub(super) rollout_budget: Arc<RolloutBudget>,
/// The user-selected root routing tier, shared by the entire agent tree.
pub(super) root_service_tier: Arc<ArcSwapOption<String>>,
/// Retains the root's opt-in instruction provider even when the root is unloaded.
pub(super) shared_thread_instructions_provider:
Arc<OnceLock<Arc<dyn ThreadInstructionsProvider>>>,
pub(super) registry: Arc<AgentRegistry>,
pub(super) residency: Arc<V2Residency>,
pub(super) mailboxes: Arc<super::mailbox::Mailboxes>,
/// Shared by every session in this tree, including private delegates.
pub(crate) shutdown: CancellationToken,
shutdown_state: Arc<AgentTreeShutdownState>,
}
impl LocalAgentRuntime {
pub(super) fn new(
manager: Weak<ThreadManagerState>,
thread_id_generator: ThreadIdGenerator,
rollout_budget: Option<RolloutBudgetConfig>,
) -> Self {
let runtime = Self {
manager,
thread_id_generator,
item_id_generator: Session::new_item_id_generator(),
context_window_id_generator: Arc::new(akode_protocol::ContextWindowId::new_uuid_v7),
registry: Arc::default(),
residency: Arc::default(),
mailboxes: Arc::default(),
shutdown: CancellationToken::new(),
shutdown_state: Arc::default(),
agent_execution_limiter: Arc::default(),
rollout_budget: Arc::default(),
root_service_tier: Arc::new(ArcSwapOption::from(None)),
shared_thread_instructions_provider: Arc::default(),
};
if let Some(rollout_budget) = rollout_budget {
runtime.rollout_budget.configure(rollout_budget);
}
runtime
}
pub(crate) fn tree_id(&self) -> Uuid {
self.shutdown_state
.report
.lock()
.unwrap_or_else(PoisonError::into_inner)
.tree_id
}
/// Bind local startup to the same tree state with this session's identity.
pub(crate) fn control(&self, session_id: SessionId) -> LocalAgentControl {
LocalAgentControl {
session_id,
runtime: self.clone(),
}
}
}
/// Local construction binds identity after reading history. Hosts and internal children
/// provide an already-bound controller without selecting a backend again.
#[derive(Clone)]
pub(crate) enum AgentControlInit {
Local(LocalAgentControl),
Provided {
control: Arc<dyn AgentControl>,
runtime: LocalAgentRuntime,
},
}
impl From<LocalAgentControl> for AgentControlInit {
fn from(control: LocalAgentControl) -> Self {
Self::Local(control)
}
}
impl AgentControlInit {
pub(crate) fn runtime(&self) -> &LocalAgentRuntime {
match self {
Self::Local(control) => &control.runtime,
Self::Provided { runtime, .. } => runtime,
}
}
pub(crate) fn control(&self) -> &dyn AgentControl {
match self {
Self::Local(control) => control,
Self::Provided { control, .. } => control.as_ref(),
}
}
}
impl LocalAgentRuntime {
pub(crate) fn admit_start(&self) -> CodexResult<AgentTreeMembership> {
if self.shutdown_state.members.is_closed() {
return Err(
CodexErr::InvalidRequest("agent runtime is shutting down".to_owned())
.with_agent_context(AgentErrorContext::RuntimeShutdown),
);
}
let membership = AgentTreeMembership {
state: Arc::clone(&self.shutdown_state),
_member: self.shutdown_state.members.token(),
};
// Closing a TaskTracker does not reject new tokens. Recheck so a start racing with
// shutdown is either admitted before the fence or rejected after it.
if self.shutdown_state.members.is_closed() {
return Err(
CodexErr::InvalidRequest("agent runtime is shutting down".to_owned())
.with_agent_context(AgentErrorContext::RuntimeShutdown),
);
}
Ok(membership)
}
pub(crate) fn request_shutdown(&self) -> Arc<AgentTreeShutdownState> {
self.shutdown_state.members.close();
self.shutdown.cancel();
self.mailboxes.close();
Arc::clone(&self.shutdown_state)
}
/// The caller must hold tree membership until this record has been written. This keeps
/// the completed shutdown report stable for every waiter.
pub(crate) fn record_shutdown_failure(&self, failure: AgentTreeShutdownFailure) {
self.shutdown_state.record_failure(failure);
}
pub(crate) fn generate_thread_id(&self) -> ThreadId {
(self.thread_id_generator)()
}
/// Shares the tree's trace with a new or reloaded child runtime.
pub(crate) async fn parent_rollout_thread_trace(
&self,
session_source: &SessionSource,
) -> ThreadTraceContext {
let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id, ..
}) = session_source
else {
return ThreadTraceContext::disabled();
};
let Some(manager) = self.manager.upgrade() else {
return ThreadTraceContext::disabled();
};
// Reattach reloaded children through the v2 root: their immediate parent
// may also be evicted. V1 has no registered root, so it uses the parent.
let trace_owner = self
.registry
.agent_id_for_path(&AgentPath::root())
.unwrap_or(*parent_thread_id);
manager
.get_thread(trace_owner)
.await
.ok()
.filter(|thread| thread.is_running())
.map(|thread| thread.session.services.rollout_thread_trace.clone())
.unwrap_or_else(ThreadTraceContext::disabled)
}
pub(crate) fn root_thread_instructions_provider(
&self,
root_thread_id: ThreadId,
provider: Option<Arc<dyn ThreadInstructionsProvider>>,
) -> Option<Arc<dyn ThreadInstructionsProvider>> {
let provider = match self.manager.upgrade() {
Some(manager) => manager.shared_thread_instructions_provider(root_thread_id, provider),
None => provider,
};
if let Some(provider) = provider
.as_ref()
.filter(|provider| provider.share_with_subagents())
{
let _ = self
.shared_thread_instructions_provider
.set(Arc::clone(provider));
}
provider
}
}
#[cfg(test)]
#[path = "runtime_tests.rs"]
mod tests;

View File

@@ -0,0 +1,139 @@
//! Local registry lookups for startup, legacy context and loaded descendant checks.
//! These use the same local registry and thread manager as lifecycle operations.
use super::LocalAgentRuntime;
use crate::agent::types::AgentMetadata;
use crate::session_prefix::format_subagent_context_line;
use crate::thread_manager::ThreadManagerState;
use akode_protocol::ThreadId;
use akode_protocol::error::AgentErrorContext;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use std::collections::HashMap;
use std::sync::Arc;
impl LocalAgentRuntime {
pub(crate) fn register_session_root(
&self,
current_thread_id: ThreadId,
current_parent_thread_id: Option<ThreadId>,
) {
if current_parent_thread_id.is_none() {
self.registry.register_root_thread(current_thread_id);
}
}
pub(crate) fn ensure_agent_known(&self, agent_id: ThreadId) -> CodexResult<AgentMetadata> {
self.registry
.agent_metadata_for_thread(agent_id)
.ok_or_else(|| CodexErr::ThreadNotFound(agent_id))
}
pub(crate) async fn list_live_agent_subtree_thread_ids(
&self,
agent_id: ThreadId,
) -> CodexResult<Vec<ThreadId>> {
let mut thread_ids = vec![agent_id];
thread_ids.extend(self.live_thread_spawn_descendants(agent_id).await?);
Ok(thread_ids)
}
pub(crate) async fn format_legacy_environment_context_subagents(
&self,
parent_thread_id: ThreadId,
) -> String {
let Ok(agents) = self.open_thread_spawn_children(parent_thread_id).await else {
return String::new();
};
agents
.into_iter()
.map(|(thread_id, metadata)| {
let reference = metadata
.agent_path
.as_ref()
.map(|path| path.name().to_string())
.unwrap_or_else(|| thread_id.to_string());
format_subagent_context_line(&reference, metadata.agent_nickname.as_deref())
})
.collect::<Vec<_>>()
.join("\n")
}
pub(super) async fn open_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
) -> CodexResult<Vec<(ThreadId, AgentMetadata)>> {
let mut children_by_parent = self.live_thread_spawn_children().await?;
Ok(children_by_parent
.remove(&parent_thread_id)
.unwrap_or_default())
}
pub(super) async fn live_thread_spawn_children(
&self,
) -> CodexResult<HashMap<ThreadId, Vec<(ThreadId, AgentMetadata)>>> {
let state = self.upgrade()?;
let mut children_by_parent = HashMap::<ThreadId, Vec<(ThreadId, AgentMetadata)>>::new();
for (parent_thread_id, child_thread_id) in state.list_live_thread_spawn_edges().await {
children_by_parent
.entry(parent_thread_id)
.or_default()
.push((
child_thread_id,
self.registry
.agent_metadata_for_thread(child_thread_id)
.unwrap_or(AgentMetadata {
agent_id: Some(child_thread_id),
..Default::default()
}),
));
}
for children in children_by_parent.values_mut() {
children.sort_by(|left, right| {
left.1
.agent_path
.as_deref()
.unwrap_or_default()
.cmp(right.1.agent_path.as_deref().unwrap_or_default())
.then_with(|| left.0.to_string().cmp(&right.0.to_string()))
});
}
Ok(children_by_parent)
}
pub(super) async fn live_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
) -> CodexResult<Vec<ThreadId>> {
let mut children_by_parent = self.live_thread_spawn_children().await?;
let mut descendants = Vec::new();
let mut stack = children_by_parent
.remove(&root_thread_id)
.unwrap_or_default()
.into_iter()
.map(|(child_thread_id, _)| child_thread_id)
.rev()
.collect::<Vec<_>>();
while let Some(thread_id) = stack.pop() {
descendants.push(thread_id);
if let Some(children) = children_by_parent.remove(&thread_id) {
for (child_thread_id, _) in children.into_iter().rev() {
stack.push(child_thread_id);
}
}
}
Ok(descendants)
}
pub(in crate::agent) fn upgrade(&self) -> CodexResult<Arc<ThreadManagerState>> {
self.manager.upgrade().ok_or_else(|| {
CodexErr::UnsupportedOperation("thread manager dropped".to_string())
.with_agent_context(AgentErrorContext::ManagerUnavailable)
})
}
}

View File

@@ -0,0 +1,260 @@
use super::*;
use crate::thread_manager::default_thread_id_generator;
use akode_protocol::error::CodexErrorDetails;
use akode_thread_store::ThreadStoreError;
use futures::future;
use pretty_assertions::assert_eq;
use tokio::sync::Barrier;
use tokio::sync::oneshot;
fn runtime() -> LocalAgentRuntime {
LocalAgentRuntime::new(
Weak::default(),
default_thread_id_generator(),
/*rollout_budget*/ None,
)
}
#[tokio::test]
async fn aborted_teardown_reports_operation_and_thread() {
let runtime = runtime();
let tree_id = runtime.tree_id();
let thread_id = ThreadId::new();
let teardown = runtime
.admit_start()
.expect("teardown should be admitted")
.into_teardown_guard("session_startup", Some(thread_id));
let (ready_tx, ready_rx) = oneshot::channel();
let task = tokio::spawn(async move {
let _teardown = teardown;
let _ = ready_tx.send(());
future::pending::<()>().await;
});
ready_rx.await.expect("teardown task should start");
let shutdown = runtime.request_shutdown();
task.abort();
task.await.expect_err("teardown task should be aborted");
let report = shutdown
.wait_detailed()
.await
.expect_err("aborted teardown must fail tree shutdown");
assert_eq!(
report,
AgentTreeShutdownReport {
tree_id,
failures: vec![AgentTreeShutdownFailure {
operation: "session_startup",
thread_id: Some(thread_id),
reason: AgentTreeShutdownFailureReason::GuardAbandoned,
}],
omitted_failures: 0,
}
);
assert_eq!(
report.to_string(),
format!(
"agent tree shutdown did not complete cleanly: tree_id={}, failures=[{{operation=session_startup, thread_id={thread_id}, reason=guard_abandoned}}]; omitted_failures=0",
report.tree_id,
)
);
let error = shutdown
.wait()
.await
.expect_err("legacy wait must fail after an abandoned teardown");
assert!(matches!(
error.details(),
CodexErrorDetails::Fatal(message) if message == "agent tree shutdown did not complete cleanly"
));
}
#[tokio::test]
async fn completed_teardown_does_not_fail_tree_shutdown() {
let runtime = runtime();
let teardown = runtime
.admit_start()
.expect("teardown should be admitted")
.into_teardown_guard("session_loop", /*thread_id*/ None);
let shutdown = runtime.request_shutdown();
teardown.complete();
assert_eq!(shutdown.wait_detailed().await, Ok(()));
assert!(shutdown.wait().await.is_ok());
}
#[tokio::test]
async fn report_display_includes_safe_cause_without_raw_error_payload() {
let runtime = runtime();
let thread_id = ThreadId::new();
let teardown = runtime
.admit_start()
.expect("teardown should be admitted")
.into_teardown_guard("session_startup", Some(thread_id));
let raw_payload = "sensitive thread-store error payload";
for error in [
ThreadStoreError::Internal {
message: raw_payload.to_owned(),
},
ThreadStoreError::Retryable {
message: raw_payload.to_owned(),
},
ThreadStoreError::OutcomeUnknown {
message: raw_payload.to_owned(),
},
] {
teardown.record_shutdown_failure(
"discard_persistence",
crate::thread_manager::thread_store_error_kind(&error),
);
}
let shutdown = runtime.request_shutdown();
teardown.complete();
let report = shutdown
.wait_detailed()
.await
.expect_err("recorded failure must fail shutdown");
let displayed = report.to_string();
assert_eq!(
displayed,
format!(
"agent tree shutdown did not complete cleanly: tree_id={}, failures=[{{operation=session_startup, phase=discard_persistence, thread_id={thread_id}, reason=operation_failed, error_kind=thread_store_internal}}, {{operation=session_startup, phase=discard_persistence, thread_id={thread_id}, reason=operation_failed, error_kind=thread_store_retryable}}, {{operation=session_startup, phase=discard_persistence, thread_id={thread_id}, reason=operation_failed, error_kind=thread_store_outcome_unknown}}]; omitted_failures=0",
report.tree_id,
)
);
assert!(!displayed.contains(raw_payload));
}
#[tokio::test]
async fn cloned_guard_reports_its_own_context_before_releasing_membership() {
let runtime = runtime();
let original = runtime
.admit_start()
.expect("teardown should be admitted")
.into_teardown_guard("startup", /*thread_id*/ None);
let mut session = original.clone_for_teardown("session_loop", /*thread_id*/ None);
let thread_id = ThreadId::new();
session.set_thread_id(thread_id);
let shutdown = runtime.request_shutdown();
original.complete();
let wait = shutdown.wait_detailed();
tokio::pin!(wait);
assert!(futures::poll!(&mut wait).is_pending());
drop(session);
let report = wait
.await
.expect_err("abandoned session must fail shutdown");
assert_eq!(
report,
AgentTreeShutdownReport {
tree_id: report.tree_id,
failures: vec![AgentTreeShutdownFailure {
operation: "session_loop",
thread_id: Some(thread_id),
reason: AgentTreeShutdownFailureReason::GuardAbandoned,
}],
omitted_failures: 0,
}
);
}
#[tokio::test]
async fn concurrent_failures_are_retained_for_every_waiter() {
let runtime = runtime();
let barrier = Arc::new(Barrier::new(/*n*/ 3));
let thread_ids = [
ThreadId::from_u128(/*value*/ 1),
ThreadId::from_u128(/*value*/ 2),
];
let mut tasks = Vec::new();
for thread_id in thread_ids {
let teardown = runtime
.admit_start()
.expect("teardown should be admitted")
.into_teardown_guard("child_spawn", Some(thread_id));
let barrier = Arc::clone(&barrier);
tasks.push(tokio::spawn(async move {
barrier.wait().await;
teardown.record_shutdown_failure("discard_persistence", "thread_store_internal");
teardown.complete();
}));
}
let shutdown = runtime.request_shutdown();
let first_waiter = {
let shutdown = Arc::clone(&shutdown);
tokio::spawn(async move { shutdown.wait_detailed().await })
};
let second_waiter = {
let shutdown = Arc::clone(&shutdown);
tokio::spawn(async move { shutdown.wait_detailed().await })
};
barrier.wait().await;
for task in tasks {
task.await.expect("cleanup task should finish");
}
let mut first = first_waiter
.await
.expect("first waiter should finish")
.expect_err("recorded failures must fail shutdown");
let second = second_waiter
.await
.expect("second waiter should finish")
.expect_err("recorded failures must fail shutdown");
assert_eq!(first, second);
assert_eq!(shutdown.wait_detailed().await, Err(first.clone()));
first
.failures
.sort_by_key(|failure| failure.thread_id.map(|thread_id| thread_id.to_string()));
assert_eq!(
first,
AgentTreeShutdownReport {
tree_id: first.tree_id,
failures: thread_ids
.into_iter()
.map(|thread_id| AgentTreeShutdownFailure::operation_failed(
"child_spawn",
"discard_persistence",
Some(thread_id),
"thread_store_internal",
))
.collect(),
omitted_failures: 0,
}
);
}
#[tokio::test]
async fn failure_report_counts_omitted_failures() {
let runtime = runtime();
let teardown = runtime
.admit_start()
.expect("teardown should be admitted")
.into_teardown_guard("startup", /*thread_id*/ None);
let failure = AgentTreeShutdownFailure::operation_failed(
"startup",
"stop_session",
/*thread_id*/ None,
"internal",
);
for _ in 0..MAX_RETAINED_SHUTDOWN_FAILURES + 3 {
runtime.record_shutdown_failure(failure.clone());
}
let shutdown = runtime.request_shutdown();
teardown.complete();
let report = shutdown
.wait_detailed()
.await
.expect_err("recorded failures must fail shutdown");
assert_eq!(
report,
AgentTreeShutdownReport {
tree_id: report.tree_id,
failures: vec![failure; MAX_RETAINED_SHUTDOWN_FAILURES],
omitted_failures: 3,
}
);
}

View File

@@ -0,0 +1,125 @@
//! Captures genuine sender instructions and assistant context for host-delivered task messages.
//! Only turn-input admission calls this, before queueing; ordinary tool results and
//! quoted delegation text cannot establish sender provenance. Unloaded senders are read
//! through the host's authenticated thread store, without resuming their runtime.
use crate::context::GuardianSenderMessages;
use crate::context_manager::ContextManager;
use akode_history::RolloutItem;
use akode_protocol::ThreadId;
use akode_protocol::models::ResponseItem;
use akode_thread_store::LoadThreadHistoryParams;
use akode_utils_output_truncation::TruncationPolicy;
use std::time::Duration;
use super::LocalAgentRuntime;
impl LocalAgentRuntime {
pub(crate) async fn capture_sender_user_messages(
&self,
item: &ResponseItem,
receiver_thread_id: ThreadId,
) -> Option<GuardianSenderMessages> {
let ResponseItem::FunctionCallOutput {
id: Some(id),
call_id: None,
name: Some(name),
namespace: Some(namespace),
output,
..
} = item
else {
return None;
};
if !matches!(
(namespace.as_str(), name.as_str()),
("codex_app" | "akode_tui", "send_message_to_thread")
| ("codex_app", "create_thread")
| ("cloud_threads", "send_message")
) {
return None;
}
// Recognized deliveries always get their own snapshot, even without usable provenance.
let source_thread_id = output.body.to_text().and_then(|text| {
let (source, input) = text
.strip_prefix("<codex_delegation>")?
.strip_suffix("</codex_delegation>")?
.trim()
.strip_prefix("<source_thread_id>")?
.split_once("</source_thread_id>")?;
let input = input.trim();
// Cloud deliveries include Dot attribution, but authority comes from the source thread.
let input = if let Some(rest) = input.strip_prefix("<source_orbit_id>") {
let (orbit_id, input) = rest.split_once("</source_orbit_id>")?;
if orbit_id.contains('<') {
return None;
}
input.trim()
} else {
input
};
input.strip_prefix("<input>")?.strip_suffix("</input>")?;
ThreadId::from_string(source)
.ok()
.filter(|source| *source != receiver_thread_id)
});
let mut fragment = GuardianSenderMessages {
source: source_thread_id,
delivery: id.to_string(),
from_storage: false,
messages: Vec::new(),
};
if let Some(source_thread_id) = source_thread_id
&& let Ok(manager) = self.upgrade()
{
let context = match manager.get_thread(source_thread_id).await {
Ok(sender) => sender
.conversation_history_snapshot()
.await
.retained_context()
.cloned(),
Err(_) => {
// The store owns authorization, including cross-worker tenant boundaries.
// Bound the read so unavailable storage cannot stall turn admission.
let stored = tokio::time::timeout(
Duration::from_secs(/*secs*/ 5),
manager.load_latest_model_context(LoadThreadHistoryParams {
thread_id: source_thread_id,
include_archived: true,
}),
)
.await;
match stored {
Ok(Ok(stored)) if stored.thread_id == source_thread_id => {
let meta = stored.items.iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta) => Some(&meta.meta),
_ => None,
});
meta.filter(|meta| {
meta.id == source_thread_id && !meta.source.is_internal()
})
.map(|meta| {
fragment.from_storage = true;
ContextManager::reconstruct_rollout(
&stored.items,
meta.history_mode,
ContextManager::new(std::sync::Arc::clone(
&self.item_id_generator,
)),
// Tool bodies are not sender authorization evidence.
TruncationPolicy::Bytes(0),
)
.retained_context
})
}
Ok(Ok(_)) | Ok(Err(_)) | Err(_) => None,
}
}
};
if let Some(context) = context {
fragment.messages = akode_guardian_reviewer::guardian_sender_exchanges(&context);
}
}
Some(fragment)
}
}

View File

@@ -0,0 +1,21 @@
//! Shares the root user's selected routing tier across the entire agent tree.
use super::LocalAgentControl;
use std::sync::Arc;
impl LocalAgentControl {
/// Returns the latest user-selected tier for this root and all its descendants.
pub(crate) fn root_service_tier(&self) -> Option<String> {
self.runtime
.root_service_tier
.load_full()
.map(|service_tier| (*service_tier).clone())
}
/// Publishes a root-owned tier without mutating individual child sessions.
pub(crate) fn set_root_service_tier(&self, service_tier: Option<String>) {
self.runtime
.root_service_tier
.store(service_tier.map(Arc::new));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,125 @@
//! Owns a provisional child until the spawn result can be returned without yielding.
//! Graph publication stays owned through cancellation and settles before cleanup closes its edge.
use super::AgentTreeMembership;
use crate::thread_manager::ThreadManagerState;
use crate::thread_manager::thread_store_error_kind;
use akode_agent_graph_store::AgentGraphStoreError;
use akode_agent_graph_store::ThreadSpawnEdgeStatus;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrKind;
use akode_protocol::error::Result as CodexResult;
use akode_thread_store::ThreadStoreError;
use std::sync::Arc;
use tokio::task::JoinHandle;
use tracing::warn;
pub(in crate::agent) enum SpawnOwner {
Local,
Host,
}
pub(in crate::agent) struct PendingSpawn {
state: Arc<ThreadManagerState>,
pending: Option<(ThreadId, AgentTreeMembership)>,
edge_write: Option<JoinHandle<CodexResult<bool>>>,
close_spawn_edge: bool,
owner: SpawnOwner,
}
impl PendingSpawn {
pub(in crate::agent) fn new(
state: Arc<ThreadManagerState>,
child: ThreadId,
membership: AgentTreeMembership,
owner: SpawnOwner,
) -> Self {
Self {
state,
pending: Some((child, membership)),
edge_write: None,
close_spawn_edge: false,
owner,
}
}
pub(super) fn set_edge_write(&mut self, edge_write: JoinHandle<CodexResult<bool>>) {
self.edge_write = Some(edge_write);
}
pub(super) async fn wait_for_edge(&mut self) -> CodexResult<()> {
let Some(edge_write) = self.edge_write.as_mut() else {
return Ok(());
};
// Keep ownership while waiting, then clear the completed handle before returning errors.
let result = edge_write.await;
self.edge_write = None;
// An error may follow a committed write; only an explicit skip rules it out.
self.close_spawn_edge = !matches!(&result, Ok(Ok(false)));
result??;
Ok(())
}
pub(in crate::agent) fn disarm(mut self) -> AgentTreeMembership {
let Some((_child, membership)) = self.pending.take() else {
unreachable!("pending spawn must own agent-tree membership");
};
membership
}
}
impl Drop for PendingSpawn {
fn drop(&mut self) {
let Some((child, membership)) = self.pending.take() else {
return;
};
let state = Arc::clone(&self.state);
let teardown = membership.into_teardown_guard("child_spawn_cleanup", Some(child));
let edge_write = self.edge_write.take();
let close_spawn_edge = self.close_spawn_edge;
let local_owner = matches!(self.owner, SpawnOwner::Local);
drop(tokio::spawn(async move {
if let Some(thread) = state.remove_thread(&child).await {
if let Err(error) = thread.shutdown_and_wait().await {
teardown
.record_shutdown_failure("stop_child", CodexErrKind::from(&error).into());
warn!("failed to stop cancelled child spawn: {error}");
}
if let Some(live_thread) = thread.session.live_thread() {
match live_thread.discard().await {
Ok(()) | Err(ThreadStoreError::ThreadNotFound { .. }) => {}
Err(error) => {
teardown.record_shutdown_failure(
"discard_child_persistence",
thread_store_error_kind(&error),
);
warn!("failed to discard cancelled child spawn: {error}");
}
}
}
}
// A pending Open write must finish before cleanup writes Closed.
let close_spawn_edge = match edge_write {
Some(edge_write) => !matches!(edge_write.await, Ok(Ok(false))),
None => close_spawn_edge,
};
if local_owner
&& close_spawn_edge
&& let Some(store) = state.agent_graph_store()
&& let Err(error) = store
.set_thread_spawn_edge_status(child, ThreadSpawnEdgeStatus::Closed)
.await
{
let error_kind = match &error {
AgentGraphStoreError::InvalidRequest { .. } => {
"agent_graph_store_invalid_request"
}
AgentGraphStoreError::Internal { .. } => "agent_graph_store_internal",
};
teardown.record_shutdown_failure("close_spawn_edge", error_kind);
warn!("failed to close cancelled child spawn edge: {error}");
}
teardown.complete();
}));
}
}

View File

@@ -0,0 +1,356 @@
#![cfg(test)]
//! Exercises spawn cleanup against real SQLite graph writes with controlled acknowledgements.
//! Publication must survive caller cancellation and finish before cleanup closes the edge.
use super::*;
use akode_agent_graph_store::AgentGraphStore;
use akode_agent_graph_store::AgentGraphStoreError;
use akode_agent_graph_store::AgentGraphStoreFuture;
use akode_agent_graph_store::LocalAgentGraphStore;
use akode_agent_graph_store::ThreadSpawnEdgeStatus;
use pretty_assertions::assert_eq;
#[derive(Clone, Copy)]
enum SpawnEdgeFailure {
CancelledBeforeCommit,
CancelledBeforeAck,
ErrorAfterCommit,
}
enum SkippedPublication {
Ephemeral,
NoParent,
}
struct FaultingGraphStore {
inner: LocalAgentGraphStore,
failure: SpawnEdgeFailure,
started: CancellationToken,
held: CancellationToken,
release: CancellationToken,
cancelled: CancellationToken,
close_attempted: CancellationToken,
}
impl FaultingGraphStore {
async fn hold_write(&self) {
self.held.cancel();
self.release.cancelled().await;
}
}
impl AgentGraphStore for FaultingGraphStore {
fn upsert_thread_spawn_edge(
&self,
parent: ThreadId,
child: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
Box::pin(async move {
let cancellation_guard = self.cancelled.clone().drop_guard();
self.started.cancel();
if matches!(self.failure, SpawnEdgeFailure::CancelledBeforeCommit) {
self.hold_write().await;
}
self.inner
.upsert_thread_spawn_edge(parent, child, status)
.await?;
if matches!(self.failure, SpawnEdgeFailure::CancelledBeforeAck) {
self.hold_write().await;
}
cancellation_guard.disarm();
match self.failure {
SpawnEdgeFailure::CancelledBeforeCommit | SpawnEdgeFailure::CancelledBeforeAck => {
Ok(())
}
SpawnEdgeFailure::ErrorAfterCommit => Err(AgentGraphStoreError::Internal {
message: "injected response loss after successful commit".to_string(),
}),
}
})
}
fn set_thread_spawn_edge_status(
&self,
child: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
self.close_attempted.cancel();
self.inner.set_thread_spawn_edge_status(child, status)
}
fn list_thread_spawn_children(
&self,
parent: ThreadId,
status: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
self.inner.list_thread_spawn_children(parent, status)
}
fn list_thread_spawn_descendants(
&self,
root: ThreadId,
status: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
self.inner.list_thread_spawn_descendants(root, status)
}
}
async fn publication_harness(
failure: SpawnEdgeFailure,
generate_thread_id: impl Fn() -> ThreadId + Send + Sync + 'static,
) -> (AgentControlHarness, Arc<FaultingGraphStore>) {
let mut harness = AgentControlHarness::new().await;
let graph = Arc::new(FaultingGraphStore {
inner: LocalAgentGraphStore::new(harness.state_db.clone().expect("state db")),
failure,
started: CancellationToken::new(),
held: CancellationToken::new(),
release: CancellationToken::new(),
cancelled: CancellationToken::new(),
close_attempted: CancellationToken::new(),
});
harness.manager = ThreadManager::new(
&harness.config,
crate::build_startup_models(
&harness.config,
harness.manager.auth_manager(),
"spawn-publication-cleanup-test".to_string(),
crate::test_support::fixed_model_catalog(harness.manager.get_models_manager()),
),
SessionSource::Exec,
harness.manager.environment_manager(),
empty_extension_registry(),
Arc::new(crate::test_support::EmptyUserInstructionsProvider),
harness.manager.image_store(),
crate::ThreadStoreBuilder::from_config(&harness.config, harness.state_db.clone()).build(),
Some(graph.clone()),
/*external_time_provider*/ None,
)
.with_thread_id_generator(generate_thread_id);
harness.control = harness.manager.agent_control();
(harness, graph)
}
async fn spawn_publication_child(
harness: &AgentControlHarness,
parent: ThreadId,
) -> CodexResult<ThreadId> {
harness
.control
.spawn_agent(
harness.config.clone(),
text_input("child task"),
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: parent,
depth: 1,
agent_path: None,
agent_nickname: None,
agent_role: None,
})),
)
.await
}
async fn assert_publication_closed(
harness: &AgentControlHarness,
graph: &FaultingGraphStore,
parent: ThreadId,
) {
harness
.control
.runtime
.request_shutdown()
.wait()
.await
.expect("cleanup completes");
let all = graph
.list_thread_spawn_children(parent, /*status_filter*/ None)
.await
.expect("graph readable");
assert_eq!(
all.len(),
1,
"the store durably accepted the prepublication"
);
assert_thread_not_loaded(&harness.manager, all[0]).await;
assert_eq!(
graph
.list_thread_spawn_children(parent, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open graph"),
Vec::<ThreadId>::new(),
"rejected or cancelled spawn must close its committed edge",
);
assert_eq!(
graph
.list_thread_spawn_children(parent, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed graph"),
all,
);
}
#[test_case::test_case(SpawnEdgeFailure::CancelledBeforeCommit, 0; "before_commit")]
#[test_case::test_case(SpawnEdgeFailure::CancelledBeforeAck, 1; "before_acknowledgement")]
#[tokio::test]
async fn cancelled_spawn_edge_publication_cleanup(
failure: SpawnEdgeFailure,
committed_children: usize,
) {
let (harness, graph) = publication_harness(failure, ThreadId::new).await;
let parent = ThreadId::new();
let mut spawn = Box::pin(spawn_publication_child(&harness, parent));
tokio::select! {
biased;
() = graph.held.cancelled() => {},
result = &mut spawn => panic!("spawn returned while publication was held: {result:?}"),
}
assert_eq!(
graph
.list_thread_spawn_children(parent, /*status_filter*/ None)
.await
.expect("graph before cancellation")
.len(),
committed_children
);
drop(spawn);
// Dropping a directly-awaited store future cancels this token synchronously.
// Keeping only the child ID in the guard cannot satisfy this ownership check.
assert!(
!graph.cancelled.is_cancelled(),
"caller cancellation must retain the submitted write"
);
// Paused time advances only after runnable cleanup has been polled. No real
// storage operation is pending while the graph-store future is held.
tokio::time::pause();
let early_close = timeout(Duration::from_secs(1), graph.close_attempted.cancelled()).await;
tokio::time::resume();
assert!(early_close.is_err(), "Closed must wait for Open");
graph.release.cancel();
assert_publication_closed(&harness, &graph, parent).await;
}
#[tokio::test]
async fn failed_spawn_edge_publication_cleanup() {
let (harness, graph) =
publication_harness(SpawnEdgeFailure::ErrorAfterCommit, ThreadId::new).await;
let parent = ThreadId::new();
let error = spawn_publication_child(&harness, parent)
.await
.expect_err("lost commit acknowledgement rejects spawn");
assert_eq!(
error.to_string(),
"Fatal error: failed to persist spawned agent relationship"
);
assert_publication_closed(&harness, &graph, parent).await;
}
#[test_case::test_case(SkippedPublication::Ephemeral; "ephemeral")]
#[test_case::test_case(SkippedPublication::NoParent; "no_parent")]
#[tokio::test]
async fn failed_spawn_without_publication_does_not_close_graph(skipped: SkippedPublication) {
let (mut harness, graph) =
publication_harness(SpawnEdgeFailure::ErrorAfterCommit, ThreadId::new).await;
let parent = ThreadId::new();
let source = match skipped {
SkippedPublication::Ephemeral => {
harness.config.ephemeral = true;
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: parent,
depth: 1,
agent_path: None,
agent_nickname: None,
agent_role: None,
}))
}
SkippedPublication::NoParent => None,
};
let state = harness.control.runtime.upgrade().expect("live manager");
let spawn =
harness
.control
.spawn_agent(harness.config.clone(), text_input("child task"), source);
tokio::pin!(spawn);
let shutdown = {
let _threads = state.threads.write().await;
assert!(
spawn
.as_mut()
.poll(&mut Context::from_waker(Waker::noop()))
.is_pending()
);
harness.control.runtime.request_shutdown()
};
assert_eq!(
CodexErrKind::from(&spawn.await.expect_err("child startup rejects shutdown")),
CodexErrKind::InvalidRequest,
);
shutdown
.wait()
.await
.expect("cleanup completes without graph errors");
assert!(!graph.started.is_cancelled(), "no Open write was issued");
assert!(
!graph.close_attempted.is_cancelled(),
"skipped publication needs no Closed write"
);
assert_eq!(
graph
.list_thread_spawn_children(parent, /*status_filter*/ None)
.await
.expect("graph readable"),
Vec::<ThreadId>::new()
);
}
#[tokio::test]
async fn repeated_child_id_preserves_existing_thread_and_graph() {
let repeated_id = ThreadId::new();
let (harness, graph) =
publication_harness(SpawnEdgeFailure::ErrorAfterCommit, move || repeated_id).await;
let (parent, existing_thread) = harness.start_thread().await;
assert_eq!(parent, repeated_id);
let children_before = graph
.list_thread_spawn_children(parent, /*status_filter*/ None)
.await
.expect("initial graph");
let error = spawn_publication_child(&harness, parent)
.await
.expect_err("loaded IDs are rejected");
assert_eq!(
(error.agent_context(), CodexErrKind::from(&error)),
(
Some(AgentErrorContext::ChildStartup),
CodexErrKind::InvalidRequest
),
);
assert!(Arc::ptr_eq(
&existing_thread,
&harness
.manager
.get_thread(parent)
.await
.expect("existing thread survives")
));
assert!(
!graph.started.is_cancelled(),
"duplicate ID must be rejected before publication"
);
assert!(
!graph.close_attempted.is_cancelled(),
"existing thread is not provisional cleanup"
);
assert_eq!(
graph
.list_thread_spawn_children(parent, /*status_filter*/ None)
.await
.expect("graph after rejection"),
children_before
);
existing_thread
.shutdown_and_wait()
.await
.expect("stop existing thread");
}

View File

@@ -0,0 +1,64 @@
//! Successful multi-agent spawn latency metrics.
//!
//! Runtime values are collapsed to bounded labels before emission. Failed spawns do not emit
//! partial phase timings.
use crate::agent::types::SpawnAgentForkMode;
use akode_otel::SessionTelemetry;
use akode_protocol::protocol::MultiAgentVersion;
use akode_protocol::protocol::ThreadHistoryMode;
use std::time::Duration;
pub(super) struct SpawnMeasurements {
pub(super) history_mode: ThreadHistoryMode,
pub(super) residency_reservation: Option<Duration>,
pub(super) fork_context: Option<Duration>,
pub(super) child_create: Duration,
pub(super) durability_wait: Duration,
pub(super) input_admission: Duration,
pub(super) total: Duration,
}
pub(super) fn record_spawn_success(
telemetry: &SessionTelemetry,
fork_mode: Option<&SpawnAgentForkMode>,
multi_agent_version: MultiAgentVersion,
measurements: SpawnMeasurements,
) {
let fork_mode = match fork_mode {
None => "none",
Some(SpawnAgentForkMode::FullHistory) => "all",
};
let history_mode = match measurements.history_mode {
ThreadHistoryMode::Legacy => "legacy",
ThreadHistoryMode::Paginated => "paginated",
};
let multi_agent_version = match multi_agent_version {
MultiAgentVersion::Disabled => "disabled",
MultiAgentVersion::V1 => "v1",
MultiAgentVersion::V2 => "v2",
};
let record_phase = |phase, duration| {
telemetry.record_multi_agent_spawn_phase(
phase,
duration,
fork_mode,
history_mode,
multi_agent_version,
);
};
if let Some(duration) = measurements.residency_reservation {
record_phase("residency_reservation", duration);
}
if let Some(duration) = measurements.fork_context {
record_phase("fork_context", duration);
}
record_phase("child_create", measurements.child_create);
record_phase("durability_wait", measurements.durability_wait);
record_phase("input_admission", measurements.input_admission);
record_phase("total", measurements.total);
}
#[cfg(test)]
#[path = "spawn_telemetry_tests.rs"]
mod tests;

View File

@@ -0,0 +1,95 @@
use super::*;
use akode_otel::MULTI_AGENT_SPAWN_PHASE_DURATION_METRIC;
use akode_otel::MetricsClient;
use akode_otel::MetricsConfig;
use akode_protocol::ThreadId;
use akode_protocol::protocol::SessionSource;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
#[test]
fn records_bounded_spawn_phase_metrics() {
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"akode-core",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)
.expect("create in-memory metrics client");
let telemetry = SessionTelemetry::new(
ThreadId::new(),
"test-model",
"test-model",
/*account_id*/ None,
/*account_email*/ None,
/*auth_mode*/ None,
"test-originator".to_string(),
/*log_user_prompts*/ false,
"test-terminal".to_string(),
SessionSource::Cli,
)
.with_product_sku(Some("codex"))
.with_metrics_without_metadata_tags(metrics.clone());
record_spawn_success(
&telemetry,
Some(&SpawnAgentForkMode::FullHistory),
MultiAgentVersion::V2,
SpawnMeasurements {
history_mode: ThreadHistoryMode::Paginated,
residency_reservation: Some(Duration::from_millis(11)),
fork_context: Some(Duration::from_millis(13)),
child_create: Duration::from_millis(17),
durability_wait: Duration::from_millis(19),
input_admission: Duration::from_millis(23),
total: Duration::from_millis(29),
},
);
let snapshot = metrics.snapshot().expect("snapshot spawn metrics");
let metric = snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.find(|metric| metric.name() == MULTI_AGENT_SPAWN_PHASE_DURATION_METRIC)
.expect("spawn phase metric");
let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = metric.data() else {
panic!("expected spawn phase histogram");
};
let phases = histogram
.data_points()
.map(|point| {
let attributes = point
.attributes()
.map(|attribute| {
(
attribute.key.as_str().to_string(),
attribute.value.as_str().to_string(),
)
})
.collect::<BTreeMap<_, _>>();
assert_eq!(attributes.len(), 5);
assert_eq!(attributes["fork_mode"], "all");
assert_eq!(attributes["history_mode"], "paginated");
assert_eq!(attributes["multi_agent_version"], "v2");
assert_eq!(attributes["product_sku"], "codex");
(attributes["phase"].clone(), (point.count(), point.sum()))
})
.collect::<BTreeMap<_, _>>();
assert_eq!(
phases,
BTreeMap::from([
("child_create".to_string(), (1, 17.0)),
("durability_wait".to_string(), (1, 19.0)),
("fork_context".to_string(), (1, 13.0)),
("input_admission".to_string(), (1, 23.0)),
("residency_reservation".to_string(), (1, 11.0)),
("total".to_string(), (1, 29.0)),
])
);
}

View File

@@ -0,0 +1,61 @@
//! Resolves controller targets using the caller's registered identity.
//! Legacy callers can still supply their captured session source for path resolution.
use super::LocalAgentControl;
use super::LocalAgentRuntime;
use crate::agent::api::AgentTarget;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::SessionSource;
impl LocalAgentControl {
pub(crate) fn resolve_target(
&self,
caller: ThreadId,
target: &AgentTarget,
) -> CodexResult<ThreadId> {
match target {
AgentTarget::Id(thread_id) => Ok(*thread_id),
AgentTarget::Reference(reference) => {
let caller = self.runtime.ensure_agent_known(caller)?;
self.runtime.resolve_path_reference(
&caller.agent_path.unwrap_or_else(AgentPath::root),
reference,
)
}
}
}
}
impl LocalAgentRuntime {
pub(crate) async fn resolve_agent_reference(
&self,
_current_thread_id: ThreadId,
current_session_source: &SessionSource,
agent_reference: &str,
) -> CodexResult<ThreadId> {
let current_agent_path = current_session_source
.get_agent_path()
.unwrap_or_else(AgentPath::root);
self.resolve_path_reference(&current_agent_path, agent_reference)
}
pub(super) fn resolve_path_reference(
&self,
current_agent_path: &AgentPath,
agent_reference: &str,
) -> CodexResult<ThreadId> {
let agent_path = current_agent_path
.resolve(agent_reference)
.map_err(CodexErr::UnsupportedOperation)?;
if let Some(thread_id) = self.registry.agent_id_for_path(&agent_path) {
return Ok(thread_id);
}
Err(CodexErr::UnsupportedOperation(format!(
"live agent path `{}` not found",
agent_path.as_str()
)))
}
}

View File

@@ -0,0 +1,319 @@
//! Projects bounded retained root evidence for worker reviewers.
//! Retained root instructions stay authoritative while old checkpoints use legacy review.
//! Selects recent user and assistant evidence together by source order.
//! Explicit assistant commentary is excluded; confirmed messaging survives compaction.
//! Projection omissions keep missing authorization and assistant context explicit.
//! Retained-history reconciliation owns recovery order and missing-instruction provenance.
//! Known positions preserve host order, not delivery order or inferred question-answer pairs.
//! Unmatched legacy instructions supplement retained facts without claiming a known ordering.
//! Optional handoff filtering narrows assistant context using surviving calls as relevance boundaries.
//! Handoff projection preserves saved heartbeat instructions and the active turn's skills.
use std::borrow::Cow;
use super::LocalAgentControl;
use crate::codex_thread::GuardianRootMessage;
use crate::codex_thread::GuardianRootSnapshot;
use crate::compact::is_summary_message;
use crate::context::ContextualUserFragment;
use crate::context::GuardianReviewEvidence;
use crate::context::UserGoalUpdate;
use crate::context::is_contextual_user_fragment;
use crate::context_manager::ContextManager;
use crate::event_mapping::parse_turn_item;
use akode_guardian_context::RootAssistantCandidate;
use akode_guardian_context::RootAssistantContent;
use akode_guardian_context::RootConversationCandidates;
use akode_guardian_context::RootConversationInput;
use akode_guardian_context::RootConversationSource;
use akode_guardian_context::RootDeliveredMessage;
use akode_guardian_context::RootMessageCandidate;
use akode_guardian_context::RootRetainedAssistant;
use akode_history::ReconciledRetainedContext;
use akode_history::RetainedContextEntry;
use akode_history::RetainedContextOrder;
use akode_history::RetainedUserMessage;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use akode_protocol::items::TurnItem;
use akode_protocol::models::ContentItem;
use akode_protocol::models::MessagePhase;
use akode_protocol::models::ResponseItem;
use akode_protocol::protocol::MultiAgentVersion;
struct CapturedRootConversation {
history: ContextManager,
handoff_boundaries: Vec<RetainedContextOrder>,
}
impl RootConversationSource for CapturedRootConversation {
fn prepare(
&self,
budgeting: akode_guardian_context::ContextBudgeting,
) -> akode_guardian_context::PreparedRootContext {
let root_history = &self.history;
// Join calls to host-confirmed outputs in this snapshot. Older outputs without
// captured text cannot establish what was sent, including after a hook rewrite.
let delivered_candidates = root_history
.annotated_items()
.iter()
.rev()
.filter_map(|envelope| {
let ResponseItem::FunctionCallOutput {
call_id: Some(call_id),
..
} = &envelope.item
else {
return None;
};
let text = envelope
.metadata
.as_ref()?
.delivered_assistant_message
.as_deref()?;
Some(RootDeliveredMessage { call_id, text })
})
.collect::<Vec<_>>();
let retained_context = root_history.retained_context();
let reconciled = ReconciledRetainedContext::new(
Some(retained_context),
root_history
.annotated_items()
.iter()
.filter_map(|envelope| {
let item = &envelope.item;
let Some(TurnItem::UserMessage(message)) = parse_turn_item(item) else {
return None;
};
let text = message.message();
if is_summary_message(&text)
|| text.trim_start().starts_with("<user_action>")
|| is_contextual_user_fragment(&ContentItem::InputText {
text: text.clone(),
})
{
return None;
}
let order = envelope
.metadata
.as_ref()
.filter(|metadata| !metadata.inherited_user_message)
.and_then(|metadata| metadata.user_input_order);
Some((
order,
RetainedUserMessage {
phase: None,
origin: akode_history::UserInputOrigin::from_message(item),
turn_id: item.turn_id().unwrap_or_default().to_owned(),
message_id: item.id().map(|id| id.as_str().to_owned()),
text,
complete: false,
},
))
}),
);
let mut missing_root_instructions = reconciled.missing_user_messages;
let user_candidates = reconciled
.ordered_entries()
.filter_map(|(order, entry)| match entry {
RetainedContextEntry::UserMessage(message) => {
let text = if message.text.is_empty() && !message.complete {
// Older records may omit a large instruction. Recover that exact
// source while it remains available in the parent context.
let original = message.message_id.as_deref().and_then(|id| {
root_history
.raw_items()
.chain(root_history.guardian_history_items().into_iter().flatten())
.find(|item| {
item.id().is_some_and(|item_id| item_id.as_str() == id)
})
});
let Some(TurnItem::UserMessage(original)) =
original.and_then(parse_turn_item)
else {
missing_root_instructions = true;
return None;
};
Cow::Owned(original.message())
} else {
Cow::Borrowed(message.text.as_str())
};
let is_goal_update = UserGoalUpdate::matches_text(&text);
// A retained placeholder cannot recover an omitted goal restriction.
missing_root_instructions |= is_goal_update && !message.complete;
if is_contextual_user_fragment(&ContentItem::InputText {
text: text.to_string(),
}) && !is_goal_update
{
return None;
}
(!is_summary_message(&text) && !text.trim_start().starts_with("<user_action>"))
.then(|| RootMessageCandidate {
order: Some(order),
message: GuardianRootMessage::User(text.to_string()),
})
}
RetainedContextEntry::VerifiedAnswer(answer) => Some(RootMessageCandidate {
order: Some(order),
message: GuardianRootMessage::UserInput(
akode_guardian_context::render_original_verified_answer(answer),
),
}),
RetainedContextEntry::AssistantMessage(_) => None,
})
.collect::<Vec<_>>();
let original_missing_root_instructions = missing_root_instructions;
let retained_user_sources = reconciled
.ordered_entries()
.filter_map(|(_, entry)| match entry {
RetainedContextEntry::UserMessage(message) => Some(message.clone()),
RetainedContextEntry::AssistantMessage(_)
| RetainedContextEntry::VerifiedAnswer(_) => None,
})
.collect();
let assistant_candidates = root_history
.annotated_items()
.iter()
.filter(|envelope| {
!envelope
.metadata
.as_ref()
.is_some_and(|metadata| metadata.compaction_output)
})
.filter_map(|envelope| {
let content = match &envelope.item {
ResponseItem::FunctionCall { call_id, .. } => {
RootAssistantContent::DeliveredCall {
call_id: call_id.clone(),
}
}
ResponseItem::Message {
role,
content,
phase,
..
} if role == "assistant" && *phase != Some(MessagePhase::Commentary) => {
RootAssistantContent::Text(content)
}
_ => return None,
};
Some(RootAssistantCandidate {
message_id: envelope.item.id().map(|id| id.as_str().to_owned()),
order: envelope
.metadata
.as_ref()
.filter(|metadata| !metadata.inherited_user_message)
.and_then(|metadata| metadata.user_input_order)
.map(RetainedContextOrder::Local),
content,
})
})
.collect::<Vec<_>>();
let retained_assistant_candidates = reconciled
.ordered_entries()
.filter_map(|(order, entry)| {
let RetainedContextEntry::AssistantMessage(message) = entry else {
return None;
};
let standalone_eligible = !(message.phase == Some(MessagePhase::Commentary)
|| message.message_id.as_deref().is_some_and(|id| {
root_history
.raw_items()
.chain(root_history.guardian_history_items().into_iter().flatten())
.any(|item| {
matches!(item, ResponseItem::Message {
id: Some(source_id), phase: Some(MessagePhase::Commentary), ..
} if source_id.as_str() == id)
})
}));
Some(RootRetainedAssistant {
order,
message,
standalone_eligible,
})
})
.collect::<Vec<_>>();
let request_candidates = RootConversationCandidates {
user_messages: user_candidates,
assistant_messages: assistant_candidates,
retained_assistants: retained_assistant_candidates,
delivered_messages: delivered_candidates,
retained_user_sources,
handoff_boundaries: self.handoff_boundaries.clone(),
latest_user_turn_id: reconciled.latest_user_turn_id.clone(),
missing_root_instructions: original_missing_root_instructions,
missing_assistant_context: retained_context.has_omitted_assistant_messages(),
missing_verified_answers: !retained_context.verified_answers_complete(),
};
akode_guardian_context::prepare_root_context(
&request_candidates,
root_history.original_legacy_user_messages(),
budgeting,
)
}
}
impl LocalAgentControl {
/// Returns bounded root conversation and authorization state for a MultiAgent V2 worker.
pub(crate) async fn root_user_authorization(
&self,
thread_id: ThreadId,
) -> Option<GuardianRootSnapshot> {
let root_thread_id = self
.runtime
.registry
.agent_id_for_path(&AgentPath::root())?;
if root_thread_id == thread_id {
return None;
}
let manager = self.runtime.upgrade().ok()?;
let root_thread = manager.get_thread(root_thread_id).await.ok()?;
if root_thread.multi_agent_version() != Some(MultiAgentVersion::V2) {
return None;
}
let worker_path = root_thread
.enabled(akode_features::Feature::GuardianRootHandoffContext)
.then(|| {
self.runtime
.registry
.agent_metadata_for_thread(thread_id)?
.agent_path
})
.flatten();
let root_history = root_thread.session.clone_history().await;
let handoff_boundaries = if let Some(worker) = worker_path {
super::root_handoff::handoff_boundaries(
root_history.annotated_items(),
&worker,
root_thread
.config()
.await
.multi_agent_v2
.tool_namespace
.as_deref(),
)
} else {
Vec::new()
};
let history = root_history.conversation_history_snapshot();
let history_reset_version = root_history.reset_version;
let request_candidates = RootConversationInput::new(CapturedRootConversation {
history: root_history,
handoff_boundaries,
});
let prepared = request_candidates.prepare(akode_guardian_context::ContextBudgeting::Fixed);
let root_evidence = root_thread
.session
.services
.thread_extension_data
.get_or_init(GuardianReviewEvidence::default);
Some(root_evidence.root_snapshot(
root_thread_id,
history_reset_version,
history.as_ref(),
prepared,
request_candidates,
))
}
}

View File

@@ -0,0 +1,65 @@
//! Exposes local status changes as shared agent snapshots instead of Tokio receivers.
//! Subscriptions retain no runtime handle and preserve the watch channel's coalescing.
use super::LocalAgentControl;
use crate::agent::api::AgentInfo;
use crate::agent::types::LiveAgent;
use akode_protocol::ThreadId;
use akode_protocol::error::Result as CodexResult;
use futures::StreamExt;
use futures::stream;
use futures::stream::BoxStream;
use std::sync::Arc;
/// An initial runtime snapshot followed by coalesced status changes. The stream ends
/// when that local runtime's status channel closes; it does not follow a later reload.
pub(crate) type StatusSubscription = BoxStream<'static, CodexResult<AgentInfo>>;
impl LocalAgentControl {
pub(crate) async fn subscribe_status(
&self,
agent_id: ThreadId,
) -> CodexResult<StatusSubscription> {
let manager = self.runtime.upgrade()?;
let thread = manager.get_thread(agent_id).await?;
// Subscribe before reading settings; mark the initial status seen only afterward.
let mut receiver = thread.subscribe_status();
let config = Box::new(thread.config_snapshot().await);
let initial = LiveAgent {
thread_id: agent_id,
metadata: self.get_agent_metadata(agent_id).unwrap_or_default(),
status: receiver.borrow_and_update().clone(),
};
let weak_thread = Arc::downgrade(&thread);
let changes = stream::unfold(
(receiver, initial.clone(), config.clone()),
move |(mut receiver, mut snapshot, mut config)| {
let weak_thread = weak_thread.clone();
async move {
receiver.changed().await.ok()?;
snapshot.status = receiver.borrow_and_update().clone();
if let Some(thread) = weak_thread.upgrade() {
*config = thread.config_snapshot().await;
}
// A final status can outlive the runtime. Keep its last observed settings
// so removal from the manager does not hide an already-published update.
Some((
Ok(AgentInfo::Loaded {
agent: snapshot.clone(),
config: config.clone(),
}),
(receiver, snapshot, config),
))
}
},
);
Ok(stream::once(async move {
Ok(AgentInfo::Loaded {
agent: initial,
config,
})
})
.chain(changes)
.boxed())
}
}