aKode fase 3: provider locali, chiavi per provider, modelli dal server, SearXNG
- Provider: rimossi openai, Bedrock e GCP integrati e ogni fallback a OpenAI;
restano ollama, lmstudio e i provider personalizzati. Senza provider, exec e
TUI mostrano come configurarlo.
- Chiave per provider: api_key = "keyring", provider_api_key_store =
auto|keyring|file (fallback su file 0600 / ACL Windows); `codex login
--provider <id> --with-api-key`, `logout --provider`; login status e doctor
mostrano dove sta la chiave senza rivelarla.
- Modelli letti da GET {base_url}/models; contesto da config, poi dal server
(/props, meta.n_ctx), poi 32768; apply_patch come tool function; niente tool
ospitati; niente piu' avviso "metadata not found".
- Unione dei soli messaggi system/developer iniziali in un unico system;
quelli successivi restano al loro posto come user (cache del server
preservata: turno N prefisso esatto del turno N+1).
- Modelli ausiliari (memorie, guardian-v2) = modello di sessione se il
preferito gpt-* non e' nel catalogo.
- Ricerca web: crate web-tools, backend SearXNG con web_search e web_fetch
(protezione SSRF); senza backend nessuno strumento web.
- Skill: rimossa openai-docs; skill-installer punta a git.difonzo.net.
- apply_patch accetta gli header @@ -a,b +c,d @@ dei diff unificati.
- Rimossi resti: request_plugin_install, AppsInstructions, --cyber-access-program,
URL updater/realtime predefiniti.
- Fix: importazione sessioni con provider vuoto.
- Istruzioni di sistema invariate. Test: cancellati solo quelli del codice
rimosso, test di sicurezza adattati; restano solo fallimenti d'ambiente.
- Prova reale su imeAI + SearXNG: risposta, modifica file, web_search,
cache riusata, connessioni solo verso .25 e .57.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,7 @@ use codex_extension_api::ToolContributor;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::config_types::WebSearchBackendConfig;
|
||||
use codex_protocol::config_types::WebSearchContextSize;
|
||||
use codex_protocol::config_types::WebSearchMode;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
@@ -34,6 +35,8 @@ struct WebSearchExtension {
|
||||
|
||||
#[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,
|
||||
@@ -43,8 +46,9 @@ struct WebSearchExtensionConfig {
|
||||
impl From<&Config> for WebSearchExtensionConfig {
|
||||
fn from(config: &Config) -> Self {
|
||||
Self {
|
||||
provider_supports_search: config.model_provider.is_openai()
|
||||
|| config.model_provider.supports_standalone_web_search,
|
||||
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),
|
||||
@@ -124,10 +128,23 @@ impl ToolContributor for WebSearchExtension {
|
||||
) -> Vec<
|
||||
Arc<dyn for<'call> codex_extension_api::ToolExecutor<codex_extension_api::ToolCall<'call>>>,
|
||||
> {
|
||||
let (Some(config), Some(mode)) = (
|
||||
thread_store.get::<WebSearchExtensionConfig>(),
|
||||
step_store.get::<WebSearchMode>(),
|
||||
) else {
|
||||
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 {
|
||||
@@ -189,6 +206,7 @@ mod tests {
|
||||
use crate::tool::WEB_NAMESPACE;
|
||||
use codex_api::ExternalWebAccess;
|
||||
use codex_api::ExternalWebAccessMode;
|
||||
use codex_protocol::config_types::WebSearchBackendConfig;
|
||||
use codex_protocol::config_types::WebSearchMode;
|
||||
|
||||
#[test]
|
||||
@@ -223,9 +241,13 @@ mod tests {
|
||||
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_openai_provider(/*base_url*/ None),
|
||||
provider: ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("http://127.0.0.1:9/v1".to_string()),
|
||||
),
|
||||
settings: Default::default(),
|
||||
});
|
||||
|
||||
@@ -243,4 +265,101 @@ mod tests {
|
||||
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: codex_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 codex_extension_api::ToolSpec::Function(spec) = tool.spec() else {
|
||||
panic!("expected a function tool");
|
||||
};
|
||||
assert!(spec.name == "web_search" || spec.name == "web_fetch");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ mod extension;
|
||||
mod history;
|
||||
mod output;
|
||||
mod schema;
|
||||
mod searxng;
|
||||
mod tool;
|
||||
|
||||
pub use extension::install;
|
||||
|
||||
281
codex-rs/ext/web-search/src/searxng.rs
Normal file
281
codex-rs/ext/web-search/src/searxng.rs
Normal 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 codex_extension_api::ExtensionTurnItem;
|
||||
use codex_extension_api::FunctionCallError;
|
||||
use codex_extension_api::ResponsesApiTool;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_extension_api::ToolName;
|
||||
use codex_extension_api::ToolOutput;
|
||||
use codex_extension_api::ToolSpec;
|
||||
use codex_extension_items::ExtensionItem;
|
||||
use codex_extension_items::web_search::WebSearchAction;
|
||||
use codex_extension_items::web_search::WebSearchItem;
|
||||
use codex_protocol::config_types::WebSearchBackendConfig;
|
||||
use codex_protocol::models::WebSearchAction as CoreWebSearchAction;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::WebSearchBeginEvent;
|
||||
use codex_protocol::protocol::WebSearchEndEvent;
|
||||
use codex_tools::JsonSchema;
|
||||
use codex_tools::ToolExposure;
|
||||
use codex_web_tools::SearxngClient;
|
||||
use codex_web_tools::SearxngOptions;
|
||||
use codex_web_tools::WebFetchOptions;
|
||||
use codex_web_tools::WebFetcher;
|
||||
use codex_web_tools::format_fetched_page;
|
||||
use codex_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>) -> codex_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>) -> codex_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>)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user