| 1 | //! One admitted process operation. The Builtin orchestrates; Rust owns all launch and caller facts. |
| 2 | use std::collections::HashMap; |
| 3 | use std::sync::{ |
| 4 | Arc, Mutex, |
| 5 | atomic::{AtomicU64, Ordering}, |
| 6 | }; |
| 7 | use std::time::{Duration, Instant}; |
| 8 | |
| 9 | use serde_json::{Value, json}; |
| 10 | use tokio::sync::{OwnedSemaphorePermit, Semaphore}; |
| 11 | use tokio_util::sync::CancellationToken; |
| 12 | |
| 13 | use super::protocol::{ |
| 14 | CoreRequest, ExecutionRedeemParams, HarnessRunParams, RpcErrorWire, error_code, |
| 15 | }; |
| 16 | use super::registry::OwnerState; |
| 17 | use super::supervisor::HostRequestContext; |
| 18 | use super::ticket::{Grant, Presented, Ticket, TicketKind}; |
| 19 | use super::tier::HostCohort; |
| 20 | use super::{ExtensionHostManager, ManagerShared, activation}; |
| 21 | use crate::tools::spec::{ToolContext, ToolError, ToolResult}; |
| 22 | use codewhale_config::OwnerRef; |
| 23 | use codewhale_config::PluginAuthority; |
| 24 | use codewhale_plugins::PluginRegistry; |
| 25 | use codewhale_plugins::activation::PluginActivationCapability; |
| 26 | |
| 27 | const DEADLINE: Duration = Duration::from_secs(120); |
| 28 | const MAX_JOBS: usize = 32; |
| 29 | const MAX_INPUT: usize = 1024 * 1024; |
| 30 | const MAX_REVIEW: usize = 16 * 1024 * 1024; |
| 31 | const MAX_STDOUT: usize = 1024 * 1024; |
| 32 | const MAX_STDERR: usize = 64 * 1024; |
| 33 | |
| 34 | #[derive(Clone)] |
| 35 | struct Caller { |
| 36 | workspace: std::path::PathBuf, |
| 37 | plugins: Option<Arc<PluginRegistry>>, |
| 38 | session_id: Option<String>, |
| 39 | agent_id: Option<String>, |
| 40 | origin_turn_id: Option<String>, |
| 41 | origin_call_id: Option<String>, |
| 42 | authorities: Vec<PluginAuthority>, |
| 43 | native_owners: Vec<OwnerRef>, |
| 44 | native_host_generations: Vec<(HostCohort, u64)>, |
| 45 | requires_native_policy: bool, |
| 46 | } |
| 47 | impl Caller { |
| 48 | fn capture(context: &ToolContext, shared: &ManagerShared) -> Result<Self, String> { |
| 49 | Self::from_hook(crate::hooks::HookCaller::from_tool(context), shared, None) |
| 50 | } |
| 51 | fn from_hook( |
| 52 | caller: crate::hooks::HookCaller, |
| 53 | shared: &ManagerShared, |
| 54 | only_plugin: Option<&str>, |
| 55 | ) -> Result<Self, String> { |
| 56 | let plugins = caller.plugins.clone(); |
| 57 | let mut authorities = Vec::new(); |
| 58 | if let Some(plugins) = plugins.as_ref() { |
| 59 | for entry in plugins |
| 60 | .selected_native_entries() |
| 61 | .iter() |
| 62 | .filter(|entry| only_plugin.is_none_or(|id| entry.plugin_id == id)) |
| 63 | { |
| 64 | let authority = plugins |
| 65 | .authority_for(&entry.plugin_id) |
| 66 | .ok_or("selected Native source has no authority")?; |
| 67 | if authority.content_hash != entry.content_hash { |
| 68 | return Err("selected Native source changed".into()); |
| 69 | } |
| 70 | if !authorities |
| 71 | .iter() |
| 72 | .any(|old: &PluginAuthority| old.plugin_id == authority.plugin_id) |
| 73 | { |
| 74 | authorities.push(authority); |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | let (native_owners, native_host_generations) = { |
| 79 | let registry = shared.registry.lock().expect("registry lock"); |
| 80 | let mut owners = Vec::new(); |
| 81 | let mut cohorts = std::collections::HashSet::new(); |
| 82 | for authority in &authorities { |
| 83 | let owner = registry |
| 84 | .owner(authority.plugin_id.as_str()) |
| 85 | .filter(|owner| { |
| 86 | owner.state == OwnerState::Active |
| 87 | && owner.content_hash == authority.content_hash |
| 88 | }) |
| 89 | .ok_or_else(|| "Native caller owner is no longer live".to_string())?; |
| 90 | owners.push(owner.owner.clone()); |
| 91 | cohorts.insert(owner.cohort.clone()); |
| 92 | } |
| 93 | drop(registry); |
| 94 | let mut generations = Vec::new(); |
| 95 | for cohort in cohorts { |
| 96 | let host_generation = shared |
| 97 | .ready_host(&cohort) |
| 98 | .map_err(|status| status.to_string())? |
| 99 | .generation; |
| 100 | generations.push((cohort, host_generation)); |
| 101 | } |
| 102 | (owners, generations) |
| 103 | }; |
| 104 | Ok(Self { |
| 105 | workspace: caller.workspace, |
| 106 | plugins, |
| 107 | session_id: caller.session_id.filter(|id| !id.is_empty()), |
| 108 | agent_id: caller.agent_id, |
| 109 | origin_turn_id: caller.origin_turn_id, |
| 110 | origin_call_id: caller.origin_call_id, |
| 111 | authorities, |
| 112 | native_owners, |
| 113 | native_host_generations, |
| 114 | requires_native_policy: true, |
| 115 | }) |
| 116 | } |
| 117 | fn check(&self, shared: &ManagerShared) -> Result<(), String> { |
| 118 | if (self.requires_native_policy || !self.authorities.is_empty()) |
| 119 | && !activation::extension_host_policy_enabled() |
| 120 | { |
| 121 | return Err("plugin host is disabled".into()); |
| 122 | } |
| 123 | for (cohort, generation) in &self.native_host_generations { |
| 124 | if shared |
| 125 | .ready_host(cohort) |
| 126 | .map_err(|status| status.to_string())? |
| 127 | .generation |
| 128 | != *generation |
| 129 | { |
| 130 | return Err("Native caller host restarted".into()); |
| 131 | } |
| 132 | } |
| 133 | if !self.native_host_generations.is_empty() { |
| 134 | let registry = shared.registry.lock().expect("registry lock"); |
| 135 | for owner in &self.native_owners { |
| 136 | let active = registry |
| 137 | .owner(&owner.plugin_id) |
| 138 | .filter(|entry| entry.owner == *owner && entry.state == OwnerState::Active) |
| 139 | .ok_or("Native caller owner changed")?; |
| 140 | for entry in self |
| 141 | .plugins |
| 142 | .as_ref() |
| 143 | .expect("Native view") |
| 144 | .selected_native_entries() |
| 145 | .iter() |
| 146 | .filter(|entry| entry.plugin_id == owner.plugin_id) |
| 147 | { |
| 148 | if active.scopes.get(&entry.entry) != Some(&OwnerState::Active) { |
| 149 | return Err("Native caller entry was withdrawn".into()); |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | if let Some(plugins) = self.plugins.as_ref() { |
| 155 | if plugins.workspace() != self.workspace { |
| 156 | return Err("execution workspace does not match its caller".into()); |
| 157 | } |
| 158 | if let Some(revision) = plugins.caller_selection() { |
| 159 | let (current, agent) = shared |
| 160 | .plugins_for_selection(revision, self.session_id.as_deref()) |
| 161 | .ok_or("execution caller was detached or changed")?; |
| 162 | if agent != self.agent_id || !Arc::ptr_eq(plugins, ¤t) { |
| 163 | return Err("execution caller identity changed".into()); |
| 164 | } |
| 165 | } else if !plugins.selected_native_entries().is_empty() { |
| 166 | return Err("selected Native execution has no caller receipt".into()); |
| 167 | } |
| 168 | } |
| 169 | Ok(()) |
| 170 | } |
| 171 | fn target(&self, id: &str) -> Value { |
| 172 | json!({"execution_id":id,"workspace":self.workspace,"session_id":self.session_id,"agent_id":self.agent_id,"origin_turn_id":self.origin_turn_id,"origin_call_id":self.origin_call_id,"selection":self.plugins.as_ref().and_then(|plugins| plugins.caller_selection())}) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// An exhaustive pure-transform inventory, never an arbitrary module/function selector. |
| 177 | #[derive(Clone, Copy)] |
| 178 | pub enum StockOperation { |
| 179 | WebFilters, |
| 180 | WebRequest, |
| 181 | WebProvider, |
| 182 | WebEntries, |
| 183 | WebFinalize, |
| 184 | WebExtract, |
| 185 | WebImages, |
| 186 | ValidateData, |
| 187 | SpeechOptions, |
| 188 | SpeechFormat, |
| 189 | ReviewSourcePrompt, |
| 190 | ReviewPassPrompt, |
| 191 | ReviewInteractivePr, |
| 192 | ReviewReport, |
| 193 | } |
| 194 | impl StockOperation { |
| 195 | fn as_str(self) -> &'static str { |
| 196 | match self { |
| 197 | Self::WebFilters => "web_filters", |
| 198 | Self::WebRequest => "web_request", |
| 199 | Self::WebProvider => "web_provider", |
| 200 | Self::WebEntries => "web_entries", |
| 201 | Self::WebFinalize => "web_finalize", |
| 202 | Self::WebExtract => "web_extract", |
| 203 | Self::WebImages => "web_images", |
| 204 | Self::ValidateData => "validate_data", |
| 205 | Self::SpeechOptions => "speech_options", |
| 206 | Self::SpeechFormat => "speech_format", |
| 207 | Self::ReviewSourcePrompt => "review_source_prompt", |
| 208 | Self::ReviewPassPrompt => "review_pass_prompt", |
| 209 | Self::ReviewInteractivePr => "review_interactive_pr", |
| 210 | Self::ReviewReport => "review_report", |
| 211 | } |
| 212 | } |
| 213 | fn is_review(self) -> bool { |
| 214 | matches!( |
| 215 | self, |
| 216 | Self::ReviewSourcePrompt |
| 217 | | Self::ReviewPassPrompt |
| 218 | | Self::ReviewInteractivePr |
| 219 | | Self::ReviewReport |
| 220 | ) |
| 221 | } |
| 222 | fn slots(self) -> u32 { |
| 223 | if self.is_review() { 16 } else { 1 } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | fn review_envelope_fits(value: &Value) -> Result<bool, ToolError> { |
| 228 | super::protocol::encode_frame(&json!({"jsonrpc":"2.0","id":u64::MAX,"result":value})) |
| 229 | .map(|frame| frame.len() <= MAX_REVIEW) |
| 230 | .map_err(|_| { |
| 231 | ToolError::invalid_input("Serialized review envelope exceeds the existing frame limit") |
| 232 | }) |
| 233 | } |
| 234 | fn check_stock_snapshot(operation: StockOperation, input: &Value) -> Result<(), ToolError> { |
| 235 | if operation.is_review() { |
| 236 | let projection = |
| 237 | json!({"kind":"stock_adapter","operation":operation.as_str(),"input":input}); |
| 238 | if !review_envelope_fits(&projection)? { |
| 239 | return Err(ToolError::invalid_input( |
| 240 | "Serialized review snapshot/envelope exceeds 16 MiB; no source was truncated", |
| 241 | )); |
| 242 | } |
| 243 | } else if serde_json::to_vec(input) |
| 244 | .map_err(|_| ToolError::invalid_input("adapter snapshot is not JSON"))? |
| 245 | .len() |
| 246 | > MAX_INPUT |
| 247 | { |
| 248 | return Err(ToolError::invalid_input("adapter snapshot exceeds 1 MiB")); |
| 249 | } |
| 250 | Ok(()) |
| 251 | } |
| 252 | |
| 253 | type HookRun = Box<dyn FnOnce(CancellationToken) -> crate::hooks::HookResult + Send>; |
| 254 | struct HookLaunch { |
| 255 | run: HookRun, |
| 256 | hook: codewhale_config::hooks::Hook, |
| 257 | } |
| 258 | struct PdfLaunch { |
| 259 | input: crate::tools::pdf::CapturedPdf, |
| 260 | output: Arc<Mutex<Option<crate::tools::pdf::PdfProcessOutcome>>>, |
| 261 | } |
| 262 | enum OcrLaunch { |
| 263 | Native { |
| 264 | input: crate::tools::image_ocr::CapturedOcr, |
| 265 | output: Arc<Mutex<Option<crate::tools::image_ocr::OcrOutcome>>>, |
| 266 | }, |
| 267 | Tesseract { |
| 268 | step: crate::tools::image_ocr::OcrNativeStep, |
| 269 | output: Arc<Mutex<Option<crate::tools::image_ocr::OcrOutcome>>>, |
| 270 | }, |
| 271 | } |
| 272 | struct Continuation { |
| 273 | ticket: Ticket, |
| 274 | target: Value, |
| 275 | } |
| 276 | struct GithubLaunch { |
| 277 | request: crate::tools::github::host::Request, |
| 278 | context: Option<ToolContext>, |
| 279 | output: Arc<Mutex<crate::tools::github::host::RunState>>, |
| 280 | } |
| 281 | struct Launch { |
| 282 | github: Option<GithubLaunch>, |
| 283 | ocr: Option<OcrLaunch>, |
| 284 | pdf: Option<PdfLaunch>, |
| 285 | stock: Option<(StockOperation, Value)>, |
| 286 | hook: Option<HookLaunch>, |
| 287 | command: Option<tokio::process::Command>, |
| 288 | input: Vec<u8>, |
| 289 | } |
| 290 | struct Job { |
| 291 | id: String, |
| 292 | owner: OwnerRef, |
| 293 | generation: u64, |
| 294 | caller: Caller, |
| 295 | target: Value, |
| 296 | expires: Instant, |
| 297 | cancel: CancellationToken, |
| 298 | launch: Mutex<Option<Launch>>, |
| 299 | ticket: Ticket, |
| 300 | continuation: Mutex<Option<Continuation>>, |
| 301 | hook_result: Mutex<Option<crate::hooks::HookResult>>, |
| 302 | // The worker owns this Arc until process cleanup and blocking receipt checks finish. |
| 303 | _permit: OwnedSemaphorePermit, |
| 304 | } |
| 305 | impl Job { |
| 306 | fn check(&self, shared: &ManagerShared) -> Result<(), String> { |
| 307 | if self.cancel.is_cancelled() || Instant::now() >= self.expires { |
| 308 | return Err("execution cancelled or expired".into()); |
| 309 | } |
| 310 | if shared.builtin.host_generation.load(Ordering::SeqCst) != self.generation { |
| 311 | return Err("execution host restarted".into()); |
| 312 | } |
| 313 | shared.live_owner_authority(HostCohort::Builtin, |registry| { |
| 314 | registry |
| 315 | .owner("host:harness") |
| 316 | .filter(|entry| entry.owner == self.owner && entry.state == OwnerState::Active) |
| 317 | .map(|entry| entry.owner.clone()) |
| 318 | .ok_or_else(|| "execution builtin owner is no longer live".to_string()) |
| 319 | })?; |
| 320 | self.caller.check(shared) |
| 321 | } |
| 322 | async fn checked(self: &Arc<Self>, shared: &Arc<ManagerShared>) -> Result<(), String> { |
| 323 | self.check(shared)?; |
| 324 | let job = Arc::clone(self); |
| 325 | let policy = activation::extension_host_policy_enabled(); |
| 326 | #[cfg(any(test, feature = "test-support"))] |
| 327 | let env_scope = crate::test_support::env_scope_ticket(); |
| 328 | shared |
| 329 | .engine_handle()? |
| 330 | .spawn_blocking(move || { |
| 331 | let _policy = activation::PolicyScope::propagate(policy); |
| 332 | #[cfg(any(test, feature = "test-support"))] |
| 333 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 334 | for authority in &job.caller.authorities { |
| 335 | codewhale_plugins::registry::verify_plugin_component_authority( |
| 336 | authority, |
| 337 | PluginActivationCapability::Native, |
| 338 | )?; |
| 339 | } |
| 340 | Ok::<(), String>(()) |
| 341 | }) |
| 342 | .await |
| 343 | .map_err(|_| "execution receipt check failed".to_string())??; |
| 344 | self.check(shared) |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | pub(super) struct Broker { |
| 349 | jobs: Mutex<HashMap<String, Arc<Job>>>, |
| 350 | slots: Arc<Semaphore>, |
| 351 | } |
| 352 | impl Default for Broker { |
| 353 | fn default() -> Self { |
| 354 | Self { |
| 355 | jobs: Mutex::new(HashMap::new()), |
| 356 | slots: Arc::new(Semaphore::new(MAX_JOBS)), |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | impl Drop for Broker { |
| 361 | fn drop(&mut self) { |
| 362 | for job in self.jobs.get_mut().expect("execution lock").values() { |
| 363 | job.cancel.cancel(); |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | impl Broker { |
| 368 | fn admit(&self, units: u32) -> Result<OwnedSemaphorePermit, ToolError> { |
| 369 | Arc::clone(&self.slots) |
| 370 | .try_acquire_many_owned(units) |
| 371 | .map_err(|_| ToolError::not_available("execution concurrency limit reached")) |
| 372 | } |
| 373 | pub(super) fn revoke_owner(&self, owner: &str) { |
| 374 | for job in self.jobs.lock().expect("execution lock").values() { |
| 375 | if job.owner.plugin_id == owner |
| 376 | || job |
| 377 | .caller |
| 378 | .authorities |
| 379 | .iter() |
| 380 | .any(|authority| authority.plugin_id.as_str() == owner) |
| 381 | { |
| 382 | job.cancel.cancel(); |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | pub(super) fn revoke_host(&self, cohort: impl Into<HostCohort>, generation: u64) { |
| 387 | let cohort = cohort.into(); |
| 388 | for job in self.jobs.lock().expect("execution lock").values() { |
| 389 | if (cohort == HostCohort::Builtin && job.generation == generation) |
| 390 | || job |
| 391 | .caller |
| 392 | .native_host_generations |
| 393 | .iter() |
| 394 | .any(|(c, g)| *c == cohort && *g == generation) |
| 395 | { |
| 396 | job.cancel.cancel(); |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | pub(super) fn revoke_scope(&self, plugin_id: &str, scope: &codewhale_config::EntryRef) { |
| 401 | for job in self.jobs.lock().expect("execution lock").values() { |
| 402 | if job.caller.plugins.as_ref().is_some_and(|plugins| { |
| 403 | plugins |
| 404 | .selected_native_entries() |
| 405 | .iter() |
| 406 | .any(|entry| entry.plugin_id == plugin_id && entry.entry == *scope) |
| 407 | }) { |
| 408 | job.cancel.cancel(); |
| 409 | } |
| 410 | } |
| 411 | } |
| 412 | pub(super) fn revoke_attachment(&self, id: u64) { |
| 413 | for job in self.jobs.lock().expect("execution lock").values() { |
| 414 | if job |
| 415 | .caller |
| 416 | .plugins |
| 417 | .as_ref() |
| 418 | .and_then(|plugins| plugins.caller_selection()) |
| 419 | .is_some_and(|selected| selected.attachment_id == id) |
| 420 | { |
| 421 | job.cancel.cancel(); |
| 422 | } |
| 423 | } |
| 424 | } |
| 425 | pub(super) async fn serve( |
| 426 | &self, |
| 427 | shared: &Arc<ManagerShared>, |
| 428 | generation: u64, |
| 429 | params: ExecutionRedeemParams, |
| 430 | cx: HostRequestContext, |
| 431 | ) -> Result<Value, RpcErrorWire> { |
| 432 | let refused = |message: String| RpcErrorWire { |
| 433 | code: error_code::REFUSED, |
| 434 | message, |
| 435 | data: None, |
| 436 | }; |
| 437 | if params.owner.plugin_id != "host:harness" || cx.cancel.is_cancelled() { |
| 438 | return Err(refused("execution is not admitted".into())); |
| 439 | } |
| 440 | let job = self |
| 441 | .jobs |
| 442 | .lock() |
| 443 | .expect("execution lock") |
| 444 | .get(¶ms.execution_id) |
| 445 | .cloned() |
| 446 | .ok_or_else(|| refused("execution is no longer admitted".into()))?; |
| 447 | if generation != job.generation || params.owner != job.owner { |
| 448 | return Err(refused("execution owner or generation changed".into())); |
| 449 | } |
| 450 | job.check(shared).map_err(refused)?; |
| 451 | let target = job |
| 452 | .continuation |
| 453 | .lock() |
| 454 | .expect("execution continuation lock") |
| 455 | .as_ref() |
| 456 | .map(|grant| grant.target.clone()) |
| 457 | .unwrap_or_else(|| job.target.clone()); |
| 458 | if let Err(error) = shared.core_calls.tickets.redeem(&Presented { |
| 459 | ticket: ¶ms.ticket, |
| 460 | kind: TicketKind::Execution, |
| 461 | cohort: HostCohort::Builtin, |
| 462 | host_generation: generation, |
| 463 | owner: ¶ms.owner, |
| 464 | method: "exec/redeem", |
| 465 | target: Some(&target), |
| 466 | }) { |
| 467 | if error.violation { |
| 468 | cx.violation("too many invalid execution tickets".to_string()); |
| 469 | } |
| 470 | return Err(RpcErrorWire { |
| 471 | code: error_code::REFUSED, |
| 472 | message: error.reason.describe().to_string(), |
| 473 | data: None, |
| 474 | }); |
| 475 | } |
| 476 | let mut guard = CancelOnDrop(job.cancel.clone()); |
| 477 | let shared_worker = Arc::clone(shared); |
| 478 | let job_worker = Arc::clone(&job); |
| 479 | let work = dispatch_job( |
| 480 | shared.engine_handle().map_err(refused)?, |
| 481 | job_worker, |
| 482 | move |job| run_job(shared_worker, job), |
| 483 | ); |
| 484 | let result = tokio::select! { |
| 485 | result = work => result.map_err(|_| refused("execution worker failed".into()))?, |
| 486 | _ = cx.cancel.cancelled() => { job.cancel.cancel(); return Err(refused("execution request cancelled".into())); } |
| 487 | }.map_err(refused)?; |
| 488 | job.check(shared).map_err(refused)?; |
| 489 | guard.0 = CancellationToken::new(); |
| 490 | Ok(result) |
| 491 | } |
| 492 | } |
| 493 | struct CancelOnDrop(CancellationToken); |
| 494 | impl Drop for CancelOnDrop { |
| 495 | fn drop(&mut self) { |
| 496 | self.0.cancel(); |
| 497 | } |
| 498 | } |
| 499 | struct Demand<'a>(&'a AtomicU64); |
| 500 | impl Drop for Demand<'_> { |
| 501 | fn drop(&mut self) { |
| 502 | self.0.fetch_sub(1, Ordering::SeqCst); |
| 503 | } |
| 504 | } |
| 505 | struct Invocation { |
| 506 | shared: Arc<ManagerShared>, |
| 507 | job: Arc<Job>, |
| 508 | } |
| 509 | impl Drop for Invocation { |
| 510 | fn drop(&mut self) { |
| 511 | self.job.cancel.cancel(); |
| 512 | self.shared.core_calls.tickets.revoke(&self.job.ticket); |
| 513 | if let Some(grant) = self |
| 514 | .job |
| 515 | .continuation |
| 516 | .lock() |
| 517 | .expect("execution continuation lock") |
| 518 | .as_ref() |
| 519 | { |
| 520 | self.shared.core_calls.tickets.revoke(&grant.ticket); |
| 521 | } |
| 522 | self.shared |
| 523 | .execution_broker |
| 524 | .jobs |
| 525 | .lock() |
| 526 | .expect("execution lock") |
| 527 | .remove(&self.job.id); |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | // A dropped request awaits no result, but the Engine worker retains its job and quota |
| 532 | // until its admitted process/receipt cleanup completes. No transient runtime. |
| 533 | fn dispatch_job<F, R>( |
| 534 | handle: tokio::runtime::Handle, |
| 535 | job: Arc<Job>, |
| 536 | run: F, |
| 537 | ) -> tokio::task::JoinHandle<Result<Value, String>> |
| 538 | where |
| 539 | F: FnOnce(Arc<Job>) -> R + Send + 'static, |
| 540 | R: std::future::Future<Output = Result<Value, String>> + Send + 'static, |
| 541 | { |
| 542 | handle.spawn(async move { |
| 543 | let result = run(Arc::clone(&job)).await; |
| 544 | drop(job); |
| 545 | result |
| 546 | }) |
| 547 | } |
| 548 | |
| 549 | async fn run_job(shared: Arc<ManagerShared>, job: Arc<Job>) -> Result<Value, String> { |
| 550 | job.checked(&shared).await?; |
| 551 | let mut launch = job |
| 552 | .launch |
| 553 | .lock() |
| 554 | .expect("execution launch lock") |
| 555 | .take() |
| 556 | .ok_or("execution was already redeemed")?; |
| 557 | if let Some(github) = launch.github.take() { |
| 558 | let shared_check = Arc::clone(&shared); |
| 559 | let job_check = Arc::clone(&job); |
| 560 | let result = crate::tools::github::host::run( |
| 561 | github.request, |
| 562 | github.context, |
| 563 | job.cancel.clone(), |
| 564 | move || { |
| 565 | let shared = Arc::clone(&shared_check); |
| 566 | let job = Arc::clone(&job_check); |
| 567 | async move { job.checked(&shared).await.map_err(ToolError::not_available) } |
| 568 | }, |
| 569 | Arc::clone(&github.output), |
| 570 | ) |
| 571 | .await; |
| 572 | let projection = match result.as_ref() { |
| 573 | Ok(outcome) => Ok( |
| 574 | json!({"kind":"stock_adapter","operation":"github_result","input":&outcome.projection}), |
| 575 | ), |
| 576 | Err(_) => Err("GitHub Core operation failed".to_string()), |
| 577 | }; |
| 578 | github.output.lock().expect("GitHub result lock").result = Some(result); |
| 579 | // A Core fault never crosses into the Host diagnostic/projection. |
| 580 | let projection = projection?; |
| 581 | job.checked(&shared).await?; |
| 582 | return Ok(projection); |
| 583 | } |
| 584 | if let Some(ocr) = launch.ocr.take() { |
| 585 | match ocr { |
| 586 | OcrLaunch::Native { input, output } => { |
| 587 | let worker = Arc::clone(&job); |
| 588 | let shared_worker = Arc::clone(&shared); |
| 589 | #[cfg(any(test, feature = "test-support"))] |
| 590 | let scope = crate::test_support::env_scope_ticket(); |
| 591 | let policy = activation::extension_host_policy_enabled(); |
| 592 | let step = shared |
| 593 | .engine_handle()? |
| 594 | .spawn_blocking(move || { |
| 595 | let _policy = activation::PolicyScope::propagate(policy); |
| 596 | #[cfg(any(test, feature = "test-support"))] |
| 597 | let _scope = crate::test_support::join_env_scope(scope); |
| 598 | worker.check(&shared_worker)?; |
| 599 | // Retain the same job/quota until non-preemptible Vision FFI exits. |
| 600 | let step = input.native_step(); |
| 601 | worker.check(&shared_worker)?; |
| 602 | Ok::<_, String>(step) |
| 603 | }) |
| 604 | .await |
| 605 | .map_err(|_| "OCR Native worker failed".to_string())??; |
| 606 | job.checked(&shared).await?; |
| 607 | let mut projection = step.projection(); |
| 608 | if step.needs_tesseract() { |
| 609 | let mut continuation = job |
| 610 | .continuation |
| 611 | .lock() |
| 612 | .expect("execution continuation lock"); |
| 613 | job.check(&shared)?; |
| 614 | if continuation.is_some() { |
| 615 | return Err("OCR continuation was already issued".into()); |
| 616 | } |
| 617 | let remaining = job.expires.saturating_duration_since(Instant::now()); |
| 618 | if remaining.is_zero() { |
| 619 | return Err("OCR deadline exhausted".into()); |
| 620 | } |
| 621 | let mut target = job.target.clone(); |
| 622 | target["operation"] = json!("ocr_tesseract"); |
| 623 | target["captured_sha256"] = json!(step.digest()); |
| 624 | let ticket = shared.core_calls.tickets.mint(Grant { |
| 625 | kind: TicketKind::Execution, |
| 626 | cohort: HostCohort::Builtin, |
| 627 | host_generation: job.generation, |
| 628 | owner: job.owner.clone(), |
| 629 | method: "exec/redeem", |
| 630 | target: target.clone(), |
| 631 | ttl: remaining, |
| 632 | uses: 1, |
| 633 | }); |
| 634 | projection["next_ticket"] = json!(ticket.expose()); |
| 635 | *job.launch.lock().expect("execution launch lock") = Some(Launch { |
| 636 | github: None, |
| 637 | ocr: Some(OcrLaunch::Tesseract { step, output }), |
| 638 | pdf: None, |
| 639 | stock: None, |
| 640 | hook: None, |
| 641 | command: None, |
| 642 | input: Vec::new(), |
| 643 | }); |
| 644 | *continuation = Some(Continuation { ticket, target }); |
| 645 | } else { |
| 646 | *output.lock().expect("OCR result lock") = Some(step.finish()); |
| 647 | } |
| 648 | job.checked(&shared).await?; |
| 649 | return Ok(projection); |
| 650 | } |
| 651 | OcrLaunch::Tesseract { step, output } => { |
| 652 | let result = step |
| 653 | .tesseract( |
| 654 | Some(&job.cancel), |
| 655 | tokio::time::Instant::from_std(job.expires), |
| 656 | ) |
| 657 | .await; |
| 658 | let projection = result.projection(); |
| 659 | *output.lock().expect("OCR result lock") = Some(result); |
| 660 | job.checked(&shared).await?; |
| 661 | return Ok(projection); |
| 662 | } |
| 663 | } |
| 664 | } |
| 665 | if let Some(pdf) = launch.pdf.take() { |
| 666 | let result = crate::tools::pdf::run_pdf_driver(pdf.input, Some(&job.cancel)).await; |
| 667 | let projection = result.projection(); |
| 668 | *pdf.output.lock().expect("PDF result lock") = Some(result); |
| 669 | job.checked(&shared).await?; |
| 670 | return Ok(projection); |
| 671 | } |
| 672 | if let Some((operation, input)) = launch.stock.take() { |
| 673 | job.checked(&shared).await?; |
| 674 | return Ok(json!({"kind":"stock_adapter","operation":operation.as_str(),"input":input})); |
| 675 | } |
| 676 | if let Some(launch_hook) = launch.hook.take() { |
| 677 | let job_worker = Arc::clone(&job); |
| 678 | let shared_worker = Arc::clone(&shared); |
| 679 | let policy = activation::extension_host_policy_enabled(); |
| 680 | #[cfg(any(test, feature = "test-support"))] |
| 681 | let env_scope = crate::test_support::env_scope_ticket(); |
| 682 | let result=shared.engine_handle()?.spawn_blocking(move || { |
| 683 | let _policy=activation::PolicyScope::propagate(policy); |
| 684 | #[cfg(any(test, feature = "test-support"))] let _env_scope=crate::test_support::join_env_scope(env_scope); |
| 685 | job_worker.check(&shared_worker)?; |
| 686 | crate::hooks::authority::verify_hook(&launch_hook.hook)?; |
| 687 | if let Some(native)=launch_hook.hook.native_shell.as_ref() { |
| 688 | shared_worker.registry.lock().expect("registry lock").check_shell_hook(native)?; |
| 689 | } |
| 690 | let result=(launch_hook.run)(job_worker.cancel.clone()); |
| 691 | crate::hooks::authority::verify_hook(&launch_hook.hook)?; |
| 692 | if let Some(native)=launch_hook.hook.native_shell.as_ref() { |
| 693 | shared_worker.registry.lock().expect("registry lock").check_shell_hook(native)?; |
| 694 | } |
| 695 | job_worker.check(&shared_worker)?; |
| 696 | // ShellEnv stdout may contain credentials. It is retained only in Rust. |
| 697 | let projection=if launch_hook.hook.event==codewhale_config::hooks::HookEvent::ShellEnv { |
| 698 | json!({"kind":"hook","event":"shell_env","success":result.success,"exit_code":result.exit_code,"keys":crate::hooks::shell_env_keys(&result.stdout)}) |
| 699 | } else if launch_hook.hook.native_shell.is_some() { |
| 700 | json!({"kind":"hook","event":launch_hook.hook.event.as_str(),"success":result.success,"exit_code":result.exit_code,"stdout":result.stdout,"stderr":result.stderr}) |
| 701 | } else { |
| 702 | json!({"kind":"hook","event":launch_hook.hook.event.as_str(),"success":result.success,"exit_code":result.exit_code}) |
| 703 | }; |
| 704 | *job_worker.hook_result.lock().expect("hook result lock")=Some(result); |
| 705 | Ok::<Value,String>(projection) |
| 706 | }).await.map_err(|_|"hook worker was lost".to_string())??; |
| 707 | job.checked(&shared).await?; |
| 708 | return Ok(result); |
| 709 | } |
| 710 | let command = launch |
| 711 | .command |
| 712 | .as_mut() |
| 713 | .ok_or("execution command is missing")?; |
| 714 | // The selected Builtin never sees the environment, argv, input, cwd or decision. |
| 715 | codewhale_runtime::child_env::apply_to_tokio_command( |
| 716 | command, |
| 717 | std::iter::empty::<(&str, &str)>(), |
| 718 | ); |
| 719 | job.check(&shared)?; |
| 720 | let stop = async { |
| 721 | let remaining = job.expires.saturating_duration_since(Instant::now()); |
| 722 | tokio::select! { _ = job.cancel.cancelled() => {}, _ = tokio::time::sleep(remaining) => {}, } |
| 723 | }; |
| 724 | let output = codewhale_runtime::process_tree::contained_output_with_input_bounded( |
| 725 | command, |
| 726 | launch.input, |
| 727 | MAX_STDOUT, |
| 728 | MAX_STDERR, |
| 729 | stop, |
| 730 | ) |
| 731 | .await |
| 732 | .map_err(|_| "execution spawn or output collection failed".to_string())?; |
| 733 | if output.stopped { |
| 734 | return Err("execution cancelled or timed out".into()); |
| 735 | } |
| 736 | job.checked(&shared).await?; |
| 737 | Ok( |
| 738 | json!({"success":output.output.status.success(),"stdout":String::from_utf8_lossy(&output.output.stdout),"stderr":String::from_utf8_lossy(&output.output.stderr)}), |
| 739 | ) |
| 740 | } |
| 741 | |
| 742 | impl ExtensionHostManager { |
| 743 | /// Same weighted quota for the nonpreemptible Core capture worker. |
| 744 | pub fn admit_review_capture(&self) -> Result<OwnedSemaphorePermit, ToolError> { |
| 745 | self.shared |
| 746 | .execution_broker |
| 747 | .admit(StockOperation::ReviewPassPrompt.slots()) |
| 748 | } |
| 749 | |
| 750 | /// Called only by the already planned/gated Script and Command ToolSpecs. |
| 751 | pub async fn execute_script( |
| 752 | &self, |
| 753 | command: tokio::process::Command, |
| 754 | input: Value, |
| 755 | context: &ToolContext, |
| 756 | ) -> Result<ToolResult, ToolError> { |
| 757 | let input = serde_json::to_vec(&input) |
| 758 | .map_err(|_| ToolError::invalid_input("script input is not JSON"))?; |
| 759 | if input.len() > MAX_INPUT { |
| 760 | return Err(ToolError::invalid_input("script input exceeds 1 MiB")); |
| 761 | } |
| 762 | self.execute_launch( |
| 763 | Launch { |
| 764 | github: None, |
| 765 | ocr: None, |
| 766 | pdf: None, |
| 767 | command: Some(command), |
| 768 | input, |
| 769 | hook: None, |
| 770 | stock: None, |
| 771 | }, |
| 772 | context, |
| 773 | DEADLINE, |
| 774 | None, |
| 775 | ) |
| 776 | .await |
| 777 | } |
| 778 | |
| 779 | /// Captured data only. Rust has already performed the planned network/file access |
| 780 | /// and parser checks. No URL, command, environment or writable handle is granted. |
| 781 | pub async fn execute_stock( |
| 782 | &self, |
| 783 | operation: StockOperation, |
| 784 | input: Value, |
| 785 | context: &ToolContext, |
| 786 | budget: Duration, |
| 787 | ) -> Result<ToolResult, ToolError> { |
| 788 | if operation.is_review() |
| 789 | && !context |
| 790 | .features |
| 791 | .enabled(codewhale_runtime::features::Feature::ReviewHost) |
| 792 | { |
| 793 | return Err(ToolError::not_available( |
| 794 | "Review Host backend is not selected", |
| 795 | )); |
| 796 | } |
| 797 | // Admit before constructing the encoded snapshot, and carry this exact |
| 798 | // permit into the actual job. Concurrent validation cannot outrun quota. |
| 799 | let admission = self.shared.execution_broker.admit(operation.slots())?; |
| 800 | check_stock_snapshot(operation, &input)?; |
| 801 | // Adopt the existing Engine scheduler; this never creates a runtime. |
| 802 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 803 | self.bind_engine_handle(handle); |
| 804 | } |
| 805 | self.execute_launch( |
| 806 | Launch { |
| 807 | github: None, |
| 808 | ocr: None, |
| 809 | pdf: None, |
| 810 | command: None, |
| 811 | input: Vec::new(), |
| 812 | hook: None, |
| 813 | stock: Some((operation, input)), |
| 814 | }, |
| 815 | context, |
| 816 | budget, |
| 817 | Some(admission), |
| 818 | ) |
| 819 | .await |
| 820 | } |
| 821 | |
| 822 | /// Only the canonical already-planned ToolSpec can capture a write operation. |
| 823 | pub async fn execute_github( |
| 824 | &self, |
| 825 | request: crate::tools::github::host::Request, |
| 826 | context: &ToolContext, |
| 827 | ) -> Result<ToolResult, ToolError> { |
| 828 | if !context |
| 829 | .features |
| 830 | .enabled(codewhale_runtime::features::Feature::GithubHost) |
| 831 | { |
| 832 | return Err(ToolError::not_available( |
| 833 | "GitHub Host backend is not selected", |
| 834 | )); |
| 835 | } |
| 836 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 837 | self.bind_engine_handle(handle); |
| 838 | } |
| 839 | let caller = Caller::capture(context, &self.shared).map_err(ToolError::not_available)?; |
| 840 | let cancel = context |
| 841 | .cancel_token |
| 842 | .as_ref() |
| 843 | .map(CancellationToken::child_token) |
| 844 | .unwrap_or_default(); |
| 845 | let mut budget = DEADLINE; |
| 846 | if let Some(deadline) = context.turn_deadline { |
| 847 | budget = budget.min(deadline.saturating_duration_since(tokio::time::Instant::now())); |
| 848 | } |
| 849 | self.execute_github_captured(request, Some(context.clone()), caller, cancel, budget) |
| 850 | .await |
| 851 | } |
| 852 | /// Read-only operator path: actual app/session/agent identity, no synthetic tool approval. |
| 853 | pub async fn execute_github_review( |
| 854 | &self, |
| 855 | caller: crate::hooks::HookCaller, |
| 856 | id: String, |
| 857 | ) -> Result<ToolResult, ToolError> { |
| 858 | let session = caller |
| 859 | .session_id |
| 860 | .clone() |
| 861 | .filter(|id| !id.is_empty()) |
| 862 | .ok_or_else(|| { |
| 863 | ToolError::not_available("Feedback review requires the current session") |
| 864 | })?; |
| 865 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 866 | self.bind_engine_handle(handle); |
| 867 | } |
| 868 | let caller = |
| 869 | Caller::from_hook(caller, &self.shared, None).map_err(ToolError::not_available)?; |
| 870 | self.execute_github_captured( |
| 871 | crate::tools::github::host::Request::Read { |
| 872 | session, |
| 873 | id, |
| 874 | operator: true, |
| 875 | }, |
| 876 | None, |
| 877 | caller, |
| 878 | CancellationToken::new(), |
| 879 | Duration::from_secs(30), |
| 880 | ) |
| 881 | .await |
| 882 | } |
| 883 | async fn execute_github_captured( |
| 884 | &self, |
| 885 | request: crate::tools::github::host::Request, |
| 886 | context: Option<ToolContext>, |
| 887 | caller: Caller, |
| 888 | cancel: CancellationToken, |
| 889 | budget: Duration, |
| 890 | ) -> Result<ToolResult, ToolError> { |
| 891 | let output = Arc::new(Mutex::new(crate::tools::github::host::RunState::default())); |
| 892 | let result = self |
| 893 | .execute_launch_for_caller( |
| 894 | Launch { |
| 895 | github: Some(GithubLaunch { |
| 896 | request, |
| 897 | context, |
| 898 | output: Arc::clone(&output), |
| 899 | }), |
| 900 | ocr: None, |
| 901 | pdf: None, |
| 902 | stock: None, |
| 903 | hook: None, |
| 904 | command: None, |
| 905 | input: Vec::new(), |
| 906 | }, |
| 907 | caller, |
| 908 | cancel, |
| 909 | budget, |
| 910 | None, |
| 911 | ) |
| 912 | .await; |
| 913 | crate::tools::github::host::finish_run(&output, result) |
| 914 | } |
| 915 | |
| 916 | /// Only the planned/gated PDF consumers can construct this captured parser job. |
| 917 | pub async fn execute_pdf( |
| 918 | &self, |
| 919 | input: crate::tools::pdf::CapturedPdf, |
| 920 | context: &ToolContext, |
| 921 | ) -> Result<(crate::tools::pdf::PdfProcessOutcome, ToolResult), ToolError> { |
| 922 | if !context |
| 923 | .features |
| 924 | .enabled(codewhale_runtime::features::Feature::PdfHost) |
| 925 | { |
| 926 | return Err(ToolError::not_available("PDF Host backend is not selected")); |
| 927 | } |
| 928 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 929 | self.bind_engine_handle(handle); |
| 930 | } |
| 931 | let mut budget = input.timeout; |
| 932 | if let Some(deadline) = context.turn_deadline { |
| 933 | budget = budget.min(deadline.saturating_duration_since(tokio::time::Instant::now())); |
| 934 | } |
| 935 | let output = Arc::new(Mutex::new(None)); |
| 936 | let result = self |
| 937 | .execute_launch( |
| 938 | Launch { |
| 939 | github: None, |
| 940 | ocr: None, |
| 941 | pdf: Some(PdfLaunch { |
| 942 | input, |
| 943 | output: Arc::clone(&output), |
| 944 | }), |
| 945 | stock: None, |
| 946 | hook: None, |
| 947 | command: None, |
| 948 | input: Vec::new(), |
| 949 | }, |
| 950 | context, |
| 951 | budget, |
| 952 | None, |
| 953 | ) |
| 954 | .await?; |
| 955 | let output = output |
| 956 | .lock() |
| 957 | .expect("PDF result lock") |
| 958 | .take() |
| 959 | .ok_or_else(|| ToolError::execution_failed("PDF driver has no captured output"))?; |
| 960 | Ok((output, result)) |
| 961 | } |
| 962 | |
| 963 | pub async fn execute_ocr( |
| 964 | &self, |
| 965 | input: crate::tools::image_ocr::CapturedOcr, |
| 966 | context: &ToolContext, |
| 967 | ) -> Result<(crate::tools::image_ocr::OcrOutcome, ToolResult), ToolError> { |
| 968 | if !context |
| 969 | .features |
| 970 | .enabled(codewhale_runtime::features::Feature::OcrHost) |
| 971 | { |
| 972 | return Err(ToolError::not_available("OCR Host backend is not selected")); |
| 973 | } |
| 974 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 975 | self.bind_engine_handle(handle); |
| 976 | } |
| 977 | let budget = context |
| 978 | .turn_deadline |
| 979 | .map(|deadline| deadline.saturating_duration_since(tokio::time::Instant::now())) |
| 980 | .unwrap_or(DEADLINE) |
| 981 | .min(DEADLINE); |
| 982 | let output = Arc::new(Mutex::new(None)); |
| 983 | let result = self |
| 984 | .execute_launch( |
| 985 | Launch { |
| 986 | github: None, |
| 987 | ocr: Some(OcrLaunch::Native { |
| 988 | input, |
| 989 | output: Arc::clone(&output), |
| 990 | }), |
| 991 | pdf: None, |
| 992 | stock: None, |
| 993 | hook: None, |
| 994 | command: None, |
| 995 | input: Vec::new(), |
| 996 | }, |
| 997 | context, |
| 998 | budget, |
| 999 | None, |
| 1000 | ) |
| 1001 | .await; |
| 1002 | let decision = match result { |
| 1003 | Err(_) |
| 1004 | if context |
| 1005 | .cancel_token |
| 1006 | .as_ref() |
| 1007 | .is_some_and(CancellationToken::is_cancelled) => |
| 1008 | { |
| 1009 | return Err(ToolError::cancelled("Image OCR was cancelled")); |
| 1010 | } |
| 1011 | other => other?, |
| 1012 | }; |
| 1013 | let outcome = output |
| 1014 | .lock() |
| 1015 | .expect("OCR result lock") |
| 1016 | .take() |
| 1017 | .ok_or_else(|| ToolError::execution_failed("OCR driver has no captured output"))?; |
| 1018 | Ok((outcome, decision)) |
| 1019 | } |
| 1020 | |
| 1021 | async fn execute_launch( |
| 1022 | &self, |
| 1023 | launch: Launch, |
| 1024 | context: &ToolContext, |
| 1025 | budget: Duration, |
| 1026 | admission: Option<OwnedSemaphorePermit>, |
| 1027 | ) -> Result<ToolResult, ToolError> { |
| 1028 | let caller = Caller::capture(context, &self.shared).map_err(ToolError::not_available)?; |
| 1029 | let cancel = context |
| 1030 | .cancel_token |
| 1031 | .as_ref() |
| 1032 | .map(CancellationToken::child_token) |
| 1033 | .unwrap_or_default(); |
| 1034 | self.execute_launch_for_caller(launch, caller, cancel, budget, admission) |
| 1035 | .await |
| 1036 | } |
| 1037 | |
| 1038 | async fn execute_launch_for_caller( |
| 1039 | &self, |
| 1040 | launch: Launch, |
| 1041 | mut caller: Caller, |
| 1042 | cancel: CancellationToken, |
| 1043 | budget: Duration, |
| 1044 | admission: Option<OwnedSemaphorePermit>, |
| 1045 | ) -> Result<ToolResult, ToolError> { |
| 1046 | self.shared |
| 1047 | .engine_handle() |
| 1048 | .map_err(ToolError::not_available)?; |
| 1049 | let budget = budget.min(DEADLINE); |
| 1050 | if budget.is_zero() { |
| 1051 | return Err(ToolError::Timeout { seconds: 0 }); |
| 1052 | } |
| 1053 | let expires = Instant::now() + budget; |
| 1054 | let stock = launch.stock.is_some() |
| 1055 | || launch.pdf.is_some() |
| 1056 | || launch.ocr.is_some() |
| 1057 | || launch.github.is_some(); |
| 1058 | caller.requires_native_policy = !stock; |
| 1059 | caller |
| 1060 | .check(&self.shared) |
| 1061 | .map_err(ToolError::not_available)?; |
| 1062 | let operation = launch.stock.as_ref().map(|(operation, _)| *operation); |
| 1063 | let review = operation.is_some_and(StockOperation::is_review); |
| 1064 | let permit = match admission { |
| 1065 | Some(admission) => admission, |
| 1066 | None => self |
| 1067 | .shared |
| 1068 | .execution_broker |
| 1069 | .admit(operation.map_or(1, StockOperation::slots))?, |
| 1070 | }; |
| 1071 | let demand = if stock { |
| 1072 | &self.shared.stock_users |
| 1073 | } else { |
| 1074 | &self.shared.harness_users |
| 1075 | }; |
| 1076 | demand.fetch_add(1, Ordering::SeqCst); |
| 1077 | let _demand = Demand(demand); |
| 1078 | let ready = async { |
| 1079 | if stock { |
| 1080 | self.ensure_stock_builtin().await |
| 1081 | } else { |
| 1082 | self.ensure_harness_builtin().await |
| 1083 | } |
| 1084 | }; |
| 1085 | |
| 1086 | let deadline = tokio::time::Instant::from_std(expires); |
| 1087 | let (host, owner, generation) = tokio::select! { |
| 1088 | biased; |
| 1089 | _ = cancel.cancelled() => return Err(ToolError::not_available("execution cancelled")), |
| 1090 | ready = tokio::time::timeout_at(deadline, ready) => ready |
| 1091 | .map_err(|_| ToolError::Timeout { seconds: budget.as_secs().saturating_add(u64::from(budget.subsec_nanos() != 0)) })? |
| 1092 | .map_err(ToolError::not_available)?, |
| 1093 | }; |
| 1094 | caller |
| 1095 | .check(&self.shared) |
| 1096 | .map_err(ToolError::not_available)?; |
| 1097 | let id = uuid::Uuid::new_v4().to_string(); |
| 1098 | let mut target = caller.target(&id); |
| 1099 | if let Some(github) = launch.github.as_ref() { |
| 1100 | target["operation"] = json!("github_capture"); |
| 1101 | target["snapshot_sha256"] = json!(codewhale_runtime::hashing::sha256_hex( |
| 1102 | &serde_json::to_vec(&github.request) |
| 1103 | .map_err(|_| ToolError::invalid_input("GitHub operation is not JSON"))? |
| 1104 | )); |
| 1105 | } |
| 1106 | if let Some(OcrLaunch::Native { input, .. }) = launch.ocr.as_ref() { |
| 1107 | target["operation"] = json!("ocr_native"); |
| 1108 | target["captured_sha256"] = json!(input.digest()); |
| 1109 | } |
| 1110 | if let Some(pdf) = launch.pdf.as_ref() { |
| 1111 | target["operation"] = json!("pdf_extract"); |
| 1112 | target["captured_sha256"] = json!(pdf.input.digest()); |
| 1113 | } |
| 1114 | if let Some((operation, input)) = launch.stock.as_ref() { |
| 1115 | target["operation"] = json!(operation.as_str()); |
| 1116 | target["snapshot_sha256"] = json!(codewhale_runtime::hashing::sha256_hex( |
| 1117 | &serde_json::to_vec(input) |
| 1118 | .map_err(|_| ToolError::invalid_input("adapter snapshot is not JSON"))? |
| 1119 | )); |
| 1120 | } |
| 1121 | let remaining = expires.saturating_duration_since(Instant::now()); |
| 1122 | if remaining.is_zero() { |
| 1123 | return Err(ToolError::not_available("execution deadline exhausted")); |
| 1124 | } |
| 1125 | let ticket = self.shared.core_calls.tickets.mint(Grant { |
| 1126 | kind: TicketKind::Execution, |
| 1127 | cohort: HostCohort::Builtin, |
| 1128 | host_generation: generation, |
| 1129 | owner: owner.clone(), |
| 1130 | method: "exec/redeem", |
| 1131 | target: target.clone(), |
| 1132 | ttl: remaining, |
| 1133 | uses: 1, |
| 1134 | }); |
| 1135 | let job = Arc::new(Job { |
| 1136 | id: id.clone(), |
| 1137 | owner: owner.clone(), |
| 1138 | generation, |
| 1139 | caller, |
| 1140 | target, |
| 1141 | expires, |
| 1142 | cancel, |
| 1143 | launch: Mutex::new(Some(launch)), |
| 1144 | ticket: ticket.clone(), |
| 1145 | continuation: Mutex::new(None), |
| 1146 | hook_result: Mutex::new(None), |
| 1147 | _permit: permit, |
| 1148 | }); |
| 1149 | self.shared |
| 1150 | .execution_broker |
| 1151 | .jobs |
| 1152 | .lock() |
| 1153 | .expect("execution lock") |
| 1154 | .insert(id.clone(), Arc::clone(&job)); |
| 1155 | let _invocation = Invocation { |
| 1156 | shared: Arc::clone(&self.shared), |
| 1157 | job: Arc::clone(&job), |
| 1158 | }; |
| 1159 | let request = host.call( |
| 1160 | CoreRequest::HarnessRun(HarnessRunParams { |
| 1161 | owner, |
| 1162 | execution_id: id, |
| 1163 | ticket: ticket.expose().to_string(), |
| 1164 | // Round the peer timer up: Core owns the exact deadline and must |
| 1165 | // settle expiry before a rounded-down Host timer reports a runner fault. |
| 1166 | deadline_ms: remaining.as_nanos().div_ceil(1_000_000).max(1) as u64, |
| 1167 | hook: None, |
| 1168 | }), |
| 1169 | Some("host:harness".into()), |
| 1170 | ); |
| 1171 | let value = tokio::select! { |
| 1172 | biased; |
| 1173 | _ = job.cancel.cancelled() => return Err(ToolError::not_available("execution cancelled")), |
| 1174 | value = tokio::time::timeout_at(deadline, request) => value |
| 1175 | .map_err(|_| ToolError::Timeout { seconds: budget.as_secs().saturating_add(u64::from(budget.subsec_nanos() != 0)) })? |
| 1176 | .map_err(|_| ToolError::execution_failed("Builtin runner failed; no Rust fallback was attempted"))?, |
| 1177 | }; |
| 1178 | job.checked(&self.shared) |
| 1179 | .await |
| 1180 | .map_err(ToolError::not_available)?; |
| 1181 | if review |
| 1182 | && !review_envelope_fits(&value).map_err(|_| { |
| 1183 | ToolError::execution_failed( |
| 1184 | "Serialized review result exceeds the existing frame limit", |
| 1185 | ) |
| 1186 | })? |
| 1187 | { |
| 1188 | return Err(ToolError::execution_failed( |
| 1189 | "Serialized review result/envelope exceeds 16 MiB", |
| 1190 | )); |
| 1191 | } |
| 1192 | if stock |
| 1193 | && !review |
| 1194 | && serde_json::to_vec(&value) |
| 1195 | .map_err(|_| ToolError::execution_failed("Builtin result is not JSON"))? |
| 1196 | .len() |
| 1197 | > MAX_INPUT |
| 1198 | { |
| 1199 | return Err(ToolError::execution_failed("Builtin result exceeds 1 MiB")); |
| 1200 | } |
| 1201 | if value.get("ok").and_then(Value::as_bool) == Some(true) { |
| 1202 | serde_json::from_value( |
| 1203 | value |
| 1204 | .get("result") |
| 1205 | .cloned() |
| 1206 | .ok_or_else(|| ToolError::execution_failed("Builtin result missing"))?, |
| 1207 | ) |
| 1208 | .map_err(|_| ToolError::execution_failed("Builtin result malformed")) |
| 1209 | } else { |
| 1210 | Err(ToolError::execution_failed( |
| 1211 | value |
| 1212 | .get("error") |
| 1213 | .and_then(Value::as_str) |
| 1214 | .unwrap_or("Builtin result failed"), |
| 1215 | )) |
| 1216 | } |
| 1217 | } |
| 1218 | } |
| 1219 | |
| 1220 | impl ExtensionHostManager { |
| 1221 | pub async fn execute_hook<F>( |
| 1222 | &self, |
| 1223 | caller: crate::hooks::HookCaller, |
| 1224 | hook: codewhale_config::hooks::Hook, |
| 1225 | timeout: Duration, |
| 1226 | query: String, |
| 1227 | run: F, |
| 1228 | ) -> Result<crate::hooks::HookResult, String> |
| 1229 | where |
| 1230 | F: FnOnce(CancellationToken) -> crate::hooks::HookResult + Send + 'static, |
| 1231 | { |
| 1232 | self.shared.engine_handle()?; |
| 1233 | let deadline_ms = u64::try_from(timeout.as_millis()) |
| 1234 | .map_err(|_| "hook timeout exceeds the execution bound")?; |
| 1235 | if deadline_ms == 0 || deadline_ms > i32::MAX as u64 { |
| 1236 | return Err("hook timeout exceeds the execution bound".into()); |
| 1237 | } |
| 1238 | let caller = Caller::from_hook( |
| 1239 | caller, |
| 1240 | &self.shared, |
| 1241 | Some( |
| 1242 | hook.native_shell |
| 1243 | .as_ref() |
| 1244 | .map_or("", |native| native.owner.plugin_id.as_str()), |
| 1245 | ), |
| 1246 | )?; |
| 1247 | caller.check(&self.shared)?; |
| 1248 | let permit = Arc::clone(&self.shared.execution_broker.slots) |
| 1249 | .try_acquire_owned() |
| 1250 | .map_err(|_| "execution concurrency limit reached")?; |
| 1251 | self.shared.harness_users.fetch_add(1, Ordering::SeqCst); |
| 1252 | let _demand = Demand(&self.shared.harness_users); |
| 1253 | let (host, owner, generation) = self.ensure_harness_builtin().await?; |
| 1254 | caller.check(&self.shared)?; |
| 1255 | let id = uuid::Uuid::new_v4().to_string(); |
| 1256 | let metadata = super::protocol::HookDispatchWire { |
| 1257 | event: hook.event.as_str().into(), |
| 1258 | dialect: hook |
| 1259 | .native_shell |
| 1260 | .as_ref() |
| 1261 | .map_or("codewhale".into(), |n| n.dialect.clone()), |
| 1262 | point: hook |
| 1263 | .native_shell |
| 1264 | .as_ref() |
| 1265 | .map_or(hook.event.as_str().into(), |n| n.point.clone()), |
| 1266 | matcher: hook.native_shell.as_ref().and_then(|n| n.matcher.clone()), |
| 1267 | query, |
| 1268 | }; |
| 1269 | let target = json!({"caller":caller.target(&id),"hook":metadata}); |
| 1270 | let ticket = self.shared.core_calls.tickets.mint(Grant { |
| 1271 | kind: TicketKind::Execution, |
| 1272 | cohort: HostCohort::Builtin, |
| 1273 | host_generation: generation, |
| 1274 | owner: owner.clone(), |
| 1275 | method: "exec/redeem", |
| 1276 | target: target.clone(), |
| 1277 | ttl: timeout, |
| 1278 | uses: 1, |
| 1279 | }); |
| 1280 | let job = Arc::new(Job { |
| 1281 | id: id.clone(), |
| 1282 | owner: owner.clone(), |
| 1283 | generation, |
| 1284 | caller, |
| 1285 | target, |
| 1286 | expires: Instant::now() |
| 1287 | .checked_add(timeout) |
| 1288 | .ok_or("hook timeout is not representable")?, |
| 1289 | cancel: CancellationToken::new(), |
| 1290 | launch: Mutex::new(Some(Launch { |
| 1291 | github: None, |
| 1292 | ocr: None, |
| 1293 | pdf: None, |
| 1294 | stock: None, |
| 1295 | command: None, |
| 1296 | input: Vec::new(), |
| 1297 | hook: Some(HookLaunch { |
| 1298 | run: Box::new(run), |
| 1299 | hook: hook.clone(), |
| 1300 | }), |
| 1301 | })), |
| 1302 | ticket: ticket.clone(), |
| 1303 | continuation: Mutex::new(None), |
| 1304 | hook_result: Mutex::new(None), |
| 1305 | _permit: permit, |
| 1306 | }); |
| 1307 | self.shared |
| 1308 | .execution_broker |
| 1309 | .jobs |
| 1310 | .lock() |
| 1311 | .expect("execution lock") |
| 1312 | .insert(id.clone(), Arc::clone(&job)); |
| 1313 | let _invocation = Invocation { |
| 1314 | shared: Arc::clone(&self.shared), |
| 1315 | job: Arc::clone(&job), |
| 1316 | }; |
| 1317 | let value = host |
| 1318 | .call( |
| 1319 | CoreRequest::HarnessRun(HarnessRunParams { |
| 1320 | owner, |
| 1321 | execution_id: id, |
| 1322 | ticket: ticket.expose().into(), |
| 1323 | deadline_ms, |
| 1324 | hook: Some(metadata), |
| 1325 | }), |
| 1326 | Some("host:harness".into()), |
| 1327 | ) |
| 1328 | .await |
| 1329 | .map_err(|_| "Builtin hook runner failed; no legacy fallback was attempted")?; |
| 1330 | job.checked(&self.shared).await?; |
| 1331 | if value.get("hook_skipped").and_then(Value::as_bool) == Some(true) { |
| 1332 | if job.hook_result.lock().expect("hook result lock").is_some() { |
| 1333 | return Err("hook ran despite its nonmatching receipt".into()); |
| 1334 | } |
| 1335 | return Ok(crate::hooks::HookResult { |
| 1336 | name: hook.name, |
| 1337 | success: true, |
| 1338 | background: false, |
| 1339 | strict: false, |
| 1340 | exit_code: Some(0), |
| 1341 | stdout: String::new(), |
| 1342 | stderr: String::new(), |
| 1343 | duration: Duration::ZERO, |
| 1344 | error: None, |
| 1345 | }); |
| 1346 | } |
| 1347 | if value.get("hook_completed").and_then(Value::as_bool) != Some(true) { |
| 1348 | return Err("Builtin hook receipt is missing".into()); |
| 1349 | } |
| 1350 | let mut result = job |
| 1351 | .hook_result |
| 1352 | .lock() |
| 1353 | .expect("hook result lock") |
| 1354 | .take() |
| 1355 | .ok_or("hook process produced no receipt")?; |
| 1356 | // Only Native dialect codecs may project a bounded proposal; final steering stays Rust-owned. |
| 1357 | if hook.native_shell.is_some() |
| 1358 | && hook.event != codewhale_config::hooks::HookEvent::ShellEnv |
| 1359 | && let Some(stdout) = value.get("proposal").and_then(Value::as_str) |
| 1360 | { |
| 1361 | if stdout.len() > 64 * 1024 { |
| 1362 | return Err("hook proposal exceeds 64 KiB".into()); |
| 1363 | } |
| 1364 | result.stdout = stdout.into(); |
| 1365 | } |
| 1366 | Ok(result) |
| 1367 | } |
| 1368 | } |
| 1369 | |
| 1370 | #[cfg(test)] |
| 1371 | mod tests { |
| 1372 | use super::super::{ExtensionHostOptions, ticket::TicketTable}; |
| 1373 | use super::*; |
| 1374 | fn caller() -> Caller { |
| 1375 | Caller { |
| 1376 | workspace: std::path::PathBuf::from("."), |
| 1377 | plugins: None, |
| 1378 | session_id: Some("session".into()), |
| 1379 | agent_id: Some("agent".into()), |
| 1380 | origin_turn_id: Some("turn".into()), |
| 1381 | origin_call_id: Some("call".into()), |
| 1382 | authorities: Vec::new(), |
| 1383 | native_owners: Vec::new(), |
| 1384 | native_host_generations: Vec::new(), |
| 1385 | requires_native_policy: true, |
| 1386 | } |
| 1387 | } |
| 1388 | fn owner() -> OwnerRef { |
| 1389 | OwnerRef { |
| 1390 | plugin_id: "host:harness".into(), |
| 1391 | generation: 3, |
| 1392 | owner_token: "test-owner".into(), |
| 1393 | } |
| 1394 | } |
| 1395 | fn grant(owner: OwnerRef, target: Value) -> Grant { |
| 1396 | Grant { |
| 1397 | kind: TicketKind::Execution, |
| 1398 | cohort: HostCohort::Builtin, |
| 1399 | host_generation: 4, |
| 1400 | owner, |
| 1401 | method: "exec/redeem", |
| 1402 | target, |
| 1403 | ttl: DEADLINE, |
| 1404 | uses: 1, |
| 1405 | } |
| 1406 | } |
| 1407 | #[test] |
| 1408 | fn review_purpose_bounds_use_the_encoded_frame_and_keep_other_helpers_at_one_mib() { |
| 1409 | let large = json!({"kind":"cli_diff","diff":"漢".repeat(400_000)+"FINAL_END"}); |
| 1410 | assert!(serde_json::to_vec(&large).unwrap().len() > MAX_INPUT); |
| 1411 | assert!(check_stock_snapshot(StockOperation::ReviewSourcePrompt, &large).is_ok()); |
| 1412 | assert!(check_stock_snapshot(StockOperation::SpeechOptions, &large).is_err()); |
| 1413 | let escaped = json!({"kind":"cli_diff","diff":"\0".repeat(3*1024*1024)}); |
| 1414 | assert!(escaped["diff"].as_str().unwrap().len() < MAX_REVIEW); |
| 1415 | assert!(check_stock_snapshot(StockOperation::ReviewSourcePrompt, &escaped).is_err()); |
| 1416 | let result = json!({"ok":true,"result":{"content":"\0".repeat(3*1024*1024),"success":true,"metadata":null}}); |
| 1417 | assert!(!review_envelope_fits(&result).unwrap()); |
| 1418 | let frame = super::super::protocol::encode_frame( |
| 1419 | &json!({"jsonrpc":"2.0","id":u64::MAX,"result":large}), |
| 1420 | ) |
| 1421 | .unwrap(); |
| 1422 | assert_eq!( |
| 1423 | review_envelope_fits(&large).unwrap(), |
| 1424 | frame.len() <= MAX_REVIEW |
| 1425 | ); |
| 1426 | } |
| 1427 | |
| 1428 | #[test] |
| 1429 | fn weighted_review_admission_reuses_all_thirty_two_execution_slots() { |
| 1430 | let broker = Broker::default(); |
| 1431 | let first = broker.admit(StockOperation::ReviewReport.slots()).unwrap(); |
| 1432 | let second = broker |
| 1433 | .admit(StockOperation::ReviewPassPrompt.slots()) |
| 1434 | .unwrap(); |
| 1435 | assert_eq!(broker.slots.available_permits(), 0); |
| 1436 | assert!(broker.admit(1).is_err()); |
| 1437 | assert!(broker.admit(16).is_err()); |
| 1438 | drop(first); |
| 1439 | assert_eq!(broker.slots.available_permits(), 16); |
| 1440 | let ordinary = broker.admit(1).unwrap(); |
| 1441 | assert!(broker.admit(16).is_err()); |
| 1442 | drop(second); |
| 1443 | drop(ordinary); |
| 1444 | assert_eq!(broker.slots.available_permits(), MAX_JOBS); |
| 1445 | } |
| 1446 | |
| 1447 | #[tokio::test(flavor = "current_thread")] |
| 1448 | async fn abandoned_review_capture_worker_retains_weighted_quota_until_completion() { |
| 1449 | let manager = ExtensionHostManager::new(ExtensionHostOptions::default()); |
| 1450 | let permit = manager.admit_review_capture().unwrap(); |
| 1451 | let occupied = manager.admit_review_capture().unwrap(); |
| 1452 | let (started_tx, started_rx) = tokio::sync::oneshot::channel(); |
| 1453 | let (finish_tx, finish_rx) = std::sync::mpsc::channel(); |
| 1454 | let waiter = tokio::spawn(crate::tools::github::host::report_worker( |
| 1455 | permit, |
| 1456 | move || { |
| 1457 | started_tx.send(()).unwrap(); |
| 1458 | finish_rx.recv().unwrap(); |
| 1459 | Ok(()) |
| 1460 | }, |
| 1461 | )); |
| 1462 | started_rx.await.unwrap(); |
| 1463 | waiter.abort(); |
| 1464 | assert!(waiter.await.unwrap_err().is_cancelled()); |
| 1465 | assert!(manager.admit_review_capture().is_err()); |
| 1466 | assert_eq!(manager.shared.execution_broker.slots.available_permits(), 0); |
| 1467 | drop(occupied); |
| 1468 | assert_eq!( |
| 1469 | manager.shared.execution_broker.slots.available_permits(), |
| 1470 | 16 |
| 1471 | ); |
| 1472 | finish_tx.send(()).unwrap(); |
| 1473 | tokio::time::timeout(Duration::from_secs(2), async { |
| 1474 | while manager.shared.execution_broker.slots.available_permits() != MAX_JOBS { |
| 1475 | tokio::task::yield_now().await; |
| 1476 | } |
| 1477 | }) |
| 1478 | .await |
| 1479 | .unwrap(); |
| 1480 | assert!(manager.admit_review_capture().is_ok()); |
| 1481 | } |
| 1482 | |
| 1483 | #[tokio::test(flavor = "current_thread")] |
| 1484 | async fn actual_review_host_matches_frozen_core_cases_and_accepts_over_one_mib() { |
| 1485 | let _home = crate::test_support::SealedHome::new(); |
| 1486 | let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(false); |
| 1487 | let Some(node) = super::super::test_support::node_for_tests("review_captured_parity") |
| 1488 | else { |
| 1489 | return; |
| 1490 | }; |
| 1491 | let root = tempfile::tempdir().unwrap(); |
| 1492 | let manager = ExtensionHostManager::new(ExtensionHostOptions { |
| 1493 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 1494 | node_override: Some(node), |
| 1495 | root: Some(root.path().join("host")), |
| 1496 | ..Default::default() |
| 1497 | }); |
| 1498 | let mut features = codewhale_runtime::features::Features::with_defaults(); |
| 1499 | features.enable(codewhale_runtime::features::Feature::ReviewHost); |
| 1500 | let context = ToolContext::new(root.path()).with_features(features); |
| 1501 | let fixture: Value = |
| 1502 | serde_json::from_str(include_str!("../../tests/fixtures/review-host-parity.json")) |
| 1503 | .unwrap(); |
| 1504 | for case in fixture["cases"].as_array().unwrap() { |
| 1505 | let operation = match case["operation"].as_str().unwrap() { |
| 1506 | "review_source_prompt" => StockOperation::ReviewSourcePrompt, |
| 1507 | "review_interactive_pr" => StockOperation::ReviewInteractivePr, |
| 1508 | "review_report" => StockOperation::ReviewReport, |
| 1509 | _ => panic!("unadmitted fixture operation"), |
| 1510 | }; |
| 1511 | let result = manager |
| 1512 | .execute_stock( |
| 1513 | operation, |
| 1514 | case["input"].clone(), |
| 1515 | &context, |
| 1516 | Duration::from_secs(10), |
| 1517 | ) |
| 1518 | .await |
| 1519 | .unwrap(); |
| 1520 | assert_eq!(result.content, case["content"].as_str().unwrap()); |
| 1521 | assert!(result.success); |
| 1522 | assert!(result.metadata.is_none()); |
| 1523 | } |
| 1524 | let input = json!({"kind":"cli_diff","diff":"漢".repeat(400_000)+"FINAL_END"}); |
| 1525 | let result = manager |
| 1526 | .execute_stock( |
| 1527 | StockOperation::ReviewSourcePrompt, |
| 1528 | input, |
| 1529 | &context, |
| 1530 | Duration::from_secs(10), |
| 1531 | ) |
| 1532 | .await |
| 1533 | .unwrap(); |
| 1534 | assert!(result.content.ends_with("FINAL_END\n\nEnd of diff.")); |
| 1535 | let cancelled = CancellationToken::new(); |
| 1536 | cancelled.cancel(); |
| 1537 | let error = manager |
| 1538 | .execute_stock( |
| 1539 | StockOperation::ReviewReport, |
| 1540 | json!({"review":null,"output":"late","posted":false}), |
| 1541 | &context.with_cancel_token(cancelled), |
| 1542 | Duration::from_secs(10), |
| 1543 | ) |
| 1544 | .await |
| 1545 | .unwrap_err(); |
| 1546 | assert!(matches!( |
| 1547 | error, |
| 1548 | ToolError::NotAvailable { .. } | ToolError::Cancelled { .. } |
| 1549 | )); |
| 1550 | manager.shutdown().await; |
| 1551 | } |
| 1552 | |
| 1553 | #[test] |
| 1554 | fn execution_ticket_cannot_redeem_mcp_or_replay_or_change_caller() { |
| 1555 | let table = TicketTable::default(); |
| 1556 | let owner = owner(); |
| 1557 | let caller = caller(); |
| 1558 | let target = caller.target("exact"); |
| 1559 | let ticket = table.mint(grant(owner.clone(), target.clone())); |
| 1560 | let mut present = Presented { |
| 1561 | ticket: ticket.expose(), |
| 1562 | kind: TicketKind::McpOperation, |
| 1563 | cohort: HostCohort::Builtin, |
| 1564 | host_generation: 4, |
| 1565 | owner: &owner, |
| 1566 | method: "exec/redeem", |
| 1567 | target: Some(&target), |
| 1568 | }; |
| 1569 | assert!(table.redeem(&present).is_err()); |
| 1570 | present.kind = TicketKind::Execution; |
| 1571 | let wrong = json!({"execution_id":"exact","session_id":"another"}); |
| 1572 | present.target = Some(&wrong); |
| 1573 | assert!(table.redeem(&present).is_err()); |
| 1574 | present.target = Some(&target); |
| 1575 | assert!(table.redeem(&present).is_ok()); |
| 1576 | assert!(table.redeem(&present).is_err()); |
| 1577 | } |
| 1578 | #[test] |
| 1579 | fn execution_caller_checks_exact_session_agent_and_selected_view() { |
| 1580 | let _policy = activation::PolicyScope::propagate(true); |
| 1581 | let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default())); |
| 1582 | let attachment = manager.attach(Arc::new(PluginRegistry::empty(std::path::Path::new(".")))); |
| 1583 | attachment.set_identity(Some("session".into()), Some("agent".into())); |
| 1584 | let mut caller = caller(); |
| 1585 | caller.plugins = Some(attachment.plugin_view()); |
| 1586 | assert!(caller.check(&manager.shared).is_ok()); |
| 1587 | caller.session_id = Some("other".into()); |
| 1588 | assert!(caller.check(&manager.shared).is_err()); |
| 1589 | caller.session_id = Some("session".into()); |
| 1590 | caller.agent_id = None; |
| 1591 | assert!(caller.check(&manager.shared).is_err()); |
| 1592 | caller.agent_id = Some("agent".into()); |
| 1593 | drop(attachment); |
| 1594 | assert!(caller.check(&manager.shared).is_err()); |
| 1595 | } |
| 1596 | #[tokio::test(flavor = "current_thread")] |
| 1597 | async fn actual_github_broker_returns_private_core_permission_fault() { |
| 1598 | use codewhale_net::network_policy::{DecisionToml, NetworkPolicy, NetworkPolicyDecider}; |
| 1599 | let _home = crate::test_support::SealedHome::new(); |
| 1600 | let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(false); |
| 1601 | let Some(node) = super::super::test_support::node_for_tests("github_private_core_fault") |
| 1602 | else { |
| 1603 | return; |
| 1604 | }; |
| 1605 | let temp = tempfile::tempdir().unwrap(); |
| 1606 | let _repo = crate::test_support::EnvVarGuard::set("GH_REPO", "owner/name"); |
| 1607 | let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions { |
| 1608 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 1609 | node_override: Some(node), |
| 1610 | root: Some(temp.path().join("host")), |
| 1611 | ..Default::default() |
| 1612 | })); |
| 1613 | let mut context = |
| 1614 | ToolContext::new(temp.path()).with_network_policy(NetworkPolicyDecider::new( |
| 1615 | NetworkPolicy { |
| 1616 | default: DecisionToml::Deny, |
| 1617 | ..Default::default() |
| 1618 | }, |
| 1619 | None, |
| 1620 | )); |
| 1621 | context |
| 1622 | .features |
| 1623 | .enable(codewhale_runtime::features::Feature::GithubHost); |
| 1624 | let error = manager |
| 1625 | .execute_github( |
| 1626 | crate::tools::github::host::Request::Comment { |
| 1627 | target: "issue".into(), |
| 1628 | number: 1, |
| 1629 | body: "never sent".into(), |
| 1630 | dry: false, |
| 1631 | }, |
| 1632 | &context, |
| 1633 | ) |
| 1634 | .await |
| 1635 | .unwrap_err(); |
| 1636 | assert!(matches!(error, ToolError::PermissionDenied { .. })); |
| 1637 | assert!( |
| 1638 | error |
| 1639 | .to_string() |
| 1640 | .contains("blocked or awaiting network approval") |
| 1641 | ); |
| 1642 | assert!(!error.to_string().contains("Builtin runner failed")); |
| 1643 | assert!(!error.to_string().contains("never sent")); |
| 1644 | manager.shutdown().await; |
| 1645 | } |
| 1646 | |
| 1647 | #[cfg(unix)] |
| 1648 | #[tokio::test(flavor = "current_thread")] |
| 1649 | async fn actual_ocr_native_cancel_retains_job_quota_until_framework_worker_exits() { |
| 1650 | let _home = crate::test_support::SealedHome::new(); |
| 1651 | let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(false); |
| 1652 | let Some(node) = super::super::test_support::node_for_tests("ocr_native_quota") else { |
| 1653 | return; |
| 1654 | }; |
| 1655 | let root = tempfile::tempdir().unwrap(); |
| 1656 | let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions { |
| 1657 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 1658 | node_override: Some(node), |
| 1659 | root: Some(root.path().join("host")), |
| 1660 | ..ExtensionHostOptions::default() |
| 1661 | })); |
| 1662 | let started = Arc::new(tokio::sync::Notify::new()); |
| 1663 | let release = Arc::new((Mutex::new(false), std::sync::Condvar::new())); |
| 1664 | let announce = Arc::clone(&started); |
| 1665 | let latch = Arc::clone(&release); |
| 1666 | let input = crate::tools::image_ocr::CapturedOcr::for_test( |
| 1667 | root.path(), |
| 1668 | Arc::new(move |_| { |
| 1669 | announce.notify_one(); |
| 1670 | let (lock, wake) = &*latch; |
| 1671 | let mut ready = lock.lock().unwrap(); |
| 1672 | while !*ready { |
| 1673 | ready = wake.wait(ready).unwrap(); |
| 1674 | } |
| 1675 | Ok(Some("discarded late Native text".into())) |
| 1676 | }), |
| 1677 | None, |
| 1678 | ); |
| 1679 | let mut flags = codewhale_runtime::features::Features::with_defaults(); |
| 1680 | flags.enable(codewhale_runtime::features::Feature::OcrHost); |
| 1681 | let cancel = CancellationToken::new(); |
| 1682 | let context = ToolContext::new(root.path()) |
| 1683 | .with_features(flags) |
| 1684 | .with_cancel_token(cancel.clone()); |
| 1685 | let future = manager.execute_ocr(input, &context); |
| 1686 | tokio::pin!(future); |
| 1687 | tokio::select! {result=&mut future=>panic!("OCR settled before its blocking worker: {:?}",result.err()),_=started.notified()=>{},} |
| 1688 | cancel.cancel(); |
| 1689 | assert!(matches!(future.await, Err(ToolError::Cancelled { .. }))); |
| 1690 | assert_eq!( |
| 1691 | manager.shared.execution_broker.slots.available_permits(), |
| 1692 | MAX_JOBS - 1 |
| 1693 | ); |
| 1694 | let (lock, wake) = &*release; |
| 1695 | *lock.lock().unwrap() = true; |
| 1696 | wake.notify_all(); |
| 1697 | tokio::time::timeout(Duration::from_secs(5), async { |
| 1698 | while manager.shared.execution_broker.slots.available_permits() != MAX_JOBS { |
| 1699 | tokio::time::sleep(Duration::from_millis(5)).await; |
| 1700 | } |
| 1701 | }) |
| 1702 | .await |
| 1703 | .unwrap(); |
| 1704 | manager.shutdown().await; |
| 1705 | } |
| 1706 | |
| 1707 | #[cfg(unix)] |
| 1708 | #[tokio::test(flavor = "current_thread")] |
| 1709 | async fn actual_ocr_broker_decodes_exact_ordered_grants_and_refuses_replay_or_withdrawal() { |
| 1710 | use std::os::unix::fs::PermissionsExt; |
| 1711 | let _home = crate::test_support::SealedHome::new(); |
| 1712 | let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(false); |
| 1713 | let Some(node) = super::super::test_support::node_for_tests("ocr_exact_grants") else { |
| 1714 | return; |
| 1715 | }; |
| 1716 | let root = tempfile::tempdir().unwrap(); |
| 1717 | let marker = root.path().join("written"); |
| 1718 | let binary = root.path().join("tesseract"); |
| 1719 | std::fs::write( |
| 1720 | &binary, |
| 1721 | format!( |
| 1722 | "#!/bin/sh\nprintf x >> '{}'; printf 'private extracted text\\n'\n", |
| 1723 | marker.display() |
| 1724 | ), |
| 1725 | ) |
| 1726 | .unwrap(); |
| 1727 | std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap(); |
| 1728 | let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions { |
| 1729 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 1730 | node_override: Some(node), |
| 1731 | root: Some(root.path().join("host")), |
| 1732 | ..ExtensionHostOptions::default() |
| 1733 | })); |
| 1734 | manager.bind_engine_handle(tokio::runtime::Handle::current()); |
| 1735 | manager.shared.stock_users.fetch_add(1, Ordering::SeqCst); |
| 1736 | let _demand = Demand(&manager.shared.stock_users); |
| 1737 | let (_host, owner, generation) = manager.ensure_stock_builtin().await.unwrap(); |
| 1738 | let context = ToolContext::new(root.path()); |
| 1739 | let make_job = |id: &str| { |
| 1740 | let input = crate::tools::image_ocr::CapturedOcr::for_test( |
| 1741 | root.path(), |
| 1742 | Arc::new(|_| Err(ToolError::execution_failed("Native refusal"))), |
| 1743 | Some(binary.clone().into_os_string()), |
| 1744 | ); |
| 1745 | let output = Arc::new(Mutex::new(None)); |
| 1746 | let mut caller = Caller::capture(&context, &manager.shared).unwrap(); |
| 1747 | caller.requires_native_policy = false; |
| 1748 | let mut target = caller.target(id); |
| 1749 | target["operation"] = json!("ocr_native"); |
| 1750 | target["captured_sha256"] = json!(input.digest()); |
| 1751 | let ticket = manager.shared.core_calls.tickets.mint(Grant { |
| 1752 | kind: TicketKind::Execution, |
| 1753 | cohort: HostCohort::Builtin, |
| 1754 | host_generation: generation, |
| 1755 | owner: owner.clone(), |
| 1756 | method: "exec/redeem", |
| 1757 | target: target.clone(), |
| 1758 | ttl: DEADLINE, |
| 1759 | uses: 1, |
| 1760 | }); |
| 1761 | let job = Arc::new(Job { |
| 1762 | id: id.into(), |
| 1763 | owner: owner.clone(), |
| 1764 | generation, |
| 1765 | caller, |
| 1766 | target, |
| 1767 | expires: Instant::now() + DEADLINE, |
| 1768 | cancel: CancellationToken::new(), |
| 1769 | launch: Mutex::new(Some(Launch { |
| 1770 | github: None, |
| 1771 | ocr: Some(OcrLaunch::Native { |
| 1772 | input, |
| 1773 | output: Arc::clone(&output), |
| 1774 | }), |
| 1775 | pdf: None, |
| 1776 | stock: None, |
| 1777 | hook: None, |
| 1778 | command: None, |
| 1779 | input: Vec::new(), |
| 1780 | })), |
| 1781 | ticket: ticket.clone(), |
| 1782 | continuation: Mutex::new(None), |
| 1783 | hook_result: Mutex::new(None), |
| 1784 | _permit: Arc::clone(&manager.shared.execution_broker.slots) |
| 1785 | .try_acquire_owned() |
| 1786 | .unwrap(), |
| 1787 | }); |
| 1788 | manager |
| 1789 | .shared |
| 1790 | .execution_broker |
| 1791 | .jobs |
| 1792 | .lock() |
| 1793 | .unwrap() |
| 1794 | .insert(id.into(), Arc::clone(&job)); |
| 1795 | let invocation = Invocation { |
| 1796 | shared: Arc::clone(&manager.shared), |
| 1797 | job: Arc::clone(&job), |
| 1798 | }; |
| 1799 | (job, invocation, output) |
| 1800 | }; |
| 1801 | let (job, invocation, output) = make_job("ordered-ocr"); |
| 1802 | let decoded = |id: &str, ticket: &str| { |
| 1803 | serde_json::from_value::<ExecutionRedeemParams>( |
| 1804 | json!({"owner":owner,"execution_id":id,"ticket":ticket}), |
| 1805 | ) |
| 1806 | .unwrap() |
| 1807 | }; |
| 1808 | let cx = || HostRequestContext::for_test(99).0; |
| 1809 | let first = decoded(&job.id, job.ticket.expose()); |
| 1810 | let mut wrong_owner = first.clone(); |
| 1811 | wrong_owner.owner.plugin_id = "native:forged".into(); |
| 1812 | assert!( |
| 1813 | manager |
| 1814 | .shared |
| 1815 | .execution_broker |
| 1816 | .serve(&manager.shared, generation, wrong_owner, cx()) |
| 1817 | .await |
| 1818 | .is_err() |
| 1819 | ); |
| 1820 | assert!( |
| 1821 | manager |
| 1822 | .shared |
| 1823 | .execution_broker |
| 1824 | .serve(&manager.shared, generation + 1, first.clone(), cx()) |
| 1825 | .await |
| 1826 | .is_err() |
| 1827 | ); |
| 1828 | assert!( |
| 1829 | manager |
| 1830 | .shared |
| 1831 | .execution_broker |
| 1832 | .serve( |
| 1833 | &manager.shared, |
| 1834 | generation, |
| 1835 | decoded("other-ocr", job.ticket.expose()), |
| 1836 | cx() |
| 1837 | ) |
| 1838 | .await |
| 1839 | .is_err() |
| 1840 | ); |
| 1841 | assert!(!marker.exists()); |
| 1842 | let native = manager |
| 1843 | .shared |
| 1844 | .execution_broker |
| 1845 | .serve(&manager.shared, generation, first.clone(), cx()) |
| 1846 | .await |
| 1847 | .unwrap(); |
| 1848 | let next = native["next_ticket"].as_str().unwrap().to_string(); |
| 1849 | assert_eq!(native["status"], "error"); |
| 1850 | assert!(!marker.exists()); |
| 1851 | // The first grant is already spent and never authorizes the later write. |
| 1852 | assert!( |
| 1853 | manager |
| 1854 | .shared |
| 1855 | .execution_broker |
| 1856 | .serve(&manager.shared, generation, first, cx()) |
| 1857 | .await |
| 1858 | .is_err() |
| 1859 | ); |
| 1860 | let target = job |
| 1861 | .continuation |
| 1862 | .lock() |
| 1863 | .unwrap() |
| 1864 | .as_ref() |
| 1865 | .unwrap() |
| 1866 | .target |
| 1867 | .clone(); |
| 1868 | assert_eq!(target["operation"], "ocr_tesseract"); |
| 1869 | assert_ne!(target["captured_sha256"], job.target["captured_sha256"]); |
| 1870 | let wrong_kind = manager.shared.core_calls.tickets.mint(Grant { |
| 1871 | kind: TicketKind::McpOperation, |
| 1872 | cohort: HostCohort::Builtin, |
| 1873 | host_generation: generation, |
| 1874 | owner: owner.clone(), |
| 1875 | method: "exec/redeem", |
| 1876 | target, |
| 1877 | ttl: DEADLINE, |
| 1878 | uses: 1, |
| 1879 | }); |
| 1880 | assert!( |
| 1881 | manager |
| 1882 | .shared |
| 1883 | .execution_broker |
| 1884 | .serve( |
| 1885 | &manager.shared, |
| 1886 | generation, |
| 1887 | decoded(&job.id, wrong_kind.expose()), |
| 1888 | cx() |
| 1889 | ) |
| 1890 | .await |
| 1891 | .is_err() |
| 1892 | ); |
| 1893 | assert!(!marker.exists()); |
| 1894 | let mut altered_target = job |
| 1895 | .continuation |
| 1896 | .lock() |
| 1897 | .unwrap() |
| 1898 | .as_ref() |
| 1899 | .unwrap() |
| 1900 | .target |
| 1901 | .clone(); |
| 1902 | altered_target["captured_sha256"] = json!("changed-command-or-image"); |
| 1903 | let mismatch = manager.shared.core_calls.tickets.mint(Grant { |
| 1904 | kind: TicketKind::Execution, |
| 1905 | cohort: HostCohort::Builtin, |
| 1906 | host_generation: generation, |
| 1907 | owner: owner.clone(), |
| 1908 | method: "exec/redeem", |
| 1909 | target: altered_target, |
| 1910 | ttl: DEADLINE, |
| 1911 | uses: 1, |
| 1912 | }); |
| 1913 | assert!( |
| 1914 | manager |
| 1915 | .shared |
| 1916 | .execution_broker |
| 1917 | .serve( |
| 1918 | &manager.shared, |
| 1919 | generation, |
| 1920 | decoded(&job.id, mismatch.expose()), |
| 1921 | cx() |
| 1922 | ) |
| 1923 | .await |
| 1924 | .is_err() |
| 1925 | ); |
| 1926 | assert!( |
| 1927 | !marker.exists(), |
| 1928 | "parsed request must match its exact captured-operation digest before write" |
| 1929 | ); |
| 1930 | assert!(serde_json::from_value::<ExecutionRedeemParams>(json!({"owner":owner,"execution_id":job.id,"ticket":next,"path":"unreviewed-image.png"})).is_err()); |
| 1931 | let next = decoded(&job.id, &next); |
| 1932 | let projected = manager |
| 1933 | .shared |
| 1934 | .execution_broker |
| 1935 | .serve(&manager.shared, generation, next.clone(), cx()) |
| 1936 | .await |
| 1937 | .unwrap(); |
| 1938 | assert_eq!(projected["state"], "tesseract"); |
| 1939 | assert!(projected.get("stdout").is_none()); |
| 1940 | assert!(output.lock().unwrap().is_some()); |
| 1941 | assert_eq!(std::fs::read(&marker).unwrap(), b"x"); |
| 1942 | assert!( |
| 1943 | manager |
| 1944 | .shared |
| 1945 | .execution_broker |
| 1946 | .serve(&manager.shared, generation, next, cx()) |
| 1947 | .await |
| 1948 | .is_err() |
| 1949 | ); |
| 1950 | assert_eq!(std::fs::read(&marker).unwrap(), b"x"); |
| 1951 | drop(invocation); |
| 1952 | let (withdrawn, invocation, _) = make_job("withdrawn-ocr"); |
| 1953 | let native = manager |
| 1954 | .shared |
| 1955 | .execution_broker |
| 1956 | .serve( |
| 1957 | &manager.shared, |
| 1958 | generation, |
| 1959 | decoded(&withdrawn.id, withdrawn.ticket.expose()), |
| 1960 | cx(), |
| 1961 | ) |
| 1962 | .await |
| 1963 | .unwrap(); |
| 1964 | let next = decoded(&withdrawn.id, native["next_ticket"].as_str().unwrap()); |
| 1965 | manager.shared.execution_broker.revoke_owner("host:harness"); |
| 1966 | assert!( |
| 1967 | manager |
| 1968 | .shared |
| 1969 | .execution_broker |
| 1970 | .serve(&manager.shared, generation, next, cx()) |
| 1971 | .await |
| 1972 | .is_err() |
| 1973 | ); |
| 1974 | assert_eq!(std::fs::read(&marker).unwrap(), b"x"); |
| 1975 | drop(invocation); |
| 1976 | manager.shutdown().await; |
| 1977 | } |
| 1978 | |
| 1979 | #[tokio::test(flavor = "current_thread")] |
| 1980 | async fn abandoned_execution_worker_keeps_quota_until_cleanup_completes() { |
| 1981 | let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default())); |
| 1982 | manager.bind_engine_handle(tokio::runtime::Handle::current()); |
| 1983 | let broker = &manager.shared.execution_broker; |
| 1984 | let owner = owner(); |
| 1985 | let caller = caller(); |
| 1986 | let target = caller.target("job"); |
| 1987 | let ticket = manager |
| 1988 | .shared |
| 1989 | .core_calls |
| 1990 | .tickets |
| 1991 | .mint(grant(owner.clone(), target.clone())); |
| 1992 | let job = Arc::new(Job { |
| 1993 | id: "job".into(), |
| 1994 | owner, |
| 1995 | generation: 4, |
| 1996 | caller, |
| 1997 | target, |
| 1998 | expires: Instant::now() + DEADLINE, |
| 1999 | cancel: CancellationToken::new(), |
| 2000 | launch: Mutex::new(None), |
| 2001 | ticket, |
| 2002 | continuation: Mutex::new(None), |
| 2003 | hook_result: Mutex::new(None), |
| 2004 | _permit: Arc::clone(&broker.slots).acquire_owned().await.unwrap(), |
| 2005 | }); |
| 2006 | broker |
| 2007 | .jobs |
| 2008 | .lock() |
| 2009 | .unwrap() |
| 2010 | .insert("job".into(), Arc::clone(&job)); |
| 2011 | let invocation = Invocation { |
| 2012 | shared: Arc::clone(&manager.shared), |
| 2013 | job: Arc::clone(&job), |
| 2014 | }; |
| 2015 | let (started_tx, started_rx) = tokio::sync::oneshot::channel(); |
| 2016 | let (finish_tx, finish_rx) = tokio::sync::oneshot::channel(); |
| 2017 | let (done_tx, done_rx) = tokio::sync::oneshot::channel(); |
| 2018 | let worker = dispatch_job( |
| 2019 | manager.shared.engine_handle().unwrap(), |
| 2020 | Arc::clone(&job), |
| 2021 | move |job| async move { |
| 2022 | started_tx.send(()).unwrap(); |
| 2023 | job.cancel.cancelled().await; |
| 2024 | finish_rx.await.unwrap(); |
| 2025 | done_tx.send(()).unwrap(); |
| 2026 | Ok(json!({})) |
| 2027 | }, |
| 2028 | ); |
| 2029 | started_rx.await.unwrap(); |
| 2030 | drop(worker); |
| 2031 | drop(invocation); |
| 2032 | drop(job); |
| 2033 | assert_eq!(broker.slots.available_permits(), MAX_JOBS - 1); |
| 2034 | finish_tx.send(()).unwrap(); |
| 2035 | done_rx.await.unwrap(); |
| 2036 | tokio::task::yield_now().await; |
| 2037 | assert_eq!(broker.slots.available_permits(), MAX_JOBS); |
| 2038 | } |
| 2039 | } |
| 2040 |