mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
Add StopFailure hook recovery
This commit is contained in:
@@ -1119,6 +1119,7 @@ fn analytics_hook_event_name(event_name: HookEventName) -> &'static str {
|
||||
HookEventName::SubagentStart => "SubagentStart",
|
||||
HookEventName::SubagentStop => "SubagentStop",
|
||||
HookEventName::Stop => "Stop",
|
||||
HookEventName::StopFailure => "StopFailure",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1993,7 +1993,8 @@
|
||||
"userPromptSubmit",
|
||||
"subagentStart",
|
||||
"subagentStop",
|
||||
"stop"
|
||||
"stop",
|
||||
"stopFailure"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
+9
-1
@@ -10649,7 +10649,8 @@
|
||||
"userPromptSubmit",
|
||||
"subagentStart",
|
||||
"subagentStop",
|
||||
"stop"
|
||||
"stop",
|
||||
"stopFailure"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
@@ -11548,6 +11549,12 @@
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"StopFailure": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ConfiguredHookMatcherGroup"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"SubagentStart": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ConfiguredHookMatcherGroup"
|
||||
@@ -11587,6 +11594,7 @@
|
||||
"PreToolUse",
|
||||
"SessionStart",
|
||||
"Stop",
|
||||
"StopFailure",
|
||||
"SubagentStart",
|
||||
"SubagentStop",
|
||||
"UserPromptSubmit"
|
||||
|
||||
+9
-1
@@ -7053,7 +7053,8 @@
|
||||
"userPromptSubmit",
|
||||
"subagentStart",
|
||||
"subagentStop",
|
||||
"stop"
|
||||
"stop",
|
||||
"stopFailure"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
@@ -8001,6 +8002,12 @@
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"StopFailure": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"SubagentStart": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
|
||||
@@ -8040,6 +8047,7 @@
|
||||
"PreToolUse",
|
||||
"SessionStart",
|
||||
"Stop",
|
||||
"StopFailure",
|
||||
"SubagentStart",
|
||||
"SubagentStop",
|
||||
"UserPromptSubmit"
|
||||
|
||||
+7
@@ -318,6 +318,12 @@
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"StopFailure": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"SubagentStart": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ConfiguredHookMatcherGroup"
|
||||
@@ -357,6 +363,7 @@
|
||||
"PreToolUse",
|
||||
"SessionStart",
|
||||
"Stop",
|
||||
"StopFailure",
|
||||
"SubagentStart",
|
||||
"SubagentStop",
|
||||
"UserPromptSubmit"
|
||||
|
||||
+2
-1
@@ -16,7 +16,8 @@
|
||||
"userPromptSubmit",
|
||||
"subagentStart",
|
||||
"subagentStop",
|
||||
"stop"
|
||||
"stop",
|
||||
"stopFailure"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
"userPromptSubmit",
|
||||
"subagentStart",
|
||||
"subagentStop",
|
||||
"stop"
|
||||
"stop",
|
||||
"stopFailure"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -31,7 +31,8 @@
|
||||
"userPromptSubmit",
|
||||
"subagentStart",
|
||||
"subagentStop",
|
||||
"stop"
|
||||
"stop",
|
||||
"stopFailure"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -119,7 +119,8 @@
|
||||
"userPromptSubmit",
|
||||
"subagentStart",
|
||||
"subagentStop",
|
||||
"stop"
|
||||
"stop",
|
||||
"stopFailure"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "preCompact" | "postCompact" | "sessionStart" | "userPromptSubmit" | "subagentStart" | "subagentStop" | "stop";
|
||||
export type HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "preCompact" | "postCompact" | "sessionStart" | "userPromptSubmit" | "subagentStart" | "subagentStop" | "stop" | "stopFailure";
|
||||
|
||||
+1
-1
@@ -3,4 +3,4 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ConfiguredHookMatcherGroup } from "./ConfiguredHookMatcherGroup";
|
||||
|
||||
export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array<ConfiguredHookMatcherGroup>, PermissionRequest: Array<ConfiguredHookMatcherGroup>, PostToolUse: Array<ConfiguredHookMatcherGroup>, PreCompact: Array<ConfiguredHookMatcherGroup>, PostCompact: Array<ConfiguredHookMatcherGroup>, SessionStart: Array<ConfiguredHookMatcherGroup>, UserPromptSubmit: Array<ConfiguredHookMatcherGroup>, SubagentStart: Array<ConfiguredHookMatcherGroup>, SubagentStop: Array<ConfiguredHookMatcherGroup>, Stop: Array<ConfiguredHookMatcherGroup>, };
|
||||
export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array<ConfiguredHookMatcherGroup>, PermissionRequest: Array<ConfiguredHookMatcherGroup>, PostToolUse: Array<ConfiguredHookMatcherGroup>, PreCompact: Array<ConfiguredHookMatcherGroup>, PostCompact: Array<ConfiguredHookMatcherGroup>, SessionStart: Array<ConfiguredHookMatcherGroup>, UserPromptSubmit: Array<ConfiguredHookMatcherGroup>, SubagentStart: Array<ConfiguredHookMatcherGroup>, SubagentStop: Array<ConfiguredHookMatcherGroup>, Stop: Array<ConfiguredHookMatcherGroup>, StopFailure: Array<ConfiguredHookMatcherGroup>, };
|
||||
|
||||
@@ -434,6 +434,9 @@ pub struct ManagedHooksRequirements {
|
||||
#[serde(rename = "Stop")]
|
||||
#[ts(rename = "Stop")]
|
||||
pub stop: Vec<ConfiguredHookMatcherGroup>,
|
||||
#[serde(rename = "StopFailure")]
|
||||
#[ts(rename = "StopFailure")]
|
||||
pub stop_failure: Vec<ConfiguredHookMatcherGroup>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
|
||||
@@ -17,7 +17,7 @@ use ts_rs::TS;
|
||||
|
||||
v2_enum_from_core!(
|
||||
pub enum HookEventName from CoreHookEventName {
|
||||
PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, UserPromptSubmit, SubagentStart, SubagentStop, Stop
|
||||
PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, UserPromptSubmit, SubagentStart, SubagentStop, Stop, StopFailure
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -404,6 +404,7 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed
|
||||
subagent_start,
|
||||
subagent_stop,
|
||||
stop,
|
||||
stop_failure,
|
||||
} = hooks;
|
||||
|
||||
ManagedHooksRequirements {
|
||||
@@ -419,6 +420,7 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed
|
||||
subagent_start: map_hook_matcher_groups_to_api(subagent_start),
|
||||
subagent_stop: map_hook_matcher_groups_to_api(subagent_stop),
|
||||
stop: map_hook_matcher_groups_to_api(stop),
|
||||
stop_failure: map_hook_matcher_groups_to_api(stop_failure),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ pub struct HookEventsToml {
|
||||
pub subagent_stop: Vec<MatcherGroup>,
|
||||
#[serde(rename = "Stop", default)]
|
||||
pub stop: Vec<MatcherGroup>,
|
||||
#[serde(rename = "StopFailure", default)]
|
||||
pub stop_failure: Vec<MatcherGroup>,
|
||||
}
|
||||
|
||||
impl HookEventsToml {
|
||||
@@ -67,6 +69,7 @@ impl HookEventsToml {
|
||||
subagent_start,
|
||||
subagent_stop,
|
||||
stop,
|
||||
stop_failure,
|
||||
} = self;
|
||||
pre_tool_use.is_empty()
|
||||
&& permission_request.is_empty()
|
||||
@@ -78,6 +81,7 @@ impl HookEventsToml {
|
||||
&& subagent_start.is_empty()
|
||||
&& subagent_stop.is_empty()
|
||||
&& stop.is_empty()
|
||||
&& stop_failure.is_empty()
|
||||
}
|
||||
|
||||
pub fn handler_count(&self) -> usize {
|
||||
@@ -92,6 +96,7 @@ impl HookEventsToml {
|
||||
subagent_start,
|
||||
subagent_stop,
|
||||
stop,
|
||||
stop_failure,
|
||||
} = self;
|
||||
[
|
||||
pre_tool_use,
|
||||
@@ -104,6 +109,7 @@ impl HookEventsToml {
|
||||
subagent_start,
|
||||
subagent_stop,
|
||||
stop,
|
||||
stop_failure,
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -111,7 +117,7 @@ impl HookEventsToml {
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn into_matcher_groups(self) -> [(HookEventName, Vec<MatcherGroup>); 10] {
|
||||
pub fn into_matcher_groups(self) -> [(HookEventName, Vec<MatcherGroup>); 11] {
|
||||
[
|
||||
(HookEventName::PreToolUse, self.pre_tool_use),
|
||||
(HookEventName::PermissionRequest, self.permission_request),
|
||||
@@ -123,6 +129,7 @@ impl HookEventsToml {
|
||||
(HookEventName::SubagentStart, self.subagent_start),
|
||||
(HookEventName::SubagentStop, self.subagent_stop),
|
||||
(HookEventName::Stop, self.stop),
|
||||
(HookEventName::StopFailure, self.stop_failure),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +214,7 @@ fn append_hook_events(existing: &mut HookEventsToml, incoming: HookEventsToml) -
|
||||
subagent_start,
|
||||
subagent_stop,
|
||||
stop,
|
||||
stop_failure,
|
||||
} = incoming;
|
||||
|
||||
let mut changed = false;
|
||||
@@ -227,6 +228,7 @@ fn append_hook_events(existing: &mut HookEventsToml, incoming: HookEventsToml) -
|
||||
changed |= append_vec(&mut existing.subagent_start, subagent_start);
|
||||
changed |= append_vec(&mut existing.subagent_stop, subagent_stop);
|
||||
changed |= append_vec(&mut existing.stop, stop);
|
||||
changed |= append_vec(&mut existing.stop_failure, stop_failure);
|
||||
changed
|
||||
}
|
||||
|
||||
|
||||
@@ -1187,6 +1187,13 @@
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"StopFailure": {
|
||||
"default": [],
|
||||
"items": {
|
||||
"$ref": "#/definitions/MatcherGroup"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"SubagentStart": {
|
||||
"default": [],
|
||||
"items": {
|
||||
@@ -5280,4 +5287,4 @@
|
||||
},
|
||||
"title": "ConfigToml",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,9 @@ use codex_hooks::PreToolUseOutcome;
|
||||
use codex_hooks::PreToolUseRequest;
|
||||
use codex_hooks::SessionStartOutcome;
|
||||
use codex_hooks::StartHookTarget;
|
||||
use codex_hooks::StopFailureError;
|
||||
use codex_hooks::StopFailureOutcome;
|
||||
use codex_hooks::StopFailureRequest;
|
||||
use codex_hooks::StopHookTarget;
|
||||
use codex_hooks::StopOutcome;
|
||||
use codex_hooks::SubagentHookContext;
|
||||
@@ -21,6 +24,7 @@ use codex_hooks::UserPromptSubmitOutcome;
|
||||
use codex_hooks::UserPromptSubmitRequest;
|
||||
use codex_otel::HOOK_RUN_DURATION_METRIC;
|
||||
use codex_otel::HOOK_RUN_METRIC;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::items::UserMessageItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
@@ -365,6 +369,43 @@ pub(crate) async fn run_turn_stop_hooks(
|
||||
outcome
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
pub(crate) async fn run_turn_stop_failure_hooks(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
error: &CodexErr,
|
||||
error_kind: StopFailureError,
|
||||
last_assistant_message: Option<String>,
|
||||
) -> StopFailureOutcome {
|
||||
if matches!(
|
||||
&turn_context.session_source,
|
||||
SessionSource::SubAgent(source)
|
||||
if !matches!(source, SubAgentSource::ThreadSpawn { .. })
|
||||
) {
|
||||
return StopFailureOutcome::default();
|
||||
}
|
||||
|
||||
let error_message = error.to_string();
|
||||
let request = StopFailureRequest {
|
||||
session_id: sess.session_id().into(),
|
||||
turn_id: turn_context.sub_id.clone(),
|
||||
#[allow(deprecated)]
|
||||
cwd: turn_context.cwd.clone(),
|
||||
transcript_path: sess.hook_transcript_path().await,
|
||||
model: turn_context.model_info.slug.clone(),
|
||||
permission_mode: hook_permission_mode(turn_context),
|
||||
error: error_kind,
|
||||
error_details: Some(error_message.clone()),
|
||||
last_assistant_message,
|
||||
};
|
||||
let hooks = sess.hooks();
|
||||
emit_hook_started_events(sess, turn_context, hooks.preview_stop_failure(&request)).await;
|
||||
|
||||
let mut outcome = hooks.run_stop_failure(request).await;
|
||||
emit_hook_completed_events(sess, turn_context, std::mem::take(&mut outcome.hook_events)).await;
|
||||
outcome
|
||||
}
|
||||
|
||||
pub(crate) async fn run_pre_compact_hooks(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
@@ -706,6 +747,7 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str);
|
||||
HookEventName::SubagentStart => "SubagentStart",
|
||||
HookEventName::SubagentStop => "SubagentStop",
|
||||
HookEventName::Stop => "Stop",
|
||||
HookEventName::StopFailure => "StopFailure",
|
||||
};
|
||||
let hook_source = match run.source {
|
||||
HookSource::System => "system",
|
||||
|
||||
@@ -23,6 +23,7 @@ use crate::hook_runtime::record_additional_contexts;
|
||||
use crate::hook_runtime::record_pending_input;
|
||||
use crate::hook_runtime::run_legacy_after_agent_hook;
|
||||
use crate::hook_runtime::run_pending_session_start_hooks;
|
||||
use crate::hook_runtime::run_turn_stop_failure_hooks;
|
||||
use crate::hook_runtime::run_turn_stop_hooks;
|
||||
use crate::injection::ToolMentionKind;
|
||||
use crate::injection::app_id_from_path;
|
||||
@@ -76,6 +77,9 @@ use codex_extension_api::TurnInputContext;
|
||||
use codex_extension_api::TurnInputEnvironment;
|
||||
use codex_features::Feature;
|
||||
use codex_git_utils::get_git_repo_root_with_fs;
|
||||
use codex_hooks::StopFailureError;
|
||||
use codex_hooks::StopFailureModelSelector;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_protocol::config_types::AutoCompactTokenLimitScope;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::ServiceTier;
|
||||
@@ -136,7 +140,7 @@ use tracing::warn;
|
||||
///
|
||||
pub(crate) async fn run_turn(
|
||||
sess: Arc<Session>,
|
||||
turn_context: Arc<TurnContext>,
|
||||
mut turn_context: Arc<TurnContext>,
|
||||
turn_extension_data: Arc<codex_extension_api::ExtensionData>,
|
||||
input: Vec<TurnInput>,
|
||||
prewarmed_client_session: Option<ModelClientSession>,
|
||||
@@ -187,6 +191,7 @@ pub(crate) async fn run_turn(
|
||||
|
||||
let mut last_agent_message: Option<String> = None;
|
||||
let mut stop_hook_active = false;
|
||||
let mut stop_failure_hook_ran = false;
|
||||
// Although from the perspective of codex.rs, TurnDiffTracker has the lifecycle of a Task which contains
|
||||
// many turns, from the perspective of the user, it is a single turn.
|
||||
let display_roots = turn_diff_display_roots(turn_context.as_ref()).await;
|
||||
@@ -381,6 +386,21 @@ pub(crate) async fn run_turn(
|
||||
}
|
||||
}
|
||||
|
||||
if !stop_failure_hook_ran {
|
||||
stop_failure_hook_ran = true;
|
||||
if let Some(recovered_context) = recover_from_stop_failure(
|
||||
&sess,
|
||||
&turn_context,
|
||||
&codex_error,
|
||||
last_agent_message.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
turn_context = recovered_context;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
sess.track_turn_codex_error(turn_context.as_ref(), &codex_error);
|
||||
let error = CodexErrorInfo::BadRequest;
|
||||
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
|
||||
@@ -395,6 +415,20 @@ pub(crate) async fn run_turn(
|
||||
}
|
||||
Err(e) => {
|
||||
info!("Turn error: {e:#}");
|
||||
if !stop_failure_hook_ran {
|
||||
stop_failure_hook_ran = true;
|
||||
if let Some(recovered_context) = recover_from_stop_failure(
|
||||
&sess,
|
||||
&turn_context,
|
||||
&e,
|
||||
last_agent_message.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
turn_context = recovered_context;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let error = e.to_codex_protocol_error();
|
||||
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
|
||||
.await;
|
||||
@@ -410,6 +444,103 @@ pub(crate) async fn run_turn(
|
||||
last_agent_message
|
||||
}
|
||||
|
||||
async fn recover_from_stop_failure(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
error: &CodexErr,
|
||||
last_assistant_message: Option<String>,
|
||||
) -> Option<Arc<TurnContext>> {
|
||||
let failure_kind = StopFailureError::classify(error)?;
|
||||
let recovery = run_turn_stop_failure_hooks(
|
||||
sess,
|
||||
turn_context,
|
||||
error,
|
||||
failure_kind,
|
||||
last_assistant_message,
|
||||
)
|
||||
.await
|
||||
.recovery?;
|
||||
let current_model = turn_context.model_info.slug.as_str();
|
||||
let (target_model, selector) = match recovery.model {
|
||||
StopFailureModelSelector::Current => (current_model.to_string(), "current"),
|
||||
StopFailureModelSelector::CatalogDefault => {
|
||||
let configured_model = None;
|
||||
(
|
||||
sess.services
|
||||
.models_manager
|
||||
.get_default_model(&configured_model, RefreshStrategy::OnlineIfUncached)
|
||||
.await,
|
||||
"catalog_default",
|
||||
)
|
||||
}
|
||||
StopFailureModelSelector::Id(id) => (id, "id"),
|
||||
};
|
||||
if target_model.is_empty() {
|
||||
sess.send_event(
|
||||
turn_context,
|
||||
EventMsg::Warning(WarningEvent {
|
||||
message: "StopFailure hook requested recovery without a usable model; preserving the original error."
|
||||
.to_string(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
return None;
|
||||
}
|
||||
|
||||
let model_changed = target_model != current_model;
|
||||
let recovered_context = if model_changed {
|
||||
let recovered_context = Arc::new(
|
||||
turn_context
|
||||
.with_model(target_model.clone(), &sess.services.models_manager)
|
||||
.await,
|
||||
);
|
||||
sess.record_context_updates_and_set_reference_context_item(recovered_context.as_ref())
|
||||
.await;
|
||||
sess.set_previous_turn_settings(Some(PreviousTurnSettings {
|
||||
model: recovered_context.model_info.slug.clone(),
|
||||
comp_hash: recovered_context.comp_hash.clone(),
|
||||
realtime_active: Some(recovered_context.realtime_active),
|
||||
}))
|
||||
.await;
|
||||
recovered_context
|
||||
} else {
|
||||
Arc::clone(turn_context)
|
||||
};
|
||||
|
||||
let mut message = format!(
|
||||
"Recovering from {} by retrying with model {}.",
|
||||
failure_kind.as_str(),
|
||||
recovered_context.model_info.slug
|
||||
);
|
||||
if let Some(reason) = recovery.reason {
|
||||
message.push(' ');
|
||||
message.push_str(&reason);
|
||||
}
|
||||
sess.send_event(
|
||||
&recovered_context,
|
||||
EventMsg::Warning(WarningEvent { message }),
|
||||
)
|
||||
.await;
|
||||
turn_context.session_telemetry.counter(
|
||||
"codex.stop_failure.recovery",
|
||||
/*inc*/ 1,
|
||||
&[
|
||||
("error", failure_kind.as_str()),
|
||||
("model_selector", selector),
|
||||
],
|
||||
);
|
||||
|
||||
if !model_changed {
|
||||
let delay = match error {
|
||||
CodexErr::Stream(_, Some(delay)) => *delay,
|
||||
_ => crate::util::backoff(/*retry_count*/ 1),
|
||||
};
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
|
||||
Some(recovered_context)
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
async fn turn_diff_display_roots(turn_context: &TurnContext) -> Vec<(String, PathBuf)> {
|
||||
let mut display_roots = Vec::new();
|
||||
|
||||
@@ -37,6 +37,7 @@ use core_test_support::responses::ev_response_created;
|
||||
use core_test_support::responses::mount_sse_once;
|
||||
use core_test_support::responses::mount_sse_sequence;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::sse_failed;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::skip_if_windows;
|
||||
@@ -59,6 +60,15 @@ const BLOCKED_PROMPT_CONTEXT: &str = "Remember the blocked lighthouse note.";
|
||||
const PERMISSION_REQUEST_HOOK_MATCHER: &str = "^Bash$";
|
||||
const PERMISSION_REQUEST_ALLOW_REASON: &str = "should not be used for allow";
|
||||
|
||||
fn bundled_default_model_slug() -> String {
|
||||
codex_core::test_support::all_model_presets()
|
||||
.iter()
|
||||
.find(|preset| preset.is_default)
|
||||
.expect("bundled models should include a default")
|
||||
.model
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn restrictive_workspace_write_profile() -> PermissionProfile {
|
||||
PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
@@ -168,6 +178,55 @@ else:
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_stop_failure_hook(home: &Path, matcher: &str, output: Value) -> Result<()> {
|
||||
let script_path = home.join("stop_failure_hook.py");
|
||||
let log_path = home.join("stop_failure_hook_log.jsonl");
|
||||
let output_json = serde_json::to_string(&output).context("serialize StopFailure output")?;
|
||||
let script = format!(
|
||||
r#"import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
log_path = Path(r"{log_path}")
|
||||
output = json.loads({output_json:?})
|
||||
payload = json.load(sys.stdin)
|
||||
|
||||
with log_path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(payload) + "\n")
|
||||
|
||||
print(json.dumps(output))
|
||||
"#,
|
||||
log_path = log_path.display(),
|
||||
output_json = output_json,
|
||||
);
|
||||
let hooks = serde_json::json!({
|
||||
"hooks": {
|
||||
"StopFailure": [{
|
||||
"matcher": matcher,
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": format!("python3 {}", script_path.display()),
|
||||
"statusMessage": "choosing a recovery",
|
||||
}]
|
||||
}]
|
||||
}
|
||||
});
|
||||
|
||||
fs::write(&script_path, script).context("write StopFailure hook script")?;
|
||||
fs::write(home.join("hooks.json"), hooks.to_string()).context("write hooks.json")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_stop_failure_hook_inputs(home: &Path) -> Result<Vec<Value>> {
|
||||
let path = home.join("stop_failure_hook_log.jsonl");
|
||||
let contents = fs::read_to_string(path).context("read StopFailure hook log")?;
|
||||
contents
|
||||
.lines()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.map(|line| serde_json::from_str(line).context("parse StopFailure hook input"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn write_parallel_stop_hooks(home: &Path, prompts: &[&str]) -> Result<()> {
|
||||
let hook_entries = prompts
|
||||
.iter()
|
||||
@@ -1065,6 +1124,161 @@ fn request_message_input_texts(body: &[u8], role: &str) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_failure_hook_can_retry_with_an_explicit_model() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let responses = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse_failed("resp-1", "server_is_overloaded", "capacity"),
|
||||
sse(vec![
|
||||
ev_response_created("resp-2"),
|
||||
ev_assistant_message("msg-2", "recovered"),
|
||||
ev_completed("resp-2"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let recovery_output = serde_json::json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "StopFailure",
|
||||
"recovery": {
|
||||
"action": "retry",
|
||||
"model": { "selector": "id", "id": "gpt-5.4" },
|
||||
"reason": "The configured fallback is available."
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut builder = test_codex()
|
||||
.with_model("gpt-5.2")
|
||||
.with_pre_build_hook(move |home| {
|
||||
write_stop_failure_hook(home, "overloaded", recovery_output)
|
||||
.expect("failed to write StopFailure hook fixture");
|
||||
})
|
||||
.with_config(trust_discovered_hooks);
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
test.submit_turn("please recover").await?;
|
||||
|
||||
let requests = responses.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(requests[0].body_json()["model"], "gpt-5.2");
|
||||
assert_eq!(requests[1].body_json()["model"], "gpt-5.4");
|
||||
assert!(
|
||||
requests[1].body_contains_text("<model_switch>"),
|
||||
"the recovery request should use the ordinary model-switch context"
|
||||
);
|
||||
|
||||
let hook_inputs = read_stop_failure_hook_inputs(test.codex_home_path())?;
|
||||
assert_eq!(hook_inputs.len(), 1);
|
||||
let input = &hook_inputs[0];
|
||||
assert_eq!(input["hook_event_name"], "StopFailure");
|
||||
assert_eq!(input["error"], "overloaded");
|
||||
assert_eq!(input["model"], "gpt-5.2");
|
||||
assert_eq!(input["last_assistant_message"], Value::Null);
|
||||
assert!(
|
||||
input["error_details"]
|
||||
.as_str()
|
||||
.is_some_and(|details| details.contains("capacity"))
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_failure_hook_can_retry_with_the_catalog_default() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let responses = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse_failed("resp-1", "server_is_overloaded", "capacity"),
|
||||
sse(vec![
|
||||
ev_response_created("resp-2"),
|
||||
ev_assistant_message("msg-2", "recovered"),
|
||||
ev_completed("resp-2"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let recovery_output = serde_json::json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "StopFailure",
|
||||
"recovery": {
|
||||
"action": "retry",
|
||||
"model": { "selector": "catalog_default" }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut builder = test_codex()
|
||||
.with_model("gpt-5.2")
|
||||
.with_pre_build_hook(move |home| {
|
||||
write_stop_failure_hook(home, "overloaded", recovery_output)
|
||||
.expect("failed to write StopFailure hook fixture");
|
||||
})
|
||||
.with_config(trust_discovered_hooks);
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
test.submit_turn("use the default fallback").await?;
|
||||
|
||||
let requests = responses.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(
|
||||
requests[1].body_json()["model"],
|
||||
bundled_default_model_slug()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_failure_hook_runs_at_most_once_per_turn() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let responses = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse_failed("resp-1", "server_is_overloaded", "first failure"),
|
||||
sse_failed("resp-2", "server_is_overloaded", "recovery failure"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let recovery_output = serde_json::json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "StopFailure",
|
||||
"recovery": {
|
||||
"action": "retry",
|
||||
"model": { "selector": "id", "id": "gpt-5.4" }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut builder = test_codex()
|
||||
.with_model("gpt-5.2")
|
||||
.with_pre_build_hook(move |home| {
|
||||
write_stop_failure_hook(home, "overloaded", recovery_output)
|
||||
.expect("failed to write StopFailure hook fixture");
|
||||
})
|
||||
.with_config(trust_discovered_hooks);
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
test.submit_turn("only recover once").await?;
|
||||
|
||||
assert_eq!(responses.requests().len(), 2);
|
||||
assert_eq!(
|
||||
read_stop_failure_hook_inputs(test.codex_home_path())?.len(),
|
||||
1
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_hook_can_block_multiple_times_in_same_turn() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"additionalProperties": false,
|
||||
"definitions": {
|
||||
"NullableString": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"type": "string"
|
||||
},
|
||||
"error": {
|
||||
"enum": [
|
||||
"rate_limit",
|
||||
"overloaded",
|
||||
"authentication_failed",
|
||||
"billing_error",
|
||||
"invalid_request",
|
||||
"server_error",
|
||||
"unknown"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"error_details": {
|
||||
"$ref": "#/definitions/NullableString"
|
||||
},
|
||||
"hook_event_name": {
|
||||
"const": "StopFailure",
|
||||
"type": "string"
|
||||
},
|
||||
"last_assistant_message": {
|
||||
"$ref": "#/definitions/NullableString"
|
||||
},
|
||||
"model": {
|
||||
"type": "string"
|
||||
},
|
||||
"permission_mode": {
|
||||
"enum": [
|
||||
"default",
|
||||
"acceptEdits",
|
||||
"plan",
|
||||
"dontAsk",
|
||||
"bypassPermissions"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"session_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"transcript_path": {
|
||||
"$ref": "#/definitions/NullableString"
|
||||
},
|
||||
"turn_id": {
|
||||
"description": "Codex extension: expose the active turn id to internal turn-scoped hooks.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"cwd",
|
||||
"error",
|
||||
"error_details",
|
||||
"hook_event_name",
|
||||
"last_assistant_message",
|
||||
"model",
|
||||
"permission_mode",
|
||||
"session_id",
|
||||
"transcript_path",
|
||||
"turn_id"
|
||||
],
|
||||
"title": "stop-failure.command.input",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"additionalProperties": false,
|
||||
"definitions": {
|
||||
"StopFailureHookSpecificOutputWire": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"hookEventName": {
|
||||
"const": "StopFailure",
|
||||
"type": "string"
|
||||
},
|
||||
"recovery": {
|
||||
"$ref": "#/definitions/StopFailureRecoveryWire"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"hookEventName",
|
||||
"recovery"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"StopFailureModelSelectorWire": {
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"selector": {
|
||||
"enum": [
|
||||
"current"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"selector"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"selector": {
|
||||
"enum": [
|
||||
"catalog_default"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"selector"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"selector": {
|
||||
"enum": [
|
||||
"id"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"selector"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
]
|
||||
},
|
||||
"StopFailureRecoveryActionWire": {
|
||||
"enum": [
|
||||
"retry"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"StopFailureRecoveryWire": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"action": {
|
||||
"$ref": "#/definitions/StopFailureRecoveryActionWire"
|
||||
},
|
||||
"model": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/StopFailureModelSelectorWire"
|
||||
}
|
||||
],
|
||||
"default": null
|
||||
},
|
||||
"reason": {
|
||||
"default": null,
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"continue": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"hookSpecificOutput": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/StopFailureHookSpecificOutputWire"
|
||||
}
|
||||
],
|
||||
"default": null
|
||||
},
|
||||
"stopReason": {
|
||||
"default": null,
|
||||
"type": "string"
|
||||
},
|
||||
"suppressOutput": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"systemMessage": {
|
||||
"default": null,
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"title": "stop-failure.command.output",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -51,6 +51,7 @@ pub(crate) fn select_handlers_for_matcher_inputs(
|
||||
| HookEventName::SessionStart
|
||||
| HookEventName::SubagentStart
|
||||
| HookEventName::SubagentStop
|
||||
| HookEventName::StopFailure
|
||||
| HookEventName::PreCompact
|
||||
| HookEventName::PostCompact => {
|
||||
if matcher_inputs.is_empty() {
|
||||
@@ -149,7 +150,8 @@ fn scope_for_event(event_name: HookEventName) -> HookScope {
|
||||
| HookEventName::PostCompact
|
||||
| HookEventName::UserPromptSubmit
|
||||
| HookEventName::SubagentStop
|
||||
| HookEventName::Stop => HookScope::Turn,
|
||||
| HookEventName::Stop
|
||||
| HookEventName::StopFailure => HookScope::Turn,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ use crate::events::session_start::SessionStartOutcome;
|
||||
use crate::events::session_start::SessionStartRequest;
|
||||
use crate::events::stop::StopOutcome;
|
||||
use crate::events::stop::StopRequest;
|
||||
use crate::events::stop_failure::StopFailureOutcome;
|
||||
use crate::events::stop_failure::StopFailureRequest;
|
||||
use crate::events::user_prompt_submit::UserPromptSubmitOutcome;
|
||||
use crate::events::user_prompt_submit::UserPromptSubmitRequest;
|
||||
use crate::output_spill::HookOutputSpiller;
|
||||
@@ -73,6 +75,7 @@ impl ConfiguredHandler {
|
||||
codex_protocol::protocol::HookEventName::SubagentStart => "subagent-start",
|
||||
codex_protocol::protocol::HookEventName::SubagentStop => "subagent-stop",
|
||||
codex_protocol::protocol::HookEventName::Stop => "stop",
|
||||
codex_protocol::protocol::HookEventName::StopFailure => "stop-failure",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -265,6 +268,14 @@ impl ClaudeHooksEngine {
|
||||
outcome
|
||||
}
|
||||
|
||||
pub(crate) fn preview_stop_failure(&self, request: &StopFailureRequest) -> Vec<HookRunSummary> {
|
||||
crate::events::stop_failure::preview(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_stop_failure(&self, request: StopFailureRequest) -> StopFailureOutcome {
|
||||
crate::events::stop_failure::run(&self.handlers, &self.shell, request).await
|
||||
}
|
||||
|
||||
async fn maybe_spill_texts(&self, session_id: ThreadId, texts: Vec<String>) -> Vec<String> {
|
||||
self.output_spiller
|
||||
.maybe_spill_texts(session_id, texts)
|
||||
|
||||
@@ -74,6 +74,7 @@ pub(crate) struct StatelessHookOutput {
|
||||
}
|
||||
|
||||
use crate::schema::BlockDecisionWire;
|
||||
use crate::schema::HookEventNameWire;
|
||||
use crate::schema::HookUniversalOutputWire;
|
||||
use crate::schema::PermissionRequestBehaviorWire;
|
||||
use crate::schema::PermissionRequestCommandOutputWire;
|
||||
@@ -86,6 +87,9 @@ use crate::schema::PreToolUseDecisionWire;
|
||||
use crate::schema::PreToolUsePermissionDecisionWire;
|
||||
use crate::schema::SessionStartCommandOutputWire;
|
||||
use crate::schema::StopCommandOutputWire;
|
||||
use crate::schema::StopFailureCommandOutputWire;
|
||||
use crate::schema::StopFailureModelSelectorWire;
|
||||
use crate::schema::StopFailureRecoveryActionWire;
|
||||
use crate::schema::SubagentStartCommandOutputWire;
|
||||
use crate::schema::SubagentStopCommandOutputWire;
|
||||
use crate::schema::UserPromptSubmitCommandOutputWire;
|
||||
@@ -290,6 +294,49 @@ pub(crate) fn parse_stop(stdout: &str) -> Option<StopOutput> {
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn parse_stop_failure(
|
||||
stdout: &str,
|
||||
) -> Option<crate::events::stop_failure::StopFailureOutput> {
|
||||
let wire: StopFailureCommandOutputWire = parse_json(stdout)?;
|
||||
let _ = wire.universal;
|
||||
let recovery = match wire.hook_specific_output {
|
||||
None => None,
|
||||
Some(output) => {
|
||||
if output.hook_event_name != HookEventNameWire::StopFailure {
|
||||
return None;
|
||||
}
|
||||
let recovery = output.recovery;
|
||||
let model = match recovery.model {
|
||||
None | Some(StopFailureModelSelectorWire::Current) => {
|
||||
crate::events::stop_failure::StopFailureModelSelector::Current
|
||||
}
|
||||
Some(StopFailureModelSelectorWire::CatalogDefault) => {
|
||||
crate::events::stop_failure::StopFailureModelSelector::CatalogDefault
|
||||
}
|
||||
Some(StopFailureModelSelectorWire::Id { id }) => {
|
||||
let id = id.trim();
|
||||
if id.is_empty() {
|
||||
return None;
|
||||
}
|
||||
crate::events::stop_failure::StopFailureModelSelector::Id(id.to_string())
|
||||
}
|
||||
};
|
||||
match recovery.action {
|
||||
StopFailureRecoveryActionWire::Retry => {
|
||||
Some(crate::events::stop_failure::StopFailureRecovery {
|
||||
model,
|
||||
reason: recovery.reason.and_then(|reason| {
|
||||
let reason = reason.trim();
|
||||
(!reason.is_empty()).then(|| reason.to_string())
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(crate::events::stop_failure::StopFailureOutput { recovery })
|
||||
}
|
||||
|
||||
pub(crate) fn parse_subagent_stop(stdout: &str) -> Option<StopOutput> {
|
||||
let wire: SubagentStopCommandOutputWire = parse_json(stdout)?;
|
||||
Some(stop_output(
|
||||
|
||||
@@ -24,6 +24,8 @@ pub(crate) struct GeneratedHookSchemas {
|
||||
pub user_prompt_submit_command_output: Value,
|
||||
pub stop_command_input: Value,
|
||||
pub stop_command_output: Value,
|
||||
pub stop_failure_command_input: Value,
|
||||
pub stop_failure_command_output: Value,
|
||||
}
|
||||
|
||||
pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas {
|
||||
@@ -109,6 +111,14 @@ pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas {
|
||||
"stop.command.output",
|
||||
include_str!("../../schema/generated/stop.command.output.schema.json"),
|
||||
),
|
||||
stop_failure_command_input: parse_json_schema(
|
||||
"stop-failure.command.input",
|
||||
include_str!("../../schema/generated/stop-failure.command.input.schema.json"),
|
||||
),
|
||||
stop_failure_command_output: parse_json_schema(
|
||||
"stop-failure.command.output",
|
||||
include_str!("../../schema/generated/stop-failure.command.output.schema.json"),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -146,5 +156,7 @@ mod tests {
|
||||
assert_eq!(schemas.user_prompt_submit_command_output["type"], "object");
|
||||
assert_eq!(schemas.stop_command_input["type"], "object");
|
||||
assert_eq!(schemas.stop_command_output["type"], "object");
|
||||
assert_eq!(schemas.stop_failure_command_input["type"], "object");
|
||||
assert_eq!(schemas.stop_failure_command_output["type"], "object");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +113,7 @@ pub(crate) fn matcher_pattern_for_event(
|
||||
| HookEventName::SessionStart
|
||||
| HookEventName::SubagentStart
|
||||
| HookEventName::SubagentStop
|
||||
| HookEventName::StopFailure
|
||||
| HookEventName::PreCompact
|
||||
| HookEventName::PostCompact => matcher,
|
||||
HookEventName::UserPromptSubmit | HookEventName::Stop => None,
|
||||
|
||||
@@ -5,4 +5,5 @@ pub mod post_tool_use;
|
||||
pub mod pre_tool_use;
|
||||
pub mod session_start;
|
||||
pub mod stop;
|
||||
pub mod stop_failure;
|
||||
pub mod user_prompt_submit;
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::protocol::HookCompletedEvent;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookOutputEntry;
|
||||
use codex_protocol::protocol::HookOutputEntryKind;
|
||||
use codex_protocol::protocol::HookRunStatus;
|
||||
use codex_protocol::protocol::HookRunSummary;
|
||||
use codex_protocol::protocol::RateLimitReachedType;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use super::common;
|
||||
use crate::engine::CommandShell;
|
||||
use crate::engine::ConfiguredHandler;
|
||||
use crate::engine::command_runner::CommandRunResult;
|
||||
use crate::engine::dispatcher;
|
||||
use crate::engine::output_parser;
|
||||
use crate::schema::NullableString;
|
||||
use crate::schema::StopFailureCommandInput;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StopFailureRequest {
|
||||
pub session_id: ThreadId,
|
||||
pub turn_id: String,
|
||||
pub cwd: AbsolutePathBuf,
|
||||
pub transcript_path: Option<PathBuf>,
|
||||
pub model: String,
|
||||
pub permission_mode: String,
|
||||
pub error: StopFailureError,
|
||||
pub error_details: Option<String>,
|
||||
pub last_assistant_message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct StopFailureOutcome {
|
||||
pub hook_events: Vec<HookCompletedEvent>,
|
||||
pub recovery: Option<StopFailureRecovery>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StopFailureOutput {
|
||||
pub recovery: Option<StopFailureRecovery>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StopFailureRecovery {
|
||||
pub model: StopFailureModelSelector,
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum StopFailureModelSelector {
|
||||
Current,
|
||||
CatalogDefault,
|
||||
Id(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StopFailureError {
|
||||
RateLimit,
|
||||
Overloaded,
|
||||
AuthenticationFailed,
|
||||
BillingError,
|
||||
InvalidRequest,
|
||||
ServerError,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl StopFailureError {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::RateLimit => "rate_limit",
|
||||
Self::Overloaded => "overloaded",
|
||||
Self::AuthenticationFailed => "authentication_failed",
|
||||
Self::BillingError => "billing_error",
|
||||
Self::InvalidRequest => "invalid_request",
|
||||
Self::ServerError => "server_error",
|
||||
Self::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
fn from_http_status(status: u16) -> Self {
|
||||
match status {
|
||||
401 => Self::AuthenticationFailed,
|
||||
402 => Self::BillingError,
|
||||
429 => Self::RateLimit,
|
||||
400..=499 => Self::InvalidRequest,
|
||||
500..=599 => Self::ServerError,
|
||||
_ => Self::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn classify(error: &CodexErr) -> Option<Self> {
|
||||
let error = match error {
|
||||
CodexErr::UsageLimitReached(error) => match error.rate_limit_reached_type {
|
||||
Some(
|
||||
RateLimitReachedType::WorkspaceOwnerCreditsDepleted
|
||||
| RateLimitReachedType::WorkspaceMemberCreditsDepleted
|
||||
| RateLimitReachedType::WorkspaceOwnerUsageLimitReached
|
||||
| RateLimitReachedType::WorkspaceMemberUsageLimitReached,
|
||||
) => Self::BillingError,
|
||||
Some(RateLimitReachedType::RateLimitReached) | None => Self::RateLimit,
|
||||
},
|
||||
CodexErr::ServerOverloaded => Self::Overloaded,
|
||||
CodexErr::RefreshTokenFailed(_) => Self::AuthenticationFailed,
|
||||
CodexErr::QuotaExceeded | CodexErr::UsageNotIncluded => Self::BillingError,
|
||||
CodexErr::ContextWindowExceeded
|
||||
| CodexErr::InvalidRequest(_)
|
||||
| CodexErr::InvalidImageRequest() => Self::InvalidRequest,
|
||||
CodexErr::InternalServerError | CodexErr::Stream(_, _) | CodexErr::RequestTimeout => {
|
||||
Self::ServerError
|
||||
}
|
||||
CodexErr::UnexpectedStatus(error) => Self::from_http_status(error.status.as_u16()),
|
||||
CodexErr::RetryLimit(error) => Self::from_http_status(error.status.as_u16()),
|
||||
CodexErr::ConnectionFailed(error) => {
|
||||
error.source.status().map_or(Self::ServerError, |status| {
|
||||
Self::from_http_status(status.as_u16())
|
||||
})
|
||||
}
|
||||
CodexErr::ResponseStreamFailed(error) => {
|
||||
error.source.status().map_or(Self::ServerError, |status| {
|
||||
Self::from_http_status(status.as_u16())
|
||||
})
|
||||
}
|
||||
CodexErr::CyberPolicy { .. }
|
||||
| CodexErr::TurnAborted
|
||||
| CodexErr::ThreadNotFound(_)
|
||||
| CodexErr::AgentLimitReached { .. }
|
||||
| CodexErr::SessionConfiguredNotFirstEvent
|
||||
| CodexErr::Timeout
|
||||
| CodexErr::Spawn
|
||||
| CodexErr::Interrupted
|
||||
| CodexErr::InternalAgentDied
|
||||
| CodexErr::Sandbox(_)
|
||||
| CodexErr::LandlockSandboxExecutableNotProvided
|
||||
| CodexErr::UnsupportedOperation(_)
|
||||
| CodexErr::Fatal(_)
|
||||
| CodexErr::Io(_)
|
||||
| CodexErr::Json(_)
|
||||
| CodexErr::TokioJoin(_)
|
||||
| CodexErr::EnvVar(_) => return None,
|
||||
#[cfg(target_os = "linux")]
|
||||
CodexErr::LandlockRuleset(_) | CodexErr::LandlockPathFd(_) => return None,
|
||||
};
|
||||
Some(error)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn preview(
|
||||
handlers: &[ConfiguredHandler],
|
||||
request: &StopFailureRequest,
|
||||
) -> Vec<HookRunSummary> {
|
||||
dispatcher::select_handlers(
|
||||
handlers,
|
||||
HookEventName::StopFailure,
|
||||
Some(request.error.as_str()),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|handler| dispatcher::running_summary(&handler))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
handlers: &[ConfiguredHandler],
|
||||
shell: &CommandShell,
|
||||
request: StopFailureRequest,
|
||||
) -> StopFailureOutcome {
|
||||
let matched = dispatcher::select_handlers(
|
||||
handlers,
|
||||
HookEventName::StopFailure,
|
||||
Some(request.error.as_str()),
|
||||
);
|
||||
if matched.is_empty() {
|
||||
return StopFailureOutcome::default();
|
||||
}
|
||||
|
||||
let input = StopFailureCommandInput {
|
||||
session_id: request.session_id.to_string(),
|
||||
turn_id: request.turn_id.clone(),
|
||||
transcript_path: NullableString::from_path(request.transcript_path),
|
||||
cwd: request.cwd.display().to_string(),
|
||||
hook_event_name: "StopFailure".to_string(),
|
||||
model: request.model,
|
||||
permission_mode: request.permission_mode,
|
||||
error: request.error.as_str().to_string(),
|
||||
error_details: NullableString::from_string(request.error_details),
|
||||
last_assistant_message: NullableString::from_string(request.last_assistant_message),
|
||||
};
|
||||
let input_json = match serde_json::to_string(&input) {
|
||||
Ok(input_json) => input_json,
|
||||
Err(error) => {
|
||||
return StopFailureOutcome {
|
||||
hook_events: common::serialization_failure_hook_events(
|
||||
matched,
|
||||
Some(request.turn_id),
|
||||
format!("failed to serialize stop failure hook input: {error}"),
|
||||
),
|
||||
recovery: None,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
let results = dispatcher::execute_handlers(
|
||||
shell,
|
||||
matched,
|
||||
input_json,
|
||||
request.cwd.as_path(),
|
||||
Some(request.turn_id),
|
||||
parse_completed,
|
||||
)
|
||||
.await;
|
||||
let recovery = results
|
||||
.iter()
|
||||
.find_map(|result| result.data.recovery.clone());
|
||||
StopFailureOutcome {
|
||||
hook_events: results.into_iter().map(|result| result.completed).collect(),
|
||||
recovery,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_completed(
|
||||
handler: &ConfiguredHandler,
|
||||
run_result: CommandRunResult,
|
||||
turn_id: Option<String>,
|
||||
) -> dispatcher::ParsedHandler<StopFailureOutput> {
|
||||
let mut entries = Vec::new();
|
||||
let mut status = HookRunStatus::Completed;
|
||||
let mut recovery = None;
|
||||
|
||||
match run_result.error.as_deref() {
|
||||
Some(error) => {
|
||||
status = HookRunStatus::Failed;
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: error.to_string(),
|
||||
});
|
||||
}
|
||||
None => match run_result.exit_code {
|
||||
Some(0) => {
|
||||
let stdout = run_result.stdout.trim();
|
||||
if !stdout.is_empty() {
|
||||
if let Some(parsed) = output_parser::parse_stop_failure(stdout) {
|
||||
recovery = parsed.recovery;
|
||||
if let Some(reason) = recovery
|
||||
.as_ref()
|
||||
.and_then(|recovery| recovery.reason.clone())
|
||||
{
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Feedback,
|
||||
text: reason,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
status = HookRunStatus::Failed;
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: "hook returned invalid StopFailure hook JSON output".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(code) => {
|
||||
status = HookRunStatus::Failed;
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: common::trimmed_non_empty(&run_result.stderr)
|
||||
.unwrap_or_else(|| format!("hook exited with code {code}")),
|
||||
});
|
||||
}
|
||||
None => {
|
||||
status = HookRunStatus::Failed;
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: "hook process terminated without an exit code".to_string(),
|
||||
});
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
dispatcher::ParsedHandler {
|
||||
completed: HookCompletedEvent {
|
||||
turn_id,
|
||||
run: dispatcher::completed_summary(handler, &run_result, status, entries),
|
||||
},
|
||||
data: StopFailureOutput { recovery },
|
||||
completion_order: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "stop_failure_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,120 @@
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::UsageLimitReachedError;
|
||||
use codex_protocol::protocol::RateLimitReachedType;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::StopFailureError;
|
||||
use super::StopFailureModelSelector;
|
||||
use super::StopFailureOutput;
|
||||
use super::StopFailureRecovery;
|
||||
use crate::engine::output_parser::parse_stop_failure;
|
||||
|
||||
fn usage_limit_error(rate_limit_reached_type: RateLimitReachedType) -> CodexErr {
|
||||
CodexErr::UsageLimitReached(UsageLimitReachedError {
|
||||
plan_type: None,
|
||||
resets_at: None,
|
||||
rate_limits: None,
|
||||
promo_message: None,
|
||||
rate_limit_reached_type: Some(rate_limit_reached_type),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_recoverable_api_errors() {
|
||||
let cases = [
|
||||
(CodexErr::ServerOverloaded, StopFailureError::Overloaded),
|
||||
(
|
||||
usage_limit_error(RateLimitReachedType::RateLimitReached),
|
||||
StopFailureError::RateLimit,
|
||||
),
|
||||
(
|
||||
usage_limit_error(RateLimitReachedType::WorkspaceOwnerCreditsDepleted),
|
||||
StopFailureError::BillingError,
|
||||
),
|
||||
(
|
||||
CodexErr::InvalidRequest("bad request".to_string()),
|
||||
StopFailureError::InvalidRequest,
|
||||
),
|
||||
(CodexErr::InternalServerError, StopFailureError::ServerError),
|
||||
];
|
||||
|
||||
for (error, expected) in cases {
|
||||
assert_eq!(StopFailureError::classify(&error), Some(expected));
|
||||
}
|
||||
|
||||
assert_eq!(StopFailureError::classify(&CodexErr::TurnAborted), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_each_model_selector() {
|
||||
let cases = [
|
||||
(
|
||||
serde_json::json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "StopFailure",
|
||||
"recovery": { "action": "retry" }
|
||||
}
|
||||
}),
|
||||
StopFailureModelSelector::Current,
|
||||
),
|
||||
(
|
||||
serde_json::json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "StopFailure",
|
||||
"recovery": {
|
||||
"action": "retry",
|
||||
"model": { "selector": "catalog_default" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
StopFailureModelSelector::CatalogDefault,
|
||||
),
|
||||
(
|
||||
serde_json::json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "StopFailure",
|
||||
"recovery": {
|
||||
"action": "retry",
|
||||
"model": { "selector": "id", "id": "gpt-5.4" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
StopFailureModelSelector::Id("gpt-5.4".to_string()),
|
||||
),
|
||||
];
|
||||
|
||||
for (output, expected_model) in cases {
|
||||
assert_eq!(
|
||||
parse_stop_failure(&output.to_string()),
|
||||
Some(StopFailureOutput {
|
||||
recovery: Some(StopFailureRecovery {
|
||||
model: expected_model,
|
||||
reason: None,
|
||||
}),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_recovery_is_a_valid_noop() {
|
||||
assert_eq!(
|
||||
parse_stop_failure("{}"),
|
||||
Some(StopFailureOutput { recovery: None })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_explicit_model_id_is_rejected() {
|
||||
let output = serde_json::json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "StopFailure",
|
||||
"recovery": {
|
||||
"action": "retry",
|
||||
"model": { "selector": "id", "id": " " }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
assert_eq!(parse_stop_failure(&output.to_string()), None);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ pub use declarations::plugin_hook_declarations;
|
||||
pub use engine::HookListEntry;
|
||||
pub use events::common::SubagentHookContext;
|
||||
/// Hook event names as they appear in hooks JSON and config files.
|
||||
pub const HOOK_EVENT_NAMES: [&str; 10] = [
|
||||
pub const HOOK_EVENT_NAMES: [&str; 11] = [
|
||||
"PreToolUse",
|
||||
"PermissionRequest",
|
||||
"PostToolUse",
|
||||
@@ -27,6 +27,7 @@ pub const HOOK_EVENT_NAMES: [&str; 10] = [
|
||||
"SubagentStart",
|
||||
"SubagentStop",
|
||||
"Stop",
|
||||
"StopFailure",
|
||||
];
|
||||
|
||||
/// Hook event names whose matcher fields are meaningful during dispatch.
|
||||
@@ -34,7 +35,7 @@ pub const HOOK_EVENT_NAMES: [&str; 10] = [
|
||||
/// Other events can appear in hooks JSON, but Codex ignores their matcher
|
||||
/// fields because those events do not dispatch against a tool, compaction
|
||||
/// trigger, or session-start source.
|
||||
pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 8] = [
|
||||
pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 9] = [
|
||||
"PreToolUse",
|
||||
"PermissionRequest",
|
||||
"PostToolUse",
|
||||
@@ -43,6 +44,7 @@ pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 8] = [
|
||||
"SessionStart",
|
||||
"SubagentStart",
|
||||
"SubagentStop",
|
||||
"StopFailure",
|
||||
];
|
||||
|
||||
pub use events::compact::PostCompactRequest;
|
||||
@@ -63,6 +65,11 @@ pub use events::session_start::StartHookTarget;
|
||||
pub use events::stop::StopHookTarget;
|
||||
pub use events::stop::StopOutcome;
|
||||
pub use events::stop::StopRequest;
|
||||
pub use events::stop_failure::StopFailureError;
|
||||
pub use events::stop_failure::StopFailureModelSelector;
|
||||
pub use events::stop_failure::StopFailureOutcome;
|
||||
pub use events::stop_failure::StopFailureRecovery;
|
||||
pub use events::stop_failure::StopFailureRequest;
|
||||
pub use events::user_prompt_submit::UserPromptSubmitOutcome;
|
||||
pub use events::user_prompt_submit::UserPromptSubmitRequest;
|
||||
pub use legacy_notify::legacy_notify_json;
|
||||
@@ -93,6 +100,7 @@ pub fn hook_event_key_label(event_name: HookEventName) -> &'static str {
|
||||
HookEventName::SubagentStart => "subagent_start",
|
||||
HookEventName::SubagentStop => "subagent_stop",
|
||||
HookEventName::Stop => "stop",
|
||||
HookEventName::StopFailure => "stop_failure",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::events::session_start::SessionStartOutcome;
|
||||
use crate::events::session_start::SessionStartRequest;
|
||||
use crate::events::stop::StopOutcome;
|
||||
use crate::events::stop::StopRequest;
|
||||
use crate::events::stop_failure::StopFailureOutcome;
|
||||
use crate::events::stop_failure::StopFailureRequest;
|
||||
use crate::events::user_prompt_submit::UserPromptSubmitOutcome;
|
||||
use crate::events::user_prompt_submit::UserPromptSubmitRequest;
|
||||
use crate::types::Hook;
|
||||
@@ -203,6 +205,17 @@ impl Hooks {
|
||||
pub async fn run_stop(&self, request: StopRequest) -> StopOutcome {
|
||||
self.engine.run_stop(request).await
|
||||
}
|
||||
|
||||
pub fn preview_stop_failure(
|
||||
&self,
|
||||
request: &StopFailureRequest,
|
||||
) -> Vec<codex_protocol::protocol::HookRunSummary> {
|
||||
self.engine.preview_stop_failure(request)
|
||||
}
|
||||
|
||||
pub async fn run_stop_failure(&self, request: StopFailureRequest) -> StopFailureOutcome {
|
||||
self.engine.run_stop_failure(request).await
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_hooks(config: HooksConfig) -> HookListOutcome {
|
||||
|
||||
@@ -35,6 +35,8 @@ const SUBAGENT_STOP_INPUT_FIXTURE: &str = "subagent-stop.command.input.schema.js
|
||||
const SUBAGENT_STOP_OUTPUT_FIXTURE: &str = "subagent-stop.command.output.schema.json";
|
||||
const STOP_INPUT_FIXTURE: &str = "stop.command.input.schema.json";
|
||||
const STOP_OUTPUT_FIXTURE: &str = "stop.command.output.schema.json";
|
||||
const STOP_FAILURE_INPUT_FIXTURE: &str = "stop-failure.command.input.schema.json";
|
||||
const STOP_FAILURE_OUTPUT_FIXTURE: &str = "stop-failure.command.output.schema.json";
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(transparent)]
|
||||
@@ -117,6 +119,8 @@ pub(crate) enum HookEventNameWire {
|
||||
SubagentStop,
|
||||
#[serde(rename = "Stop")]
|
||||
Stop,
|
||||
#[serde(rename = "StopFailure")]
|
||||
StopFailure,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
@@ -458,6 +462,51 @@ pub(crate) struct StopCommandOutputWire {
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[schemars(rename = "stop-failure.command.output")]
|
||||
pub(crate) struct StopFailureCommandOutputWire {
|
||||
#[serde(flatten)]
|
||||
pub universal: HookUniversalOutputWire,
|
||||
#[serde(default)]
|
||||
pub hook_specific_output: Option<StopFailureHookSpecificOutputWire>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct StopFailureHookSpecificOutputWire {
|
||||
#[schemars(schema_with = "stop_failure_hook_event_name_schema")]
|
||||
pub hook_event_name: HookEventNameWire,
|
||||
pub recovery: StopFailureRecoveryWire,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct StopFailureRecoveryWire {
|
||||
pub action: StopFailureRecoveryActionWire,
|
||||
#[serde(default)]
|
||||
pub model: Option<StopFailureModelSelectorWire>,
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum StopFailureRecoveryActionWire {
|
||||
Retry,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
|
||||
#[serde(tag = "selector", rename_all = "snake_case")]
|
||||
pub(crate) enum StopFailureModelSelectorWire {
|
||||
Current,
|
||||
CatalogDefault,
|
||||
Id { id: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -573,6 +622,26 @@ pub(crate) struct StopCommandInput {
|
||||
pub last_assistant_message: NullableString,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[schemars(rename = "stop-failure.command.input")]
|
||||
pub(crate) struct StopFailureCommandInput {
|
||||
pub session_id: String,
|
||||
/// Codex extension: expose the active turn id to internal turn-scoped hooks.
|
||||
pub turn_id: String,
|
||||
pub transcript_path: NullableString,
|
||||
pub cwd: String,
|
||||
#[schemars(schema_with = "stop_failure_hook_event_name_schema")]
|
||||
pub hook_event_name: String,
|
||||
pub model: String,
|
||||
#[schemars(schema_with = "permission_mode_schema")]
|
||||
pub permission_mode: String,
|
||||
#[schemars(schema_with = "stop_failure_error_schema")]
|
||||
pub error: String,
|
||||
pub error_details: NullableString,
|
||||
pub last_assistant_message: NullableString,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[schemars(rename = "subagent-stop.command.input")]
|
||||
@@ -678,6 +747,14 @@ pub fn write_schema_fixtures(schema_root: &Path) -> anyhow::Result<()> {
|
||||
&generated_dir.join(STOP_OUTPUT_FIXTURE),
|
||||
schema_json::<StopCommandOutputWire>()?,
|
||||
)?;
|
||||
write_schema(
|
||||
&generated_dir.join(STOP_FAILURE_INPUT_FIXTURE),
|
||||
schema_json::<StopFailureCommandInput>()?,
|
||||
)?;
|
||||
write_schema(
|
||||
&generated_dir.join(STOP_FAILURE_OUTPUT_FIXTURE),
|
||||
schema_json::<StopFailureCommandOutputWire>()?,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -773,6 +850,22 @@ fn stop_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema {
|
||||
string_const_schema("Stop")
|
||||
}
|
||||
|
||||
fn stop_failure_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema {
|
||||
string_const_schema("StopFailure")
|
||||
}
|
||||
|
||||
fn stop_failure_error_schema(_gen: &mut SchemaGenerator) -> Schema {
|
||||
string_enum_schema(&[
|
||||
"rate_limit",
|
||||
"overloaded",
|
||||
"authentication_failed",
|
||||
"billing_error",
|
||||
"invalid_request",
|
||||
"server_error",
|
||||
"unknown",
|
||||
])
|
||||
}
|
||||
|
||||
fn permission_mode_schema(_gen: &mut SchemaGenerator) -> Schema {
|
||||
string_enum_schema(&[
|
||||
"default",
|
||||
@@ -841,6 +934,8 @@ mod tests {
|
||||
use super::PreToolUseCommandOutputWire;
|
||||
use super::SESSION_START_INPUT_FIXTURE;
|
||||
use super::SESSION_START_OUTPUT_FIXTURE;
|
||||
use super::STOP_FAILURE_INPUT_FIXTURE;
|
||||
use super::STOP_FAILURE_OUTPUT_FIXTURE;
|
||||
use super::STOP_INPUT_FIXTURE;
|
||||
use super::STOP_OUTPUT_FIXTURE;
|
||||
use super::SUBAGENT_START_INPUT_FIXTURE;
|
||||
@@ -849,6 +944,8 @@ mod tests {
|
||||
use super::SUBAGENT_STOP_OUTPUT_FIXTURE;
|
||||
use super::SessionStartCommandOutputWire;
|
||||
use super::StopCommandInput;
|
||||
use super::StopFailureCommandInput;
|
||||
use super::StopFailureCommandOutputWire;
|
||||
use super::SubagentCommandInputFields;
|
||||
use super::SubagentStartCommandInput;
|
||||
use super::SubagentStartCommandOutputWire;
|
||||
@@ -928,6 +1025,12 @@ mod tests {
|
||||
STOP_OUTPUT_FIXTURE => {
|
||||
include_str!("../schema/generated/stop.command.output.schema.json")
|
||||
}
|
||||
STOP_FAILURE_INPUT_FIXTURE => {
|
||||
include_str!("../schema/generated/stop-failure.command.input.schema.json")
|
||||
}
|
||||
STOP_FAILURE_OUTPUT_FIXTURE => {
|
||||
include_str!("../schema/generated/stop-failure.command.output.schema.json")
|
||||
}
|
||||
_ => panic!("unexpected fixture name: {name}"),
|
||||
}
|
||||
}
|
||||
@@ -977,6 +1080,8 @@ mod tests {
|
||||
SUBAGENT_STOP_OUTPUT_FIXTURE,
|
||||
STOP_INPUT_FIXTURE,
|
||||
STOP_OUTPUT_FIXTURE,
|
||||
STOP_FAILURE_INPUT_FIXTURE,
|
||||
STOP_FAILURE_OUTPUT_FIXTURE,
|
||||
] {
|
||||
let expected = normalize_newlines(expected_fixture(fixture));
|
||||
let actual = std::fs::read_to_string(schema_root.join("generated").join(fixture))
|
||||
@@ -1012,6 +1117,10 @@ mod tests {
|
||||
"UserPromptSubmitHookSpecificOutputWire",
|
||||
"UserPromptSubmit",
|
||||
);
|
||||
assert_output_hook_event_name_const::<StopFailureCommandOutputWire>(
|
||||
"StopFailureHookSpecificOutputWire",
|
||||
"StopFailure",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1059,6 +1168,10 @@ mod tests {
|
||||
&schema_json::<StopCommandInput>().expect("serialize stop input schema"),
|
||||
)
|
||||
.expect("parse stop input schema");
|
||||
let stop_failure: Value = serde_json::from_slice(
|
||||
&schema_json::<StopFailureCommandInput>().expect("serialize stop failure input schema"),
|
||||
)
|
||||
.expect("parse stop failure input schema");
|
||||
|
||||
for schema in [
|
||||
&pre_tool_use,
|
||||
@@ -1070,6 +1183,7 @@ mod tests {
|
||||
&subagent_start,
|
||||
&subagent_stop,
|
||||
&stop,
|
||||
&stop_failure,
|
||||
] {
|
||||
assert_eq!(schema["properties"]["turn_id"]["type"], "string");
|
||||
assert!(
|
||||
|
||||
@@ -1419,6 +1419,7 @@ pub enum HookEventName {
|
||||
SubagentStart,
|
||||
SubagentStop,
|
||||
Stop,
|
||||
StopFailure,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
|
||||
|
||||
@@ -739,6 +739,7 @@ fn event_label(event_name: HookEventName) -> &'static str {
|
||||
HookEventName::SubagentStart => "SubagentStart",
|
||||
HookEventName::SubagentStop => "SubagentStop",
|
||||
HookEventName::Stop => "Stop",
|
||||
HookEventName::StopFailure => "StopFailure",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -754,6 +755,7 @@ fn event_description(event_name: HookEventName) -> &'static str {
|
||||
HookEventName::SubagentStart => "When a subagent is created",
|
||||
HookEventName::SubagentStop => "Right before a subagent ends its turn",
|
||||
HookEventName::Stop => "Right before Codex ends its turn",
|
||||
HookEventName::StopFailure => "When a turn ends because of an API error",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -17,5 +17,6 @@ expression: "render_lines(&view, 112)"
|
||||
SubagentStart 0 0 When a subagent is created
|
||||
SubagentStop 0 0 Right before a subagent ends its turn
|
||||
Stop 0 0 Right before Codex ends its turn
|
||||
StopFailure 0 0 When a turn ends because of an API error
|
||||
|
||||
Press enter to view hooks; esc to close
|
||||
|
||||
+1
@@ -21,5 +21,6 @@ expression: "render_lines(&view, 112)"
|
||||
SubagentStart 0 0 When a subagent is created
|
||||
SubagentStop 0 0 Right before a subagent ends its turn
|
||||
Stop 0 0 Right before Codex ends its turn
|
||||
StopFailure 0 0 When a turn ends because of an API error
|
||||
|
||||
Press enter to view hooks; esc to close
|
||||
|
||||
+1
@@ -19,5 +19,6 @@ expression: "render_lines(&view, 112)"
|
||||
SubagentStart 0 0 0 When a subagent is created
|
||||
SubagentStop 0 0 0 Right before a subagent ends its turn
|
||||
Stop 0 0 0 Right before Codex ends its turn
|
||||
StopFailure 0 0 0 When a turn ends because of an API error
|
||||
|
||||
Press t to trust all; enter to review hooks; esc to close
|
||||
|
||||
+1
@@ -20,5 +20,6 @@ expression: popup
|
||||
SubagentStart 0 0 When a subagent is created
|
||||
SubagentStop 0 0 Right before a subagent ends its turn
|
||||
Stop 0 0 Right before Codex ends its turn
|
||||
StopFailure 0 0 When a turn ends because of an API error
|
||||
|
||||
Press enter to view hooks; esc to close
|
||||
|
||||
@@ -1612,5 +1612,6 @@ fn hook_event_label(event_name: codex_app_server_protocol::HookEventName) -> &'s
|
||||
codex_app_server_protocol::HookEventName::SubagentStart => "SubagentStart",
|
||||
codex_app_server_protocol::HookEventName::SubagentStop => "SubagentStop",
|
||||
codex_app_server_protocol::HookEventName::Stop => "Stop",
|
||||
codex_app_server_protocol::HookEventName::StopFailure => "StopFailure",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -734,6 +734,7 @@ fn hook_event_label(event_name: HookEventName) -> &'static str {
|
||||
HookEventName::SubagentStart => "SubagentStart",
|
||||
HookEventName::SubagentStop => "SubagentStop",
|
||||
HookEventName::Stop => "Stop",
|
||||
HookEventName::StopFailure => "StopFailure",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user