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:
134
akode-rs/core/src/tasks/admission.rs
Normal file
134
akode-rs/core/src/tasks/admission.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
//! Acquires host execution capacity without blocking the submission dispatcher.
|
||||
//! Input stays with the registered task until admission succeeds, so abort owns cleanup.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_async_utils::OrCancelExt;
|
||||
use akode_protocol::error::CodexErr;
|
||||
use akode_protocol::error::CodexErrorDetails;
|
||||
use akode_protocol::error::Result;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::agent::host::AgentTurnAdmission;
|
||||
use crate::agent::host::AgentTurnAdmissionRequest;
|
||||
use crate::hook_environment_executor::with_environment_hooks;
|
||||
use crate::hook_runtime::record_pending_input;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn::recordable_inputs;
|
||||
use crate::session::turn::run_hooks_and_record_inputs;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::state::TaskKind;
|
||||
use crate::state::TurnState;
|
||||
use akode_protocol::protocol::HookEventName;
|
||||
use akode_protocol::protocol::TurnAbortReason;
|
||||
use akode_thread_store::PersistContext;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// The host admission path already emitted the logical turn's start event.
|
||||
pub(crate) struct HostTurnStarted;
|
||||
|
||||
pub(super) async fn admit(
|
||||
session: &Arc<Session>,
|
||||
context: &Arc<TurnContext>,
|
||||
task_kind: TaskKind,
|
||||
provider: &dyn AgentTurnAdmission,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<Vec<TurnInput>> {
|
||||
// Review forwards the delegate's start event. Other tasks announce the attempt
|
||||
// here so an unresolved admission remains visible and interruptible.
|
||||
if task_kind != TaskKind::Review {
|
||||
session.emit_turn_started(context, task_kind).await;
|
||||
context.extension_data.insert(HostTurnStarted);
|
||||
}
|
||||
let guard = provider
|
||||
.admit_turn(AgentTurnAdmissionRequest {
|
||||
thread_id: session.thread_id,
|
||||
turn_id: context.sub_id.clone(),
|
||||
})
|
||||
.or_cancel(cancellation)
|
||||
.await
|
||||
.map_err(|_| CodexErr::new(CodexErrorDetails::TurnAborted))??;
|
||||
|
||||
// Acquiring this lock waits for turn registration to finish before attaching the permit.
|
||||
// A cancelled/replaced task must never install its permit into a newer task,
|
||||
// even if recovery reused the turn ID.
|
||||
let mut active = session.active_turn.lock().await;
|
||||
let task = active
|
||||
.as_mut()
|
||||
.and_then(|turn| turn.task.as_mut())
|
||||
.filter(|task| Arc::ptr_eq(&task.turn_context, context))
|
||||
.filter(|_| !cancellation.is_cancelled())
|
||||
.ok_or_else(|| CodexErr::new(CodexErrorDetails::TurnAborted))?;
|
||||
task._agent_execution_guard = Some(guard);
|
||||
task.pending_initial_input.take().ok_or_else(|| {
|
||||
CodexErr::Fatal("initial input missing from the task awaiting host admission".into())
|
||||
})
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub(crate) fn host_turn_admission(&self) -> Option<Arc<dyn AgentTurnAdmission>> {
|
||||
match &self.agent_runtime {
|
||||
crate::agent::host::AgentRuntimeServices::Controller => None,
|
||||
crate::agent::host::AgentRuntimeServices::Host(services) => {
|
||||
Some(Arc::clone(&services.turn_admission))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interruption and suspension stop the task before it can persist its initial input.
|
||||
pub(crate) async fn record_pending_initial_input(
|
||||
self: &Arc<Self>,
|
||||
context: &Arc<TurnContext>,
|
||||
turn_state: &Mutex<TurnState>,
|
||||
input: Option<Vec<TurnInput>>,
|
||||
abort_reason: Option<&TurnAbortReason>,
|
||||
) -> Result<()> {
|
||||
let Some(mut input) = input else {
|
||||
return Ok(());
|
||||
};
|
||||
input.extend(
|
||||
self.input_queue
|
||||
.take_pending_input_for_turn_state(turn_state)
|
||||
.await,
|
||||
);
|
||||
let model_info = context.capture_current_model_info();
|
||||
if abort_reason != Some(&TurnAbortReason::Interrupted) {
|
||||
run_hooks_and_record_inputs(
|
||||
self,
|
||||
context,
|
||||
&model_info,
|
||||
&input,
|
||||
PersistContext::Standard,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for item in recordable_inputs(self, &model_info, &input) {
|
||||
let item = item?;
|
||||
// The user must resubmit a prompt that still needs a submit hook.
|
||||
if matches!(item.as_ref(), TurnInput::UserInput { .. })
|
||||
&& with_environment_hooks(
|
||||
self,
|
||||
context,
|
||||
&context.initial_environments.refresh_readiness(),
|
||||
)
|
||||
.execution_mode_for_event(HookEventName::UserPromptSubmit)
|
||||
.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
record_pending_input(
|
||||
self,
|
||||
context,
|
||||
&model_info,
|
||||
item.into_owned(),
|
||||
Vec::new(),
|
||||
PersistContext::Standard,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
111
akode-rs/core/src/tasks/compact.rs
Normal file
111
akode-rs/core/src/tasks/compact.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::SessionTask;
|
||||
use super::SessionTaskResult;
|
||||
use super::emit_compact_metric;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::state::TaskKind;
|
||||
use akode_features::Feature;
|
||||
use akode_model_provider::RemoteCompactionSupport;
|
||||
use akode_protocol::error::CodexErrorDetails;
|
||||
use akode_protocol::protocol::CodexErrorInfo;
|
||||
use akode_protocol::user_input::UserInput;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(crate) struct CompactTask;
|
||||
|
||||
impl SessionTask for CompactTask {
|
||||
fn kind(&self) -> TaskKind {
|
||||
TaskKind::Compact
|
||||
}
|
||||
|
||||
fn span_name(&self) -> &'static str {
|
||||
"session_task.compact"
|
||||
}
|
||||
|
||||
async fn run(
|
||||
self: Arc<Self>,
|
||||
session: Arc<Session>,
|
||||
ctx: Arc<TurnContext>,
|
||||
_input: Vec<TurnInput>,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> SessionTaskResult {
|
||||
let _profile_guard = ctx.turn_timing_state.begin_compaction();
|
||||
let _compaction_span = tracing::trace_span!(
|
||||
"codex.compaction",
|
||||
codex.turn.phase = "compaction",
|
||||
conversation.id = %session.thread_id,
|
||||
turn.id = %ctx.sub_id,
|
||||
);
|
||||
// Preparation errors must reach the task runner, which reports them to the client.
|
||||
session.emit_turn_started(&ctx, TaskKind::Compact).await;
|
||||
let step_context = session
|
||||
.capture_step_context(Arc::clone(&ctx), &cancellation_token)
|
||||
.await?;
|
||||
let world_state = Arc::new(
|
||||
session
|
||||
.build_world_state_for_step(&step_context, /*new_window*/ true)
|
||||
.await?,
|
||||
);
|
||||
if ctx.config.features.enabled(Feature::TokenBudget) {
|
||||
crate::compact_token_budget::run_manual_compact_task(
|
||||
session,
|
||||
step_context,
|
||||
world_state,
|
||||
)
|
||||
.await?;
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let result = match ctx.provider.capabilities().remote_compaction {
|
||||
RemoteCompactionSupport::V2 => {
|
||||
emit_compact_metric(
|
||||
&session.services.session_telemetry,
|
||||
"remote_v2",
|
||||
/*manual*/ true,
|
||||
);
|
||||
crate::compact_remote_v2::run_remote_compact_task(
|
||||
session.clone(),
|
||||
step_context,
|
||||
world_state,
|
||||
)
|
||||
.await
|
||||
}
|
||||
RemoteCompactionSupport::Unsupported => {
|
||||
emit_compact_metric(
|
||||
&session.services.session_telemetry,
|
||||
"local",
|
||||
/*manual*/ true,
|
||||
);
|
||||
let input = vec![UserInput::Text {
|
||||
text: ctx
|
||||
.config
|
||||
.compact_prompt
|
||||
.as_deref()
|
||||
.unwrap_or(crate::compact::SUMMARIZATION_PROMPT)
|
||||
.to_string(),
|
||||
// Compaction prompt is synthesized; no UI element ranges to preserve.
|
||||
text_elements: Vec::new(),
|
||||
}];
|
||||
crate::compact::run_compact_task(session.clone(), step_context, world_state, input)
|
||||
.await
|
||||
}
|
||||
};
|
||||
if let Err(err) = result {
|
||||
if matches!(err.details(), CodexErrorDetails::TurnAborted) {
|
||||
return Err(err);
|
||||
}
|
||||
let error = err.to_codex_protocol_error();
|
||||
if matches!(error, CodexErrorInfo::UsageLimitExceeded) {
|
||||
// Compaction already emitted the error; notify extensions without emitting it twice.
|
||||
session
|
||||
.emit_turn_error_lifecycle(ctx.as_ref(), error, err.details())
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
123
akode-rs/core/src/tasks/lifecycle.rs
Normal file
123
akode-rs/core/src/tasks/lifecycle.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_extension_api::ExtensionData;
|
||||
use akode_extension_api::ThreadIdleCause;
|
||||
use akode_extension_api::TurnStartPhase;
|
||||
use akode_protocol::error::CodexErrorDetails;
|
||||
use akode_protocol::protocol::CodexErrorInfo;
|
||||
use akode_protocol::protocol::TokenUsage;
|
||||
use akode_protocol::protocol::TurnAbortReason;
|
||||
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
|
||||
impl Session {
|
||||
#[tracing::instrument(level = "trace", skip_all, fields(turn_id = %turn_context.sub_id, phase = ?phase))]
|
||||
pub(super) async fn emit_turn_start_lifecycle(
|
||||
self: &Arc<Self>,
|
||||
turn_context: &TurnContext,
|
||||
token_usage_at_turn_start: Option<&TokenUsage>,
|
||||
phase: TurnStartPhase,
|
||||
) {
|
||||
turn_context
|
||||
.extension_data
|
||||
.insert(turn_context.session_telemetry.clone());
|
||||
let collaboration_mode = turn_context.collaboration_mode();
|
||||
for contributor in self.services.extensions.turn_lifecycle_contributors() {
|
||||
if contributor.turn_start_phase(&self.services.thread_extension_data) != phase {
|
||||
continue;
|
||||
}
|
||||
if phase == TurnStartPhase::RegularTaskStart
|
||||
&& contributor.requires_mcp_runtime(&self.services.thread_extension_data)
|
||||
{
|
||||
self.refresh_mcp_if_dirty().await;
|
||||
}
|
||||
contributor
|
||||
.on_turn_start(akode_extension_api::TurnStartInput {
|
||||
turn_id: turn_context.sub_id.as_str(),
|
||||
collaboration_mode: &collaboration_mode,
|
||||
token_usage_at_turn_start,
|
||||
session_store: &self.services.session_extension_data,
|
||||
thread_store: &self.services.thread_extension_data,
|
||||
turn_store: turn_context.extension_data.as_ref(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn emit_turn_stop_lifecycle(&self, turn_store: &ExtensionData) {
|
||||
for contributor in self.services.extensions.turn_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_turn_stop(akode_extension_api::TurnStopInput {
|
||||
session_store: &self.services.session_extension_data,
|
||||
thread_store: &self.services.thread_extension_data,
|
||||
turn_store,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn emit_thread_idle_lifecycle_if_idle(&self, cause: ThreadIdleCause) {
|
||||
let cause = {
|
||||
let active_turn = self.active_turn.lock().await;
|
||||
if active_turn.is_some() {
|
||||
return;
|
||||
}
|
||||
if self.is_interrupted() {
|
||||
ThreadIdleCause::Interrupted
|
||||
} else {
|
||||
cause
|
||||
}
|
||||
};
|
||||
if self.input_queue.has_trigger_turn_mailbox_items().await {
|
||||
return;
|
||||
}
|
||||
|
||||
for contributor in self.services.extensions.thread_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_thread_idle(akode_extension_api::ThreadIdleInput {
|
||||
cause,
|
||||
session_store: &self.services.session_extension_data,
|
||||
thread_store: &self.services.thread_extension_data,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn emit_turn_abort_lifecycle(
|
||||
&self,
|
||||
reason: TurnAbortReason,
|
||||
turn_store: &ExtensionData,
|
||||
) {
|
||||
for contributor in self.services.extensions.turn_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_turn_abort(akode_extension_api::TurnAbortInput {
|
||||
reason: reason.clone(),
|
||||
session_store: &self.services.session_extension_data,
|
||||
thread_store: &self.services.thread_extension_data,
|
||||
turn_store,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn emit_turn_error_lifecycle(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
error: CodexErrorInfo,
|
||||
error_details: &CodexErrorDetails,
|
||||
) {
|
||||
for contributor in self.services.extensions.turn_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_turn_error(akode_extension_api::TurnErrorInput {
|
||||
turn_id: turn_context.sub_id.as_str(),
|
||||
error: error.clone(),
|
||||
error_details,
|
||||
session_store: &self.services.session_extension_data,
|
||||
thread_store: &self.services.thread_extension_data,
|
||||
turn_store: turn_context.extension_data.as_ref(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
1156
akode-rs/core/src/tasks/mod.rs
Normal file
1156
akode-rs/core/src/tasks/mod.rs
Normal file
File diff suppressed because it is too large
Load Diff
806
akode-rs/core/src/tasks/mod_tests.rs
Normal file
806
akode-rs/core/src/tasks/mod_tests.rs
Normal file
@@ -0,0 +1,806 @@
|
||||
use super::SessionTask;
|
||||
use super::SessionTaskResult;
|
||||
use super::TASK_COMPACT_METRIC;
|
||||
use super::emit_compact_metric;
|
||||
use super::emit_turn_memory_metric;
|
||||
use super::emit_turn_network_proxy_metric;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::tests::make_session_and_context_with_rx;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::state::TaskKind;
|
||||
use akode_otel::MetricsClient;
|
||||
use akode_otel::MetricsConfig;
|
||||
use akode_otel::SessionTelemetry;
|
||||
use akode_otel::TURN_CRITICAL_PATH_CAPTURE_METRIC;
|
||||
use akode_otel::TURN_CRITICAL_PATH_COMPONENT_METRIC;
|
||||
use akode_otel::TURN_CRITICAL_PATH_DURATION_METRIC;
|
||||
use akode_otel::TURN_MEMORY_METRIC;
|
||||
use akode_otel::TURN_NETWORK_PROXY_METRIC;
|
||||
use akode_otel::TURN_TOKEN_USAGE_METRIC;
|
||||
use akode_otel::TURN_TOOL_CALL_METRIC;
|
||||
use akode_otel::TURN_UNIFIED_EXEC_RUNNING_PROCESSES_METRIC;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::error::CodexErr;
|
||||
use akode_protocol::models::AudioReference;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::protocol::CodexErrorInfo;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::TokenUsage;
|
||||
use akode_protocol::user_input::UserInput;
|
||||
use opentelemetry::KeyValue;
|
||||
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::Metric;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ResourceMetrics;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
struct PendingTask;
|
||||
|
||||
impl SessionTask for PendingTask {
|
||||
fn kind(&self) -> TaskKind {
|
||||
TaskKind::Regular
|
||||
}
|
||||
|
||||
fn span_name(&self) -> &'static str {
|
||||
"session_task.pending"
|
||||
}
|
||||
|
||||
async fn run(
|
||||
self: Arc<Self>,
|
||||
_session: Arc<Session>,
|
||||
_turn_context: Arc<TurnContext>,
|
||||
_input: Vec<TurnInput>,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> SessionTaskResult {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn task_finish_rejects_uploaded_audio_without_losing_other_pending_input() {
|
||||
let (session, turn_context, receiver) = make_session_and_context_with_rx().await;
|
||||
session
|
||||
.spawn_task(Arc::clone(&turn_context), Vec::new(), PendingTask)
|
||||
.await;
|
||||
while receiver.try_recv().is_ok() {}
|
||||
|
||||
let turn_state = {
|
||||
let active_turn = session.active_turn.lock().await;
|
||||
Arc::clone(
|
||||
&active_turn
|
||||
.as_ref()
|
||||
.expect("active pending task")
|
||||
.turn_state,
|
||||
)
|
||||
};
|
||||
session
|
||||
.input_queue
|
||||
.extend_pending_input_for_turn_state(
|
||||
turn_state.as_ref(),
|
||||
vec![TurnInput::UserInput {
|
||||
content: vec![
|
||||
UserInput::Text {
|
||||
text: "preserve pending text".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
UserInput::Audio {
|
||||
audio: AudioReference::File {
|
||||
file_id: "file_disabled_at_finish".to_string(),
|
||||
},
|
||||
},
|
||||
],
|
||||
client_id: None,
|
||||
metadata: Default::default(),
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
|
||||
session
|
||||
.on_task_finished(Arc::clone(&turn_context), /*task_result*/ Ok(None))
|
||||
.await;
|
||||
|
||||
let history = session.clone_history().await;
|
||||
assert!(history.raw_items().any(|item| {
|
||||
matches!(item, ResponseItem::Message { content, .. } if content.iter().any(|part| {
|
||||
matches!(part, ContentItem::InputText { text } if text == "preserve pending text")
|
||||
}))
|
||||
}));
|
||||
assert!(history.raw_items().all(|item| {
|
||||
!matches!(item, ResponseItem::Message { content, .. } if content.iter().any(|part| {
|
||||
matches!(part, ContentItem::InputAudio {
|
||||
audio: AudioReference::File { file_id, .. },
|
||||
} if file_id == "file_disabled_at_finish")
|
||||
}))
|
||||
}));
|
||||
|
||||
let (saw_error, completed) = tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
let mut saw_error = false;
|
||||
loop {
|
||||
match receiver.recv().await.expect("event channel open").msg {
|
||||
EventMsg::Error(error) => {
|
||||
saw_error = true;
|
||||
assert_eq!(error.codex_error_info, Some(CodexErrorInfo::BadRequest));
|
||||
}
|
||||
EventMsg::TurnComplete(completed) => break (saw_error, completed),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("task finish events");
|
||||
assert!(saw_error, "the rejected drain should emit an error event");
|
||||
assert_eq!(
|
||||
completed
|
||||
.error
|
||||
.as_ref()
|
||||
.and_then(|error| error.codex_error_info.clone()),
|
||||
Some(CodexErrorInfo::BadRequest)
|
||||
);
|
||||
}
|
||||
|
||||
fn test_session_telemetry() -> SessionTelemetry {
|
||||
let exporter = InMemoryMetricExporter::default();
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "akode-core", env!("CARGO_PKG_VERSION"), exporter)
|
||||
.with_runtime_reader(),
|
||||
)
|
||||
.expect("in-memory metrics client");
|
||||
SessionTelemetry::new(
|
||||
ThreadId::new(),
|
||||
"gpt-5.4",
|
||||
"gpt-5.4",
|
||||
/*account_id*/ None,
|
||||
/*account_email*/ None,
|
||||
/*auth_mode*/ None,
|
||||
"test_originator".to_string(),
|
||||
/*log_user_prompts*/ false,
|
||||
"tty".to_string(),
|
||||
SessionSource::Cli,
|
||||
)
|
||||
.with_metrics_without_metadata_tags(metrics)
|
||||
}
|
||||
|
||||
fn find_metric<'a>(resource_metrics: &'a ResourceMetrics, name: &str) -> &'a Metric {
|
||||
for scope_metrics in resource_metrics.scope_metrics() {
|
||||
for metric in scope_metrics.metrics() {
|
||||
if metric.name() == name {
|
||||
return metric;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("metric {name} missing");
|
||||
}
|
||||
|
||||
fn attributes_to_map<'a>(
|
||||
attributes: impl Iterator<Item = &'a KeyValue>,
|
||||
) -> BTreeMap<String, String> {
|
||||
attributes
|
||||
.map(|kv| (kv.key.as_str().to_string(), kv.value.as_str().to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn metric_point(resource_metrics: &ResourceMetrics, name: &str) -> (BTreeMap<String, String>, u64) {
|
||||
let metric = find_metric(resource_metrics, name);
|
||||
match metric.data() {
|
||||
AggregatedMetrics::U64(data) => match data {
|
||||
MetricData::Sum(sum) => {
|
||||
let points: Vec<_> = sum.data_points().collect();
|
||||
assert_eq!(points.len(), 1);
|
||||
let point = points[0];
|
||||
(attributes_to_map(point.attributes()), point.value())
|
||||
}
|
||||
_ => panic!("unexpected counter aggregation"),
|
||||
},
|
||||
_ => panic!("unexpected counter data type"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum UsageScenario {
|
||||
ResponseOnly,
|
||||
ResponseAfterStepSwitch,
|
||||
CompactThenResponse,
|
||||
CompactThenStop,
|
||||
NoResponse,
|
||||
}
|
||||
|
||||
#[test_case::test_case(UsageScenario::ResponseOnly; "response_only")]
|
||||
#[test_case::test_case(UsageScenario::ResponseAfterStepSwitch; "response_after_step_switch")]
|
||||
#[test_case::test_case(UsageScenario::CompactThenResponse; "compact_then_response")]
|
||||
#[test_case::test_case(UsageScenario::CompactThenStop; "compact_then_stop")]
|
||||
#[test_case::test_case(UsageScenario::NoResponse; "no_response")]
|
||||
#[tokio::test]
|
||||
async fn turn_completion_metrics_follow_model_switch(scenario: UsageScenario) {
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory(
|
||||
"test",
|
||||
"akode-core",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
)
|
||||
.with_runtime_reader(),
|
||||
)
|
||||
.expect("in-memory metrics client");
|
||||
let (mut session, mut turn_context, receiver) = make_session_and_context_with_rx().await;
|
||||
let session_telemetry = session
|
||||
.services
|
||||
.session_telemetry
|
||||
.clone()
|
||||
.with_metrics(metrics.clone());
|
||||
Arc::get_mut(&mut session)
|
||||
.expect("session should be uniquely owned")
|
||||
.services
|
||||
.session_telemetry = session_telemetry.clone();
|
||||
Arc::get_mut(&mut turn_context)
|
||||
.expect("turn context should be uniquely owned")
|
||||
.session_telemetry = session_telemetry;
|
||||
|
||||
let next_model = if turn_context.model_info().slug == "gpt-5.4" {
|
||||
"gpt-5.2"
|
||||
} else {
|
||||
"gpt-5.4"
|
||||
};
|
||||
let previous_context = turn_context;
|
||||
let turn_context = Arc::new(
|
||||
previous_context
|
||||
.with_model(next_model.to_string(), &session.services.models_manager)
|
||||
.await,
|
||||
);
|
||||
// Earlier session usage must not leak into this turn's per-model samples.
|
||||
session
|
||||
.update_token_usage_info(
|
||||
&previous_context,
|
||||
Some(&TokenUsage {
|
||||
input_tokens: 1_000,
|
||||
total_tokens: 1_000,
|
||||
..TokenUsage::default()
|
||||
}),
|
||||
/*includes_reasoning*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("earlier session usage should be recorded");
|
||||
session
|
||||
.spawn_task(Arc::clone(&turn_context), Vec::new(), PendingTask)
|
||||
.await;
|
||||
let mut expected_usage = Vec::new();
|
||||
if matches!(
|
||||
scenario,
|
||||
UsageScenario::CompactThenResponse | UsageScenario::CompactThenStop
|
||||
) {
|
||||
let compaction_usage = TokenUsage {
|
||||
input_tokens: 100,
|
||||
cached_input_tokens: 30,
|
||||
cache_write_input_tokens: 20,
|
||||
output_tokens: 70,
|
||||
reasoning_output_tokens: 40,
|
||||
total_tokens: 170,
|
||||
codex_rollout_budget_units: None,
|
||||
};
|
||||
// Local pre-turn compaction records usage with the previous model's context.
|
||||
session
|
||||
.update_token_usage_info(
|
||||
&previous_context,
|
||||
Some(&compaction_usage),
|
||||
/*includes_reasoning*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("compaction usage should be recorded");
|
||||
expected_usage.push((previous_context.model_info().slug.clone(), compaction_usage));
|
||||
}
|
||||
if matches!(
|
||||
scenario,
|
||||
UsageScenario::ResponseOnly
|
||||
| UsageScenario::ResponseAfterStepSwitch
|
||||
| UsageScenario::CompactThenResponse
|
||||
) {
|
||||
let response_context = if matches!(scenario, UsageScenario::ResponseAfterStepSwitch) {
|
||||
&previous_context
|
||||
} else {
|
||||
&turn_context
|
||||
};
|
||||
let response_usage = TokenUsage {
|
||||
input_tokens: 10,
|
||||
cached_input_tokens: 3,
|
||||
cache_write_input_tokens: 2,
|
||||
output_tokens: 7,
|
||||
reasoning_output_tokens: 4,
|
||||
total_tokens: 17,
|
||||
codex_rollout_budget_units: None,
|
||||
};
|
||||
// Multiple requests for one model must still produce one turn histogram sample.
|
||||
for _ in 0..2 {
|
||||
session
|
||||
.record_token_usage_info(
|
||||
&turn_context,
|
||||
&response_context.initial_settings,
|
||||
Some(&response_usage),
|
||||
crate::session::TokenUsageContext::Sampling {
|
||||
includes_reasoning: false,
|
||||
input_item_count: 0,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("response usage should be recorded");
|
||||
}
|
||||
let mut total_usage = response_usage.clone();
|
||||
total_usage.add_assign(&response_usage);
|
||||
expected_usage.push((response_context.model_info().slug.clone(), total_usage));
|
||||
}
|
||||
if matches!(scenario, UsageScenario::NoResponse) {
|
||||
expected_usage.push((next_model.to_string(), TokenUsage::default()));
|
||||
}
|
||||
|
||||
let task_result = if matches!(scenario, UsageScenario::CompactThenStop) {
|
||||
// A PostCompact hook can stop the turn before the new model samples.
|
||||
Err(CodexErr::TurnAborted)
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
let expected_root = turn_context.root_turn_id();
|
||||
session.on_task_finished(turn_context, task_result).await;
|
||||
let mut terminal_root = None;
|
||||
while let Ok(event) = receiver.try_recv() {
|
||||
match event.msg {
|
||||
akode_protocol::protocol::EventMsg::TurnComplete(event) => {
|
||||
terminal_root = event.root_turn_id;
|
||||
}
|
||||
akode_protocol::protocol::EventMsg::TurnAborted(event) => {
|
||||
terminal_root = event.root_turn_id;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(terminal_root, Some(expected_root));
|
||||
|
||||
let snapshot = metrics.snapshot().expect("runtime metrics snapshot");
|
||||
let token_usage_metric = find_metric(&snapshot, TURN_TOKEN_USAGE_METRIC);
|
||||
let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = token_usage_metric.data() else {
|
||||
panic!("expected token usage histogram");
|
||||
};
|
||||
let mut token_usage_points = histogram
|
||||
.data_points()
|
||||
.map(|point| {
|
||||
let mut attributes = attributes_to_map(point.attributes());
|
||||
(
|
||||
(
|
||||
attributes
|
||||
.remove("token_type")
|
||||
.expect("token usage metric should include a token type"),
|
||||
attributes
|
||||
.remove("model")
|
||||
.expect("token usage metric should include a model"),
|
||||
),
|
||||
point.count(),
|
||||
point.sum(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut expected_points = expected_usage
|
||||
.into_iter()
|
||||
.flat_map(|(model, usage)| {
|
||||
[
|
||||
("cache_write_input", usage.cache_write_input_tokens),
|
||||
("cached_input", usage.cached_input()),
|
||||
("input", usage.input_tokens),
|
||||
("output", usage.output_tokens),
|
||||
("reasoning_output", usage.reasoning_output_tokens),
|
||||
("total", usage.total_tokens),
|
||||
]
|
||||
.map(|(token_type, value)| ((token_type.to_string(), model.clone()), 1, value as f64))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
token_usage_points.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
expected_points.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
assert_eq!(token_usage_points, expected_points);
|
||||
|
||||
let tool_call_metric = find_metric(&snapshot, TURN_TOOL_CALL_METRIC);
|
||||
let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = tool_call_metric.data() else {
|
||||
panic!("expected tool call histogram");
|
||||
};
|
||||
let tool_call_models = histogram
|
||||
.data_points()
|
||||
.map(|point| {
|
||||
attributes_to_map(point.attributes())
|
||||
.remove("model")
|
||||
.expect("tool call metric should include a model")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(tool_call_models, vec![next_model.to_string()]);
|
||||
|
||||
let counter_models = [
|
||||
TURN_MEMORY_METRIC,
|
||||
TURN_NETWORK_PROXY_METRIC,
|
||||
TURN_UNIFIED_EXEC_RUNNING_PROCESSES_METRIC,
|
||||
]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let (mut attributes, _value) = metric_point(&snapshot, name);
|
||||
(
|
||||
name.to_string(),
|
||||
attributes
|
||||
.remove("model")
|
||||
.expect("turn counter should include a model"),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
assert_eq!(
|
||||
counter_models,
|
||||
BTreeMap::from([
|
||||
(TURN_MEMORY_METRIC.to_string(), next_model.to_string()),
|
||||
(
|
||||
TURN_NETWORK_PROXY_METRIC.to_string(),
|
||||
next_model.to_string(),
|
||||
),
|
||||
(
|
||||
TURN_UNIFIED_EXEC_RUNNING_PROCESSES_METRIC.to_string(),
|
||||
next_model.to_string(),
|
||||
),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_turn_network_proxy_metric_records_active_turn() {
|
||||
let session_telemetry = test_session_telemetry();
|
||||
|
||||
emit_turn_network_proxy_metric(
|
||||
&session_telemetry,
|
||||
/*network_proxy_active*/ true,
|
||||
("tmp_mem_enabled", "true"),
|
||||
);
|
||||
|
||||
let snapshot = session_telemetry
|
||||
.snapshot_metrics()
|
||||
.expect("runtime metrics snapshot");
|
||||
let (attrs, value) = metric_point(&snapshot, TURN_NETWORK_PROXY_METRIC);
|
||||
|
||||
assert_eq!(value, 1);
|
||||
assert_eq!(
|
||||
attrs,
|
||||
BTreeMap::from([
|
||||
("active".to_string(), "true".to_string()),
|
||||
("tmp_mem_enabled".to_string(), "true".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_turn_network_proxy_metric_records_inactive_turn() {
|
||||
let session_telemetry = test_session_telemetry();
|
||||
|
||||
emit_turn_network_proxy_metric(
|
||||
&session_telemetry,
|
||||
/*network_proxy_active*/ false,
|
||||
("tmp_mem_enabled", "false"),
|
||||
);
|
||||
|
||||
let snapshot = session_telemetry
|
||||
.snapshot_metrics()
|
||||
.expect("runtime metrics snapshot");
|
||||
let (attrs, value) = metric_point(&snapshot, TURN_NETWORK_PROXY_METRIC);
|
||||
|
||||
assert_eq!(value, 1);
|
||||
assert_eq!(
|
||||
attrs,
|
||||
BTreeMap::from([
|
||||
("active".to_string(), "false".to_string()),
|
||||
("tmp_mem_enabled".to_string(), "false".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_turn_memory_metric_records_read_allowed_with_citations() {
|
||||
let session_telemetry = test_session_telemetry();
|
||||
|
||||
emit_turn_memory_metric(
|
||||
&session_telemetry,
|
||||
/*feature_enabled*/ true,
|
||||
/*config_enabled*/ true,
|
||||
/*has_citations*/ true,
|
||||
);
|
||||
|
||||
let snapshot = session_telemetry
|
||||
.snapshot_metrics()
|
||||
.expect("runtime metrics snapshot");
|
||||
let (attrs, value) = metric_point(&snapshot, TURN_MEMORY_METRIC);
|
||||
|
||||
assert_eq!(value, 1);
|
||||
assert_eq!(
|
||||
attrs,
|
||||
BTreeMap::from([
|
||||
("config_use_memories".to_string(), "true".to_string()),
|
||||
("feature_enabled".to_string(), "true".to_string()),
|
||||
("has_citations".to_string(), "true".to_string()),
|
||||
("read_allowed".to_string(), "true".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_turn_memory_metric_records_config_disabled_without_citations() {
|
||||
let session_telemetry = test_session_telemetry();
|
||||
|
||||
emit_turn_memory_metric(
|
||||
&session_telemetry,
|
||||
/*feature_enabled*/ true,
|
||||
/*config_enabled*/ false,
|
||||
/*has_citations*/ false,
|
||||
);
|
||||
|
||||
let snapshot = session_telemetry
|
||||
.snapshot_metrics()
|
||||
.expect("runtime metrics snapshot");
|
||||
let (attrs, value) = metric_point(&snapshot, TURN_MEMORY_METRIC);
|
||||
|
||||
assert_eq!(value, 1);
|
||||
assert_eq!(
|
||||
attrs,
|
||||
BTreeMap::from([
|
||||
("config_use_memories".to_string(), "false".to_string()),
|
||||
("feature_enabled".to_string(), "true".to_string()),
|
||||
("has_citations".to_string(), "false".to_string()),
|
||||
("read_allowed".to_string(), "false".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_compact_metric_records_manual_remote_v2() {
|
||||
let session_telemetry = test_session_telemetry();
|
||||
|
||||
emit_compact_metric(&session_telemetry, "remote_v2", /*manual*/ true);
|
||||
|
||||
let snapshot = session_telemetry
|
||||
.snapshot_metrics()
|
||||
.expect("runtime metrics snapshot");
|
||||
let (attrs, value) = metric_point(&snapshot, TASK_COMPACT_METRIC);
|
||||
|
||||
assert_eq!(value, 1);
|
||||
assert_eq!(
|
||||
attrs,
|
||||
BTreeMap::from([
|
||||
("manual".to_string(), "true".to_string()),
|
||||
("type".to_string(), "remote_v2".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_compact_metric_records_auto_local() {
|
||||
let session_telemetry = test_session_telemetry();
|
||||
|
||||
emit_compact_metric(&session_telemetry, "local", /*manual*/ false);
|
||||
|
||||
let snapshot = session_telemetry
|
||||
.snapshot_metrics()
|
||||
.expect("runtime metrics snapshot");
|
||||
let (attrs, value) = metric_point(&snapshot, TASK_COMPACT_METRIC);
|
||||
|
||||
assert_eq!(value, 1);
|
||||
assert_eq!(
|
||||
attrs,
|
||||
BTreeMap::from([
|
||||
("manual".to_string(), "false".to_string()),
|
||||
("type".to_string(), "local".to_string()),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
struct UncooperativeTimedTask {
|
||||
entered: Arc<tokio::sync::Notify>,
|
||||
}
|
||||
|
||||
impl SessionTask for UncooperativeTimedTask {
|
||||
fn kind(&self) -> TaskKind {
|
||||
TaskKind::Regular
|
||||
}
|
||||
fn span_name(&self) -> &'static str {
|
||||
"session_task.uncooperative_timing"
|
||||
}
|
||||
async fn run(
|
||||
self: Arc<Self>,
|
||||
_session: Arc<Session>,
|
||||
context: Arc<TurnContext>,
|
||||
_input: Vec<TurnInput>,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> SessionTaskResult {
|
||||
let timing = &context.turn_timing_state;
|
||||
timing.enable_critical_path();
|
||||
let batch = akode_direct_tool_timing::ToolBatchTiming::default();
|
||||
let now = std::time::Instant::now();
|
||||
let _blocking;
|
||||
let _work = timing.direct_tool_timings.start_turn_direct_call(
|
||||
"uncooperative",
|
||||
&context.sub_id,
|
||||
batch.clone(),
|
||||
now,
|
||||
timing.snapshot_path(now),
|
||||
);
|
||||
_blocking = timing.begin_tool_blocking(Some(batch));
|
||||
let _review = _work.start_review();
|
||||
self.entered.notify_one();
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn hard_abort_drops_timing_guards_before_profile_completion() {
|
||||
let (session, context, _receiver) = make_session_and_context_with_rx().await;
|
||||
let entered = Arc::new(tokio::sync::Notify::new());
|
||||
session
|
||||
.spawn_task(
|
||||
Arc::clone(&context),
|
||||
Vec::new(),
|
||||
UncooperativeTimedTask {
|
||||
entered: Arc::clone(&entered),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
entered.notified().await;
|
||||
session
|
||||
.abort_all_tasks(akode_protocol::protocol::TurnAbortReason::Interrupted)
|
||||
.await;
|
||||
// The task's review and tool guards are gone before abort completion.
|
||||
assert!(
|
||||
context
|
||||
.turn_timing_state
|
||||
.direct_tool_timings
|
||||
.owner_for_turn("uncooperative", &context.sub_id)
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
context
|
||||
.turn_timing_state
|
||||
.snapshot_path(std::time::Instant::now()),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_critical_path_metrics_count_each_capture_once() {
|
||||
use crate::turn_timing::TurnCriticalPath;
|
||||
use crate::turn_timing::TurnCriticalPathDurations;
|
||||
|
||||
let (session, mut context, _rx) = make_session_and_context_with_rx().await;
|
||||
let context = Arc::get_mut(&mut context).unwrap();
|
||||
context.session_telemetry = test_session_telemetry();
|
||||
let complete = TurnCriticalPath::Complete(TurnCriticalPathDurations {
|
||||
duration_ms: 60,
|
||||
inference_ms: 31,
|
||||
sampling_ms: 31,
|
||||
compaction_ms: 0,
|
||||
auto_review_ms: 2,
|
||||
auto_review_overhead_ms: None,
|
||||
tools_ms: 10,
|
||||
user_wait_ms: 0,
|
||||
overhead_ms: 14,
|
||||
unknown_ms: 3,
|
||||
});
|
||||
let _interest_cache_guard =
|
||||
tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());
|
||||
for (sku, path) in [
|
||||
(Some("codex"), complete),
|
||||
(Some("codex"), TurnCriticalPath::Disabled),
|
||||
(None, TurnCriticalPath::Incomplete),
|
||||
(Some("unrecognized-sku"), TurnCriticalPath::Incomplete),
|
||||
] {
|
||||
Arc::make_mut(&mut context.config).apps_mcp_product_sku = sku.map(str::to_owned);
|
||||
context.turn_timing_state = Arc::default();
|
||||
let (_, _, mut profile) = context
|
||||
.turn_timing_state
|
||||
.complete_profile_and_duration_ms()
|
||||
.await;
|
||||
profile.critical_path = path;
|
||||
let buffer: &std::sync::Mutex<Vec<u8>> =
|
||||
Box::leak(Box::new(std::sync::Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_ansi(false)
|
||||
.with_writer(tracing_test::internal::MockWriter::new(buffer))
|
||||
.finish();
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
for _ in 0..2 {
|
||||
crate::turn_timing::record_terminal_turn_profile(
|
||||
session.thread_id,
|
||||
context,
|
||||
&profile,
|
||||
);
|
||||
}
|
||||
});
|
||||
let trace = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
|
||||
match &profile.critical_path {
|
||||
TurnCriticalPath::Complete(_) => {
|
||||
assert!(trace.contains("critical_path_status=\"complete\""));
|
||||
assert!(trace.contains("critical_path_inference_ms=31"));
|
||||
assert!(trace.contains("critical_path_user_wait_ms=0"));
|
||||
}
|
||||
TurnCriticalPath::Disabled | TurnCriticalPath::Incomplete => {
|
||||
assert!(!trace.contains("critical_path_duration_ms="));
|
||||
let status = if matches!(profile.critical_path, TurnCriticalPath::Disabled) {
|
||||
"disabled"
|
||||
} else {
|
||||
"incomplete"
|
||||
};
|
||||
assert!(trace.contains(&format!("critical_path_status=\"{status}\"")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let snapshot = context.session_telemetry.snapshot_metrics().unwrap();
|
||||
let AggregatedMetrics::U64(MetricData::Sum(captures)) =
|
||||
find_metric(&snapshot, TURN_CRITICAL_PATH_CAPTURE_METRIC).data()
|
||||
else {
|
||||
panic!("expected capture counter");
|
||||
};
|
||||
let counts = captures
|
||||
.data_points()
|
||||
.map(|point| {
|
||||
let tags = attributes_to_map(point.attributes());
|
||||
(
|
||||
(tags["product_sku"].clone(), tags["capture_status"].clone()),
|
||||
point.value(),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
assert_eq!(
|
||||
counts,
|
||||
BTreeMap::from([
|
||||
(("codex".into(), "complete".into()), 1),
|
||||
(("unknown".into(), "incomplete".into()), 1),
|
||||
(("other".into(), "incomplete".into()), 1),
|
||||
])
|
||||
);
|
||||
|
||||
for (name, expected) in [
|
||||
(
|
||||
TURN_CRITICAL_PATH_DURATION_METRIC,
|
||||
BTreeMap::from([("total", 60.0)]),
|
||||
),
|
||||
(
|
||||
TURN_CRITICAL_PATH_COMPONENT_METRIC,
|
||||
BTreeMap::from([
|
||||
("inference", 31.0),
|
||||
("auto_review", 2.0),
|
||||
("tools", 10.0),
|
||||
("user_wait", 0.0),
|
||||
("overhead", 14.0),
|
||||
("unknown", 3.0),
|
||||
]),
|
||||
),
|
||||
] {
|
||||
let AggregatedMetrics::F64(MetricData::Histogram(histogram)) =
|
||||
find_metric(&snapshot, name).data()
|
||||
else {
|
||||
panic!("expected duration histogram");
|
||||
};
|
||||
assert_eq!(histogram.data_points().count(), expected.len());
|
||||
for point in histogram.data_points() {
|
||||
let tags = attributes_to_map(point.attributes());
|
||||
assert_eq!(tags["product_sku"], "codex");
|
||||
assert_eq!(
|
||||
point
|
||||
.bounds()
|
||||
.filter(|bound| *bound > 120_000.0)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
180_000.0,
|
||||
300_000.0,
|
||||
600_000.0,
|
||||
900_000.0,
|
||||
1_800_000.0,
|
||||
3_600_000.0,
|
||||
7_200_000.0
|
||||
]
|
||||
);
|
||||
let component = tags.get("component").map_or("total", String::as_str);
|
||||
assert_eq!((point.count(), point.sum()), (1, expected[component]));
|
||||
}
|
||||
}
|
||||
}
|
||||
175
akode-rs/core/src/tasks/regular.rs
Normal file
175
akode-rs/core/src/tasks/regular.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_async_utils::OrCancelExt;
|
||||
use akode_extension_api::TurnStartPhase;
|
||||
use akode_protocol::protocol::InternalSessionSource;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use futures::future::BoxFuture;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::client::ModelClientSession;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::startup_prewarm::SessionStartupPrewarmResolution;
|
||||
use crate::session::turn::McpStartupRequirements;
|
||||
use crate::session::turn::run_hooks_and_record_inputs;
|
||||
use crate::session::turn::run_turn;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::state::TaskKind;
|
||||
use akode_thread_store::PersistContext;
|
||||
use tracing::Instrument;
|
||||
use tracing::trace_span;
|
||||
|
||||
use super::SessionTask;
|
||||
use super::SessionTaskResult;
|
||||
|
||||
/// The last answer and the MCP requirements needed if a steer reopens sampling.
|
||||
pub(crate) struct RegularTaskOutput {
|
||||
pub(super) last_agent_message: Option<String>,
|
||||
pub(super) mcp_startup_requirements: McpStartupRequirements,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RegularTask;
|
||||
|
||||
impl RegularTask {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionTask for RegularTask {
|
||||
fn kind(&self) -> TaskKind {
|
||||
TaskKind::Regular
|
||||
}
|
||||
|
||||
fn span_name(&self) -> &'static str {
|
||||
"session_task.turn"
|
||||
}
|
||||
|
||||
async fn run(
|
||||
self: Arc<Self>,
|
||||
sess: Arc<Session>,
|
||||
ctx: Arc<TurnContext>,
|
||||
input: Vec<TurnInput>,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> SessionTaskResult {
|
||||
if ctx
|
||||
.config
|
||||
.features
|
||||
.enabled(akode_features::Feature::CriticalPathTiming)
|
||||
&& !matches!(
|
||||
ctx.session_source,
|
||||
SessionSource::Internal(InternalSessionSource::MemoryConsolidation)
|
||||
| SessionSource::SubAgent(SubAgentSource::MemoryConsolidation)
|
||||
)
|
||||
{
|
||||
ctx.turn_timing_state.enable_critical_path();
|
||||
}
|
||||
// Regular turns emit `TurnStarted` inline so first-turn lifecycle does
|
||||
// not wait on startup prewarm resolution.
|
||||
let prewarmed_client_session = async {
|
||||
sess.emit_turn_started(&ctx, TaskKind::Regular).await;
|
||||
// Regular-start contributors run once, after the task is visible and interruptible.
|
||||
let prepares_mcp = sess
|
||||
.services
|
||||
.extensions
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.any(|contributor| {
|
||||
contributor.turn_start_phase(&sess.services.thread_extension_data)
|
||||
== TurnStartPhase::RegularTaskStart
|
||||
&& contributor.requires_mcp_runtime(&sess.services.thread_extension_data)
|
||||
});
|
||||
let preparation = sess
|
||||
.emit_turn_start_lifecycle(
|
||||
&ctx,
|
||||
/*token_usage_at_turn_start*/ None,
|
||||
TurnStartPhase::RegularTaskStart,
|
||||
)
|
||||
.or_cancel(&cancellation_token)
|
||||
.await;
|
||||
// Even cancelled discovery may have cleared the previous account's catalog.
|
||||
if prepares_mcp {
|
||||
sess.request_mcp_runtime_reprojection();
|
||||
}
|
||||
if preparation.is_err() {
|
||||
return SessionStartupPrewarmResolution::Cancelled;
|
||||
}
|
||||
sess.consume_startup_prewarm_for_regular_turn(&cancellation_token)
|
||||
.await
|
||||
}
|
||||
.instrument(trace_span!("regular_task.prepare_run_turn"))
|
||||
.await;
|
||||
let prewarmed_client_session = match prewarmed_client_session {
|
||||
SessionStartupPrewarmResolution::Cancelled => {
|
||||
let _ = run_hooks_and_record_inputs(
|
||||
&sess,
|
||||
&ctx,
|
||||
&ctx.capture_current_model_info(),
|
||||
&input,
|
||||
PersistContext::Standard,
|
||||
)
|
||||
.await;
|
||||
return Ok(None);
|
||||
}
|
||||
SessionStartupPrewarmResolution::Unavailable { .. } => None,
|
||||
SessionStartupPrewarmResolution::Ready(prewarmed_client_session) => {
|
||||
Some(*prewarmed_client_session)
|
||||
}
|
||||
};
|
||||
Self::run_turns(
|
||||
sess,
|
||||
ctx,
|
||||
input,
|
||||
McpStartupRequirements::default(),
|
||||
prewarmed_client_session,
|
||||
cancellation_token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl RegularTask {
|
||||
/// Runs model requests for a regular turn, retaining explicit MCP requirements across steers.
|
||||
pub(super) fn run_turns(
|
||||
sess: Arc<Session>,
|
||||
ctx: Arc<TurnContext>,
|
||||
mut next_input: Vec<TurnInput>,
|
||||
mut mcp_startup_requirements: McpStartupRequirements,
|
||||
mut prewarmed_client_session: Option<ModelClientSession>,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> BoxFuture<'static, SessionTaskResult> {
|
||||
Box::pin(async move {
|
||||
let run_turn_span = trace_span!(
|
||||
"run_turn",
|
||||
conversation.id = %sess.thread_id,
|
||||
turn.id = %ctx.sub_id,
|
||||
);
|
||||
loop {
|
||||
let last_agent_message = run_turn(
|
||||
Arc::clone(&sess),
|
||||
Arc::clone(&ctx),
|
||||
next_input,
|
||||
&mut mcp_startup_requirements,
|
||||
prewarmed_client_session.take(),
|
||||
cancellation_token.child_token(),
|
||||
)
|
||||
.instrument(run_turn_span.clone())
|
||||
.await?;
|
||||
// Terminal errors are already reported. Let task completion preserve pending
|
||||
// input instead of restarting the failed turn for that same input.
|
||||
if ctx.terminal_error.lock().await.is_some()
|
||||
|| !sess.input_queue.has_pending_input(&sess.active_turn).await
|
||||
{
|
||||
return Ok(Some(RegularTaskOutput {
|
||||
last_agent_message,
|
||||
mcp_startup_requirements,
|
||||
}));
|
||||
}
|
||||
next_input = Vec::new();
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
285
akode-rs/core/src/tasks/review.rs
Normal file
285
akode-rs/core/src/tasks/review.rs
Normal file
@@ -0,0 +1,285 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_prompts::render_review_exit_interrupted;
|
||||
use akode_prompts::render_review_exit_success;
|
||||
use akode_protocol::config_types::WebSearchMode;
|
||||
use akode_protocol::items::ExitedReviewModeItem;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::models::BaseInstructionsProvenance;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::protocol::AgentMessageContentDeltaEvent;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::Event;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::ItemCompletedEvent;
|
||||
use akode_protocol::protocol::ReviewOutputEvent;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_protocol::review_format::format_review_findings_block;
|
||||
use akode_protocol::review_format::render_review_output_text;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::codex_delegate::run_codex_thread_one_shot;
|
||||
use crate::config::Constrained;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::state::TaskKind;
|
||||
use akode_features::Feature;
|
||||
use akode_protocol::user_input::UserInput;
|
||||
use akode_thread_store::PersistContext;
|
||||
|
||||
use super::SessionTask;
|
||||
use super::SessionTaskResult;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ReviewTask;
|
||||
|
||||
impl ReviewTask {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionTask for ReviewTask {
|
||||
fn kind(&self) -> TaskKind {
|
||||
TaskKind::Review
|
||||
}
|
||||
|
||||
fn span_name(&self) -> &'static str {
|
||||
"session_task.review"
|
||||
}
|
||||
|
||||
async fn run(
|
||||
self: Arc<Self>,
|
||||
session: Arc<Session>,
|
||||
ctx: Arc<TurnContext>,
|
||||
input: Vec<TurnInput>,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> SessionTaskResult {
|
||||
session
|
||||
.services
|
||||
.session_telemetry
|
||||
.counter("codex.task.review", /*inc*/ 1, &[]);
|
||||
|
||||
let mut user_input = Vec::new();
|
||||
for item in input {
|
||||
match item {
|
||||
TurnInput::UserInput { mut content, .. } => user_input.append(&mut content),
|
||||
TurnInput::ResponseItem(_)
|
||||
| TurnInput::FunctionCallOutput(_)
|
||||
| TurnInput::InterAgentCommunication(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Start sub-codex conversation and get the receiver for events.
|
||||
let output = match start_review_conversation(
|
||||
session.clone(),
|
||||
ctx.clone(),
|
||||
user_input,
|
||||
cancellation_token.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(receiver) => process_review_events(session.clone(), ctx.clone(), receiver).await,
|
||||
None => None,
|
||||
};
|
||||
if !cancellation_token.is_cancelled() {
|
||||
exit_review_mode(Arc::clone(&session), output.clone(), ctx.clone()).await;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn abort(&self, session: Arc<Session>, ctx: Arc<TurnContext>) {
|
||||
exit_review_mode(session, /*review_output*/ None, ctx).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_review_conversation(
|
||||
session: Arc<Session>,
|
||||
ctx: Arc<TurnContext>,
|
||||
input: Vec<UserInput>,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Option<async_channel::Receiver<Event>> {
|
||||
let config = ctx.config.clone();
|
||||
let mut sub_agent_config = config.as_ref().clone();
|
||||
// Carry over review-only feature restrictions so the delegate cannot
|
||||
// re-enable blocked tools (web search, collab tools, view image).
|
||||
if let Err(err) = sub_agent_config
|
||||
.web_search_mode
|
||||
.set(WebSearchMode::Disabled)
|
||||
{
|
||||
panic!("by construction Constrained<WebSearchMode> must always support Disabled: {err}");
|
||||
}
|
||||
let _ = sub_agent_config.features.disable(Feature::Collab);
|
||||
let _ = sub_agent_config.features.disable(Feature::MultiAgentV2);
|
||||
|
||||
// Set explicit review rubric for the sub-agent
|
||||
sub_agent_config.base_instructions = Some(crate::REVIEW_PROMPT.to_string());
|
||||
sub_agent_config.base_instructions_provenance = Some(BaseInstructionsProvenance::Custom);
|
||||
sub_agent_config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
|
||||
|
||||
let model = config
|
||||
.review_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| ctx.model_info().slug.clone());
|
||||
sub_agent_config.model = Some(model);
|
||||
(run_codex_thread_one_shot(
|
||||
sub_agent_config,
|
||||
Arc::clone(&session.services.auth_manager),
|
||||
Arc::clone(&session.services.models_manager),
|
||||
input,
|
||||
Arc::clone(&session),
|
||||
ctx.clone(),
|
||||
cancellation_token,
|
||||
SubAgentSource::Review,
|
||||
/*final_output_json_schema*/ None,
|
||||
/*initial_history*/ None,
|
||||
)
|
||||
.await)
|
||||
.ok()
|
||||
.map(|(_session, io)| io.rx_event)
|
||||
}
|
||||
|
||||
async fn process_review_events(
|
||||
session: Arc<Session>,
|
||||
ctx: Arc<TurnContext>,
|
||||
receiver: async_channel::Receiver<Event>,
|
||||
) -> Option<ReviewOutputEvent> {
|
||||
let mut prev_agent_message: Option<Event> = None;
|
||||
while let Ok(event) = receiver.recv().await {
|
||||
match event.clone().msg {
|
||||
EventMsg::AgentMessage(_) => {
|
||||
if let Some(prev) = prev_agent_message.take() {
|
||||
session.send_event(ctx.as_ref(), prev.msg).await;
|
||||
}
|
||||
prev_agent_message = Some(event);
|
||||
}
|
||||
// Suppress ItemCompleted only for assistant messages: forwarding it
|
||||
// would trigger legacy AgentMessage via as_legacy_events(), which this
|
||||
// review flow intentionally hides in favor of structured output.
|
||||
EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
item: TurnItem::AgentMessage(_),
|
||||
..
|
||||
})
|
||||
| EventMsg::AgentMessageContentDelta(AgentMessageContentDeltaEvent { .. }) => {}
|
||||
EventMsg::TurnComplete(task_complete) => {
|
||||
// Parse review output from the last agent message (if present).
|
||||
let out = task_complete
|
||||
.last_agent_message
|
||||
.as_deref()
|
||||
.map(parse_review_output_event);
|
||||
return out;
|
||||
}
|
||||
EventMsg::TurnAborted(_) => {
|
||||
// Cancellation or abort: consumer will finalize with None.
|
||||
return None;
|
||||
}
|
||||
other => {
|
||||
session.send_event(ctx.as_ref(), other).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Channel closed without TurnComplete: treat as interrupted.
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse a ReviewOutputEvent from a text blob returned by the reviewer model.
|
||||
/// If the text is valid JSON matching ReviewOutputEvent, deserialize it.
|
||||
/// Otherwise, attempt to extract the first JSON object substring and parse it.
|
||||
/// If parsing still fails, return a structured fallback carrying the plain text
|
||||
/// in `overall_explanation`.
|
||||
fn parse_review_output_event(text: &str) -> ReviewOutputEvent {
|
||||
if let Ok(ev) = serde_json::from_str::<ReviewOutputEvent>(text) {
|
||||
return ev;
|
||||
}
|
||||
if let (Some(start), Some(end)) = (text.find('{'), text.rfind('}'))
|
||||
&& start < end
|
||||
&& let Some(slice) = text.get(start..=end)
|
||||
&& let Ok(ev) = serde_json::from_str::<ReviewOutputEvent>(slice)
|
||||
{
|
||||
return ev;
|
||||
}
|
||||
ReviewOutputEvent {
|
||||
overall_explanation: text.to_string(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits ExitedReviewMode item lifecycle with optional ReviewOutput,
|
||||
/// and records the review output back into conversation history.
|
||||
pub(crate) async fn exit_review_mode(
|
||||
session: Arc<Session>,
|
||||
review_output: Option<ReviewOutputEvent>,
|
||||
ctx: Arc<TurnContext>,
|
||||
) {
|
||||
let (user_message, assistant_message) = if let Some(out) = review_output.clone() {
|
||||
let mut findings_str = String::new();
|
||||
let text = out.overall_explanation.trim();
|
||||
if !text.is_empty() {
|
||||
findings_str.push_str(text);
|
||||
}
|
||||
if !out.findings.is_empty() {
|
||||
let block = format_review_findings_block(&out.findings, /*selection*/ None);
|
||||
findings_str.push_str(&format!("\n{block}"));
|
||||
}
|
||||
let rendered = render_review_exit_success(&findings_str);
|
||||
let assistant_message = render_review_output_text(&out);
|
||||
(rendered, assistant_message)
|
||||
} else {
|
||||
let rendered = render_review_exit_interrupted();
|
||||
let assistant_message =
|
||||
"Review was interrupted. Please re-run /review and wait for it to complete."
|
||||
.to_string();
|
||||
(rendered, assistant_message)
|
||||
};
|
||||
|
||||
session
|
||||
.record_conversation_items(
|
||||
&ctx,
|
||||
ctx.model_info(),
|
||||
&[ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: Some((session.item_id_generator)("msg")),
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText { text: user_message }],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
|
||||
let item = TurnItem::ExitedReviewMode(ExitedReviewModeItem {
|
||||
id: uuid::Uuid::now_v7().to_string(),
|
||||
review_output,
|
||||
});
|
||||
session.emit_turn_item_started(ctx.as_ref(), &item).await;
|
||||
session.emit_turn_item_completed(ctx.as_ref(), item).await;
|
||||
session
|
||||
.record_response_item_and_emit_turn_item(
|
||||
ctx.as_ref(),
|
||||
ctx.model_info(),
|
||||
ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: Some((session.item_id_generator)("msg")),
|
||||
role: "assistant".to_string(),
|
||||
content: vec![ContentItem::OutputText {
|
||||
annotations: None,
|
||||
logprobs: None,
|
||||
text: assistant_message,
|
||||
}],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// Review turns can run before any regular user turn, so explicitly
|
||||
// materialize rollout persistence. Do this after emitting review output so
|
||||
// file creation + git metadata collection cannot delay client-facing items.
|
||||
session
|
||||
.ensure_rollout_materialized(PersistContext::Standard)
|
||||
.await;
|
||||
}
|
||||
473
akode-rs/core/src/tasks/user_shell.rs
Normal file
473
akode-rs/core/src/tasks/user_shell.rs
Normal file
@@ -0,0 +1,473 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_async_utils::CancelErr;
|
||||
use akode_async_utils::OrCancelExt;
|
||||
use akode_network_proxy::PROXY_ACTIVE_ENV_KEY;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::error;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::exec::ExecCapturePolicy;
|
||||
use crate::exec::StdoutStream;
|
||||
use crate::exec::execute_exec_request;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::exec_env::inject_apply_patch_env;
|
||||
use crate::exec_env::inject_session_env;
|
||||
use crate::sandboxing::ExecRequest;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::shell::Shell;
|
||||
use crate::state::TaskKind;
|
||||
use crate::tools::runtimes::RuntimePathPrepends;
|
||||
#[cfg(unix)]
|
||||
use crate::tools::runtimes::apply_package_path_prepend;
|
||||
use crate::tools::runtimes::maybe_wrap_shell_lc_with_snapshot;
|
||||
use crate::tools::runtimes::strip_managed_proxy_env;
|
||||
use crate::user_shell_command::user_shell_command_record_item;
|
||||
use akode_protocol::exec_output::ExecToolCallOutput;
|
||||
use akode_protocol::exec_output::StreamOutput;
|
||||
use akode_protocol::items::CommandExecutionItem;
|
||||
use akode_protocol::items::CommandExecutionStatus;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::protocol::ErrorEvent;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::ExecCommandSource;
|
||||
use akode_sandboxing::SandboxType;
|
||||
use akode_shell_command::parse_command::parse_command;
|
||||
use akode_thread_store::PersistContext;
|
||||
|
||||
use super::SessionTask;
|
||||
use super::SessionTaskResult;
|
||||
use crate::session::session::Session;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
|
||||
const USER_SHELL_TIMEOUT_MS: u64 = 60 * 60 * 1000; // 1 hour
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum UserShellCommandMode {
|
||||
/// Executes as an independent turn lifecycle (emits TurnStarted/TurnComplete
|
||||
/// via task lifecycle plumbing).
|
||||
StandaloneTurn,
|
||||
/// Executes while another turn is already active. This mode must not emit a
|
||||
/// second TurnStarted/TurnComplete pair for the same active turn.
|
||||
ActiveTurnAuxiliary,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct UserShellCommandTask {
|
||||
command: String,
|
||||
timeout_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl UserShellCommandTask {
|
||||
pub(crate) fn new(command: String, timeout_ms: Option<u64>) -> Self {
|
||||
Self {
|
||||
command,
|
||||
timeout_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionTask for UserShellCommandTask {
|
||||
fn kind(&self) -> TaskKind {
|
||||
TaskKind::Regular
|
||||
}
|
||||
|
||||
fn span_name(&self) -> &'static str {
|
||||
"session_task.user_shell"
|
||||
}
|
||||
|
||||
async fn run(
|
||||
self: Arc<Self>,
|
||||
session: Arc<Session>,
|
||||
turn_context: Arc<TurnContext>,
|
||||
_input: Vec<TurnInput>,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> SessionTaskResult {
|
||||
execute_user_shell_command(
|
||||
session,
|
||||
turn_context,
|
||||
self.command.clone(),
|
||||
self.timeout_ms,
|
||||
cancellation_token,
|
||||
UserShellCommandMode::StandaloneTurn,
|
||||
)
|
||||
.await;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_user_shell_command(
|
||||
session: Arc<Session>,
|
||||
turn_context: Arc<TurnContext>,
|
||||
command: String,
|
||||
timeout_ms: Option<u64>,
|
||||
cancellation_token: CancellationToken,
|
||||
mode: UserShellCommandMode,
|
||||
) {
|
||||
session
|
||||
.services
|
||||
.session_telemetry
|
||||
.counter("codex.task.user_shell", /*inc*/ 1, &[]);
|
||||
|
||||
if mode == UserShellCommandMode::StandaloneTurn {
|
||||
// Auxiliary mode runs within an existing active turn. That turn already
|
||||
// emitted TurnStarted, so emitting another TurnStarted here would create
|
||||
// duplicate turn lifecycle events and confuse clients.
|
||||
// TODO(ccunningham): After TurnStarted, emit model-visible turn context diffs for
|
||||
// standalone lifecycle tasks (for example /shell, and review once it emits TurnStarted).
|
||||
// `/compact` is an intentional exception because compaction requests should not include
|
||||
// freshly reinjected context before the summary/replacement history is applied.
|
||||
session
|
||||
.emit_turn_started(&turn_context, TaskKind::Regular)
|
||||
.await;
|
||||
}
|
||||
|
||||
let Some((turn_environment, environment_shell)) = turn_context
|
||||
.initial_environments
|
||||
.local()
|
||||
.and_then(|environment| environment.shell.as_ref().map(|shell| (environment, shell)))
|
||||
else {
|
||||
send_user_shell_error(
|
||||
&session,
|
||||
turn_context.as_ref(),
|
||||
"shell is unavailable in this session",
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
};
|
||||
|
||||
// Execute the user's script under the environment's shell; this
|
||||
// allows commands that use shell features (pipes, &&, redirects, etc.).
|
||||
// We do not source rc files or otherwise reformat the script.
|
||||
let use_login_shell = true;
|
||||
let display_command = environment_shell.derive_exec_args(&command, use_login_shell);
|
||||
// TODO(anp): Migrate user-shell events and execution plumbing to PathUri so this local-only
|
||||
// feature does not need to project the selected environment cwd onto the Codex host.
|
||||
let Ok(cwd) = turn_environment.cwd().to_abs_path() else {
|
||||
send_user_shell_error(
|
||||
&session,
|
||||
turn_context.as_ref(),
|
||||
"shell working directory is not native to the Codex host",
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
};
|
||||
let shell_snapshot = turn_environment
|
||||
.shell_snapshot(
|
||||
&cwd,
|
||||
&display_command,
|
||||
environment_shell,
|
||||
&turn_context.config,
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await;
|
||||
let shell_snapshot_location = shell_snapshot.as_ref().map(|snapshot| snapshot.path());
|
||||
let shell_environment_policy = turn_environment.shell_environment_policy();
|
||||
let mut exec_env_map = create_env(shell_environment_policy, Some(session.thread_id));
|
||||
inject_session_env(&mut exec_env_map, session.session_id());
|
||||
inject_apply_patch_env(&mut exec_env_map);
|
||||
if exec_env_map.contains_key(PROXY_ACTIVE_ENV_KEY) {
|
||||
strip_managed_proxy_env(&mut exec_env_map);
|
||||
}
|
||||
let exec_command = prepare_user_shell_exec_command(
|
||||
&display_command,
|
||||
environment_shell,
|
||||
shell_snapshot_location.as_ref(),
|
||||
&shell_environment_policy.r#set,
|
||||
&mut exec_env_map,
|
||||
);
|
||||
|
||||
let call_id = Uuid::new_v4().to_string();
|
||||
let raw_command = command;
|
||||
|
||||
let parsed_cmd = parse_command(&display_command);
|
||||
session
|
||||
.emit_turn_item_started(
|
||||
turn_context.as_ref(),
|
||||
&TurnItem::CommandExecution(CommandExecutionItem {
|
||||
model_context: None,
|
||||
sandbox_type: None,
|
||||
id: call_id.clone(),
|
||||
plugin_id: None,
|
||||
script_path: None,
|
||||
process_id: None,
|
||||
command: display_command.clone(),
|
||||
cwd: cwd.clone().into(),
|
||||
parsed_cmd: parsed_cmd.clone(),
|
||||
source: ExecCommandSource::UserShell,
|
||||
interaction_input: None,
|
||||
status: CommandExecutionStatus::InProgress,
|
||||
aggregated_output: None,
|
||||
exit_code: None,
|
||||
duration: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let permission_profile = PermissionProfile::Disabled;
|
||||
let exec_env = ExecRequest {
|
||||
command: exec_command.clone(),
|
||||
cwd: cwd.clone().into(),
|
||||
env: exec_env_map,
|
||||
exec_server_env_config: None,
|
||||
exec_server_shell_snapshot: None,
|
||||
// `/shell` is the explicit full-access escape hatch, so it must not
|
||||
// inherit a managed proxy from the surrounding session or turn.
|
||||
network: None,
|
||||
network_environment_id: None,
|
||||
expiration: timeout_ms.unwrap_or(USER_SHELL_TIMEOUT_MS).into(),
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
sandbox: SandboxType::None,
|
||||
windows_sandbox_policy_cwd: cwd.clone().into(),
|
||||
windows_sandbox_workspace_roots: Vec::new(),
|
||||
windows_sandbox_level: turn_context.windows_sandbox_level,
|
||||
permission_profile,
|
||||
windows_sandbox_filesystem_overrides: None,
|
||||
arg0: None,
|
||||
exec_server_sandbox: None,
|
||||
exec_server_enforce_managed_network: false,
|
||||
exec_server_managed_network: None,
|
||||
exec_server_network_proxy: None,
|
||||
};
|
||||
|
||||
let stdout_stream = Some(StdoutStream {
|
||||
sub_id: turn_context.sub_id.clone(),
|
||||
call_id: call_id.clone(),
|
||||
tx_event: session.get_tx_event(),
|
||||
});
|
||||
|
||||
let exec_result = execute_exec_request(exec_env, stdout_stream, /*after_spawn*/ None)
|
||||
.or_cancel(&cancellation_token)
|
||||
.await;
|
||||
|
||||
match exec_result {
|
||||
Err(CancelErr::Cancelled) => {
|
||||
let aborted_message = "command aborted by user".to_string();
|
||||
let exec_output = ExecToolCallOutput {
|
||||
exit_code: -1,
|
||||
stdout: StreamOutput::new(String::new()),
|
||||
stderr: StreamOutput::new(aborted_message.clone()),
|
||||
aggregated_output: StreamOutput::new(aborted_message.clone()),
|
||||
duration: Duration::ZERO,
|
||||
timed_out: false,
|
||||
};
|
||||
persist_user_shell_output(
|
||||
&session,
|
||||
turn_context.as_ref(),
|
||||
&raw_command,
|
||||
&exec_output,
|
||||
mode,
|
||||
)
|
||||
.await;
|
||||
session
|
||||
.emit_turn_item_completed(
|
||||
turn_context.as_ref(),
|
||||
TurnItem::CommandExecution(CommandExecutionItem {
|
||||
model_context: None,
|
||||
sandbox_type: None,
|
||||
id: call_id,
|
||||
plugin_id: None,
|
||||
script_path: None,
|
||||
process_id: None,
|
||||
command: display_command.clone(),
|
||||
cwd: cwd.clone().into(),
|
||||
parsed_cmd: parsed_cmd.clone(),
|
||||
source: ExecCommandSource::UserShell,
|
||||
interaction_input: None,
|
||||
status: CommandExecutionStatus::Failed,
|
||||
aggregated_output: Some(aborted_message.clone()),
|
||||
exit_code: Some(-1),
|
||||
duration: Some(Duration::ZERO),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Ok(Ok(output)) => {
|
||||
session
|
||||
.emit_turn_item_completed(
|
||||
turn_context.as_ref(),
|
||||
TurnItem::CommandExecution(CommandExecutionItem {
|
||||
model_context: None,
|
||||
sandbox_type: Some(SandboxType::None),
|
||||
id: call_id.clone(),
|
||||
plugin_id: None,
|
||||
script_path: None,
|
||||
process_id: None,
|
||||
command: display_command.clone(),
|
||||
cwd: cwd.clone().into(),
|
||||
parsed_cmd: parsed_cmd.clone(),
|
||||
source: ExecCommandSource::UserShell,
|
||||
interaction_input: None,
|
||||
status: if output.exit_code == 0 {
|
||||
CommandExecutionStatus::Completed
|
||||
} else {
|
||||
CommandExecutionStatus::Failed
|
||||
},
|
||||
aggregated_output: Some(output.aggregated_output.text.clone()),
|
||||
exit_code: Some(output.exit_code),
|
||||
duration: Some(output.duration),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
persist_user_shell_output(&session, turn_context.as_ref(), &raw_command, &output, mode)
|
||||
.await;
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
error!("user shell command failed: {err:?}");
|
||||
let message = format!("execution error: {err:?}");
|
||||
let exec_output = ExecToolCallOutput {
|
||||
exit_code: -1,
|
||||
stdout: StreamOutput::new(String::new()),
|
||||
stderr: StreamOutput::new(message.clone()),
|
||||
aggregated_output: StreamOutput::new(message.clone()),
|
||||
duration: Duration::ZERO,
|
||||
timed_out: false,
|
||||
};
|
||||
session
|
||||
.emit_turn_item_completed(
|
||||
turn_context.as_ref(),
|
||||
TurnItem::CommandExecution(CommandExecutionItem {
|
||||
model_context: None,
|
||||
sandbox_type: None,
|
||||
id: call_id,
|
||||
plugin_id: None,
|
||||
script_path: None,
|
||||
process_id: None,
|
||||
command: display_command,
|
||||
cwd: cwd.into(),
|
||||
parsed_cmd,
|
||||
source: ExecCommandSource::UserShell,
|
||||
interaction_input: None,
|
||||
status: CommandExecutionStatus::Failed,
|
||||
aggregated_output: Some(exec_output.aggregated_output.text.clone()),
|
||||
exit_code: Some(exec_output.exit_code),
|
||||
duration: Some(exec_output.duration),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
persist_user_shell_output(
|
||||
&session,
|
||||
turn_context.as_ref(),
|
||||
&raw_command,
|
||||
&exec_output,
|
||||
mode,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_user_shell_error(session: &Session, turn_context: &TurnContext, message: &str) {
|
||||
session
|
||||
.send_event(
|
||||
turn_context,
|
||||
EventMsg::Error(ErrorEvent {
|
||||
misalignment: None,
|
||||
message: message.to_string(),
|
||||
codex_error_info: None,
|
||||
rejected_audio_file_ids: Vec::new(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn prepare_user_shell_exec_command(
|
||||
display_command: &[String],
|
||||
shell: &Shell,
|
||||
shell_snapshot: Option<&AbsolutePathBuf>,
|
||||
shell_environment_set: &HashMap<String, String>,
|
||||
exec_env_map: &mut HashMap<String, String>,
|
||||
) -> Vec<String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
prepare_user_shell_exec_command_with_path_prepend(
|
||||
display_command,
|
||||
shell,
|
||||
shell_snapshot,
|
||||
shell_environment_set,
|
||||
exec_env_map,
|
||||
apply_package_path_prepend,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
maybe_wrap_shell_lc_with_snapshot(
|
||||
display_command,
|
||||
shell,
|
||||
shell_snapshot,
|
||||
shell_environment_set,
|
||||
exec_env_map,
|
||||
// On non-Unix targets, arg0 has already prepended the package path
|
||||
// to the process PATH before create_env() builds exec_env_map.
|
||||
// RuntimePathPrepends is only needed for Unix shell snapshot replay.
|
||||
&RuntimePathPrepends::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepares a user-shell command after adding runtime-owned PATH entries.
|
||||
///
|
||||
/// The callback mutates the live exec environment for commands that are not
|
||||
/// wrapped with a shell snapshot and records only the runtime-owned entries so
|
||||
/// snapshot wrapping can reapply them after restoring the user's snapshot PATH.
|
||||
#[cfg(unix)]
|
||||
fn prepare_user_shell_exec_command_with_path_prepend(
|
||||
display_command: &[String],
|
||||
shell: &Shell,
|
||||
shell_snapshot: Option<&AbsolutePathBuf>,
|
||||
shell_environment_set: &HashMap<String, String>,
|
||||
exec_env_map: &mut HashMap<String, String>,
|
||||
prepend_runtime_path: impl FnOnce(&mut HashMap<String, String>, &mut RuntimePathPrepends),
|
||||
) -> Vec<String> {
|
||||
let explicit_env_overrides = shell_environment_set.clone();
|
||||
let mut runtime_path_prepends = RuntimePathPrepends::default();
|
||||
prepend_runtime_path(exec_env_map, &mut runtime_path_prepends);
|
||||
maybe_wrap_shell_lc_with_snapshot(
|
||||
display_command,
|
||||
shell,
|
||||
shell_snapshot,
|
||||
&explicit_env_overrides,
|
||||
exec_env_map,
|
||||
&runtime_path_prepends,
|
||||
)
|
||||
}
|
||||
|
||||
async fn persist_user_shell_output(
|
||||
session: &Session,
|
||||
turn_context: &TurnContext,
|
||||
raw_command: &str,
|
||||
exec_output: &ExecToolCallOutput,
|
||||
mode: UserShellCommandMode,
|
||||
) {
|
||||
let output_item = user_shell_command_record_item(raw_command, exec_output, turn_context);
|
||||
|
||||
if mode == UserShellCommandMode::StandaloneTurn {
|
||||
session
|
||||
.record_conversation_items(
|
||||
turn_context,
|
||||
turn_context.model_info(),
|
||||
std::slice::from_ref(&output_item),
|
||||
)
|
||||
.await;
|
||||
// Standalone shell turns can run before any regular user turn, so
|
||||
// explicitly materialize rollout persistence after recording output.
|
||||
session
|
||||
.ensure_rollout_materialized(PersistContext::Standard)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
|
||||
session
|
||||
.inject_no_new_turn(vec![output_item], Some(turn_context))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "user_shell_tests.rs"]
|
||||
mod tests;
|
||||
62
akode-rs/core/src/tasks/user_shell_tests.rs
Normal file
62
akode-rs/core/src/tasks/user_shell_tests.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
use super::*;
|
||||
use crate::shell::Shell;
|
||||
use crate::shell::ShellType;
|
||||
use core_test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
fn shell_with_snapshot(
|
||||
shell_type: ShellType,
|
||||
shell_path: &str,
|
||||
snapshot_path: AbsolutePathBuf,
|
||||
) -> (Shell, AbsolutePathBuf) {
|
||||
(
|
||||
Shell {
|
||||
shell_type,
|
||||
shell_path: PathBuf::from(shell_path),
|
||||
},
|
||||
snapshot_path,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_shell_snapshot_preserves_package_path_prepend() {
|
||||
let dir = tempfile::tempdir().expect("create temp dir");
|
||||
let snapshot_path = dir.path().join("snapshot.sh");
|
||||
std::fs::write(
|
||||
&snapshot_path,
|
||||
"# Snapshot file\nexport PATH='/snapshot/bin'\n",
|
||||
)
|
||||
.expect("write snapshot");
|
||||
let (session_shell, shell_snapshot) =
|
||||
shell_with_snapshot(ShellType::Bash, "/bin/bash", snapshot_path.abs());
|
||||
let command = vec![
|
||||
"/bin/bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"printf '%s' \"$PATH\"".to_string(),
|
||||
];
|
||||
let package_path_dir = dir.path().join("codex-path");
|
||||
let mut env = HashMap::from([("PATH".to_string(), "/worktree/bin".to_string())]);
|
||||
let rewritten = prepare_user_shell_exec_command_with_path_prepend(
|
||||
&command,
|
||||
&session_shell,
|
||||
Some(&shell_snapshot),
|
||||
&HashMap::new(),
|
||||
&mut env,
|
||||
|env, runtime_path_prepends| {
|
||||
runtime_path_prepends.prepend(env, package_path_dir.as_path());
|
||||
},
|
||||
);
|
||||
let output = Command::new(&rewritten[0])
|
||||
.args(&rewritten[1..])
|
||||
.env("PATH", env.get("PATH").expect("PATH should be set"))
|
||||
.output()
|
||||
.expect("run rewritten command");
|
||||
|
||||
assert!(output.status.success(), "command failed: {output:?}");
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
format!("{}:/snapshot/bin", package_path_dir.display())
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user