| 1 | //! `HostToolSpec`: an extension tool as an ordinary registry `ToolSpec`. |
| 2 | //! |
| 3 | //! Because it is a registry tool, every existing gate applies unchanged: |
| 4 | //! plan mode, the authority envelope, deferral, hooks, approval, and code |
| 5 | //! mode (which suspends gated calls for approval and refuses ungated calls |
| 6 | //! before any host call). Four rules are specific to extension tools: |
| 7 | //! |
| 8 | //! * **A plugin's tool is always `ApprovalRequirement::Required`.** A plugin's |
| 9 | //! own read-only hint (`presentCall` `kind: 'read'`, MCP-style annotations) |
| 10 | //! is display data at most. Honouring it would let a plugin switch approval |
| 11 | //! off for a tool whose body runs arbitrary Node — self-approval. A tool of |
| 12 | //! a built-in module (tier 0, owner `host:<module>`) gets the approval the |
| 13 | //! Rust table [`super::tier::BUILTIN_MODULES`] lists for it and nothing the |
| 14 | //! module says; unlisted is `Required`. It is still never read-only for |
| 15 | //! plan mode. |
| 16 | //! * **Approval grants are receipt-bound.** Keys are |
| 17 | //! `ext:<plugin_id>@<content_hash>:<name>:<hash(input)>` for both the exact |
| 18 | //! and the session-grant key ([`ToolSpec::approval_scope`]), so an updated |
| 19 | //! plugin, or a different plugin that later takes the same tool name, never |
| 20 | //! inherits a grant. |
| 21 | //! * **Input is checked against the tool's registered JSON Schema** before |
| 22 | //! approval and again before anything is sent to the host |
| 23 | //! ([`super::registry::InputValidator`]). A schema that cannot be compiled is |
| 24 | //! refused at registration. |
| 25 | //! * **Liveness is re-checked at call time**: the plugin's reviewed receipt, |
| 26 | //! the Native adapter in this build's policy, and the exact owner |
| 27 | //! generation. A revocation mid-turn fails the call closed. |
| 28 | //! |
| 29 | //! A fifth thing is not a rule but a capability: when the turn loop serves a |
| 30 | //! permission gate for exactly this call (the model called the tool directly), |
| 31 | //! the call carries an invocation ticket and the tool may ask the core to run |
| 32 | //! core tools through `core/call` (`super::core_call`). The call's deadline |
| 33 | //! then stops while one of those waits on an approval card, and what the tool |
| 34 | //! asked the core to run is attached to its result metadata (`core_calls`). |
| 35 | |
| 36 | use std::sync::Arc; |
| 37 | use std::time::Duration; |
| 38 | |
| 39 | use async_trait::async_trait; |
| 40 | use serde_json::Value; |
| 41 | |
| 42 | use super::ManagerShared; |
| 43 | use super::core_call::{HeldImage, InvocationGuard}; |
| 44 | use super::protocol::{ContentBlockWire, CoreRequest, DshService, ToolCallParams, ToolResultWire}; |
| 45 | use super::registry::ToolRegistration; |
| 46 | use super::supervisor::HostCallError; |
| 47 | use super::tier::{self, HostTier}; |
| 48 | use crate::tools::codemode::ExtensionCaller; |
| 49 | use crate::tools::spec::{ |
| 50 | ApprovalRequirement, PreparedToolCall, RichToolResult, ToolCapability, ToolContext, ToolError, |
| 51 | ToolResult, ToolSpec, |
| 52 | }; |
| 53 | use codewhale_tools::ToolResultContentBlock; |
| 54 | |
| 55 | /// Default per-call deadline, matching script tools |
| 56 | /// (`SupervisionOptions::tool_call_deadline`). |
| 57 | pub const TOOL_CALL_DEADLINE: Duration = Duration::from_secs(120); |
| 58 | |
| 59 | pub struct HostToolSpec { |
| 60 | registration: ToolRegistration, |
| 61 | manager: Arc<ManagerShared>, |
| 62 | selection: Option<codewhale_plugins::composition_scope::SelectionRevision>, |
| 63 | } |
| 64 | |
| 65 | impl HostToolSpec { |
| 66 | #[cfg(any(test, feature = "test-support"))] |
| 67 | pub fn new(registration: ToolRegistration, manager: Arc<ManagerShared>) -> Self { |
| 68 | Self { |
| 69 | registration, |
| 70 | manager, |
| 71 | selection: None, |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | pub fn for_selection( |
| 76 | registration: ToolRegistration, |
| 77 | manager: Arc<ManagerShared>, |
| 78 | selection: Option<codewhale_plugins::composition_scope::SelectionRevision>, |
| 79 | ) -> Self { |
| 80 | Self { |
| 81 | registration, |
| 82 | manager, |
| 83 | selection, |
| 84 | } |
| 85 | } |
| 86 | fn check_caller(&self, context: &ToolContext) -> Result<(), ToolError> { |
| 87 | self.manager |
| 88 | .check_selection( |
| 89 | self.selection, |
| 90 | context.plugin_registry.as_deref(), |
| 91 | &self.registration.owner.plugin_id, |
| 92 | &self.registration.content_hash, |
| 93 | self.registration.scope.as_ref(), |
| 94 | ) |
| 95 | .map_err(ToolError::not_available) |
| 96 | } |
| 97 | |
| 98 | /// `extension:<plugin>` (or the module's owner id, `host:<module>`): the |
| 99 | /// origin shown in approval cards and diagnostics. |
| 100 | #[must_use] |
| 101 | pub fn origin(&self) -> String { |
| 102 | match self.registration.tier() { |
| 103 | HostTier::Plugin => format!("extension:{}", self.registration.plugin_name), |
| 104 | HostTier::Builtin => self.registration.owner.plugin_id.clone(), |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | /// The approval this tool needs: always `Required` for a plugin's tool; |
| 109 | /// for a built-in module's, what the Rust table says and `Required` when |
| 110 | /// it says nothing. |
| 111 | fn approval(&self) -> ApprovalRequirement { |
| 112 | match self.registration.tier() { |
| 113 | HostTier::Plugin => ApprovalRequirement::Required, |
| 114 | HostTier::Builtin => tier::tool_approval( |
| 115 | self.manager.builtin_modules, |
| 116 | &self.registration.owner.plugin_id, |
| 117 | &self.registration.name, |
| 118 | ), |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | fn is_creator_plugin_manager(&self) -> bool { |
| 123 | self.registration.owner.plugin_id == super::creator_policy::CREATOR_PLUGIN_ID |
| 124 | && self.registration.name == super::creator_policy::PLUGIN_MANAGER_TOOL_NAME |
| 125 | } |
| 126 | |
| 127 | /// Check `input` against the schema the plugin registered the tool with. |
| 128 | /// The error is the ordinary invalid-input tool error, so the model sees |
| 129 | /// what to correct; the host is never reached. |
| 130 | fn check_input(&self, input: &Value) -> Result<(), ToolError> { |
| 131 | self.registration |
| 132 | .input_validator |
| 133 | .check(input) |
| 134 | .map_err(|reason| { |
| 135 | ToolError::invalid_input(format!( |
| 136 | "plugin tool `{}` rejected the input: {reason}", |
| 137 | self.registration.name |
| 138 | )) |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | /// Who this tool is to the turn loop's gate: composed here, from the |
| 143 | /// registration, never from anything the host says. |
| 144 | fn caller(&self) -> ExtensionCaller { |
| 145 | ExtensionCaller { |
| 146 | origin: self.origin(), |
| 147 | tool: self.registration.name.clone(), |
| 148 | scope: format!( |
| 149 | "ext:{}@{}:{}:{}:{}", |
| 150 | self.registration.owner.plugin_id, |
| 151 | self.registration.content_hash, |
| 152 | self.registration |
| 153 | .scope |
| 154 | .as_ref() |
| 155 | .map(|entry| format!("{}@{}", entry.path, entry.sha256)) |
| 156 | .unwrap_or_default(), |
| 157 | self.selection |
| 158 | .map(|selection| format!("{}:{}", selection.attachment_id, selection.revision)) |
| 159 | .unwrap_or_default(), |
| 160 | crate::session_manager::current_session_boot_id() |
| 161 | ), |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// The approval-card text. Rust composes it; the extension supplies none. |
| 166 | /// Plugins in one host share a process and can interfere with each other, |
| 167 | /// so the card says when this one is not alone (design §4.4, threat 3). |
| 168 | #[must_use] |
| 169 | pub fn approval_text(&self) -> String { |
| 170 | if self.registration.tier() == HostTier::Builtin { |
| 171 | return format!( |
| 172 | "Tool `{}` of built-in host module `{}` ({}) runs on Codewhale's built-in plugin host", |
| 173 | self.registration.name, |
| 174 | self.registration.plugin_name, |
| 175 | self.origin() |
| 176 | ); |
| 177 | } |
| 178 | let others = self |
| 179 | .manager |
| 180 | .registry |
| 181 | .lock() |
| 182 | .expect("registry lock") |
| 183 | .other_active_owners(&self.registration.owner.plugin_id); |
| 184 | let sharing = match others { |
| 185 | 0 => String::new(), |
| 186 | 1 => "; it shares one host process with 1 other plugin, which can alter its behaviour" |
| 187 | .to_string(), |
| 188 | n => format!( |
| 189 | "; it shares one host process with {n} other plugins, which can alter its behaviour" |
| 190 | ), |
| 191 | }; |
| 192 | format!( |
| 193 | "Plugin tool `{}` from plugin `{}` ({}) runs JavaScript on this computer with the plugin host's permissions{sharing}", |
| 194 | self.registration.name, |
| 195 | self.registration.plugin_name, |
| 196 | self.origin() |
| 197 | ) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | impl std::fmt::Debug for HostToolSpec { |
| 202 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 203 | f.debug_struct("HostToolSpec") |
| 204 | .field("name", &self.registration.name) |
| 205 | .field("plugin", &self.registration.plugin_name) |
| 206 | .field("handle", &self.registration.handle) |
| 207 | .finish() |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | fn map_call_error(tool: &str, error: HostCallError) -> ToolError { |
| 212 | match error { |
| 213 | HostCallError::Cancelled(reason) => ToolError::Cancelled { |
| 214 | message: format!("plugin tool `{tool}`: {reason}"), |
| 215 | }, |
| 216 | HostCallError::Timeout { after, .. } => ToolError::Timeout { |
| 217 | seconds: after.as_secs(), |
| 218 | }, |
| 219 | HostCallError::Exited(reason) => { |
| 220 | ToolError::not_available(format!("plugin host exited: {reason}")) |
| 221 | } |
| 222 | HostCallError::Busy => { |
| 223 | ToolError::not_available("plugin host is busy; try again".to_string()) |
| 224 | } |
| 225 | HostCallError::Rpc { code, message } => { |
| 226 | if code == super::protocol::error_code::NOT_AVAILABLE { |
| 227 | ToolError::not_available(format!("plugin tool `{tool}`: {message}")) |
| 228 | } else { |
| 229 | ToolError::execution_failed(format!("plugin tool `{tool}` failed: {message}")) |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | #[cfg(test)] |
| 236 | pub(super) fn failed_with_acts( |
| 237 | error: ToolError, |
| 238 | receipts: Option<&Value>, |
| 239 | ) -> Result<ToolResultWire, ToolError> { |
| 240 | failed_with_acts_and_mark(error, receipts, None) |
| 241 | } |
| 242 | |
| 243 | pub(super) fn failed_with_acts_and_mark( |
| 244 | error: ToolError, |
| 245 | receipts: Option<&Value>, |
| 246 | plugin_change: Option<&super::core_call::PluginChangeMark>, |
| 247 | ) -> Result<ToolResultWire, ToolError> { |
| 248 | let holds_acts = receipts.is_some_and(|receipts| receipts.get("broker_acts").is_some()) |
| 249 | || plugin_change.is_some(); |
| 250 | if !holds_acts { |
| 251 | return Err(error); |
| 252 | } |
| 253 | Ok(ToolResultWire { |
| 254 | content: vec![ContentBlockWire::Text { |
| 255 | text: error.to_string(), |
| 256 | }], |
| 257 | is_error: true, |
| 258 | structured: None, |
| 259 | }) |
| 260 | } |
| 261 | |
| 262 | fn record_held_image_outcome( |
| 263 | invocation: Option<&InvocationGuard>, |
| 264 | method: &str, |
| 265 | outcome: &str, |
| 266 | reason: Option<&str>, |
| 267 | held: &HeldImage, |
| 268 | ) { |
| 269 | let Some(invocation) = invocation else { |
| 270 | return; |
| 271 | }; |
| 272 | let mut entry = serde_json::json!({ |
| 273 | "method": method, |
| 274 | "outcome": outcome, |
| 275 | "attachment_id": held.attachment_id, |
| 276 | "media_type": held.media_type, |
| 277 | "bytes": held.bytes, |
| 278 | "width": held.width, |
| 279 | "height": held.height, |
| 280 | }); |
| 281 | if let (Some(reason), Some(map)) = (reason, entry.as_object_mut()) { |
| 282 | map.insert("reason".to_string(), Value::String(reason.to_string())); |
| 283 | } |
| 284 | let _ = invocation.record_service_act(DshService::Attachments, entry); |
| 285 | } |
| 286 | |
| 287 | pub(super) fn resolve_held_image( |
| 288 | held_image: Option<HeldImage>, |
| 289 | attachments_granted: bool, |
| 290 | settled: &mut Result<ToolResultWire, ToolError>, |
| 291 | invocation: Option<&InvocationGuard>, |
| 292 | ) -> Vec<ToolResultContentBlock> { |
| 293 | if !attachments_granted { |
| 294 | if let Some(held) = held_image.as_ref() { |
| 295 | record_held_image_outcome(invocation, "save", "dropped", Some("grant_revoked"), held); |
| 296 | } |
| 297 | if let Ok(wire) = settled.as_ref() |
| 298 | && wire |
| 299 | .content |
| 300 | .iter() |
| 301 | .any(|block| matches!(block, ContentBlockWire::ImageRef { .. })) |
| 302 | { |
| 303 | *settled = Err(ToolError::execution_failed( |
| 304 | "tool returned an image reference after `attachments` grant was revoked", |
| 305 | )); |
| 306 | } |
| 307 | return Vec::new(); |
| 308 | } |
| 309 | match settled { |
| 310 | Ok(wire) => { |
| 311 | let refs: Vec<&str> = wire |
| 312 | .content |
| 313 | .iter() |
| 314 | .filter_map(|block| match block { |
| 315 | ContentBlockWire::ImageRef { attachment_id } => Some(attachment_id.as_str()), |
| 316 | ContentBlockWire::Text { .. } => None, |
| 317 | }) |
| 318 | .collect(); |
| 319 | if wire.is_error { |
| 320 | let unheld = refs.iter().find(|id| { |
| 321 | held_image |
| 322 | .as_ref() |
| 323 | .is_none_or(|held| held.attachment_id != **id) |
| 324 | }); |
| 325 | if let Some(held) = held_image.as_ref() { |
| 326 | let reason = if unheld.is_some() { |
| 327 | "unheld_reference" |
| 328 | } else { |
| 329 | "tool_failed" |
| 330 | }; |
| 331 | record_held_image_outcome(invocation, "save", "dropped", Some(reason), held); |
| 332 | } |
| 333 | if let Some(bad) = unheld { |
| 334 | let shown: String = bad.chars().take(80).collect(); |
| 335 | *settled = Err(ToolError::execution_failed(format!( |
| 336 | "tool returned an image reference `{shown}` not held by this call" |
| 337 | ))); |
| 338 | } |
| 339 | return Vec::new(); |
| 340 | } |
| 341 | if refs.len() > crate::image_attach::MAX_TOOL_RESULT_IMAGES { |
| 342 | if let Some(held) = held_image.as_ref() { |
| 343 | record_held_image_outcome( |
| 344 | invocation, |
| 345 | "save", |
| 346 | "dropped", |
| 347 | Some("too_many_images"), |
| 348 | held, |
| 349 | ); |
| 350 | } |
| 351 | *settled = Err(ToolError::execution_failed( |
| 352 | "this Codewhale keeps one image per tool result", |
| 353 | )); |
| 354 | return Vec::new(); |
| 355 | } |
| 356 | if let [wanted_id] = refs.as_slice() { |
| 357 | match held_image { |
| 358 | Some(held) if held.attachment_id == *wanted_id => { |
| 359 | record_held_image_outcome(invocation, "result", "delivered", None, &held); |
| 360 | return vec![ToolResultContentBlock::Image { |
| 361 | mime_type: held.media_type, |
| 362 | data: held.data_base64, |
| 363 | }]; |
| 364 | } |
| 365 | Some(held) => { |
| 366 | record_held_image_outcome( |
| 367 | invocation, |
| 368 | "save", |
| 369 | "dropped", |
| 370 | Some("unheld_reference"), |
| 371 | &held, |
| 372 | ); |
| 373 | let shown: String = wanted_id.chars().take(80).collect(); |
| 374 | *settled = Err(ToolError::execution_failed(format!( |
| 375 | "tool returned an image reference `{shown}` not held by this call" |
| 376 | ))); |
| 377 | return Vec::new(); |
| 378 | } |
| 379 | None => { |
| 380 | let shown: String = wanted_id.chars().take(80).collect(); |
| 381 | *settled = Err(ToolError::execution_failed(format!( |
| 382 | "tool returned an image reference `{shown}` not held by this call" |
| 383 | ))); |
| 384 | return Vec::new(); |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | if let Some(held) = held_image.as_ref() { |
| 389 | record_held_image_outcome( |
| 390 | invocation, |
| 391 | "save", |
| 392 | "dropped", |
| 393 | Some("not_referenced"), |
| 394 | held, |
| 395 | ); |
| 396 | } |
| 397 | Vec::new() |
| 398 | } |
| 399 | Err(_) => { |
| 400 | if let Some(held) = held_image.as_ref() { |
| 401 | record_held_image_outcome(invocation, "save", "dropped", Some("tool_failed"), held); |
| 402 | } |
| 403 | Vec::new() |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | pub fn wire_to_result(wire: ToolResultWire, origin: &str) -> ToolResult { |
| 409 | let content = wire |
| 410 | .content |
| 411 | .iter() |
| 412 | .filter_map(|block| match block { |
| 413 | ContentBlockWire::Text { text } => Some(text.as_str()), |
| 414 | ContentBlockWire::ImageRef { .. } => None, |
| 415 | }) |
| 416 | .collect::<Vec<_>>() |
| 417 | .join("\n"); |
| 418 | let mut metadata = serde_json::Map::new(); |
| 419 | metadata.insert("origin".to_string(), Value::String(origin.to_string())); |
| 420 | if let Some(structured) = wire.structured { |
| 421 | metadata.insert("structured".to_string(), structured); |
| 422 | } |
| 423 | ToolResult { |
| 424 | content, |
| 425 | success: !wire.is_error, |
| 426 | metadata: Some(Value::Object(metadata)), |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | #[async_trait] |
| 431 | impl ToolSpec for HostToolSpec { |
| 432 | fn name(&self) -> &str { |
| 433 | &self.registration.name |
| 434 | } |
| 435 | |
| 436 | fn registration_origin(&self) -> std::borrow::Cow<'_, str> { |
| 437 | self.origin().into() |
| 438 | } |
| 439 | |
| 440 | fn description(&self) -> &str { |
| 441 | &self.registration.description |
| 442 | } |
| 443 | |
| 444 | fn input_schema(&self) -> Value { |
| 445 | self.registration.input_schema.clone() |
| 446 | } |
| 447 | |
| 448 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 449 | let mut capabilities = vec![ToolCapability::ExecutesCode]; |
| 450 | if self.approval() != ApprovalRequirement::Auto { |
| 451 | capabilities.push(ToolCapability::RequiresApproval); |
| 452 | } |
| 453 | capabilities |
| 454 | } |
| 455 | |
| 456 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 457 | self.approval() |
| 458 | } |
| 459 | |
| 460 | fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement { |
| 461 | if self.is_creator_plugin_manager() && super::creator_policy::is_list_action(input) { |
| 462 | ApprovalRequirement::Auto |
| 463 | } else { |
| 464 | self.approval() |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | fn is_read_only(&self) -> bool { |
| 469 | false |
| 470 | } |
| 471 | |
| 472 | fn is_read_only_for(&self, input: &Value) -> bool { |
| 473 | self.is_creator_plugin_manager() && super::creator_policy::is_list_action(input) |
| 474 | } |
| 475 | |
| 476 | fn defer_loading(&self) -> bool { |
| 477 | true |
| 478 | } |
| 479 | |
| 480 | /// Grants are bound to the plugin's reviewed receipt (design §4.3). |
| 481 | fn approval_scope(&self) -> Option<String> { |
| 482 | Some(self.caller().scope) |
| 483 | } |
| 484 | |
| 485 | /// The turn loop serves a permission gate for this tool's call, through |
| 486 | /// which its `core/call`s are planned and approved. |
| 487 | fn extension_caller(&self) -> Option<ExtensionCaller> { |
| 488 | Some(self.caller()) |
| 489 | } |
| 490 | |
| 491 | fn prepare(&self, input: Value, context: &ToolContext) -> Result<PreparedToolCall, ToolError> { |
| 492 | self.check_caller(context)?; |
| 493 | // Before the user is asked to approve it: a call the schema refuses is |
| 494 | // returned to the model to correct and never becomes an approval card. |
| 495 | self.check_input(&input)?; |
| 496 | let read_only = self.is_read_only_for(&input); |
| 497 | let approval = self.approval_requirement_for(&input); |
| 498 | let description = if self.is_creator_plugin_manager() { |
| 499 | super::creator_policy::initial_prepared_description(&input) |
| 500 | } else { |
| 501 | self.approval_text() |
| 502 | }; |
| 503 | Ok(PreparedToolCall { |
| 504 | name: self.registration.name.clone(), |
| 505 | // Rust composes the card; the extension cannot supply approval text. |
| 506 | description, |
| 507 | read_only, |
| 508 | supports_parallel: false, |
| 509 | starts_detached: false, |
| 510 | approval, |
| 511 | resources: if read_only { |
| 512 | Vec::new() |
| 513 | } else { |
| 514 | vec![crate::tools::spec::ResourceClaim::GlobalExclusive] |
| 515 | }, |
| 516 | input, |
| 517 | }) |
| 518 | } |
| 519 | |
| 520 | async fn execute_rich( |
| 521 | &self, |
| 522 | input: Value, |
| 523 | context: &ToolContext, |
| 524 | ) -> Result<RichToolResult, ToolError> { |
| 525 | self.check_caller(context)?; |
| 526 | let registration = &self.registration; |
| 527 | // Again here: `execute` is also reached without `prepare`, and nothing |
| 528 | // that fails the schema may be sent to the host. |
| 529 | self.check_input(&input)?; |
| 530 | let host = self |
| 531 | .manager |
| 532 | .live_host_for(registration) |
| 533 | .await |
| 534 | .map_err(ToolError::not_available)?; |
| 535 | self.check_caller(context)?; |
| 536 | let call_id = context |
| 537 | .execution |
| 538 | .owner_agent_id |
| 539 | .clone() |
| 540 | .map(|agent| format!("{agent}:{}", uuid::Uuid::new_v4().simple())) |
| 541 | .unwrap_or_else(|| uuid::Uuid::new_v4().simple().to_string()); |
| 542 | // The deadline travels with the call: the host is told the bound |
| 543 | // `HostProcess::call` enforces (and cancels at). |
| 544 | let deadline = self.manager.options.supervision.tool_call_deadline; |
| 545 | // An invocation ticket (so the tool may ask the core to run tools for |
| 546 | // it) exists only when the turn loop is serving a permission gate for |
| 547 | // exactly this tool's call. Otherwise (a call nested in |
| 548 | // `execute_tools`, a test) the tool has no way to ask for anything. |
| 549 | let invocation: Option<InvocationGuard> = context |
| 550 | .execution |
| 551 | .nested_call_gate |
| 552 | .as_ref() |
| 553 | .and_then(|gate| { |
| 554 | self.manager.core_calls.begin_scoped( |
| 555 | ®istration.cohort, |
| 556 | host.generation, |
| 557 | ®istration.owner, |
| 558 | &call_id, |
| 559 | &self.caller(), |
| 560 | context, |
| 561 | gate, |
| 562 | registration.scope.clone(), |
| 563 | registration.content_hash.clone(), |
| 564 | &self.manager.broker_services(®istration.owner), |
| 565 | ) |
| 566 | }); |
| 567 | let request = CoreRequest::ToolCall(ToolCallParams { |
| 568 | handle: registration.handle, |
| 569 | call_id, |
| 570 | input, |
| 571 | deadline_ms: u64::try_from(deadline.as_millis()).unwrap_or(u64::MAX), |
| 572 | // The calling session's workspace and no other: the plugin never |
| 573 | // learns where else this process has workspaces. |
| 574 | workspace: context.workspace.to_str().map(str::to_owned), |
| 575 | ticket: invocation.as_ref().map(|i| i.ticket().to_string()), |
| 576 | checkpoint_ticket: invocation |
| 577 | .as_ref() |
| 578 | .and_then(|i| i.checkpoint_ticket().map(str::to_string)), |
| 579 | question_ticket: invocation |
| 580 | .as_ref() |
| 581 | .and_then(|i| i.question_ticket().map(str::to_string)), |
| 582 | subagent_ticket: invocation |
| 583 | .as_ref() |
| 584 | .and_then(|i| i.subagent_ticket().map(str::to_string)), |
| 585 | broker_tickets: invocation.as_ref().and_then(|i| i.broker_tickets()), |
| 586 | caller_tools: invocation.as_ref().and_then(|i| i.caller_tools()), |
| 587 | session_id: context |
| 588 | .execution |
| 589 | .session_objects |
| 590 | .as_ref() |
| 591 | .map(|session| session.session_id.clone()) |
| 592 | .filter(|id| !id.is_empty()), |
| 593 | agent_id: context.execution.owner_agent_id.clone(), |
| 594 | origin_turn_id: context.execution.origin_turn_id.clone(), |
| 595 | }); |
| 596 | // The deadline stops while one of this call's `core/call`s waits on |
| 597 | // the gate (an approval card), so a person's time is not the tool's. |
| 598 | let outcome = host |
| 599 | .call_with_clock( |
| 600 | request, |
| 601 | Some(registration.owner.plugin_id.clone()), |
| 602 | invocation.as_ref().map(InvocationGuard::clock), |
| 603 | ) |
| 604 | .await; |
| 605 | let held_image = invocation |
| 606 | .as_ref() |
| 607 | .and_then(InvocationGuard::seal_held_image); |
| 608 | let mut settled: Result<ToolResultWire, ToolError> = async { |
| 609 | match outcome { |
| 610 | Ok(value) => { |
| 611 | self.check_caller(context)?; |
| 612 | self.manager |
| 613 | .live_host_for(registration) |
| 614 | .await |
| 615 | .map_err(ToolError::not_available)?; |
| 616 | self.check_caller(context)?; |
| 617 | serde_json::from_value(value).map_err(|error| { |
| 618 | ToolError::execution_failed(format!( |
| 619 | "plugin tool `{}` returned a malformed result: {error}", |
| 620 | registration.name |
| 621 | )) |
| 622 | }) |
| 623 | } |
| 624 | Err(error) => Err(map_call_error(®istration.name, error)), |
| 625 | } |
| 626 | } |
| 627 | .await; |
| 628 | let needs_attachment_grant = held_image.is_some() |
| 629 | || matches!( |
| 630 | settled.as_ref(), |
| 631 | Ok(wire) |
| 632 | if wire |
| 633 | .content |
| 634 | .iter() |
| 635 | .any(|block| matches!(block, ContentBlockWire::ImageRef { .. })) |
| 636 | ); |
| 637 | let attachments_granted = if needs_attachment_grant { |
| 638 | self.manager |
| 639 | .broker_granted(®istration.owner, DshService::Attachments) |
| 640 | .await |
| 641 | } else { |
| 642 | true |
| 643 | }; |
| 644 | let content_blocks = resolve_held_image( |
| 645 | held_image, |
| 646 | attachments_granted, |
| 647 | &mut settled, |
| 648 | invocation.as_ref(), |
| 649 | ); |
| 650 | let receipts = invocation.as_ref().and_then(InvocationGuard::seal_receipts); |
| 651 | let plugin_change = invocation |
| 652 | .as_ref() |
| 653 | .and_then(InvocationGuard::seal_plugin_change) |
| 654 | .filter(|_| self.is_creator_plugin_manager()); |
| 655 | let wire = match settled { |
| 656 | Ok(wire) => wire, |
| 657 | Err(error) => { |
| 658 | let wire = |
| 659 | failed_with_acts_and_mark(error, receipts.as_ref(), plugin_change.as_ref())?; |
| 660 | if plugin_change.is_some() { |
| 661 | wire |
| 662 | } else { |
| 663 | match self.check_caller(context) { |
| 664 | Ok(()) => wire, |
| 665 | Err(stale) => failed_with_acts_and_mark( |
| 666 | stale, |
| 667 | receipts.as_ref(), |
| 668 | plugin_change.as_ref(), |
| 669 | )?, |
| 670 | } |
| 671 | } |
| 672 | } |
| 673 | }; |
| 674 | let mut result = wire_to_result(wire, &self.origin()); |
| 675 | if let Some(Value::Object(metadata)) = result.metadata.as_mut() { |
| 676 | metadata.remove("plugin_change"); |
| 677 | metadata.insert( |
| 678 | "extension".to_string(), |
| 679 | serde_json::json!({ |
| 680 | "plugin_id": registration.owner.plugin_id, |
| 681 | "content_hash": registration.content_hash, |
| 682 | "entry": registration.scope, |
| 683 | "generation": registration.owner.generation, |
| 684 | "host_generation": host.generation, |
| 685 | "selection": self.selection, |
| 686 | "handle": registration.handle, |
| 687 | "boot_id": crate::session_manager::current_session_boot_id(), |
| 688 | }), |
| 689 | ); |
| 690 | } |
| 691 | // What the tool asked the core to run, so the persisted record shows it. |
| 692 | if let (Some(receipts), Some(Value::Object(metadata))) = |
| 693 | (receipts, result.metadata.as_mut()) |
| 694 | { |
| 695 | metadata.insert("core_calls".to_string(), receipts); |
| 696 | } |
| 697 | if let (Some(mark), Some(Value::Object(metadata))) = |
| 698 | (plugin_change, result.metadata.as_mut()) |
| 699 | && let Ok(value) = serde_json::to_value(mark) |
| 700 | { |
| 701 | metadata.insert("plugin_change".to_string(), value); |
| 702 | } |
| 703 | Ok(RichToolResult::with_content_blocks(result, content_blocks)) |
| 704 | } |
| 705 | |
| 706 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 707 | self.execute_rich(input, context) |
| 708 | .await |
| 709 | .map(RichToolResult::into_result) |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | #[cfg(test)] |
| 714 | mod tests { |
| 715 | use super::*; |
| 716 | use serde_json::json; |
| 717 | |
| 718 | #[test] |
| 719 | fn structured_result_and_soft_failure_survive_the_host_boundary() { |
| 720 | let value = json!({"count": 2, "items": ["a", "b"]}); |
| 721 | let result = wire_to_result( |
| 722 | ToolResultWire { |
| 723 | content: vec![ContentBlockWire::Text { |
| 724 | text: "two items".to_string(), |
| 725 | }], |
| 726 | is_error: true, |
| 727 | structured: Some(value.clone()), |
| 728 | }, |
| 729 | "extension:fixture", |
| 730 | ); |
| 731 | assert_eq!(result.content, "two items"); |
| 732 | assert!(!result.success); |
| 733 | let metadata = result.metadata.expect("result metadata"); |
| 734 | assert_eq!(metadata["origin"], "extension:fixture"); |
| 735 | assert_eq!(metadata["structured"], value); |
| 736 | } |
| 737 | } |
| 738 |