| 1 | use std::future::Future; |
| 2 | use std::pin::Pin; |
| 3 | |
| 4 | use codewhale_config::OwnerRef; |
| 5 | use serde::de::DeserializeOwned; |
| 6 | use serde_json::{Value, json}; |
| 7 | |
| 8 | use super::protocol::{DshService, RpcErrorWire, error_code}; |
| 9 | use super::registry::OwnerRegistry; |
| 10 | use super::tier::{HOST_OWNER_PREFIX, HostTier}; |
| 11 | use super::{ |
| 12 | dsh_attachments, dsh_catalog, dsh_llm, dsh_network, dsh_plugins, dsh_remote, dsh_settings, |
| 13 | dsh_terminal, dsh_workspace, |
| 14 | }; |
| 15 | use crate::tools::codemode::{NestedDecision, NestedFailure}; |
| 16 | use crate::tools::spec::{ |
| 17 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 18 | }; |
| 19 | |
| 20 | pub use super::core_call::BrokerContext; |
| 21 | |
| 22 | pub struct BrokerCall { |
| 23 | pub owner: OwnerRef, |
| 24 | pub session_id: String, |
| 25 | pub service: DshService, |
| 26 | pub method: String, |
| 27 | pub input: Value, |
| 28 | pub context: BrokerContext, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 32 | pub enum BrokerRefusal { |
| 33 | UnknownService(String), |
| 34 | UnknownMethod { |
| 35 | service: DshService, |
| 36 | method: String, |
| 37 | }, |
| 38 | InvalidInput { |
| 39 | service: DshService, |
| 40 | message: String, |
| 41 | }, |
| 42 | NotAvailable(DshService), |
| 43 | NotGranted(DshService), |
| 44 | Denied { |
| 45 | service: DshService, |
| 46 | message: String, |
| 47 | }, |
| 48 | Refused { |
| 49 | service: DshService, |
| 50 | message: String, |
| 51 | }, |
| 52 | } |
| 53 | |
| 54 | impl BrokerRefusal { |
| 55 | #[must_use] |
| 56 | pub fn code(&self) -> &'static str { |
| 57 | match self { |
| 58 | Self::UnknownService(_) => "unknown_service", |
| 59 | Self::UnknownMethod { .. } => "unknown_method", |
| 60 | Self::InvalidInput { .. } => "invalid_input", |
| 61 | Self::NotAvailable(_) => "not_available", |
| 62 | Self::NotGranted(_) => "not_granted", |
| 63 | Self::Denied { .. } => "denied", |
| 64 | Self::Refused { .. } => "refused", |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | #[must_use] |
| 69 | pub fn wire(self) -> RpcErrorWire { |
| 70 | let code = self.code(); |
| 71 | let (rpc, message, service) = match self { |
| 72 | Self::UnknownService(name) => ( |
| 73 | error_code::INVALID_PARAMS, |
| 74 | "dsh/broker names a service the core does not broker".to_string(), |
| 75 | Value::String(name.chars().take(64).collect()), |
| 76 | ), |
| 77 | Self::UnknownMethod { service, method } => ( |
| 78 | error_code::INVALID_PARAMS, |
| 79 | format!( |
| 80 | "the {} broker has no method `{}`", |
| 81 | service.name(), |
| 82 | method.chars().take(64).collect::<String>() |
| 83 | ), |
| 84 | Value::String(service.name().into()), |
| 85 | ), |
| 86 | Self::InvalidInput { service, message } => ( |
| 87 | error_code::INVALID_PARAMS, |
| 88 | format!("invalid {} broker input: {message}", service.name()), |
| 89 | Value::String(service.name().into()), |
| 90 | ), |
| 91 | Self::NotAvailable(service) => ( |
| 92 | error_code::NOT_AVAILABLE, |
| 93 | format!("the {} broker is not available yet", service.name()), |
| 94 | Value::String(service.name().into()), |
| 95 | ), |
| 96 | Self::NotGranted(service) => ( |
| 97 | error_code::REFUSED, |
| 98 | format!( |
| 99 | "the {} service is not granted to this plugin", |
| 100 | service.name() |
| 101 | ), |
| 102 | Value::String(service.name().into()), |
| 103 | ), |
| 104 | Self::Denied { service, message } => ( |
| 105 | error_code::DENIED, |
| 106 | message, |
| 107 | Value::String(service.name().into()), |
| 108 | ), |
| 109 | Self::Refused { service, message } => ( |
| 110 | error_code::REFUSED, |
| 111 | message, |
| 112 | Value::String(service.name().into()), |
| 113 | ), |
| 114 | }; |
| 115 | RpcErrorWire { |
| 116 | code: rpc, |
| 117 | message, |
| 118 | data: Some(json!({ "dsh_refusal": code, "service": service })), |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[must_use] |
| 123 | pub fn nested(service: DshService, failure: NestedFailure) -> Self { |
| 124 | match failure { |
| 125 | NestedFailure::Rejected { |
| 126 | decision: NestedDecision::Denied, |
| 127 | message, |
| 128 | } => Self::Denied { service, message }, |
| 129 | NestedFailure::Rejected { message, .. } | NestedFailure::Unavailable(message) => { |
| 130 | Self::Refused { service, message } |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | pub const TICKET_REFUSED: &str = "ticket_refused"; |
| 137 | pub const LIMIT: &str = "limit"; |
| 138 | pub const CANCELLED: &str = "cancelled"; |
| 139 | |
| 140 | #[must_use] |
| 141 | pub fn coded(mut error: RpcErrorWire, code: &str) -> RpcErrorWire { |
| 142 | error.data = Some(json!({ "dsh_refusal": code })); |
| 143 | error |
| 144 | } |
| 145 | |
| 146 | pub type BrokerFuture = Pin<Box<dyn Future<Output = Result<Value, BrokerRefusal>> + Send>>; |
| 147 | pub type Arm = fn(BrokerCall) -> BrokerFuture; |
| 148 | |
| 149 | pub const TABLE: &[(DshService, Arm)] = &[ |
| 150 | (DshService::Workspace, dsh_workspace::serve as Arm), |
| 151 | (DshService::Llm, dsh_llm::serve as Arm), |
| 152 | (DshService::Network, dsh_network::serve as Arm), |
| 153 | (DshService::Settings, dsh_settings::serve as Arm), |
| 154 | (DshService::Catalog, dsh_catalog::serve as Arm), |
| 155 | (DshService::Terminal, dsh_terminal::serve as Arm), |
| 156 | (DshService::Remote, dsh_remote::serve as Arm), |
| 157 | (DshService::Attachments, dsh_attachments::serve as Arm), |
| 158 | (DshService::Plugins, dsh_plugins::serve as Arm), |
| 159 | ]; |
| 160 | |
| 161 | #[must_use] |
| 162 | pub fn builtin_services(owner_id: &str) -> &'static [DshService] { |
| 163 | owner_id |
| 164 | .strip_prefix(HOST_OWNER_PREFIX) |
| 165 | .and_then(|module| { |
| 166 | super::tier::BUILTIN_MODULES |
| 167 | .iter() |
| 168 | .find(|row| row.id == module) |
| 169 | .map(|row| row.services) |
| 170 | }) |
| 171 | .unwrap_or(&[]) |
| 172 | } |
| 173 | |
| 174 | fn builtin_route(owner: &OwnerRef, service: DshService) -> bool { |
| 175 | owner.plugin_id.starts_with(HOST_OWNER_PREFIX) || service.builtin_only() |
| 176 | } |
| 177 | |
| 178 | #[must_use] |
| 179 | pub fn builtin_granted( |
| 180 | registry: &OwnerRegistry, |
| 181 | owner: &OwnerRef, |
| 182 | service: DshService, |
| 183 | ) -> Option<bool> { |
| 184 | builtin_route(owner, service).then(|| { |
| 185 | registry.tier_of(owner) == Some(HostTier::Builtin) |
| 186 | && builtin_services(&owner.plugin_id).contains(&service) |
| 187 | }) |
| 188 | } |
| 189 | |
| 190 | #[must_use] |
| 191 | pub fn mintable(tier: HostTier, owner: &OwnerRef, service: DshService, root_agent: bool) -> bool { |
| 192 | if builtin_route(owner, service) || tier == HostTier::Builtin { |
| 193 | tier == HostTier::Builtin |
| 194 | && owner.plugin_id.starts_with(HOST_OWNER_PREFIX) |
| 195 | && builtin_services(&owner.plugin_id).contains(&service) |
| 196 | && (root_agent || !service.builtin_only()) |
| 197 | } else { |
| 198 | tier == HostTier::Plugin |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | #[cfg(test)] |
| 203 | thread_local! { |
| 204 | static TEST_GRANTS: std::cell::RefCell<Option<Vec<DshService>>> = |
| 205 | const { std::cell::RefCell::new(None) }; |
| 206 | } |
| 207 | |
| 208 | #[cfg(test)] |
| 209 | pub struct TestGrants(Option<Vec<DshService>>); |
| 210 | |
| 211 | #[cfg(test)] |
| 212 | impl TestGrants { |
| 213 | pub fn only(services: &[DshService]) -> Self { |
| 214 | Self(TEST_GRANTS.with(|grants| grants.replace(Some(services.to_vec())))) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[cfg(test)] |
| 219 | impl Drop for TestGrants { |
| 220 | fn drop(&mut self) { |
| 221 | let previous = self.0.take(); |
| 222 | TEST_GRANTS.with(|grants| *grants.borrow_mut() = previous); |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | #[cfg(test)] |
| 227 | pub(super) fn test_grants() -> Option<Vec<DshService>> { |
| 228 | TEST_GRANTS.with(|grants| grants.borrow().clone()) |
| 229 | } |
| 230 | |
| 231 | #[cfg(not(test))] |
| 232 | pub(super) fn test_grants() -> Option<Vec<DshService>> { |
| 233 | None |
| 234 | } |
| 235 | |
| 236 | #[must_use] |
| 237 | pub fn offered(service: DshService) -> bool { |
| 238 | use codewhale_plugins::host_services::HostService; |
| 239 | HostService::parse(service.name()).is_some_and(codewhale_plugins::host_services::offered) |
| 240 | } |
| 241 | |
| 242 | #[must_use] |
| 243 | pub fn granted(registry: &OwnerRegistry, owner: &OwnerRef, service: DshService) -> bool { |
| 244 | if let Some(granted) = builtin_granted(registry, owner, service) { |
| 245 | return granted; |
| 246 | } |
| 247 | match test_grants() { |
| 248 | Some(granted) => granted.contains(&service), |
| 249 | None => offered(service) && registry.host_service_granted(owner, service), |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | #[must_use] |
| 254 | pub fn granted_services(registry: &OwnerRegistry, owner: &OwnerRef) -> Vec<DshService> { |
| 255 | DshService::EVERY |
| 256 | .into_iter() |
| 257 | .filter(|service| granted(registry, owner, *service)) |
| 258 | .collect() |
| 259 | } |
| 260 | |
| 261 | #[must_use] |
| 262 | pub fn arm_in(table: &[(DshService, Arm)], service: DshService) -> Option<Arm> { |
| 263 | table |
| 264 | .iter() |
| 265 | .find(|(candidate, _)| *candidate == service) |
| 266 | .map(|(_, arm)| *arm) |
| 267 | } |
| 268 | |
| 269 | #[must_use] |
| 270 | pub fn ticket_method(service: DshService) -> &'static str { |
| 271 | match service { |
| 272 | DshService::Workspace => "dsh/broker:workspace", |
| 273 | DshService::Llm => "dsh/broker:llm", |
| 274 | DshService::Network => "dsh/broker:network", |
| 275 | DshService::Settings => "dsh/broker:settings", |
| 276 | DshService::Catalog => "dsh/broker:catalog", |
| 277 | DshService::Terminal => "dsh/broker:terminal", |
| 278 | DshService::Remote => "dsh/broker:remote", |
| 279 | DshService::Attachments => "dsh/broker:attachments", |
| 280 | DshService::Plugins => "dsh/broker:plugins", |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | pub trait BrokerMethods: DeserializeOwned { |
| 285 | const NAMES: &'static [&'static str]; |
| 286 | } |
| 287 | |
| 288 | pub fn decode<M: BrokerMethods>(call: &BrokerCall) -> Result<M, BrokerRefusal> { |
| 289 | if !M::NAMES.contains(&call.method.as_str()) { |
| 290 | return Err(BrokerRefusal::UnknownMethod { |
| 291 | service: call.service, |
| 292 | method: call.method.clone(), |
| 293 | }); |
| 294 | } |
| 295 | serde_json::from_value(json!({ "method": call.method, "input": call.input })).map_err(|error| { |
| 296 | BrokerRefusal::InvalidInput { |
| 297 | service: call.service, |
| 298 | message: error.to_string(), |
| 299 | } |
| 300 | }) |
| 301 | } |
| 302 | |
| 303 | pub fn not_available(service: DshService) -> BrokerFuture { |
| 304 | Box::pin(std::future::ready(Err(BrokerRefusal::NotAvailable( |
| 305 | service, |
| 306 | )))) |
| 307 | } |
| 308 | |
| 309 | pub const ACT_TOOL: &str = "dsh_broker_act"; |
| 310 | pub const REACH_TOOL: &str = "dsh_broker_reach"; |
| 311 | pub const GATE_TOOLS: [&str; 2] = [ACT_TOOL, REACH_TOOL]; |
| 312 | pub const MAX_ACT_TARGET: usize = 256; |
| 313 | const MAX_OPEN_ACTS: usize = 256; |
| 314 | pub const MAX_OPEN_ACTS_PER_INVOCATION: usize = 4; |
| 315 | |
| 316 | #[must_use] |
| 317 | pub fn is_gate_tool(name: &str) -> bool { |
| 318 | GATE_TOOLS |
| 319 | .iter() |
| 320 | .any(|tool| name.eq_ignore_ascii_case(tool)) |
| 321 | } |
| 322 | |
| 323 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 324 | #[serde(rename_all = "snake_case")] |
| 325 | pub enum BrokerEffect { |
| 326 | Read, |
| 327 | Write, |
| 328 | Reach, |
| 329 | } |
| 330 | |
| 331 | impl BrokerEffect { |
| 332 | #[must_use] |
| 333 | pub fn name(self) -> &'static str { |
| 334 | match self { |
| 335 | Self::Read => "read", |
| 336 | Self::Write => "write", |
| 337 | Self::Reach => "reach", |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | #[must_use] |
| 342 | pub fn gate_tool(self) -> &'static str { |
| 343 | match self { |
| 344 | Self::Reach => REACH_TOOL, |
| 345 | Self::Read | Self::Write => ACT_TOOL, |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | fn of(input: &Value) -> Option<Self> { |
| 350 | serde_json::from_value(input.get("effect")?.clone()).ok() |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | static OPEN_ACTS: std::sync::Mutex<Vec<(usize, Value)>> = std::sync::Mutex::new(Vec::new()); |
| 355 | |
| 356 | fn open_acts() -> std::sync::MutexGuard<'static, Vec<(usize, Value)>> { |
| 357 | OPEN_ACTS |
| 358 | .lock() |
| 359 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 360 | } |
| 361 | |
| 362 | pub struct OpenAct(usize, Value); |
| 363 | |
| 364 | impl OpenAct { |
| 365 | #[must_use] |
| 366 | pub fn open(input: &Value, holder: usize) -> Option<Self> { |
| 367 | let mut open = open_acts(); |
| 368 | if open.len() >= MAX_OPEN_ACTS { |
| 369 | return None; |
| 370 | } |
| 371 | open.push((holder, input.clone())); |
| 372 | Some(Self(holder, input.clone())) |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | impl Drop for OpenAct { |
| 377 | fn drop(&mut self) { |
| 378 | let mut open = open_acts(); |
| 379 | if let Some(at) = open |
| 380 | .iter() |
| 381 | .position(|(holder, act)| *holder == self.0 && *act == self.1) |
| 382 | { |
| 383 | open.swap_remove(at); |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | fn act_is_open(input: &Value) -> bool { |
| 389 | open_acts().iter().any(|(_, open)| open == input) |
| 390 | } |
| 391 | |
| 392 | #[must_use] |
| 393 | pub fn answered_for(input: &Value, result: &Value) -> bool { |
| 394 | match result.get("content") { |
| 395 | Some(Value::String(text)) => { |
| 396 | serde_json::from_str::<Value>(text).is_ok_and(|answered| answered == *input) |
| 397 | } |
| 398 | Some(other) => other == input, |
| 399 | None => false, |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | #[must_use] |
| 404 | pub fn is_gate_spec(spec: &dyn ToolSpec) -> bool { |
| 405 | is_gate_tool(spec.name()) |
| 406 | && spec.registration_origin() == std::any::type_name::<BrokerActTool>() |
| 407 | } |
| 408 | |
| 409 | #[must_use] |
| 410 | pub fn act_description(input: &Value) -> String { |
| 411 | let field = |key: &str| input.get(key).and_then(Value::as_str).unwrap_or("?"); |
| 412 | let verb = match BrokerEffect::of(input) { |
| 413 | Some(BrokerEffect::Write) => "change something", |
| 414 | Some(BrokerEffect::Reach) => "reach outside this session", |
| 415 | _ => "read", |
| 416 | }; |
| 417 | let target = input |
| 418 | .get("target") |
| 419 | .and_then(Value::as_str) |
| 420 | .map(|target| format!(" ({target})")) |
| 421 | .unwrap_or_default(); |
| 422 | format!( |
| 423 | "plugin `{}` asks to {verb} through the {} service: `{}`{target}", |
| 424 | field("plugin"), |
| 425 | field("service"), |
| 426 | field("method"), |
| 427 | ) |
| 428 | } |
| 429 | |
| 430 | pub struct BrokerActTool { |
| 431 | reach: bool, |
| 432 | } |
| 433 | |
| 434 | impl BrokerActTool { |
| 435 | pub const ACT: Self = Self { reach: false }; |
| 436 | pub const REACH: Self = Self { reach: true }; |
| 437 | |
| 438 | #[must_use] |
| 439 | pub fn all() -> [std::sync::Arc<dyn ToolSpec>; 2] { |
| 440 | [ |
| 441 | std::sync::Arc::new(Self::ACT), |
| 442 | std::sync::Arc::new(Self::REACH), |
| 443 | ] |
| 444 | } |
| 445 | |
| 446 | fn effects(&self) -> &'static [&'static str] { |
| 447 | if self.reach { |
| 448 | &["reach"] |
| 449 | } else { |
| 450 | &["read", "write"] |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | fn admits(&self, input: &Value) -> Result<(), ToolError> { |
| 455 | let fits = BrokerEffect::of(input) |
| 456 | .is_some_and(|effect| (effect == BrokerEffect::Reach) == self.reach); |
| 457 | if fits && act_is_open(input) { |
| 458 | Ok(()) |
| 459 | } else { |
| 460 | Err(ToolError::permission_denied(format!( |
| 461 | "{} answers only for an act a plugin broker has open", |
| 462 | self.name() |
| 463 | ))) |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | #[async_trait::async_trait] |
| 469 | impl ToolSpec for BrokerActTool { |
| 470 | fn name(&self) -> &str { |
| 471 | if self.reach { REACH_TOOL } else { ACT_TOOL } |
| 472 | } |
| 473 | |
| 474 | fn description(&self) -> &str { |
| 475 | "The session's permission gate for one act a plugin asked the host broker for." |
| 476 | } |
| 477 | |
| 478 | fn input_schema(&self) -> Value { |
| 479 | json!({ |
| 480 | "type": "object", |
| 481 | "properties": { |
| 482 | "plugin": {"type": "string"}, |
| 483 | "service": {"type": "string"}, |
| 484 | "method": {"type": "string"}, |
| 485 | "effect": {"type": "string", "enum": self.effects()}, |
| 486 | "target": {"type": "string"}, |
| 487 | }, |
| 488 | "required": ["plugin", "service", "method", "effect"], |
| 489 | "additionalProperties": false, |
| 490 | }) |
| 491 | } |
| 492 | |
| 493 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 494 | if self.reach { |
| 495 | vec![ToolCapability::Network] |
| 496 | } else { |
| 497 | Vec::new() |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 502 | ApprovalRequirement::Required |
| 503 | } |
| 504 | |
| 505 | fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement { |
| 506 | match BrokerEffect::of(input) { |
| 507 | Some(BrokerEffect::Read) => ApprovalRequirement::Auto, |
| 508 | _ => ApprovalRequirement::Required, |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | fn is_read_only(&self) -> bool { |
| 513 | false |
| 514 | } |
| 515 | |
| 516 | fn is_read_only_for(&self, input: &Value) -> bool { |
| 517 | BrokerEffect::of(input) == Some(BrokerEffect::Read) |
| 518 | } |
| 519 | |
| 520 | fn model_visible(&self) -> bool { |
| 521 | false |
| 522 | } |
| 523 | |
| 524 | fn prepare( |
| 525 | &self, |
| 526 | input: Value, |
| 527 | _context: &ToolContext, |
| 528 | ) -> Result<crate::tools::spec::PreparedToolCall, ToolError> { |
| 529 | self.admits(&input)?; |
| 530 | Ok(crate::tools::spec::PreparedToolCall { |
| 531 | name: self.name().to_string(), |
| 532 | description: act_description(&input), |
| 533 | read_only: self.is_read_only_for(&input), |
| 534 | supports_parallel: false, |
| 535 | starts_detached: false, |
| 536 | approval: self.approval_requirement_for(&input), |
| 537 | resources: vec![crate::tools::spec::ResourceClaim::GlobalExclusive], |
| 538 | input, |
| 539 | }) |
| 540 | } |
| 541 | |
| 542 | async fn execute(&self, input: Value, _context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 543 | self.admits(&input)?; |
| 544 | Ok(ToolResult::success(input.to_string())) |
| 545 | } |
| 546 | } |
| 547 |