aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,365 @@
use std::sync::Arc;
use akode_api::AllowedCaller;
use akode_api::ApproximateLocation;
use akode_api::ExternalWebAccess;
use akode_api::ExternalWebAccessMode;
use akode_api::LocationType;
use akode_api::SearchContextSize;
use akode_api::SearchFilters;
use akode_api::SearchSettings;
use akode_core::config::Config;
use akode_extension_api::ConfigContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadOriginator;
use akode_extension_api::ThreadStartInput;
use akode_extension_api::ToolContributor;
use akode_http_client::HttpClientFactory;
use akode_login::AuthManager;
use akode_model_provider_info::ModelProviderInfo;
use akode_protocol::config_types::WebSearchBackendConfig;
use akode_protocol::config_types::WebSearchContextSize;
use akode_protocol::config_types::WebSearchMode;
use akode_protocol::openai_models::ModelInfo;
use crate::schema::LITERATURE_SEARCH_QUERY;
use crate::tool::WebSearchTool;
#[derive(Clone)]
struct WebSearchExtension {
auth_manager: Arc<AuthManager>,
}
#[derive(Clone)]
struct WebSearchExtensionConfig {
/// Client-side backend from `[web_search] backend = ...`; takes precedence.
backend: Option<WebSearchBackendConfig>,
provider_supports_search: bool,
http_client_factory: HttpClientFactory,
provider: ModelProviderInfo,
settings: SearchSettings,
}
impl From<&Config> for WebSearchExtensionConfig {
fn from(config: &Config) -> Self {
Self {
backend: config.web_search_backend.clone(),
// The provider-backed standalone search endpoint is opt-in per provider.
provider_supports_search: config.model_provider.supports_standalone_web_search,
http_client_factory: config.http_client_factory(),
provider: config.model_provider.clone(),
settings: search_settings(config),
}
}
}
fn search_settings(config: &Config) -> SearchSettings {
let web_search_config = config.web_search_config.as_ref();
SearchSettings {
user_location: web_search_config
.and_then(|config| config.user_location.as_ref())
.map(|location| ApproximateLocation {
r#type: LocationType::Approximate,
country: location.country.clone(),
region: location.region.clone(),
city: location.city.clone(),
timezone: location.timezone.clone(),
}),
search_context_size: web_search_config
.and_then(|config| config.search_context_size)
.map(|size| match size {
WebSearchContextSize::Low => SearchContextSize::Low,
WebSearchContextSize::Medium => SearchContextSize::Medium,
WebSearchContextSize::High => SearchContextSize::High,
}),
filters: web_search_config
.and_then(|config| config.filters.as_ref())
.map(|filters| SearchFilters {
allowed_domains: filters.allowed_domains.clone(),
blocked_domains: None,
}),
allowed_callers: Some(vec![AllowedCaller::Direct]),
..Default::default()
}
}
fn external_web_access_for_mode(web_search_mode: WebSearchMode) -> ExternalWebAccess {
match web_search_mode {
WebSearchMode::Disabled | WebSearchMode::Cached => ExternalWebAccess::Boolean(false),
WebSearchMode::Indexed => ExternalWebAccess::Mode(ExternalWebAccessMode::Indexed),
WebSearchMode::Live => ExternalWebAccess::Boolean(true),
}
}
impl ThreadLifecycleContributor<Config> for WebSearchExtension {
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input
.thread_store
.insert(WebSearchExtensionConfig::from(input.config));
})
}
}
impl ConfigContributor<Config> for WebSearchExtension {
fn on_config_changed(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
_previous_config: &Config,
new_config: &Config,
) {
thread_store.insert(WebSearchExtensionConfig::from(new_config));
}
}
impl ToolContributor for WebSearchExtension {
fn tools_for_step(
&self,
session_store: &ExtensionData,
thread_store: &ExtensionData,
step_store: &ExtensionData,
) -> Vec<
Arc<dyn for<'call> akode_extension_api::ToolExecutor<akode_extension_api::ToolCall<'call>>>,
> {
let Some(config) = thread_store.get::<WebSearchExtensionConfig>() else {
return Vec::new();
};
let mode = step_store.get::<WebSearchMode>();
if let Some(backend) = config.backend.as_ref() {
if mode.as_deref() == Some(&WebSearchMode::Disabled) {
return Vec::new();
}
return match crate::searxng::searxng_tools(backend) {
Ok(tools) => tools,
Err(error) => {
tracing::warn!("web search backend unavailable: {error}");
Vec::new()
}
};
}
let Some(mode) = mode else {
return Vec::new();
};
if !config.provider_supports_search || *mode == WebSearchMode::Disabled {
return Vec::new();
}
let auth = thread_store
.get::<akode_model_provider::ProviderAuthContext>()
.unwrap_or_else(|| {
Arc::new(akode_model_provider::ProviderAuthContext {
credentials: Arc::clone(&self.auth_manager),
})
});
vec![Arc::new(WebSearchTool {
session_id: session_store.level_id().to_string(),
http_client_factory: config.http_client_factory.clone(),
provider: auth.model_provider(config.provider.clone()),
settings: SearchSettings {
external_web_access: Some(external_web_access_for_mode(*mode)),
..config.settings.clone()
},
supports_literature_search: step_store.get::<ModelInfo>().is_some_and(|model| {
model
.experimental_supported_tools
.iter()
.any(|tool| tool == LITERATURE_SEARCH_QUERY)
}),
originator: thread_store
.get::<ThreadOriginator>()
.map(|originator| originator.0.clone()),
})]
}
}
pub fn install(registry: &mut ExtensionRegistryBuilder<Config>, auth_manager: Arc<AuthManager>) {
let extension = Arc::new(WebSearchExtension { auth_manager });
registry.thread_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone());
registry.tool_contributor(extension);
}
#[cfg(test)]
mod tests {
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::ToolName;
use akode_http_client::HttpClientFactory;
use akode_http_client::OutboundProxyPolicy;
use akode_login::CodexAuth;
use akode_model_provider_info::ModelProviderInfo;
use pretty_assertions::assert_eq;
use super::AuthManager;
use super::Config;
use super::WebSearchExtensionConfig;
use super::external_web_access_for_mode;
use super::install;
use crate::tool::RUN_TOOL_NAME;
use crate::tool::WEB_NAMESPACE;
use akode_api::ExternalWebAccess;
use akode_api::ExternalWebAccessMode;
use akode_protocol::config_types::WebSearchBackendConfig;
use akode_protocol::config_types::WebSearchMode;
#[test]
fn external_web_access_preserves_legacy_values_until_indexed() {
assert_eq!(
[
WebSearchMode::Disabled,
WebSearchMode::Cached,
WebSearchMode::Indexed,
WebSearchMode::Live,
]
.map(external_web_access_for_mode),
[
ExternalWebAccess::Boolean(false),
ExternalWebAccess::Boolean(false),
ExternalWebAccess::Mode(ExternalWebAccessMode::Indexed),
ExternalWebAccess::Boolean(true),
]
);
}
#[test]
fn installed_extension_contributes_web_run_when_enabled() {
let mut builder = ExtensionRegistryBuilder::<Config>::new();
install(
&mut builder,
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy")),
);
let registry = builder.build();
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("11111111-1111-4111-8111-111111111111");
let step_store = ExtensionData::new("step");
step_store.insert(WebSearchMode::Cached);
thread_store.insert(WebSearchExtensionConfig {
backend: None,
provider_supports_search: true,
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
provider: ModelProviderInfo::create_responses_provider(
"mock",
Some("http://127.0.0.1:9/v1".to_string()),
),
settings: Default::default(),
});
let tool_names = registry
.tool_contributors()
.iter()
.flat_map(|contributor| {
contributor.tools_for_step(&session_store, &thread_store, &step_store)
})
.map(|tool| (tool.tool_name(), tool.supports_parallel_tool_calls()))
.collect::<Vec<_>>();
assert_eq!(
tool_names,
vec![(ToolName::namespaced(WEB_NAMESPACE, RUN_TOOL_NAME), true)]
);
}
fn registry_tool_names(
config: WebSearchExtensionConfig,
mode: Option<WebSearchMode>,
) -> Vec<ToolName> {
let mut builder = ExtensionRegistryBuilder::<Config>::new();
install(
&mut builder,
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy")),
);
let registry = builder.build();
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("11111111-1111-4111-8111-111111111111");
let step_store = ExtensionData::new("step");
if let Some(mode) = mode {
step_store.insert(mode);
}
thread_store.insert(config);
registry
.tool_contributors()
.iter()
.flat_map(|contributor| {
contributor.tools_for_step(&session_store, &thread_store, &step_store)
})
.map(|tool| tool.tool_name())
.collect()
}
fn config_with(
backend: Option<WebSearchBackendConfig>,
provider_supports_search: bool,
) -> WebSearchExtensionConfig {
WebSearchExtensionConfig {
backend,
provider_supports_search,
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
provider: ModelProviderInfo::create_responses_provider(
"mock",
Some("http://127.0.0.1:9/v1".to_string()),
),
settings: Default::default(),
}
}
fn searxng(fetch: bool) -> WebSearchBackendConfig {
WebSearchBackendConfig {
backend: akode_protocol::config_types::WebSearchBackendKind::Searxng,
url: "http://192.168.40.57:8080".to_string(),
max_results: 8,
fetch,
}
}
#[test]
fn searxng_backend_contributes_web_search_and_web_fetch() {
for mode in [None, Some(WebSearchMode::Cached), Some(WebSearchMode::Live)] {
assert_eq!(
registry_tool_names(config_with(Some(searxng(true)), false), mode),
vec![
ToolName::plain(crate::searxng::WEB_SEARCH_TOOL_NAME),
ToolName::plain(crate::searxng::WEB_FETCH_TOOL_NAME),
]
);
}
assert_eq!(
registry_tool_names(config_with(Some(searxng(false)), false), None),
vec![ToolName::plain(crate::searxng::WEB_SEARCH_TOOL_NAME)]
);
}
#[test]
fn no_backend_means_no_web_tools() {
for mode in [None, Some(WebSearchMode::Cached), Some(WebSearchMode::Live)] {
assert_eq!(
registry_tool_names(config_with(None, false), mode),
Vec::new()
);
}
assert_eq!(
registry_tool_names(
config_with(Some(searxng(true)), false),
Some(WebSearchMode::Disabled)
),
Vec::new()
);
}
#[test]
fn searxng_tools_are_plain_function_tools() {
let tools = crate::searxng::searxng_tools(&searxng(true)).expect("tools");
for tool in tools {
let akode_extension_api::ToolSpec::Function(spec) = tool.spec() else {
panic!("expected a function tool");
};
assert!(spec.name == "web_search" || spec.name == "web_fetch");
}
}
}

View File

@@ -0,0 +1,223 @@
use akode_api::SearchInput;
use akode_core::parse_turn_item;
use akode_protocol::items::TurnItem;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ResponseItem;
use akode_protocol::models::plaintext_agent_message_content;
use akode_tools::retain_tail_from_last_n_user_messages;
use akode_tools::truncate_assistant_output_text_to_token_budget;
const ASSISTANT_CONTEXT_TOKEN_LIMIT: usize = 1_000;
const ASSISTANT_ROLE: &str = "assistant";
const USER_ROLE: &str = "user";
/// Builds the conversation tail for standalone web search.
///
/// The tail keeps the previous user text message, up to 1k tokens of assistant
/// text that followed it, and the current user text message.
pub(crate) fn recent_input(items: &[ResponseItem]) -> Option<SearchInput> {
let mut messages = Vec::new();
for item in items {
push_visible_message(&mut messages, item);
}
retain_tail_from_last_n_user_messages(&mut messages, /*user_message_count*/ 2);
truncate_assistant_output_text_to_token_budget(&mut messages, ASSISTANT_CONTEXT_TOKEN_LIMIT);
(!messages.is_empty()).then_some(SearchInput::Items(messages))
}
fn push_visible_message(messages: &mut Vec<ResponseItem>, item: &ResponseItem) {
match item {
ResponseItem::Message { role, .. } if role == ASSISTANT_ROLE => {
let mut message = item.clone();
message.set_id(/*new_id*/ None);
messages.push(message);
}
ResponseItem::AgentMessage {
author,
content,
internal_chat_message_metadata_passthrough: metadata,
..
} => {
if let Some(text) = plaintext_agent_message_content(content) {
messages.push(ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: ASSISTANT_ROLE.to_string(),
content: vec![ContentItem::OutputText {
annotations: None,
logprobs: None,
text: format!("Agent message from {author}:\n{text}"),
}],
phase: None,
internal_chat_message_metadata_passthrough: metadata.clone(),
});
}
}
ResponseItem::Message {
id: _,
role,
content,
phase,
internal_chat_message_metadata_passthrough: metadata,
..
} if role == USER_ROLE
&& matches!(parse_turn_item(item), Some(TurnItem::UserMessage(_))) =>
{
let content = content
.iter()
.filter(|item| matches!(item, ContentItem::InputText { .. }))
.cloned()
.collect::<Vec<_>>();
if !content.is_empty() {
messages.push(ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: role.clone(),
content,
phase: phase.clone(),
internal_chat_message_metadata_passthrough: metadata.clone(),
});
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use akode_api::SearchInput;
use akode_protocol::ResponseItemId;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ImageReference;
use akode_protocol::models::ResponseItem;
use pretty_assertions::assert_eq;
use super::ASSISTANT_ROLE;
use super::USER_ROLE;
use super::recent_input;
fn message(role: &str, text: &str) -> ResponseItem {
ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: role.to_string(),
content: vec![if role == ASSISTANT_ROLE {
ContentItem::OutputText {
annotations: None,
logprobs: None,
text: text.to_string(),
}
} else {
ContentItem::InputText {
text: text.to_string(),
}
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}
}
#[test]
fn keeps_current_user_and_previous_visible_turn() {
let mut previous_user = message(USER_ROLE, "previous user");
previous_user.set_id(Some(ResponseItemId::with_suffix("msg", "previous_user")));
let mut previous_assistant = message(ASSISTANT_ROLE, "previous assistant");
previous_assistant.set_id(Some(ResponseItemId::with_suffix(
"msg",
"previous_assistant",
)));
let items = vec![
message("system", "system"),
message(USER_ROLE, "old user"),
message(ASSISTANT_ROLE, "old assistant"),
previous_user,
ResponseItem::FunctionCall {
status: None,
encrypted_content: None,
id: None,
name: "tool".to_string(),
namespace: None,
arguments: "{}".to_string(),
call_id: "call-1".to_string(),
encrypted_function_args: None,
internal_chat_message_metadata_passthrough: None,
},
previous_assistant,
message("developer", "developer"),
message(USER_ROLE, "current user"),
message(ASSISTANT_ROLE, "current commentary"),
];
assert_eq!(
recent_input(&items),
Some(SearchInput::Items(vec![
message(USER_ROLE, "previous user"),
message(ASSISTANT_ROLE, "previous assistant"),
message(USER_ROLE, "current user"),
]))
);
}
#[test]
fn keeps_only_text_from_recent_user_messages() {
let previous_user = ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: USER_ROLE.to_string(),
content: vec![
ContentItem::InputText {
text: "previous user".to_string(),
},
ContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,image".to_string(),
},
detail: None,
},
],
phase: None,
internal_chat_message_metadata_passthrough: None,
};
let items = vec![
previous_user,
message(ASSISTANT_ROLE, "previous assistant"),
message(USER_ROLE, "current user"),
];
assert_eq!(
recent_input(&items),
Some(SearchInput::Items(vec![
message(USER_ROLE, "previous user"),
message(ASSISTANT_ROLE, "previous assistant"),
message(USER_ROLE, "current user"),
]))
);
}
#[test]
fn ignores_contextual_user_messages_when_selecting_recent_turns() {
let items = vec![
message(USER_ROLE, "previous user"),
message(ASSISTANT_ROLE, "previous assistant"),
message(
USER_ROLE,
"<environment_context>\n<cwd>/tmp</cwd>\n</environment_context>",
),
message(USER_ROLE, "current user"),
];
assert_eq!(
recent_input(&items),
Some(SearchInput::Items(vec![
message(USER_ROLE, "previous user"),
message(ASSISTANT_ROLE, "previous assistant"),
message(USER_ROLE, "current user"),
]))
);
}
}

View File

@@ -0,0 +1,8 @@
mod extension;
mod history;
mod output;
mod schema;
mod searxng;
mod tool;
pub use extension::install;

View File

@@ -0,0 +1,65 @@
use akode_extension_api::ToolOutput;
use akode_extension_api::ToolPayload;
use akode_protocol::models::FunctionCallOutputContentItem;
use akode_protocol::models::FunctionCallOutputPayload;
use akode_protocol::models::ResponseInputItem;
pub(crate) struct SearchOutput {
payload: FunctionCallOutputPayload,
}
impl SearchOutput {
pub(crate) fn new(result: Result<String, String>) -> Self {
let payload = match result {
Ok(text) => FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputText { text },
]),
Err(error) => FunctionCallOutputPayload {
success: Some(false),
..FunctionCallOutputPayload::from_text(error)
},
};
Self { payload }
}
}
impl ToolOutput for SearchOutput {
fn log_output(&self) -> String {
"[standalone web search output]".to_string()
}
fn success_for_logging(&self) -> bool {
self.payload.success.unwrap_or(true)
}
fn contains_external_context(&self) -> bool {
true
}
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: self.payload.clone(),
}
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::SearchOutput;
use super::ToolOutput;
#[test]
fn reports_search_status_for_logging_and_downstream_handling() {
for (result, success) in [
(Ok("found".into()), None),
(Err("failed".into()), Some(false)),
] {
let output = SearchOutput::new(result);
assert_eq!(output.payload.success, success);
assert_eq!(output.success_for_logging(), success.unwrap_or(true));
}
}
}

View File

@@ -0,0 +1,43 @@
use akode_api::SearchCommands;
use schemars::r#gen::SchemaSettings;
use serde_json::Map;
use serde_json::Value;
pub(crate) const LITERATURE_SEARCH_QUERY: &str = "literature_search_query";
pub(crate) fn commands_schema(supports_literature_search: bool) -> Value {
let schema = SchemaSettings::draft2019_09()
.with(|settings| {
settings.inline_subschemas = true;
settings.option_add_null_type = false;
})
.into_generator()
.into_root_schema_for::<SearchCommands>();
let schema = match serde_json::to_value(schema) {
Ok(schema) => schema,
Err(err) => panic!("search commands schema should serialize: {err}"),
};
let Value::Object(mut schema) = schema else {
unreachable!("search commands schema must be an object");
};
if !supports_literature_search
&& let Some(Value::Object(properties)) = schema.get_mut("properties")
{
properties.remove(LITERATURE_SEARCH_QUERY);
}
let mut tool_schema = Map::new();
for key in [
"properties",
"required",
"type",
"additionalProperties",
"$defs",
"definitions",
] {
if let Some(value) = schema.remove(key) {
tool_schema.insert(key.to_string(), value);
}
}
Value::Object(tool_schema)
}

View File

@@ -0,0 +1,281 @@
//! Client-side web tools backed by a SearXNG instance (`[web_search] backend = "searxng"`).
//!
//! `web_search` queries `{url}/search?q=...&format=json` and returns the top results;
//! `web_fetch` downloads a public http(s) page and returns its text. Fetches resolve DNS
//! themselves and refuse private, loopback, link-local and metadata addresses (also after
//! redirects); the configured SearXNG URL is the only private address ever contacted, and
//! only by `web_search`.
use std::collections::BTreeMap;
use std::sync::Arc;
use akode_extension_api::ExtensionTurnItem;
use akode_extension_api::FunctionCallError;
use akode_extension_api::ResponsesApiTool;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolOutput;
use akode_extension_api::ToolSpec;
use akode_extension_items::ExtensionItem;
use akode_extension_items::web_search::WebSearchAction;
use akode_extension_items::web_search::WebSearchItem;
use akode_protocol::config_types::WebSearchBackendConfig;
use akode_protocol::models::WebSearchAction as CoreWebSearchAction;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::WebSearchBeginEvent;
use akode_protocol::protocol::WebSearchEndEvent;
use akode_tools::JsonSchema;
use akode_tools::ToolExposure;
use akode_web_tools::SearxngClient;
use akode_web_tools::SearxngOptions;
use akode_web_tools::WebFetchOptions;
use akode_web_tools::WebFetcher;
use akode_web_tools::format_fetched_page;
use akode_web_tools::format_search_results;
use serde::Deserialize;
use url::Url;
use crate::output::SearchOutput;
pub(crate) const WEB_SEARCH_TOOL_NAME: &str = "web_search";
pub(crate) const WEB_FETCH_TOOL_NAME: &str = "web_fetch";
/// Builds the SearXNG-backed tools for a validated backend configuration.
pub(crate) fn searxng_tools(
config: &WebSearchBackendConfig,
) -> Result<Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>>, String> {
let base_url = Url::parse(&config.url).map_err(|_| "invalid web_search.url".to_string())?;
let client = SearxngClient::new(
base_url,
SearxngOptions {
max_results: config.max_results,
..SearxngOptions::default()
},
)
.map_err(|error| error.to_string())?;
let mut tools: Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> =
vec![Arc::new(SearxngSearchTool {
client: Arc::new(client),
max_results: config.max_results,
})];
if config.fetch {
tools.push(Arc::new(WebFetchTool {
// No private address is allowed for fetches, not even the SearXNG host.
fetcher: Arc::new(WebFetcher::new(WebFetchOptions::default())),
}));
}
Ok(tools)
}
fn function_spec(
name: &str,
description: &str,
properties: BTreeMap<String, JsonSchema>,
required: &[&str],
) -> ToolSpec {
ToolSpec::Function(ResponsesApiTool {
name: name.to_string(),
description: description.to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
properties,
Some(required.iter().map(|name| (*name).to_string()).collect()),
Some(false.into()),
),
output_schema: None,
})
}
fn extension_turn_item(item: WebSearchItem, event: EventMsg) -> ExtensionTurnItem {
ExtensionTurnItem {
item: ExtensionItem::WebSearch(item),
legacy_events: vec![event],
}
}
async fn emit_started(call: &ToolCall<'_>) {
call.turn_item_emitter
.emit_started(extension_turn_item(
WebSearchItem {
id: call.call_id.clone(),
query: String::new(),
action: None,
results: None,
},
EventMsg::WebSearchBegin(WebSearchBeginEvent {
call_id: call.call_id.clone(),
}),
))
.await;
}
async fn emit_completed(
call: &ToolCall<'_>,
query: String,
action: WebSearchAction,
legacy_action: CoreWebSearchAction,
) {
call.turn_item_emitter
.emit_completed(extension_turn_item(
WebSearchItem {
id: call.call_id.clone(),
query: query.clone(),
action: Some(action),
results: None,
},
EventMsg::WebSearchEnd(WebSearchEndEvent {
call_id: call.call_id.clone(),
query,
action: legacy_action,
results: None,
}),
))
.await;
}
fn parse_args<'a, T: Deserialize<'a>>(arguments: &'a str) -> Result<T, FunctionCallError> {
serde_json::from_str(arguments)
.map_err(|error| FunctionCallError::RespondToModel(format!("invalid arguments: {error}")))
}
#[derive(Deserialize)]
struct SearchArgs {
query: String,
#[serde(default)]
max_results: Option<usize>,
}
pub(crate) struct SearxngSearchTool {
client: Arc<SearxngClient>,
max_results: usize,
}
impl<'call> ToolExecutor<ToolCall<'call>> for SearxngSearchTool {
fn tool_name(&self) -> ToolName {
ToolName::plain(WEB_SEARCH_TOOL_NAME)
}
fn spec(&self) -> ToolSpec {
function_spec(
WEB_SEARCH_TOOL_NAME,
"Search the web. Returns the top results with title, URL and snippet. Use web_fetch to read a result page.",
BTreeMap::from([
(
"query".to_string(),
JsonSchema::string(Some("The search query.".to_string())),
),
(
"max_results".to_string(),
JsonSchema::integer(Some(format!(
"Number of results to return (default {}).",
self.max_results
))),
),
]),
&["query"],
)
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let args: SearchArgs = parse_args(call.function_arguments()?)?;
emit_started(&call).await;
let result = self
.client
.search(&args.query, args.max_results)
.await
.map(|results| format_search_results(&results))
.map_err(|error| format!("web_search failed: {error}"));
emit_completed(
&call,
args.query.clone(),
WebSearchAction::Search {
query: Some(args.query.clone()),
queries: None,
},
CoreWebSearchAction::Search {
query: Some(args.query),
queries: None,
},
)
.await;
Ok(Box::new(SearchOutput::new(result)) as Box<dyn ToolOutput>)
})
}
}
#[derive(Deserialize)]
struct FetchArgs {
url: String,
}
pub(crate) struct WebFetchTool {
fetcher: Arc<WebFetcher>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for WebFetchTool {
fn tool_name(&self) -> ToolName {
ToolName::plain(WEB_FETCH_TOOL_NAME)
}
fn spec(&self) -> ToolSpec {
function_spec(
WEB_FETCH_TOOL_NAME,
"Fetch a public web page (http or https) and return its text content. Private and local network addresses are not reachable.",
BTreeMap::from([(
"url".to_string(),
JsonSchema::string(Some("The absolute http(s) URL to fetch.".to_string())),
)]),
&["url"],
)
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let args: FetchArgs = parse_args(call.function_arguments()?)?;
emit_started(&call).await;
let result = self
.fetcher
.fetch(&args.url)
.await
.map(|page| format_fetched_page(&page))
.map_err(|error| format!("web_fetch failed: {error}"));
emit_completed(
&call,
args.url.clone(),
WebSearchAction::OpenPage {
url: Some(args.url.clone()),
},
CoreWebSearchAction::OpenPage {
url: Some(args.url),
},
)
.await;
Ok(Box::new(SearchOutput::new(result)) as Box<dyn ToolOutput>)
})
}
}

View File

@@ -0,0 +1,404 @@
use akode_api::ReqwestTransport;
use akode_api::SearchClient;
use akode_api::SearchCommands;
use akode_api::SearchQuery;
use akode_api::SearchRequest;
use akode_api::SearchSettings;
use akode_core::X_CODEX_TURN_METADATA_HEADER;
use akode_core::web_search_action_detail;
use akode_extension_api::ExtensionTurnItem;
use akode_extension_api::FunctionCallError;
use akode_extension_api::ResponsesApiTool;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolOutput;
use akode_extension_api::ToolSpec;
use akode_extension_api::parse_tool_input_schema_without_compaction;
use akode_extension_items::ExtensionItem;
use akode_extension_items::web_search::WebSearchAction;
use akode_extension_items::web_search::WebSearchItem;
use akode_http_client::ClientRouteClass;
use akode_http_client::HttpClientFactory;
use akode_login::default_client::ClientRedirectPolicy;
use akode_login::default_client::add_originator_header;
use akode_login::default_client::create_client_for_route_async;
use akode_login::default_client::create_transport_for_routes_async;
use akode_model_provider::SharedModelProvider;
use akode_protocol::models::WebSearchAction as CoreWebSearchAction;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::WebSearchBeginEvent;
use akode_protocol::protocol::WebSearchEndEvent;
use akode_tools::ResponsesApiNamespace;
use akode_tools::ResponsesApiNamespaceTool;
use akode_tools::ToolExposure;
use akode_tools::default_namespace_description;
use http::HeaderMap;
use http::HeaderValue;
use url::Url;
use crate::history::recent_input;
use crate::output::SearchOutput;
use crate::schema::commands_schema;
pub(crate) const WEB_NAMESPACE: &str = "web";
pub(crate) const RUN_TOOL_NAME: &str = "run";
const WEB_RUN_DESCRIPTION: &str = include_str!("../web_run_description.md");
const RESULTS_PAYLOAD_BYTES_METRIC: &str = "codex.web_search.results.payload_bytes";
const MAX_SEARCH_ERROR_BYTES: usize = 1024;
pub(crate) struct WebSearchTool {
pub(crate) session_id: String,
pub(crate) http_client_factory: HttpClientFactory,
pub(crate) provider: SharedModelProvider,
pub(crate) settings: SearchSettings,
pub(crate) supports_literature_search: bool,
pub(crate) originator: Option<String>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for WebSearchTool {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(WEB_NAMESPACE, RUN_TOOL_NAME)
}
fn spec(&self) -> ToolSpec {
// parse schema without compaction that removes field metadata/descriptions to match hosted tool definition
let schema = commands_schema(self.supports_literature_search);
let parameters = match parse_tool_input_schema_without_compaction(&schema) {
Ok(parameters) => parameters,
Err(err) => panic!("search command schema should parse: {err}"),
};
ToolSpec::Namespace(ResponsesApiNamespace {
name: WEB_NAMESPACE.to_string(),
description: default_namespace_description(WEB_NAMESPACE),
tools: vec![ResponsesApiNamespaceTool::Function(ResponsesApiTool {
name: RUN_TOOL_NAME.to_string(),
description: WEB_RUN_DESCRIPTION.to_string(),
strict: false,
parameters,
output_schema: None,
defer_loading: None,
})],
})
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl WebSearchTool {
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let commands = parse_commands(call.function_arguments()?, self.supports_literature_search)?;
let command_action = command_action(&commands);
let setup = akode_model_provider::resolve_request(
self.provider.as_ref(),
self.http_client_factory.clone(),
)
.await
.map_err(|err| FunctionCallError::RespondToModel(search_error_message(err)))?;
let transport = if setup.redirect_policy == ClientRedirectPolicy::Reject {
create_client_for_route_async(
setup.http_client_factory,
setup.api_provider.url_for_path("alpha/search"),
ClientRouteClass::Api,
ClientRedirectPolicy::Reject,
)
.await
.map(ReqwestTransport::from_http_client)
} else {
create_transport_for_routes_async(
setup.http_client_factory,
ClientRouteClass::Api,
setup.redirect_policy,
)
.await
}
.map_err(|err| FunctionCallError::RespondToModel(search_error_message(err)))?;
let client = SearchClient::new(transport, setup.api_provider, setup.api_auth);
let request = SearchRequest {
id: self.session_id.clone(),
model: call.model.clone(),
reasoning: None,
input: recent_input(call.conversation_history.items()),
commands: Some(commands),
settings: Some(self.settings.clone()),
max_output_tokens: Some(
u64::try_from(call.truncation_policy.token_budget()).unwrap_or(u64::MAX),
),
};
let extra_headers = search_request_headers(
self.originator.as_deref(),
call.codex_turn_metadata.as_deref(),
);
call.turn_item_emitter
.emit_started(extension_turn_item(
WebSearchItem {
id: call.call_id.clone(),
query: String::new(),
action: None,
results: None,
},
EventMsg::WebSearchBegin(WebSearchBeginEvent {
call_id: call.call_id.clone(),
}),
))
.await;
let (output, results) = match client.search(&request, extra_headers).await {
Ok(response) => (Ok(response.output), response.results),
Err(err) => (Err(search_error_message(err)), None),
};
if let Some(results) = results.as_ref()
&& let Some(metrics) = akode_otel::global()
&& let Ok(payload) = serde_json::to_vec(results)
{
let payload_bytes = i64::try_from(payload.len()).unwrap_or(i64::MAX);
let _ = metrics.histogram(RESULTS_PAYLOAD_BYTES_METRIC, payload_bytes, &[]);
}
let legacy_action = match &command_action {
WebSearchAction::Search { query, queries } => CoreWebSearchAction::Search {
query: query.clone(),
queries: queries.clone(),
},
WebSearchAction::OpenPage { url } => CoreWebSearchAction::OpenPage { url: url.clone() },
WebSearchAction::FindInPage { url, pattern } => CoreWebSearchAction::FindInPage {
url: url.clone(),
pattern: pattern.clone(),
},
WebSearchAction::Other => CoreWebSearchAction::Other,
};
let query = web_search_action_detail(&legacy_action);
call.turn_item_emitter
.emit_completed(extension_turn_item(
WebSearchItem {
id: call.call_id.clone(),
query: query.clone(),
action: Some(command_action),
results: results.clone(),
},
EventMsg::WebSearchEnd(WebSearchEndEvent {
call_id: call.call_id.clone(),
query,
action: legacy_action,
results,
}),
))
.await;
Ok(Box::new(SearchOutput::new(output)))
}
}
fn search_error_message(error: impl std::fmt::Display) -> String {
let mut message = error.to_string();
if message.len() > MAX_SEARCH_ERROR_BYTES {
const SUFFIX: &str = "… [truncated]";
message.truncate(message.floor_char_boundary(MAX_SEARCH_ERROR_BYTES - SUFFIX.len()));
message.push_str(SUFFIX);
}
message
}
fn search_request_headers(originator: Option<&str>, turn_metadata: Option<&str>) -> HeaderMap {
let mut headers = HeaderMap::new();
if let Some(turn_metadata) = turn_metadata
&& let Ok(header_value) = HeaderValue::from_str(turn_metadata)
{
headers.insert(X_CODEX_TURN_METADATA_HEADER, header_value);
}
if let Some(originator) = originator {
add_originator_header(&mut headers, originator);
}
headers
}
fn parse_commands(
arguments: &str,
supports_literature_search: bool,
) -> Result<SearchCommands, FunctionCallError> {
if arguments.trim().is_empty() {
return Ok(SearchCommands::default());
}
let commands: SearchCommands = serde_json::from_str(arguments)
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?;
if !supports_literature_search && commands.literature_search_query.is_some() {
return Err(FunctionCallError::RespondToModel(
"literature_search_query is unavailable for this model".to_string(),
));
}
Ok(commands)
}
fn command_action(commands: &SearchCommands) -> WebSearchAction {
commands
.search_query
.as_deref()
.and_then(query_action)
.or_else(|| {
commands
.literature_search_query
.as_deref()
.and_then(query_action)
})
.or_else(|| commands.image_query.as_deref().and_then(query_action))
.or_else(|| {
commands
.open
.as_deref()
.and_then(|operations| operations.first())
.and_then(|operation| {
literal_url(&operation.ref_id)
.map(|url| WebSearchAction::OpenPage { url: Some(url) })
})
})
.or_else(|| {
commands
.find
.as_deref()
.and_then(|operations| operations.first())
.map(|operation| WebSearchAction::FindInPage {
url: literal_url(&operation.ref_id),
pattern: Some(operation.pattern.clone()),
})
})
.unwrap_or(WebSearchAction::Other)
}
fn query_action(queries: &[SearchQuery]) -> Option<WebSearchAction> {
match queries {
[] => None,
[query] => Some(WebSearchAction::Search {
query: Some(query.q.clone()),
queries: None,
}),
queries => Some(WebSearchAction::Search {
query: None,
queries: Some(queries.iter().map(|query| query.q.clone()).collect()),
}),
}
}
fn literal_url(ref_id: &str) -> Option<String> {
Url::parse(ref_id).is_ok().then(|| ref_id.to_string())
}
fn extension_turn_item(item: WebSearchItem, legacy_event: EventMsg) -> ExtensionTurnItem {
ExtensionTurnItem {
item: ExtensionItem::WebSearch(item),
legacy_events: vec![legacy_event],
}
}
#[cfg(test)]
mod tests {
use akode_api::SearchCommands;
use akode_extension_items::web_search::WebSearchAction;
use pretty_assertions::assert_eq;
use super::command_action;
use super::parse_commands;
use super::search_error_message;
use super::search_request_headers;
use akode_core::X_CODEX_TURN_METADATA_HEADER;
use akode_extension_api::FunctionCallError;
#[test]
fn search_errors_preserve_short_messages_and_bound_utf8_output() {
let fits = "x".repeat(/*n*/ 1024);
assert_eq!(search_error_message(&fits), fits);
let oversized = "🦀".repeat(/*n*/ 512);
let message = search_error_message(&oversized);
assert!(message.len() <= 1024);
assert!(oversized.starts_with(message.strip_suffix("… [truncated]").unwrap()));
}
#[test]
fn search_request_headers_forward_thread_originator_and_turn_metadata() {
let headers = search_request_headers(Some("chatgpt_cca"), Some("turn-metadata"));
assert_eq!(
headers
.get("originator")
.and_then(|value| value.to_str().ok()),
Some("chatgpt_cca")
);
assert_eq!(
headers
.get(X_CODEX_TURN_METADATA_HEADER)
.and_then(|value| value.to_str().ok()),
Some("turn-metadata")
);
}
#[test]
fn rejects_literature_search_without_the_model_capability() {
let arguments =
r#"{"search_query":[{"q":"regular"}],"literature_search_query":[{"q":"papers"}]}"#;
assert!(matches!(
parse_commands(arguments, /*supports_literature_search*/ false),
Err(FunctionCallError::RespondToModel(message))
if message == "literature_search_query is unavailable for this model"
));
}
#[test]
fn command_action_reports_queries_and_navigation_detail() {
let cases = [
(
r#"{"image_query":[{"q":"waterfalls"},{"q":"mountains"}]}"#,
WebSearchAction::Search {
query: None,
queries: Some(vec!["waterfalls".to_string(), "mountains".to_string()]),
},
),
(
r#"{"open":[{"ref_id":"https://example.com/docs"}]}"#,
WebSearchAction::OpenPage {
url: Some("https://example.com/docs".to_string()),
},
),
(
r#"{"find":[{"ref_id":"https://example.com/docs","pattern":"install"}]}"#,
WebSearchAction::FindInPage {
url: Some("https://example.com/docs".to_string()),
pattern: Some("install".to_string()),
},
),
(
r#"{"find":[{"ref_id":"turn0search0","pattern":"install"}]}"#,
WebSearchAction::FindInPage {
url: None,
pattern: Some("install".to_string()),
},
),
(
r#"{"open":[{"ref_id":"turn0search0"}]}"#,
WebSearchAction::Other,
),
];
for (arguments, expected) in cases {
let commands: SearchCommands =
serde_json::from_str(arguments).expect("valid search command arguments");
assert_eq!(command_action(&commands), expected);
}
}
}