返回 CodeWhale
registry.rs
根目录 / crates / engine / src / extension_host / registry.rs
1 //! Owned registrations: the Rust side is the authority (design §3).
2 //!
3 //! Every registration belongs to exactly one `(plugin_id, generation)` owner.
4 //! Revocation is synchronous and never waits for the host: removing an owner
5 //! removes its tools from every later turn's registry at once, and
6 //! `HostToolSpec` re-checks liveness before each call. Handles are never
7 //! reused, so undoing one registration can never touch a newer one.
8 //!
9 //! One registry serves both trust tiers ([`super::tier`]): an owner records
10 //! which host process it lives in, `begin_owner` refuses an id the tier cannot
11 //! hold (`host:<module>` is tier 0's alone), and a host exit removes only its
12 //! own tier's owners and registrations.
13
14 use std::collections::{BTreeMap, HashMap, HashSet};
15 use std::sync::Arc;
16
17 use serde_json::Value;
18
19 use super::protocol::{DshService, RegisterKind, RegisterParams};
20 use super::tier::{HostCohort, HostTier, PluginCohort};
21 use codewhale_config::PluginAuthority;
22 use codewhale_config::{EntryRef, OwnerRef};
23
24 /// Largest accepted tool input schema, serialized.
25 pub const MAX_SCHEMA_BYTES: usize = 64 * 1024;
26 /// Largest accepted tool description.
27 pub const MAX_DESCRIPTION_BYTES: usize = 4 * 1024;
28 pub const MAX_TOOLS_PER_OWNER: usize = 128;
29 pub const MAX_TOOLS_PER_HOST: usize = 1024;
30 /// Commands are listed in the palette and `/help`, so the caps are tighter.
31 pub const MAX_COMMANDS_PER_OWNER: usize = 64;
32 pub const MAX_COMMANDS_PER_HOST: usize = 256;
33 /// A command description is one palette line; a hint is a short placeholder.
34 pub const MAX_COMMAND_DESCRIPTION_BYTES: usize = 1024;
35 pub const MAX_COMMAND_HINT_BYTES: usize = 256;
36
37 /// Name prefixes no extension may use: MCP's namespace, and one kept free
38 /// for future core-issued extension names.
39 const RESERVED_PREFIXES: &[&str] = &["mcp_", "ext_"];
40 const NAME_HINT: &str = "use a plugin-specific prefix, for example `myplugin_read_x`";
41
42 /// Core tool names that exist outside the native registry builder (catalog
43 /// meta-tools) and so never show up in a registry snapshot.
44 const RESERVED_NAMES: &[&str] = &[
45 "tool_search",
46 "tool_search_tool_regex",
47 "tool_search_tool_bm25",
48 "retrieve_tool_result",
49 "execute_tools",
50 "code_execution",
51 "js_execution",
52 "request_user_input",
53 "multi_tool_use.parallel",
54 "dsh_broker_act",
55 "dsh_broker_reach",
56 ];
57
58 #[derive(Debug, Clone, PartialEq, Eq)]
59 pub enum OwnerState {
60 Activating,
61 Active,
62 Failed(String),
63 Faulted(String),
64 Revoked,
65 }
66
67 #[derive(Debug, Clone)]
68 pub struct OwnerEntry {
69 pub owner: OwnerRef,
70 pub cohort: HostCohort,
71 pub plugin_name: String,
72 pub authority: Option<PluginAuthority>,
73 pub content_hash: String,
74 pub config_hash: String,
75 pub host_services: Vec<DshService>,
76 pub state: OwnerState,
77 pub scopes: HashMap<EntryRef, OwnerState>,
78 }
79
80 impl OwnerEntry {
81 pub fn tier(&self) -> HostTier {
82 self.cohort.tier()
83 }
84
85 pub fn live(&self) -> bool {
86 matches!(self.state, OwnerState::Activating | OwnerState::Active)
87 }
88
89 pub fn loaded_in_cohort(&self, cohort: &HostCohort) -> bool {
90 self.cohort == *cohort && self.live()
91 }
92
93 pub fn loaded_in_plugin_host(&self) -> bool {
94 self.cohort.tier() == HostTier::Plugin && self.live()
95 }
96 }
97
98 /// Most schema violations one refused call reports back to the model.
99 const MAX_REPORTED_INPUT_ERRORS: usize = 5;
100 /// Bound on the refusal text (violations quote the offending values).
101 const MAX_INPUT_ERROR_BYTES: usize = 2048;
102
103 /// A tool's input schema, compiled once at registration. The core checks every
104 /// call's input against it before anything is sent to the host: a plugin that
105 /// registers a plain object receives only input its own schema admits, without
106 /// having to validate it itself.
107 ///
108 /// Compiled by `jsonschema` (already linked for Workflow `responseSchema`),
109 /// which resolves no external `$ref` here (no network or file resolver is
110 /// enabled); a schema it cannot compile is refused at registration.
111 #[derive(Clone)]
112 pub struct InputValidator(Arc<jsonschema::Validator>);
113
114 impl InputValidator {
115 /// Compile `schema`, or say why it cannot be.
116 pub fn compile(schema: &Value) -> Result<Self, String> {
117 jsonschema::validator_for(schema)
118 .map(|validator| Self(Arc::new(validator)))
119 .map_err(|error| error.to_string())
120 }
121
122 /// `Ok` when `input` satisfies the schema; otherwise the violations, as
123 /// text a model can correct its call from.
124 pub fn check(&self, input: &Value) -> Result<(), String> {
125 let mut errors = self.0.iter_errors(input);
126 let Some(first) = errors.next() else {
127 return Ok(());
128 };
129 let describe = |error: &jsonschema::ValidationError<'_>| {
130 let at = error.instance_path().to_string();
131 if at.is_empty() {
132 error.to_string()
133 } else {
134 format!("{error} (at {at})")
135 }
136 };
137 let mut reasons = vec![describe(&first)];
138 let mut more = 0usize;
139 for error in errors {
140 if reasons.len() < MAX_REPORTED_INPUT_ERRORS {
141 reasons.push(describe(&error));
142 } else {
143 more += 1;
144 }
145 }
146 let mut text = reasons.join("; ");
147 if more > 0 {
148 text.push_str(&format!("; and {more} more"));
149 }
150 if text.len() > MAX_INPUT_ERROR_BYTES {
151 let mut end = MAX_INPUT_ERROR_BYTES;
152 while !text.is_char_boundary(end) {
153 end -= 1;
154 }
155 text.truncate(end);
156 text.push('…');
157 }
158 Err(text)
159 }
160 }
161
162 impl PartialEq for InputValidator {
163 fn eq(&self, other: &Self) -> bool {
164 Arc::ptr_eq(&self.0, &other.0)
165 }
166 }
167
168 impl std::fmt::Debug for InputValidator {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 f.debug_struct("InputValidator").finish_non_exhaustive()
171 }
172 }
173
174 #[derive(Debug, Clone, PartialEq)]
175 pub struct ToolRegistration {
176 pub handle: u64,
177 pub owner: OwnerRef,
178 pub scope: Option<EntryRef>,
179 pub cohort: HostCohort,
180 pub plugin_name: String,
181 pub content_hash: String,
182 pub name: String,
183 pub description: String,
184 pub input_schema: Value,
185 pub input_validator: InputValidator,
186 }
187
188 impl ToolRegistration {
189 pub fn tier(&self) -> HostTier {
190 self.cohort.tier()
191 }
192 }
193
194 #[derive(Debug, Clone, PartialEq)]
195 pub struct CommandRegistration {
196 pub handle: u64,
197 pub owner: OwnerRef,
198 pub scope: Option<EntryRef>,
199 pub cohort: HostCohort,
200 pub plugin_name: String,
201 pub content_hash: String,
202 pub name: String,
203 pub declared_name: String,
204 pub description: String,
205 pub argument_hint: Option<String>,
206 }
207
208 impl CommandRegistration {
209 pub fn tier(&self) -> HostTier {
210 self.cohort.tier()
211 }
212 }
213
214 #[derive(Debug, Clone, PartialEq)]
215 pub struct HookRegistration {
216 pub handle: u64,
217 pub owner: OwnerRef,
218 pub scope: Option<EntryRef>,
219 pub cohort: HostCohort,
220 pub plugin_name: String,
221 pub content_hash: String,
222 pub event: String,
223 }
224
225 impl HookRegistration {
226 pub fn tier(&self) -> HostTier {
227 self.cohort.tier()
228 }
229 }
230
231 #[derive(Debug, Clone, PartialEq)]
232 pub struct PromptSectionRegistration {
233 pub handle: u64,
234 pub owner: OwnerRef,
235 pub scope: Option<EntryRef>,
236 pub cohort: HostCohort,
237 pub plugin_name: String,
238 pub content_hash: String,
239 pub id: String,
240 pub text: String,
241 pub interpolate: bool,
242 }
243
244 impl PromptSectionRegistration {
245 pub fn tier(&self) -> HostTier {
246 self.cohort.tier()
247 }
248 }
249
250 #[derive(Debug, Clone)]
251 pub struct ShellHookRegistration {
252 pub handle: u64,
253 pub owner: OwnerRef,
254 pub scope: Option<EntryRef>,
255 pub content_hash: String,
256 pub hook: codewhale_config::hooks::Hook,
257 }
258 #[derive(Debug, serde::Deserialize)]
259 #[serde(deny_unknown_fields)]
260 struct ShellSpec {
261 dialect: String,
262 point: String,
263 #[serde(default)]
264 matcher: Option<String>,
265 hook: codewhale_config::hooks::Hook,
266 }
267
268 #[derive(Debug, Default)]
269 pub struct OwnerRegistry {
270 next_handle: u64,
271 next_generation: u64,
272 owners: HashMap<String, OwnerEntry>,
273 tools: BTreeMap<u64, ToolRegistration>,
274 /// Lower-cased tool name → handle, so `Read` cannot impersonate `read`.
275 by_name: HashMap<String, u64>,
276 commands: BTreeMap<u64, CommandRegistration>,
277 /// Command name → handle. Commands and tools are separate namespaces: a
278 /// tool is called by the model, a command by the user.
279 commands_by_name: HashMap<String, u64>,
280 hooks: BTreeMap<u64, HookRegistration>,
281 shell_hooks: BTreeMap<u64, ShellHookRegistration>,
282 prompt_sections: BTreeMap<u64, PromptSectionRegistration>,
283 skill_roots: BTreeMap<u64, super::skills::SkillRootRegistration>,
284 avatar_packs: BTreeMap<u64, super::avatars::AvatarRegistration>,
285 mcp_servers: BTreeMap<u64, super::native_mcp::McpRegistration>,
286 /// Lower-cased names of every native tool any engine's turn build has
287 /// reported, plus the static set. Only ever grows: engines in one
288 /// process build different native surfaces, and a name that is native
289 /// anywhere is refused everywhere.
290 native_names: HashSet<String>,
291 departed_cohorts: HashSet<HostCohort>,
292 withheld_reported: String,
293 }
294
295 fn mint_token() -> String {
296 // Two v4 UUIDs: 244 random bits from the OS generator.
297 format!(
298 "{}{}",
299 uuid::Uuid::new_v4().simple(),
300 uuid::Uuid::new_v4().simple()
301 )
302 }
303
304 fn valid_tool_name(name: &str) -> bool {
305 let mut chars = name.chars();
306 matches!(chars.next(), Some(first) if first.is_ascii_alphabetic())
307 && name.len() <= 64
308 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
309 }
310
311 /// DSH's command grammar (`^[a-z][a-z0-9_-]*$`), bounded. Lower case only:
312 /// the user's input is lower-cased before it is looked up.
313 fn valid_command_name(name: &str) -> bool {
314 let mut chars = name.chars();
315 matches!(chars.next(), Some(first) if first.is_ascii_lowercase())
316 && name.len() <= 64
317 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
318 }
319
320 fn namespaced_command(plugin_name: &str, plugin_id: &str, name: &str) -> String {
321 let slug: String = plugin_name
322 .chars()
323 .map(|c| {
324 let c = c.to_ascii_lowercase();
325 if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-' {
326 c
327 } else {
328 '-'
329 }
330 })
331 .collect();
332 let slug = slug.trim_matches('-');
333 let slug = if slug.is_empty() { "extension" } else { slug };
334 let mut alias = format!("plugin-{slug}-{name}");
335 if alias.len() > 64 {
336 let digest = codewhale_runtime::hashing::sha256_hex(format!("{plugin_id}\0{name}"));
337 alias.truncate(51);
338 while alias.ends_with('-') {
339 alias.pop();
340 }
341 alias.push('-');
342 alias.push_str(&digest[..12]);
343 }
344 alias
345 }
346
347 /// Why the core would treat a tool called `name` as something other than an
348 /// opaque extension tool, if it would.
349 ///
350 /// Approval keys, approval-card summaries, and the approval/auto-review
351 /// category are all derived from the tool *name*. A name any of them
352 /// special-cases would let an extension borrow a native tool's identity: a
353 /// session grant for `fetch_url` on a host (`net:<host>`) would approve a
354 /// plugin tool named `web_fetch`, and a `read_*` name would be classified as
355 /// a read. Such names need not be registered natives (`web_fetch`,
356 /// `exec_wait`, and mode-dependent tools such as `task_shell_start` are not),
357 /// so they are refused by probing the classifiers themselves rather than by a
358 /// hand-kept list that would drift from them.
359 fn core_special_case(name: &str) -> Option<&'static str> {
360 use crate::core::authority::{ToolCategory, get_tool_category_for_call};
361 use crate::tools::approval_cache::{build_approval_grouping_key, build_approval_key};
362 let empty = Value::Object(serde_json::Map::new());
363 let spellings = [name.to_string(), name.to_ascii_lowercase()];
364 for spelling in &spellings {
365 let generic = format!("tool:{spelling}:");
366 if !build_approval_key(spelling, &empty).0.starts_with(&generic)
367 || !build_approval_grouping_key(spelling, &empty)
368 .0
369 .starts_with(&generic)
370 {
371 return Some("the approval cache keys it as a built-in tool family");
372 }
373 if codewhale_execpolicy::canonical_action::canonical_action_alias(spelling, &empty)
374 != spelling
375 {
376 return Some("it is an alias of a built-in tool");
377 }
378 if crate::tools::approval_summary::approval_summary(spelling, &empty, None)
379 != format!("Use the {spelling} tool")
380 {
381 return Some("approval cards describe it as a built-in tool");
382 }
383 if get_tool_category_for_call(spelling, &empty) != ToolCategory::Unknown {
384 return Some(
385 "the approval policy classifies it by name (read, write, shell, network, MCP or agent)",
386 );
387 }
388 }
389 None
390 }
391
392 impl OwnerRegistry {
393 #[must_use]
394 pub fn new() -> Self {
395 let mut native_names: HashSet<String> = RESERVED_NAMES
396 .iter()
397 .chain(crate::core::engine::tool_catalog::DEFAULT_ACTIVE_NATIVE_TOOLS)
398 .map(|name| name.to_ascii_lowercase())
399 .collect();
400 for (family, _, alias) in codewhale_execpolicy::canonical_action::CANONICAL_ACTION_ALIASES {
401 native_names.insert(family.to_ascii_lowercase());
402 native_names.insert(alias.to_ascii_lowercase());
403 }
404 Self {
405 native_names,
406 ..Self::default()
407 }
408 }
409
410 /// Add native tool names from one engine's turn build (the registry
411 /// before scripts, plugins or extensions are added). Never removes one.
412 pub fn add_native_names<'a>(&mut self, names: impl IntoIterator<Item = &'a str>) {
413 self.native_names
414 .extend(names.into_iter().map(str::to_ascii_lowercase));
415 }
416
417 /// Start a new activation for `plugin_id` on `tier`, superseding any
418 /// previous one. Refuses an id the tier cannot hold (a `host:` id on the
419 /// plugin tier, any other on the builtin tier) and an authority that does
420 /// not fit it: a plugin owner is bound to its reviewed plugin authority, a
421 /// built-in module to none (its pinned digest is `content_hash`).
422 pub fn begin_owner(
423 &mut self,
424 cohort: impl Into<HostCohort>,
425 plugin_id: &str,
426 plugin_name: &str,
427 authority: Option<PluginAuthority>,
428 content_hash: &str,
429 ) -> Result<OwnerRef, String> {
430 let cohort = cohort.into();
431 let tier = cohort.tier();
432 tier.check_owner_id(plugin_id)?;
433 match (tier, authority.is_some()) {
434 (HostTier::Plugin, false) => {
435 return Err(format!(
436 "plugin owner `{plugin_id}` needs its reviewed plugin authority"
437 ));
438 }
439 (HostTier::Builtin, true) => {
440 return Err(format!(
441 "built-in module `{plugin_id}` has no plugin authority; the digest the Rust table pins is its authority"
442 ));
443 }
444 _ => {}
445 }
446 self.revoke_owner(plugin_id);
447 self.next_generation += 1;
448 let owner = OwnerRef {
449 plugin_id: plugin_id.to_string(),
450 generation: self.next_generation,
451 owner_token: mint_token(),
452 };
453 self.owners.insert(
454 plugin_id.to_string(),
455 OwnerEntry {
456 owner: owner.clone(),
457 cohort,
458 plugin_name: plugin_name.to_string(),
459 authority,
460 content_hash: content_hash.to_string(),
461 config_hash: String::new(),
462 host_services: Vec::new(),
463 state: OwnerState::Activating,
464 scopes: HashMap::new(),
465 },
466 );
467 Ok(owner)
468 }
469
470 /// Record which config `owner`'s activation was given.
471 pub fn set_config_hash(&mut self, owner: &OwnerRef, hash: &str) {
472 if let Some(entry) = self.owners.get_mut(&owner.plugin_id)
473 && entry.owner == *owner
474 {
475 entry.config_hash = hash.to_string();
476 }
477 }
478
479 pub fn set_host_services(&mut self, owner: &OwnerRef, services: Vec<DshService>) {
480 if let Some(entry) = self.owners.get_mut(&owner.plugin_id)
481 && entry.owner == *owner
482 && entry.cohort.tier() == HostTier::Plugin
483 && entry.authority.is_some()
484 {
485 entry.host_services = services;
486 }
487 }
488
489 #[must_use]
490 pub fn host_service_granted(&self, owner: &OwnerRef, service: DshService) -> bool {
491 let Some(entry) = self.current(owner) else {
492 return false;
493 };
494 if entry.cohort.tier() != HostTier::Plugin || entry.authority.is_none() {
495 return false;
496 }
497 if self.departed_cohorts.contains(&entry.cohort) {
498 return false;
499 }
500 self.owners
501 .values()
502 .filter(|other| other.loaded_in_cohort(&entry.cohort))
503 .all(|other| other.host_services.contains(&service))
504 }
505
506 #[must_use]
507 pub fn cohort_authorities(&self, cohort: &HostCohort) -> Vec<PluginAuthority> {
508 self.owners
509 .values()
510 .filter(|entry| entry.loaded_in_cohort(cohort))
511 .filter_map(|entry| entry.authority.clone())
512 .collect()
513 }
514
515 #[must_use]
516 pub fn plugin_host_authorities(&self) -> Vec<PluginAuthority> {
517 self.cohort_authorities(&HostCohort::reviewed())
518 }
519
520 #[must_use]
521 pub fn cohort_departed(&self, cohort: &HostCohort) -> bool {
522 self.departed_cohorts.contains(cohort)
523 }
524
525 #[must_use]
526 pub fn host_services_await_restart(&self, cohort: impl Into<HostCohort>) -> bool {
527 let cohort = cohort.into();
528 self.departed_cohorts.contains(&cohort)
529 && self
530 .owners
531 .values()
532 .any(|entry| entry.loaded_in_cohort(&cohort) && !entry.host_services.is_empty())
533 }
534
535 pub fn host_process_started(&mut self, cohort: impl Into<HostCohort>) {
536 self.departed_cohorts.remove(&cohort.into());
537 }
538
539 pub fn take_withheld_report(&mut self) -> Option<String> {
540 let mut reports = Vec::new();
541 let mut cohorts: Vec<HostCohort> = self
542 .owners
543 .values()
544 .map(|entry| entry.cohort.clone())
545 .collect::<HashSet<_>>()
546 .into_iter()
547 .collect();
548 cohorts.sort_by_key(|c| c.to_string());
549 for cohort in &cohorts {
550 let loaded: Vec<&OwnerEntry> = self
551 .owners
552 .values()
553 .filter(|entry| entry.loaded_in_cohort(cohort))
554 .collect();
555 if loaded.is_empty() {
556 continue;
557 }
558 let mut held: Vec<DshService> = DshService::ALL
559 .into_iter()
560 .filter(|service| {
561 loaded
562 .iter()
563 .any(|entry| entry.host_services.contains(service))
564 })
565 .collect();
566 if held.is_empty() {
567 continue;
568 }
569 if self.departed_cohorts.contains(cohort) {
570 let label = match cohort {
571 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
572 format!("agent cohort `{}` host services are off until its host restarts: a plugin that was turned off, changed or failed is still loaded in it", cohort)
573 }
574 _ => "host services are off until the plugin host restarts: a plugin that was turned off, changed or failed is still loaded in it".to_string(),
575 };
576 reports.push(label);
577 } else {
578 held.retain(|service| {
579 loaded
580 .iter()
581 .any(|entry| !entry.host_services.contains(service))
582 });
583 for service in held {
584 let mut without: Vec<&str> = loaded
585 .iter()
586 .filter(|entry| !entry.host_services.contains(&service))
587 .map(|entry| entry.plugin_name.as_str())
588 .collect();
589 without.sort_unstable();
590 reports.push(format!(
591 "host service `{}` is off: the {} of {} {} not include it",
592 service.name(),
593 if without.len() == 1 {
594 "review"
595 } else {
596 "reviews"
597 },
598 without
599 .iter()
600 .map(|name| format!("`{name}`"))
601 .collect::<Vec<_>>()
602 .join(", "),
603 if without.len() == 1 { "does" } else { "do" },
604 ));
605 }
606 }
607 }
608 let report = reports.join("; ");
609 if report == self.withheld_reported {
610 return None;
611 }
612 self.withheld_reported.clone_from(&report);
613 (!report.is_empty()).then_some(report)
614 }
615
616 #[must_use]
617 pub fn owner(&self, plugin_id: &str) -> Option<&OwnerEntry> {
618 self.owners.get(plugin_id)
619 }
620
621 pub(super) fn route_owner(
622 &self,
623 authority: &PluginAuthority,
624 ) -> Result<Option<&OwnerEntry>, &'static str> {
625 let Some(entry) = self.owner(authority.plugin_id.as_str()) else {
626 return Ok(None);
627 };
628 match entry.authority.as_ref() {
629 Some(current) if current == authority => Ok(Some(entry)),
630 Some(current)
631 if current.state_path == authority.state_path
632 && current.workspace != authority.workspace
633 && entry.state != OwnerState::Revoked =>
634 {
635 Err("workspace_conflict")
636 }
637 _ => Ok(None),
638 }
639 }
640
641 #[must_use]
642 pub fn cohort_of_plugin_id(&self, plugin_id: &str) -> Option<HostCohort> {
643 self.owners.get(plugin_id).map(|entry| entry.cohort.clone())
644 }
645
646 pub fn owners(&self) -> impl Iterator<Item = &OwnerEntry> {
647 self.owners.values()
648 }
649
650 /// The exact current, not-yet-revoked owner (token and generation match).
651 fn current(&self, owner: &OwnerRef) -> Option<&OwnerEntry> {
652 self.owners.get(&owner.plugin_id).filter(|entry| {
653 entry.owner == *owner
654 && matches!(entry.state, OwnerState::Activating | OwnerState::Active)
655 })
656 }
657
658 pub fn mark_active(&mut self, owner: &OwnerRef) -> bool {
659 match self.owners.get_mut(&owner.plugin_id) {
660 Some(entry) if entry.owner == *owner && entry.state == OwnerState::Activating => {
661 entry.state = OwnerState::Active;
662 super::native_mcp::changed();
663 super::command::bump_epoch();
664 true
665 }
666 _ => false,
667 }
668 }
669
670 /// Mark an owner failed or faulted and drop everything it registered.
671 pub fn mark_failed(&mut self, owner: &OwnerRef, state: OwnerState) -> bool {
672 let matches = self
673 .owners
674 .get(&owner.plugin_id)
675 .is_some_and(|entry| entry.owner == *owner);
676 if matches {
677 self.remove_registrations_of(&owner.plugin_id);
678 if let Some(entry) = self.owners.get_mut(&owner.plugin_id) {
679 if entry.live() {
680 self.departed_cohorts.insert(entry.cohort.clone());
681 }
682 entry.state = state;
683 }
684 }
685 matches
686 }
687
688 pub fn record_activation_failure(
689 &mut self,
690 cohort: HostCohort,
691 plugin_id: &str,
692 plugin_name: &str,
693 authority: Option<PluginAuthority>,
694 content_hash: &str,
695 reason: String,
696 ) {
697 self.remove_registrations_of(plugin_id);
698 self.next_generation += 1;
699 let owner = OwnerRef {
700 plugin_id: plugin_id.to_string(),
701 generation: self.next_generation,
702 owner_token: mint_token(),
703 };
704 self.owners.insert(
705 plugin_id.to_string(),
706 OwnerEntry {
707 owner,
708 cohort,
709 plugin_name: plugin_name.to_string(),
710 authority,
711 content_hash: content_hash.to_string(),
712 config_hash: String::new(),
713 host_services: Vec::new(),
714 state: OwnerState::Failed(reason),
715 scopes: HashMap::new(),
716 },
717 );
718 }
719
720 /// Only core invokes this after the existing Native inventory/receipt check.
721 pub(super) fn begin_scope(&mut self, owner: &OwnerRef, scope: EntryRef) -> Result<(), String> {
722 let entry = self
723 .owners
724 .get_mut(&owner.plugin_id)
725 .filter(|entry| entry.owner == *owner)
726 .ok_or("scope owner was withdrawn")?;
727 if entry.cohort.tier() != HostTier::Plugin || entry.authority.is_none() {
728 return Err("scope requires reviewed Native authority".into());
729 }
730 if entry.scopes.contains_key(&scope) {
731 return Err("scope is already admitted".into());
732 }
733 entry.scopes.insert(scope, OwnerState::Activating);
734 Ok(())
735 }
736 pub(super) fn mark_scope_active(&mut self, owner: &OwnerRef, scope: &EntryRef) -> bool {
737 let Some(entry) = self
738 .owners
739 .get_mut(&owner.plugin_id)
740 .filter(|entry| entry.owner == *owner)
741 else {
742 return false;
743 };
744 let Some(state) = entry.scopes.get_mut(scope) else {
745 return false;
746 };
747 if *state != OwnerState::Activating {
748 return false;
749 }
750 *state = OwnerState::Active;
751 super::native_mcp::changed();
752 super::command::bump_epoch();
753 true
754 }
755 pub(super) fn check_scope(
756 &self,
757 owner: &OwnerRef,
758 scope: Option<&EntryRef>,
759 active: bool,
760 ) -> Result<(), String> {
761 let entry = self.current(owner).ok_or("scope owner was withdrawn")?;
762 if scope.is_none() && entry.cohort.tier() == HostTier::Plugin && !entry.scopes.is_empty() {
763 return Err("Native contribution must name its core-admitted entry scope".into());
764 }
765 if let Some(scope) = scope {
766 let state = entry
767 .scopes
768 .get(scope)
769 .ok_or("scope was not admitted by core")?;
770 if !matches!(state, OwnerState::Active)
771 && (active || !matches!(state, OwnerState::Activating))
772 {
773 return Err("scope was withdrawn or is not ready".into());
774 }
775 }
776 Ok(())
777 }
778 pub(super) fn fail_scope(&mut self, owner: &OwnerRef, scope: &EntryRef) {
779 let _ = self.revoke_scope(owner, scope);
780 if let Some(entry) = self
781 .owners
782 .get_mut(&owner.plugin_id)
783 .filter(|entry| entry.owner == *owner)
784 {
785 entry.scopes.insert(
786 scope.clone(),
787 OwnerState::Failed("Native entry activation failed".into()),
788 );
789 }
790 }
791 pub(super) fn revoke_scope(&mut self, owner: &OwnerRef, scope: &EntryRef) -> Vec<u64> {
792 if let Some(entry) = self
793 .owners
794 .get_mut(&owner.plugin_id)
795 .filter(|entry| entry.owner == *owner)
796 {
797 entry.scopes.remove(scope);
798 }
799 let handles: Vec<_> = self
800 .tools
801 .values()
802 .filter(|r| r.owner == *owner && r.scope.as_ref() == Some(scope))
803 .map(|r| r.handle)
804 .chain(
805 self.commands
806 .values()
807 .filter(|r| r.owner == *owner && r.scope.as_ref() == Some(scope))
808 .map(|r| r.handle),
809 )
810 .chain(
811 self.hooks
812 .values()
813 .filter(|r| r.owner == *owner && r.scope.as_ref() == Some(scope))
814 .map(|r| r.handle),
815 )
816 .chain(
817 self.shell_hooks
818 .values()
819 .filter(|r| r.owner == *owner && r.scope.as_ref() == Some(scope))
820 .map(|r| r.handle),
821 )
822 .chain(
823 self.prompt_sections
824 .values()
825 .filter(|r| r.owner == *owner && r.scope.as_ref() == Some(scope))
826 .map(|r| r.handle),
827 )
828 .chain(
829 self.skill_roots
830 .values()
831 .filter(|r| r.owner == *owner && r.scope.as_ref() == Some(scope))
832 .map(|r| r.handle),
833 )
834 .chain(
835 self.avatar_packs
836 .values()
837 .filter(|r| r.owner == *owner && r.scope.as_ref() == Some(scope))
838 .map(|r| r.handle),
839 )
840 .chain(
841 self.mcp_servers
842 .values()
843 .filter(|r| r.owner == *owner && r.scope == *scope)
844 .map(|r| r.handle),
845 )
846 .collect();
847 for handle in &handles {
848 self.unregister(owner, *handle);
849 }
850 super::command::bump_epoch();
851 handles
852 }
853
854 /// Admit or refuse one `registry/register`, whatever its kind.
855 pub fn register(&mut self, params: &RegisterParams) -> Result<u64, String> {
856 match params.kind {
857 RegisterKind::Tool => self.register_tool(params),
858 RegisterKind::Command => self.register_command(params),
859 RegisterKind::Hook => self.register_hook(params),
860 RegisterKind::ShellHook => self.register_shell_hook(params),
861 RegisterKind::PromptSection | RegisterKind::PromptTemplate => {
862 self.register_prompt_section(params)
863 }
864 RegisterKind::McpServer => {
865 Err("MCP definitions require reviewed snapshot admission".into())
866 }
867 RegisterKind::AvatarPack => {
868 Err("avatar packs require reviewed snapshot admission".into())
869 }
870 RegisterKind::SkillRoot => {
871 Err("skill roots require reviewed snapshot admission".to_string())
872 }
873 }
874 }
875
876 pub(super) fn register_mcp(
877 &mut self,
878 params: &RegisterParams,
879 config: codewhale_mcp::config::McpServerConfig,
880 host_generation: u64,
881 ) -> Result<u64, String> {
882 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
883 params.check_spec()?;
884 if params.kind != RegisterKind::McpServer
885 || params.spec.description.len() > super::native_mcp::MAX_DEFINITION_BYTES
886 {
887 return Err("Invalid MCP definition".into());
888 }
889 let scope = params
890 .scope
891 .clone()
892 .ok_or("MCP definition requires an entry scope")?;
893 let owner = self.current(&params.owner).ok_or("MCP owner is stale")?;
894 if owner.cohort.tier() != HostTier::Plugin {
895 return Err("MCP definition owner must be Native".into());
896 }
897 let content_hash = owner.content_hash.clone();
898 let owned = self
899 .mcp_servers
900 .values()
901 .filter(|r| r.owner == params.owner)
902 .collect::<Vec<_>>();
903 if owned.len() >= super::native_mcp::MAX_PER_OWNER
904 || self.mcp_servers.len() >= super::native_mcp::MAX_PER_HOST
905 {
906 return Err("MCP owner or host definition limit reached".into());
907 }
908 if owned
909 .iter()
910 .any(|r| r.name == params.spec.name && r.scope == scope)
911 {
912 return Err("MCP server is already registered in this entry".into());
913 }
914 self.next_handle += 1;
915 let handle = self.next_handle;
916 self.mcp_servers.insert(
917 handle,
918 super::native_mcp::McpRegistration {
919 handle,
920 owner: params.owner.clone(),
921 scope,
922 content_hash,
923 host_generation,
924 name: params.spec.name.clone(),
925 config,
926 cancel: tokio_util::sync::CancellationToken::new(),
927 },
928 );
929 super::native_mcp::changed();
930 Ok(handle)
931 }
932 pub(super) fn live_mcp(&self) -> Vec<super::native_mcp::McpRegistration> {
933 self.mcp_servers
934 .values()
935 .filter(|r| self.is_live_mcp(r))
936 .cloned()
937 .collect()
938 }
939 pub(super) fn is_live_mcp(&self, r: &super::native_mcp::McpRegistration) -> bool {
940 self.mcp_servers.get(&r.handle).is_some_and(|current| {
941 current.owner == r.owner
942 && current.scope == r.scope
943 && current.host_generation == r.host_generation
944 && current.content_hash == r.content_hash
945 }) && self.owners.get(&r.owner.plugin_id).is_some_and(|owner| {
946 owner.owner == r.owner
947 && owner.state == OwnerState::Active
948 && self.check_scope(&r.owner, Some(&r.scope), true).is_ok()
949 })
950 }
951
952 pub fn register_avatar(
953 &mut self,
954 params: &RegisterParams,
955 pack: codewhale_protocol::avatar::Pack,
956 png: Vec<Vec<u8>>,
957 host_generation: u64,
958 ) -> Result<u64, String> {
959 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
960 params.check_spec()?;
961 if params.kind != RegisterKind::AvatarPack || !params.spec.description.is_empty() {
962 return Err("invalid avatar pack registration".into());
963 }
964 pack.validate()?;
965 if png.len() != pack.atlases.len() {
966 return Err("avatar pages do not match manifest".into());
967 }
968 for page in &png {
969 pack.validate_png(page)?;
970 }
971 let entry = self.current(&params.owner).ok_or("stale avatar owner")?;
972 if entry.cohort.tier() != HostTier::Plugin || entry.authority.is_none() {
973 return Err("avatar pack owner has no reviewed bundle".into());
974 }
975 let content_hash = entry.content_hash.clone();
976 let owned: Vec<_> = self
977 .avatar_packs
978 .values()
979 .filter(|r| r.owner == params.owner)
980 .collect();
981 if owned.len() >= 4
982 || self.avatar_packs.len() >= 16
983 || self
984 .avatar_packs
985 .values()
986 .map(|r| r.png.iter().map(Vec::len).sum::<usize>())
987 .sum::<usize>()
988 + png.iter().map(Vec::len).sum::<usize>()
989 > 32 * 1024 * 1024
990 || owned
991 .iter()
992 .any(|r| r.pack.id == pack.id && r.scope == params.scope)
993 {
994 return Err("avatar pack duplicate or registration budget exceeded".into());
995 }
996 self.next_handle += 1;
997 let handle = self.next_handle;
998 self.avatar_packs.insert(
999 handle,
1000 super::avatars::AvatarRegistration {
1001 handle,
1002 owner: params.owner.clone(),
1003 scope: params.scope.clone(),
1004 host_generation,
1005 content_hash,
1006 pack,
1007 png: Arc::new(png),
1008 },
1009 );
1010 Ok(handle)
1011 }
1012
1013 pub fn live_avatars(&self) -> Vec<super::avatars::AvatarRegistration> {
1014 self.avatar_packs
1015 .values()
1016 .filter(|r| {
1017 self.current(&r.owner)
1018 .is_some_and(|entry| entry.state == OwnerState::Active)
1019 && self.check_scope(&r.owner, r.scope.as_ref(), true).is_ok()
1020 })
1021 .cloned()
1022 .collect()
1023 }
1024
1025 pub fn register_skill_root(
1026 &mut self,
1027 params: &RegisterParams,
1028 snapshots: Vec<codewhale_plugins::types::PluginSkillSnapshot>,
1029 host_generation: u64,
1030 ) -> Result<u64, String> {
1031 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
1032 use super::skills::*;
1033 params.check_spec()?;
1034 root_path(&params.spec.name)?;
1035 if params.kind != RegisterKind::SkillRoot || !params.spec.description.is_empty() {
1036 return Err("invalid skill root spec".to_string());
1037 }
1038 let entry = self
1039 .current(&params.owner)
1040 .ok_or_else(|| "stale or unknown skill owner".to_string())?;
1041 if entry.cohort.tier() != HostTier::Plugin {
1042 return Err("skill root owner has no reviewed bundle".to_string());
1043 }
1044 let content_hash = entry.content_hash.clone();
1045 let owned: Vec<_> = self
1046 .skill_roots
1047 .values()
1048 .filter(|root| root.owner == params.owner)
1049 .collect();
1050 let bytes = snapshots.iter().map(snapshot_bytes).sum::<usize>();
1051 if snapshots.is_empty()
1052 || owned
1053 .iter()
1054 .any(|root| root.path == params.spec.name && root.scope == params.scope)
1055 {
1056 return Err(
1057 "skill root is empty or already registered; dispose it before registering it again"
1058 .to_string(),
1059 );
1060 }
1061 let names: HashSet<_> = owned
1062 .iter()
1063 .filter(|root| root.scope == params.scope)
1064 .flat_map(|root| root.snapshots.iter().map(|skill| &skill.name))
1065 .collect();
1066 if snapshots.iter().any(|skill| names.contains(&skill.name)) {
1067 return Err("skill name is duplicated across this owner's roots".to_string());
1068 }
1069 if owned.len() >= MAX_ROOTS_PER_OWNER
1070 || self.skill_roots.len() >= MAX_ROOTS_PER_HOST
1071 || owned.iter().map(|root| root.snapshots.len()).sum::<usize>() + snapshots.len()
1072 > MAX_SKILLS_PER_OWNER
1073 || self
1074 .skill_roots
1075 .values()
1076 .map(|root| root.snapshots.len())
1077 .sum::<usize>()
1078 + snapshots.len()
1079 > MAX_SKILLS_PER_HOST
1080 || owned.iter().map(|root| root.bytes).sum::<usize>() + bytes > MAX_BYTES_PER_OWNER
1081 || self
1082 .skill_roots
1083 .values()
1084 .map(|root| root.bytes)
1085 .sum::<usize>()
1086 + bytes
1087 > MAX_BYTES_PER_HOST
1088 {
1089 return Err(
1090 "skill root owner or host count/instruction-byte limit reached".to_string(),
1091 );
1092 }
1093 self.next_handle += 1;
1094 let handle = self.next_handle;
1095 self.skill_roots.insert(
1096 handle,
1097 SkillRootRegistration {
1098 handle,
1099 owner: params.owner.clone(),
1100 scope: params.scope.clone(),
1101 host_generation,
1102 content_hash,
1103 path: params.spec.name.clone(),
1104 snapshots,
1105 bytes,
1106 },
1107 );
1108 super::command::bump_epoch();
1109 Ok(handle)
1110 }
1111
1112 pub fn live_skill_roots(&self) -> Vec<super::skills::SkillRootRegistration> {
1113 self.skill_roots
1114 .values()
1115 .filter(|root| {
1116 self.owners.get(&root.owner.plugin_id).is_some_and(|entry| {
1117 entry.owner == root.owner
1118 && entry.state == OwnerState::Active
1119 && self
1120 .check_scope(&root.owner, root.scope.as_ref(), true)
1121 .is_ok()
1122 })
1123 })
1124 .cloned()
1125 .collect()
1126 }
1127
1128 pub fn is_live_skill_root(
1129 &self,
1130 handle: u64,
1131 plugin_id: &str,
1132 generation: u64,
1133 host_generation: u64,
1134 content_hash: &str,
1135 state_generation: u64,
1136 ) -> bool {
1137 self.skill_roots.get(&handle).is_some_and(|root| {
1138 root.owner.plugin_id == plugin_id
1139 && root.owner.generation == generation
1140 && root.host_generation == host_generation
1141 && root.content_hash == content_hash
1142 && self
1143 .check_scope(&root.owner, root.scope.as_ref(), true)
1144 .is_ok()
1145 && self.owners.get(plugin_id).is_some_and(|entry| {
1146 entry.owner == root.owner
1147 && entry.state == OwnerState::Active
1148 && entry
1149 .authority
1150 .as_ref()
1151 .is_some_and(|authority| authority.state_generation == state_generation)
1152 })
1153 })
1154 }
1155
1156 pub fn register_prompt_section(&mut self, params: &RegisterParams) -> Result<u64, String> {
1157 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
1158 use super::prompt::{
1159 MAX_PROMPT_HOST_BYTES, MAX_PROMPT_OWNER_BYTES, MAX_PROMPT_SECTION_BYTES,
1160 MAX_PROMPT_SECTIONS_PER_HOST, MAX_PROMPT_SECTIONS_PER_OWNER,
1161 };
1162 params.check_spec()?;
1163 if !matches!(
1164 params.kind,
1165 RegisterKind::PromptSection | RegisterKind::PromptTemplate
1166 ) {
1167 return Err("prompt registration has an invalid kind".to_string());
1168 }
1169 let id = &params.spec.name;
1170 let text = &params.spec.description;
1171 if params.kind == RegisterKind::PromptTemplate {
1172 super::prompt::validate_prompt_template(text)?;
1173 }
1174 if !valid_command_name(id)
1175 || id.len() > 64
1176 || text.trim().is_empty()
1177 || text.len() > MAX_PROMPT_SECTION_BYTES
1178 || text
1179 .chars()
1180 .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))
1181 {
1182 return Err("prompt section needs a valid short id and bounded non-empty text without control characters".to_string());
1183 }
1184 let entry = self
1185 .current(&params.owner)
1186 .ok_or_else(|| "stale or unknown owner".to_string())?;
1187 let owned: Vec<_> = self
1188 .prompt_sections
1189 .values()
1190 .filter(|section| section.owner == params.owner)
1191 .collect();
1192 if owned
1193 .iter()
1194 .any(|section| &section.id == id && section.scope == params.scope)
1195 {
1196 return Err(
1197 "prompt section id is already registered; dispose it before registering it again"
1198 .to_string(),
1199 );
1200 }
1201 if owned.len() >= MAX_PROMPT_SECTIONS_PER_OWNER
1202 || self.prompt_sections.len() >= MAX_PROMPT_SECTIONS_PER_HOST
1203 || owned
1204 .iter()
1205 .map(|section| section.text.len())
1206 .sum::<usize>()
1207 + text.len()
1208 > MAX_PROMPT_OWNER_BYTES
1209 || self
1210 .prompt_sections
1211 .values()
1212 .map(|section| section.text.len())
1213 .sum::<usize>()
1214 + text.len()
1215 > MAX_PROMPT_HOST_BYTES
1216 {
1217 return Err("prompt section owner or host byte/registration limit reached".to_string());
1218 }
1219 let section = PromptSectionRegistration {
1220 handle: self.next_handle + 1,
1221 owner: params.owner.clone(),
1222 scope: params.scope.clone(),
1223 cohort: entry.cohort.clone(),
1224 plugin_name: entry.plugin_name.clone(),
1225 content_hash: entry.content_hash.clone(),
1226 id: id.clone(),
1227 text: text.clone(),
1228 interpolate: params.kind == RegisterKind::PromptTemplate,
1229 };
1230 self.next_handle += 1;
1231 self.prompt_sections.insert(section.handle, section);
1232 Ok(self.next_handle)
1233 }
1234
1235 fn register_shell_hook(&mut self, params: &RegisterParams) -> Result<u64, String> {
1236 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
1237 params.check_spec()?;
1238 let entry = self
1239 .current(&params.owner)
1240 .ok_or("shell hook owner is stale")?;
1241 if entry.cohort.tier() != HostTier::Plugin {
1242 return Err("shell hooks require reviewed Native code".into());
1243 }
1244 if params.spec.description.len() > 64 * 1024 || params.spec.name.len() > 256 {
1245 return Err("shell hook definition is oversized".into());
1246 }
1247 let mut spec: ShellSpec = serde_json::from_str(&params.spec.description)
1248 .map_err(|_| "invalid shell hook definition")?;
1249 let expected = match spec.point.as_str() {
1250 "SessionStart" => codewhale_config::hooks::HookEvent::SessionStart,
1251 "UserPromptSubmit" => codewhale_config::hooks::HookEvent::MessageSubmit,
1252 "PreToolUse" => codewhale_config::hooks::HookEvent::ToolCallBefore,
1253 "PostToolUse" => codewhale_config::hooks::HookEvent::ToolCallAfter,
1254 "Stop" => codewhale_config::hooks::HookEvent::TurnEnd,
1255 "SubagentStart" => codewhale_config::hooks::HookEvent::SubagentSpawn,
1256 "SubagentStop" => codewhale_config::hooks::HookEvent::SubagentComplete,
1257 _ => return Err("unsupported dialect hook point".into()),
1258 };
1259 if !matches!(spec.dialect.as_str(), "claude-code" | "codex")
1260 || spec.hook.event != expected
1261 || (spec.dialect == "codex"
1262 && matches!(spec.point.as_str(), "SubagentStart" | "SubagentStop"))
1263 {
1264 return Err("dialect hook point does not match its core event".into());
1265 }
1266 if spec.matcher.as_ref().is_some_and(|m| m.len() > 1024)
1267 || spec.hook.command.len() > 32 * 1024
1268 || spec.hook.timeout_secs == 0
1269 || spec.hook.timeout_secs > 86_400
1270 || spec.hook.background
1271 {
1272 return Err("shell hook command/matcher/timeout is not bounded".into());
1273 }
1274 if self.shell_hooks.len() >= 1024
1275 || self
1276 .shell_hooks
1277 .values()
1278 .filter(|h| h.owner == params.owner)
1279 .count()
1280 >= 128
1281 {
1282 return Err("shell hook registration cap reached".into());
1283 }
1284 let authority = entry
1285 .authority
1286 .clone()
1287 .ok_or("Native shell hook authority is absent")?;
1288 let content_hash = entry.content_hash.clone();
1289 let handle = self.next_handle + 1;
1290 spec.hook.native_shell = Some(codewhale_config::hooks::NativeShellHook {
1291 owner: params.owner.clone(),
1292 scope: params.scope.clone(),
1293 handle,
1294 dialect: spec.dialect,
1295 point: spec.point,
1296 matcher: spec.matcher,
1297 });
1298 spec.hook.plugin_authority = Some(authority);
1299 spec.hook.project_authority = None;
1300 spec.hook.continue_on_error = false;
1301 self.next_handle = handle;
1302 self.shell_hooks.insert(
1303 handle,
1304 ShellHookRegistration {
1305 handle,
1306 owner: params.owner.clone(),
1307 scope: params.scope.clone(),
1308 content_hash,
1309 hook: spec.hook,
1310 },
1311 );
1312 Ok(handle)
1313 }
1314 pub fn live_shell_hooks(&self) -> Vec<ShellHookRegistration> {
1315 self.shell_hooks
1316 .values()
1317 .filter(|h| {
1318 self.check_shell_hook(h.hook.native_shell.as_ref().expect("Native reference"))
1319 .is_ok()
1320 })
1321 .cloned()
1322 .collect()
1323 }
1324 pub fn check_shell_hook(
1325 &self,
1326 native: &codewhale_config::hooks::NativeShellHook,
1327 ) -> Result<(), String> {
1328 self.check_scope(&native.owner, native.scope.as_ref(), true)?;
1329 let owner = self
1330 .current(&native.owner)
1331 .filter(|o| o.state == OwnerState::Active)
1332 .ok_or("Native shell hook owner is not active")?;
1333 self.shell_hooks
1334 .get(&native.handle)
1335 .filter(|h| {
1336 h.owner == native.owner
1337 && h.scope == native.scope
1338 && h.content_hash == owner.content_hash
1339 })
1340 .ok_or("Native shell hook was withdrawn")?;
1341 Ok(())
1342 }
1343
1344 fn register_hook(&mut self, params: &RegisterParams) -> Result<u64, String> {
1345 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
1346 params.check_spec()?;
1347 if !matches!(
1348 params.spec.name.as_str(),
1349 "tools/pre-execute" | "tools/post-execute"
1350 ) {
1351 return Err(
1352 "only `tools/pre-execute` and `tools/post-execute` listeners are supported"
1353 .to_string(),
1354 );
1355 }
1356 let entry = self
1357 .current(&params.owner)
1358 .ok_or_else(|| "stale or unknown owner".to_string())?;
1359 if self.hooks.len() >= 1024
1360 || self
1361 .hooks
1362 .values()
1363 .filter(|hook| hook.owner == params.owner)
1364 .count()
1365 >= 128
1366 {
1367 return Err("plugin hook registration limit reached".to_string());
1368 }
1369 let registration = HookRegistration {
1370 handle: self.next_handle + 1,
1371 owner: params.owner.clone(),
1372 scope: params.scope.clone(),
1373 cohort: entry.cohort.clone(),
1374 plugin_name: entry.plugin_name.clone(),
1375 content_hash: entry.content_hash.clone(),
1376 event: params.spec.name.clone(),
1377 };
1378 self.next_handle += 1;
1379 self.hooks.insert(registration.handle, registration);
1380 Ok(self.next_handle)
1381 }
1382
1383 /// Admit or refuse one command registration. An extension command never
1384 /// shadows a built-in command or another plugin's command; a clash with
1385 /// a user, workspace or manifest (markdown) command is resolved when the
1386 /// user registry loads (the markdown command wins and the extension
1387 /// command is not loaded), because only that registry knows the workspace.
1388 pub fn register_command(&mut self, params: &RegisterParams) -> Result<u64, String> {
1389 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
1390 let entry = self
1391 .current(&params.owner)
1392 .ok_or_else(|| "stale or unknown owner".to_string())?;
1393 let plugin_name = entry.plugin_name.clone();
1394 let content_hash = entry.content_hash.clone();
1395 let cohort = entry.cohort.clone();
1396 let tier = cohort.tier();
1397 let spec = &params.spec;
1398 let name = spec.name.as_str();
1399 const COMMAND_HINT: &str = "a command name is lower case, starts with a letter, and uses only a-z, 0-9, `_` and `-` (at most 64 characters)";
1400 if !valid_command_name(name) {
1401 return Err(format!(
1402 "command name `{}` is invalid: {COMMAND_HINT}",
1403 codewhale_runtime::safe_label::SafeLabel::identifier(name)
1404 ));
1405 }
1406 // Fail closed: with no catalog installed there is nothing to check the
1407 // name against, so the registration is refused, not accepted unchecked.
1408 let Some(catalog) = crate::command_catalog::installed() else {
1409 return Err(format!(
1410 "command `/{name}` cannot be checked against the built-in commands: no built-in command catalog is installed, so plugin commands are refused"
1411 ));
1412 };
1413 let alias = if catalog.answers_to(name) {
1414 if tier != HostTier::Plugin {
1415 return Err(format!(
1416 "command `/{name}` collides with a built-in command"
1417 ));
1418 }
1419 let alias = namespaced_command(&plugin_name, &params.owner.plugin_id, name);
1420 if !valid_command_name(&alias) || catalog.answers_to(&alias) {
1421 return Err(format!(
1422 "command `/{name}` collides with a built-in command and its namespaced alias is unavailable"
1423 ));
1424 }
1425 Some(alias)
1426 } else {
1427 None
1428 };
1429 let published_name = alias.as_deref().unwrap_or(name);
1430 if spec.input_schema.is_some() {
1431 return Err(format!("command `/{name}` has no input schema"));
1432 }
1433 let description = spec.description.trim();
1434 if description.is_empty() {
1435 return Err(format!("command `/{name}` needs a description"));
1436 }
1437 if description.len() > MAX_COMMAND_DESCRIPTION_BYTES {
1438 return Err(format!(
1439 "command `/{name}` description exceeds {MAX_COMMAND_DESCRIPTION_BYTES} bytes"
1440 ));
1441 }
1442 let hint = spec.argument_hint.as_deref().map(str::trim);
1443 if hint.is_some_and(str::is_empty) {
1444 return Err(format!("command `/{name}` argument hint must not be empty"));
1445 }
1446 if hint.is_some_and(|hint| hint.len() > MAX_COMMAND_HINT_BYTES) {
1447 return Err(format!(
1448 "command `/{name}` argument hint exceeds {MAX_COMMAND_HINT_BYTES} bytes"
1449 ));
1450 }
1451 // The palette, `/help` and the composer print these verbatim.
1452 if description.chars().any(char::is_control)
1453 || hint.is_some_and(|h| h.chars().any(char::is_control))
1454 {
1455 return Err(format!(
1456 "command `/{name}` description and argument hint must be single-line text without control characters"
1457 ));
1458 }
1459 let mut replaced = None;
1460 if let Some(existing) = self
1461 .commands_by_name
1462 .get(&codewhale_plugins::composition_scope::name_key(
1463 &params.owner.plugin_id,
1464 published_name,
1465 params.scope.as_ref(),
1466 ))
1467 .and_then(|handle| self.commands.get(handle))
1468 {
1469 if existing.owner.plugin_id != params.owner.plugin_id {
1470 return Err(format!(
1471 "command `/{name}` is already registered by plugin `{}`; use a plugin-specific name",
1472 existing.plugin_name
1473 ));
1474 }
1475 if existing.declared_name != name {
1476 return Err(format!(
1477 "command `/{name}` would collide with another command's namespaced alias `/{published_name}`"
1478 ));
1479 }
1480 // Same owner re-registering a name: the new handle retires the old.
1481 replaced = Some(existing.handle);
1482 }
1483 let owned = self
1484 .commands
1485 .values()
1486 .filter(|command| command.owner.plugin_id == params.owner.plugin_id)
1487 .count()
1488 - usize::from(replaced.is_some());
1489 if owned >= MAX_COMMANDS_PER_OWNER {
1490 return Err(format!(
1491 "a plugin may register at most {MAX_COMMANDS_PER_OWNER} commands"
1492 ));
1493 }
1494 if self.commands.len() - usize::from(replaced.is_some()) >= MAX_COMMANDS_PER_HOST {
1495 return Err(format!(
1496 "the plugin host holds at most {MAX_COMMANDS_PER_HOST} commands"
1497 ));
1498 }
1499 if let Some(old) = replaced {
1500 self.commands.remove(&old);
1501 }
1502 self.next_handle += 1;
1503 let handle = self.next_handle;
1504 self.commands.insert(
1505 handle,
1506 CommandRegistration {
1507 handle,
1508 owner: params.owner.clone(),
1509 scope: params.scope.clone(),
1510 cohort,
1511 plugin_name,
1512 content_hash,
1513 name: published_name.to_string(),
1514 declared_name: name.to_string(),
1515 description: description.to_string(),
1516 argument_hint: hint.map(str::to_string),
1517 },
1518 );
1519 self.commands_by_name.insert(
1520 codewhale_plugins::composition_scope::name_key(
1521 &params.owner.plugin_id,
1522 published_name,
1523 params.scope.as_ref(),
1524 ),
1525 handle,
1526 );
1527 super::command::bump_epoch();
1528 Ok(handle)
1529 }
1530
1531 /// Admit or refuse one tool registration.
1532 pub fn register_tool(&mut self, params: &RegisterParams) -> Result<u64, String> {
1533 self.check_scope(&params.owner, params.scope.as_ref(), false)?;
1534 let entry = self
1535 .current(&params.owner)
1536 .ok_or_else(|| "stale or unknown owner".to_string())?;
1537 let plugin_name = entry.plugin_name.clone();
1538 let content_hash = entry.content_hash.clone();
1539 let cohort = entry.cohort.clone();
1540 let spec = &params.spec;
1541 let name = spec.name.as_str();
1542 if !valid_tool_name(name) {
1543 return Err(format!(
1544 "tool name `{}` must match ^[A-Za-z][A-Za-z0-9_-]{{0,63}}$; {NAME_HINT}",
1545 codewhale_runtime::safe_label::SafeLabel::identifier(name)
1546 ));
1547 }
1548 let plain_key = name.to_ascii_lowercase();
1549 let key = codewhale_plugins::composition_scope::name_key(
1550 &params.owner.plugin_id,
1551 &plain_key,
1552 params.scope.as_ref(),
1553 );
1554 if RESERVED_PREFIXES
1555 .iter()
1556 .any(|prefix| plain_key.starts_with(prefix))
1557 {
1558 return Err(format!(
1559 "tool name `{name}` uses a reserved prefix; {NAME_HINT}"
1560 ));
1561 }
1562 if self.native_names.contains(&plain_key)
1563 || (params.owner.plugin_id != "host:creator"
1564 && crate::conversation_modes::CREATOR_TOOL_NAMES
1565 .iter()
1566 .any(|reserved| reserved.eq_ignore_ascii_case(name)))
1567 {
1568 return Err(format!(
1569 "tool name `{name}` collides with a built-in tool; plugins never shadow core tools; {NAME_HINT}"
1570 ));
1571 }
1572 if let Some(reason) = core_special_case(name) {
1573 return Err(format!(
1574 "tool name `{name}` is reserved: {reason}; plugin tools never borrow a built-in's approval identity; {NAME_HINT}"
1575 ));
1576 }
1577 if spec.description.len() > MAX_DESCRIPTION_BYTES {
1578 return Err(format!(
1579 "tool `{name}` description exceeds {MAX_DESCRIPTION_BYTES} bytes"
1580 ));
1581 }
1582 let schema = Value::Object(
1583 spec.input_schema
1584 .clone()
1585 .ok_or_else(|| format!("tool `{name}` needs an input schema"))?,
1586 );
1587 let schema_bytes = serde_json::to_vec(&schema)
1588 .map(|bytes| bytes.len())
1589 .unwrap_or(usize::MAX);
1590 if schema_bytes > MAX_SCHEMA_BYTES {
1591 return Err(format!(
1592 "tool `{name}` input schema exceeds {MAX_SCHEMA_BYTES} bytes"
1593 ));
1594 }
1595 if schema.get("type").and_then(Value::as_str) != Some("object") {
1596 return Err(format!(
1597 "tool `{name}` input schema must be a JSON object schema (`\"type\": \"object\"`)"
1598 ));
1599 }
1600 let input_validator = InputValidator::compile(&schema).map_err(|reason| {
1601 format!("tool `{name}` input schema is not a valid JSON Schema: {reason}")
1602 })?;
1603 let mut replaced = None;
1604 if let Some(existing) = self
1605 .by_name
1606 .get(&key)
1607 .and_then(|handle| self.tools.get(handle))
1608 {
1609 if existing.owner.plugin_id != params.owner.plugin_id {
1610 return Err(format!(
1611 "tool name `{name}` is already registered by plugin `{}`; {NAME_HINT}",
1612 existing.plugin_name
1613 ));
1614 }
1615 // Same owner re-registering a name: the new handle retires the old.
1616 replaced = Some(existing.handle);
1617 }
1618 let owned = self
1619 .tools
1620 .values()
1621 .filter(|tool| tool.owner.plugin_id == params.owner.plugin_id)
1622 .count()
1623 - usize::from(replaced.is_some());
1624 if owned >= MAX_TOOLS_PER_OWNER {
1625 return Err(format!(
1626 "a plugin may register at most {MAX_TOOLS_PER_OWNER} tools"
1627 ));
1628 }
1629 if self.tools.len() - usize::from(replaced.is_some()) >= MAX_TOOLS_PER_HOST {
1630 return Err(format!(
1631 "the plugin host holds at most {MAX_TOOLS_PER_HOST} tools"
1632 ));
1633 }
1634 if let Some(old) = replaced {
1635 self.tools.remove(&old);
1636 }
1637 self.next_handle += 1;
1638 let handle = self.next_handle;
1639 self.tools.insert(
1640 handle,
1641 ToolRegistration {
1642 handle,
1643 owner: params.owner.clone(),
1644 scope: params.scope.clone(),
1645 cohort,
1646 plugin_name,
1647 content_hash,
1648 name: name.to_string(),
1649 description: spec.description.clone(),
1650 input_schema: schema,
1651 input_validator,
1652 },
1653 );
1654 self.by_name.insert(key, handle);
1655 Ok(handle)
1656 }
1657
1658 /// Undo exactly one registration. Idempotent; a stale or foreign handle is a no-op.
1659 pub fn unregister(&mut self, owner: &OwnerRef, handle: u64) {
1660 if self
1661 .mcp_servers
1662 .get(&handle)
1663 .is_some_and(|r| r.owner == *owner)
1664 {
1665 if let Some(r) = self.mcp_servers.remove(&handle) {
1666 r.cancel.cancel();
1667 }
1668 super::native_mcp::changed();
1669 return;
1670 }
1671
1672 if self
1673 .shell_hooks
1674 .get(&handle)
1675 .is_some_and(|h| h.owner == *owner)
1676 {
1677 self.shell_hooks.remove(&handle);
1678 return;
1679 }
1680 if self
1681 .avatar_packs
1682 .get(&handle)
1683 .is_some_and(|r| r.owner == *owner)
1684 {
1685 self.avatar_packs.remove(&handle);
1686 return;
1687 }
1688 if self
1689 .skill_roots
1690 .get(&handle)
1691 .is_some_and(|root| root.owner == *owner)
1692 {
1693 self.skill_roots.remove(&handle);
1694 super::command::bump_epoch();
1695 return;
1696 }
1697 if self
1698 .prompt_sections
1699 .get(&handle)
1700 .is_some_and(|section| section.owner == *owner)
1701 {
1702 self.prompt_sections.remove(&handle);
1703 return;
1704 }
1705 if self
1706 .hooks
1707 .get(&handle)
1708 .is_some_and(|hook| hook.owner == *owner)
1709 {
1710 self.hooks.remove(&handle);
1711 return;
1712 }
1713 if self
1714 .commands
1715 .get(&handle)
1716 .is_some_and(|command| command.owner == *owner)
1717 && let Some(command) = self.commands.remove(&handle)
1718 {
1719 if self
1720 .commands_by_name
1721 .get(&codewhale_plugins::composition_scope::name_key(
1722 &command.owner.plugin_id,
1723 &command.name,
1724 command.scope.as_ref(),
1725 ))
1726 == Some(&handle)
1727 {
1728 self.commands_by_name
1729 .remove(&codewhale_plugins::composition_scope::name_key(
1730 &command.owner.plugin_id,
1731 &command.name,
1732 command.scope.as_ref(),
1733 ));
1734 }
1735 super::command::bump_epoch();
1736 return;
1737 }
1738 let owned = self
1739 .tools
1740 .get(&handle)
1741 .is_some_and(|tool| tool.owner == *owner);
1742 if !owned {
1743 return;
1744 }
1745 if let Some(tool) = self.tools.remove(&handle) {
1746 let key = codewhale_plugins::composition_scope::name_key(
1747 &tool.owner.plugin_id,
1748 &tool.name.to_ascii_lowercase(),
1749 tool.scope.as_ref(),
1750 );
1751 if self.by_name.get(&key) == Some(&handle) {
1752 self.by_name.remove(&key);
1753 }
1754 }
1755 }
1756
1757 fn remove_commands_of(&mut self, plugin_id: &str) {
1758 // Called by `remove_registrations_of`, so every revocation path that
1759 // drops an owner's tools drops its commands too.
1760 let handles: Vec<u64> = self
1761 .commands
1762 .values()
1763 .filter(|command| command.owner.plugin_id == plugin_id)
1764 .map(|command| command.handle)
1765 .collect();
1766 for handle in handles {
1767 if let Some(command) = self.commands.remove(&handle)
1768 && self
1769 .commands_by_name
1770 .get(&codewhale_plugins::composition_scope::name_key(
1771 &command.owner.plugin_id,
1772 &command.name,
1773 command.scope.as_ref(),
1774 ))
1775 == Some(&handle)
1776 {
1777 self.commands_by_name
1778 .remove(&codewhale_plugins::composition_scope::name_key(
1779 &command.owner.plugin_id,
1780 &command.name,
1781 command.scope.as_ref(),
1782 ));
1783 }
1784 }
1785 super::command::bump_epoch();
1786 }
1787
1788 fn remove_registrations_of(&mut self, plugin_id: &str) -> Vec<u64> {
1789 let count = self.mcp_servers.len();
1790 self.mcp_servers.retain(|_, r| {
1791 if r.owner.plugin_id == plugin_id {
1792 r.cancel.cancel();
1793 false
1794 } else {
1795 true
1796 }
1797 });
1798 if count != self.mcp_servers.len() {
1799 super::native_mcp::changed()
1800 }
1801
1802 self.shell_hooks
1803 .retain(|_, h| h.owner.plugin_id != plugin_id);
1804 self.skill_roots
1805 .retain(|_, root| root.owner.plugin_id != plugin_id);
1806 self.avatar_packs
1807 .retain(|_, r| r.owner.plugin_id != plugin_id);
1808 self.prompt_sections
1809 .retain(|_, section| section.owner.plugin_id != plugin_id);
1810 self.hooks
1811 .retain(|_, hook| hook.owner.plugin_id != plugin_id);
1812 self.remove_commands_of(plugin_id);
1813 let handles: Vec<u64> = self
1814 .tools
1815 .values()
1816 .filter(|tool| tool.owner.plugin_id == plugin_id)
1817 .map(|tool| tool.handle)
1818 .collect();
1819 for handle in &handles {
1820 if let Some(tool) = self.tools.remove(handle) {
1821 let key = codewhale_plugins::composition_scope::name_key(
1822 &tool.owner.plugin_id,
1823 &tool.name.to_ascii_lowercase(),
1824 tool.scope.as_ref(),
1825 );
1826 if self.by_name.get(&key) == Some(handle) {
1827 self.by_name.remove(&key);
1828 }
1829 }
1830 }
1831 handles
1832 }
1833
1834 /// Revoke an owner synchronously. Returns the owner that was live, if any.
1835 pub fn revoke_owner(&mut self, plugin_id: &str) -> Option<OwnerRef> {
1836 self.remove_registrations_of(plugin_id);
1837 let entry = self.owners.get_mut(plugin_id)?;
1838 let was_live = entry.live();
1839 if was_live {
1840 self.departed_cohorts.insert(entry.cohort.clone());
1841 }
1842 entry.state = OwnerState::Revoked;
1843 was_live.then(|| entry.owner.clone())
1844 }
1845
1846 /// Forget an owner entirely (after revocation, when its plugin is gone).
1847 pub fn forget_owner(&mut self, plugin_id: &str) {
1848 self.remove_registrations_of(plugin_id);
1849 if let Some(entry) = self.owners.remove(plugin_id)
1850 && entry.live()
1851 {
1852 self.departed_cohorts.insert(entry.cohort.clone());
1853 }
1854 }
1855
1856 /// Forget owners that are not live (failed, faulted, revoked) so a new
1857 /// explicit plugin mutation retries them.
1858 pub fn forget_inactive(&mut self) {
1859 for owner in self.owners.values_mut() {
1860 owner
1861 .scopes
1862 .retain(|_, state| matches!(state, OwnerState::Activating | OwnerState::Active));
1863 }
1864 self.owners
1865 .retain(|_, entry| matches!(entry.state, OwnerState::Activating | OwnerState::Active));
1866 }
1867
1868 pub fn forget_inactive_for_cohort(&mut self, cohort: &HostCohort) {
1869 for owner in self.owners.values_mut() {
1870 if &owner.cohort == cohort {
1871 owner.scopes.retain(|_, state| {
1872 matches!(state, OwnerState::Activating | OwnerState::Active)
1873 });
1874 }
1875 }
1876 self.owners.retain(|_, entry| {
1877 &entry.cohort != cohort
1878 || matches!(entry.state, OwnerState::Activating | OwnerState::Active)
1879 });
1880 }
1881
1882 fn clear_cohort_registrations(&mut self, cohort: &HostCohort) {
1883 let count = self.mcp_servers.len();
1884 self.mcp_servers.retain(|_, r| {
1885 if self
1886 .owners
1887 .get(&r.owner.plugin_id)
1888 .is_some_and(|o| o.cohort == *cohort)
1889 {
1890 r.cancel.cancel();
1891 false
1892 } else {
1893 true
1894 }
1895 });
1896 if count != self.mcp_servers.len() {
1897 super::native_mcp::changed()
1898 }
1899
1900 self.skill_roots.retain(|_, root| {
1901 !self
1902 .owners
1903 .get(&root.owner.plugin_id)
1904 .is_some_and(|o| o.cohort == *cohort)
1905 });
1906 self.avatar_packs.retain(|_, r| {
1907 !self
1908 .owners
1909 .get(&r.owner.plugin_id)
1910 .is_some_and(|o| o.cohort == *cohort)
1911 });
1912 self.prompt_sections
1913 .retain(|_, section| section.cohort != *cohort);
1914 self.shell_hooks.retain(|_, h| {
1915 !self
1916 .owners
1917 .get(&h.owner.plugin_id)
1918 .is_some_and(|o| o.cohort == *cohort)
1919 });
1920 self.hooks.retain(|_, hook| hook.cohort != *cohort);
1921 self.tools.retain(|_, tool| tool.cohort != *cohort);
1922 let tools = &self.tools;
1923 self.by_name.retain(|_, handle| tools.contains_key(handle));
1924 self.commands.retain(|_, command| command.cohort != *cohort);
1925 let commands = &self.commands;
1926 self.commands_by_name
1927 .retain(|_, handle| commands.contains_key(handle));
1928 super::command::bump_epoch();
1929 }
1930
1931 pub fn host_exited(&mut self, cohort: impl Into<HostCohort>, reason: &str) -> bool {
1932 let cohort = cohort.into();
1933 let had_live_owners = self
1934 .owners
1935 .values()
1936 .any(|entry| entry.cohort == cohort && entry.live());
1937 self.clear_cohort_registrations(&cohort);
1938 self.host_process_started(&cohort);
1939 let activating: Vec<_> = self
1940 .owners
1941 .values()
1942 .filter(|entry| entry.cohort == cohort && entry.state == OwnerState::Activating)
1943 .map(|entry| entry.owner.plugin_id.clone())
1944 .collect();
1945 if let [plugin] = activating.as_slice() {
1946 self.owners.get_mut(plugin).expect("activating owner").state =
1947 OwnerState::Failed(format!("host crashed during activation: {reason}"));
1948 }
1949 self.owners.retain(|_, entry| {
1950 entry.cohort != cohort
1951 || matches!(entry.state, OwnerState::Failed(_) | OwnerState::Faulted(_))
1952 });
1953 had_live_owners
1954 }
1955
1956 pub fn revoke_cohort(&mut self, cohort: &HostCohort, reason: &str) {
1957 self.clear_cohort_registrations(cohort);
1958 for entry in self.owners.values_mut() {
1959 if &entry.cohort == cohort
1960 && matches!(entry.state, OwnerState::Activating | OwnerState::Active)
1961 {
1962 if entry.cohort.tier() == HostTier::Plugin {
1963 self.departed_cohorts.insert(entry.cohort.clone());
1964 }
1965 entry.state = OwnerState::Failed(reason.to_string());
1966 }
1967 }
1968 }
1969
1970 /// Planned test shutdown drops `tier`'s tools and fails its remaining live owners.
1971 #[cfg(any(test, feature = "test-support"))]
1972 pub fn revoke_all(&mut self, cohort: impl Into<HostCohort>, reason: &str) {
1973 let cohort = cohort.into();
1974 self.clear_cohort_registrations(&cohort);
1975 for entry in self.owners.values_mut() {
1976 if entry.cohort == cohort
1977 && matches!(entry.state, OwnerState::Activating | OwnerState::Active)
1978 {
1979 if entry.cohort.tier() == HostTier::Plugin {
1980 self.departed_cohorts.insert(entry.cohort.clone());
1981 }
1982 entry.state = OwnerState::Failed(reason.to_string());
1983 }
1984 }
1985 }
1986
1987 /// Tools of active owners, in handle order.
1988 #[must_use]
1989 pub fn live_tools(&self) -> Vec<ToolRegistration> {
1990 self.tools
1991 .values()
1992 .filter(|tool| {
1993 self.owners.get(&tool.owner.plugin_id).is_some_and(|entry| {
1994 entry.owner == tool.owner
1995 && entry.state == OwnerState::Active
1996 && self
1997 .check_scope(&tool.owner, tool.scope.as_ref(), true)
1998 .is_ok()
1999 })
2000 })
2001 .cloned()
2002 .collect()
2003 }
2004
2005 /// Hooks of active owners, in registration order. Multiple listeners for
2006 /// the same event coexist; withdrawing one never removes another.
2007 pub fn live_hooks(&self) -> Vec<HookRegistration> {
2008 self.hooks
2009 .values()
2010 .filter(|hook| self.is_live_hook(hook.handle, &hook.owner))
2011 .cloned()
2012 .collect()
2013 }
2014
2015 pub fn live_prompt_sections(&self) -> Vec<PromptSectionRegistration> {
2016 let mut sections: Vec<_> = self
2017 .prompt_sections
2018 .values()
2019 .filter(|section| self.is_live_prompt_section(section.handle, &section.owner))
2020 .cloned()
2021 .collect();
2022 sections.sort_by(|a, b| (&a.owner.plugin_id, &a.id).cmp(&(&b.owner.plugin_id, &b.id)));
2023 sections
2024 }
2025
2026 pub fn is_live_prompt_section(&self, handle: u64, owner: &OwnerRef) -> bool {
2027 self.prompt_sections.get(&handle).is_some_and(|section| {
2028 section.owner == *owner
2029 && self
2030 .check_scope(owner, section.scope.as_ref(), true)
2031 .is_ok()
2032 }) && self
2033 .owners
2034 .get(&owner.plugin_id)
2035 .is_some_and(|entry| entry.owner == *owner && entry.state == OwnerState::Active)
2036 }
2037
2038 pub fn is_live_hook(&self, handle: u64, owner: &OwnerRef) -> bool {
2039 self.hooks.get(&handle).is_some_and(|hook| {
2040 hook.owner == *owner && self.check_scope(owner, hook.scope.as_ref(), true).is_ok()
2041 }) && self
2042 .owners
2043 .get(&owner.plugin_id)
2044 .is_some_and(|entry| entry.owner == *owner && entry.state == OwnerState::Active)
2045 }
2046
2047 /// Commands of active owners, in handle order.
2048 #[must_use]
2049 pub fn live_commands(&self) -> Vec<CommandRegistration> {
2050 self.commands
2051 .values()
2052 .filter(|command| {
2053 self.owners
2054 .get(&command.owner.plugin_id)
2055 .is_some_and(|entry| {
2056 entry.owner == command.owner
2057 && entry.state == OwnerState::Active
2058 && self
2059 .check_scope(&command.owner, command.scope.as_ref(), true)
2060 .is_ok()
2061 })
2062 })
2063 .cloned()
2064 .collect()
2065 }
2066
2067 /// The command behind `handle`, if it is still admitted for exactly this
2068 /// owner generation of `plugin_id`. A stale reference finds nothing.
2069 #[must_use]
2070 pub fn live_command(
2071 &self,
2072 handle: u64,
2073 plugin_id: &str,
2074 generation: u64,
2075 ) -> Option<CommandRegistration> {
2076 let command = self.commands.get(&handle)?;
2077 (command.owner.plugin_id == plugin_id
2078 && command.owner.generation == generation
2079 && self.owners.get(plugin_id).is_some_and(|entry| {
2080 entry.owner == command.owner
2081 && entry.state == OwnerState::Active
2082 && self
2083 .check_scope(&command.owner, command.scope.as_ref(), true)
2084 .is_ok()
2085 }))
2086 .then(|| command.clone())
2087 }
2088
2089 /// Whether `handle` is still admitted for exactly this owner generation.
2090 #[must_use]
2091 pub fn is_live(&self, handle: u64, owner: &OwnerRef) -> bool {
2092 self.tools.get(&handle).is_some_and(|tool| {
2093 tool.owner == *owner && self.check_scope(owner, tool.scope.as_ref(), true).is_ok()
2094 }) && self
2095 .owners
2096 .get(&owner.plugin_id)
2097 .is_some_and(|entry| entry.owner == *owner && entry.state == OwnerState::Active)
2098 }
2099
2100 #[must_use]
2101 pub fn other_active_owners(&self, plugin_id: &str) -> usize {
2102 let Some(entry) = self.owners.get(plugin_id) else {
2103 return 0;
2104 };
2105 let cohort = &entry.cohort;
2106 self.owners
2107 .values()
2108 .filter(|other| {
2109 other.cohort == *cohort
2110 && other.owner.plugin_id != plugin_id
2111 && other.state == OwnerState::Active
2112 })
2113 .count()
2114 }
2115
2116 /// The plugin authority of the exact current owner: `None` for a stale
2117 /// owner and for a built-in module, which has none.
2118 #[must_use]
2119 pub fn authority_for(&self, owner: &OwnerRef) -> Option<PluginAuthority> {
2120 self.current(owner)
2121 .and_then(|entry| entry.authority.clone())
2122 }
2123
2124 /// The tier of the exact current owner.
2125 #[must_use]
2126 pub fn tier_of(&self, owner: &OwnerRef) -> Option<HostTier> {
2127 self.current(owner).map(|entry| entry.cohort.tier())
2128 }
2129
2130 #[must_use]
2131 pub fn cohort_of(&self, owner: &OwnerRef) -> Option<HostCohort> {
2132 self.current(owner).map(|entry| entry.cohort.clone())
2133 }
2134 }
2135
2136 #[cfg(test)]
2137 mod shell_hook_tests {
2138 use super::super::protocol::RegisterSpecWire;
2139 use super::*;
2140 fn spec(owner: &OwnerRef, scope: Option<EntryRef>) -> RegisterParams {
2141 RegisterParams {owner:owner.clone(),scope,kind:RegisterKind::ShellHook,spec:RegisterSpecWire {name:"claude:PreToolUse:1".into(),description:serde_json::json!({"dialect":"claude-code","point":"PreToolUse","matcher":"write","hook":{"event":"tool_call_before","command":"true","timeout_secs":3,"background":false,"continue_on_error":false}}).to_string(),input_schema:None,argument_hint:None}}
2142 }
2143 fn new_owner(registry: &mut OwnerRegistry, id: &str) -> OwnerRef {
2144 registry
2145 .begin_owner(
2146 HostCohort::reviewed(),
2147 id,
2148 id,
2149 Some(super::super::test_support::fake_authority(id)),
2150 "build",
2151 )
2152 .unwrap()
2153 }
2154 #[test]
2155 fn native_shell_hooks_withdraw_exact_scope_and_host_exit_releases_budget() {
2156 let mut registry = OwnerRegistry::new();
2157 let owner = new_owner(&mut registry, "hook-a");
2158 let scope = EntryRef {
2159 path: "/reviewed/a.mjs".into(),
2160 sha256: "a".repeat(64),
2161 };
2162 registry.begin_scope(&owner, scope.clone()).unwrap();
2163 let handle = registry
2164 .register(&spec(&owner, Some(scope.clone())))
2165 .unwrap();
2166 assert!(registry.live_shell_hooks().is_empty());
2167 registry.mark_scope_active(&owner, &scope);
2168 registry.mark_active(&owner);
2169 let native = registry.live_shell_hooks()[0]
2170 .hook
2171 .native_shell
2172 .clone()
2173 .unwrap();
2174 assert_eq!(native.handle, handle);
2175 registry.host_exited(HostCohort::Builtin, "builtin test exit");
2176 assert!(registry.check_shell_hook(&native).is_ok());
2177 registry.revoke_scope(&owner, &scope);
2178 assert!(registry.check_shell_hook(&native).is_err());
2179 assert!(registry.shell_hooks.is_empty());
2180 let other = new_owner(&mut registry, "hook-b");
2181 let admitted = registry.register(&spec(&other, None)).unwrap();
2182 registry.mark_active(&other);
2183 assert_eq!(registry.live_shell_hooks()[0].handle, admitted);
2184 registry.host_exited(HostCohort::reviewed(), "test crash");
2185 assert!(registry.shell_hooks.is_empty());
2186 }
2187 #[test]
2188 fn native_shell_registration_refuses_wrong_event_oversized_and_foreign_withdrawal() {
2189 let mut registry = OwnerRegistry::new();
2190 let a = new_owner(&mut registry, "a");
2191 let b = new_owner(&mut registry, "b");
2192 let mut wrong = spec(&a, None);
2193 wrong.spec.description = wrong
2194 .spec
2195 .description
2196 .replace("tool_call_before", "shell_env");
2197 assert!(registry.register(&wrong).is_err());
2198 let mut huge = spec(&a, None);
2199 huge.spec.description = "x".repeat(65537);
2200 assert!(registry.register(&huge).is_err());
2201 let handle = registry.register(&spec(&a, None)).unwrap();
2202 registry.mark_active(&a);
2203 registry.unregister(&b, handle);
2204 assert_eq!(registry.live_shell_hooks().len(), 1);
2205 registry.unregister(&a, handle);
2206 assert!(registry.live_shell_hooks().is_empty());
2207 }
2208 }
2209
2209 lines RUST