Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "history-notes",
crate_name = "codex_history_notes_extension",
)

View File

@@ -0,0 +1,37 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-history-notes-extension"
version.workspace = true
[lib]
name = "codex_history_notes_extension"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
codex-analytics = { workspace = true }
codex-client = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
codex-http-client = { workspace = true }
codex-login = { workspace = true }
codex-model-provider = { workspace = true }
codex-protocol = { workspace = true }
codex-tools = { workspace = true }
codex-utils-output-truncation = { workspace = true }
http = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
codex-config = { workspace = true }
codex-model-provider-info = { workspace = true }
core_test_support = { workspace = true }
insta = { workspace = true }
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,114 @@
use std::time::Duration;
use codex_client::HttpTransport;
use codex_client::RequestBody;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_login::default_client::create_transport_for_routes_async;
use codex_model_provider::SharedModelProvider;
use codex_utils_output_truncation::TruncationPolicy;
use http::HeaderValue;
use http::Method;
use serde_json::Value;
use serde_json::json;
const HISTORY_NOTES_BACKEND_TIMEOUT: Duration = Duration::from_secs(35);
const ENCRYPTED_TOOL_ARGUMENTS_HEADER: &str = "x-openai-encrypted-tool-arguments";
const TOOL_OUTPUT_TRUNCATION_POLICY_HEADER: &str = "x-openai-tool-output-truncation-policy";
const OPERATION_ERROR_PREFIX: &str = "Unable to perform operation:";
#[derive(Clone)]
pub(crate) struct HistoryNotesBackend {
provider: SharedModelProvider,
http_client_factory: HttpClientFactory,
}
impl HistoryNotesBackend {
pub(crate) fn new(
provider: SharedModelProvider,
http_client_factory: HttpClientFactory,
) -> Self {
Self {
provider,
http_client_factory,
}
}
pub(crate) async fn call(
&self,
path: &str,
session_id: &str,
current_agent_name: &str,
mut arguments: Value,
truncation_policy: TruncationPolicy,
) -> Result<Value, String> {
let Some(arguments_object) = arguments.as_object_mut() else {
return Err("History tool arguments must be a JSON object".to_string());
};
arguments_object.insert(
"context".to_string(),
json!({
"session_id": session_id,
"current_agent_name": current_agent_name,
}),
);
let setup = codex_model_provider::resolve_request(
self.provider.as_ref(),
/*scope*/ None,
/*routing*/ None,
self.http_client_factory.clone(),
)
.await
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} Could not prepare the backend request."))?;
let mut request = setup.api_provider.build_request(Method::POST, path);
let encoded_truncation_policy =
serde_json::to_string(&truncation_policy).map_err(|_| {
format!("{OPERATION_ERROR_PREFIX} Could not encode the output truncation policy.")
})?;
request.headers.insert(
TOOL_OUTPUT_TRUNCATION_POLICY_HEADER,
HeaderValue::from_str(&encoded_truncation_policy).map_err(|_| {
format!(
"{OPERATION_ERROR_PREFIX} Could not construct the output truncation policy header."
)
})?,
);
if matches!(
path,
"alpha/history/v2/search_contents"
| "alpha/notes/v2/search_contents"
| "alpha/notes/v2/append_to_file"
| "alpha/notes/v2/write_file"
) {
request.headers.insert(
ENCRYPTED_TOOL_ARGUMENTS_HEADER,
HeaderValue::from_static("true"),
);
}
request.body = Some(RequestBody::Json(arguments));
request.timeout = Some(HISTORY_NOTES_BACKEND_TIMEOUT);
let request = setup.api_auth.apply_auth(request).await.map_err(|_| {
format!("{OPERATION_ERROR_PREFIX} Could not apply backend authentication.")
})?;
let transport = create_transport_for_routes_async(
setup.http_client_factory,
ClientRouteClass::Api,
setup.redirect_policy,
)
.await
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} The backend request failed."))?;
let response = transport
.execute(request)
.await
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} The backend request failed."))?;
serde_json::from_slice(&response.body)
.map_err(|_| format!("{OPERATION_ERROR_PREFIX} The backend returned invalid JSON."))
}
}
#[cfg(test)]
#[path = "backend_tests.rs"]
mod tests;

View File

@@ -0,0 +1,147 @@
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_login::AuthHeaders;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_model_provider::create_model_provider;
use codex_model_provider_info::ModelProviderInfo;
use codex_utils_output_truncation::TruncationPolicy;
use http::HeaderMap;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::ENCRYPTED_TOOL_ARGUMENTS_HEADER;
use super::HistoryNotesBackend;
#[tokio::test]
async fn routes_through_codex_backend_and_injects_trusted_session_agent_context() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/backend-api/codex/alpha/notes/v2/read_file"))
.and(header("x-openai-actor-authorization", "actor-biscuit"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"encrypted_output": "enc_payload"
})))
.mount(&server)
.await;
let mut headers = HeaderMap::new();
headers.insert(
"x-openai-actor-authorization",
HeaderValue::from_static("actor-biscuit"),
);
let auth_manager =
AuthManager::from_auth_for_testing(CodexAuth::Headers(AuthHeaders::new(headers)));
let provider = create_model_provider(
ModelProviderInfo::create_openai_provider(Some(format!(
"{}/backend-api/codex",
server.uri()
))),
Some(auth_manager),
);
let backend = HistoryNotesBackend::new(
provider,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let response = backend
.call(
"alpha/notes/v2/read_file",
"session-123",
"/root/worker",
json!({
"path": "notes.md",
"context": {
"session_id": "spoofed-session",
"current_agent_name": "/root/spoofed",
}
}),
TruncationPolicy::Bytes(1024),
)
.await
.expect("History request should succeed");
assert_eq!(response, json!({"encrypted_output": "enc_payload"}));
let requests = server.received_requests().await.expect("recorded requests");
assert_eq!(requests.len(), 1);
assert!(
requests[0]
.headers
.get(ENCRYPTED_TOOL_ARGUMENTS_HEADER)
.is_none()
);
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&requests[0].body).expect("JSON body"),
json!({
"path": "notes.md",
"context": {
"session_id": "session-123",
"current_agent_name": "/root/worker",
}
})
);
}
#[tokio::test]
async fn marks_encrypted_history_and_notes_arguments_without_changing_the_json_body() {
let server = MockServer::start().await;
let cases = [
(
"history/v2/search_contents",
json!({"query": "encrypted-query"}),
),
(
"notes/v2/search_contents",
json!({"query": "encrypted-query"}),
),
(
"notes/v2/append_to_file",
json!({"path": "notes.md", "text": "encrypted-text"}),
),
(
"notes/v2/write_file",
json!({"path": "notes.md", "text": "encrypted-text"}),
),
];
for (route, _) in &cases {
Mock::given(method("POST"))
.and(path(format!("/backend-api/codex/alpha/{route}")))
.and(header(ENCRYPTED_TOOL_ARGUMENTS_HEADER, "true"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
.expect(1)
.mount(&server)
.await;
}
let auth_manager =
AuthManager::from_auth_for_testing(CodexAuth::Headers(AuthHeaders::new(HeaderMap::new())));
let backend = HistoryNotesBackend::new(
create_model_provider(
ModelProviderInfo::create_openai_provider(Some(format!(
"{}/backend-api/codex",
server.uri()
))),
Some(auth_manager),
),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
for (route, arguments) in cases {
backend
.call(
&format!("alpha/{route}"),
"session-123",
"/root",
arguments.clone(),
TruncationPolicy::Bytes(1024),
)
.await
.expect("encrypted argument request should succeed");
}
}

View File

@@ -0,0 +1,233 @@
use std::sync::Arc;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::ThreadHintStatus;
use codex_analytics::ThreadHintStatusEvent;
use codex_core::config::Config;
use codex_extension_api::ConfigContributor;
use codex_extension_api::ContentItemKind;
use codex_extension_api::ContextContributor;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::PromptFragment;
use codex_extension_api::PromptSlot;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadStartInput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolContributor;
use codex_extension_api::ToolExecutor;
use codex_login::AuthManager;
use codex_protocol::AgentPath;
use codex_protocol::openai_models::HistoryToolMessages;
use codex_protocol::openai_models::NotesToolMessages;
use codex_utils_output_truncation::TruncationPolicy;
use serde_json::json;
use crate::backend::HistoryNotesBackend;
use crate::tools::HistoryNotesAction;
use crate::tools::HistoryNotesTool;
// Bound model context even when note paths are unusually long.
const MAX_THREAD_HINT_BYTES: usize = 4_000;
struct HistoryNotesExtension {
auth_manager: Arc<AuthManager>,
}
struct HistoryNotesExtensionConfig {
backend: HistoryNotesBackend,
}
struct HistoryNotesAgentIdentity {
agent_name: String,
}
impl HistoryNotesExtension {
fn update_config(&self, thread_store: &ExtensionData, config: &Config) {
let auth = thread_store
.get::<codex_model_provider::ProviderAuthContext>()
.unwrap_or_else(|| {
Arc::new(codex_model_provider::ProviderAuthContext {
credentials: Arc::clone(&self.auth_manager),
runtime_auth: None,
})
});
if config
.token_budget
.as_ref()
.is_some_and(|token_budget| token_budget.use_history_notes_extension)
&& config.model_provider.is_openai()
&& auth.credentials.current_auth_uses_codex_backend()
{
thread_store.insert(HistoryNotesExtensionConfig {
backend: HistoryNotesBackend::new(
auth.model_provider(config.model_provider.clone()),
config.http_client_factory(),
),
});
} else {
thread_store.remove::<HistoryNotesExtensionConfig>();
}
}
}
impl ThreadLifecycleContributor<Config> for HistoryNotesExtension {
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let agent_name = input
.session_source
.get_agent_path()
.unwrap_or_else(AgentPath::root)
.to_string();
input
.thread_store
.insert(HistoryNotesAgentIdentity { agent_name });
self.update_config(input.thread_store, input.config);
})
}
}
impl ConfigContributor<Config> for HistoryNotesExtension {
fn on_config_changed(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
_previous_config: &Config,
new_config: &Config,
) {
self.update_config(thread_store, new_config);
}
}
impl ContextContributor for HistoryNotesExtension {
fn contribute_thread_context<'a>(
&'a self,
session_store: &'a ExtensionData,
thread_store: &'a ExtensionData,
) -> ExtensionFuture<'a, Vec<PromptFragment>> {
Box::pin(async move {
let Some(config) = thread_store.get::<HistoryNotesExtensionConfig>() else {
return Vec::new();
};
let Some(identity) = thread_store.get::<HistoryNotesAgentIdentity>() else {
return Vec::new();
};
let track_status = |status| {
if let Some(analytics) = session_store.get::<AnalyticsEventsClient>() {
analytics.track_thread_hint_status(ThreadHintStatusEvent {
thread_id: thread_store.level_id().to_string(),
status,
occurred_at_ms: codex_analytics::now_unix_millis(),
});
}
};
let Ok(result) = config
.backend
.call(
"alpha/notes/v2/thread_hint",
session_store.level_id(),
&identity.agent_name,
json!({}),
TruncationPolicy::Bytes(MAX_THREAD_HINT_BYTES),
)
.await
else {
track_status(ThreadHintStatus::Failed);
return Vec::new();
};
let Some(text) = result.get("text").and_then(serde_json::Value::as_str) else {
track_status(ThreadHintStatus::Failed);
return Vec::new();
};
if text.len() > MAX_THREAD_HINT_BYTES {
track_status(ThreadHintStatus::Failed);
return Vec::new();
}
track_status(ThreadHintStatus::Succeeded);
if text.is_empty() {
return Vec::new();
}
vec![PromptFragment::tool(
PromptSlot::ContextWindow,
text,
ContentItemKind("notes.thread_hint".to_string()),
"notes".to_string(),
)]
})
}
}
impl ToolContributor for HistoryNotesExtension {
fn tools(
&self,
session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
self.tools_with_messages(
session_store,
thread_store,
/*history_messages*/ None,
/*notes_messages*/ None,
)
}
fn tools_for_step(
&self,
session_store: &ExtensionData,
thread_store: &ExtensionData,
step_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
let history_messages = step_store.get::<HistoryToolMessages>();
let notes_messages = step_store.get::<NotesToolMessages>();
self.tools_with_messages(
session_store,
thread_store,
history_messages.as_deref(),
notes_messages.as_deref(),
)
}
}
impl HistoryNotesExtension {
fn tools_with_messages(
&self,
session_store: &ExtensionData,
thread_store: &ExtensionData,
history_messages: Option<&HistoryToolMessages>,
notes_messages: Option<&NotesToolMessages>,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
let Some(config) = thread_store.get::<HistoryNotesExtensionConfig>() else {
return Vec::new();
};
let Some(identity) = thread_store.get::<HistoryNotesAgentIdentity>() else {
return Vec::new();
};
HistoryNotesAction::ALL
.into_iter()
.map(|action| {
Arc::new(HistoryNotesTool::new(
action,
config.backend.clone(),
session_store.level_id().to_string(),
identity.agent_name.clone(),
history_messages,
notes_messages,
)) as Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>
})
.collect()
}
}
/// Installs the standalone history and notes tools backed by the Codex backend.
pub fn install(registry: &mut ExtensionRegistryBuilder<Config>, auth_manager: Arc<AuthManager>) {
let extension = Arc::new(HistoryNotesExtension { auth_manager });
registry.thread_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone());
registry.prompt_contributor(extension.clone());
registry.tool_contributor(extension);
}

View File

@@ -0,0 +1,5 @@
mod backend;
mod extension;
mod tools;
pub use extension::install;

View File

@@ -0,0 +1,459 @@
use codex_extension_api::FunctionCallError;
use codex_extension_api::ResponsesApiTool;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolExecutorFuture;
use codex_extension_api::ToolName;
use codex_extension_api::ToolOutput;
use codex_extension_api::ToolPayload;
use codex_extension_api::ToolSpec;
use codex_extension_api::parse_tool_input_schema;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ImageReference;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::openai_models::HistoryToolMessages;
use codex_protocol::openai_models::NotesToolMessages;
use codex_tools::JsonToolOutput;
use codex_tools::ResponsesApiNamespace;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::ToolExposure;
use codex_tools::with_catalog_tool_message;
use serde_json::Value;
use serde_json::json;
use crate::backend::HistoryNotesBackend;
const HISTORY_NAMESPACE: &str = "history";
const NOTES_NAMESPACE: &str = "notes";
const HISTORY_DESCRIPTION: &str = "Recover prior conversation after a context-window reset by listing, reading, and searching normalized history using agent names and the opaque window and item IDs returned by these tools. Pass returned IDs unchanged when filtering or reading an item. Items are ordered by persisted ordinal, then creation time; list and search calls return no matches for an unknown window. Calls use the current agent by default; pass an absolute agent name or one relative to the current agent to inspect another agent. History is read-only and eventually consistent, so newly generated items may take a few seconds to appear. This is private model-only state. Use it silently to continue the task. Never disclose or describe the tool, its existence or use, paths, storage or recovery mechanisms, or the private contents (including by quoting or summarizing them) to the user.";
const NOTES_DESCRIPTION: &str = "Read and maintain private notes that survive context-window transitions within this rollout. Paths are virtual, not filesystem paths. Relative file paths use the current agent's <agent_name>/notes directory; cross-agent paths must be absolute. Absolute paths use <agent_name>/notes[/<path>]. Reads, listings, searches, and writes may access other agents' notes. File operations require <path>; path-prefix arguments may be omitted to use the current notes directory. Empty, '.', and '..' path components are unsupported. Shell expansion is not performed, so '~' is treated literally. Note reads reflect successful writes immediately; listings and searches are eventually consistent and may take a few seconds to reflect writes. Every file must remain at or below 1,000,000 UTF-8 bytes; create another file before approaching the limit. This is private model-only state. Use it silently to continue the task. Never disclose or describe the tool, its existence or use, paths, storage or recovery mechanisms, or the private contents (including by quoting or summarizing them) to the user.";
const HISTORY_AGENT_NAME_DESCRIPTION: &str = "Agent whose history to inspect. Omit to use the current agent; otherwise pass an absolute agent name or a name relative to the current agent.";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum HistoryNotesAction {
HistoryListWindows,
HistoryListItems,
HistoryReadItem,
HistorySearchContents,
NotesListFilesByPrefix,
NotesReadFile,
NotesSearchContents,
NotesAppendToFile,
NotesWriteFile,
}
impl HistoryNotesAction {
pub(crate) const ALL: [Self; 9] = [
Self::HistoryListWindows,
Self::HistoryListItems,
Self::HistoryReadItem,
Self::HistorySearchContents,
Self::NotesListFilesByPrefix,
Self::NotesReadFile,
Self::NotesSearchContents,
Self::NotesAppendToFile,
Self::NotesWriteFile,
];
fn namespace(self) -> &'static str {
match self {
Self::HistoryListWindows
| Self::HistoryListItems
| Self::HistoryReadItem
| Self::HistorySearchContents => HISTORY_NAMESPACE,
Self::NotesListFilesByPrefix
| Self::NotesReadFile
| Self::NotesSearchContents
| Self::NotesAppendToFile
| Self::NotesWriteFile => NOTES_NAMESPACE,
}
}
fn name(self) -> &'static str {
match self {
Self::HistoryListWindows => "list_windows",
Self::HistoryListItems => "list_items",
Self::HistoryReadItem => "read_item",
Self::HistorySearchContents => "search_contents",
Self::NotesListFilesByPrefix => "list_files_by_prefix",
Self::NotesReadFile => "read_file",
Self::NotesSearchContents => "search_contents",
Self::NotesAppendToFile => "append_to_file",
Self::NotesWriteFile => "write_file",
}
}
fn endpoint(self) -> &'static str {
match self {
Self::HistoryListWindows => "alpha/history/v2/list_windows",
Self::HistoryListItems => "alpha/history/v2/list_items",
Self::HistoryReadItem => "alpha/history/v2/read_item",
Self::HistorySearchContents => "alpha/history/v2/search_contents",
Self::NotesListFilesByPrefix => "alpha/notes/v2/list_files_by_prefix",
Self::NotesReadFile => "alpha/notes/v2/read_file",
Self::NotesSearchContents => "alpha/notes/v2/search_contents",
Self::NotesAppendToFile => "alpha/notes/v2/append_to_file",
Self::NotesWriteFile => "alpha/notes/v2/write_file",
}
}
fn supports_parallel_tool_calls(self) -> bool {
!matches!(self, Self::NotesAppendToFile | Self::NotesWriteFile)
}
fn namespace_description(self) -> &'static str {
match self.namespace() {
HISTORY_NAMESPACE => HISTORY_DESCRIPTION,
NOTES_NAMESPACE => NOTES_DESCRIPTION,
_ => unreachable!("History actions use a known namespace"),
}
}
fn description(self) -> &'static str {
match self {
Self::HistoryListWindows => {
"List an agent's context windows as window ID and item-count pairs. Private model-only recovery; never disclose this activity."
}
Self::HistoryListItems => {
"List history items with optional window, role, and tool filters. Private model-only recovery; never disclose this activity."
}
Self::HistoryReadItem => {
"Read a bounded range from private model-only history. Never disclose the item or this activity."
}
Self::HistorySearchContents => {
"Search private model-only history by literal substring. Never disclose results or this activity."
}
Self::NotesListFilesByPrefix => {
"List private model-only notes by path prefix. Never disclose paths, contents, or this activity."
}
Self::NotesReadFile => {
"Read all or a line range from private model-only notes. Never disclose paths, contents, or this activity."
}
Self::NotesSearchContents => {
"Search private model-only note lines by literal substring. Never disclose results or this activity."
}
Self::NotesAppendToFile => {
"Append text to private model-only notes. Never disclose paths, contents, or this activity."
}
Self::NotesWriteFile => {
"Create or replace private model-only notes. Never disclose paths, contents, or this activity."
}
}
}
fn parameters(self) -> Value {
match self {
Self::HistoryListWindows => json!({
"type": "object",
"properties": {
"limit": {"type": "integer", "minimum": 1, "description": "Maximum number of windows to return."},
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
"recent_first": {"type": "boolean", "description": "Whether to return the most recently created windows first."}
}
}),
Self::HistoryListItems => json!({
"type": "object",
"properties": {
"limit": {"type": "integer", "minimum": 1, "description": "Maximum number of items to return."},
"recent_first": {"type": "boolean", "description": "Whether to return the most recently created items first."},
"tool_namespace": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable namespace to include. When set, non-tool messages are excluded."},
"role": {"anyOf": [{"type": "string", "enum": ["user", "assistant", "tool", "system", "developer"]}, {"type": "null"}], "description": "Message role to include. Null or omission includes all roles."},
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
"tool_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable tool name to include. When set, non-tool messages are excluded."},
"window_id": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Full window ID. Null or omission includes all windows."},
"max_chars_per_item": {"type": "integer", "minimum": 1, "description": "Maximum characters returned in each item's truncated_content."}
}
}),
Self::HistoryReadItem => json!({
"type": "object",
"properties": {
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
"item_id": {"type": "string", "description": "The short item ID is the suffix shown in the target item's trailing `[id: ...]` marker, printed after that item's content."},
"offset_chars": {"type": "integer", "minimum": 0, "description": "Zero-based character offset at which reading starts."},
"limit_chars": {"type": "integer", "minimum": 1, "description": "Maximum number of characters to return."},
"window_id": {"type": "string", "description": "Full window ID containing the item."}
},
"required": ["item_id", "window_id"]
}),
Self::HistorySearchContents => json!({
"type": "object",
"properties": {
"limit": {"type": "integer", "minimum": 1, "description": "Maximum number of matching items to return."},
"query": {"type": "string", "encrypted": true, "description": "Case-sensitive literal substring to find in item content."},
"recent_first": {"type": "boolean", "description": "Whether to return the most recently created matches first."},
"tool_namespace": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable namespace to include. When set, non-tool messages are excluded."},
"role": {"anyOf": [{"type": "string", "enum": ["user", "assistant", "tool", "system", "developer"]}, {"type": "null"}], "description": "Message role to include. Null or omission includes all roles."},
"agent_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": HISTORY_AGENT_NAME_DESCRIPTION},
"tool_name": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Callable tool name to include. When set, non-tool messages are excluded."},
"window_id": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Full window ID. Null or omission includes all windows."}
},
"required": ["query"]
}),
Self::NotesListFilesByPrefix => json!({
"type": "object",
"properties": {
"prefix": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Note path prefix to list."},
"max_results": {"type": "integer", "minimum": 1, "description": "Maximum number of files to return."},
"file_order_by": {"type": "string", "enum": ["name", "created_at", "updated_at"], "description": "Field used to order files."},
"file_order": {"type": "string", "enum": ["ascending", "descending"], "description": "Direction used to order files."}
}
}),
Self::NotesReadFile => json!({
"type": "object",
"properties": {
"path": {"type": "string", "description": "Note file path to read."},
"start_line": {"anyOf": [{"type": "integer"}, {"type": "null"}], "description": "First line to return, inclusive and 1-based. Negative values count backward from the final line."},
"stop_line": {"anyOf": [{"type": "integer"}, {"type": "null"}], "description": "Last line to return, inclusive and 1-based. Negative values count backward from the final line."}
},
"required": ["path"]
}),
Self::NotesSearchContents => json!({
"type": "object",
"properties": {
"max_matches_per_file": {"type": "integer", "minimum": 1, "description": "Maximum number of matching lines returned per file."},
"query": {"type": "string", "encrypted": true, "description": "Case-sensitive literal substring to find in note lines."},
"recent_file_first": {"type": "boolean", "description": "Whether to order matching files by creation time, newest first."},
"max_files": {"type": "integer", "minimum": 1, "description": "Maximum number of matching files returned."},
"path_prefix": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Note path prefix to search."}
},
"required": ["query"]
}),
Self::NotesAppendToFile => json!({
"type": "object",
"properties": {
"text": {"type": "string", "encrypted": true, "description": "Text appended exactly as provided."},
"path": {"type": "string", "description": "Note file path to append to."}
},
"required": ["text", "path"]
}),
Self::NotesWriteFile => json!({
"type": "object",
"properties": {
"text": {"type": "string", "encrypted": true, "description": "Complete replacement text for the file."},
"path": {"type": "string", "description": "Note file path to create or replace."}
},
"required": ["text", "path"]
}),
}
}
fn spec(
self,
history_messages: Option<&HistoryToolMessages>,
notes_messages: Option<&NotesToolMessages>,
) -> ToolSpec {
let (namespace_description, tool_message) = match self {
Self::HistoryListWindows => history_messages
.map(|messages| (&messages.namespace_description, &messages.list_windows)),
Self::HistoryListItems => history_messages
.map(|messages| (&messages.namespace_description, &messages.list_items)),
Self::HistoryReadItem => history_messages
.map(|messages| (&messages.namespace_description, &messages.read_item)),
Self::HistorySearchContents => history_messages
.map(|messages| (&messages.namespace_description, &messages.search_contents)),
Self::NotesListFilesByPrefix => notes_messages.map(|messages| {
(
&messages.namespace_description,
&messages.list_files_by_prefix,
)
}),
Self::NotesReadFile => notes_messages
.map(|messages| (&messages.namespace_description, &messages.read_file)),
Self::NotesSearchContents => notes_messages
.map(|messages| (&messages.namespace_description, &messages.search_contents)),
Self::NotesAppendToFile => notes_messages
.map(|messages| (&messages.namespace_description, &messages.append_to_file)),
Self::NotesWriteFile => notes_messages
.map(|messages| (&messages.namespace_description, &messages.write_file)),
}
.map_or((None, None), |(namespace_description, tool_message)| {
(namespace_description.as_deref(), tool_message.as_ref())
});
let tool = with_catalog_tool_message(
ResponsesApiTool {
name: self.name().to_string(),
description: self.description().to_string(),
strict: false,
parameters: parse_tool_input_schema(&self.parameters()).unwrap_or_else(|error| {
panic!("History tool input schema should parse: {error}")
}),
output_schema: None,
defer_loading: None,
},
tool_message,
);
ToolSpec::Namespace(ResponsesApiNamespace {
name: self.namespace().to_string(),
description: namespace_description
.unwrap_or(self.namespace_description())
.to_string(),
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
})
}
}
pub(crate) struct HistoryNotesTool {
action: HistoryNotesAction,
backend: HistoryNotesBackend,
session_id: String,
current_agent_name: String,
spec: ToolSpec,
}
impl HistoryNotesTool {
pub(crate) fn new(
action: HistoryNotesAction,
backend: HistoryNotesBackend,
session_id: String,
current_agent_name: String,
history_messages: Option<&HistoryToolMessages>,
notes_messages: Option<&NotesToolMessages>,
) -> Self {
Self {
action,
backend,
session_id,
current_agent_name,
spec: action.spec(history_messages, notes_messages),
}
}
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let arguments = call.function_arguments()?;
let arguments = if arguments.trim().is_empty() {
json!({})
} else {
serde_json::from_str(arguments)
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?
};
let result = self
.backend
.call(
self.action.endpoint(),
&self.session_id,
&self.current_agent_name,
arguments,
call.truncation_policy,
)
.await
.map_err(FunctionCallError::RespondToModel)?;
Ok(Box::new(HistoryNotesToolOutput::new(result)?))
}
}
impl<'call> ToolExecutor<ToolCall<'call>> for HistoryNotesTool {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(self.action.namespace(), self.action.name())
}
fn spec(&self) -> ToolSpec {
self.spec.clone()
}
fn exposure(&self) -> ToolExposure {
ToolExposure::DirectModelOnly
}
fn supports_parallel_tool_calls(&self) -> bool {
self.action.supports_parallel_tool_calls()
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
struct HistoryNotesToolOutput {
result: Value,
output: FunctionCallOutputPayload,
}
impl HistoryNotesToolOutput {
fn new(mut result: Value) -> Result<Self, FunctionCallError> {
// Separate attachments before serializing any text or retaining log output.
let images = result.as_object_mut().and_then(|map| map.remove("images"));
// The server applies the requested output budget before encryption.
let mut output = match result.get("encrypted_output").and_then(Value::as_str) {
Some(encrypted_content) => FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::EncryptedContent {
encrypted_content: encrypted_content.to_string(),
},
]),
None => FunctionCallOutputPayload::from_text(result.to_string()),
};
if let Some(images) = images {
let invalid_image = || {
FunctionCallError::RespondToModel(
"History backend returned invalid image content.".to_string(),
)
};
let images = images.as_array().ok_or_else(invalid_image)?;
let mut content = match output.body {
FunctionCallOutputBody::Text(text) => {
vec![FunctionCallOutputContentItem::InputText { text }]
}
FunctionCallOutputBody::ContentItems(content) => content,
};
for image in images {
let data = image
.get("data")
.and_then(Value::as_str)
.ok_or_else(invalid_image)?;
let mime_type = image
.get("mime_type")
.and_then(Value::as_str)
.ok_or_else(invalid_image)?;
let detail =
serde_json::from_value(image.get("detail").cloned().unwrap_or(Value::Null))
.map_err(|_| invalid_image())?;
content.push(FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: format!("data:{mime_type};base64,{data}"),
},
detail,
});
}
output = FunctionCallOutputPayload::from_content_items(content);
}
Ok(Self { result, output })
}
}
impl ToolOutput for HistoryNotesToolOutput {
fn log_output(&self) -> String {
JsonToolOutput::new(self.result.clone()).log_output()
}
fn success_for_logging(&self) -> bool {
true
}
fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<Value> {
// Hooks must not receive model-only image attachments.
Some(self.result.clone())
}
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: self.output.clone(),
}
}
fn code_mode_result(&self, _payload: &ToolPayload) -> Value {
Value::String("History tools are unavailable in code mode.".to_string())
}
}
#[cfg(test)]
#[path = "tools_tests.rs"]
mod tests;

View File

@@ -0,0 +1,181 @@
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ImageDetail;
use codex_protocol::models::ImageReference;
use codex_protocol::models::ResponseInputItem;
use codex_tools::ToolOutput;
use codex_tools::ToolPayload;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::HistoryNotesToolOutput;
#[test]
fn preserves_encrypted_history_output() {
let result = HistoryNotesToolOutput::new(json!({"encrypted_output": "enc_payload"}))
.expect("valid output")
.to_response_item(
"call-1",
&ToolPayload::Function {
arguments: "{}".to_string(),
},
);
let ResponseInputItem::FunctionCallOutput { output, .. } = result else {
panic!("expected function-call output");
};
assert_eq!(
output.content_items(),
Some(
[FunctionCallOutputContentItem::EncryptedContent {
encrypted_content: "enc_payload".to_string(),
}]
.as_slice()
)
);
}
#[test]
fn preserves_images_as_separate_output_items_without_logging_bytes() {
let output = HistoryNotesToolOutput::new(json!({
"encrypted_output": "enc_payload",
"images": [
{"data": "cG5n", "mime_type": "image/png", "detail": "original"},
{"data": "anBlZw==", "mime_type": "image/jpeg", "detail": "low"},
{"data": "Z2lm", "mime_type": "image/gif"},
{"data": "d2VicA==", "mime_type": "image/webp", "detail": null}
]
}))
.expect("valid image output");
assert_eq!(
output.log_output(),
json!({"encrypted_output": "enc_payload"}).to_string()
);
assert_eq!(
output.post_tool_use_response(
"call-1",
&ToolPayload::Function {
arguments: "{}".to_string()
}
),
Some(json!({"encrypted_output": "enc_payload"}))
);
assert_eq!(
output.to_response_item(
"call-1",
&ToolPayload::Function {
arguments: "{}".to_string()
}
),
ResponseInputItem::FunctionCallOutput {
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::EncryptedContent {
encrypted_content: "enc_payload".to_string()
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,cG5n".to_string()
},
detail: Some(ImageDetail::Original)
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/jpeg;base64,anBlZw==".to_string()
},
detail: Some(ImageDetail::Low)
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/gif;base64,Z2lm".to_string()
},
detail: None
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/webp;base64,d2VicA==".to_string()
},
detail: None
},
])
}
);
}
#[test]
fn accepts_empty_attachments_and_legacy_plaintext_results() {
for (result, expected) in [
(
json!({"encrypted_output": "enc_payload", "images": []}),
FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::EncryptedContent {
encrypted_content: "enc_payload".to_string(),
},
]),
),
(
json!({"text": "legacy result"}),
FunctionCallOutputPayload::from_text(json!({"text": "legacy result"}).to_string()),
),
] {
let output = HistoryNotesToolOutput::new(result).expect("valid output");
assert_eq!(
output.to_response_item(
"call-1",
&ToolPayload::Function {
arguments: "{}".to_string()
}
),
ResponseInputItem::FunctionCallOutput {
call_id: "call-1".to_string(),
output: expected
}
);
}
}
#[test]
fn rejects_malformed_attachments_instead_of_silently_dropping_them() {
for images in [
json!(null),
json!({}),
json!([null]),
json!([{"mime_type": "image/png"}]),
json!([{"data": "private-image-bytes"}]),
json!([{"data": "private-image-bytes", "mime_type": "image/png", "detail": "invalid"}]),
] {
let result = HistoryNotesToolOutput::new(
json!({"encrypted_output": "enc_payload", "images": images}),
);
let Err(codex_extension_api::FunctionCallError::RespondToModel(message)) = result else {
panic!("expected a model-facing image error");
};
assert_eq!(message, "History backend returned invalid image content.");
}
}
#[test]
fn sparse_catalog_messages_preserve_defaults_and_explicit_empty_descriptions() {
let action = super::HistoryNotesAction::NotesReadFile;
let mut expected = action.spec(/*history_messages*/ None, /*notes_messages*/ None);
let codex_tools::ToolSpec::Namespace(namespace) = &mut expected else {
panic!("expected namespace");
};
namespace.description.clear();
let codex_tools::ResponsesApiNamespaceTool::Function(tool) = &mut namespace.tools[0] else {
panic!("expected function");
};
tool.description.clear();
let messages = codex_protocol::openai_models::NotesToolMessages {
namespace_description: Some(String::new()),
read_file: Some(codex_protocol::openai_models::ToolMessage {
description: Some(String::new()),
parameters: Some(String::new()),
}),
..Default::default()
};
assert_eq!(
action.spec(/*history_messages*/ None, Some(&messages)),
expected
);
}

View File

@@ -0,0 +1,505 @@
use std::sync::Arc;
use codex_config::LoaderOverrides;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
use codex_core::config::TokenBudgetConfig;
use codex_extension_api::ContentItemKind;
use codex_extension_api::ConversationHistory;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::NoopTurnItemEmitter;
use codex_extension_api::PromptFragment;
use codex_extension_api::PromptSlot;
use codex_extension_api::ThreadStartInput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolCallSource;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolName;
use codex_extension_api::ToolPayload;
use codex_history_notes_extension::install;
use codex_http_client::DestinationPolicy;
use codex_http_client::NetworkPolicyController;
use codex_login::AuthHeaders;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_model_provider_info::ModelProviderInfo;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::openai_models::NotesToolMessages;
use codex_protocol::openai_models::ToolMessage;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::TruncationPolicy;
use http::HeaderMap;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
type TestResult = Result<(), Box<dyn std::error::Error>>;
const THREAD_HINT: &str = "Recent notes (up to 5, most-recent first):\n- /root/worker/notes/latest.md (2 lines, 14 UTF-8 bytes)";
#[tokio::test]
async fn installed_extension_exposes_and_invokes_history_notes_tools() -> TestResult {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/backend-api/codex/alpha/notes/v2/read_file"))
.and(header("x-openai-actor-authorization", "actor-biscuit"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"encrypted_output": "enc_payload"
})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/backend-api/codex/alpha/notes/v2/thread_hint"))
.and(header("x-openai-actor-authorization", "actor-biscuit"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"text": THREAD_HINT})))
.mount(&server)
.await;
let codex_home = TempDir::new()?;
let mut config = ConfigBuilder::default()
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.codex_home(codex_home.path().to_path_buf())
.build()
.await?;
config.model_provider.base_url = Some(format!("{}/backend-api/codex", server.uri()));
config.token_budget = Some(TokenBudgetConfig {
use_history_notes_extension: true,
..TokenBudgetConfig::default()
});
let controller = NetworkPolicyController::default();
config.application_network_policy = controller.policy();
assert!(controller.publish(
controller.policy().revision(),
DestinationPolicy::Unrestricted
));
let mut headers = HeaderMap::new();
headers.insert(
"x-openai-actor-authorization",
HeaderValue::from_static("actor-biscuit"),
);
let auth_manager =
AuthManager::from_auth_for_testing(CodexAuth::Headers(AuthHeaders::new(headers)));
let mut builder = ExtensionRegistryBuilder::<Config>::new();
install(&mut builder, auth_manager);
let registry = builder.build();
let session_store = ExtensionData::new("session-123");
let thread_store = ExtensionData::new("thread-123");
let session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: ThreadId::new(),
depth: 1,
agent_path: Some(AgentPath::root().join("worker").expect("agent path")),
agent_nickname: None,
agent_role: None,
});
for contributor in registry.thread_lifecycle_contributors() {
contributor
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &session_source,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
}
let tools = exposed_tools(&registry, &session_store, &thread_store);
assert_eq!(
tools
.iter()
.map(|tool| tool.tool_name())
.collect::<Vec<_>>(),
vec![
ToolName::namespaced("history", "list_windows"),
ToolName::namespaced("history", "list_items"),
ToolName::namespaced("history", "read_item"),
ToolName::namespaced("history", "search_contents"),
ToolName::namespaced("notes", "list_files_by_prefix"),
ToolName::namespaced("notes", "read_file"),
ToolName::namespaced("notes", "search_contents"),
ToolName::namespaced("notes", "append_to_file"),
ToolName::namespaced("notes", "write_file"),
]
);
// Existing executors retain the catalog snapshot selected for their step.
let step_store = ExtensionData::new("step-1");
let mut messages = NotesToolMessages {
read_file: Some(ToolMessage {
description: Some("Catalog read instructions".to_string()),
..Default::default()
}),
..Default::default()
};
step_store.insert(messages.clone());
let catalog_tools =
registry.tool_contributors()[0].tools_for_step(&session_store, &thread_store, &step_store);
let captured_tool = catalog_tools
.iter()
.find(|tool| tool.tool_name() == ToolName::namespaced("notes", "read_file"))
.expect("notes.read_file should be exposed");
let captured_spec = captured_tool.spec();
messages.read_file.as_mut().expect("read_file").description = Some(String::new());
step_store.insert(messages);
let next_tools =
registry.tool_contributors()[0].tools_for_step(&session_store, &thread_store, &step_store);
assert_ne!(
next_tools
.iter()
.find(|tool| tool.tool_name() == ToolName::namespaced("notes", "read_file"))
.expect("notes.read_file should be exposed")
.spec(),
captured_spec
);
assert_eq!(captured_tool.spec(), captured_spec);
let read_file = tools
.iter()
.find(|tool| tool.tool_name() == ToolName::namespaced("notes", "read_file"))
.expect("notes.read_file should be exposed");
let call = tool_call(
ToolName::namespaced("notes", "read_file"),
json!({"path": "notes.md"}),
);
let output = read_file.handle(call.clone()).await?;
let ResponseInputItem::FunctionCallOutput { output, .. } =
output.to_response_item(&call.call_id, &call.payload)
else {
panic!("expected function-call output");
};
assert_eq!(
output.content_items(),
Some(
[FunctionCallOutputContentItem::EncryptedContent {
encrypted_content: "enc_payload".to_string(),
}]
.as_slice()
)
);
let hints = registry.context_contributors()[0]
.contribute_thread_context(&session_store, &thread_store)
.await;
assert_eq!(
hints,
vec![PromptFragment::tool(
PromptSlot::ContextWindow,
THREAD_HINT,
ContentItemKind("notes.thread_hint".to_string()),
"notes".to_string(),
)]
);
let requests = server.received_requests().await.expect("recorded requests");
assert_eq!(requests.len(), 2);
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&requests[0].body)?,
json!({
"path": "notes.md",
"context": {
"session_id": "session-123",
"current_agent_name": "/root/worker",
}
})
);
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&requests[1].body)?,
json!({
"context": {
"session_id": "session-123",
"current_agent_name": "/root/worker",
}
})
);
for (namespace, name, mut arguments) in [
("history", "list_windows", json!({"limit": 101})),
("history", "list_items", json!({})),
(
"history",
"list_items",
json!({"limit": 21, "max_chars_per_item": 4_000}),
),
(
"history",
"read_item",
json!({"window_id": "window", "item_id": "item", "limit_chars": 20_001}),
),
(
"history",
"search_contents",
json!({"query": "x".repeat(1_001), "limit": 21}),
),
("history", "search_contents", json!({"query": ""})),
("notes", "list_files_by_prefix", json!({"max_results": 101})),
(
"notes",
"search_contents",
json!({"query": "x".repeat(1_001), "max_files": 21, "max_matches_per_file": 11}),
),
("notes", "search_contents", json!({"query": ""})),
(
"notes",
"read_file",
json!({"path": "notes.md", "start_line": -2}),
),
(
"notes",
"append_to_file",
json!({"path": "notes.md", "text": "append"}),
),
(
"notes",
"write_file",
json!({"path": "notes.md", "text": "replace"}),
),
] {
server.reset().await;
let mut response = json!({"encrypted_output": "enc_history"});
let mut expected_output =
vec![json!({"type": "encrypted_content", "encrypted_content": "enc_history"})];
if namespace == "history" && name == "read_item" {
// Images are not part of the text budget sent to the backend.
let data = "cG5n".repeat(1_000);
response["images"] = json!([
{"data": data, "mime_type": "image/png", "detail": "original"},
{"data": "anBlZw==", "mime_type": "image/jpeg", "detail": "high"}
]);
expected_output.extend([
json!({"type": "input_image", "image_url": format!("data:image/png;base64,{data}"), "detail": "original"}),
json!({"type": "input_image", "image_url": "data:image/jpeg;base64,anBlZw==", "detail": "high"})
]);
}
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/codex/alpha/{namespace}/v2/{name}"
)))
.and(header("x-openai-actor-authorization", "actor-biscuit"))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.mount(&server)
.await;
let tool_name = ToolName::namespaced(namespace, name);
let tool = tools
.iter()
.find(|tool| tool.tool_name() == tool_name)
.expect("exposed tool");
let call = tool_call(tool_name, arguments.clone());
let output = tool.handle(call.clone()).await?;
assert_eq!(
serde_json::to_value(output.to_response_item(&call.call_id, &call.payload))?,
json!({"type": "function_call_output", "call_id": call.call_id, "output": expected_output})
);
arguments["context"] = json!({
"session_id": "session-123",
"current_agent_name": "/root/worker",
});
let requests = server.received_requests().await.expect("recorded requests");
for request in &requests {
assert_eq!(
serde_json::from_str::<serde_json::Value>(
request
.headers
.get("x-openai-tool-output-truncation-policy")
.expect("truncation policy header")
.to_str()?
)?,
json!({"mode": "bytes", "limit": 1024})
);
}
assert_eq!(
requests
.iter()
.map(|request| serde_json::from_slice::<serde_json::Value>(&request.body))
.collect::<Result<Vec<_>, _>>()?,
vec![arguments]
);
}
// Plaintext backend responses must keep attachments out of text and logs too.
server.reset().await;
let text_result = json!({"content": "look: [image 1]", "n_chars": 15, "next_offset_chars": 15});
let mut response = text_result.clone();
response["images"] = json!([
{"data": "cG5n", "mime_type": "image/png", "detail": "original"}
]);
Mock::given(method("POST"))
.and(path("/backend-api/codex/alpha/history/v2/read_item"))
.and(header("x-openai-actor-authorization", "actor-biscuit"))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.mount(&server)
.await;
let tool_name = ToolName::namespaced("history", "read_item");
let read_item = tools
.iter()
.find(|tool| tool.tool_name() == tool_name)
.expect("history.read_item");
let call = tool_call(tool_name, json!({"window_id": "window", "item_id": "item"}));
let output = read_item.handle(call.clone()).await?;
assert_eq!(output.log_output(), text_result.to_string());
assert_eq!(
serde_json::to_value(output.to_response_item(&call.call_id, &call.payload))?,
json!({
"type": "function_call_output",
"call_id": call.call_id,
"output": [
{"type": "input_text", "text": text_result.to_string()},
{"type": "input_image", "image_url": "data:image/png;base64,cG5n", "detail": "original"}
]
})
);
for result in [
json!({"text": ""}),
json!({"text": "x".repeat(4_001)}),
json!({"encrypted_output": "old-backend-hint"}),
] {
server.reset().await;
Mock::given(method("POST"))
.and(path("/backend-api/codex/alpha/notes/v2/thread_hint"))
.respond_with(ResponseTemplate::new(200).set_body_json(result))
.mount(&server)
.await;
assert!(
registry.context_contributors()[0]
.contribute_thread_context(&session_store, &thread_store)
.await
.is_empty()
);
}
server.reset().await;
assert!(controller.publish(
controller.policy().revision(),
DestinationPolicy::Restricted {
allowed_hosts: Default::default(),
},
));
assert!(
registry.context_contributors()[0]
.contribute_thread_context(&session_store, &thread_store)
.await
.is_empty()
);
assert!(
server
.received_requests()
.await
.expect("recorded requests")
.is_empty()
);
let mut disabled_config = config.clone();
disabled_config.token_budget = None;
for contributor in registry.config_contributors() {
contributor.on_config_changed(&session_store, &thread_store, &config, &disabled_config);
}
assert!(exposed_tools(&registry, &session_store, &thread_store).is_empty());
assert!(
registry.context_contributors()[0]
.contribute_thread_context(&session_store, &thread_store)
.await
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn history_notes_require_an_openai_provider_and_codex_backend_auth() -> TestResult {
let codex_home = TempDir::new()?;
let mut config = ConfigBuilder::default()
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.codex_home(codex_home.path().to_path_buf())
.build()
.await?;
config.token_budget = Some(TokenBudgetConfig {
use_history_notes_extension: true,
..TokenBudgetConfig::default()
});
for (provider, auth) in [
(
config.model_provider.clone(),
CodexAuth::from_api_key("test-api-key"),
),
(
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
),
] {
config.model_provider = provider;
let mut builder = ExtensionRegistryBuilder::<Config>::new();
install(&mut builder, AuthManager::from_auth_for_testing(auth));
let registry = builder.build();
let session_store = ExtensionData::new("session-123");
let thread_store = ExtensionData::new("thread-123");
for contributor in registry.thread_lifecycle_contributors() {
contributor
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
}
assert!(exposed_tools(&registry, &session_store, &thread_store).is_empty());
}
Ok(())
}
fn exposed_tools(
registry: &ExtensionRegistry<Config>,
session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
registry
.tool_contributors()
.iter()
.flat_map(|contributor| contributor.tools(session_store, thread_store))
.collect()
}
fn tool_call(tool_name: ToolName, arguments: serde_json::Value) -> ToolCall<'static> {
ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-read-file".to_string(),
tool_name,
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: codex_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: ToolPayload::Function {
arguments: arguments.to_string(),
},
}
}

View File

@@ -0,0 +1,175 @@
//! Verify captured catalog definitions and history attachments reach outgoing model requests.
use std::collections::BTreeMap;
use std::sync::Arc;
use codex_core::config::Config;
use codex_core::config::TokenBudgetConfig;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_history_notes_extension::install;
use codex_login::AuthHeaders;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::responses;
use core_test_support::test_codex::test_codex;
use http::HeaderMap;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
const PNG: &str =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=";
const NATIVE_TOOLS: [(&str, &str, &[&str]); 2] = [
(
"history",
"",
&["list_windows", "list_items", "read_item", "search_contents"],
),
(
"notes",
" ",
&[
"list_files_by_prefix",
"read_file",
"search_contents",
"append_to_file",
"write_file",
],
),
];
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn history_images_reach_the_next_model_request() -> Result<(), Box<dyn std::error::Error>> {
let server = responses::start_mock_server().await;
Mock::given(method("POST"))
.and(path("/v1/alpha/history/v2/read_item"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"encrypted_output": "opaque-history-text",
"images": [
{"data": PNG, "mime_type": "image/png", "detail": "original"},
{"data": PNG, "mime_type": "image/png", "detail": "high"},
{"data": PNG, "mime_type": "image/png", "detail": "auto"}
]
})))
.mount(&server)
.await;
let requests = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_function_call_with_namespace(
"read-history",
"history",
"read_item",
&json!({"window_id": "window", "item_id": "item"}).to_string(),
),
responses::ev_completed("first-response"),
]),
responses::sse(vec![
responses::ev_assistant_message("assistant", "done"),
responses::ev_completed("second-response"),
]),
],
)
.await;
let auth = CodexAuth::Headers(AuthHeaders::new(HeaderMap::new()));
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
install(
&mut extensions,
AuthManager::from_auth_for_testing(auth.clone()),
);
let parameters = json!({
"type": "object", "description": "Catalog read parameters",
"properties": {"window_id": {"type": "string"}, "item_id": {"type": "string"}},
"required": ["window_id", "item_id"]
});
let catalog_parameters = parameters.clone();
let test = test_codex()
.with_auth(auth)
.with_model_info_override("gpt-5.5", move |model_info| {
model_info.supports_experimental_context = true;
let mut messages = json!({});
for (namespace, description, names) in NATIVE_TOOLS {
messages[namespace] = json!({"namespace_description": description});
for name in names {
messages[namespace][*name] =
json!({"description": format!("Catalog {namespace}.{name}")});
}
}
messages["history"]["read_item"]["parameters"] = json!(catalog_parameters.to_string());
model_info.model_messages.get_or_insert_default().tools =
Some(serde_json::from_value(messages).expect("native catalog messages"));
})
.with_extensions(Arc::new(extensions.build()))
.with_config(|config| {
config.model_provider.name = "OpenAI".to_string();
config.token_budget = Some(TokenBudgetConfig {
use_history_notes_extension: true,
..TokenBudgetConfig::default()
});
})
.build_with_auto_env(&server)
.await?;
test.submit_text_turn("Read the image from history.")
.await?;
let requests = requests.requests();
assert_eq!(requests.len(), 2);
for request in &requests {
let body = request.body_json();
for (name, description, tool_names) in NATIVE_TOOLS {
let namespace = body["tools"]
.as_array()
.expect("tools")
.iter()
.find(|tool| tool["name"] == name)
.expect("native namespace");
assert_eq!(namespace["description"], description);
let tools = namespace["tools"].as_array().expect("namespace tools");
assert_eq!(
tools
.iter()
.map(|tool| (
tool["name"].as_str().unwrap(),
tool["description"].as_str().unwrap().to_string(),
))
.collect::<BTreeMap<_, _>>(),
tool_names
.iter()
.map(|tool| (*tool, format!("Catalog {name}.{tool}")))
.collect(),
);
if name == "history" {
assert_eq!(
tools
.iter()
.find(|tool| tool["name"] == "read_item")
.unwrap()["parameters"],
parameters
);
}
}
}
assert_eq!(
requests[1].function_call_output("read-history")["output"],
json!([
{"type": "encrypted_content", "encrypted_content": "opaque-history-text"},
{"type": "input_image", "image_url": format!("data:image/png;base64,{PNG}"), "detail": "original"},
{"type": "input_image", "image_url": format!("data:image/png;base64,{PNG}"), "detail": "original"},
{"type": "input_image", "image_url": format!("data:image/png;base64,{PNG}"), "detail": "original"}
])
);
insta::assert_snapshot!(context_snapshot::format_request_history_snapshot(
"History/Notes catalog definitions preserve empty and whitespace namespace descriptions, and history images reach the next model request.",
&requests,
&ContextSnapshotOptions::default()
.rewrite_known_segments()
.include_request_settings(),
));
Ok(())
}

View File

@@ -0,0 +1,52 @@
---
source: ext/history-notes/tests/image_model_input.rs
expression: "context_snapshot::format_request_history_snapshot(\"History/Notes catalog definitions preserve empty and whitespace namespace descriptions, and history images reach the next model request.\",\n&requests,\n&ContextSnapshotOptions::default().rewrite_known_segments().include_request_settings(),)"
---
Scenario: History/Notes catalog definitions preserve empty and whitespace namespace descriptions, and history images reach the next model request.
## Window 1
Settings:
include: ["reasoning.encrypted_content"]
model: "gpt-5.5"
parallel_tool_calls: true
prompt_cache_key: "<PROMPT_CACHE_KEY 1>"
reasoning: {"effort":"medium"}
store: false
stream: true
text: {"verbosity":"low"}
tool_choice: "auto"
tools (9; hash=8ee44dddbc5ba019):
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
- namespace/history; hash=48578cec2ffd3727
- function/list_items
- function/list_windows
- function/read_item
- function/search_contents
- namespace/notes: ; hash=1984d9e2f2d6c4f0
- function/append_to_file
- function/list_files_by_prefix
- function/read_file
- function/search_contents
- function/write_file
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
- web_search; hash=f103e327c6870a46
-- request 1 (turn) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[2]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<ENVIRONMENT_CONTEXT>
03:message/user:
Read the image from history.
-- request 2 (turn) --
04:function_call/history.read_item:{"item_id":"item","window_id":"window"}
05:function_call_output:<encrypted_content> | <input_image> | <input_image> | <input_image>