Merge remote-tracking branch 'origin/model-fallback-list' into repair/collab-stack-refresh-20260402

# Conflicts:
#	codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
#	codex-rs/core/src/tools/handlers/multi_agents_tests.rs
#	codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
#	codex-rs/tools/src/agent_tool.rs
#	codex-rs/tools/src/agent_tool_tests.rs
This commit is contained in:
Friel
2026-04-02 11:45:32 +00:00
11 changed files with 858 additions and 171 deletions
@@ -24,7 +24,6 @@ use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::CollabAgentInteractionBeginEvent;
use codex_protocol::protocol::CollabAgentInteractionEndEvent;
use codex_protocol::protocol::CollabAgentRef;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabCloseBeginEvent;
use codex_protocol::protocol::CollabCloseEndEvent;
@@ -71,30 +71,6 @@ impl ToolHandler for Handler {
let fork_context = args
.fork_context
.unwrap_or_else(|| default_fork_context_for_role(&turn.config, role_name));
session
.send_event(
&turn,
CollabAgentSpawnBeginEvent {
call_id: call_id.clone(),
sender_thread_id: session.conversation_id,
prompt: prompt.clone(),
model: args
.model_fallback_list
.as_ref()
.and_then(|list| list.first())
.map(|candidate| candidate.model.clone())
.unwrap_or_else(|| args.model.clone().unwrap_or_default()),
reasoning_effort: args
.model_fallback_list
.as_ref()
.and_then(|list| list.first())
.and_then(|candidate| candidate.reasoning_effort)
.unwrap_or_else(|| args.reasoning_effort.unwrap_or_default()),
}
.into(),
)
.await;
let config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
let mut candidates_to_try = collect_spawn_agent_model_candidates(
@@ -111,6 +87,18 @@ impl ToolHandler for Handler {
let mut spawn_result = None;
for (idx, candidate) in candidates_to_try.iter().enumerate() {
let attempt_call_id = spawn_attempt_event_call_id(&call_id, idx);
let candidate_model = candidate.model.clone().unwrap_or_default();
let candidate_reasoning_effort = candidate.reasoning_effort.unwrap_or_default();
send_collab_agent_spawn_begin_event(
&session,
&turn,
attempt_call_id.clone(),
prompt.clone(),
candidate_model.clone(),
candidate_reasoning_effort,
)
.await;
let mut candidate_config = config.clone();
if !fork_context {
apply_requested_spawn_agent_model_overrides(
@@ -159,20 +147,57 @@ impl ToolHandler for Handler {
.await;
match attempt_result {
Ok(spawned_agent) => {
if spawn_should_retry_on_async_quota_exhaustion(
spawned_agent.status.clone(),
spawned_agent.thread_id,
&session.services.agent_control,
)
.await
&& idx + 1 < candidates_to_try.len()
{
continue;
}
spawn_result = Some(spawned_agent);
let status = if idx + 1 < candidates_to_try.len() {
match probe_spawn_attempt_for_async_quota_exhaustion(
spawned_agent.status.clone(),
spawned_agent.thread_id,
&session.services.agent_control,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(retry_status) => {
match close_quota_exhausted_spawn_attempt(
&session.services.agent_control,
spawned_agent.thread_id,
retry_status,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(status) => {
send_collab_agent_spawn_retry_preempted_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
status,
)
.await;
continue;
}
}
}
}
} else {
spawned_agent.status.clone()
};
spawn_result = Some((spawned_agent, status, attempt_call_id));
break;
}
Err(err) => {
send_collab_agent_spawn_error_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
&err,
)
.await;
if spawn_should_retry_on_quota_exhaustion(&err)
&& idx + 1 < candidates_to_try.len()
{
@@ -182,14 +207,13 @@ impl ToolHandler for Handler {
}
}
}
let Some(spawned_agent) = spawn_result else {
let Some((spawned_agent, status, spawn_event_call_id)) = spawn_result else {
return Err(FunctionCallError::RespondToModel(
"No spawn attempts were executed".to_string(),
));
};
let new_thread_id = Some(spawned_agent.thread_id);
let new_agent_metadata = Some(spawned_agent.metadata.clone());
let status = spawned_agent.status.clone();
let agent_snapshot = match new_thread_id {
Some(thread_id) => {
session
@@ -227,7 +251,7 @@ impl ToolHandler for Handler {
.send_event(
&turn,
CollabAgentSpawnEndEvent {
call_id,
call_id: spawn_event_call_id,
sender_thread_id: session.conversation_id,
new_thread_id,
new_agent_nickname,
@@ -1,5 +1,4 @@
use crate::agent::AgentStatus;
use crate::agent::status::is_final;
use crate::codex::Session;
use crate::codex::TurnContext;
use crate::config::Config;
@@ -17,6 +16,8 @@ use codex_protocol::models::ResponseInputItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::openai_models::ReasoningEffortPreset;
use codex_protocol::protocol::CollabAgentRef;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabAgentStatusEntry;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::SessionSource;
@@ -27,12 +28,27 @@ use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use tokio::time::Duration;
use tokio::time::Instant;
use tokio::time::timeout;
/// Minimum wait timeout to prevent tight polling loops from burning CPU.
pub(crate) const MIN_WAIT_TIMEOUT_MS: i64 = 10_000;
pub(crate) const DEFAULT_WAIT_TIMEOUT_MS: i64 = 30_000;
pub(crate) const MAX_WAIT_TIMEOUT_MS: i64 = 3600 * 1000;
const ASYNC_QUOTA_EXHAUSTION_STATUS_TIMEOUT: Duration = Duration::from_secs(2);
pub(crate) enum SpawnAttemptRetryDecision {
Accept(AgentStatus),
Retry(AgentStatus),
}
pub(crate) fn spawn_attempt_event_call_id(call_id: &str, attempt_index: usize) -> String {
if attempt_index == 0 {
call_id.to_string()
} else {
format!("{call_id}#{}", attempt_index + 1)
}
}
pub(crate) fn function_arguments(payload: ToolPayload) -> Result<String, FunctionCallError> {
match payload {
@@ -98,7 +114,7 @@ pub(crate) fn collect_spawn_agent_model_candidates(
.iter()
.map(|candidate| SpawnAgentModelCandidate {
model: Some(candidate.model.clone()),
reasoning_effort: candidate.reasoning_effort,
reasoning_effort: candidate.reasoning_effort.or(requested_reasoning_effort),
})
.collect();
}
@@ -113,6 +129,30 @@ pub(crate) fn collect_spawn_agent_model_candidates(
candidates
}
pub(crate) async fn close_quota_exhausted_spawn_attempt(
agent_control: &crate::agent::control::AgentControl,
thread_id: ThreadId,
retry_status: AgentStatus,
) -> SpawnAttemptRetryDecision {
let retry_decision =
recheck_spawn_attempt_retry_decision(retry_status, thread_id, agent_control).await;
let SpawnAttemptRetryDecision::Retry(status) = retry_decision else {
return retry_decision;
};
// There is still a narrow TOCTOU window: a child can leave `PendingInit` after the final
// status read above and before `close_agent` runs. `AgentControl` does not currently expose
// a compare-and-close primitive, so this is the strongest local mitigation available.
if let Err(err) = agent_control.close_agent(thread_id).await
&& !matches!(
err,
CodexErr::ThreadNotFound(_) | CodexErr::InternalAgentDied
)
{
tracing::warn!("failed to close quota-exhausted spawn attempt {thread_id}: {err}");
}
SpawnAttemptRetryDecision::Retry(status)
}
pub(crate) fn spawn_should_retry_on_quota_exhaustion(error: &CodexErr) -> bool {
matches!(
error,
@@ -120,36 +160,93 @@ pub(crate) fn spawn_should_retry_on_quota_exhaustion(error: &CodexErr) -> bool {
)
}
pub(crate) async fn spawn_should_retry_on_async_quota_exhaustion(
pub(crate) async fn probe_spawn_attempt_for_async_quota_exhaustion(
thread_status: AgentStatus,
thread_id: ThreadId,
agent_control: &crate::agent::control::AgentControl,
) -> bool {
if is_final(&thread_status) && spawn_should_retry_on_quota_exhaustion_status(&thread_status) {
return true;
) -> SpawnAttemptRetryDecision {
match thread_status {
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => {
return retry_decision_for_final_spawn_status(thread_status);
}
AgentStatus::PendingInit | AgentStatus::Running | AgentStatus::Interrupted => {}
}
let Ok(mut status_rx) = agent_control.subscribe_status(thread_id).await else {
return false;
return match thread_status {
AgentStatus::Running | AgentStatus::Interrupted => {
SpawnAttemptRetryDecision::Accept(thread_status)
}
_ => SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
};
};
let mut status = status_rx.borrow_and_update().clone();
if is_final(&status) && spawn_should_retry_on_quota_exhaustion_status(&status) {
return true;
}
let deadline = Instant::now() + ASYNC_QUOTA_EXHAUSTION_STATUS_TIMEOUT;
loop {
if timeout(Duration::from_millis(250), status_rx.changed())
.await
.is_err()
{
break;
let status = status_rx.borrow_and_update().clone();
match status {
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => {
return retry_decision_for_final_spawn_status(status);
}
AgentStatus::PendingInit | AgentStatus::Running | AgentStatus::Interrupted => {}
}
status = status_rx.borrow().clone();
if is_final(&status) {
return spawn_should_retry_on_quota_exhaustion_status(&status);
let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
return match status {
AgentStatus::PendingInit => {
SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit)
}
AgentStatus::Running | AgentStatus::Interrupted => {
SpawnAttemptRetryDecision::Accept(status)
}
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => retry_decision_for_final_spawn_status(status),
};
};
match timeout(remaining, status_rx.changed()).await {
Ok(Ok(())) => {}
Ok(Err(_)) => return SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
Err(_) => return SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
}
}
false
}
pub(crate) async fn recheck_spawn_attempt_retry_decision(
status: AgentStatus,
thread_id: ThreadId,
agent_control: &crate::agent::control::AgentControl,
) -> SpawnAttemptRetryDecision {
if !matches!(status, AgentStatus::PendingInit) {
return SpawnAttemptRetryDecision::Retry(status);
}
let latest_status = agent_control.get_status(thread_id).await;
match latest_status {
AgentStatus::Running | AgentStatus::Interrupted => {
SpawnAttemptRetryDecision::Accept(latest_status)
}
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => retry_decision_for_final_spawn_status(latest_status),
AgentStatus::PendingInit => SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
}
}
fn retry_decision_for_final_spawn_status(status: AgentStatus) -> SpawnAttemptRetryDecision {
if spawn_should_retry_on_quota_exhaustion_status(&status) {
SpawnAttemptRetryDecision::Retry(status)
} else {
SpawnAttemptRetryDecision::Accept(status)
}
}
fn spawn_should_retry_on_quota_exhaustion_status(status: &AgentStatus) -> bool {
@@ -212,6 +309,88 @@ pub(crate) fn collab_spawn_error(err: CodexErr) -> FunctionCallError {
}
}
pub(crate) async fn send_collab_agent_spawn_error_event(
session: &Session,
turn: &TurnContext,
call_id: String,
prompt: String,
model: String,
reasoning_effort: ReasoningEffort,
err: &CodexErr,
) {
session
.send_event(
turn,
CollabAgentSpawnEndEvent {
call_id,
sender_thread_id: session.conversation_id,
new_thread_id: None,
new_agent_nickname: None,
new_agent_role: None,
prompt,
model,
reasoning_effort,
status: match err {
CodexErr::ThreadNotFound(_) => AgentStatus::NotFound,
err => AgentStatus::Errored(err.to_string()),
},
}
.into(),
)
.await;
}
pub(crate) async fn send_collab_agent_spawn_begin_event(
session: &Session,
turn: &TurnContext,
call_id: String,
prompt: String,
model: String,
reasoning_effort: ReasoningEffort,
) {
session
.send_event(
turn,
CollabAgentSpawnBeginEvent {
call_id,
sender_thread_id: session.conversation_id,
prompt,
model,
reasoning_effort,
}
.into(),
)
.await;
}
pub(crate) async fn send_collab_agent_spawn_retry_preempted_event(
session: &Session,
turn: &TurnContext,
call_id: String,
prompt: String,
model: String,
reasoning_effort: ReasoningEffort,
status: AgentStatus,
) {
session
.send_event(
turn,
CollabAgentSpawnEndEvent {
call_id,
sender_thread_id: session.conversation_id,
new_thread_id: None,
new_agent_nickname: None,
new_agent_role: None,
prompt,
model,
reasoning_effort,
status,
}
.into(),
)
.await;
}
pub(crate) fn collab_agent_error(agent_id: ThreadId, err: CodexErr) -> FunctionCallError {
match err {
CodexErr::ThreadNotFound(id) => {
@@ -3,6 +3,7 @@ use crate::ThreadManager;
use crate::agent::WatchdogRegistration;
use crate::built_in_model_providers;
use crate::codex::make_session_and_context;
use crate::codex::make_session_and_context_with_rx;
use crate::config::AgentRoleConfig;
use crate::config::DEFAULT_AGENT_MAX_DEPTH;
use crate::function_tool::FunctionCallError;
@@ -35,6 +36,8 @@ use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::FileSystemSandboxPolicy;
use codex_protocol::protocol::InitialHistory;
@@ -264,6 +267,20 @@ where
}
}
async fn wait_for_collab_spawn_end_event(
rx: &async_channel::Receiver<Event>,
) -> CollabAgentSpawnEndEvent {
loop {
let event = timeout(Duration::from_secs(1), rx.recv())
.await
.expect("collab spawn-end event timed out")
.expect("collab spawn-end event missing");
if let EventMsg::CollabAgentSpawnEnd(event) = event.msg {
return event;
}
}
}
#[derive(Debug, Deserialize)]
struct ListAgentsResult {
agents: Vec<ListedAgentResult>,
@@ -704,22 +721,175 @@ async fn multi_agent_v2_spawn_rejects_legacy_items_field() {
#[tokio::test]
async fn spawn_agent_errors_when_manager_dropped() {
let (session, turn) = make_session_and_context().await;
let (session, turn, rx) = make_session_and_context_with_rx().await;
let invocation = invocation(
Arc::new(session),
Arc::new(turn),
session.clone(),
turn.clone(),
"spawn_agent",
function_payload(json!({"message": "hello", "fork_context": false})),
);
let Err(err) = SpawnAgentHandler.handle(invocation).await else {
panic!("spawn should fail without a manager");
};
let spawn_end_event = wait_for_collab_spawn_end_event(&rx).await;
assert_eq!(spawn_end_event.call_id, "call-1");
assert_eq!(spawn_end_event.sender_thread_id, session.conversation_id);
assert_eq!(spawn_end_event.new_thread_id, None);
assert_eq!(spawn_end_event.new_agent_nickname, None);
assert_eq!(spawn_end_event.new_agent_role, None);
assert_eq!(spawn_end_event.prompt, "hello");
assert_eq!(spawn_end_event.model, "");
assert_eq!(spawn_end_event.reasoning_effort, ReasoningEffort::default());
assert!(matches!(
spawn_end_event.status,
AgentStatus::Errored(ref message) if message.contains("thread manager dropped")
));
assert_eq!(
err,
FunctionCallError::RespondToModel("collab manager unavailable".to_string())
);
}
#[tokio::test]
async fn multi_agent_v2_spawn_agent_errors_when_manager_dropped() {
let (session, mut turn, rx) = make_session_and_context_with_rx().await;
let turn_context = Arc::get_mut(&mut turn).expect("single turn context ref");
let mut config = (*turn_context.config).clone();
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
turn_context.config = Arc::new(config);
let invocation = invocation(
session.clone(),
turn.clone(),
"spawn_agent",
function_payload(json!({
"message": "inspect this repo",
"task_name": "worker"
})),
);
let Err(err) = SpawnAgentHandlerV2.handle(invocation).await else {
panic!("spawn should fail without a manager");
};
let spawn_end_event = wait_for_collab_spawn_end_event(&rx).await;
assert_eq!(spawn_end_event.call_id, "call-1");
assert_eq!(spawn_end_event.sender_thread_id, session.conversation_id);
assert_eq!(spawn_end_event.new_thread_id, None);
assert_eq!(spawn_end_event.new_agent_nickname, None);
assert_eq!(spawn_end_event.new_agent_role, None);
assert_eq!(spawn_end_event.prompt, "inspect this repo");
assert_eq!(spawn_end_event.model, "");
assert_eq!(spawn_end_event.reasoning_effort, ReasoningEffort::default());
assert!(matches!(
spawn_end_event.status,
AgentStatus::Errored(ref message) if message.contains("thread manager dropped")
));
assert_eq!(
err,
FunctionCallError::RespondToModel("collab manager unavailable".to_string())
);
}
#[tokio::test]
async fn spawn_retry_preempted_event_omits_thread_identity() {
let (session, turn, rx) = make_session_and_context_with_rx().await;
send_collab_agent_spawn_retry_preempted_event(
session.as_ref(),
turn.as_ref(),
"call-1".to_string(),
"inspect this repo".to_string(),
"gpt-5.4-mini".to_string(),
ReasoningEffort::Medium,
AgentStatus::PendingInit,
)
.await;
let spawn_end_event = wait_for_collab_spawn_end_event(&rx).await;
assert_eq!(spawn_end_event.call_id, "call-1");
assert_eq!(spawn_end_event.sender_thread_id, session.conversation_id);
assert_eq!(spawn_end_event.new_thread_id, None);
assert_eq!(spawn_end_event.new_agent_nickname, None);
assert_eq!(spawn_end_event.new_agent_role, None);
assert_eq!(spawn_end_event.prompt, "inspect this repo");
assert_eq!(spawn_end_event.model, "gpt-5.4-mini");
assert_eq!(spawn_end_event.reasoning_effort, ReasoningEffort::Medium);
assert_eq!(spawn_end_event.status, AgentStatus::PendingInit);
}
#[tokio::test]
async fn spawn_async_quota_probe_accepts_running_child() {
let decision = probe_spawn_attempt_for_async_quota_exhaustion(
AgentStatus::Running,
ThreadId::default(),
&crate::agent::control::AgentControl::default(),
)
.await;
assert!(matches!(
decision,
SpawnAttemptRetryDecision::Accept(AgentStatus::Running)
));
}
#[tokio::test]
async fn close_quota_exhausted_spawn_attempt_accepts_child_that_started_running() {
let (_session, turn) = make_session_and_context().await;
let manager = thread_manager();
let thread = manager
.start_thread((*turn.config).clone())
.await
.expect("child thread should start");
let active_turn = thread.thread.codex.session.new_default_turn().await;
thread
.thread
.codex
.session
.spawn_task(
Arc::clone(&active_turn),
vec![UserInput::Text {
text: "working".to_string(),
text_elements: Vec::new(),
}],
NeverEndingTask,
)
.await;
timeout(Duration::from_secs(1), async {
loop {
if manager.agent_control().get_status(thread.thread_id).await == AgentStatus::Running {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("child should reach running");
let decision = close_quota_exhausted_spawn_attempt(
&manager.agent_control(),
thread.thread_id,
AgentStatus::PendingInit,
)
.await;
assert!(matches!(
decision,
SpawnAttemptRetryDecision::Accept(AgentStatus::Running)
));
assert_eq!(
manager.agent_control().get_status(thread.thread_id).await,
AgentStatus::Running
);
let _ = thread
.thread
.submit(Op::Shutdown {})
.await
.expect("shutdown should submit");
}
#[tokio::test]
async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_path() {
#[derive(Debug, Deserialize)]
@@ -17,7 +17,6 @@ use codex_protocol::models::ResponseInputItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::CollabAgentInteractionBeginEvent;
use codex_protocol::protocol::CollabAgentInteractionEndEvent;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabCloseBeginEvent;
use codex_protocol::protocol::CollabCloseEndEvent;
@@ -53,29 +53,6 @@ impl ToolHandler for Handler {
"Agent depth limit reached. Solve the task yourself.".to_string(),
));
}
session
.send_event(
&turn,
CollabAgentSpawnBeginEvent {
call_id: call_id.clone(),
sender_thread_id: session.conversation_id,
prompt: prompt.clone(),
model: args
.model_fallback_list
.as_ref()
.and_then(|list| list.first())
.map(|candidate| candidate.model.clone())
.unwrap_or_else(|| args.model.clone().unwrap_or_default()),
reasoning_effort: args
.model_fallback_list
.as_ref()
.and_then(|list| list.first())
.and_then(|candidate| candidate.reasoning_effort)
.unwrap_or_else(|| args.reasoning_effort.unwrap_or_default()),
}
.into(),
)
.await;
let config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
@@ -120,6 +97,18 @@ impl ToolHandler for Handler {
let mut spawn_result = None;
for (idx, candidate) in candidates_to_try.iter().enumerate() {
let attempt_call_id = spawn_attempt_event_call_id(&call_id, idx);
let candidate_model = candidate.model.clone().unwrap_or_default();
let candidate_reasoning_effort = candidate.reasoning_effort.unwrap_or_default();
send_collab_agent_spawn_begin_event(
&session,
&turn,
attempt_call_id.clone(),
prompt.clone(),
candidate_model.clone(),
candidate_reasoning_effort,
)
.await;
let mut candidate_config = config.clone();
if fork_mode.is_none() {
apply_requested_spawn_agent_model_overrides(
@@ -147,31 +136,64 @@ impl ToolHandler for Handler {
initial_agent_op.clone(),
Some(spawn_source.clone()),
SpawnAgentOptions {
fork_parent_spawn_call_id: if fork_mode.is_some() {
Some(call_id.clone())
} else {
None
},
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
fork_mode: fork_mode.clone(),
},
)
.await;
match attempt_result {
Ok(spawned_agent) => {
if spawn_should_retry_on_async_quota_exhaustion(
spawned_agent.status.clone(),
spawned_agent.thread_id,
&session.services.agent_control,
)
.await
&& idx + 1 < candidates_to_try.len()
{
continue;
}
spawn_result = Some(spawned_agent);
let status = if idx + 1 < candidates_to_try.len() {
match probe_spawn_attempt_for_async_quota_exhaustion(
spawned_agent.status.clone(),
spawned_agent.thread_id,
&session.services.agent_control,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(retry_status) => {
match close_quota_exhausted_spawn_attempt(
&session.services.agent_control,
spawned_agent.thread_id,
retry_status,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(status) => {
send_collab_agent_spawn_retry_preempted_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
status,
)
.await;
continue;
}
}
}
}
} else {
spawned_agent.status.clone()
};
spawn_result = Some((spawned_agent, status, attempt_call_id));
break;
}
Err(err) => {
send_collab_agent_spawn_error_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
&err,
)
.await;
if spawn_should_retry_on_quota_exhaustion(&err)
&& idx + 1 < candidates_to_try.len()
{
@@ -181,14 +203,13 @@ impl ToolHandler for Handler {
}
}
}
let Some(spawned_agent) = spawn_result else {
let Some((spawned_agent, status, spawn_event_call_id)) = spawn_result else {
return Err(FunctionCallError::RespondToModel(
"No spawn attempts were executed".to_string(),
));
};
let new_thread_id = Some(spawned_agent.thread_id);
let new_agent_metadata = Some(spawned_agent.metadata.clone());
let status = spawned_agent.status.clone();
let agent_snapshot = match new_thread_id {
Some(thread_id) => {
session
@@ -226,7 +247,7 @@ impl ToolHandler for Handler {
.send_event(
&turn,
CollabAgentSpawnEndEvent {
call_id,
call_id: spawn_event_call_id,
sender_thread_id: session.conversation_id,
new_thread_id,
new_agent_nickname,
@@ -260,6 +281,7 @@ impl ToolHandler for Handler {
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct SpawnAgentArgs {
message: String,
task_name: String,