返回 CodeWhale
mod.rs
1 //! Experimental TypeScript extension host — phase 1 (`[features] extension_host`).
2 //!
3 //! Codewhale's Rust core stays closed and authoritative: one turn loop, one
4 //! event authority, one store, one prompt authority, one approval gate. The
5 //! extension host (`crates/engine/extension-host`, a Bun or Node process running
6 //! the embedded bundle) is the only extensible surface, and in phase 1 it can do
7 //! exactly one thing: contribute tools, which become ordinary registry
8 //! `ToolSpec`s ([`tool::HostToolSpec`]) behind the existing gate.
9 //!
10 //! Lifecycle: a reviewed, enabled plugin with a `native` entry (activation
11 //! policy v4, selected by the flag) makes [`ExtensionHostManager::reconcile_in_background`]
12 //! spawn the host in the background — never on the first-prompt path — and
13 //! activate one owner per plugin. Tools join the per-turn registry at the next
14 //! rebuild, or before the next model request when the creator `plugin_manager`
15 //! changes a plugin mid-turn. Disabling, revoking or updating the plugin revokes its
16 //! registrations synchronously before the host is asked to tear down.
17 //!
18 //! `core/call` ([`core_call`], tickets in [`ticket`]): an extension tool that
19 //! the model called directly may ask the core to run a core tool for it,
20 //! through the same gate as the model's own calls. The host decides nothing:
21 //! planning, approval and the card's text are Rust's, MCP and anything that
22 //! changes the session's authority are refused, and shell and network calls
23 //! force a prompt.
24 //!
25 //! Engines: the manager and its one host are process-wide, but each engine
26 //! holds its own [`HostAttachment`] carrying the plugin snapshot of its
27 //! workspace. Reconcile activates the union of what every attached snapshot
28 //! desires and revokes only owners no attachment desires. Each snapshot is
29 //! re-verified against persisted plugin state on every reconcile, so a
30 //! disable or revoke made through any registry revokes the plugin for every
31 //! engine. An engine installs only the tools of owners its own snapshot
32 //! desires, so a workspace never sees another workspace's project plugins.
33 //! Dropping an attachment detaches without revoking; the next reconcile
34 //! revokes whatever no remaining attachment desires. Engines without a
35 //! plugin snapshot of their own (isolated chats, the empty fallback) never
36 //! attach.
37 //!
38 //! Commands: a plugin may also contribute slash commands ([`command`]). They
39 //! are owned registrations like tools, loaded into the user command registry
40 //! at the lowest precedence, and run by `command/run` only when the user
41 //! invokes them.
42 //!
43 //! Plugin context: a plugin's `apply(ctx, config)` receives the settings from
44 //! `[plugins."<name>".config]` ([`plugin_config`]), and its tools and commands
45 //! are told, per call, the workspace the call comes from and the plugin's own
46 //! data directory. A plugin with several `native` entries activates them in
47 //! order under one owner.
48 //!
49 //! Known limitations (by design — see the design doc §8 and its "As built"
50 //! sections):
51 //! * Tools, slash commands, programmable pre-execute admission hooks, additive
52 //! prompt sections and owner-local storage. Skills and MCP are not host services yet.
53 //! The one thing the host may ask the core to do is a `core/call` from a tool
54 //! under the turn's gate; commands, timers and activation code ask for
55 //! nothing.
56 //! * Heartbeat and bounded automatic restart preserve the shared crash budget
57 //! across engine creation and replay. Dead-host calls fail with a typed
58 //! error and are never replayed. Three crashes in five minutes require an
59 //! explicit plugin change/reload to retry. Two dirty teardowns within ten
60 //! minutes retire the process once non-heartbeat calls are idle, without
61 //! resetting or consuming the unexpected-crash budget.
62 //! * Every awaited core→host request is bounded by its method's deadline
63 //! (`protocol::CoreRequest::deadline`) and then cancelled with `$/cancel`
64 //! (`supervisor::HostProcess::call`). Cancellation is a request: a plugin
65 //! that ignores its abort signal keeps running in the host until the host
66 //! is torn down, though the core has already failed the call.
67 //! * One host per engine process and trust tier ([`tier`]): the plugin tier
68 //! hosts reviewed third-party plugins, the builtin tier (tier 0) is for
69 //! Codewhale's own host code and starts only for a row of
70 //! [`tier::BUILTIN_MODULES`]. The MCP SDK backend starts its pinned module
71 //! only when explicitly selected; plugin attachment does not start it.
72 //! Under its OS sandbox
73 //! (Seatbelt on macOS; bubblewrap on Linux when a launch-time probe shows it
74 //! works) the host has no direct network, and cannot read the Codewhale
75 //! home (except the bundle, its data dir and plugin code), the Codex and
76 //! DSH credential homes, or the default credential stores
77 //! (`supervisor::plan_launch`, whose module docs list what bubblewrap does
78 //! not cover). Other files the user can read — including project `.env`
79 //! files — stay readable, and Mach services are not restricted. On Windows,
80 //! and on Linux where bwrap is missing or cannot start, Native launch is
81 //! refused. The pinned Builtin exception is explicitly diagnosed and still
82 //! ticket-bound. The flag remains Experimental.
83 //! * The runtime (`[extension_host] runtime`) defaults to Node. Bun is an
84 //! opt-in (`bun`, or `auto`, which prefers a Bun >= 1.4.0 and uses Node
85 //! when none is found) and is qualified on macOS only. The runtime is
86 //! pinned once a host on it completes the handshake; restarts reuse it
87 //! without probing it again, and the handshake refuses a host reporting a
88 //! different runtime or version. Under `auto`, a Bun that fails to launch or
89 //! handshake before anything is pinned is reported once and Node is used
90 //! for the rest of the session; an explicit `bun`/`node` never falls back.
91 //! The 1 GiB memory cap is applied through `RLIMIT_DATA` on Linux, the Job
92 //! Object on Windows and, for a Bun host on macOS, a jetsam limit the host
93 //! applies to itself; a macOS Node host is checked at each heartbeat
94 //! instead. The Rust host tests have not run a Bun host on Linux or
95 //! Windows (`supervisor` module docs say what was measured where).
96 //! * In-process native code is taken away from plugins by the host
97 //! (`extension-host/src/runtime.ts`), for the entry points found so far; a
98 //! native-code entry point a newer runtime adds is not covered until it is
99 //! added there. A process a plugin starts is outside that policy and runs
100 //! under the same verified OS sandbox required for Native admission.
101 //! * The owner token is a bug/staleness guard, not a boundary between
102 //! plugins that share the process: one plugin can alter another's
103 //! behaviour, which the approval card discloses.
104 //! * Extension tool names that any name-keyed approval table special-cases
105 //! are refused (`registry::core_special_case`), so an extension tool never
106 //! shares an approval key, summary or category with a built-in.
107 //! * The host's process tree (Unix process group / Windows Job Object,
108 //! shared with hooks via `codewhale_runtime::process_tree`) is killed as a whole. On
109 //! Windows the host is assigned to its job just after spawn, not created
110 //! suspended as hooks are. On Unix a plugin child that calls `setsid` leaves
111 //! the group and is not killed with it. When the core goes away, the host
112 //! kills its own group at stdin EOF, and a watchdog thread does the same
113 //! when its parent process changes, even if a plugin blocks the event loop.
114 //! * A running engine's snapshot is replaced only by its own workspace
115 //! switch or by [`plugins_changed`] for the same workspace. A plugin newly
116 //! enabled through another workspace's registry reaches an engine at its
117 //! next snapshot, not at once; disables and revokes always reach it at the
118 //! next reconcile, through the persisted-state check.
119 //! * The host re-hashes each `native` entry file before importing it; other
120 //! files in the staged snapshot are covered by Rust's per-call receipt
121 //! check, not re-hashed by the host.
122
123 pub mod command;
124 pub mod composition_review;
125 pub mod core_call;
126 pub(crate) mod creator_policy;
127 mod dsh_attachments;
128 pub mod dsh_broker;
129 mod dsh_catalog;
130 mod dsh_llm;
131 pub(crate) mod dsh_network;
132 mod dsh_plugins;
133 mod dsh_remote;
134 pub(crate) use dsh_remote::end_remote_session;
135 pub use dsh_remote::{RemoteClient, RemoteDenial, RemotePairing, RemoteSecret, RemoteState};
136 pub mod dsh_settings;
137 pub(crate) mod dsh_terminal;
138 pub mod dsh_webserver;
139 mod dsh_workspace;
140 pub use dsh_webserver::{
141 MAX_PLUGIN_ROUTE_REQUEST_BYTES, MAX_PLUGIN_ROUTE_RESPONSE_BYTES,
142 PLUGIN_ROUTE_DISPATCH_DEADLINE, PluginRouteError, PluginRouteRequest, PluginRouteResponse,
143 dispatch_plugin_route,
144 };
145 pub mod execution;
146 pub use dsh_network::forget_plugin_credentials;
147 pub use execution::StockOperation;
148 pub mod avatars;
149 mod hooks;
150 mod host_port;
151 pub mod mcp;
152 pub mod native_mcp;
153 pub mod plugin_config;
154 pub mod prompt;
155 pub mod protocol;
156 pub mod registry;
157 pub mod skills;
158 pub mod supervisor;
159 pub mod ticket;
160 pub mod tier;
161 pub mod tool;
162 #[cfg(windows)]
163 mod windows;
164
165 #[cfg(test)]
166 mod cohort_tests;
167 #[cfg(test)]
168 mod core_call_tests;
169 #[cfg(test)]
170 mod dsh_grant_tests;
171 #[cfg(any(test, feature = "test-support"))]
172 pub mod test_support;
173 #[cfg(test)]
174 mod tests;
175
176 use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
177 use std::fmt;
178 use std::path::{Path, PathBuf};
179 use std::sync::atomic::{AtomicU64, Ordering};
180 use std::sync::{Arc, Mutex, OnceLock, Weak};
181 use std::time::{Duration, Instant};
182
183 use async_trait::async_trait;
184 use sha2::{Digest, Sha256};
185 use tokio_util::sync::CancellationToken;
186
187 use self::protocol::{
188 ActivateParams, ActivateResult, CoreRequest, DeactivateParams, DeactivateResult, RegisterKind,
189 RegisterResult,
190 };
191 use self::registry::{CommandRegistration, OwnerRegistry, OwnerState, ToolRegistration};
192 use self::supervisor::{HostEvents, HostProcess, HostRequestContext};
193 use self::tier::{BuiltinModule, HostCohort, HostTier, PluginCohort};
194 use codewhale_config::PluginAuthority;
195 use codewhale_config::{EntryRef, OwnerRef};
196 use codewhale_plugins::activation::{self, PluginActivationCapability};
197 use codewhale_plugins::{PluginRegistry, types::LoadedPlugin};
198
199 /// The host bundle, embedded so every distribution channel carries it.
200 const BUNDLE: &[u8] = include_bytes!("../../extension-host/dist/codewhale-extension-host.mjs");
201 const BUNDLE_FILE_NAME: &str = "codewhale-extension-host.mjs";
202 /// The licence notices of the third-party code inside [`BUNDLE`], generated by
203 /// the host build from the bundler's metafile (`extension-host/build.mjs`). The
204 /// bundle's banner promises "LICENSES.txt next to this file", so every
205 /// materialised copy of the bundle carries one.
206 const NOTICES: &[u8] = include_bytes!("../../extension-host/dist/LICENSES.txt");
207 const NOTICES_FILE_NAME: &str = "LICENSES.txt";
208 const MAX_DIAGNOSTICS: usize = 64;
209 const MAX_DIAGNOSTIC_BYTES: usize = 2048;
210 const DIRTY_RESTART_REASON: &str = "planned restart after repeated dirty teardowns";
211 const NO_DESIRED_OWNERS_REASON: &str = "no desired owners remain";
212
213 struct Diagnostic {
214 plugin_id: Option<String>,
215 message: String,
216 }
217
218 fn bounded_diagnostic(mut message: String) -> String {
219 if message.len() > MAX_DIAGNOSTIC_BYTES {
220 let mut end = MAX_DIAGNOSTIC_BYTES;
221 while !message.is_char_boundary(end) {
222 end -= 1;
223 }
224 message.truncate(end);
225 message.push('…');
226 }
227 message
228 }
229
230 fn hex(bytes: impl AsRef<[u8]>) -> String {
231 bytes
232 .as_ref()
233 .iter()
234 .map(|byte| format!("{byte:02x}"))
235 .collect()
236 }
237
238 /// SHA-256 of the embedded bundle.
239 #[must_use]
240 pub fn bundle_sha256() -> &'static str {
241 static DIGEST: OnceLock<String> = OnceLock::new();
242 DIGEST.get_or_init(|| hex(Sha256::digest(BUNDLE)))
243 }
244
245 /// Write the embedded bundle, and the licence notices that belong with it, to
246 /// `<root>/extension-host/<sha256>/` unless identical copies are already there,
247 /// then re-verify the bytes on disk. A file is never overwritten in place: a
248 /// different build writes a different directory. Blocking.
249 fn materialize_bundle(root: &Path) -> Result<PathBuf, String> {
250 let dir = supervisor::bundle_dir(root, bundle_sha256());
251 let bundle = materialize_file(&dir, BUNDLE_FILE_NAME, BUNDLE)?;
252 materialize_file(&dir, NOTICES_FILE_NAME, NOTICES)?;
253 materialize_file(
254 &dir.join("builtin"),
255 "mcp.mjs",
256 include_bytes!("../../extension-host/dist/builtin/mcp.mjs"),
257 )?;
258 materialize_file(
259 &dir.join("builtin"),
260 "harness.mjs",
261 include_bytes!("../../extension-host/dist/builtin/harness.mjs"),
262 )?;
263 materialize_file(
264 &dir.join("builtin"),
265 "creator.mjs",
266 include_bytes!("../../extension-host/dist/builtin/creator.mjs"),
267 )?;
268 Ok(bundle)
269 }
270
271 fn materialized_bundle(root: &Path) -> Result<PathBuf, String> {
272 let bundle = supervisor::bundle_dir(root, bundle_sha256()).join(BUNDLE_FILE_NAME);
273 if bundle.is_file() {
274 Ok(bundle)
275 } else {
276 Err(supervisor::would_create(&bundle))
277 }
278 }
279
280 /// One embedded file in `dir`: written to a private staging name, made
281 /// read-only, renamed into place (so a reader never sees a partial file and a
282 /// symlink at the final name is replaced, not followed), and read back.
283 fn materialize_file(dir: &Path, file_name: &str, bytes: &[u8]) -> Result<PathBuf, String> {
284 let path = dir.join(file_name);
285 let matches = |path: &Path| std::fs::read(path).is_ok_and(|on_disk| on_disk == bytes);
286 if !matches(&path) {
287 std::fs::create_dir_all(dir)
288 .map_err(|error| format!("cannot create {}: {error}", dir.display()))?;
289 if let Err(error) = codewhale_util::utils::write_atomic(&path, bytes)
290 && !matches(&path)
291 {
292 return Err(format!("cannot publish {}: {error}", path.display()));
293 }
294 #[cfg(unix)]
295 {
296 use std::os::unix::fs::PermissionsExt;
297 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400));
298 }
299 }
300 // Re-check what will actually be used.
301 if !matches(&path) {
302 return Err(format!(
303 "{} does not match the embedded copy (sha256 {})",
304 path.display(),
305 hex(Sha256::digest(bytes))
306 ));
307 }
308 Ok(path)
309 }
310
311 /// Options fixed for the life of one manager.
312 #[derive(Debug, Clone, Default)]
313 pub struct ExtensionHostOptions {
314 /// `[extension_host] runtime`: `node` (the default), `bun`, or `auto`
315 /// (Bun first).
316 pub runtime: codewhale_config::extension_host::ExtensionHostRuntime,
317 /// `[extension_host] node`: tried before every `node` on `PATH`.
318 pub node_override: Option<PathBuf>,
319 /// `[extension_host] bun`: tried before every `bun` on `PATH`.
320 pub bun_override: Option<PathBuf>,
321 /// Where the bundle is materialized; defaults to the Codewhale home.
322 pub root: Option<PathBuf>,
323 /// Per-manager timings; tests can shorten them without global state.
324 pub supervision: SupervisionOptions,
325 }
326
327 #[derive(Debug, Clone)]
328 pub struct SupervisionOptions {
329 pub heartbeat_interval: Duration,
330 pub ping_timeout: Duration,
331 pub hang_timeout: Duration,
332 pub restart_backoff: Duration,
333 pub crash_window: Duration,
334 pub crash_limit: usize,
335 pub start_retry_cooldown: Duration,
336 pub dirty_window: Duration,
337 pub dirty_limit: usize,
338 /// Host memory cap in bytes (`supervisor::HOST_MEMORY_CAP`).
339 pub memory_cap: u64,
340 /// How long one extension tool call may take before the core cancels it
341 /// (`tool::TOOL_CALL_DEADLINE`); sent to the host as `deadline_ms`. The
342 /// other methods' deadlines are fixed (`CoreRequest::deadline`).
343 pub tool_call_deadline: Duration,
344 /// How long the user waits for one extension command before the core
345 /// cancels it (`command::COMMAND_RUN_DEADLINE`); sent to the host as
346 /// `deadline_ms`.
347 pub command_run_deadline: Duration,
348 }
349
350 impl ExtensionHostOptions {
351 /// Options for the `[extension_host]` table (paths `~`-expanded).
352 #[must_use]
353 pub fn from_config(
354 table: Option<&codewhale_config::extension_host::ExtensionHostConfig>,
355 ) -> Self {
356 let expand = |path: Option<&String>| {
357 path.map(|path| PathBuf::from(shellexpand::tilde(path).as_ref()))
358 };
359 Self {
360 runtime: table.map_or_else(Default::default, |table| table.effective_runtime()),
361 node_override: expand(table.and_then(|table| table.node.as_ref())),
362 bun_override: expand(table.and_then(|table| table.bun.as_ref())),
363 ..Default::default()
364 }
365 }
366 }
367
368 impl Default for SupervisionOptions {
369 fn default() -> Self {
370 Self {
371 heartbeat_interval: Duration::from_secs(3),
372 ping_timeout: Duration::from_secs(3),
373 hang_timeout: supervisor::PING_DEADLINE,
374 restart_backoff: Duration::from_millis(250),
375 crash_window: Duration::from_secs(5 * 60),
376 crash_limit: 3,
377 start_retry_cooldown: Duration::from_secs(60),
378 dirty_window: Duration::from_secs(10 * 60),
379 dirty_limit: 2,
380 memory_cap: supervisor::HOST_MEMORY_CAP,
381 tool_call_deadline: tool::TOOL_CALL_DEADLINE,
382 command_run_deadline: command::COMMAND_RUN_DEADLINE,
383 }
384 }
385 }
386
387 #[derive(Default)]
388 struct SupervisionState {
389 crashes: VecDeque<Instant>,
390 last_start: Option<Instant>,
391 launch_failed: bool,
392 retry_ticket: u64,
393 policy: bool,
394 dirty_teardowns: VecDeque<Instant>,
395 dirty_restart_pending: bool,
396 planned_restart: Option<u64>,
397 }
398
399 impl SupervisionState {
400 fn record_dirty_teardown(&mut self, now: Instant, options: &SupervisionOptions) {
401 while self
402 .dirty_teardowns
403 .front()
404 .is_some_and(|at| now.saturating_duration_since(*at) >= options.dirty_window)
405 {
406 self.dirty_teardowns.pop_front();
407 }
408 self.dirty_teardowns.push_back(now);
409 let limit = options.dirty_limit.max(1);
410 self.dirty_restart_pending |= self.dirty_teardowns.len() >= limit;
411 while self.dirty_teardowns.len() > limit {
412 self.dirty_teardowns.pop_front();
413 }
414 }
415
416 fn record_crash(&mut self, now: Instant, options: &SupervisionOptions) -> bool {
417 while self
418 .crashes
419 .front()
420 .is_some_and(|at| now.saturating_duration_since(*at) >= options.crash_window)
421 {
422 self.crashes.pop_front();
423 }
424 self.crashes.push_back(now);
425 self.launch_failed = false;
426 self.retry_ticket += 1;
427 self.crashes.len() < options.crash_limit
428 }
429 }
430
431 /// Observable host state: the one source for `/plugin` and for the error a
432 /// tool call routed to the host gets while it is down ([`fmt::Display`]).
433 #[derive(Debug, Clone, PartialEq, Eq)]
434 pub enum HostStatus {
435 /// `[features] extension_host` is off for this process.
436 Disabled,
437 /// Not started: nothing has needed it yet.
438 Idle,
439 Starting,
440 Ready {
441 pid: Option<u32>,
442 /// `bun` or `node`.
443 runtime: &'static str,
444 /// As reported by the host (`host/hello`).
445 runtime_version: String,
446 sandbox: supervisor::HostSandbox,
447 /// How the memory cap is enforced for this process.
448 memory: supervisor::MemoryEnforcement,
449 },
450 Unresponsive {
451 pid: Option<u32>,
452 },
453 /// Crashed (or retired for maintenance); the supervisor restarts it.
454 Restarting {
455 reason: String,
456 },
457 /// Start refused (`start failed: …`) or crash budget exhausted; only an
458 /// explicit plugin change or reload retries.
459 Failed {
460 reason: String,
461 stderr_tail: String,
462 },
463 }
464
465 /// Why the host can or cannot take a call, in one phrase.
466 impl fmt::Display for HostStatus {
467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468 match self {
469 Self::Disabled => f.write_str("disabled by config ([features] extension_host is off)"),
470 Self::Idle => f.write_str(
471 "not started (it starts in the background when a reviewed plugin with host code is enabled)",
472 ),
473 Self::Starting => f.write_str("starting"),
474 Self::Ready { .. } => f.write_str("running"),
475 Self::Unresponsive { pid } => write!(
476 f,
477 "unresponsive (pid {} missed its heartbeat; the supervisor restarts it if it stays silent)",
478 pid.map_or_else(|| "?".to_string(), |pid| pid.to_string())
479 ),
480 Self::Restarting { reason } => write!(f, "restarting after: {reason}"),
481 Self::Failed { reason, .. } => {
482 write!(f, "{reason} (change or reload a plugin to retry)")
483 }
484 }
485 }
486 }
487
488 enum HostSlot {
489 Idle,
490 Starting,
491 Ready(Arc<HostProcess>),
492 Unresponsive(Arc<HostProcess>),
493 Restarting { reason: String },
494 Failed { reason: String, stderr_tail: String },
495 }
496
497 impl HostSlot {
498 fn status(&self) -> HostStatus {
499 match self {
500 Self::Idle => HostStatus::Idle,
501 Self::Starting => HostStatus::Starting,
502 Self::Ready(host) if host.is_retiring() => HostStatus::Restarting {
503 reason: DIRTY_RESTART_REASON.to_string(),
504 },
505 // The exit watcher reports the exit a moment later.
506 Self::Ready(host) | Self::Unresponsive(host) if host.has_exited() => {
507 HostStatus::Restarting {
508 reason: "the host process exited".to_string(),
509 }
510 }
511 Self::Ready(host) => HostStatus::Ready {
512 pid: host.pid,
513 runtime: host.runtime.kind.name(),
514 runtime_version: host.runtime_version.get().cloned().unwrap_or_default(),
515 sandbox: host.sandbox.clone(),
516 memory: host.memory(),
517 },
518 Self::Unresponsive(host) => HostStatus::Unresponsive { pid: host.pid },
519 Self::Restarting { reason } => HostStatus::Restarting {
520 reason: reason.clone(),
521 },
522 Self::Failed {
523 reason,
524 stderr_tail,
525 } => HostStatus::Failed {
526 reason: reason.clone(),
527 stderr_tail: stderr_tail.clone(),
528 },
529 }
530 }
531 }
532
533 /// One tier's host process, and everything that goes with supervising it: the
534 /// slot, the generation that makes old callbacks harmless, the spawn count and
535 /// the crash/restart bookkeeping. The two tiers each own one, so a crash,
536 /// restart or failed launch of one never touches the other. The owner
537 /// registry, the runtime pin and the attachments stay shared.
538 struct TierRuntime {
539 host: Mutex<HostSlot>,
540 host_generation: AtomicU64,
541 spawn_attempts: AtomicU64,
542 /// Lock order: see [`ManagerShared`].
543 supervision: Mutex<SupervisionState>,
544 imported_entries: Mutex<(u64, BTreeMap<PathBuf, String>)>,
545 }
546
547 impl TierRuntime {
548 fn new() -> Self {
549 Self {
550 host: Mutex::new(HostSlot::Idle),
551 host_generation: AtomicU64::new(0),
552 spawn_attempts: AtomicU64::new(0),
553 supervision: Mutex::new(SupervisionState::default()),
554 imported_entries: Mutex::new((0, BTreeMap::new())),
555 }
556 }
557 }
558
559 #[derive(Clone)]
560 struct DesiredOwner {
561 cohort: HostCohort,
562 plugin_name: String,
563 authority: PluginAuthority,
564 entries: Vec<(PathBuf, String)>,
565 host_services: Vec<protocol::DshService>,
566 }
567
568 /// What [`ExtensionHostManager::activate_owner`] activates, on either tier:
569 /// a plugin's reviewed bytes, or a built-in module's pinned source.
570 struct Activation {
571 cohort: HostCohort,
572 owner_id: String,
573 /// The plugin's manifest name, or the module's name.
574 name: String,
575 /// The reviewed plugin authority; `None` for a built-in module.
576 authority: Option<PluginAuthority>,
577 /// What the owner is bound to: the plugin's content hash, or the module's
578 /// pinned source digest.
579 content_hash: String,
580 entries: Vec<(PathBuf, String)>,
581 host_services: Vec<protocol::DshService>,
582 }
583
584 impl Activation {
585 pub fn tier(&self) -> HostTier {
586 self.cohort.tier()
587 }
588 }
589
590 /// One engine's view: its plugin snapshot and the owners (plugin id →
591 /// reviewed content hash) that snapshot desired at the last reconcile.
592 struct AttachmentState {
593 route_authority: Option<Arc<PluginAuthority>>,
594 plugins: Arc<PluginRegistry>,
595 desired: BTreeMap<String, String>,
596 selection: codewhale_plugins::composition_scope::CompositionSelection,
597 revision: u64,
598 selection_cancel: CancellationToken,
599 settled: Option<codewhale_plugins::composition_scope::SelectionRevision>,
600 session_id: Option<String>,
601 agent_id: Option<String>,
602 creator_demanded: bool,
603 }
604
605 /// Lock order, outermost first, everywhere in this module:
606 ///
607 /// 1. `sync_lock` (async; the only lock held across an await, and it only
608 /// serializes reconciliation);
609 /// 2. `agent_cohorts` and `pending_migrations` (cohort discovery and migration coordination);
610 /// 3. one cohort's `host` slot, then that same cohort's `supervision`;
611 /// 4. `registry`.
612 ///
613 /// No code holds multiple cohorts' slots or multiple cohorts' supervision state at once:
614 /// a path that must visit multiple cohorts visits one, releases it, then the other.
615 /// `attachments`, `runtime`, `plugin_configs` and `diagnostics` are leaf
616 /// locks, never held together with another lock (`diagnostics` is only ever
617 /// taken last, from the `diagnostic` helpers). No lock but `sync_lock` is held
618 /// across an await.
619 pub struct ManagerShared {
620 options: ExtensionHostOptions,
621 /// The built-in host modules this manager may start the builtin tier for:
622 /// [`tier::BUILTIN_MODULES`] in production; a test substitutes its
623 /// own through [`ExtensionHostManager::with_builtin_modules`].
624 builtin_modules: &'static [BuiltinModule],
625 materialize_default_builtins: bool,
626 attachments: Mutex<BTreeMap<u64, AttachmentState>>,
627 next_attachment: AtomicU64,
628 /// One registry for both tiers: an owner's entry records which.
629 registry: Mutex<OwnerRegistry>,
630 /// Capability tickets and the invocations they belong to (`core/call`).
631 /// A leaf lock domain: its mutexes are never held with another lock.
632 core_calls: Arc<core_call::CoreCalls>,
633 engine_handle: OnceLock<tokio::runtime::Handle>,
634 execution_broker: execution::Broker,
635 harness_users: AtomicU64,
636 stock_users: AtomicU64,
637 creator_users: AtomicU64,
638 mcp_broker: mcp::Broker,
639 mcp_users: AtomicU64,
640 /// Tier 1: reviewed third-party plugins.
641 plugin: Arc<TierRuntime>,
642 /// Tier 0: Codewhale's own host code. Starts only for a built-in module.
643 builtin: Arc<TierRuntime>,
644 agent_cohorts: Mutex<BTreeMap<PathBuf, Arc<TierRuntime>>>,
645 agent_host_generation: AtomicU64,
646 pending_migrations: Mutex<BTreeMap<String, HostCohort>>,
647 sync_lock: tokio::sync::Mutex<()>,
648 /// Bound native root parsing independently of reconciliation (activation
649 /// itself calls admission while reconciliation owns sync_lock).
650 skill_admission: Arc<tokio::sync::Semaphore>,
651 diagnostics: Mutex<VecDeque<Diagnostic>>,
652 /// Which runtime every host (of either tier) runs on.
653 runtime: Mutex<RuntimePin>,
654 /// User settings per plugin name.
655 plugin_configs: Mutex<plugin_config::PluginConfigs>,
656 reconcile_settled: tokio::sync::Notify,
657 }
658
659 /// Which runtime this manager's hosts run on.
660 #[derive(Default)]
661 struct RuntimePin {
662 /// Set by the first host that completes the handshake and reused by
663 /// every restart, so a session never switches runtime (a `bun` install
664 /// or removal mid-session changes nothing until the next process; a
665 /// binary replaced at the pinned path is refused at the handshake). With
666 /// the one-line summary of why it was chosen, for `/plugin`.
667 pinned: Option<(codewhale_dependencies::HostRuntime, String)>,
668 /// `runtime = "auto"` only: a Bun host failed to launch or handshake
669 /// before anything was pinned, so every later launch this session
670 /// resolves Node.
671 bun_failed: bool,
672 }
673
674 /// Resolve the runtime unless one is pinned, materialize the bundle and plan
675 /// the launch. Returns the summary to pin once a host on this runtime
676 /// completes the handshake, or `None` when the runtime was already pinned.
677 /// Blocking.
678 fn prepare_launch(
679 options: &ExtensionHostOptions,
680 cohort: &HostCohort,
681 pinned: Option<(codewhale_dependencies::HostRuntime, String)>,
682 bun_failed: bool,
683 snapshot_state_paths: &[PathBuf],
684 ) -> Result<(supervisor::HostLaunch, Option<String>), String> {
685 let (runtime, summary) = match pinned {
686 Some((runtime, _)) => (runtime, None),
687 None => {
688 let choice = if bun_failed {
689 codewhale_config::extension_host::ExtensionHostRuntime::Node
690 } else {
691 options.runtime
692 };
693 let mut resolution = codewhale_dependencies::resolve_extension_host_runtime(
694 choice,
695 options.node_override.as_deref(),
696 options.bun_override.as_deref(),
697 crate::extension_host::bundle_sha256(),
698 );
699 // Report the configured choice, not the Node-only fallback.
700 resolution.choice = options.runtime;
701 let note = if bun_failed {
702 "; Bun failed to start this session (see diagnostics)"
703 } else {
704 ""
705 };
706 let Some(runtime) = resolution.selected.clone() else {
707 return Err(format!("{}{note}", resolution.failure()));
708 };
709 (runtime, Some(format!("{}{note}", resolution.summary())))
710 }
711 };
712 let root = host_root(options)?;
713 let bundle = materialize_bundle(&root)?;
714 let launch = supervisor::plan_launch(
715 cohort,
716 &runtime,
717 &bundle,
718 &root,
719 options.supervision.memory_cap,
720 snapshot_state_paths,
721 )?;
722 Ok((launch, summary))
723 }
724
725 /// The Codewhale home the host lives under.
726 fn host_root(options: &ExtensionHostOptions) -> Result<PathBuf, String> {
727 match options.root.clone() {
728 Some(root) => Ok(root),
729 None => codewhale_config::codewhale_home()
730 .map_err(|error| format!("Codewhale home unavailable: {error}")),
731 }
732 }
733
734 /// The selected tier's sandbox, planned exactly as a launch does (for doctor).
735 /// Blocking; creates nothing, and probes bubblewrap on Linux.
736 pub fn planned_sandbox(
737 options: &ExtensionHostOptions,
738 runtime: &codewhale_dependencies::HostRuntime,
739 tier: HostTier,
740 ) -> Result<supervisor::HostSandbox, String> {
741 supervisor::planned_sandbox_tier(tier, runtime, &host_root(options)?)
742 }
743
744 impl ManagerShared {
745 pub fn engine_handle(&self) -> Result<tokio::runtime::Handle, String> {
746 self.engine_handle.get().cloned().ok_or_else(|| "enabled execution requires the Engine scheduler; no new runtime or legacy fallback is allowed".to_string())
747 }
748
749 fn cohort_runtime(&self, cohort: &HostCohort) -> Option<Arc<TierRuntime>> {
750 match cohort {
751 HostCohort::Builtin => Some(Arc::clone(&self.builtin)),
752 HostCohort::Plugin(PluginCohort::Reviewed) => Some(Arc::clone(&self.plugin)),
753 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
754 let path = cohort.agent_project_path()?;
755 self.agent_cohorts
756 .lock()
757 .expect("agent cohorts lock")
758 .get(&path)
759 .cloned()
760 }
761 }
762 }
763
764 fn get_or_create_cohort_runtime(&self, cohort: &HostCohort) -> Arc<TierRuntime> {
765 match cohort {
766 HostCohort::Builtin => Arc::clone(&self.builtin),
767 HostCohort::Plugin(PluginCohort::Reviewed) => Arc::clone(&self.plugin),
768 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
769 let path = cohort
770 .agent_project_path()
771 .unwrap_or_else(|| PathBuf::from(""));
772 self.agent_cohorts
773 .lock()
774 .expect("agent cohorts lock")
775 .entry(path)
776 .or_insert_with(|| Arc::new(TierRuntime::new()))
777 .clone()
778 }
779 }
780 }
781
782 fn all_runtimes(&self) -> Vec<Arc<TierRuntime>> {
783 let mut runtimes = vec![Arc::clone(&self.builtin), Arc::clone(&self.plugin)];
784 runtimes.extend(
785 self.agent_cohorts
786 .lock()
787 .expect("agent cohorts lock")
788 .values()
789 .cloned(),
790 );
791 runtimes
792 }
793
794 /// The supervision state of `tier`'s host.
795 fn tier_runtime(&self, tier: HostTier) -> Arc<TierRuntime> {
796 match tier {
797 HostTier::Plugin => Arc::clone(&self.plugin),
798 HostTier::Builtin => Arc::clone(&self.builtin),
799 }
800 }
801
802 async fn deactivate_owner(&self, host: &Arc<HostProcess>, owner: &OwnerRef) {
803 self.deactivate_entry(host, owner, None).await;
804 }
805 /// A failed or retired Native entry must produce the same bounded teardown
806 /// receipt as a whole owner, while its other selected entries stay live.
807 async fn deactivate_entry(
808 &self,
809 host: &Arc<HostProcess>,
810 owner: &OwnerRef,
811 entry: Option<EntryRef>,
812 ) {
813 let diagnostic = match host
814 .call(
815 CoreRequest::Deactivate(DeactivateParams {
816 entry,
817 owner: owner.clone(),
818 }),
819 None,
820 )
821 .await
822 .map(serde_json::from_value::<DeactivateResult>)
823 {
824 Ok(Ok(ack)) if ack.disposed && ack.leaked.is_empty() => return,
825 Ok(Ok(ack)) => format!(
826 "plugin `{}` teardown incomplete (disposed: {}, leaked: {:?})",
827 owner.plugin_id, ack.disposed, ack.leaked
828 ),
829 Ok(Err(error)) => format!(
830 "plugin `{}` teardown answer malformed: {error}",
831 owner.plugin_id
832 ),
833 Err(error) => format!("plugin `{}` teardown failed: {error}", owner.plugin_id),
834 };
835 self.plugin_diagnostic(&owner.plugin_id, diagnostic);
836 self.record_dirty_teardown(host);
837 }
838
839 fn record_dirty_teardown(&self, host: &Arc<HostProcess>) {
840 let Some(runtime) = self.cohort_runtime(&host.cohort) else {
841 return;
842 };
843 let slot = runtime.host.lock().expect("host lock");
844 if !matches!(&*slot, HostSlot::Ready(current) | HostSlot::Unresponsive(current)
845 if Arc::ptr_eq(current, host))
846 {
847 return;
848 }
849 runtime
850 .supervision
851 .lock()
852 .expect("supervision lock")
853 .record_dirty_teardown(Instant::now(), &self.options.supervision);
854 }
855
856 fn revoke_owner_state(&self, plugin_id: &str) {
857 self.core_calls.revoke_owner(plugin_id);
858 self.execution_broker.revoke_owner(plugin_id);
859 self.mcp_users
860 .fetch_sub(self.mcp_broker.revoke_owner(plugin_id), Ordering::SeqCst);
861 dsh_terminal::kill_plugin_sessions(plugin_id);
862 }
863
864 fn diagnostic(&self, message: String) {
865 self.record_diagnostic(None, message);
866 }
867
868 fn plugin_diagnostic(&self, plugin_id: &str, message: String) {
869 // Refused registrations can contain an arbitrary host-supplied id.
870 // Keep an oversized id global instead of retaining unbounded metadata
871 // or truncating it into another plugin's identity.
872 let plugin_id = (plugin_id.len() <= MAX_DIAGNOSTIC_BYTES).then(|| plugin_id.to_string());
873 self.record_diagnostic(plugin_id, message);
874 }
875
876 fn record_diagnostic(&self, plugin_id: Option<String>, message: String) {
877 let message = bounded_diagnostic(message);
878 tracing::info!(target: "extension_host", "{message}");
879 let mut diagnostics = self.diagnostics.lock().expect("diagnostics lock");
880 diagnostics.push_back(Diagnostic { plugin_id, message });
881 while diagnostics.len() > MAX_DIAGNOSTICS {
882 diagnostics.pop_front();
883 }
884 }
885
886 fn ready_host(&self, cohort: &HostCohort) -> Result<Arc<HostProcess>, HostStatus> {
887 let Some(runtime) = self.cohort_runtime(cohort) else {
888 return Err(HostStatus::Idle);
889 };
890 match &*runtime.host.lock().expect("host lock") {
891 HostSlot::Ready(host) if !host.has_exited() && !host.is_retiring() => {
892 Ok(Arc::clone(host))
893 }
894 slot => Err(slot.status()),
895 }
896 }
897
898 fn clear_plugin_diagnostics(&self, plugin_id: &str) {
899 self.diagnostics
900 .lock()
901 .expect("diagnostics lock")
902 .retain(|entry| entry.plugin_id.as_deref() != Some(plugin_id));
903 }
904
905 /// The shared fast liveness guard: current policy, running host, exact
906 /// owner generation/tier and its reviewed authority. `live_host` follows
907 /// with Native receipt validation and another host check; root admission
908 /// uses the same authority inside its one bounded blocking disk job.
909 ///
910 /// `owner_if_live` runs under the registry lock and names the owner
911 /// generation the call belongs to, or why it is no longer registered.
912 fn live_owner_authority(
913 &self,
914 cohort: impl Into<HostCohort>,
915 owner_if_live: impl FnOnce(&OwnerRegistry) -> Result<OwnerRef, String>,
916 ) -> Result<Option<PluginAuthority>, String> {
917 let cohort = cohort.into();
918 let tier = cohort.tier();
919 let native_policy = activation::extension_host_policy_enabled();
920 if tier == HostTier::Plugin && !native_policy {
921 return Err(host_down(tier, &HostStatus::Disabled));
922 }
923 self.ready_host(&cohort)
924 .map_err(|status| host_down(tier, &status))?;
925 {
926 let registry = self.registry.lock().expect("registry lock");
927 let owner = owner_if_live(&registry)?;
928 // Independent Core demand admits only the exact pinned module.
929 // Script/hook jobs still require Native policy in Caller::check.
930 let core_stock =
931 owner.plugin_id == "host:harness" && self.stock_users.load(Ordering::SeqCst) > 0;
932 let creator_live =
933 owner.plugin_id == "host:creator" && self.creator_users.load(Ordering::SeqCst) > 0;
934 if !native_policy && owner.plugin_id != "host:mcp" && !core_stock && !creator_live {
935 return Err(host_down(tier, &HostStatus::Disabled));
936 }
937 let owner_cohort = registry
938 .cohort_of(&owner)
939 .ok_or_else(|| "plugin owner has no authority".to_string())?;
940 if owner_cohort != cohort {
941 return Err(format!(
942 "plugin owner `{}` belongs to the {} cohort, not the {} cohort",
943 owner.plugin_id,
944 owner_cohort.host_label(),
945 cohort.host_label()
946 ));
947 }
948 match (tier, registry.authority_for(&owner)) {
949 (HostTier::Plugin, Some(authority)) => Ok(Some(authority)),
950 (HostTier::Builtin, None) => Ok(None),
951 _ => Err("plugin owner has no authority".to_string()),
952 }
953 }
954 }
955
956 async fn live_host(
957 &self,
958 cohort: impl Into<HostCohort>,
959 owner_if_live: impl FnOnce(&OwnerRegistry) -> Result<OwnerRef, String>,
960 ) -> Result<Arc<HostProcess>, String> {
961 let cohort = cohort.into();
962 let tier = cohort.tier();
963 let policy = activation::extension_host_policy_enabled();
964 let authority = self.live_owner_authority(&cohort, owner_if_live)?;
965 if let Some(authority) = authority {
966 #[cfg(any(test, feature = "test-support"))]
967 let env_scope = crate::test_support::env_scope_ticket();
968 tokio::task::spawn_blocking(move || {
969 #[cfg(any(test, feature = "test-support"))]
970 let _env_scope = crate::test_support::join_env_scope(env_scope);
971 let _scope = activation::PolicyScope::propagate(policy);
972 codewhale_plugins::registry::verify_plugin_component_authority(
973 &authority,
974 PluginActivationCapability::Native,
975 )
976 })
977 .await
978 .map_err(|error| format!("authority check failed: {error}"))??;
979 }
980 self.ready_host(&cohort)
981 .map_err(|status| host_down(tier, &status))
982 }
983
984 pub async fn live_host_for(
985 &self,
986 registration: &ToolRegistration,
987 ) -> Result<Arc<HostProcess>, String> {
988 self.live_host(&registration.cohort, |registry| {
989 if registry.is_live(registration.handle, &registration.owner) {
990 Ok(registration.owner.clone())
991 } else {
992 Err(format!(
993 "plugin tool `{}` from `{}` is no longer registered",
994 registration.name, registration.plugin_name
995 ))
996 }
997 })
998 .await
999 }
1000
1001 /// [`Self::live_host`] for a command the user just invoked: the exact
1002 /// registration (handle and owner generation) must still be admitted.
1003 pub async fn live_host_for_command(
1004 &self,
1005 command: &command::ExtensionCommandRef,
1006 ) -> Result<(Arc<HostProcess>, CommandRegistration), String> {
1007 let cohort = {
1008 let registry = self.registry.lock().expect("registry lock");
1009 let registration = registry
1010 .live_command(command.handle, &command.plugin_id, command.generation)
1011 .ok_or_else(|| {
1012 format!(
1013 "plugin command from `{}` is no longer registered (the plugin was reloaded, disabled or lost trust)",
1014 command.plugin_id
1015 )
1016 })?;
1017 registration.cohort.clone()
1018 };
1019 let mut found = None;
1020 let host = self
1021 .live_host(&cohort, |registry| {
1022 let registration = registry
1023 .live_command(command.handle, &command.plugin_id, command.generation)
1024 .ok_or_else(|| {
1025 format!(
1026 "plugin command from `{}` is no longer registered (the plugin was reloaded, disabled or lost trust)",
1027 command.plugin_id
1028 )
1029 })?;
1030 let owner = registration.owner.clone();
1031 found = Some(registration);
1032 Ok(owner)
1033 })
1034 .await?;
1035 Ok((host, found.expect("set when the owner was found")))
1036 }
1037
1038 pub(crate) async fn live_host_for_plugin_authority(
1039 &self,
1040 authority: &PluginAuthority,
1041 ) -> Result<(Arc<HostProcess>, OwnerRef), String> {
1042 let find_owner = |registry: &OwnerRegistry| {
1043 let entry = registry
1044 .route_owner(authority)
1045 .map_err(|_| {
1046 format!(
1047 "plugin `{}` service is already attached to another workspace",
1048 authority.plugin_id
1049 )
1050 })?
1051 .ok_or_else(|| {
1052 format!(
1053 "plugin `{}` has no active service for this revision",
1054 authority.plugin_id
1055 )
1056 })?;
1057 match &entry.state {
1058 OwnerState::Active => Ok((entry.cohort.clone(), entry.owner.clone())),
1059 OwnerState::Failed(_) => Err(format!(
1060 "plugin `{}` failed activation before its service became available",
1061 authority.plugin_id
1062 )),
1063 OwnerState::Faulted(_) => {
1064 Err(format!("plugin `{}` service faulted", authority.plugin_id))
1065 }
1066 OwnerState::Activating => {
1067 Err(format!("plugin `{}` is activating", authority.plugin_id))
1068 }
1069 OwnerState::Revoked => Err(format!(
1070 "plugin `{}` service was revoked",
1071 authority.plugin_id
1072 )),
1073 }
1074 };
1075 let (cohort, _) = find_owner(&self.registry.lock().expect("registry lock"))?;
1076 let mut found = None;
1077 let host = self
1078 .live_host(&cohort, |registry| {
1079 let (_, owner) = find_owner(registry)?;
1080 found = Some(owner.clone());
1081 Ok(owner)
1082 })
1083 .await?;
1084 Ok((host, found.expect("set when the owner was found")))
1085 }
1086 }
1087
1088 /// The error a call gets while the host of `tier` cannot take it.
1089 fn host_down(tier: HostTier, status: &HostStatus) -> String {
1090 format!("{} is down: {status}", tier.host_label())
1091 }
1092
1093 /// Channel callbacks. Holds a `Weak` so the host process (which owns the
1094 /// callbacks) never keeps the manager alive. Each belongs to one tier's host
1095 /// process and generation.
1096 struct Events {
1097 shared: Weak<ManagerShared>,
1098 cohort: HostCohort,
1099 generation: u64,
1100 }
1101
1102 #[async_trait]
1103 impl HostEvents for Events {
1104 fn responded(&self) {
1105 if let Some(shared) = self.shared.upgrade() {
1106 // Completing a live request is evidence of recovery before its
1107 // caller's post-await liveness checks. The pending ping retains
1108 // its original hang deadline; this creates no new health clock.
1109 set_host_health(&shared, &self.cohort, self.generation, false);
1110 }
1111 }
1112
1113 async fn host_request(
1114 &self,
1115 request: protocol::HostRequest,
1116 cx: HostRequestContext,
1117 ) -> Result<serde_json::Value, protocol::RpcErrorWire> {
1118 let refuse = |message: &str| protocol::RpcErrorWire {
1119 code: protocol::error_code::REFUSED,
1120 message: message.to_string(),
1121 data: None,
1122 };
1123 match request {
1124 protocol::HostRequest::ExecutionRedeem(params) => {
1125 let shared = self
1126 .shared
1127 .upgrade()
1128 .ok_or_else(|| refuse("plugin host manager is gone"))?;
1129 if self.cohort != HostCohort::Builtin {
1130 return Err(refuse("execution broker is builtin-only"));
1131 }
1132 shared
1133 .execution_broker
1134 .serve(&shared, self.generation, params, cx)
1135 .await
1136 }
1137 protocol::HostRequest::UserQuestion(params) => {
1138 let shared = self
1139 .shared
1140 .upgrade()
1141 .ok_or_else(|| refuse("plugin host manager is gone"))?;
1142 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1143 return Err(refuse("unknown host cohort"));
1144 };
1145 if runtime.host_generation.load(Ordering::SeqCst) != self.generation {
1146 return Err(refuse("stale host generation"));
1147 }
1148 shared
1149 .core_calls
1150 .serve_question(&shared, &self.cohort, self.generation, params, cx)
1151 .await
1152 }
1153 protocol::HostRequest::SubagentStart(_)
1154 | protocol::HostRequest::SubagentResult(_)
1155 | protocol::HostRequest::SubagentDispose(_)
1156 | protocol::HostRequest::SubagentPrompt(_) => {
1157 let shared = self
1158 .shared
1159 .upgrade()
1160 .ok_or_else(|| refuse("plugin host manager is gone"))?;
1161 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1162 return Err(refuse("unknown host cohort"));
1163 };
1164 if runtime.host_generation.load(Ordering::SeqCst) != self.generation {
1165 return Err(refuse("stale host generation"));
1166 }
1167 shared
1168 .core_calls
1169 .serve_subagent(&shared, &self.cohort, self.generation, request, cx)
1170 .await
1171 }
1172 protocol::HostRequest::SessionCheckpoint(params) => {
1173 let shared = self
1174 .shared
1175 .upgrade()
1176 .ok_or_else(|| refuse("plugin host manager is gone"))?;
1177 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1178 return Err(refuse("unknown host cohort"));
1179 };
1180 if runtime.host_generation.load(Ordering::SeqCst) != self.generation {
1181 return Err(refuse("stale host generation"));
1182 }
1183 shared
1184 .core_calls
1185 .serve_checkpoint(&shared, &self.cohort, self.generation, params, cx)
1186 .await
1187 }
1188 protocol::HostRequest::DshBroker(params) => {
1189 let Some(shared) = self.shared.upgrade() else {
1190 return Err(refuse("plugin host manager is gone"));
1191 };
1192 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1193 return Err(refuse("unknown host cohort"));
1194 };
1195 if runtime.host_generation.load(Ordering::SeqCst) != self.generation {
1196 return Err(refuse("stale host generation"));
1197 }
1198 shared
1199 .core_calls
1200 .serve_broker(&shared, &self.cohort, self.generation, params, cx)
1201 .await
1202 }
1203 protocol::HostRequest::CoreCall(params) => {
1204 let Some(shared) = self.shared.upgrade() else {
1205 return Err(refuse("plugin host manager is gone"));
1206 };
1207 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1208 return Err(refuse("unknown host cohort"));
1209 };
1210 if runtime.host_generation.load(Ordering::SeqCst) != self.generation {
1211 return Err(refuse("stale host generation"));
1212 }
1213 shared
1214 .core_calls
1215 .serve(&shared, &self.cohort, self.generation, params, cx)
1216 .await
1217 }
1218 protocol::HostRequest::Register(params) if params.kind == RegisterKind::McpServer => {
1219 let shared = self
1220 .shared
1221 .upgrade()
1222 .ok_or_else(|| refuse("plugin host manager is gone"))?;
1223 let result =
1224 native_mcp::admit(&shared, &self.cohort, self.generation, params, &cx).await;
1225 Ok(serde_json::to_value(result).expect("registration result is JSON"))
1226 }
1227 protocol::HostRequest::Register(params) if params.kind == RegisterKind::AvatarPack => {
1228 let Some(shared) = self.shared.upgrade() else {
1229 return Err(refuse("plugin host manager is gone"));
1230 };
1231 let result =
1232 avatars::admit(&shared, &self.cohort, self.generation, params, &cx).await;
1233 Ok(serde_json::to_value(result).expect("registration result is JSON"))
1234 }
1235 protocol::HostRequest::Register(params) if params.kind == RegisterKind::SkillRoot => {
1236 let Some(shared) = self.shared.upgrade() else {
1237 return Err(refuse("plugin host manager is gone"));
1238 };
1239 let result =
1240 skills::admit_root(&shared, &self.cohort, self.generation, params, &cx).await;
1241 Ok(serde_json::to_value(result).expect("registration result is JSON"))
1242 }
1243 request @ (protocol::HostRequest::ProcLaunch(_)
1244 | protocol::HostRequest::ProcRead(_)
1245 | protocol::HostRequest::ProcWrite(_)
1246 | protocol::HostRequest::ProcClose(_)
1247 | protocol::HostRequest::NetStart(_)
1248 | protocol::HostRequest::NetFetch(_)
1249 | protocol::HostRequest::NetRead(_)
1250 | protocol::HostRequest::NetRelease(_)
1251 | protocol::HostRequest::NetClose(_)) => {
1252 let shared = self
1253 .shared
1254 .upgrade()
1255 .ok_or_else(|| refuse("plugin host manager is gone"))?;
1256 if self.cohort != HostCohort::Builtin {
1257 return Err(refuse("MCP broker is builtin-only"));
1258 }
1259 shared
1260 .mcp_broker
1261 .serve(&shared, self.generation, request, cx)
1262 .await
1263 }
1264 other => supervisor::registry_host_request(self, other, &cx),
1265 }
1266 }
1267
1268 fn register(&self, params: &protocol::RegisterParams) -> RegisterResult {
1269 let Some(shared) = self.shared.upgrade() else {
1270 return RegisterResult::Refused {
1271 refused: "plugin host manager is gone".to_string(),
1272 };
1273 };
1274 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1275 return RegisterResult::Refused {
1276 refused: "unknown host cohort".to_string(),
1277 };
1278 };
1279 let slot = runtime.host.lock().expect("host lock");
1280 if runtime.host_generation.load(Ordering::SeqCst) != self.generation {
1281 return RegisterResult::Refused {
1282 refused: "stale host generation".to_string(),
1283 };
1284 }
1285 let mut foreign_owner = false;
1286 let unlisted_creator = self.cohort == HostCohort::Builtin
1287 && params.owner.plugin_id == "host:creator"
1288 && (params.kind != RegisterKind::Tool
1289 || !shared.builtin_modules.iter().any(|module| {
1290 module.id == "creator"
1291 && module
1292 .tools
1293 .iter()
1294 .any(|tool| tool.name == params.spec.name)
1295 }));
1296 let result = {
1297 let mut registry = shared.registry.lock().expect("registry lock");
1298 match registry.owner(&params.owner.plugin_id) {
1299 Some(entry) if entry.cohort != self.cohort => {
1300 foreign_owner = true;
1301 Err(format!(
1302 "owner `{}` belongs to the {} cohort, not this host's {} cohort",
1303 params.owner.plugin_id,
1304 entry.cohort.host_label(),
1305 self.cohort.host_label()
1306 ))
1307 }
1308 _ if unlisted_creator => Err(format!(
1309 "built-in module `creator` may not register unlisted tool `{}`",
1310 params.spec.name
1311 )),
1312 _ => registry.register(params),
1313 }
1314 };
1315 drop(slot);
1316 match result {
1317 Ok(handle) => RegisterResult::Admitted { handle },
1318 Err(reason) => {
1319 let kind = match params.kind {
1320 RegisterKind::Tool => "tool",
1321 RegisterKind::Command => "command",
1322 RegisterKind::Hook => "hook",
1323 RegisterKind::PromptSection => "prompt section",
1324 RegisterKind::PromptTemplate => "prompt template",
1325 RegisterKind::SkillRoot => "skill root",
1326 RegisterKind::AvatarPack => "avatar pack",
1327 RegisterKind::ShellHook => "shell hook",
1328 RegisterKind::McpServer => "MCP server",
1329 };
1330 let message = format!(
1331 "plugin `{}` {kind} `{}` refused: {reason}",
1332 params.owner.plugin_id, params.spec.name
1333 );
1334 // A host naming the other tier's owner does not get to write
1335 // under that owner's id: the refusal is a global diagnostic.
1336 if foreign_owner {
1337 shared.diagnostic(message);
1338 } else {
1339 shared.plugin_diagnostic(&params.owner.plugin_id, message);
1340 }
1341 RegisterResult::Refused { refused: reason }
1342 }
1343 }
1344 }
1345
1346 fn unregister(&self, params: &protocol::UnregisterParams) {
1347 if let Some(shared) = self.shared.upgrade() {
1348 shared
1349 .registry
1350 .lock()
1351 .expect("registry lock")
1352 .unregister(&params.owner, params.handle);
1353 }
1354 }
1355
1356 fn faulted(&self, params: &protocol::FaultedParams) {
1357 let Some(shared) = self.shared.upgrade() else {
1358 return;
1359 };
1360 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1361 return;
1362 };
1363 let slot = runtime.host.lock().expect("host lock");
1364 if runtime.host_generation.load(Ordering::SeqCst) != self.generation {
1365 return;
1366 }
1367 if !shared
1368 .registry
1369 .lock()
1370 .expect("registry lock")
1371 .mark_failed(&params.owner, OwnerState::Faulted(params.error.clone()))
1372 {
1373 return;
1374 }
1375 if let HostSlot::Ready(host) | HostSlot::Unresponsive(host) = &*slot {
1376 host.revoke_calls_of(&params.owner.plugin_id);
1377 }
1378 drop(slot);
1379 shared.revoke_owner_state(&params.owner.plugin_id);
1380 dsh_remote::withdraw_owner(&params.owner);
1381 shared.plugin_diagnostic(
1382 &params.owner.plugin_id,
1383 format!(
1384 "plugin `{}` faulted and was disposed: {}",
1385 params.owner.plugin_id, params.error
1386 ),
1387 );
1388 }
1389
1390 fn exited(&self, host_generation: u64, reason: String, stderr_tail: String) {
1391 let Some(shared) = self.shared.upgrade() else {
1392 return;
1393 };
1394 // Whatever this process was asked for, nothing it held is good again.
1395 shared.core_calls.revoke_host(&self.cohort, host_generation);
1396 shared
1397 .execution_broker
1398 .revoke_host(&self.cohort, host_generation);
1399 shared.mcp_users.fetch_sub(
1400 shared.mcp_broker.revoke_host(&self.cohort, host_generation),
1401 Ordering::SeqCst,
1402 );
1403 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1404 return;
1405 };
1406 let retry = {
1407 let mut agent_cohorts_guard = if self.cohort.agent_project_path().is_some() {
1408 Some(shared.agent_cohorts.lock().expect("agent cohorts lock"))
1409 } else {
1410 None
1411 };
1412 let mut slot = runtime.host.lock().expect("host lock");
1413 if runtime.host_generation.load(Ordering::SeqCst) != host_generation
1414 || !matches!(&*slot, HostSlot::Ready(_) | HostSlot::Unresponsive(_))
1415 {
1416 return;
1417 }
1418 let had_active_owners = shared
1419 .registry
1420 .lock()
1421 .expect("registry lock")
1422 .host_exited(&self.cohort, &reason);
1423
1424 if !had_active_owners && reason == NO_DESIRED_OWNERS_REASON {
1425 *slot = HostSlot::Idle;
1426 if let Some(path) = self.cohort.agent_project_path()
1427 && let Some(ref mut cohorts) = agent_cohorts_guard
1428 {
1429 cohorts.remove(&path);
1430 }
1431 None
1432 } else {
1433 let mut supervision = runtime.supervision.lock().expect("supervision lock");
1434 let planned = supervision.planned_restart.take() == Some(host_generation)
1435 && reason == DIRTY_RESTART_REASON;
1436 let restart = if planned {
1437 supervision.retry_ticket += 1;
1438 true
1439 } else {
1440 supervision.record_crash(Instant::now(), &shared.options.supervision)
1441 };
1442 *slot = if restart {
1443 HostSlot::Restarting {
1444 reason: reason.clone(),
1445 }
1446 } else {
1447 HostSlot::Failed {
1448 reason: format!("crash budget exhausted: {reason}"),
1449 stderr_tail,
1450 }
1451 };
1452 restart.then_some((supervision.retry_ticket, supervision.policy))
1453 }
1454 };
1455 shared.diagnostic(format!("{} {reason}", self.cohort.host_label()));
1456 if let Some((ticket, policy)) = retry {
1457 schedule_restart(
1458 &shared,
1459 self.cohort.clone(),
1460 host_generation,
1461 ticket,
1462 policy,
1463 );
1464 }
1465 shared.reconcile_settled.notify_waiters();
1466 let has_pending = !shared
1467 .pending_migrations
1468 .lock()
1469 .expect("pending migrations lock")
1470 .is_empty();
1471 if has_pending && self.cohort.agent_project_path().is_some() {
1472 ExtensionHostManager::reconcile_shared_in_background(&shared);
1473 }
1474 }
1475
1476 fn log(&self, params: &protocol::LogParams) {
1477 if !matches!(params.level.as_str(), "warn" | "error") {
1478 return;
1479 }
1480 let Some(plugin_id) = params.plugin_id.as_deref() else {
1481 return;
1482 };
1483 let Some(shared) = self.shared.upgrade() else {
1484 return;
1485 };
1486 let Some(runtime) = shared.cohort_runtime(&self.cohort) else {
1487 return;
1488 };
1489 let _slot = runtime.host.lock().expect("host lock");
1490 // Only for an owner of this host's own tier: a host cannot put
1491 // diagnostics under the other tier's owner ids.
1492 if runtime.host_generation.load(Ordering::SeqCst) != self.generation
1493 || !shared
1494 .registry
1495 .lock()
1496 .expect("registry lock")
1497 .owner(plugin_id)
1498 .is_some_and(|entry| entry.cohort == self.cohort)
1499 {
1500 return;
1501 }
1502 shared.plugin_diagnostic(plugin_id, format!("{}: {}", params.level, params.msg));
1503 }
1504 }
1505
1506 /// One scheduled retry owns a ticket, so explicit retry/shutdown and a newer
1507 /// host generation invalidate it. The existing reconcile lock owns replay.
1508 fn schedule_restart(
1509 shared: &Arc<ManagerShared>,
1510 cohort: HostCohort,
1511 generation: u64,
1512 ticket: u64,
1513 policy: bool,
1514 ) {
1515 let weak = Arc::downgrade(shared);
1516 let backoff = shared.options.supervision.restart_backoff;
1517 tokio::spawn(async move {
1518 tokio::time::sleep(backoff).await;
1519 let Some(shared) = weak.upgrade() else {
1520 return;
1521 };
1522 {
1523 let _serial = shared.sync_lock.lock().await;
1524 let Some(runtime) = shared.cohort_runtime(&cohort) else {
1525 return;
1526 };
1527 let mut slot = runtime.host.lock().expect("host lock");
1528 if runtime.host_generation.load(Ordering::SeqCst) != generation
1529 || runtime
1530 .supervision
1531 .lock()
1532 .expect("supervision lock")
1533 .retry_ticket
1534 != ticket
1535 || !matches!(&*slot, HostSlot::Restarting { .. })
1536 {
1537 return;
1538 }
1539 *slot = HostSlot::Idle;
1540 }
1541 let manager = ExtensionHostManager { shared };
1542 if let Err(error) = manager.reconcile_with_policy(policy).await {
1543 manager.shared.diagnostic(error);
1544 }
1545 });
1546 }
1547
1548 fn set_host_health(
1549 shared: &ManagerShared,
1550 cohort: &HostCohort,
1551 generation: u64,
1552 unresponsive: bool,
1553 ) -> bool {
1554 let Some(runtime) = shared.cohort_runtime(cohort) else {
1555 return false;
1556 };
1557 let mut slot = runtime.host.lock().expect("host lock");
1558 if runtime.host_generation.load(Ordering::SeqCst) != generation {
1559 return false;
1560 }
1561 let host = match &*slot {
1562 HostSlot::Ready(host) | HostSlot::Unresponsive(host) => Arc::clone(host),
1563 _ => return false,
1564 };
1565 *slot = if unresponsive {
1566 HostSlot::Unresponsive(host)
1567 } else {
1568 HostSlot::Ready(host)
1569 };
1570 true
1571 }
1572
1573 fn restart_dirty_host_when_idle(
1574 shared: &ManagerShared,
1575 host: &Arc<HostProcess>,
1576 generation: u64,
1577 ) -> bool {
1578 // Reconciliation owns activation/deactivation between wire requests too.
1579 let Ok(_serial) = shared.sync_lock.try_lock() else {
1580 return false;
1581 };
1582 let Some(runtime) = shared.cohort_runtime(&host.cohort) else {
1583 return false;
1584 };
1585 let slot = runtime.host.lock().expect("host lock");
1586 if runtime.host_generation.load(Ordering::SeqCst) != generation
1587 || !matches!(&*slot, HostSlot::Ready(current) if Arc::ptr_eq(current, host))
1588 {
1589 return false;
1590 }
1591 let mut supervision = runtime.supervision.lock().expect("supervision lock");
1592 let unload = match &host.cohort {
1593 HostCohort::Plugin(PluginCohort::Reviewed) => shared
1594 .registry
1595 .lock()
1596 .expect("registry lock")
1597 .host_services_await_restart(&host.cohort),
1598 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
1599 let registry = shared.registry.lock().expect("registry lock");
1600 registry.cohort_departed(&host.cohort)
1601 && registry
1602 .owners()
1603 .any(|entry| entry.loaded_in_cohort(&host.cohort))
1604 }
1605 HostCohort::Builtin => false,
1606 };
1607 if !(supervision.dirty_restart_pending || unload)
1608 || !host.terminate_if_idle(DIRTY_RESTART_REASON)
1609 {
1610 return false;
1611 }
1612 supervision.planned_restart = Some(generation);
1613 true
1614 }
1615
1616 /// A monitor never owns the manager. Dropping the manager or changing host
1617 /// generation stops its monitor; pending calls are never retried here.
1618 fn monitor_host(shared: &Arc<ManagerShared>, host: &Arc<HostProcess>, generation: u64) {
1619 let cohort = host.cohort.clone();
1620 let weak = Arc::downgrade(shared);
1621 let host = Arc::clone(host);
1622 let options = shared.options.supervision.clone();
1623 tokio::spawn(async move {
1624 let mut blocked_since = None;
1625 loop {
1626 tokio::time::sleep(options.heartbeat_interval).await;
1627 let Some(shared) = weak.upgrade() else {
1628 return;
1629 };
1630 let Some(runtime) = shared.cohort_runtime(&cohort) else {
1631 return;
1632 };
1633 if runtime.host_generation.load(Ordering::SeqCst) != generation || host.has_exited() {
1634 return;
1635 }
1636 if restart_dirty_host_when_idle(&shared, &host, generation) {
1637 return;
1638 }
1639 // Only where no kernel limit is planned (a macOS Node host).
1640 if host.memory() == supervisor::MemoryEnforcement::Heartbeat
1641 && let Some(resident) = host.pid.and_then(supervisor::resident_bytes)
1642 && resident > host.memory_cap
1643 {
1644 shared.diagnostic(format!(
1645 "{} exceeded its memory cap ({} MiB resident, cap {} MiB); killed",
1646 cohort.host_label(),
1647 resident / (1024 * 1024),
1648 host.memory_cap / (1024 * 1024)
1649 ));
1650 drop(shared);
1651 host.terminate("exceeded the memory cap".into());
1652 return;
1653 }
1654 drop(shared);
1655 let (id, mut answer) = match host.start_request(CoreRequest::Ping, None) {
1656 Ok(request) => {
1657 blocked_since = None;
1658 request
1659 }
1660 Err(supervisor::HostCallError::Busy) => {
1661 // A full outbound queue can itself be caused by a hung
1662 // host. Bound that wait too instead of skipping forever.
1663 let elapsed = blocked_since.get_or_insert_with(Instant::now).elapsed();
1664 if elapsed >= options.hang_timeout {
1665 host.terminate("heartbeat queue remained blocked".into());
1666 return;
1667 }
1668 if elapsed >= options.ping_timeout {
1669 let Some(shared) = weak.upgrade() else {
1670 return;
1671 };
1672 if !set_host_health(&shared, &cohort, generation, true) {
1673 return;
1674 }
1675 }
1676 continue;
1677 }
1678 Err(_) => return,
1679 };
1680 let result = match tokio::time::timeout(options.ping_timeout, &mut answer).await {
1681 Ok(result) => result,
1682 Err(_) => {
1683 let Some(shared) = weak.upgrade() else {
1684 host.forget(id);
1685 return;
1686 };
1687 if !set_host_health(&shared, &cohort, generation, true) {
1688 host.forget(id);
1689 return;
1690 }
1691 drop(shared);
1692 let remaining = options.hang_timeout.saturating_sub(options.ping_timeout);
1693 match tokio::time::timeout(remaining, answer).await {
1694 Ok(result) => result,
1695 Err(_) => {
1696 host.forget(id);
1697 host.terminate("heartbeat timed out".into());
1698 return;
1699 }
1700 }
1701 }
1702 };
1703 host.forget(id);
1704 if !matches!(result, Ok(Ok(serde_json::Value::Object(ref object))) if object.is_empty())
1705 {
1706 if !host.has_exited() {
1707 host.terminate("invalid heartbeat response".into());
1708 }
1709 return;
1710 }
1711 let Some(shared) = weak.upgrade() else {
1712 return;
1713 };
1714 if !set_host_health(&shared, &cohort, generation, false) {
1715 return;
1716 }
1717 }
1718 });
1719 }
1720
1721 /// Supervises at most one extension host per trust tier for this engine
1722 /// process: the plugin tier's, and the builtin tier's once a built-in module
1723 /// asks for it (none does yet).
1724 pub struct ExtensionHostManager {
1725 pub shared: Arc<ManagerShared>,
1726 }
1727
1728 impl ExtensionHostManager {
1729 #[must_use]
1730 pub fn new(options: ExtensionHostOptions) -> Self {
1731 Self::build(options, tier::BUILTIN_MODULES, true)
1732 }
1733
1734 /// A manager with its own built-in module table. Production passes the
1735 /// static table through [`Self::new`]; a test passes one of its own to
1736 /// exercise tier 0 without a production row.
1737 #[cfg(test)]
1738 fn with_builtin_modules(
1739 options: ExtensionHostOptions,
1740 builtin_modules: &'static [BuiltinModule],
1741 ) -> Self {
1742 Self::build(options, builtin_modules, false)
1743 }
1744
1745 fn build(
1746 options: ExtensionHostOptions,
1747 builtin_modules: &'static [BuiltinModule],
1748 materialize_default_builtins: bool,
1749 ) -> Self {
1750 Self {
1751 shared: Arc::new(ManagerShared {
1752 options,
1753 builtin_modules,
1754 materialize_default_builtins,
1755 attachments: Mutex::new(BTreeMap::new()),
1756 next_attachment: AtomicU64::new(0),
1757 registry: Mutex::new(OwnerRegistry::new()),
1758 core_calls: Arc::default(),
1759 engine_handle: OnceLock::new(),
1760 execution_broker: execution::Broker::default(),
1761 harness_users: AtomicU64::new(0),
1762 stock_users: AtomicU64::new(0),
1763 creator_users: AtomicU64::new(0),
1764 mcp_broker: mcp::Broker::default(),
1765 mcp_users: AtomicU64::new(0),
1766 plugin: Arc::new(TierRuntime::new()),
1767 builtin: Arc::new(TierRuntime::new()),
1768 agent_cohorts: Mutex::new(BTreeMap::new()),
1769 agent_host_generation: AtomicU64::new(0),
1770 pending_migrations: Mutex::new(BTreeMap::new()),
1771 sync_lock: tokio::sync::Mutex::new(()),
1772 skill_admission: Arc::new(tokio::sync::Semaphore::new(1)),
1773 diagnostics: Mutex::new(VecDeque::new()),
1774 runtime: Mutex::new(RuntimePin::default()),
1775 plugin_configs: Mutex::new(plugin_config::PluginConfigs::default()),
1776 reconcile_settled: tokio::sync::Notify::new(),
1777 }),
1778 }
1779 }
1780
1781 /// Reuse the Engine's existing runtime; structural commands may leave it unbound.
1782 pub fn bind_engine_handle(&self, handle: tokio::runtime::Handle) {
1783 let _ = self.shared.engine_handle.set(handle);
1784 }
1785
1786 /// The plugin host's state: what `/plugin` and the error a plugin's tool
1787 /// call gets while it is down report.
1788 #[must_use]
1789 pub fn status(&self) -> HostStatus {
1790 self.tier_status(HostTier::Plugin)
1791 }
1792
1793 /// The state of `tier`'s host.
1794 #[must_use]
1795 fn tier_status(&self, tier: HostTier) -> HostStatus {
1796 self.shared
1797 .tier_runtime(tier)
1798 .host
1799 .lock()
1800 .expect("host lock")
1801 .status()
1802 }
1803
1804 /// The pinned runtime's one-line summary, once a host on it has completed
1805 /// the handshake.
1806 #[must_use]
1807 pub fn runtime_summary(&self) -> Option<String> {
1808 self.shared
1809 .runtime
1810 .lock()
1811 .expect("runtime lock")
1812 .pinned
1813 .as_ref()
1814 .map(|(_, summary)| summary.clone())
1815 }
1816
1817 /// How many times this manager has tried to start a host process, both
1818 /// tiers together.
1819 #[must_use]
1820 pub fn spawn_attempts(&self) -> u64 {
1821 self.shared
1822 .all_runtimes()
1823 .iter()
1824 .map(|r| r.spawn_attempts.load(Ordering::SeqCst))
1825 .sum()
1826 }
1827
1828 /// How many times this manager has tried to start `tier`'s host.
1829 #[cfg(test)]
1830 #[must_use]
1831 pub(crate) fn tier_spawn_attempts(&self, tier: HostTier) -> u64 {
1832 self.shared
1833 .tier_runtime(tier)
1834 .spawn_attempts
1835 .load(Ordering::SeqCst)
1836 }
1837
1838 #[must_use]
1839 pub fn diagnostics(&self) -> Vec<String> {
1840 self.shared
1841 .diagnostics
1842 .lock()
1843 .expect("diagnostics lock")
1844 .iter()
1845 .map(|entry| entry.message.clone())
1846 .collect()
1847 }
1848
1849 pub fn native_service_state(&self, authority: &PluginAuthority) -> &'static str {
1850 self.native_service_status(authority).0
1851 }
1852
1853 pub fn native_service_status(
1854 &self,
1855 authority: &PluginAuthority,
1856 ) -> (&'static str, Option<String>) {
1857 let registry = self.shared.registry.lock().expect("registry lock");
1858 let entry = match registry.route_owner(authority) {
1859 Ok(entry) => entry,
1860 Err(state) => return (state, None),
1861 };
1862 match entry.map(|entry| &entry.state) {
1863 Some(OwnerState::Active) => ("active", None),
1864 Some(OwnerState::Activating) => ("activating", None),
1865 Some(OwnerState::Failed(reason)) => {
1866 ("failed", Some(bounded_diagnostic(reason.clone())))
1867 }
1868 Some(OwnerState::Faulted(reason)) => {
1869 ("faulted", Some(bounded_diagnostic(reason.clone())))
1870 }
1871 Some(OwnerState::Revoked) => ("revoked", None),
1872 None => ("not_started", None),
1873 }
1874 }
1875
1876 /// Recent retained diagnostics for exactly this plugin, not a persistent
1877 /// log. The command renderer escapes each field before displaying it.
1878 #[must_use]
1879 pub fn owner_report(&self, plugin_id: &str) -> Option<OwnerReport> {
1880 self.owner_report_for(plugin_id, None)
1881 }
1882
1883 #[must_use]
1884 pub(super) fn owner_report_for(
1885 &self,
1886 plugin_id: &str,
1887 expected_authority: Option<&PluginAuthority>,
1888 ) -> Option<OwnerReport> {
1889 let registry = self.shared.registry.lock().expect("registry lock");
1890 let matching_entry = registry.owner(plugin_id).filter(|entry| {
1891 expected_authority.is_none_or(|expected| {
1892 entry.authority.as_ref().is_some_and(|auth| {
1893 auth.plugin_id == expected.plugin_id
1894 && auth.content_hash == expected.content_hash
1895 && auth.capability_hash == expected.capability_hash
1896 && auth.state_generation == expected.state_generation
1897 && auth.state_path == expected.state_path
1898 })
1899 })
1900 });
1901 let cohort = matching_entry.map(|entry| entry.cohort.clone());
1902 let state = matching_entry.map(|entry| match &entry.state {
1903 OwnerState::Failed(reason) => OwnerState::Failed(bounded_diagnostic(reason.clone())),
1904 OwnerState::Faulted(reason) => OwnerState::Faulted(bounded_diagnostic(reason.clone())),
1905 state => state.clone(),
1906 });
1907 let tools = if state.is_some() {
1908 registry
1909 .live_tools()
1910 .into_iter()
1911 .filter(|tool| tool.owner.plugin_id == plugin_id)
1912 .map(|tool| tool.name)
1913 .collect()
1914 } else {
1915 Vec::new()
1916 };
1917 drop(registry);
1918 let mut diagnostics: Vec<_> = self
1919 .shared
1920 .diagnostics
1921 .lock()
1922 .expect("diagnostics lock")
1923 .iter()
1924 .rev()
1925 .filter(|entry| entry.plugin_id.as_deref() == Some(plugin_id))
1926 .take(20)
1927 .map(|entry| entry.message.clone())
1928 .collect();
1929 diagnostics.reverse();
1930 if state.is_none() && diagnostics.is_empty() {
1931 return None;
1932 }
1933 Some(OwnerReport {
1934 cohort,
1935 state,
1936 tools,
1937 diagnostics,
1938 })
1939 }
1940
1941 #[cfg(any(test, feature = "test-support"))]
1942 #[must_use]
1943 pub fn live_tool_names(&self) -> Vec<String> {
1944 self.shared
1945 .registry
1946 .lock()
1947 .expect("registry lock")
1948 .live_tools()
1949 .into_iter()
1950 .map(|tool| tool.name)
1951 .collect()
1952 }
1953
1954 #[cfg(any(test, feature = "test-support"))]
1955 #[must_use]
1956 pub fn live_command_names(&self) -> Vec<String> {
1957 self.shared
1958 .registry
1959 .lock()
1960 .expect("registry lock")
1961 .live_commands()
1962 .into_iter()
1963 .map(|command| command.name)
1964 .collect()
1965 }
1966
1967 #[cfg(any(test, feature = "test-support"))]
1968 #[must_use]
1969 pub fn owner_state(&self, plugin_id: &str) -> Option<OwnerState> {
1970 self.shared
1971 .registry
1972 .lock()
1973 .expect("registry lock")
1974 .owner(plugin_id)
1975 .map(|entry| entry.state.clone())
1976 }
1977
1978 #[cfg(any(test, feature = "test-support"))]
1979 pub fn register_test_creator_tool(&self, name: &str) {
1980 let mut reg = self.shared.registry.lock().expect("registry lock");
1981 let owner = reg
1982 .begin_owner(
1983 HostCohort::Builtin,
1984 "host:creator",
1985 "creator",
1986 None,
1987 "test-creator-hash",
1988 )
1989 .expect("creator owner");
1990 reg.register(&protocol::RegisterParams {
1991 scope: None,
1992 owner: owner.clone(),
1993 kind: protocol::RegisterKind::Tool,
1994 spec: protocol::RegisterSpecWire {
1995 name: name.to_string(),
1996 description: "creator tool".into(),
1997 input_schema: serde_json::json!({"type": "object", "properties": {}})
1998 .as_object()
1999 .cloned(),
2000 argument_hint: None,
2001 },
2002 })
2003 .expect("register creator tool");
2004 reg.mark_active(&owner);
2005 }
2006
2007 /// Install the user's `[plugins]` settings (boot), and the config file a
2008 /// later `/plugin reload` re-reads them from. Takes effect at the next
2009 /// reconcile: a plugin whose settings changed is re-activated.
2010 pub fn set_plugin_settings(
2011 &self,
2012 settings: &BTreeMap<String, codewhale_config::extension_host::PluginSettings>,
2013 source: Option<PathBuf>,
2014 ) {
2015 self.shared
2016 .plugin_configs
2017 .lock()
2018 .expect("plugin configs lock")
2019 .replace(settings, source);
2020 }
2021
2022 /// Read `[plugins]` from the config file again, if boot named one. A file
2023 /// that cannot be read or parsed keeps the previous settings.
2024 async fn reload_plugin_settings(&self) {
2025 let Some(path) = self
2026 .shared
2027 .plugin_configs
2028 .lock()
2029 .expect("plugin configs lock")
2030 .source()
2031 else {
2032 return;
2033 };
2034 let read_path = path.clone();
2035 match tokio::task::spawn_blocking(move || {
2036 codewhale_runtime::config::read_plugin_settings(&read_path)
2037 })
2038 .await
2039 {
2040 Ok(Ok(settings)) => self
2041 .shared
2042 .plugin_configs
2043 .lock()
2044 .expect("plugin configs lock")
2045 .replace_reloaded(&settings),
2046 Ok(Err(reason)) => self.shared.diagnostic(format!(
2047 "plugin settings were not reloaded ({reason}); keeping the previous ones"
2048 )),
2049 Err(error) => self.shared.diagnostic(format!(
2050 "plugin settings were not reloaded from {}: {error}",
2051 path.display()
2052 )),
2053 }
2054 }
2055
2056 /// What the user configured for `plugin_name`: the keys (never the values)
2057 /// or why the config is refused. `None` when nothing is configured.
2058 #[must_use]
2059 pub fn plugin_config_summary(&self, plugin_name: &str) -> Option<Result<Vec<String>, String>> {
2060 self.shared
2061 .plugin_configs
2062 .lock()
2063 .expect("plugin configs lock")
2064 .summary(plugin_name)
2065 }
2066
2067 /// An explicit plugin mutation retries failed receipts and clears the
2068 /// shared crash budget. Merely opening another engine never does this.
2069 pub fn retry(&self) {
2070 self.retry_cohort(&HostCohort::reviewed());
2071 self.retry_cohort(&HostCohort::Builtin);
2072 }
2073
2074 pub fn retry_cohort(&self, cohort: &HostCohort) {
2075 if let Some(runtime) = self.shared.cohort_runtime(cohort) {
2076 let mut slot = runtime.host.lock().expect("host lock");
2077 let mut supervision = runtime.supervision.lock().expect("supervision lock");
2078 supervision.crashes.clear();
2079 supervision.launch_failed = false;
2080 supervision.retry_ticket += 1;
2081 if matches!(
2082 &*slot,
2083 HostSlot::Failed { .. } | HostSlot::Restarting { .. }
2084 ) {
2085 *slot = HostSlot::Idle;
2086 }
2087 }
2088 self.shared
2089 .registry
2090 .lock()
2091 .expect("registry lock")
2092 .forget_inactive_for_cohort(cohort);
2093 }
2094
2095 fn retry_launch_on_attach(&self) {
2096 for runtime in self.shared.all_runtimes() {
2097 let mut slot = runtime.host.lock().expect("host lock");
2098 let mut supervision = runtime.supervision.lock().expect("supervision lock");
2099 if matches!(&*slot, HostSlot::Failed { .. })
2100 && supervision.launch_failed
2101 && supervision.last_start.is_some_and(|at| {
2102 at.elapsed() >= self.shared.options.supervision.start_retry_cooldown
2103 })
2104 {
2105 *slot = HostSlot::Idle;
2106 supervision.retry_ticket += 1;
2107 }
2108 }
2109 }
2110
2111 /// Record native tool names from one engine's turn build (the registry
2112 /// before scripts, plugins and extensions are added) so
2113 /// `registry/register` refuses collisions. Additive: engines in one
2114 /// process report different native surfaces and none may shrink the set.
2115 pub fn note_native_names<'a>(&self, names: impl IntoIterator<Item = &'a str>) {
2116 self.shared
2117 .registry
2118 .lock()
2119 .expect("registry lock")
2120 .add_native_names(names);
2121 }
2122
2123 /// Attach an engine whose workspace plugin snapshot is `plugins`. Nothing
2124 /// is reconciled until `HostAttachment::sync` or a background sync.
2125 #[must_use]
2126 pub fn attach(self: &Arc<Self>, plugins: Arc<PluginRegistry>) -> HostAttachment {
2127 self.attach_with_authority(plugins, None)
2128 }
2129
2130 pub fn attach_plugin_route(
2131 self: &Arc<Self>,
2132 plugins: Arc<PluginRegistry>,
2133 authority: PluginAuthority,
2134 ) -> HostAttachment {
2135 self.attach_with_authority(plugins, Some(Arc::new(authority)))
2136 }
2137
2138 fn attach_with_authority(
2139 self: &Arc<Self>,
2140 plugins: Arc<PluginRegistry>,
2141 route_authority: Option<Arc<PluginAuthority>>,
2142 ) -> HostAttachment {
2143 self.retry_launch_on_attach();
2144 let id = self.shared.next_attachment.fetch_add(1, Ordering::SeqCst) + 1;
2145 self.shared
2146 .attachments
2147 .lock()
2148 .expect("attachments lock")
2149 .insert(
2150 id,
2151 AttachmentState {
2152 route_authority,
2153 plugins: Arc::new(plugins.bind_caller(
2154 codewhale_plugins::composition_scope::SelectionRevision {
2155 attachment_id: id,
2156 revision: 1,
2157 },
2158 )),
2159 desired: BTreeMap::new(),
2160 selection: codewhale_plugins::composition_scope::CompositionSelection::default(
2161 ),
2162 revision: 1,
2163 selection_cancel: CancellationToken::new(),
2164 settled: None,
2165 session_id: None,
2166 agent_id: None,
2167 creator_demanded: false,
2168 },
2169 );
2170 command::bump_epoch();
2171 HostAttachment {
2172 id,
2173 manager: Arc::clone(self),
2174 }
2175 }
2176
2177 /// Re-scan plugins and optionally wait for one plugin's native owner to settle.
2178 pub async fn plugins_changed_and_wait(
2179 self: &Arc<Self>,
2180 plugins: &Arc<PluginRegistry>,
2181 plugin_id: Option<&str>,
2182 expected_authority: Option<&PluginAuthority>,
2183 exempt_invocation_id: Option<u64>,
2184 wait_for_owner: bool,
2185 cancel: &CancellationToken,
2186 timeout: Duration,
2187 ) -> Result<Option<OwnerReport>, String> {
2188 self.refresh_workspace_except(plugins, exempt_invocation_id);
2189 if !activation::extension_host_policy_enabled() {
2190 return if wait_for_owner {
2191 Err(
2192 "the plugin host is switched off in this process, so native plugin code did not start"
2193 .to_string(),
2194 )
2195 } else {
2196 Ok(None)
2197 };
2198 }
2199 if wait_for_owner && self.attached_engines() == 0 {
2200 if let Some(pid) = plugin_id
2201 && let Some(report) = self.owner_report_for(pid, expected_authority)
2202 && !matches!(report.state, Some(OwnerState::Activating) | None)
2203 {
2204 return Ok(Some(report));
2205 }
2206 return Err("the plugin host is not running for this session".to_string());
2207 }
2208 self.revoke_stale_or_removed_owners(plugins);
2209 self.retry_cohort(&HostCohort::reviewed());
2210 self.retry_cohort(&HostCohort::agent(plugins.workspace()));
2211 if self.attached_engines() == 0 {
2212 return Ok(None);
2213 }
2214 let policy = activation::extension_host_policy_enabled();
2215 let reconcile_manager = ExtensionHostManager {
2216 shared: Arc::clone(&self.shared),
2217 };
2218 let mut reconcile_task =
2219 tokio::spawn(async move { reconcile_manager.reconcile_with_policy(policy).await });
2220 let reconcile_res = tokio::select! {
2221 biased;
2222 () = cancel.cancelled() => {
2223 self.reload_and_reconcile_in_background();
2224 return Err(
2225 "cancelled while waiting for the plugin host to start plugin code"
2226 .to_string(),
2227 );
2228 }
2229 res = &mut reconcile_task => match res {
2230 Ok(res) => res,
2231 Err(error) => Err(format!("plugin host reconcile task failed: {error}")),
2232 },
2233 };
2234 let deadline = tokio::time::Instant::now() + timeout;
2235 if !wait_for_owner {
2236 return Ok(None);
2237 }
2238 let Some(pid) = plugin_id else {
2239 reconcile_res?;
2240 return Ok(None);
2241 };
2242 let target_cohort = plugins
2243 .get(pid)
2244 .map(|plugin| {
2245 if matches!(
2246 plugin.approved_by,
2247 Some(codewhale_plugins::host_services::PluginApprover::Agent(_))
2248 ) {
2249 HostCohort::agent(plugins.workspace())
2250 } else {
2251 HostCohort::reviewed()
2252 }
2253 })
2254 .unwrap_or_else(HostCohort::reviewed);
2255 loop {
2256 let settled = self.shared.reconcile_settled.notified();
2257 tokio::pin!(settled);
2258 settled.as_mut().enable();
2259 let report = self.owner_report_for(pid, expected_authority);
2260 let migration_pending = self
2261 .shared
2262 .pending_migrations
2263 .lock()
2264 .expect("pending migrations lock")
2265 .contains_key(pid);
2266 if !migration_pending {
2267 if let Some(report) = report {
2268 if !matches!(report.state, Some(OwnerState::Activating) | None) {
2269 return Ok(Some(report));
2270 }
2271 } else {
2272 let (slot_status, restarting_in_flight) = self
2273 .shared
2274 .cohort_runtime(&target_cohort)
2275 .map(|rt| {
2276 let slot = rt.host.lock().expect("host lock");
2277 let status = slot.status();
2278 let retiring = matches!(
2279 &*slot,
2280 HostSlot::Ready(h) | HostSlot::Unresponsive(h) if h.is_retiring()
2281 );
2282 let (planned, dirty_pending) = {
2283 let sup = rt.supervision.lock().expect("supervision lock");
2284 (sup.planned_restart.is_some(), sup.dirty_restart_pending)
2285 };
2286 (Some(status), retiring || planned || dirty_pending)
2287 })
2288 .unwrap_or((None, false));
2289 if let Some(HostStatus::Failed { reason, .. }) = slot_status {
2290 return Err(reason);
2291 }
2292 if let Err(err) = &reconcile_res
2293 && !restarting_in_flight
2294 && !matches!(
2295 slot_status,
2296 Some(HostStatus::Starting | HostStatus::Restarting { .. })
2297 )
2298 {
2299 return Err(err.clone());
2300 }
2301 let is_desired = self
2302 .shared
2303 .attachments
2304 .lock()
2305 .expect("attachments lock")
2306 .values()
2307 .any(|state| state.desired.contains_key(pid));
2308 if !is_desired
2309 && !restarting_in_flight
2310 && !matches!(
2311 slot_status,
2312 Some(HostStatus::Starting | HostStatus::Restarting { .. })
2313 )
2314 {
2315 return Err(
2316 "the plugin host did not select this plugin for activation".to_string()
2317 );
2318 }
2319 if !restarting_in_flight
2320 && matches!(
2321 slot_status,
2322 Some(
2323 HostStatus::Idle | HostStatus::Ready { .. } | HostStatus::Disabled
2324 ) | None
2325 )
2326 {
2327 return Err(
2328 "plugin activation did not register an owner in the plugin host"
2329 .to_string(),
2330 );
2331 }
2332 }
2333 }
2334 tokio::select! {
2335 biased;
2336 () = cancel.cancelled() => {
2337 return Err(
2338 "cancelled while waiting for the plugin host to start plugin code"
2339 .to_string(),
2340 );
2341 }
2342 () = tokio::time::sleep_until(deadline) => {
2343 return Err(
2344 "the plugin host did not finish starting native plugin code in time"
2345 .to_string(),
2346 );
2347 }
2348 () = settled => {}
2349 }
2350 }
2351 }
2352
2353 pub fn attached_engines(&self) -> usize {
2354 self.shared
2355 .attachments
2356 .lock()
2357 .expect("attachments lock")
2358 .len()
2359 }
2360
2361 /// Replace the snapshot of every engine attached to `plugins`'s
2362 /// workspace: a plugin was enabled, disabled, trusted or revoked there.
2363 fn refresh_workspace(&self, plugins: &Arc<PluginRegistry>) {
2364 self.refresh_workspace_except(plugins, None);
2365 }
2366
2367 fn refresh_workspace_except(
2368 &self,
2369 plugins: &Arc<PluginRegistry>,
2370 exempt_invocation_id: Option<u64>,
2371 ) {
2372 let mut ids_to_revoke = Vec::new();
2373 {
2374 let mut attachments = self.shared.attachments.lock().expect("attachments lock");
2375 for (&id, state) in attachments.iter_mut() {
2376 let next = if state.plugins.workspace() == plugins.workspace() {
2377 Some(plugins.retain_native_selection_from(state.plugins.as_ref()))
2378 } else {
2379 state.plugins.sync_user_plugins_from(plugins.as_ref())
2380 };
2381 let Some(next) = next else {
2382 continue;
2383 };
2384 ids_to_revoke.push(id);
2385 state.selection_cancel.cancel();
2386 state.selection_cancel = CancellationToken::new();
2387 state.revision += 1;
2388 let attachment_id = state
2389 .plugins
2390 .caller_selection()
2391 .expect("attached caller")
2392 .attachment_id;
2393 state.plugins = Arc::new(next.bind_caller(
2394 codewhale_plugins::composition_scope::SelectionRevision {
2395 attachment_id,
2396 revision: state.revision,
2397 },
2398 ));
2399 state.desired.clear();
2400 state.selection = Default::default();
2401 }
2402 }
2403 for id in ids_to_revoke {
2404 self.shared
2405 .core_calls
2406 .revoke_attachment_except(id, exempt_invocation_id);
2407 }
2408 command::bump_epoch();
2409 }
2410
2411 fn revoke_stale_or_removed_owners(self: &Arc<Self>, plugins: &PluginRegistry) {
2412 let mut plugin_lookup: HashMap<&str, &LoadedPlugin> = HashMap::new();
2413 for plugin in plugins.list() {
2414 plugin_lookup.insert(plugin.id.as_str(), plugin);
2415 }
2416 let plugins_state_path = plugins.state_path();
2417 let to_revoke: Vec<(String, OwnerRef, HostCohort, bool)> = {
2418 let registry = self.shared.registry.lock().expect("registry lock");
2419 registry
2420 .owners()
2421 .filter(|entry| entry.tier() == HostTier::Plugin)
2422 .filter_map(|entry| {
2423 let auth = entry.authority.as_ref()?;
2424 let same_workspace = auth.workspace == plugins.workspace();
2425 let shared_user_scope = (entry.owner.plugin_id.starts_with("user/")
2426 || entry.owner.plugin_id.starts_with("builtin/"))
2427 && plugins_state_path.is_some_and(|sp| auth.state_path == sp);
2428 if !same_workspace && !shared_user_scope {
2429 return None;
2430 }
2431 let current = plugin_lookup.get(entry.owner.plugin_id.as_str()).copied();
2432 let matches_current = current.is_some_and(|plugin| {
2433 let expected_cohort = HostCohort::from_plugin_cohort(
2434 codewhale_plugins::host_services::cohort_of(
2435 plugin.approved_by.as_ref(),
2436 ),
2437 );
2438 plugin.active()
2439 && plugin.inventory.native > 0
2440 && !plugin.outside_reach
2441 && entry.cohort == expected_cohort
2442 && plugin.content_hash == auth.content_hash
2443 && plugin.capability_hash == auth.capability_hash
2444 && plugin.state_generation == auth.state_generation
2445 && plugins_state_path.is_some_and(|sp| sp == auth.state_path)
2446 });
2447 let promote_to_reviewed =
2448 matches!(entry.cohort, HostCohort::Plugin(PluginCohort::Agent { .. }))
2449 && current.is_some_and(|plugin| {
2450 let expected_cohort = HostCohort::from_plugin_cohort(
2451 codewhale_plugins::host_services::cohort_of(
2452 plugin.approved_by.as_ref(),
2453 ),
2454 );
2455 plugin.active()
2456 && plugin.inventory.native > 0
2457 && !plugin.outside_reach
2458 && expected_cohort == HostCohort::reviewed()
2459 });
2460 (!matches_current).then(|| {
2461 (
2462 entry.owner.plugin_id.clone(),
2463 entry.owner.clone(),
2464 entry.cohort.clone(),
2465 promote_to_reviewed,
2466 )
2467 })
2468 })
2469 .collect()
2470 };
2471 if to_revoke.is_empty() {
2472 return;
2473 }
2474 if to_revoke.iter().any(|(_, _, _, promote)| *promote) {
2475 let mut migrations = self
2476 .shared
2477 .pending_migrations
2478 .lock()
2479 .expect("pending migrations lock");
2480 for (plugin_id, _, cohort, promote) in &to_revoke {
2481 if *promote {
2482 migrations.insert(plugin_id.clone(), cohort.clone());
2483 }
2484 }
2485 }
2486 let mut live_owners = Vec::new();
2487 {
2488 let mut registry = self.shared.registry.lock().expect("registry lock");
2489 for (plugin_id, owner, cohort, _) in &to_revoke {
2490 if registry.revoke_owner(plugin_id).is_some() {
2491 live_owners.push((owner.clone(), cohort.clone()));
2492 }
2493 registry.forget_owner(plugin_id);
2494 }
2495 }
2496 for (plugin_id, owner, cohort, _) in &to_revoke {
2497 self.shared.revoke_owner_state(plugin_id);
2498 self.shared.clear_plugin_diagnostics(plugin_id);
2499 dsh_remote::withdraw_owner(owner);
2500 if let Ok(host) = self.shared.ready_host(cohort) {
2501 host.revoke_calls_of(plugin_id);
2502 }
2503 }
2504 if let Ok(handle) = tokio::runtime::Handle::try_current() {
2505 for (owner, cohort) in live_owners {
2506 let Ok(host) = self.shared.ready_host(&cohort) else {
2507 continue;
2508 };
2509 let shared = Arc::clone(&self.shared);
2510 handle.spawn(async move {
2511 shared.deactivate_owner(&host, &owner).await;
2512 });
2513 }
2514 }
2515 }
2516
2517 /// Add the live tools of the owners attachment `id` desires to
2518 /// `tool_registry`, *after* natives and `~/.codewhale/tools` scripts. A
2519 /// name already present is skipped with a diagnostic —
2520 /// `ToolRegistry::register` would silently overwrite it. Returns the
2521 /// names added.
2522 fn install_tools_for(
2523 &self,
2524 id: u64,
2525 tool_registry: &mut crate::tools::ToolRegistry,
2526 ) -> Vec<String> {
2527 let desired = self
2528 .shared
2529 .attachments
2530 .lock()
2531 .expect("attachments lock")
2532 .get(&id)
2533 .map(|state| state.selection.clone())
2534 .unwrap_or_default();
2535 if desired.desired.is_empty() {
2536 return Vec::new();
2537 }
2538 let tools: Vec<ToolRegistration> = self
2539 .shared
2540 .registry
2541 .lock()
2542 .expect("registry lock")
2543 .live_tools()
2544 .into_iter()
2545 .filter(|tool| {
2546 tool.tier() != HostTier::Builtin
2547 && desired.includes(
2548 &tool.owner.plugin_id,
2549 &tool.content_hash,
2550 tool.scope.as_ref(),
2551 )
2552 })
2553 .collect();
2554 if tools.is_empty() {
2555 return Vec::new();
2556 }
2557 for gate in dsh_broker::BrokerActTool::all() {
2558 if tool_registry.get(gate.name()).is_none() {
2559 tool_registry.register(gate);
2560 }
2561 }
2562 let taken: HashSet<String> = tool_registry
2563 .names()
2564 .into_iter()
2565 .map(str::to_ascii_lowercase)
2566 .collect();
2567 let mut installed = Vec::new();
2568 let mut counts = BTreeMap::new();
2569 for tool in &tools {
2570 *counts
2571 .entry(tool.name.to_ascii_lowercase())
2572 .or_insert(0usize) += 1;
2573 }
2574 for registration in tools {
2575 if counts[&registration.name.to_ascii_lowercase()] != 1 {
2576 self.shared.plugin_diagnostic(&registration.owner.plugin_id,format!("Native tool `{}` is ambiguous in this caller; rename the selected definitions",registration.name));
2577 continue;
2578 }
2579 if taken.contains(&registration.name.to_ascii_lowercase()) {
2580 let origin = tool_registry
2581 .get(&registration.name)
2582 .map(|existing| existing.registration_origin().into_owned())
2583 .unwrap_or_else(|| "another tool".to_string());
2584 self.shared.plugin_diagnostic(&registration.owner.plugin_id, format!(
2585 "plugin tool `{}` from `{}` skipped: the name is already registered by {origin}",
2586 registration.name, registration.plugin_name
2587 ));
2588 continue;
2589 }
2590 installed.push(registration.name.clone());
2591 tool_registry.register(Arc::new(tool::HostToolSpec::for_selection(
2592 registration,
2593 Arc::clone(&self.shared),
2594 desired.revision,
2595 )));
2596 }
2597 if !installed.is_empty() && tool_registry.get(dsh_network::SEND_TOOL).is_none() {
2598 tool_registry.register(Arc::new(dsh_network::SendConsent));
2599 }
2600 installed
2601 }
2602
2603 /// The live commands of the owners that engines attached for `workspace`
2604 /// desire, each bound to the reviewed bytes that engine desires: what the
2605 /// user registry loads for that workspace. A workspace never sees another
2606 /// workspace's project plugins' commands.
2607 pub fn commands_for_workspace(&self, workspace: &Path) -> Vec<command::ExtensionCommandEntry> {
2608 let mut desired: BTreeSet<(String, String)> = BTreeSet::new();
2609 for state in self
2610 .shared
2611 .attachments
2612 .lock()
2613 .expect("attachments lock")
2614 .values()
2615 .filter(|state| state.plugins.workspace() == workspace)
2616 {
2617 desired.extend(
2618 state
2619 .desired
2620 .iter()
2621 .map(|(plugin_id, hash)| (plugin_id.clone(), hash.clone())),
2622 );
2623 }
2624 if desired.is_empty() {
2625 return Vec::new();
2626 }
2627 let registry = self.shared.registry.lock().expect("registry lock");
2628 registry
2629 .live_commands()
2630 .into_iter()
2631 .filter(|command| {
2632 command.scope.is_none()
2633 && desired.contains(&(
2634 command.owner.plugin_id.clone(),
2635 command.content_hash.clone(),
2636 ))
2637 })
2638 .filter_map(|registration| {
2639 let authority = registry.authority_for(&registration.owner)?;
2640 Some(command::ExtensionCommandEntry {
2641 registration,
2642 authority,
2643 workspace: workspace.to_path_buf(),
2644 selection: None,
2645 })
2646 })
2647 .collect()
2648 }
2649
2650 pub fn commands_for_plugins(
2651 &self,
2652 plugins: &PluginRegistry,
2653 ) -> Vec<command::ExtensionCommandEntry> {
2654 let Some(revision) = plugins.caller_selection() else {
2655 return self.commands_for_workspace(plugins.workspace());
2656 };
2657 let selected = self.shared.selection(revision.attachment_id);
2658 if selected.revision != Some(revision) {
2659 return Vec::new();
2660 }
2661 let registry = self.shared.registry.lock().expect("registry lock");
2662 let commands: Vec<_> = registry
2663 .live_commands()
2664 .into_iter()
2665 .filter(|command| {
2666 selected.includes(
2667 &command.owner.plugin_id,
2668 &command.content_hash,
2669 command.scope.as_ref(),
2670 )
2671 })
2672 .collect();
2673 let mut counts = BTreeMap::new();
2674 for command in &commands {
2675 *counts.entry(command.name.clone()).or_insert(0usize) += 1;
2676 }
2677 commands
2678 .into_iter()
2679 .filter(|command| counts[&command.name] == 1)
2680 .filter_map(|registration| {
2681 Some(command::ExtensionCommandEntry {
2682 authority: registry.authority_for(&registration.owner)?,
2683 registration,
2684 workspace: plugins.workspace().to_path_buf(),
2685 selection: Some(revision),
2686 })
2687 })
2688 .collect()
2689 }
2690
2691 /// Reconcile without waiting (turn builds, session start,
2692 /// plugin changes).
2693 pub fn reconcile_in_background(self: &Arc<Self>) {
2694 Self::reconcile_shared_in_background(&self.shared);
2695 }
2696
2697 pub fn reconcile_shared_in_background(shared: &Arc<ManagerShared>) {
2698 if tokio::runtime::Handle::try_current().is_err() {
2699 return;
2700 }
2701 let shared = Arc::clone(shared);
2702 let policy = activation::extension_host_policy_enabled();
2703 tokio::spawn(async move {
2704 let manager = ExtensionHostManager {
2705 shared: Arc::clone(&shared),
2706 };
2707 if let Err(error) = manager.reconcile_with_policy(policy).await {
2708 shared.diagnostic(error);
2709 }
2710 });
2711 }
2712
2713 /// Like [`Self::reconcile_in_background`], after re-reading the plugin
2714 /// settings from the config file: for an explicit plugin reload.
2715 fn reload_and_reconcile_in_background(self: &Arc<Self>) {
2716 if tokio::runtime::Handle::try_current().is_err() {
2717 return;
2718 }
2719 let manager = Arc::clone(self);
2720 let policy = activation::extension_host_policy_enabled();
2721 tokio::spawn(async move {
2722 manager.reload_plugin_settings().await;
2723 if let Err(error) = manager.reconcile_with_policy(policy).await {
2724 manager.shared.diagnostic(error);
2725 }
2726 });
2727 }
2728
2729 /// Reconcile host owners with the reviewed, enabled plugins that declare
2730 /// `native` entries in any attached engine's snapshot: revoke what no
2731 /// attachment desires any more or what changed (synchronously, then ask
2732 /// the host to tear down), spawn the host if needed, activate the rest.
2733 pub async fn reconcile(&self) -> Result<(), String> {
2734 self.reconcile_with_policy(activation::extension_host_policy_enabled())
2735 .await
2736 }
2737
2738 async fn reconcile_with_policy(&self, policy: bool) -> Result<(), String> {
2739 self.reconcile_with_policy_cancel(policy, None).await
2740 }
2741
2742 async fn reconcile_with_policy_cancel(
2743 &self,
2744 policy: bool,
2745 cancel: Option<&CancellationToken>,
2746 ) -> Result<(), String> {
2747 let shared = &self.shared;
2748 struct NotifyOnDrop<'a>(&'a tokio::sync::Notify);
2749 impl Drop for NotifyOnDrop<'_> {
2750 fn drop(&mut self) {
2751 self.0.notify_waiters();
2752 }
2753 }
2754 let _settled_notify = NotifyOnDrop(&shared.reconcile_settled);
2755 let _serial = match cancel {
2756 Some(token) => tokio::select! {
2757 biased;
2758 () = token.cancelled() => return Ok(()),
2759 guard = shared.sync_lock.lock() => guard,
2760 },
2761 None => shared.sync_lock.lock().await,
2762 };
2763 if cancel.is_some_and(CancellationToken::is_cancelled) {
2764 return Ok(());
2765 }
2766 let (desired, errors) = loop {
2767 let snapshots = shared
2768 .attachments
2769 .lock()
2770 .expect("attachments lock")
2771 .iter()
2772 .map(|(id, state)| AttachmentSnapshot {
2773 id: *id,
2774 plugins: state.plugins.clone(),
2775 route_authority: state.route_authority.clone(),
2776 })
2777 .collect();
2778 #[cfg(any(test, feature = "test-support"))]
2779 let env_scope = crate::test_support::env_scope_ticket();
2780 let scan = tokio::task::spawn_blocking(move || {
2781 #[cfg(any(test, feature = "test-support"))]
2782 let _env_scope = crate::test_support::join_env_scope(env_scope);
2783 let _scope = activation::PolicyScope::propagate(policy);
2784 union_of_desired_owners(snapshots)
2785 })
2786 .await
2787 .map_err(|error| format!("plugin scan failed: {error}"))?;
2788 if cancel.is_some_and(CancellationToken::is_cancelled) {
2789 return Ok(());
2790 }
2791 let published = scan.publish(&mut shared.attachments.lock().expect("attachments lock"));
2792 if let Some(published) = published {
2793 break published;
2794 }
2795 // Attach, detach, or workspace refresh raced the blocking scan.
2796 // Rescan before changing either engine views or global owners.
2797 };
2798 for error in errors {
2799 shared.diagnostic(error);
2800 }
2801
2802 // The settings each desired plugin would be activated with now. Read
2803 // before the registry lock: the settings lock is never held with it.
2804 let wanted_config: BTreeMap<String, String> = {
2805 let configs = shared.plugin_configs.lock().expect("plugin configs lock");
2806 desired
2807 .iter()
2808 .map(|(plugin_id, want)| {
2809 (
2810 plugin_id.clone(),
2811 plugin_config::activation_hash(&configs.select(&want.plugin_name)),
2812 )
2813 })
2814 .collect()
2815 };
2816
2817 // 1. Revoke first — never waits for the host. Plugin-tier owners only:
2818 // the builtin tier's modules are not plugins, are never desired by an
2819 // attachment, and the table that wants them is fixed for the
2820 // manager's life, so no plugin change revokes one.
2821 let mut revoked: Vec<(OwnerRef, HostCohort)> = Vec::new();
2822 let mut to_activate: BTreeMap<HostCohort, Vec<(String, DesiredOwner)>> = BTreeMap::new();
2823 {
2824 let mut registry = shared.registry.lock().expect("registry lock");
2825 let existing: Vec<(String, PluginAuthority, String, HostCohort)> = registry
2826 .owners()
2827 .filter(|entry| entry.tier() == HostTier::Plugin)
2828 .filter_map(|entry| {
2829 Some((
2830 entry.owner.plugin_id.clone(),
2831 entry.authority.clone()?,
2832 entry.config_hash.clone(),
2833 entry.cohort.clone(),
2834 ))
2835 })
2836 .collect();
2837 for (plugin_id, authority, config_hash, cohort) in &existing {
2838 let keep = desired.get(plugin_id).is_some_and(|want| {
2839 want.cohort == *cohort
2840 && &want.authority == authority
2841 && wanted_config.get(plugin_id) == Some(config_hash)
2842 });
2843 if !keep {
2844 if let Some(want) = desired.get(plugin_id)
2845 && matches!(cohort, HostCohort::Plugin(PluginCohort::Agent { .. }))
2846 && want.cohort == HostCohort::reviewed()
2847 {
2848 shared
2849 .pending_migrations
2850 .lock()
2851 .expect("pending migrations lock")
2852 .insert(plugin_id.clone(), cohort.clone());
2853 }
2854 if let Some(owner) = registry.revoke_owner(plugin_id) {
2855 revoked.push((owner, cohort.clone()));
2856 }
2857 registry.forget_owner(plugin_id);
2858 }
2859 }
2860 for (plugin_id, want) in desired.clone() {
2861 if registry
2862 .owner(&plugin_id)
2863 .is_none_or(|owner| owner.state == OwnerState::Active)
2864 {
2865 to_activate
2866 .entry(want.cohort.clone())
2867 .or_default()
2868 .push((plugin_id, want));
2869 }
2870 }
2871 }
2872 for (owner, cohort) in revoked {
2873 shared.revoke_owner_state(&owner.plugin_id);
2874 dsh_remote::withdraw_owner(&owner);
2875 shared.plugin_diagnostic(
2876 &owner.plugin_id,
2877 format!("plugin `{}` revoked", owner.plugin_id),
2878 );
2879 if let Ok(host) = shared.ready_host(&cohort) {
2880 host.revoke_calls_of(&owner.plugin_id);
2881 shared.deactivate_owner(&host, &owner).await;
2882 }
2883 }
2884
2885 if let Some(reviewed_owners) = to_activate.get_mut(&HostCohort::reviewed()) {
2886 let mut remaining = Vec::new();
2887 for (plugin_id, want) in std::mem::take(reviewed_owners) {
2888 let from_cohort = {
2889 let from = shared
2890 .pending_migrations
2891 .lock()
2892 .expect("pending migrations lock")
2893 .get(&plugin_id)
2894 .cloned();
2895 if from.is_some() {
2896 from
2897 } else if let Ok(home) = host_root(&shared.options) {
2898 let candidate_cohort = HostCohort::agent(&want.authority.workspace);
2899 let candidate_dir = supervisor::owner_data_dir(
2900 &home,
2901 &candidate_cohort,
2902 &plugin_id,
2903 &want.plugin_name,
2904 );
2905 if tokio::fs::symlink_metadata(&candidate_dir).await.is_ok() {
2906 shared
2907 .pending_migrations
2908 .lock()
2909 .expect("pending migrations lock")
2910 .insert(plugin_id.clone(), candidate_cohort.clone());
2911 Some(candidate_cohort)
2912 } else {
2913 None
2914 }
2915 } else {
2916 None
2917 }
2918 };
2919 if let Some(from_cohort) = from_cohort {
2920 let old_host_live = match shared.cohort_runtime(&from_cohort) {
2921 Some(rt) => {
2922 let slot = rt.host.lock().expect("host lock");
2923 matches!(
2924 &*slot,
2925 HostSlot::Ready(h) | HostSlot::Unresponsive(h) if !h.has_exited()
2926 )
2927 }
2928 None => false,
2929 };
2930 if old_host_live {
2931 shared.plugin_diagnostic(
2932 &plugin_id,
2933 format!(
2934 "plugin `{}` is waiting for its agent host to exit before moving to the reviewed host",
2935 want.plugin_name
2936 ),
2937 );
2938 continue;
2939 }
2940 let home = match host_root(&shared.options) {
2941 Ok(home) => home,
2942 Err(err) => {
2943 shared.plugin_diagnostic(&plugin_id, err);
2944 continue;
2945 }
2946 };
2947 let source_dir = supervisor::owner_data_dir(
2948 &home,
2949 &from_cohort,
2950 &plugin_id,
2951 &want.plugin_name,
2952 );
2953 let dest_dir =
2954 supervisor::plugin_data_dir(&home, &plugin_id, &want.plugin_name);
2955 enum MigrationStep {
2956 NoSource,
2957 DestExists,
2958 SourceIsLink,
2959 Failed(String),
2960 Success,
2961 }
2962 let plugin_name = want.plugin_name.clone();
2963 let s_dir = source_dir.clone();
2964 let d_dir = dest_dir.clone();
2965 let step = tokio::task::spawn_blocking(move || {
2966 let check_ancestors = |dir: &Path| -> Result<(), MigrationStep> {
2967 let mut check = dir.parent();
2968 while let Some(path) = check {
2969 let meta = match std::fs::symlink_metadata(path) {
2970 Ok(m) => m,
2971 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2972 check = path.parent();
2973 continue;
2974 }
2975 Err(e) => {
2976 return Err(MigrationStep::Failed(format!(
2977 "cannot stat ancestor {}: {e}",
2978 path.display()
2979 )));
2980 }
2981 };
2982 if codewhale_util::path_identity::metadata_is_link_or_reparse(&meta)
2983 {
2984 return Err(MigrationStep::SourceIsLink);
2985 }
2986 if path
2987 .file_name()
2988 .is_some_and(|name| name == "extension-host")
2989 {
2990 break;
2991 }
2992 check = path.parent();
2993 }
2994 Ok(())
2995 };
2996
2997 if let Err(step) = check_ancestors(&s_dir) {
2998 return step;
2999 }
3000 if let Err(step) = check_ancestors(&d_dir) {
3001 return step;
3002 }
3003
3004 let s_meta = match std::fs::symlink_metadata(&s_dir) {
3005 Ok(m) => m,
3006 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
3007 return MigrationStep::NoSource;
3008 }
3009 Err(e) => {
3010 return MigrationStep::Failed(format!(
3011 "cannot stat {}: {e}",
3012 s_dir.display()
3013 ));
3014 }
3015 };
3016 if codewhale_util::path_identity::metadata_is_link_or_reparse(&s_meta) {
3017 return MigrationStep::SourceIsLink;
3018 }
3019
3020 match std::fs::symlink_metadata(&d_dir) {
3021 Ok(_) => return MigrationStep::DestExists,
3022 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
3023 Err(e) => {
3024 return MigrationStep::Failed(format!(
3025 "cannot stat {}: {e}",
3026 d_dir.display()
3027 ));
3028 }
3029 }
3030
3031 let mut stack = vec![s_dir.clone()];
3032 while let Some(path) = stack.pop() {
3033 let meta = match std::fs::symlink_metadata(&path) {
3034 Ok(m) => m,
3035 Err(e) => {
3036 return MigrationStep::Failed(format!(
3037 "cannot stat {}: {e}",
3038 path.display()
3039 ));
3040 }
3041 };
3042 if codewhale_util::path_identity::metadata_is_link_or_reparse(&meta) {
3043 return MigrationStep::SourceIsLink;
3044 }
3045 if meta.is_dir() {
3046 let entries = match std::fs::read_dir(&path) {
3047 Ok(entries) => entries,
3048 Err(e) => {
3049 return MigrationStep::Failed(format!(
3050 "cannot read dir {}: {e}",
3051 path.display()
3052 ));
3053 }
3054 };
3055 for entry in entries {
3056 match entry {
3057 Ok(entry) => stack.push(entry.path()),
3058 Err(e) => {
3059 return MigrationStep::Failed(format!(
3060 "cannot read entry in {}: {e}",
3061 path.display()
3062 ));
3063 }
3064 }
3065 }
3066 }
3067 }
3068
3069 if let Some(parent) = d_dir.parent()
3070 && let Err(e) = std::fs::create_dir_all(parent)
3071 {
3072 return MigrationStep::Failed(format!(
3073 "cannot create parent directory {}: {e}",
3074 parent.display()
3075 ));
3076 }
3077 if let Err(err) = std::fs::rename(&s_dir, &d_dir) {
3078 return MigrationStep::Failed(format!(
3079 "cannot migrate data for `{plugin_name}` from {} to {}: {err}",
3080 s_dir.display(),
3081 d_dir.display()
3082 ));
3083 }
3084 MigrationStep::Success
3085 })
3086 .await
3087 .unwrap_or_else(|e| {
3088 MigrationStep::Failed(format!("migration task failed: {e}"))
3089 });
3090 match step {
3091 MigrationStep::NoSource => {
3092 shared
3093 .pending_migrations
3094 .lock()
3095 .expect("pending migrations lock")
3096 .remove(&plugin_id);
3097 }
3098 MigrationStep::DestExists => {
3099 let reason = format!(
3100 "cannot migrate data for `{}`: destination directory {} already exists",
3101 want.plugin_name,
3102 dest_dir.display()
3103 );
3104 shared.plugin_diagnostic(&plugin_id, reason.clone());
3105 let mut registry = shared.registry.lock().expect("registry lock");
3106 registry.record_activation_failure(
3107 want.cohort.clone(),
3108 &plugin_id,
3109 &want.plugin_name,
3110 Some(want.authority.clone()),
3111 &want.authority.content_hash,
3112 reason,
3113 );
3114 continue;
3115 }
3116 MigrationStep::SourceIsLink => {
3117 let reason = format!(
3118 "cannot migrate data for `{}`: source directory {} is a link or reparse point",
3119 want.plugin_name,
3120 source_dir.display()
3121 );
3122 shared.plugin_diagnostic(&plugin_id, reason.clone());
3123 let mut registry = shared.registry.lock().expect("registry lock");
3124 registry.record_activation_failure(
3125 want.cohort.clone(),
3126 &plugin_id,
3127 &want.plugin_name,
3128 Some(want.authority.clone()),
3129 &want.authority.content_hash,
3130 reason,
3131 );
3132 continue;
3133 }
3134 MigrationStep::Failed(reason) => {
3135 shared.plugin_diagnostic(&plugin_id, reason.clone());
3136 let mut registry = shared.registry.lock().expect("registry lock");
3137 registry.record_activation_failure(
3138 want.cohort.clone(),
3139 &plugin_id,
3140 &want.plugin_name,
3141 Some(want.authority.clone()),
3142 &want.authority.content_hash,
3143 reason,
3144 );
3145 continue;
3146 }
3147 MigrationStep::Success => {
3148 let grant_err = if cfg!(windows) {
3149 let d = dest_dir.clone();
3150 let s = source_dir.clone();
3151 let shared_c = Arc::clone(shared);
3152 tokio::task::spawn_blocking(move || {
3153 if let Ok(host) = shared_c.ready_host(&HostCohort::reviewed())
3154 && let Err(err) = host.grant_data_dir(&d)
3155 {
3156 if let Err(rollback_err) = std::fs::rename(&d, &s) {
3157 return Some(format!(
3158 "{err} (rollback also failed: {rollback_err})"
3159 ));
3160 }
3161 return Some(err);
3162 }
3163 None
3164 })
3165 .await
3166 .unwrap_or_else(|e| Some(format!("grant task failed: {e}")))
3167 } else {
3168 None
3169 };
3170 if let Some(err) = grant_err {
3171 let reason = format!("cannot grant migrated data directory: {err}");
3172 shared.plugin_diagnostic(&plugin_id, reason.clone());
3173 let mut registry = shared.registry.lock().expect("registry lock");
3174 registry.record_activation_failure(
3175 want.cohort.clone(),
3176 &plugin_id,
3177 &want.plugin_name,
3178 Some(want.authority.clone()),
3179 &want.authority.content_hash,
3180 reason,
3181 );
3182 continue;
3183 }
3184 shared
3185 .pending_migrations
3186 .lock()
3187 .expect("pending migrations lock")
3188 .remove(&plugin_id);
3189 }
3190 }
3191 }
3192 remaining.push((plugin_id, want));
3193 }
3194 *reviewed_owners = remaining;
3195 }
3196
3197 let plugins = async {
3198 let mut last_err = None;
3199 for (cohort, owners) in to_activate {
3200 if owners.is_empty() {
3201 continue;
3202 }
3203 let host = match self.ensure_host(&cohort, policy).await {
3204 Ok(host) => host,
3205 Err(error) => {
3206 shared.diagnostic(format!(
3207 "{}: failed to ensure host: {error}",
3208 cohort.host_label()
3209 ));
3210 last_err = Some(error);
3211 continue;
3212 }
3213 };
3214 if let Some(runtime) = shared.cohort_runtime(&cohort) {
3215 let generation = runtime.host_generation.load(Ordering::SeqCst);
3216 let needs_fresh_module_cache = {
3217 let imported = runtime
3218 .imported_entries
3219 .lock()
3220 .expect("imported entries lock");
3221 imported.0 == generation
3222 && owners.iter().any(|(_, want)| {
3223 want.entries.iter().any(|(path, sha256)| {
3224 imported
3225 .1
3226 .get(path)
3227 .is_some_and(|prev_sha| prev_sha != sha256)
3228 })
3229 })
3230 };
3231 if needs_fresh_module_cache {
3232 let mut supervision = runtime.supervision.lock().expect("supervision lock");
3233 supervision.planned_restart = Some(generation);
3234 if !host.terminate_if_idle(DIRTY_RESTART_REASON) {
3235 supervision.planned_restart = None;
3236 supervision.dirty_restart_pending = true;
3237 }
3238 drop(supervision);
3239 continue;
3240 }
3241 }
3242 for (plugin_id, want) in owners {
3243 if host.has_exited() {
3244 break;
3245 }
3246 let content_hash = want.authority.content_hash.clone();
3247 self.activate_owner(
3248 &host,
3249 Activation {
3250 cohort: cohort.clone(),
3251 owner_id: plugin_id,
3252 name: want.plugin_name,
3253 authority: Some(want.authority),
3254 content_hash,
3255 entries: want.entries,
3256 host_services: want.host_services,
3257 },
3258 )
3259 .await;
3260 }
3261 }
3262 match last_err {
3263 Some(err) => Err(err),
3264 None => Ok(()),
3265 }
3266 }
3267 .await;
3268
3269 let mut cohorts_to_drop = Vec::new();
3270 {
3271 let agent_cohorts = shared.agent_cohorts.lock().expect("agent cohorts lock");
3272 for (workspace, runtime) in agent_cohorts.iter() {
3273 let has_owner = desired
3274 .values()
3275 .any(|d| d.cohort.agent_project_path().as_ref() == Some(workspace));
3276 if !has_owner {
3277 let slot = runtime.host.lock().expect("host lock");
3278 match &*slot {
3279 HostSlot::Ready(host) | HostSlot::Unresponsive(host) => {
3280 host.terminate(NO_DESIRED_OWNERS_REASON.into());
3281 }
3282 HostSlot::Idle | HostSlot::Failed { .. } => {
3283 cohorts_to_drop.push(workspace.clone());
3284 }
3285 _ => {}
3286 }
3287 }
3288 }
3289 }
3290 if !cohorts_to_drop.is_empty() {
3291 let mut agent_cohorts = shared.agent_cohorts.lock().expect("agent cohorts lock");
3292 for workspace in cohorts_to_drop {
3293 agent_cohorts.remove(&workspace);
3294 }
3295 }
3296 if cancel.is_some_and(CancellationToken::is_cancelled) {
3297 return Ok(());
3298 }
3299 let has_creator_owner = shared
3300 .registry
3301 .lock()
3302 .expect("registry lock")
3303 .owner("host:creator")
3304 .is_some();
3305 let builtin = if policy
3306 || shared.mcp_users.load(Ordering::SeqCst) > 0
3307 || shared.stock_users.load(Ordering::SeqCst) > 0
3308 || shared.creator_users.load(Ordering::SeqCst) > 0
3309 || has_creator_owner
3310 {
3311 self.reconcile_builtin(policy, cancel).await
3312 } else {
3313 Ok(())
3314 };
3315 for state in shared
3316 .attachments
3317 .lock()
3318 .expect("attachments lock")
3319 .values_mut()
3320 {
3321 if state.selection.revision == state.plugins.caller_selection() {
3322 state.settled = state.selection.revision;
3323 }
3324 }
3325 let withheld = shared
3326 .registry
3327 .lock()
3328 .expect("registry lock")
3329 .take_withheld_report();
3330 if let Some(withheld) = withheld {
3331 shared.diagnostic(withheld);
3332 }
3333 match (plugins, builtin) {
3334 (Err(error), Err(other)) => {
3335 shared.diagnostic(other);
3336 Err(error)
3337 }
3338 (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
3339 (Ok(()), Ok(())) => Ok(()),
3340 }
3341 }
3342
3343 /// One real host consumer asks for the pinned MCP module. Rust mode never
3344 /// starts tier 0. This uses the same manager, supervision and owner registry.
3345 async fn ensure_mcp_builtin(
3346 &self,
3347 ) -> Result<(Arc<HostProcess>, codewhale_config::OwnerRef, u64), String> {
3348 self.ensure_demand_builtin("host:mcp", activation::extension_host_policy_enabled())
3349 .await
3350 }
3351 /// Pure Core adapters demand the same pinned harness without enabling Native plugins.
3352 async fn ensure_stock_builtin(
3353 &self,
3354 ) -> Result<(Arc<HostProcess>, codewhale_config::OwnerRef, u64), String> {
3355 self.ensure_demand_builtin("host:harness", activation::extension_host_policy_enabled())
3356 .await
3357 }
3358 async fn ensure_harness_builtin(
3359 &self,
3360 ) -> Result<(Arc<HostProcess>, codewhale_config::OwnerRef, u64), String> {
3361 let native_policy = activation::extension_host_policy_enabled();
3362 if !native_policy {
3363 return Err(
3364 "Builtin backend requires features.extension_host; no Rust fallback is allowed"
3365 .to_string(),
3366 );
3367 }
3368 self.ensure_demand_builtin("host:harness", native_policy)
3369 .await
3370 }
3371 async fn ensure_demand_builtin(
3372 &self,
3373 owner_id: &str,
3374 native_policy: bool,
3375 ) -> Result<(Arc<HostProcess>, codewhale_config::OwnerRef, u64), String> {
3376 let _serial = self.shared.sync_lock.lock().await;
3377 let root = host_root(&self.shared.options)?;
3378 materialize_bundle(&root)?;
3379 // A crashed tier-0 process cannot carry its old owner into a new
3380 // process. Retire only this builtin before minting a fresh generation.
3381 let stale = self
3382 .shared
3383 .registry
3384 .lock()
3385 .expect("registry lock")
3386 .owner(owner_id)
3387 .is_some_and(|entry| entry.state != OwnerState::Active);
3388 if stale {
3389 self.shared.revoke_owner_state(owner_id);
3390 self.shared
3391 .registry
3392 .lock()
3393 .expect("registry lock")
3394 .forget_owner(owner_id);
3395 }
3396 // Replay the actual Native policy after a Builtin crash. MCP demand
3397 // must never switch optional third-party activation on.
3398 self.reconcile_builtin(native_policy, None).await?;
3399 let host = self
3400 .shared
3401 .ready_host(&HostCohort::Builtin)
3402 .map_err(|status| host_down(HostTier::Builtin, &status))?;
3403 let owner = self
3404 .shared
3405 .registry
3406 .lock()
3407 .expect("registry lock")
3408 .owner(owner_id)
3409 .filter(|entry| entry.state == OwnerState::Active)
3410 .map(|entry| entry.owner.clone())
3411 .ok_or_else(|| "demanded builtin failed to activate".to_string())?;
3412 let generation = self.shared.builtin.host_generation.load(Ordering::SeqCst);
3413 Ok((host, owner, generation))
3414 }
3415
3416 async fn reconcile_builtin(
3417 &self,
3418 policy: bool,
3419 cancel: Option<&CancellationToken>,
3420 ) -> Result<(), String> {
3421 let shared = &self.shared;
3422 let revoked_creator = if shared.creator_users.load(Ordering::SeqCst) == 0 {
3423 let mut registry = shared.registry.lock().expect("registry lock");
3424 let revoked = registry.revoke_owner("host:creator");
3425 registry.forget_owner("host:creator");
3426 revoked
3427 } else {
3428 None
3429 };
3430 if let Some(owner) = revoked_creator {
3431 shared.revoke_owner_state(&owner.plugin_id);
3432 dsh_remote::withdraw_owner(&owner);
3433 shared.plugin_diagnostic(
3434 &owner.plugin_id,
3435 format!("plugin `{}` revoked", owner.plugin_id),
3436 );
3437 if let Ok(host) = shared.ready_host(&HostCohort::Builtin) {
3438 host.revoke_calls_of(&owner.plugin_id);
3439 shared.deactivate_owner(&host, &owner).await;
3440 }
3441 }
3442 let wanted: Vec<&'static BuiltinModule> = {
3443 let registry = shared.registry.lock().expect("registry lock");
3444 shared
3445 .builtin_modules
3446 .iter()
3447 .filter(|module| {
3448 (module.id != "mcp" || shared.mcp_users.load(Ordering::SeqCst) > 0)
3449 && (module.id != "harness"
3450 || (policy && shared.harness_users.load(Ordering::SeqCst) > 0)
3451 || shared.stock_users.load(Ordering::SeqCst) > 0)
3452 && (module.id != "creator"
3453 || shared.creator_users.load(Ordering::SeqCst) > 0)
3454 && registry.owner(&module.owner_id()).is_none()
3455 })
3456 .collect()
3457 };
3458 if wanted.is_empty() {
3459 return Ok(());
3460 }
3461 let root = host_root(&shared.options)?;
3462 if !supervisor::bundle_dir(&root, bundle_sha256())
3463 .join("builtin")
3464 .exists()
3465 && shared.materialize_default_builtins
3466 {
3467 let materialize_root = root.clone();
3468 tokio::task::spawn_blocking(move || materialize_bundle(&materialize_root))
3469 .await
3470 .map_err(|error| format!("plugin host bundle preparation failed: {error}"))??;
3471 }
3472 let mut activations = Vec::new();
3473 for module in wanted {
3474 // The module's source, accepted only if its SHA-256 is the one the
3475 // table pins: the path and digest to activate it with.
3476 let source = {
3477 let root = root.clone();
3478 tokio::task::spawn_blocking(move || {
3479 let path = builtin_source_path(&root, module);
3480 let bytes = std::fs::read(&path).map_err(|error| {
3481 format!(
3482 "cannot read the source of built-in module `{}` at {}: {error}",
3483 module.id,
3484 path.display()
3485 )
3486 })?;
3487 let digest = hex(Sha256::digest(&bytes));
3488 if digest != module.source_sha256 {
3489 return Err(format!(
3490 "the source of built-in module `{}` at {} has sha256 {digest}, not the {} the core pins",
3491 module.id,
3492 path.display(),
3493 module.source_sha256
3494 ));
3495 }
3496 Ok((path, digest))
3497 })
3498 .await
3499 .map_err(|error| format!("built-in module scan failed: {error}"))?
3500 };
3501 let owner_id = module.owner_id();
3502 match source {
3503 Ok(entry) => activations.push(Activation {
3504 cohort: HostCohort::Builtin,
3505 owner_id,
3506 name: module.id.to_string(),
3507 authority: None,
3508 content_hash: module.source_sha256.to_string(),
3509 entries: vec![entry],
3510 host_services: Vec::new(),
3511 }),
3512 Err(reason) => {
3513 let mut registry = shared.registry.lock().expect("registry lock");
3514 if let Ok(owner) = registry.begin_owner(
3515 HostCohort::Builtin,
3516 &owner_id,
3517 module.id,
3518 None,
3519 module.source_sha256,
3520 ) {
3521 registry.mark_failed(&owner, OwnerState::Failed(reason.clone()));
3522 }
3523 drop(registry);
3524 shared.plugin_diagnostic(
3525 &owner_id,
3526 format!(
3527 "built-in module `{}` failed to activate: {reason}",
3528 module.id
3529 ),
3530 );
3531 }
3532 }
3533 }
3534 if activations.is_empty() || cancel.is_some_and(CancellationToken::is_cancelled) {
3535 return Ok(());
3536 }
3537 let host = self.ensure_host(&HostCohort::Builtin, policy).await?;
3538 for activation in activations {
3539 if host.has_exited() || cancel.is_some_and(CancellationToken::is_cancelled) {
3540 break;
3541 }
3542 self.activate_owner(&host, activation).await;
3543 }
3544 Ok(())
3545 }
3546
3547 async fn activate_owner(&self, host: &Arc<HostProcess>, want: Activation) {
3548 let shared = &self.shared;
3549 let plugin_id = want.owner_id.as_str();
3550 let begun = {
3551 let mut registry = shared.registry.lock().expect("registry lock");
3552 if let Some(owner) = registry
3553 .owner(plugin_id)
3554 .filter(|entry| entry.state == OwnerState::Active)
3555 {
3556 Ok(owner.owner.clone())
3557 } else {
3558 registry
3559 .begin_owner(
3560 want.cohort.clone(),
3561 plugin_id,
3562 &want.name,
3563 want.authority.clone(),
3564 &want.content_hash,
3565 )
3566 .inspect(|owner| {
3567 registry.set_host_services(owner, want.host_services.clone());
3568 })
3569 }
3570 };
3571 let owner = match begun {
3572 Ok(owner) => owner,
3573 Err(reason) => {
3574 shared.plugin_diagnostic(
3575 plugin_id,
3576 format!("plugin `{}` was not activated: {reason}", want.name),
3577 );
3578 return;
3579 }
3580 };
3581 struct ActivatingGuard {
3582 shared: Arc<ManagerShared>,
3583 owner: OwnerRef,
3584 }
3585 impl Drop for ActivatingGuard {
3586 fn drop(&mut self) {
3587 let mut registry = self.shared.registry.lock().expect("registry lock");
3588 let still_activating = registry.owner(&self.owner.plugin_id).is_some_and(|entry| {
3589 entry.owner == self.owner && entry.state == OwnerState::Activating
3590 });
3591 if still_activating {
3592 registry.revoke_owner(&self.owner.plugin_id);
3593 registry.forget_owner(&self.owner.plugin_id);
3594 }
3595 }
3596 }
3597 let _activating_guard = ActivatingGuard {
3598 shared: Arc::clone(shared),
3599 owner: owner.clone(),
3600 };
3601 // What the owner is given: its settings and its own directory. A
3602 // config that is refused, or a directory that cannot be made, fails the
3603 // activation with the reason; the plugin is never started with
3604 // different settings than the user wrote. A built-in module takes no
3605 // user settings: `[plugins]` is keyed by plugin name and is not read
3606 // for tier 0.
3607 let selection = match want.tier() {
3608 HostTier::Plugin => shared
3609 .plugin_configs
3610 .lock()
3611 .expect("plugin configs lock")
3612 .select(&want.name),
3613 HostTier::Builtin => Ok(plugin_config::PluginConfig::empty()),
3614 };
3615 shared
3616 .registry
3617 .lock()
3618 .expect("registry lock")
3619 .set_config_hash(&owner, &plugin_config::activation_hash(&selection));
3620 let context = match selection {
3621 Ok(config) => self
3622 .owner_data_dir(&want.cohort, plugin_id, &want.name)
3623 .await
3624 .map(|data_dir| (config, data_dir)),
3625 Err(reason) => Err(reason),
3626 };
3627 let (config, data_dir) = match context {
3628 Ok(context) => context,
3629 Err(reason) => {
3630 shared
3631 .registry
3632 .lock()
3633 .expect("registry lock")
3634 .mark_failed(&owner, OwnerState::Failed(reason.clone()));
3635 shared.plugin_diagnostic(
3636 plugin_id,
3637 format!("plugin `{}` failed to activate: {reason}", want.name),
3638 );
3639 return;
3640 }
3641 };
3642 // Retire no-longer-wanted entry handles before awaiting host disposal.
3643 if want.tier() == HostTier::Plugin {
3644 let scopes: Vec<_> = {
3645 let registry = shared.registry.lock().expect("registry lock");
3646 registry
3647 .owner(plugin_id)
3648 .map(|entry| {
3649 entry
3650 .scopes
3651 .keys()
3652 .filter(|scope| {
3653 !want.entries.iter().any(|(path, hash)| {
3654 scope.path == path.to_string_lossy() && scope.sha256 == *hash
3655 })
3656 })
3657 .cloned()
3658 .collect()
3659 })
3660 .unwrap_or_default()
3661 };
3662 for scope in scopes {
3663 let handles = shared
3664 .registry
3665 .lock()
3666 .expect("registry lock")
3667 .revoke_scope(&owner, &scope);
3668 shared.core_calls.revoke_scope(plugin_id, &scope);
3669 shared.execution_broker.revoke_scope(plugin_id, &scope);
3670 host.revoke_calls_for_handles(plugin_id, &handles);
3671 shared.deactivate_entry(host, &owner, Some(scope)).await;
3672 }
3673 }
3674 if want.tier() == HostTier::Plugin {
3675 let admission = match want.authority.clone() {
3676 Some(authority) => host.admit_native_root(authority).await,
3677 None => Err("Native owner has no reviewed bundle authority".into()),
3678 };
3679 if let Err(reason) = admission {
3680 shared
3681 .registry
3682 .lock()
3683 .expect("registry lock")
3684 .mark_failed(&owner, OwnerState::Failed(reason.clone()));
3685 shared.plugin_diagnostic(
3686 plugin_id,
3687 format!("plugin `{}` failed Native admission: {reason}", want.name),
3688 );
3689 shared.deactivate_owner(host, &owner).await;
3690 return;
3691 }
3692 }
3693 let mut failure = None;
3694 let mut native_failure = None;
3695 // A plugin may declare several `native` entries. Each is activated in
3696 // declaration order under one owner. Each entry has an independent
3697 // scope: a failing entry withdraws its own handles and cleanup, while
3698 // already-active sibling entries remain usable.
3699 let mut tools = BTreeSet::new();
3700 for (path, sha256) in &want.entries {
3701 let scope = (want.tier() == HostTier::Plugin).then(|| EntryRef {
3702 path: path.to_string_lossy().into_owned(),
3703 sha256: sha256.clone(),
3704 });
3705 if let Some(scope) = &scope {
3706 let admitted = shared
3707 .registry
3708 .lock()
3709 .expect("registry lock")
3710 .begin_scope(&owner, scope.clone());
3711 if admitted.is_err() {
3712 continue;
3713 }
3714 }
3715 if want.tier() == HostTier::Plugin
3716 && let Some(runtime) = shared.cohort_runtime(&want.cohort)
3717 {
3718 let generation = runtime.host_generation.load(Ordering::SeqCst);
3719 let mut imported = runtime
3720 .imported_entries
3721 .lock()
3722 .expect("imported entries lock");
3723 if imported.0 == generation {
3724 imported.1.insert(path.clone(), sha256.clone());
3725 }
3726 }
3727 let bundled_first_party = want.authority.as_ref().is_some_and(|auth| {
3728 codewhale_plugins::builtin::is_bundled_agent_teams_id(
3729 auth.plugin_id.as_str(),
3730 &want.name,
3731 )
3732 });
3733 let request = CoreRequest::Activate(ActivateParams {
3734 scope: scope.clone(),
3735 owner: owner.clone(),
3736 plugin_name: want.name.clone(),
3737 entry: EntryRef {
3738 path: path.to_string_lossy().into_owned(),
3739 sha256: sha256.clone(),
3740 },
3741 config: config.value.clone(),
3742 data_dir: Some(data_dir.clone()),
3743 bundled_first_party,
3744 });
3745 let outcome = host
3746 .call(request, Some(plugin_id.to_string()))
3747 .await
3748 .map_err(|error| error.to_string())
3749 .and_then(|value| {
3750 serde_json::from_value::<ActivateResult>(value)
3751 .map_err(|error| format!("malformed activation answer: {error}"))
3752 })
3753 .and_then(|result| match result {
3754 ActivateResult::Ok { tools, commands } => Ok((tools, commands)),
3755 ActivateResult::Failed { diagnostic } => Err(diagnostic),
3756 });
3757 match outcome {
3758 Ok((names, _slash)) => {
3759 if want.tier() == HostTier::Builtin
3760 && want.owner_id == "host:creator"
3761 && let Some(module) = shared
3762 .builtin_modules
3763 .iter()
3764 .find(|module| module.owner_id() == want.owner_id)
3765 && let Some(unlisted) = names.iter().find(|name| {
3766 !module.tools.iter().any(|tool| tool.name == name.as_str())
3767 })
3768 {
3769 failure = Some(format!(
3770 "built-in module `{}` reported unlisted tool `{unlisted}`",
3771 want.name
3772 ));
3773 break;
3774 }
3775 tools.extend(names);
3776 if let Some(scope) = &scope {
3777 shared
3778 .registry
3779 .lock()
3780 .expect("registry lock")
3781 .mark_scope_active(&owner, scope);
3782 }
3783 }
3784 Err(reason) => {
3785 if let Some(scope) = scope {
3786 shared
3787 .registry
3788 .lock()
3789 .expect("registry lock")
3790 .fail_scope(&owner, &scope);
3791 shared.core_calls.revoke_scope(plugin_id, &scope);
3792 shared.execution_broker.revoke_scope(plugin_id, &scope);
3793 native_failure.get_or_insert_with(|| reason.clone());
3794 shared.plugin_diagnostic(plugin_id, format!("Native entry failed to activate: {reason}; other selected entries remain live"));
3795 shared.deactivate_entry(host, &owner, Some(scope)).await;
3796 } else {
3797 failure = Some(reason);
3798 break;
3799 }
3800 }
3801 }
3802 }
3803 if want.tier() == HostTier::Plugin
3804 && shared
3805 .registry
3806 .lock()
3807 .expect("registry lock")
3808 .owner(plugin_id)
3809 .is_none_or(|entry| {
3810 !entry
3811 .scopes
3812 .values()
3813 .any(|state| *state == OwnerState::Active)
3814 })
3815 {
3816 let reason =
3817 native_failure.unwrap_or_else(|| "No selected Native entry became active".into());
3818 shared
3819 .registry
3820 .lock()
3821 .expect("registry lock")
3822 .mark_failed(&owner, OwnerState::Failed(reason.clone()));
3823 shared.plugin_diagnostic(
3824 plugin_id,
3825 format!("plugin `{}` failed to activate: {reason}", want.name),
3826 );
3827 // Per-entry acknowledgements above account for incomplete cleanup.
3828 // Also retire the now-empty parent so its owner record cannot linger.
3829 shared.deactivate_owner(host, &owner).await;
3830 return;
3831 }
3832 match failure {
3833 None => {
3834 let (active, commands) = {
3835 let mut registry = shared.registry.lock().expect("registry lock");
3836 let active = registry.mark_active(&owner);
3837 let mut commands = if active {
3838 registry
3839 .live_commands()
3840 .into_iter()
3841 .filter(|command| command.owner == owner)
3842 .map(|command| command.name)
3843 .collect::<Vec<_>>()
3844 } else {
3845 Vec::new()
3846 };
3847 commands.sort();
3848 commands.dedup();
3849 (active, commands)
3850 };
3851 if active {
3852 shared.plugin_diagnostic(
3853 plugin_id,
3854 format!(
3855 "plugin `{}` active (tools: {}; commands: {})",
3856 want.name,
3857 tools.iter().cloned().collect::<Vec<_>>().join(", "),
3858 commands
3859 .iter()
3860 .map(|name| format!("/{name}"))
3861 .collect::<Vec<_>>()
3862 .join(", ")
3863 ),
3864 );
3865 }
3866 }
3867 Some(reason) => {
3868 // All-or-nothing: drop anything half-registered on this side,
3869 // and dispose any entry the host did activate.
3870 shared
3871 .registry
3872 .lock()
3873 .expect("registry lock")
3874 .mark_failed(&owner, OwnerState::Failed(reason.clone()));
3875 shared.plugin_diagnostic(
3876 plugin_id,
3877 format!("plugin `{}` failed to activate: {reason}", want.name),
3878 );
3879 shared.deactivate_owner(host, &owner).await;
3880 }
3881 }
3882 }
3883
3884 /// Create (if needed) and name an owner's own directory inside its tier's
3885 /// data dir, the host sandbox's writable root: a plugin's at its
3886 /// long-standing path, a built-in module's under the builtin tier's.
3887 async fn owner_data_dir(
3888 &self,
3889 cohort: impl Into<HostCohort>,
3890 plugin_id: &str,
3891 plugin_name: &str,
3892 ) -> Result<String, String> {
3893 let cohort = cohort.into();
3894 let path = supervisor::owner_data_dir(
3895 &host_root(&self.shared.options)?,
3896 &cohort,
3897 plugin_id,
3898 plugin_name,
3899 );
3900 let mut builder = tokio::fs::DirBuilder::new();
3901 builder.recursive(true);
3902 #[cfg(unix)]
3903 builder.mode(0o700);
3904 builder.create(&path).await.map_err(|error| {
3905 format!(
3906 "cannot create the plugin data directory {}: {error}",
3907 path.display()
3908 )
3909 })?;
3910 path.to_str().map(str::to_owned).ok_or_else(|| {
3911 format!(
3912 "the plugin data directory {} is not valid UTF-8",
3913 path.display()
3914 )
3915 })
3916 }
3917
3918 /// `tier`'s host, started (lazily, once per generation) if it is idle.
3919 async fn ensure_host(
3920 &self,
3921 cohort: &HostCohort,
3922 policy: bool,
3923 ) -> Result<Arc<HostProcess>, String> {
3924 let shared = &self.shared;
3925 let runtime = shared.get_or_create_cohort_runtime(cohort);
3926 let tier = cohort.tier();
3927 let label = cohort.host_label();
3928 let mut generation = {
3929 let mut slot = runtime.host.lock().expect("host lock");
3930 match &*slot {
3931 HostSlot::Ready(host) if !host.has_exited() && !host.is_retiring() => {
3932 return Ok(Arc::clone(host));
3933 }
3934 HostSlot::Idle => {}
3935 other => return Err(host_down(tier, &other.status())),
3936 }
3937 *slot = HostSlot::Starting;
3938 let mut supervision = runtime.supervision.lock().expect("supervision lock");
3939 supervision.last_start = Some(Instant::now());
3940 supervision.policy = policy;
3941 supervision.launch_failed = false;
3942 supervision.dirty_teardowns.clear();
3943 supervision.dirty_restart_pending = false;
3944 supervision.planned_restart = None;
3945 let next_gen = match cohort {
3946 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
3947 shared.agent_host_generation.fetch_add(1, Ordering::SeqCst) + 1
3948 }
3949 _ => runtime.host_generation.fetch_add(1, Ordering::SeqCst) + 1,
3950 };
3951 runtime.host_generation.store(next_gen, Ordering::SeqCst);
3952 *runtime
3953 .imported_entries
3954 .lock()
3955 .expect("imported entries lock") = (next_gen, BTreeMap::new());
3956 next_gen
3957 };
3958 struct StartingGuard {
3959 runtime: Arc<TierRuntime>,
3960 generation: u64,
3961 }
3962 impl Drop for StartingGuard {
3963 fn drop(&mut self) {
3964 let mut slot = self.runtime.host.lock().expect("host lock");
3965 if self.runtime.host_generation.load(Ordering::SeqCst) == self.generation
3966 && matches!(&*slot, HostSlot::Starting)
3967 {
3968 *slot = HostSlot::Idle;
3969 }
3970 }
3971 }
3972 let mut starting_guard = StartingGuard {
3973 runtime: Arc::clone(&runtime),
3974 generation,
3975 };
3976 shared
3977 .registry
3978 .lock()
3979 .expect("registry lock")
3980 .host_process_started(cohort);
3981 // At most two launches: under `auto`, before anything is pinned, a
3982 // Bun that cannot start is reported once and Node is resolved for the
3983 // rest of the session. An explicit `bun` or `node` never falls back.
3984 let spawned = loop {
3985 runtime.spawn_attempts.fetch_add(1, Ordering::SeqCst);
3986 let options = shared.options.clone();
3987 let snapshot_state_paths: Vec<_> = if tier == HostTier::Plugin {
3988 shared
3989 .attachments
3990 .lock()
3991 .expect("attachments lock")
3992 .values()
3993 .filter_map(|state| state.plugins.state_path().map(Path::to_path_buf))
3994 .collect()
3995 } else {
3996 Vec::new()
3997 };
3998 let (pinned, bun_failed) = {
3999 let runtime = shared.runtime.lock().expect("runtime lock");
4000 (runtime.pinned.clone(), runtime.bun_failed)
4001 };
4002 let cohort_cloned = cohort.clone();
4003 #[cfg(any(test, feature = "test-support"))]
4004 let env_scope = crate::test_support::env_scope_ticket();
4005 let prepared = tokio::task::spawn_blocking(move || {
4006 #[cfg(any(test, feature = "test-support"))]
4007 let _env_scope = crate::test_support::join_env_scope(env_scope);
4008 prepare_launch(
4009 &options,
4010 &cohort_cloned,
4011 pinned,
4012 bun_failed,
4013 &snapshot_state_paths,
4014 )
4015 })
4016 .await
4017 .map_err(|error| format!("plugin host preparation failed: {error}"))
4018 .and_then(|result| result);
4019 let (launch, summary) = match prepared {
4020 Ok(prepared) => prepared,
4021 Err(error) => break Err(error),
4022 };
4023 let events: Arc<dyn HostEvents> = Arc::new(Events {
4024 shared: Arc::downgrade(shared),
4025 cohort: cohort.clone(),
4026 generation,
4027 });
4028 let reason =
4029 match HostProcess::spawn(generation, &launch, bundle_sha256(), events).await {
4030 Ok(host) => break Ok((host, summary)),
4031 Err(reason) => reason,
4032 };
4033 if shared.options.runtime
4034 != codewhale_config::extension_host::ExtensionHostRuntime::Auto
4035 || launch.runtime.kind != codewhale_dependencies::HostRuntimeKind::Bun
4036 || summary.is_none()
4037 {
4038 break Err(reason);
4039 }
4040 shared.runtime.lock().expect("runtime lock").bun_failed = true;
4041 shared.diagnostic(format!(
4042 "{label}: Bun {} at {} failed to start ({reason}); runtime = \"auto\" uses Node for the rest of this session",
4043 launch.runtime.version_string(),
4044 launch.runtime.path.display()
4045 ));
4046 // A fresh generation, so the failed Bun host's exit report can
4047 // never be taken for the Node host's.
4048 generation = {
4049 let slot = runtime.host.lock().expect("host lock");
4050 if runtime.host_generation.load(Ordering::SeqCst) != generation
4051 || !matches!(&*slot, HostSlot::Starting)
4052 {
4053 break Err(format!("{label} startup was superseded"));
4054 }
4055 let next_gen = match cohort {
4056 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
4057 shared.agent_host_generation.fetch_add(1, Ordering::SeqCst) + 1
4058 }
4059 _ => runtime.host_generation.fetch_add(1, Ordering::SeqCst) + 1,
4060 };
4061 runtime.host_generation.store(next_gen, Ordering::SeqCst);
4062 next_gen
4063 };
4064 starting_guard.generation = generation;
4065 };
4066 let mut slot = runtime.host.lock().expect("host lock");
4067 if runtime.host_generation.load(Ordering::SeqCst) != generation
4068 || !matches!(&*slot, HostSlot::Starting)
4069 {
4070 drop(slot);
4071 if let Ok((host, _)) = spawned {
4072 host.terminate("host startup superseded".into());
4073 }
4074 return Err(format!("{label} startup was superseded"));
4075 }
4076 match spawned {
4077 Ok((host, summary)) => {
4078 *slot = HostSlot::Ready(Arc::clone(&host));
4079 drop(slot);
4080 // Pinned only once a host on this runtime has completed the
4081 // handshake; every restart then reuses it.
4082 if let Some(summary) = summary {
4083 let mut runtime = shared.runtime.lock().expect("runtime lock");
4084 if runtime.pinned.is_none() {
4085 runtime.pinned = Some((host.runtime.clone(), summary.clone()));
4086 drop(runtime);
4087 shared.diagnostic(format!("plugin host runtime: {summary}"));
4088 }
4089 }
4090 if host.has_exited() {
4091 Events {
4092 shared: Arc::downgrade(shared),
4093 cohort: cohort.clone(),
4094 generation,
4095 }
4096 .exited(
4097 generation,
4098 "exited immediately after handshake".into(),
4099 host.stderr_tail(),
4100 );
4101 return Err(format!("{label} exited immediately after handshake"));
4102 }
4103 monitor_host(shared, &host, generation);
4104 shared.diagnostic(format!(
4105 "{label} started (pid {}, {} {}, sandbox {})",
4106 host.pid
4107 .map_or_else(|| "?".to_string(), |pid| pid.to_string()),
4108 host.runtime.kind.name(),
4109 host.runtime_version.get().map_or("?", String::as_str),
4110 host.sandbox.label()
4111 ));
4112 Ok(host)
4113 }
4114 Err(reason) => {
4115 runtime
4116 .supervision
4117 .lock()
4118 .expect("supervision lock")
4119 .launch_failed = true;
4120 *slot = HostSlot::Failed {
4121 reason: format!("start failed: {reason}"),
4122 stderr_tail: String::new(),
4123 };
4124 drop(slot);
4125 shared.diagnostic(format!("{label} failed to start: {reason}"));
4126 Err(reason)
4127 }
4128 }
4129 }
4130
4131 /// Bounded shutdown of each tier's host process, if one is running.
4132 /// Production has no such call: the hosts are shared by every engine in
4133 /// the process, so no single engine's shutdown may stop them. When this
4134 /// process ends a host sees stdin EOF and kills its own process tree; if a
4135 /// plugin blocks its event loop, its watchdog thread does so when the
4136 /// parent changes.
4137 #[cfg(any(test, feature = "test-support"))]
4138 pub async fn shutdown(&self) {
4139 for runtime in self.shared.all_runtimes() {
4140 let host = {
4141 let mut slot = runtime.host.lock().expect("host lock");
4142 runtime.host_generation.fetch_add(1, Ordering::SeqCst);
4143 runtime
4144 .supervision
4145 .lock()
4146 .expect("supervision lock")
4147 .retry_ticket += 1;
4148 match std::mem::replace(&mut *slot, HostSlot::Idle) {
4149 HostSlot::Ready(host) | HostSlot::Unresponsive(host) => Some(host),
4150 _ => None,
4151 }
4152 };
4153 if let Some(host) = host {
4154 self.shared
4155 .registry
4156 .lock()
4157 .expect("registry lock")
4158 .revoke_cohort(&host.cohort, "plugin host shut down");
4159 host.shutdown().await;
4160 }
4161 }
4162 }
4163
4164 #[cfg(any(test, feature = "test-support"))]
4165 pub fn host_requests_started(&self) -> Option<u64> {
4166 self.shared
4167 .ready_host(&HostCohort::reviewed())
4168 .ok()
4169 .map(|host| host.requests_started())
4170 }
4171
4172 #[cfg(any(test, feature = "test-support"))]
4173 pub fn host_pid(&self) -> Option<u32> {
4174 self.shared
4175 .ready_host(&HostCohort::reviewed())
4176 .ok()
4177 .and_then(|host| host.pid)
4178 }
4179 }
4180
4181 /// Human-readable host section for `/plugin`.
4182 pub fn render_status(manager: &ExtensionHostManager) -> String {
4183 use std::fmt::Write as _;
4184 let mut out = String::from("Plugin host (experimental): ");
4185 let status = manager.status();
4186 match status.clone() {
4187 HostStatus::Ready {
4188 pid,
4189 runtime,
4190 runtime_version,
4191 sandbox,
4192 memory: _,
4193 } => {
4194 let _ = write!(
4195 out,
4196 "running · pid {} · {runtime} {runtime_version} · {sandbox}",
4197 pid.map_or_else(|| "?".to_string(), |pid| pid.to_string()),
4198 );
4199 }
4200 HostStatus::Failed { stderr_tail, .. } => {
4201 let _ = write!(out, "{status}");
4202 let tail = stderr_tail.trim();
4203 if !tail.is_empty() {
4204 let start = tail
4205 .char_indices()
4206 .rev()
4207 .nth(599)
4208 .map_or(0, |(index, _)| index);
4209 let _ = write!(out, "\n stderr: {}", &tail[start..]);
4210 }
4211 }
4212 down => {
4213 let _ = write!(out, "{down}");
4214 }
4215 }
4216 for (workspace, runtime) in manager
4217 .shared
4218 .agent_cohorts
4219 .lock()
4220 .expect("agent cohorts lock")
4221 .iter()
4222 {
4223 let slot = runtime.host.lock().expect("host lock");
4224 match &*slot {
4225 HostSlot::Ready(host) if !host.has_exited() && !host.is_retiring() => {
4226 let _ = write!(
4227 out,
4228 "\n agent host ({}): running · pid {} · {} {} · {}",
4229 workspace.display(),
4230 host.pid
4231 .map_or_else(|| "?".to_string(), |pid| pid.to_string()),
4232 host.runtime.kind.name(),
4233 host.runtime_version.get().map_or("?", String::as_str),
4234 host.sandbox.label()
4235 );
4236 }
4237 HostSlot::Idle => {}
4238 other => {
4239 let status = other.status();
4240 let _ = write!(out, "\n agent host ({}): {status}", workspace.display());
4241 }
4242 }
4243 }
4244 if let Some(summary) = manager.runtime_summary() {
4245 let _ = write!(out, "\n runtime: {summary}");
4246 // How the running host's cap is enforced, as its handshake settled
4247 // it; with no host running there is nothing enforced to describe.
4248 if let HostStatus::Ready { memory, .. } = &status {
4249 let cap = manager.shared.options.supervision.memory_cap;
4250 let _ = write!(out, " · {}", memory.describe(cap));
4251 }
4252 }
4253 let _ = write!(
4254 out,
4255 "\n spawn attempts: {} · engines attached: {}",
4256 manager.spawn_attempts(),
4257 manager.attached_engines()
4258 );
4259 // The built-in host is shown only once something has started it (nothing
4260 // does yet); the lists and the shared-process count below are the plugin
4261 // host's.
4262 match manager.tier_status(HostTier::Builtin) {
4263 HostStatus::Idle => {}
4264 HostStatus::Ready {
4265 pid,
4266 runtime,
4267 runtime_version,
4268 sandbox,
4269 memory: _,
4270 } => {
4271 let _ = write!(
4272 out,
4273 "\n built-in host (tier 0): running · pid {} · {runtime} {runtime_version} · {sandbox}",
4274 pid.map_or_else(|| "?".to_string(), |pid| pid.to_string()),
4275 );
4276 }
4277 other => {
4278 let _ = write!(out, "\n built-in host (tier 0): {other}");
4279 }
4280 }
4281 let (tools, commands, reviewed_owners) = {
4282 let registry = manager.shared.registry.lock().expect("registry lock");
4283 let reviewed_owners = registry
4284 .owners()
4285 .filter(|entry| {
4286 entry.cohort == HostCohort::reviewed() && entry.state == OwnerState::Active
4287 })
4288 .count();
4289 let tools: Vec<_> = registry
4290 .live_tools()
4291 .into_iter()
4292 .filter(|tool| tool.cohort == HostCohort::reviewed())
4293 .collect();
4294 let commands: Vec<_> = registry
4295 .live_commands()
4296 .into_iter()
4297 .filter(|command| command.cohort == HostCohort::reviewed())
4298 .collect();
4299 (tools, commands, reviewed_owners)
4300 };
4301 if reviewed_owners > 1 {
4302 let _ = write!(
4303 out,
4304 "\n {reviewed_owners} plugins share this one host process and can alter each other's behaviour"
4305 );
4306 }
4307 for tool in tools {
4308 let _ = write!(
4309 out,
4310 "\n tool {} (extension:{}; needs approval, which your approval mode or a session grant for this exact call of this plugin build may give)",
4311 tool.name, tool.plugin_name
4312 );
4313 }
4314 for command in commands {
4315 let _ = write!(
4316 out,
4317 "\n command /{} (extension:{}; runs only when you invoke it)",
4318 command.name, command.plugin_name
4319 );
4320 }
4321 let diagnostics = manager.diagnostics();
4322 for diagnostic in diagnostics.iter().rev().take(5).rev() {
4323 let _ = write!(out, "\n · {diagnostic}");
4324 }
4325 out
4326 }
4327
4328 /// A plugin was enabled, disabled, trusted, revoked or removed: refresh the
4329 /// workspace view now, and when the extension host is enabled reconcile it so
4330 /// a disabled plugin's calls are cancelled and its code torn down without
4331 /// waiting for the next turn.
4332 pub fn plugins_changed(plugins: Arc<PluginRegistry>) {
4333 let manager = manager();
4334 manager.refresh_workspace(&plugins);
4335 if activation::extension_host_policy_enabled() {
4336 manager.revoke_stale_or_removed_owners(&plugins);
4337 manager.retry_cohort(&HostCohort::reviewed());
4338 manager.retry_cohort(&HostCohort::agent(plugins.workspace()));
4339 manager.reload_and_reconcile_in_background();
4340 }
4341 }
4342
4343 pub async fn plugins_changed_and_wait(
4344 plugins: &Arc<PluginRegistry>,
4345 plugin_id: Option<&str>,
4346 expected_authority: Option<&PluginAuthority>,
4347 exempt_invocation_id: Option<u64>,
4348 wait_for_owner: bool,
4349 cancel: &CancellationToken,
4350 timeout: Duration,
4351 ) -> Result<Option<OwnerReport>, String> {
4352 manager()
4353 .plugins_changed_and_wait(
4354 plugins,
4355 plugin_id,
4356 expected_authority,
4357 exempt_invocation_id,
4358 wait_for_owner,
4359 cancel,
4360 timeout,
4361 )
4362 .await
4363 }
4364
4365 /// Install the user's per-plugin settings at boot (the host's other boot
4366 /// options are `configure`). `source` is the config file `/plugin reload`
4367 /// re-reads them from. No-op with the flag off.
4368 pub fn install_plugin_settings(
4369 settings: Option<&BTreeMap<String, codewhale_config::extension_host::PluginSettings>>,
4370 source: Option<PathBuf>,
4371 ) {
4372 if activation::extension_host_policy_enabled() {
4373 manager().set_plugin_settings(settings.unwrap_or(&BTreeMap::new()), source);
4374 }
4375 }
4376
4377 /// What the user configured for `plugin_name` (keys only, or the reason it is
4378 /// refused), for `/plugin show`. `None` with the flag off or nothing configured.
4379 #[must_use]
4380 pub fn plugin_config_summary(plugin_name: &str) -> Option<Result<Vec<String>, String>> {
4381 if !activation::extension_host_policy_enabled() {
4382 return None;
4383 }
4384 manager().plugin_config_summary(plugin_name)
4385 }
4386
4387 /// The live extension commands of `workspace`'s reviewed plugins, for the user
4388 /// command registry. Empty with the flag off. Never starts the host.
4389 #[must_use]
4390 pub fn live_commands_for(workspace: &Path) -> Vec<command::ExtensionCommandEntry> {
4391 if !activation::extension_host_policy_enabled() {
4392 return Vec::new();
4393 }
4394 manager().commands_for_workspace(workspace)
4395 }
4396
4397 pub fn live_commands_for_plugins(plugins: &PluginRegistry) -> Vec<command::ExtensionCommandEntry> {
4398 if !activation::extension_host_policy_enabled() {
4399 return Vec::new();
4400 }
4401 manager().commands_for_plugins(plugins)
4402 }
4403
4404 /// Run an extension command the user invoked; see [`command::run`]. Errors
4405 /// are the text to show.
4406 #[cfg(any(test, feature = "test-support"))]
4407 pub async fn run_command(
4408 command: &command::ExtensionCommandRef,
4409 raw_input: &str,
4410 session_id: Option<&str>,
4411 ) -> Result<command::CommandOutcome, String> {
4412 command::run(&manager().shared, command, raw_input, session_id).await
4413 }
4414
4415 /// The command the current UI caller selected. A stale focus cannot consume a
4416 /// command reference captured from another agent's palette.
4417 pub async fn run_command_for_plugins(
4418 command: &command::ExtensionCommandRef,
4419 raw_input: &str,
4420 session_id: Option<&str>,
4421 plugins: &PluginRegistry,
4422 ) -> Result<command::CommandOutcome, String> {
4423 if command.scope.is_some() && command.selection != plugins.caller_selection() {
4424 return Err("Native command belongs to a different caller; select it again".into());
4425 }
4426 command::run(&manager().shared, command, raw_input, session_id).await
4427 }
4428
4429 /// The `/plugin` section. With the experimental host off it is one line
4430 /// saying so.
4431 #[must_use]
4432 pub fn status_report() -> String {
4433 if !activation::extension_host_policy_enabled() {
4434 return format!("Plugin host (experimental): {}", HostStatus::Disabled);
4435 }
4436 render_status(&manager())
4437 }
4438
4439 pub struct OwnerReport {
4440 pub cohort: Option<HostCohort>,
4441 pub state: Option<OwnerState>,
4442 pub tools: Vec<String>,
4443 pub diagnostics: Vec<String>,
4444 }
4445
4446 /// The resolved plugin id is supplied by the existing `/plugin show` facet.
4447 pub fn owner_report(plugin_id: &str) -> Option<OwnerReport> {
4448 if !activation::extension_host_policy_enabled() {
4449 return None;
4450 }
4451 manager().owner_report(plugin_id)
4452 }
4453
4454 /// Where a built-in module's source is expected:
4455 /// `<bundle dir>/builtin/<module>.mjs`, beside the bundle that was
4456 /// materialized for this build.
4457 fn builtin_source_path(root: &Path, module: &BuiltinModule) -> PathBuf {
4458 supervisor::bundle_dir(root, bundle_sha256())
4459 .join("builtin")
4460 .join(format!("{}.mjs", module.id))
4461 }
4462
4463 /// Reviewed, enabled plugins with `native` entries, keyed by plugin id, read
4464 /// from Codewhale's immutable staged snapshot. Blocking.
4465 fn desired_owners(plugins: &PluginRegistry) -> (BTreeMap<String, DesiredOwner>, Vec<String>) {
4466 let (sources, errors) = codewhale_plugins::runtime::active_component_sources(
4467 plugins,
4468 PluginActivationCapability::Native,
4469 );
4470 desired_owners_from(plugins, sources, errors)
4471 }
4472
4473 fn desired_owners_from(
4474 plugins: &PluginRegistry,
4475 sources: Vec<codewhale_plugins::runtime::PluginComponentSource>,
4476 mut errors: Vec<String>,
4477 ) -> (BTreeMap<String, DesiredOwner>, Vec<String>) {
4478 let mut desired: BTreeMap<String, DesiredOwner> = BTreeMap::new();
4479 let mut broken: BTreeSet<String> = BTreeSet::new();
4480 let mut needs_selection: BTreeSet<String> = BTreeSet::new();
4481 for source in sources {
4482 let plugin_id = source.authority.plugin_id.as_str().to_string();
4483 if plugins.native_catalog_requires_selection(&plugin_id) {
4484 if needs_selection.insert(plugin_id.clone()) {
4485 errors.push(format!("Plugin `{}` raw agent-presets has no default; select a reviewed roster preset before activation", source.plugin_name));
4486 }
4487 continue;
4488 }
4489 // A plugin id can never be a tier-0 owner id. Discovery builds ids as
4490 // `<scope>/<hex>/<name>` and a manifest name cannot hold `:`, so this
4491 // cannot fire; it is the last check before an id reaches the host.
4492 if let Err(reason) = HostTier::Plugin.check_owner_id(&plugin_id) {
4493 errors.push(format!(
4494 "Plugin `{}` native entry {} was denied: {reason}",
4495 source.plugin_name,
4496 source.path.display()
4497 ));
4498 broken.insert(plugin_id);
4499 continue;
4500 }
4501 // The rule discovery reports, re-checked on the staged copy: the
4502 // name here, and file-ness by the read itself.
4503 let bytes = match codewhale_plugins::runtime::native_entry_problem(&source.path, true) {
4504 None => std::fs::read(&source.path).map_err(|error| error.to_string()),
4505 Some(problem) => Err(problem.to_string()),
4506 };
4507 match bytes {
4508 Ok(bytes) => {
4509 let digest = hex(Sha256::digest(&bytes));
4510 if !plugins.native_entry_selected(
4511 &plugin_id,
4512 &source.path.to_string_lossy(),
4513 &digest,
4514 ) {
4515 continue;
4516 }
4517 if !desired.contains_key(&plugin_id) {
4518 let record = match codewhale_plugins::registry::reviewed_record(
4519 &source.authority,
4520 ) {
4521 Ok(record) => record,
4522 Err(reason) => {
4523 if broken.insert(plugin_id) {
4524 errors.push(format!(
4525 "Plugin `{}` was not loaded because its review record could not be read: {reason}",
4526 source.plugin_name
4527 ));
4528 }
4529 continue;
4530 }
4531 };
4532 let record_approver = record.approved_by.as_ref();
4533 let snapshot_approver = plugins
4534 .get(&plugin_id)
4535 .and_then(|plugin| plugin.approved_by.as_ref());
4536 if record_approver != snapshot_approver {
4537 if broken.insert(plugin_id) {
4538 errors.push(format!(
4539 "Plugin `{}` was not loaded because review record approver disagrees with snapshot",
4540 source.plugin_name
4541 ));
4542 }
4543 continue;
4544 }
4545 let approver = match record_approver {
4546 Some(a) => a,
4547 None => {
4548 if broken.insert(plugin_id) {
4549 errors.push(format!(
4550 "Plugin `{}` was not loaded because review record has no approver",
4551 source.plugin_name
4552 ));
4553 }
4554 continue;
4555 }
4556 };
4557 let cohort = approver.cohort();
4558 if let PluginCohort::Agent { ref workspace } = cohort {
4559 let norm_rec =
4560 codewhale_config::normalize_project_workspace(Path::new(workspace));
4561 let norm_sess =
4562 codewhale_config::normalize_project_workspace(plugins.workspace());
4563 let match_ws = match (&norm_rec, &norm_sess) {
4564 (Ok(a), Ok(b)) => a == b,
4565 _ => Path::new(workspace) == plugins.workspace(),
4566 };
4567 if !match_ws {
4568 if broken.insert(plugin_id) {
4569 errors.push(format!(
4570 "Plugin `{}` was approved for another project workspace and cannot load here",
4571 source.plugin_name
4572 ));
4573 }
4574 continue;
4575 }
4576 }
4577 desired.insert(
4578 plugin_id.clone(),
4579 DesiredOwner {
4580 cohort: HostCohort::from_plugin_cohort(cohort),
4581 plugin_name: source.plugin_name.clone(),
4582 authority: source.authority.clone(),
4583 entries: Vec::new(),
4584 host_services: record
4585 .host_services
4586 .into_iter()
4587 .filter_map(|service| protocol::DshService::parse(service.name()))
4588 .collect(),
4589 },
4590 );
4591 }
4592 let Some(owner) = desired.get_mut(&plugin_id) else {
4593 continue;
4594 };
4595 // The manifest may name one file twice; it is one entry.
4596 if !owner.entries.iter().any(|(path, _)| *path == source.path) {
4597 owner
4598 .entries
4599 .push((source.path.clone(), hex(Sha256::digest(&bytes))));
4600 }
4601 }
4602 Err(reason) => {
4603 errors.push(format!(
4604 "Plugin `{}` native entry {} was denied: {reason}",
4605 source.plugin_name,
4606 source.path.display()
4607 ));
4608 broken.insert(plugin_id);
4609 }
4610 }
4611 }
4612 // All-or-nothing per plugin: one unusable entry keeps the whole plugin out.
4613 for plugin_id in broken {
4614 desired.remove(&plugin_id);
4615 }
4616 (desired, errors)
4617 }
4618
4619 struct AttachmentSnapshot {
4620 id: u64,
4621 plugins: Arc<PluginRegistry>,
4622 route_authority: Option<Arc<PluginAuthority>>,
4623 }
4624
4625 /// One scan of the complete attachment set. Its per-engine views and global
4626 /// owner union must be published together, against those same snapshots.
4627 struct DesiredScan {
4628 attachments: Vec<(u64, Arc<PluginRegistry>, BTreeMap<String, String>)>,
4629 owners: BTreeMap<String, DesiredOwner>,
4630 errors: Vec<String>,
4631 }
4632
4633 impl DesiredScan {
4634 fn publish(
4635 self,
4636 current: &mut BTreeMap<u64, AttachmentState>,
4637 ) -> Option<(BTreeMap<String, DesiredOwner>, Vec<String>)> {
4638 if current.len() != self.attachments.len()
4639 || self.attachments.iter().any(|(id, scanned, _)| {
4640 !current
4641 .get(id)
4642 .is_some_and(|state| Arc::ptr_eq(&state.plugins, scanned))
4643 })
4644 {
4645 return None;
4646 }
4647 for (id, _, desired) in self.attachments {
4648 let state = current.get_mut(&id).expect("validated attachment");
4649 let entries = self
4650 .owners
4651 .iter()
4652 .flat_map(|(plugin_id, want)| {
4653 want.entries.iter().filter_map(|(path, sha256)| {
4654 let entry = EntryRef {
4655 path: path.to_string_lossy().into_owned(),
4656 sha256: sha256.clone(),
4657 };
4658 (desired.get(plugin_id) == Some(&want.authority.content_hash)
4659 && state.plugins.native_entry_selected(
4660 plugin_id,
4661 &entry.path,
4662 &entry.sha256,
4663 ))
4664 .then(|| {
4665 codewhale_plugins::composition_scope::NativePresetRef {
4666 plugin_id: plugin_id.clone(),
4667 content_hash: want.authority.content_hash.clone(),
4668 entry,
4669 }
4670 })
4671 })
4672 })
4673 .collect();
4674 state.selection = codewhale_plugins::composition_scope::CompositionSelection {
4675 revision: state.plugins.caller_selection(),
4676 desired: desired.clone(),
4677 entries,
4678 };
4679 state.desired = desired;
4680 }
4681 command::bump_epoch();
4682 Some((self.owners, self.errors))
4683 }
4684 }
4685
4686 /// Scan every attached snapshot (engines sharing one snapshot scan it once)
4687 /// and merge what they desire. Blocking.
4688 ///
4689 /// Two snapshots can disagree about one plugin id only while one of them is
4690 /// stale; the stale one then fails its persisted-state check and desires
4691 /// nothing, so the first valid scan wins and the per-attachment hashes keep
4692 /// each engine's tools to the bytes it desires.
4693 fn union_of_desired_owners(snapshots: Vec<AttachmentSnapshot>) -> DesiredScan {
4694 let mut union: BTreeMap<String, DesiredOwner> = BTreeMap::new();
4695 let mut per_attachment = Vec::with_capacity(snapshots.len());
4696 let mut scanned: Vec<(Arc<PluginRegistry>, BTreeMap<String, String>)> = Vec::new();
4697 let mut errors: Vec<String> = Vec::new();
4698 let mut conflicted: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
4699 for AttachmentSnapshot {
4700 id,
4701 plugins,
4702 route_authority,
4703 } in snapshots
4704 {
4705 if route_authority.is_none()
4706 && let Some((_, hashes)) = scanned.iter().find(|(seen, _)| Arc::ptr_eq(seen, &plugins))
4707 {
4708 per_attachment.push((id, Arc::clone(&plugins), hashes.clone()));
4709 continue;
4710 }
4711 let (mut desired, scan_errors) = desired_owners(&plugins);
4712 if let Some(authority) = &route_authority {
4713 desired.retain(|_, want| &want.authority == authority.as_ref());
4714 }
4715 for error in scan_errors {
4716 if !errors.contains(&error) {
4717 errors.push(error);
4718 }
4719 }
4720 let hashes: BTreeMap<String, String> = desired
4721 .iter()
4722 .map(|(plugin_id, want)| (plugin_id.clone(), want.authority.content_hash.clone()))
4723 .collect();
4724 for (plugin_id, want) in desired {
4725 if conflicted.contains(&plugin_id) {
4726 continue;
4727 }
4728 match union.entry(plugin_id.clone()) {
4729 std::collections::btree_map::Entry::Vacant(entry) => {
4730 entry.insert(want);
4731 }
4732 std::collections::btree_map::Entry::Occupied(mut entry) => {
4733 if entry.get().cohort != want.cohort {
4734 conflicted.insert(plugin_id);
4735 errors.push(format!(
4736 "Plugin `{}` was requested in conflicting cohorts",
4737 want.plugin_name
4738 ));
4739 entry.remove();
4740 continue;
4741 }
4742 if entry.get().authority != want.authority {
4743 continue;
4744 }
4745 for native in want.entries {
4746 if !entry.get().entries.contains(&native) {
4747 entry.get_mut().entries.push(native);
4748 }
4749 }
4750 }
4751 }
4752 }
4753 per_attachment.push((id, Arc::clone(&plugins), hashes.clone()));
4754 if route_authority.is_none() {
4755 scanned.push((plugins, hashes));
4756 }
4757 }
4758 if !conflicted.is_empty() {
4759 for plugin_id in &conflicted {
4760 union.remove(plugin_id);
4761 }
4762 for (_, _, hashes) in &mut per_attachment {
4763 for plugin_id in &conflicted {
4764 hashes.remove(plugin_id);
4765 }
4766 }
4767 }
4768 DesiredScan {
4769 attachments: per_attachment,
4770 owners: union,
4771 errors,
4772 }
4773 }
4774
4775 /// One engine's hold on the process-wide extension host.
4776 ///
4777 /// The engine publishes its workspace plugin snapshot here and installs only
4778 /// the tools of owners that snapshot desires. Dropping it detaches without
4779 /// revoking anything: the next reconcile revokes owners no remaining
4780 /// attachment desires, so an engine being replaced never tears down plugins
4781 /// its successor is about to use.
4782 pub struct HostAttachment {
4783 id: u64,
4784 manager: Arc<ExtensionHostManager>,
4785 }
4786
4787 impl HostAttachment {
4788 #[must_use]
4789 pub fn manager(&self) -> &Arc<ExtensionHostManager> {
4790 &self.manager
4791 }
4792
4793 /// The engine switched workspace: publish the new snapshot.
4794 pub fn set_plugins(&self, plugins: Arc<PluginRegistry>) {
4795 self.manager.shared.core_calls.revoke_attachment(self.id);
4796 self.manager
4797 .shared
4798 .execution_broker
4799 .revoke_attachment(self.id);
4800 if let Some(state) = self
4801 .manager
4802 .shared
4803 .attachments
4804 .lock()
4805 .expect("attachments lock")
4806 .get_mut(&self.id)
4807 {
4808 state.selection_cancel.cancel();
4809 state.selection_cancel = CancellationToken::new();
4810 state.revision += 1;
4811 state.plugins = Arc::new(plugins.bind_caller(
4812 codewhale_plugins::composition_scope::SelectionRevision {
4813 attachment_id: self.id,
4814 revision: state.revision,
4815 },
4816 ));
4817 state.desired.clear();
4818 state.selection = Default::default();
4819 }
4820 command::bump_epoch();
4821 }
4822
4823 pub fn set_identity(&self, session_id: Option<String>, agent_id: Option<String>) {
4824 let mut left = None;
4825 let mut dropped_creator = false;
4826 if let Some(state) = self
4827 .manager
4828 .shared
4829 .attachments
4830 .lock()
4831 .expect("attachments lock")
4832 .get_mut(&self.id)
4833 {
4834 if state.session_id != session_id {
4835 left = state.session_id.take();
4836 }
4837 if agent_id.is_some() && state.creator_demanded {
4838 state.creator_demanded = false;
4839 dropped_creator = true;
4840 }
4841 state.session_id = session_id;
4842 state.agent_id = agent_id;
4843 }
4844 if dropped_creator
4845 && self
4846 .manager
4847 .shared
4848 .creator_users
4849 .fetch_sub(1, Ordering::SeqCst)
4850 == 1
4851 {
4852 self.manager.reconcile_in_background();
4853 }
4854 if let Some(left) = left {
4855 dsh_remote::end_remote_session(&left);
4856 }
4857 }
4858
4859 pub fn set_creator_demand(&self, demanded: bool) -> bool {
4860 let delta = {
4861 let mut attachments = self
4862 .manager
4863 .shared
4864 .attachments
4865 .lock()
4866 .expect("attachments lock");
4867 let Some(state) = attachments.get_mut(&self.id) else {
4868 return false;
4869 };
4870 let next = demanded && state.agent_id.is_none();
4871 if state.creator_demanded == next {
4872 return false;
4873 }
4874 state.creator_demanded = next;
4875 next
4876 };
4877 if delta {
4878 self.manager
4879 .shared
4880 .creator_users
4881 .fetch_add(1, Ordering::SeqCst);
4882 } else {
4883 self.manager
4884 .shared
4885 .creator_users
4886 .fetch_sub(1, Ordering::SeqCst);
4887 }
4888 true
4889 }
4890
4891 #[must_use]
4892 pub fn creator_ready(&self) -> bool {
4893 self.manager
4894 .shared
4895 .registry
4896 .lock()
4897 .expect("registry lock")
4898 .owner("host:creator")
4899 .is_some_and(|entry| entry.state == OwnerState::Active)
4900 }
4901
4902 pub fn sync_creator_in_background(&self) {
4903 if tokio::runtime::Handle::try_current().is_err() {
4904 return;
4905 }
4906 let manager = Arc::clone(&self.manager);
4907 tokio::spawn(async move {
4908 if let Err(error) = manager.reconcile_with_policy(false).await {
4909 manager.shared.diagnostic(error);
4910 }
4911 });
4912 }
4913
4914 async fn sync_policy_within(&self, policy: bool, limit: Duration) -> bool {
4915 if tokio::runtime::Handle::try_current().is_err() {
4916 return false;
4917 }
4918 let cancel = CancellationToken::new();
4919 let task_cancel = cancel.clone();
4920 let manager = Arc::clone(&self.manager);
4921 let mut task = tokio::spawn(async move {
4922 if let Err(error) = manager
4923 .reconcile_with_policy_cancel(policy, Some(&task_cancel))
4924 .await
4925 {
4926 manager.shared.diagnostic(error);
4927 }
4928 });
4929 tokio::select! {
4930 result = &mut task => result.is_ok(),
4931 () = tokio::time::sleep(limit) => {
4932 // Signal cooperative cancellation so reconcile stops at its next safe point
4933 // without aborting an in-flight host handshake that may legitimately take
4934 // longer than the first-sync wait (up to HANDSHAKE_DEADLINE).
4935 cancel.cancel();
4936 self.manager.shared.diagnostic(format!(
4937 "plugin host sync timed out after {}ms and signalled cancellation",
4938 limit.as_millis()
4939 ));
4940 false
4941 }
4942 }
4943 }
4944
4945 pub async fn sync_creator_within(&self, limit: Duration) -> bool {
4946 self.sync_policy_within(false, limit).await
4947 }
4948
4949 pub fn install_creator_tools(
4950 &self,
4951 tool_registry: &mut crate::tools::ToolRegistry,
4952 ) -> Vec<String> {
4953 let allowed = self
4954 .manager
4955 .shared
4956 .attachments
4957 .lock()
4958 .expect("attachments lock")
4959 .get(&self.id)
4960 .is_some_and(|state| state.creator_demanded && state.agent_id.is_none())
4961 && self.manager.shared.creator_users.load(Ordering::SeqCst) > 0;
4962 if !allowed {
4963 return Vec::new();
4964 }
4965 let tools: Vec<ToolRegistration> = self
4966 .manager
4967 .shared
4968 .registry
4969 .lock()
4970 .expect("registry lock")
4971 .live_tools()
4972 .into_iter()
4973 .filter(|tool| {
4974 tool.tier() == HostTier::Builtin && tool.owner.plugin_id == "host:creator"
4975 })
4976 .collect();
4977 if tools.is_empty() {
4978 return Vec::new();
4979 }
4980 if tool_registry.get(dsh_broker::ACT_TOOL).is_none() {
4981 tool_registry.register(Arc::new(dsh_broker::BrokerActTool::ACT));
4982 }
4983 let taken: HashSet<String> = tool_registry
4984 .names()
4985 .into_iter()
4986 .map(str::to_ascii_lowercase)
4987 .collect();
4988 let mut installed = Vec::new();
4989 for registration in tools {
4990 if taken.contains(&registration.name.to_ascii_lowercase()) {
4991 let origin = tool_registry
4992 .get(&registration.name)
4993 .map(|existing| existing.registration_origin().into_owned())
4994 .unwrap_or_else(|| "another tool".to_string());
4995 self.manager.shared.plugin_diagnostic(
4996 &registration.owner.plugin_id,
4997 format!(
4998 "plugin tool `{}` from `{}` skipped: the name is already registered by {origin}",
4999 registration.name, registration.plugin_name
5000 ),
5001 );
5002 continue;
5003 }
5004 installed.push(registration.name.clone());
5005 tool_registry.register(Arc::new(tool::HostToolSpec::for_selection(
5006 registration,
5007 Arc::clone(&self.manager.shared),
5008 None,
5009 )));
5010 }
5011 installed
5012 }
5013 pub fn plugin_view(&self) -> Arc<PluginRegistry> {
5014 self.manager
5015 .shared
5016 .attachments
5017 .lock()
5018 .expect("attachments lock")
5019 .get(&self.id)
5020 .map(|state| Arc::clone(&state.plugins))
5021 .unwrap_or_else(|| Arc::new(PluginRegistry::new()))
5022 }
5023 pub async fn reconcile(&self) -> Result<(), String> {
5024 self.manager.reconcile().await
5025 }
5026
5027 /// Reconcile the host against every attachment, waiting for it.
5028 #[cfg(any(test, feature = "test-support"))]
5029 pub async fn sync(&self) -> Result<(), String> {
5030 self.manager.reconcile().await
5031 }
5032
5033 /// Reconcile the host against every attachment, without waiting.
5034 pub fn sync_in_background(&self) {
5035 self.manager.reconcile_in_background();
5036 }
5037
5038 pub fn selection_settled(&self) -> bool {
5039 self.manager
5040 .shared
5041 .attachments
5042 .lock()
5043 .expect("attachments lock")
5044 .get(&self.id)
5045 .is_some_and(|state| {
5046 state.settled.is_some() && state.settled == state.plugins.caller_selection()
5047 })
5048 }
5049
5050 pub async fn sync_within(&self, limit: Duration) -> bool {
5051 self.sync_policy_within(activation::extension_host_policy_enabled(), limit)
5052 .await
5053 }
5054
5055 /// Add this engine's live extension tools to `tool_registry`.
5056 pub fn install_tools(&self, tool_registry: &mut crate::tools::ToolRegistry) -> Vec<String> {
5057 self.manager.install_tools_for(self.id, tool_registry)
5058 }
5059 }
5060
5061 impl ManagerShared {
5062 pub fn plugins_for_selection(
5063 &self,
5064 revision: codewhale_plugins::composition_scope::SelectionRevision,
5065 session_id: Option<&str>,
5066 ) -> Option<(Arc<PluginRegistry>, Option<String>)> {
5067 self.attachments
5068 .lock()
5069 .expect("attachments lock")
5070 .get(&revision.attachment_id)
5071 .filter(|state| {
5072 state.revision == revision.revision && state.session_id.as_deref() == session_id
5073 })
5074 .map(|state| (Arc::clone(&state.plugins), state.agent_id.clone()))
5075 }
5076 pub(super) fn selection_cancellation(
5077 &self,
5078 revision: codewhale_plugins::composition_scope::SelectionRevision,
5079 ) -> Option<CancellationToken> {
5080 self.attachments
5081 .lock()
5082 .expect("attachments lock")
5083 .get(&revision.attachment_id)
5084 .filter(|state| state.revision == revision.revision)
5085 .map(|state| state.selection_cancel.clone())
5086 }
5087 pub fn selection(&self, id: u64) -> codewhale_plugins::composition_scope::CompositionSelection {
5088 self.attachments
5089 .lock()
5090 .expect("attachments lock")
5091 .get(&id)
5092 .map(|state| state.selection.clone())
5093 .unwrap_or_default()
5094 }
5095 pub fn selection_current(
5096 &self,
5097 selection: codewhale_plugins::composition_scope::SelectionRevision,
5098 plugin_id: &str,
5099 hash: &str,
5100 scope: Option<&EntryRef>,
5101 ) -> bool {
5102 self.attachments
5103 .lock()
5104 .expect("attachments lock")
5105 .get(&selection.attachment_id)
5106 .is_some_and(|state| {
5107 state.revision == selection.revision
5108 && state.selection.includes(plugin_id, hash, scope)
5109 })
5110 }
5111 pub(super) fn broker_services(&self, owner: &OwnerRef) -> Vec<protocol::DshService> {
5112 if let Some(granted) = dsh_broker::test_grants() {
5113 return granted;
5114 }
5115 dsh_broker::granted_services(&self.registry.lock().expect("registry lock"), owner)
5116 }
5117
5118 pub(super) async fn broker_granted(
5119 &self,
5120 owner: &OwnerRef,
5121 service: protocol::DshService,
5122 ) -> bool {
5123 if let Some(granted) = dsh_broker::builtin_granted(
5124 &self.registry.lock().expect("registry lock"),
5125 owner,
5126 service,
5127 ) {
5128 return granted;
5129 }
5130 if let Some(granted) = dsh_broker::test_grants() {
5131 return granted.contains(&service);
5132 }
5133 let (_cohort, authorities) = {
5134 let registry = self.registry.lock().expect("registry lock");
5135 if !dsh_broker::granted(&registry, owner, service) {
5136 return false;
5137 }
5138 let cohort = registry.cohort_of(owner).unwrap_or(HostCohort::reviewed());
5139 (cohort.clone(), registry.cohort_authorities(&cohort))
5140 };
5141 let Some(wanted) = codewhale_plugins::host_services::HostService::parse(service.name())
5142 else {
5143 return false;
5144 };
5145 let policy = activation::extension_host_policy_enabled();
5146 #[cfg(any(test, feature = "test-support"))]
5147 let env_scope = crate::test_support::env_scope_ticket();
5148 tokio::task::spawn_blocking(move || {
5149 #[cfg(any(test, feature = "test-support"))]
5150 let _env_scope = crate::test_support::join_env_scope(env_scope);
5151 let _scope = activation::PolicyScope::propagate(policy);
5152 authorities.iter().all(|authority| {
5153 codewhale_plugins::registry::granted_host_services(authority)
5154 .is_ok_and(|granted| granted.contains(&wanted))
5155 })
5156 })
5157 .await
5158 .unwrap_or(false)
5159 }
5160
5161 pub fn check_selection(
5162 &self,
5163 selection: Option<codewhale_plugins::composition_scope::SelectionRevision>,
5164 plugins: Option<&PluginRegistry>,
5165 plugin_id: &str,
5166 hash: &str,
5167 scope: Option<&EntryRef>,
5168 ) -> Result<(), String> {
5169 if scope.is_none() {
5170 return Ok(());
5171 }
5172 let selection = selection.ok_or("Native contribution has no caller selection")?;
5173 if plugins.and_then(PluginRegistry::caller_selection) != Some(selection)
5174 || !self.selection_current(selection, plugin_id, hash, scope)
5175 {
5176 return Err("Native contribution is no longer selected for this caller".into());
5177 }
5178 Ok(())
5179 }
5180 }
5181 /// Last-consumer guard for any tool executed under a caller-bound composition.
5182 pub fn validate_caller_plugins(plugins: Option<&PluginRegistry>) -> Result<(), String> {
5183 let Some(revision) = plugins.and_then(PluginRegistry::caller_selection) else {
5184 return Ok(());
5185 };
5186 let manager = manager();
5187 let attachments = manager.shared.attachments.lock().expect("attachments lock");
5188 if attachments
5189 .get(&revision.attachment_id)
5190 .is_some_and(|state| state.revision == revision.revision)
5191 {
5192 Ok(())
5193 } else {
5194 Err("Native caller composition changed or was detached; prepare the call again".into())
5195 }
5196 }
5197 /// Raw catalog choices are revalidated against the reviewed staged bundle;
5198 /// discovery never activates them. Generic Native entries retain active-scope
5199 /// discovery. Child preparation revalidates before attaching the chosen entry.
5200 pub fn native_presets_for_plugins(
5201 plugins: &PluginRegistry,
5202 ) -> Vec<(
5203 codewhale_plugins::composition_scope::NativePresetRef,
5204 PluginAuthority,
5205 )> {
5206 if !activation::extension_host_policy_enabled() {
5207 return Vec::new();
5208 }
5209 let manager = manager();
5210 let mut presets: Vec<_> = codewhale_plugins::native_presets::admitted_entries(plugins)
5211 .into_iter()
5212 .map(|(preset, _, authority)| (preset, authority))
5213 .collect();
5214 let registry = manager.shared.registry.lock().expect("registry lock");
5215 for owner in registry.owners() {
5216 let Some(authority) = owner.authority.as_ref() else {
5217 continue;
5218 };
5219 if owner.tier() != HostTier::Plugin
5220 || owner.state != OwnerState::Active
5221 || manager.shared.ready_host(&owner.cohort).is_err()
5222 || authority.workspace != plugins.workspace()
5223 || !plugins.get(&owner.owner.plugin_id).is_some_and(|plugin| {
5224 plugin.component_active(PluginActivationCapability::Native)
5225 && plugin.content_hash == owner.content_hash
5226 && plugin.state_generation == authority.state_generation
5227 })
5228 {
5229 continue;
5230 }
5231 for (entry, state) in &owner.scopes {
5232 if *state == OwnerState::Active
5233 && !presets.iter().any(|(preset, _)| {
5234 preset.plugin_id == owner.owner.plugin_id && preset.entry == *entry
5235 })
5236 {
5237 presets.push((
5238 codewhale_plugins::composition_scope::NativePresetRef {
5239 plugin_id: owner.owner.plugin_id.clone(),
5240 content_hash: owner.content_hash.clone(),
5241 entry: entry.clone(),
5242 },
5243 authority.clone(),
5244 ));
5245 }
5246 }
5247 }
5248 presets.sort_by(|(left, _), (right, _)| {
5249 left.plugin_id
5250 .cmp(&right.plugin_id)
5251 .then_with(|| left.entry.path.cmp(&right.entry.path))
5252 });
5253 presets
5254 }
5255
5256 pub fn caller_view(
5257 workspace: &Path,
5258 session_id: Option<&str>,
5259 agent_id: Option<&str>,
5260 ) -> Option<Arc<PluginRegistry>> {
5261 let manager = manager();
5262 let attachments = manager.shared.attachments.lock().expect("attachments lock");
5263 let mut found = attachments.values().filter(|state| {
5264 state.plugins.workspace() == workspace
5265 && state.session_id.as_deref() == session_id
5266 && state.agent_id.as_deref() == agent_id
5267 });
5268 let view = found.next().map(|state| Arc::clone(&state.plugins));
5269 if found.next().is_some() { None } else { view }
5270 }
5271
5272 impl Drop for HostAttachment {
5273 fn drop(&mut self) {
5274 self.manager.shared.core_calls.revoke_attachment(self.id);
5275 let mut dropped_creator = false;
5276 let mut dropped_route = false;
5277 if let Ok(mut attachments) = self.manager.shared.attachments.lock()
5278 && let Some(state) = attachments.remove(&self.id)
5279 {
5280 state.selection_cancel.cancel();
5281 dropped_creator = state.creator_demanded;
5282 dropped_route = state.route_authority.is_some();
5283 }
5284 if (dropped_creator
5285 && self
5286 .manager
5287 .shared
5288 .creator_users
5289 .fetch_sub(1, Ordering::SeqCst)
5290 == 1)
5291 || dropped_route
5292 {
5293 self.manager.reconcile_in_background();
5294 }
5295 command::bump_epoch();
5296 }
5297 }
5298
5299 impl std::fmt::Debug for HostAttachment {
5300 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5301 f.debug_struct("HostAttachment")
5302 .field("id", &self.id)
5303 .finish()
5304 }
5305 }
5306
5307 static GLOBAL: OnceLock<Arc<ExtensionHostManager>> = OnceLock::new();
5308
5309 #[cfg(any(test, feature = "test-support"))]
5310 thread_local! {
5311 static TEST_MANAGER: std::cell::RefCell<Option<Arc<ExtensionHostManager>>> =
5312 const { std::cell::RefCell::new(None) };
5313 }
5314
5315 /// Configure the process-wide manager once, at boot, from user config.
5316 pub fn configure_with_handle(
5317 options: ExtensionHostOptions,
5318 handle: Option<tokio::runtime::Handle>,
5319 ) {
5320 install_ports();
5321 let manager = Arc::new(ExtensionHostManager::new(options));
5322 if let Some(handle) = handle {
5323 manager.bind_engine_handle(handle);
5324 }
5325 let _ = GLOBAL.set(manager);
5326 }
5327
5328 pub fn install_ports() {
5329 codewhale_plugins::composition_review::install_composition_reviewer(composition_review::review);
5330 host_port::install();
5331 }
5332
5333 /// The manager for this engine process (one host per process and tier).
5334 #[must_use]
5335 pub fn manager() -> Arc<ExtensionHostManager> {
5336 install_ports();
5337 #[cfg(any(test, feature = "test-support"))]
5338 if let Some(manager) = TEST_MANAGER.with(|cell| cell.borrow().clone()) {
5339 return manager;
5340 }
5341 Arc::clone(
5342 GLOBAL.get_or_init(|| Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default()))),
5343 )
5344 }
5345
5346 /// Test-only: route [`manager`] on this thread to `manager`.
5347 #[cfg(any(test, feature = "test-support"))]
5348 pub struct TestManagerGuard(Option<Arc<ExtensionHostManager>>);
5349
5350 #[cfg(any(test, feature = "test-support"))]
5351 impl TestManagerGuard {
5352 pub fn current() -> Option<Arc<ExtensionHostManager>> {
5353 TEST_MANAGER.with(|cell| cell.borrow().clone())
5354 }
5355
5356 pub fn install(manager: Arc<ExtensionHostManager>) -> Self {
5357 install_ports();
5358 Self(TEST_MANAGER.with(|cell| cell.replace(Some(manager))))
5359 }
5360 }
5361
5362 #[cfg(any(test, feature = "test-support"))]
5363 impl Drop for TestManagerGuard {
5364 fn drop(&mut self) {
5365 TEST_MANAGER.with(|cell| *cell.borrow_mut() = self.0.take());
5366 }
5367 }
5368
5369 impl ExtensionHostManager {
5370 pub fn has_shell_hooks(&self, event: codewhale_config::hooks::HookEvent) -> bool {
5371 activation::extension_host_policy_enabled()
5372 && self
5373 .shared
5374 .registry
5375 .lock()
5376 .expect("registry lock")
5377 .live_shell_hooks()
5378 .iter()
5379 .any(|r| r.hook.event == event)
5380 }
5381 pub fn shell_hooks(
5382 &self,
5383 caller: &crate::hooks::HookCaller,
5384 event: codewhale_config::hooks::HookEvent,
5385 ) -> Vec<codewhale_config::hooks::Hook> {
5386 if !activation::extension_host_policy_enabled() {
5387 return Vec::new();
5388 }
5389 let Some(plugins) = caller.plugins.as_ref() else {
5390 return Vec::new();
5391 };
5392 let Some(revision) = plugins.caller_selection() else {
5393 return Vec::new();
5394 };
5395 let Some((current, agent)) = self
5396 .shared
5397 .plugins_for_selection(revision, caller.session_id.as_deref())
5398 else {
5399 return Vec::new();
5400 };
5401 if agent != caller.agent_id
5402 || !Arc::ptr_eq(&current, plugins)
5403 || caller.workspace != plugins.workspace()
5404 {
5405 return Vec::new();
5406 }
5407 self.shared
5408 .registry
5409 .lock()
5410 .expect("registry lock")
5411 .live_shell_hooks()
5412 .into_iter()
5413 .filter(|r| {
5414 r.hook.event == event
5415 && plugins.selected_native_entries().iter().any(|entry| {
5416 entry.plugin_id == r.owner.plugin_id
5417 && entry.content_hash == r.content_hash
5418 && r.scope.as_ref().is_none_or(|scope| entry.entry == *scope)
5419 })
5420 })
5421 .map(|r| r.hook)
5422 .collect()
5423 }
5424 }
5425
5425 lines RUST