Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ fn map_hook_handler_to_api(handler: CoreHookHandlerConfig) -> ConfiguredHookHand
r#async,
status_message,
},
CoreHookHandlerConfig::Prompt {} => ConfiguredHookHandler::Prompt {},
CoreHookHandlerConfig::Prompt { .. } => ConfiguredHookHandler::Prompt {},
CoreHookHandlerConfig::Agent {} => ConfiguredHookHandler::Agent {},
}
}
Expand Down
12 changes: 11 additions & 1 deletion codex-rs/config/src/hook_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,17 @@ pub enum HookHandlerConfig {
status_message: Option<String>,
},
#[serde(rename = "prompt")]
Prompt {},
Prompt {
prompt: String,
Comment thread
abhinav-oai marked this conversation as resolved.
Comment thread
abhinav-oai marked this conversation as resolved.
#[serde(default)]
model: Option<String>,
#[serde(default, rename = "timeout", alias = "timeoutSec")]
timeout_sec: Option<u64>,
#[serde(default, rename = "statusMessage")]
status_message: Option<String>,
#[serde(default, rename = "continueOnBlock")]
continue_on_block: bool,
},
#[serde(rename = "agent")]
Agent {},
}
Expand Down
22 changes: 22 additions & 0 deletions codex-rs/core/config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,27 @@
},
{
"properties": {
"continueOnBlock": {
"default": false,
"type": "boolean"
},
"model": {
"default": null,
"type": "string"
},
"prompt": {
"type": "string"
},
"statusMessage": {
"default": null,
"type": "string"
},
"timeout": {
"default": null,
"format": "uint64",
"minimum": 0.0,
"type": "integer"
},
"type": {
"enum": [
"prompt"
Expand All @@ -1218,6 +1239,7 @@
}
},
"required": [
"prompt",
"type"
],
"type": "object"
Expand Down
21 changes: 18 additions & 3 deletions codex-rs/core/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ pub struct ModelClient {
pub struct ModelClientSession {
client: ModelClient,
websocket_session: WebsocketSession,
cache_websocket_session_on_drop: bool,
/// Turn state for sticky routing.
///
/// This is an `OnceLock` that stores the turn state value received from the server
Expand Down Expand Up @@ -480,6 +481,18 @@ impl ModelClient {
ModelClientSession {
client: self.clone(),
websocket_session: self.take_cached_websocket_session(),
cache_websocket_session_on_drop: true,
turn_state: Arc::new(OnceLock::new()),
}
}

/// Creates a fresh streaming session that does not read or write the session's cached
/// WebSocket state.
pub(crate) fn new_isolated_session(&self) -> ModelClientSession {

@abhinav-oai abhinav-oai Jun 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A normal ModelClientSession checks out the main session’s cached WebSocket state and writes its latest request/response back on drop

If a hook used that path, it could replace the continuation state for the real transcript. Starting fresh here and not caching on drop keeps hook inference from disturbing the next main turn.

ModelClientSession {
client: self.clone(),
websocket_session: WebsocketSession::default(),
cache_websocket_session_on_drop: false,
turn_state: Arc::new(OnceLock::new()),
}
}
Expand Down Expand Up @@ -1107,9 +1120,11 @@ impl ModelClient {

impl Drop for ModelClientSession {
fn drop(&mut self) {
let websocket_session = std::mem::take(&mut self.websocket_session);
self.client
.store_cached_websocket_session(websocket_session);
if self.cache_websocket_session_on_drop {
let websocket_session = std::mem::take(&mut self.websocket_session);
self.client
.store_cached_websocket_session(websocket_session);
}
}
}

Expand Down
19 changes: 19 additions & 0 deletions codex-rs/core/src/client_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use super::ModelClient;
use super::PendingUnauthorizedRetry;
use super::Prompt;
use super::UnauthorizedRecoveryExecution;
use super::WebsocketSession;
use super::X_CODEX_INSTALLATION_ID_HEADER;
use super::X_CODEX_PARENT_THREAD_ID_HEADER;
use super::X_CODEX_TURN_METADATA_HEADER;
Expand Down Expand Up @@ -276,6 +277,24 @@ fn test_model_info() -> ModelInfo {
.expect("deserialize test model info")
}

#[test]
fn isolated_session_does_not_touch_cached_websocket_state() {
let model_client = test_model_client(SessionSource::Cli);
let cached_websocket_session = WebsocketSession::default();
cached_websocket_session.set_connection_reused(/*connection_reused*/ true);
model_client.store_cached_websocket_session(cached_websocket_session);

let isolated_session = model_client.new_isolated_session();
assert!(!isolated_session.websocket_session.connection_reused());
drop(isolated_session);

assert!(
model_client
.take_cached_websocket_session()
.connection_reused()
);
}

fn test_session_telemetry() -> SessionTelemetry {
SessionTelemetry::new(
ThreadId::new(),
Expand Down
168 changes: 168 additions & 0 deletions codex-rs/core/src/hook_prompt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
use std::sync::Arc;

use codex_hooks::PromptHookRequest;
use codex_hooks::PromptHookRunner;
use codex_models_manager::ModelsManagerConfig;
use codex_models_manager::manager::SharedModelsManager;
use codex_otel::SessionTelemetry;
use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig;
use codex_protocol::models::BaseInstructions;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_rollout_trace::InferenceTraceContext;
use futures::StreamExt;
use serde_json::json;

use crate::client::ModelClient;
use crate::client_common::Prompt;
use crate::client_common::ResponseEvent;
use crate::config::Config;
use crate::responses_metadata::CodexResponsesMetadata;
use crate::stream_events_utils::raw_assistant_output_text_from_item;

const PROMPT_HOOK_BASE_INSTRUCTIONS: &str = r#"You evaluate a Codex prompt hook.

The user message contains:
1. The hook author's instructions.
2. The hook input JSON.

Decide whether the hook input satisfies the hook author's instructions.

Return only JSON:
{"ok": true}
or
{"ok": false, "reason": "concise actionable reason"}

Use ok:false only when the hook criteria fail. Do not answer the user's task. Do not include Markdown or extra text."#;

pub(crate) fn build_prompt_hook_runner(
model_client: ModelClient,
models_manager: SharedModelsManager,
config: &Config,
session_telemetry: SessionTelemetry,
service_tier: Option<String>,
responses_metadata: CodexResponsesMetadata,
) -> PromptHookRunner {
let models_manager_config = config.to_models_manager_config();
PromptHookRunner::new(move |request| {
let model_client = model_client.clone();
let models_manager = Arc::clone(&models_manager);
let models_manager_config = models_manager_config.clone();
let session_telemetry = session_telemetry.clone();
let service_tier = service_tier.clone();
let responses_metadata = responses_metadata.clone();
async move {
run_prompt_hook(
model_client,
models_manager,
models_manager_config,
session_telemetry,
service_tier,
responses_metadata,
request,
)
.await
}
})
}

/// Run the hook as an isolated model request: resolve the configured model,
/// send the rendered hook prompt as the only user message, disable all
/// tools and reasoning summaries, and constrain the final answer to the
/// small `{ ok, reason }` contract that `codex-hooks` maps back into existing
/// hook output semantics.
async fn run_prompt_hook(
model_client: ModelClient,
models_manager: SharedModelsManager,
models_manager_config: ModelsManagerConfig,
session_telemetry: SessionTelemetry,
service_tier: Option<String>,
responses_metadata: CodexResponsesMetadata,
request: PromptHookRequest,
) -> anyhow::Result<String> {
let model_info = models_manager
.get_model_info(request.model.as_str(), &models_manager_config)
.await;
let prompt = Prompt {
input: vec![ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: request.prompt,
Comment thread
abhinav-oai marked this conversation as resolved.
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}],
tools: Vec::new(),
parallel_tool_calls: false,
base_instructions: BaseInstructions {
text: PROMPT_HOOK_BASE_INSTRUCTIONS.to_string(),
},
output_schema: Some(prompt_hook_output_schema()),
output_schema_strict: false,
};

let disabled_trace = InferenceTraceContext::disabled();
let mut client_session = model_client.new_isolated_session();
let mut stream = client_session
.stream(
&prompt,
&model_info,
&session_telemetry,
/*effort*/ None,
ReasoningSummaryConfig::None,
service_tier,
&responses_metadata,
&disabled_trace,
)
.await?;
let mut delta_text = String::new();
let mut item_texts = Vec::new();
while let Some(event) = stream.next().await {
match event? {
ResponseEvent::OutputItemDone(item) => {
if let Some(text) = raw_assistant_output_text_from_item(&item) {
item_texts.push(text);
}
}
ResponseEvent::OutputTextDelta(delta) => delta_text.push_str(delta.as_str()),
ResponseEvent::Completed { .. } => break,
ResponseEvent::Created
| ResponseEvent::SafetyBuffering(_)
| ResponseEvent::TurnModerationMetadata(_)
| ResponseEvent::ReasoningSummaryDone { .. }
| ResponseEvent::OutputItemAdded(_)
| ResponseEvent::ServerModel(_)
| ResponseEvent::ModelVerifications(_)
| ResponseEvent::ServerReasoningIncluded(_)
| ResponseEvent::ToolCallInputDelta { .. }
| ResponseEvent::ReasoningSummaryDelta { .. }
| ResponseEvent::ReasoningContentDelta { .. }
| ResponseEvent::ReasoningSummaryPartAdded { .. }
| ResponseEvent::RateLimits(_)
| ResponseEvent::ModelsEtag(_) => {}
}
}

if item_texts.is_empty() {
Ok(delta_text)
} else {
Ok(item_texts.join(""))
}
}

fn prompt_hook_output_schema() -> serde_json::Value {
json!({
"type": "object",
"properties": {
"ok": {
"type": "boolean"
},
"reason": {
"type": "string"
}
},
"required": ["ok"],
"additionalProperties": false
})
}
30 changes: 25 additions & 5 deletions codex-rs/core/src/hook_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::time::Duration;
use codex_analytics::CompactionTrigger;
use codex_analytics::HookRunFact;
use codex_analytics::build_track_events_context;
use codex_hooks::Hooks;
use codex_hooks::PermissionRequestDecision;
use codex_hooks::PermissionRequestOutcome;
use codex_hooks::PermissionRequestRequest;
Expand Down Expand Up @@ -42,6 +43,7 @@ use tracing::instrument;
use crate::context::ContextualUserFragment;
use crate::context::HookAdditionalContext;
use crate::event_mapping::parse_turn_item;
use crate::responses_metadata::CodexResponsesRequestKind;
use crate::session::TurnInput;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
Expand Down Expand Up @@ -99,6 +101,24 @@ impl From<UserPromptSubmitOutcome> for ContextInjectingHookOutcome {
}
}

async fn hooks_with_prompt_runner(sess: &Arc<Session>, turn_context: &Arc<TurnContext>) -> Hooks {
let responses_metadata = turn_context.turn_metadata_state.to_responses_metadata(
sess.installation_id.clone(),
sess.current_window_id().await,
CodexResponsesRequestKind::Turn,
);
let prompt_hook_runner = crate::hook_prompt::build_prompt_hook_runner(
sess.services.model_client.clone(),
Arc::clone(&sess.services.models_manager),
turn_context.config.as_ref(),
turn_context.session_telemetry.clone(),
turn_context.config.service_tier.clone(),
responses_metadata,
);
sess.hooks()
.clone_with_prompt_hook_runner(prompt_hook_runner)
}

#[instrument(level = "trace", skip_all)]
pub(crate) async fn run_pending_session_start_hooks(
sess: &Arc<Session>,
Expand Down Expand Up @@ -181,7 +201,7 @@ pub(crate) async fn run_pre_tool_use_hooks(
tool_use_id,
tool_input: tool_input.clone(),
};
let hooks = sess.hooks();
let hooks = hooks_with_prompt_runner(sess, turn_context).await;
let preview_runs = hooks.preview_pre_tool_use(&request);
emit_hook_started_events(sess, turn_context, preview_runs).await;

Expand Down Expand Up @@ -242,7 +262,7 @@ pub(crate) async fn run_permission_request_hooks(
run_id_suffix: run_id_suffix.to_string(),
tool_input: payload.tool_input,
};
let hooks = sess.hooks();
let hooks = hooks_with_prompt_runner(sess, turn_context).await;
let preview_runs = hooks.preview_permission_request(&request);
emit_hook_started_events(sess, turn_context, preview_runs).await;

Expand Down Expand Up @@ -285,7 +305,7 @@ pub(crate) async fn run_post_tool_use_hooks(
tool_input,
tool_response,
};
let hooks = sess.hooks();
let hooks = hooks_with_prompt_runner(sess, turn_context).await;
let preview_runs = hooks.preview_post_tool_use(&request);
emit_hook_started_events(sess, turn_context, preview_runs).await;

Expand Down Expand Up @@ -357,7 +377,7 @@ pub(crate) async fn run_turn_stop_hooks(
last_assistant_message,
target,
};
let hooks = sess.hooks();
let hooks = hooks_with_prompt_runner(sess, turn_context).await;
emit_hook_started_events(sess, turn_context, hooks.preview_stop(&request)).await;

let mut outcome = hooks.run_stop(request).await;
Expand Down Expand Up @@ -515,7 +535,7 @@ pub(crate) async fn inspect_pending_input(
permission_mode: hook_permission_mode(turn_context),
prompt: UserMessageItem::new(content).message(),
};
let hooks = sess.hooks();
let hooks = hooks_with_prompt_runner(sess, turn_context).await;
let preview_runs = hooks.preview_user_prompt_submit(&request);
run_context_injecting_hook(
sess,
Expand Down
Loading
Loading