| 1 | use codewhale_runtime::config::{ |
| 2 | PersistedSearchChoice, SEARCH_PROVIDER_ANY, SearchProvider, SearchThirdParty, |
| 3 | SearchThirdPartyResolution, SearchThirdPartySource, read_persisted_search_choice, |
| 4 | search_provider_options, |
| 5 | }; |
| 6 | use serde_json::{Value, json}; |
| 7 | use std::sync::atomic::Ordering; |
| 8 | |
| 9 | use super::approval::ApprovalResult; |
| 10 | use super::{Engine, Event}; |
| 11 | use crate::approval_log::ApprovalDecider; |
| 12 | use crate::core::authority::RunOrigin; |
| 13 | use crate::tools::ToolContext; |
| 14 | use crate::tools::spec::{ToolError, ToolResult}; |
| 15 | use crate::tools::web::consent::{self, ChosenSearch, ThirdPartySearch, ThirdPartySearchPermit}; |
| 16 | |
| 17 | pub(super) const CONSENT_NEEDS_PERSON: &str = "Third-party web search needs the person's own answer on its card; a remembered grant or an automatic posture cannot give it. The search did not run."; |
| 18 | |
| 19 | pub(super) struct SearchConsentCard { |
| 20 | pub(super) id: String, |
| 21 | pub(super) input: Value, |
| 22 | pub(super) description: String, |
| 23 | pub(super) approval_key: String, |
| 24 | } |
| 25 | |
| 26 | pub(super) enum SearchConsentStep { |
| 27 | Enabled, |
| 28 | Answered(Result<ToolResult, ToolError>), |
| 29 | Steered, |
| 30 | } |
| 31 | |
| 32 | impl Engine { |
| 33 | fn persisted_search_choice(&self) -> Option<PersistedSearchChoice> { |
| 34 | let path = self.api_config.loaded_config_path.as_deref()?; |
| 35 | match read_persisted_search_choice(path) { |
| 36 | Ok(choice) => Some(choice), |
| 37 | Err(error) => { |
| 38 | tracing::warn!(target: "search", %error, "could not read [search] from config.toml"); |
| 39 | None |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub(super) fn search_third_party_resolution(&self) -> SearchThirdPartyResolution { |
| 45 | let persisted = self.persisted_search_choice(); |
| 46 | if let Some(value) = self.search_third_party_unsaved |
| 47 | && persisted.is_none_or(|choice| { |
| 48 | matches!(choice.third_party, None | Some(SearchThirdParty::Ask)) |
| 49 | }) |
| 50 | { |
| 51 | return SearchThirdPartyResolution { |
| 52 | value, |
| 53 | source: SearchThirdPartySource::Config, |
| 54 | }; |
| 55 | } |
| 56 | SearchThirdPartyResolution::with_persisted( |
| 57 | persisted, |
| 58 | self.config.search_third_party, |
| 59 | self.config.search_consent_implied, |
| 60 | ) |
| 61 | } |
| 62 | |
| 63 | fn search_consent_can_prompt(&self) -> bool { |
| 64 | self.child_host.is_none() |
| 65 | && self.turn_owner_present |
| 66 | && self.turn_run_origin == RunOrigin::Interactive |
| 67 | && !self.is_acp_turn() |
| 68 | } |
| 69 | |
| 70 | fn parent_third_party_search(&self) -> Option<ThirdPartySearch> { |
| 71 | self.child_host |
| 72 | .as_ref() |
| 73 | .map(|child| child.authority.runtime.context.third_party_search.get()) |
| 74 | } |
| 75 | |
| 76 | fn third_party_search_now(&self) -> ThirdPartySearch { |
| 77 | match self.search_third_party_resolution().value { |
| 78 | SearchThirdParty::On => ThirdPartySearch::Allowed, |
| 79 | SearchThirdParty::Off => ThirdPartySearch::Declined, |
| 80 | SearchThirdParty::Ask if self.search_consent_can_prompt() => { |
| 81 | self.search_consent_held.store(true, Ordering::SeqCst); |
| 82 | ThirdPartySearch::Withheld |
| 83 | } |
| 84 | SearchThirdParty::Ask => self.parent_third_party_search().unwrap_or( |
| 85 | if self.search_consent_held.load(Ordering::SeqCst) { |
| 86 | ThirdPartySearch::Withheld |
| 87 | } else { |
| 88 | ThirdPartySearch::Allowed |
| 89 | }, |
| 90 | ), |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | pub(super) fn refreshed_third_party_search(&self) -> ThirdPartySearchPermit { |
| 95 | self.third_party_search.set(self.third_party_search_now()); |
| 96 | self.third_party_search.clone() |
| 97 | } |
| 98 | |
| 99 | pub(super) fn search_consent_pending(&self) -> bool { |
| 100 | self.search_consent_can_prompt() |
| 101 | && self.search_third_party_resolution().value == SearchThirdParty::Ask |
| 102 | } |
| 103 | |
| 104 | pub(super) fn search_consent_card_needed( |
| 105 | &self, |
| 106 | tool_name: &str, |
| 107 | input: &Value, |
| 108 | detached_start: bool, |
| 109 | tool_registry: Option<&crate::tools::ToolRegistry>, |
| 110 | ) -> bool { |
| 111 | if detached_start |
| 112 | || !consent::is_web_search_call(tool_name, input) |
| 113 | || !self.search_consent_pending() |
| 114 | { |
| 115 | return false; |
| 116 | } |
| 117 | consent::has_image_query(input) |
| 118 | || self |
| 119 | .live_tool_context(tool_registry) |
| 120 | .is_some_and(|context| consent::first_backend_is_third_party(&context)) |
| 121 | } |
| 122 | |
| 123 | pub(super) fn search_consent_card(&self, tool_id: &str, input: &Value) -> SearchConsentCard { |
| 124 | let options = search_provider_options( |
| 125 | self.config.search_provider, |
| 126 | self.config.search_api_key.as_deref(), |
| 127 | ); |
| 128 | let selected = self |
| 129 | .persisted_search_choice() |
| 130 | .and_then(|choice| choice.provider) |
| 131 | .map(|provider| provider.as_str()) |
| 132 | .filter(|id| options.iter().any(|option| option.id == *id)) |
| 133 | .unwrap_or(SEARCH_PROVIDER_ANY); |
| 134 | let provider = if consent::searches_only_images(input) { |
| 135 | SearchProvider::DuckDuckGo |
| 136 | } else { |
| 137 | self.config.search_provider |
| 138 | }; |
| 139 | let id = consent::consent_approval_id(tool_id); |
| 140 | SearchConsentCard { |
| 141 | input: consent::input_with_consent_marker( |
| 142 | input, |
| 143 | consent::consent_marker(&options, selected), |
| 144 | ), |
| 145 | description: consent::consent_description(provider), |
| 146 | approval_key: id.clone(), |
| 147 | id, |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | pub(super) async fn ask_search_consent( |
| 152 | &mut self, |
| 153 | tool_id: &str, |
| 154 | tool_name: &str, |
| 155 | input: &Value, |
| 156 | description_prefix: &str, |
| 157 | withdraw: Option<&tokio_util::sync::CancellationToken>, |
| 158 | ) -> SearchConsentStep { |
| 159 | let card = self.search_consent_card(tool_id, input); |
| 160 | super::tool_execution::emit_tool_audit(json!({ |
| 161 | "event": "tool.approval_required", |
| 162 | "tool_id": card.id.clone(), |
| 163 | "tool_name": tool_name, |
| 164 | "search_consent": true, |
| 165 | })) |
| 166 | .await; |
| 167 | let event = Event::ApprovalRequired { |
| 168 | publication: None, |
| 169 | id: card.id.clone(), |
| 170 | tool_name: tool_name.to_string(), |
| 171 | input: card.input, |
| 172 | description: format!("{description_prefix}{}", card.description), |
| 173 | approval_key: card.approval_key.clone(), |
| 174 | approval_grouping_key: card.approval_key, |
| 175 | intent_summary: None, |
| 176 | approval_force_prompt: true, |
| 177 | }; |
| 178 | let answer = self |
| 179 | .request_tool_approval_until(&card.id, tool_name, event, withdraw) |
| 180 | .await; |
| 181 | let (decision, step) = match answer { |
| 182 | Ok(ApprovalResult::Approved(ApprovalDecider::User)) => { |
| 183 | self.record_search_consent(SearchThirdParty::On).await; |
| 184 | ("approved", SearchConsentStep::Enabled) |
| 185 | } |
| 186 | Ok(ApprovalResult::Denied(ApprovalDecider::User)) => { |
| 187 | self.record_search_consent(SearchThirdParty::Off).await; |
| 188 | ( |
| 189 | "denied", |
| 190 | SearchConsentStep::Answered(Ok(ToolResult::success(consent::DECLINED_MESSAGE))), |
| 191 | ) |
| 192 | } |
| 193 | Ok( |
| 194 | ApprovalResult::Approved(_) |
| 195 | | ApprovalResult::Denied(_) |
| 196 | | ApprovalResult::RetryWithPolicy(_), |
| 197 | ) => ( |
| 198 | "refused", |
| 199 | SearchConsentStep::Answered(Err(ToolError::permission_denied( |
| 200 | CONSENT_NEEDS_PERSON, |
| 201 | ))), |
| 202 | ), |
| 203 | Ok(ApprovalResult::TimedOut) => ( |
| 204 | "timeout", |
| 205 | SearchConsentStep::Answered(Err(super::turn_loop::approval_timed_out_error( |
| 206 | tool_name, |
| 207 | ))), |
| 208 | ), |
| 209 | Ok(ApprovalResult::Steered) => ("cancelled", SearchConsentStep::Steered), |
| 210 | Err(error) => ("cancelled", SearchConsentStep::Answered(Err(error))), |
| 211 | }; |
| 212 | super::tool_execution::emit_tool_audit(json!({ |
| 213 | "event": "tool.approval_decision", |
| 214 | "tool_id": consent::consent_approval_id(tool_id), |
| 215 | "tool_name": tool_name, |
| 216 | "decision": decision, |
| 217 | "search_consent": true, |
| 218 | })) |
| 219 | .await; |
| 220 | step |
| 221 | } |
| 222 | |
| 223 | pub(super) async fn record_search_consent(&mut self, value: SearchThirdParty) { |
| 224 | self.config.search_third_party = Some(value); |
| 225 | #[cfg(any(test, feature = "test-support"))] |
| 226 | let ticket = crate::test_support::env_scope_ticket(); |
| 227 | let persisted = match self.api_config.loaded_config_path.clone() { |
| 228 | Some(path) => tokio::task::spawn_blocking(move || { |
| 229 | #[cfg(any(test, feature = "test-support"))] |
| 230 | let _membership = crate::test_support::join_env_scope(ticket); |
| 231 | let written = codewhale_runtime::config_persistence::persist_table_string_key( |
| 232 | Some(&path), |
| 233 | "search", |
| 234 | "third_party", |
| 235 | value.as_str(), |
| 236 | ) |
| 237 | .map(|_| ()); |
| 238 | (written, read_persisted_search_choice(&path).ok()) |
| 239 | }) |
| 240 | .await |
| 241 | .ok(), |
| 242 | None => None, |
| 243 | }; |
| 244 | let (saved, pinned) = match persisted { |
| 245 | Some((written, choice)) => (written, choice.and_then(|choice| choice.provider)), |
| 246 | None if self.api_config.loaded_config_path.is_some() => { |
| 247 | (Err(anyhow::anyhow!("the save task did not finish")), None) |
| 248 | } |
| 249 | None => (Ok(()), None), |
| 250 | }; |
| 251 | self.search_third_party_unsaved = None; |
| 252 | if let Err(error) = saved { |
| 253 | tracing::warn!(target: "search", %error, "could not save [search] third_party"); |
| 254 | self.search_third_party_unsaved = Some(value); |
| 255 | let _ = self |
| 256 | .send_event(Event::status(format!( |
| 257 | "Web search choice applies to this session only; saving it to config.toml failed: {error}" |
| 258 | ))) |
| 259 | .await; |
| 260 | } |
| 261 | if value == SearchThirdParty::On |
| 262 | && let Some(provider) = pinned |
| 263 | { |
| 264 | self.config.search_provider = provider; |
| 265 | self.config.search_native.get_or_insert(false); |
| 266 | self.third_party_search.choose(Some(ChosenSearch { |
| 267 | provider, |
| 268 | native_off: self.config.search_native == Some(false), |
| 269 | })); |
| 270 | } |
| 271 | self.third_party_search.set(match value { |
| 272 | SearchThirdParty::On => ThirdPartySearch::Allowed, |
| 273 | SearchThirdParty::Off => ThirdPartySearch::Declined, |
| 274 | SearchThirdParty::Ask => self.third_party_search_now(), |
| 275 | }); |
| 276 | } |
| 277 | |
| 278 | pub(super) fn apply_search_choice(&self, mut context: ToolContext) -> ToolContext { |
| 279 | context.search_provider = self.config.search_provider; |
| 280 | if self.config.search_native == Some(false) { |
| 281 | context.provider_native_search = None; |
| 282 | } |
| 283 | context.third_party_search = self.third_party_search.clone(); |
| 284 | context |
| 285 | } |
| 286 | } |
| 287 |