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,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
);
}