返回 CodeWhale
supervisor.rs
根目录 / crates / engine / src / extension_host / supervisor.rs
1 //! One extension-host process: launch plan, spawn, handshake, channel, exit.
2 //!
3 //! When the process exits, every in-flight call fails with a typed error.
4 //! The existing Rust manager owns heartbeat, crash budget, generation changes,
5 //! and receipt-checked replay; this channel never replays a tool call.
6 //!
7 //! **Host-originated requests** run as tasks, not inline in the reader. Each
8 //! request the host sends is admitted into [`InboundRequests`] (at most
9 //! [`protocol::MAX_INFLIGHT`] at a time, no id twice, both violations end the
10 //! host) and handed to [`HostEvents::host_request`] as its own task. It is
11 //! cancelled by the host's `$/cancel` (whatever the handler later produces is
12 //! dropped), by its owner's revocation (the host is answered `Cancelled`) and
13 //! by the host's exit (nobody is answered); a handler that ignores its token is
14 //! abandoned [`CANCEL_GRACE`] after the cancel. A method reserved for the other
15 //! tier is neither accepted from the host nor sent to it
16 //! (`protocol::MethodSpec::tiers`), and `host/hello` must report the tier the
17 //! core launched and the built-in module digests it pins
18 //! ([`check_hello_identity`]).
19 //!
20 //! **Tiers** ([`HostTier`]). The host is two processes, one per trust tier,
21 //! started from the same bundle with `--tier=plugin|builtin` as the last
22 //! argument. Each has its own data directory ([`tier_data_dir`]) and its own
23 //! sandbox plan; Native cannot read the builtin tier's data directory.
24 //! Builtin backends are activated separately by the Engine.
25 //!
26 //! **OS sandbox** ([`HostSandbox`]). Native hosts use a restricted positive
27 //! filesystem policy: selected runtime and its libraries, the canonical host
28 //! bundle, Core-managed `.runtime/v2` package snapshots, and shared Native data.
29 //! Writes are limited to Native data and private scratch. Project files,
30 //! including `.env`, and unrelated user files are not granted. This remains
31 //! one trusted Native cohort, not isolation between plugins or their data.
32 //! Builtin keeps its existing separately diagnosed command-sandbox policy.
33 //! * macOS: Seatbelt with explicit reads and no toolchain cache write grants.
34 //! * Linux: bubblewrap starts an empty filesystem and binds explicit grants.
35 //! A finished `<runtime> --version` probe must succeed; missing bubblewrap
36 //! or blocked user namespaces refuses Native launch. Its private PID/network
37 //! namespaces and `--die-with-parent` contain descendants and lifetime.
38 //! * Windows: Native keeps its LPAC AppContainer and Job. Its verified
39 //! runtime/bundle/staged-root ACL grants and startup allow/deny probe remain
40 //! separate from the Unix profile. Builtin retains its diagnosed exception.
41 //!
42 //! Snapshot stores are fixed at Unix host launch. A new store requires a
43 //! restart; every owner admission verifies current authority and containment
44 //! in the captured store roots. Snapshot contents remain subject to the
45 //! existing immutable staging and per-component receipt checks.
46 //!
47 //! **Runtime.** Node (the default) or Bun (opt-in: `runtime = "bun"`, or
48 //! `"auto"`, which prefers a supported Bun), chosen once per manager
49 //! (`[extension_host] runtime`). Each gets its own flags ([`runtime_args`])
50 //! and environment ([`runtime_env`]); Bun silently ignores Node's heap and
51 //! `__proto__` flags. The host itself takes in-process native code away from
52 //! plugins (`extension-host/src/runtime.ts`: `bun:ffi`, `Bun.FFI`, SQLite
53 //! extension loading, Worker threads, ShadowRealm, `process.dlopen`) and
54 //! refuses to start if a lock does not hold. That lockdown covers the entry
55 //! points found so far (Bun 1.4, Node 22 and 26), not every one a runtime
56 //! may add.
57 //!
58 //! **Memory cap** ([`MemoryEnforcement`]). What was measured where: the
59 //! macOS mechanism on macOS 26.1 arm64 (2026-09-30, Bun 1.4.0 and Node);
60 //! the Linux thresholds in [`HOST_MEMORY_CAP`] in a Linux container
61 //! (2026-09-29). Hosted CI runs the Rust memory-cap test on Linux, macOS and
62 //! Windows with Node only; the Rust host tests have not run a Bun host on
63 //! Linux or Windows (CI's JS host suites run under Bun 1.4.0 on Linux).
64 //! * Linux: `RLIMIT_DATA`, set in the child before exec (clamped to an
65 //! inherited hard limit that is already lower); an allocation past the cap
66 //! fails. Plugin child processes inherit it.
67 //! * Windows: the Job Object's per-process limit; an allocation past the cap
68 //! fails. It applies to each process in the job, plugin children included.
69 //! * macOS: `setrlimit(RLIMIT_AS/RLIMIT_DATA)` below the current mapping size
70 //! fails with `EINVAL`, and `memorystatus_control` needs privilege. A fatal
71 //! jetsam limit set as a `posix_spawn` attribute works unprivileged, but a
72 //! later `exec` clears it, so it cannot be set on `sandbox-exec`. The Bun
73 //! host therefore re-executes itself in place with the limit before any
74 //! plugin loads, and reports it in `host/hello`; past the cap the kernel
75 //! SIGKILLs it. Plugin child processes are not covered. A Bun host that
76 //! cannot apply the requested limit is refused before initialization. Node
77 //! has no FFI to do the same, so a Node host is checked at each heartbeat
78 //! instead: enforced only as often as
79 //! the heartbeat runs. Node also keeps `--max-old-space-size=256`.
80
81 use std::collections::{HashMap, VecDeque};
82 use std::path::{Path, PathBuf};
83 use std::process::Stdio;
84 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
85 use std::sync::{Arc, Mutex};
86 use std::time::Duration;
87
88 use async_trait::async_trait;
89 use serde_json::{Value, json};
90 use tokio::io::{AsyncReadExt, AsyncWriteExt};
91 use tokio::sync::{mpsc, oneshot};
92 use tokio_util::sync::CancellationToken;
93
94 use crate::tools::codemode::PauseClock;
95 use codewhale_dependencies::{HostRuntime, HostRuntimeKind};
96
97 use super::protocol::{
98 self, CoreRequest, Direction, HelloParams, HostLimits, HostMessage, HostNotification,
99 HostRequest, InitializeParams, RegisterResult, RpcErrorWire, error_code,
100 };
101 use super::tier::{self, BuiltinModule, HostCohort, HostTier, PluginCohort};
102
103 /// Budget for spawn → `host/hello` → `host/initialize` → `host/ready`.
104 ///
105 /// A warm start takes well under 100 ms, but the first start of a freshly
106 /// materialized bundle pays for a cold `node` launch, and on Windows for an
107 /// on-access antivirus scan of both. Windows CI under full test load missed
108 /// the former 5 s budget with the host silent on stderr (four runs on
109 /// 2026-09-29) while the same tests normally finish in about 1 s.
110 /// A miss is sticky: the host is marked failed until the next session, so
111 /// a too-tight budget disables every extension for that session. The
112 /// handshake runs in the background, off the first-prompt path, so a wider
113 /// budget costs nothing when the host is healthy; 30 s matches the MCP stdio
114 /// handshake; it is independent of the active TUI MCP client.
115 pub const HANDSHAKE_DEADLINE: Duration = Duration::from_secs(30);
116 pub const ACTIVATE_DEADLINE: Duration = Duration::from_secs(5);
117 pub const DISPOSE_DEADLINE: Duration = Duration::from_secs(2);
118 /// A `host/ping` answer later than this means a hung host: the heartbeat's
119 /// default `hang_timeout`, and the bound for any other ping.
120 pub const PING_DEADLINE: Duration = Duration::from_secs(10);
121 /// Grace between `$/cancel` and resolving a call as cancelled on this side.
122 pub const CANCEL_GRACE: Duration = Duration::from_millis(500);
123 const STDERR_TAIL_BYTES: usize = 8 * 1024;
124 const OUTBOUND_QUEUE: usize = 128;
125
126 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
127 pub enum HostCallError {
128 #[error("{message} (extension error {code})")]
129 Rpc { code: i64, message: String },
130 #[error("plugin host exited: {0}")]
131 Exited(String),
132 #[error("cancelled: {0}")]
133 Cancelled(String),
134 #[error("`{method}` timed out after {after:?}; the host was told to cancel it")]
135 Timeout {
136 method: &'static str,
137 after: Duration,
138 },
139 #[error("plugin host channel is full")]
140 Busy,
141 }
142
143 /// How the host is started: the argv (wrapped by the OS sandbox when one is
144 /// available), its working directory, and which sandbox applies.
145 #[derive(Debug, Clone)]
146 pub struct HostLaunch {
147 pub cohort: HostCohort,
148 /// The trust tier this host process serves (`--tier=` in its argv).
149 pub tier: HostTier,
150 pub program: PathBuf,
151 pub args: Vec<String>,
152 pub cwd: PathBuf,
153 pub sandbox: HostSandbox,
154 /// Environment the sandbox wrapper adds (`CODEWHALE_SANDBOX`, …).
155 pub sandbox_env: Vec<(String, String)>,
156 /// The runtime inside the wrapper; `host/hello` must report the same one.
157 pub runtime: HostRuntime,
158 /// Environment the runtime needs ([`runtime_env`]).
159 pub runtime_env: Vec<(String, String)>,
160 /// Bytes; see the module docs for how each platform enforces it.
161 pub memory_cap: u64,
162 /// How the cap is meant to be enforced; a macOS Bun host confirms its
163 /// jetsam limit in `host/hello` or initialization is refused.
164 pub memory: MemoryEnforcement,
165 /// The built-in module digests `host/hello` must report: the table this
166 /// build pins ([`tier::BUILTIN_MODULES`]), which the host bundle embedded
167 /// from the same build must agree with ([`check_hello_identity`]).
168 pub builtin_modules: &'static [BuiltinModule],
169 #[cfg(not(windows))]
170 pub native_snapshot_roots: Vec<PathBuf>,
171 /// Exact verified Native LPAC plan; Builtin retains its labelled exception.
172 #[cfg(windows)]
173 pub windows: Option<super::windows::NativeSandbox>,
174 }
175
176 /// Whether the host runs under an OS sandbox, and why not when it does not
177 /// (module docs). Settled by [`plan_launch`]; never inferred afterwards.
178 #[derive(Debug, Clone, PartialEq, Eq)]
179 pub enum HostSandbox {
180 /// Under this wrapper, with a Native-specific suffix for the restricted
181 /// Unix profile (`macos-seatbelt-native`, `linux-bwrap-native`).
182 Wrapped(String),
183 /// With the user's permissions, for this reason.
184 Unsandboxed(String),
185 }
186
187 impl HostSandbox {
188 /// The wrapper's name, or `none: <reason>`, for one-line diagnostics.
189 #[must_use]
190 pub fn label(&self) -> String {
191 match self {
192 Self::Wrapped(name) => name.clone(),
193 Self::Unsandboxed(reason) => format!("none: {reason}"),
194 }
195 }
196 }
197
198 /// What `/plugin` and doctor say about the sandbox.
199 impl std::fmt::Display for HostSandbox {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 match self {
202 Self::Wrapped(name) if name == "windows-lpac" => write!(
203 f,
204 "windows-lpac sandbox (no direct network; reads only the selected runtime, canonical bundle and reviewed staged code; writes to Native data and platform-private scratch; Job limits lifetime/memory)"
205 ),
206 Self::Wrapped(name) if name.ends_with("-native") => write!(
207 f,
208 "{name} sandbox (experimental shared Native tier; reads only the host runtime, system libraries, staged package snapshots and Native data; writes only Native data and private scratch; no direct network or repository access)"
209 ),
210 Self::Wrapped(name) => write!(
211 f,
212 "{name} sandbox (no direct network; the Codewhale home except plugin code, the Codex and DSH credential homes and the default credential stores are unreadable; other files you can read, such as project .env files, are not protected)"
213 ),
214 Self::Unsandboxed(reason) => write!(
215 f,
216 "UNSANDBOXED ({reason}): host code runs with your user permissions"
217 ),
218 }
219 }
220 }
221
222 /// Environment variable carrying the jetsam limit a macOS Bun host applies to
223 /// itself, in MiB (`extension-host/src/runtime.ts`, `applyMemoryLimit`).
224 pub const MEMORY_LIMIT_REQUEST_ENV: &str = "CODEWHALE_HOST_MEMORY_LIMIT_MIB";
225
226 /// How the host's memory cap is enforced (module docs).
227 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
228 pub enum MemoryEnforcement {
229 /// Linux: kernel `RLIMIT_DATA`.
230 Rlimit,
231 /// Windows: the Job Object's per-process memory limit.
232 JobObject,
233 /// macOS + Bun: a fatal jetsam limit the host applied to itself.
234 Jetsam,
235 /// macOS otherwise: resident size checked at each heartbeat.
236 Heartbeat,
237 /// No cap on this platform.
238 Unenforced,
239 }
240
241 impl MemoryEnforcement {
242 /// What this platform does for `kind`, before the host has confirmed it.
243 #[must_use]
244 pub fn planned(kind: HostRuntimeKind) -> Self {
245 if cfg!(target_os = "linux") {
246 Self::Rlimit
247 } else if cfg!(windows) {
248 Self::JobObject
249 } else if cfg!(target_os = "macos") {
250 match kind {
251 HostRuntimeKind::Bun => Self::Jetsam,
252 HostRuntimeKind::Node => Self::Heartbeat,
253 }
254 } else {
255 Self::Unenforced
256 }
257 }
258
259 /// One line for `/plugin` and doctor.
260 #[must_use]
261 pub fn describe(self, cap: u64) -> String {
262 let mib = cap / (1024 * 1024);
263 match self {
264 Self::Rlimit => format!(
265 "memory cap {mib} MiB (kernel RLIMIT_DATA; plugin child processes inherit it)"
266 ),
267 Self::JobObject => format!(
268 "memory cap {mib} MiB (Job Object per-process limit; plugin child processes included)"
269 ),
270 Self::Jetsam => format!(
271 "memory cap {mib} MiB (kernel jetsam limit; the host is killed past it; plugin child processes are not covered)"
272 ),
273 Self::Heartbeat => format!(
274 "memory cap {mib} MiB (resident size checked at each heartbeat; on macOS only the Bun host gets a kernel limit)"
275 ),
276 Self::Unenforced => "no memory cap on this platform".to_string(),
277 }
278 }
279 }
280
281 /// The default memory cap. Measured once in a Linux container (2026-09-29),
282 /// not in CI: under `RLIMIT_DATA` Node 24 aborts when it creates the host's
283 /// watchdog Worker at 512 MiB, and Bun 1.4 aborts at startup at 256 MiB.
284 /// Both started and ran at 1 GiB and failed an allocation past it. An idle
285 /// host used 34–67 MB resident. On hosted x64 Linux (Node 24.21) each V8
286 /// isolate's executable code range is charged to `RLIMIT_DATA` in full, and
287 /// a default-sized second isolate aborted the host at this cap; the
288 /// watchdog Worker therefore asks for a 16 MiB code range (`src/main.ts`).
289 /// Plugins cannot start Workers (`denyNativeCode`), so it is the only one.
290 pub const HOST_MEMORY_CAP: u64 = 1 << 30;
291
292 /// Runtime flags, before the bundle path. Keep in sync with
293 /// `extension-host/test/harness.mjs` (`HOST_ARGS`).
294 ///
295 /// - Node: a 256 MB old-space cap, `__proto__` throws, no native addons,
296 /// and the [`codewhale_dependencies::NODE_NATIVE_CODE_FLAGS`] this Node
297 /// accepts (`node:sqlite`, and `node:ffi` where it exists). On Windows it
298 /// also keeps symlinked paths as given, so module resolution never lstats
299 /// the drive root the LPAC cannot read.
300 /// - Bun ignores all of those except `--no-addons`. Instead it gets
301 /// `--no-install`, because Bun otherwise fetches a missing package from npm
302 /// while plugin code is running. It also gets `--no-env-file` and
303 /// `--config=<null device>`, because Bun otherwise loads `.env` and
304 /// `bunfig.toml` (which can preload code) from the working directory, and
305 /// that directory is the host's writable data dir. `bun:ffi` and the rest
306 /// are locked in the host itself (`src/runtime.ts`).
307 #[must_use]
308 pub fn runtime_args(runtime: &HostRuntime) -> Vec<String> {
309 if runtime.compiled {
310 return Vec::new();
311 }
312 base_runtime_args(runtime.kind)
313 .iter()
314 .chain(&runtime.native_code_flags)
315 .map(|arg| (*arg).to_string())
316 .collect()
317 }
318
319 /// Environment for the runtime. Keep in sync with `HOST_ENV` in
320 /// `extension-host/test/harness.mjs`.
321 ///
322 /// - Both: `NODE_OPTIONS` is blanked. The child-environment allowlist passes
323 /// the user's value through (shell tools need it), and a `--require` or
324 /// `--import` preload there would run before the host's native-code
325 /// lockdown. Node honours it; Bun 1.4.0 ignored a `--require` in it when
326 /// checked (2026-09-30), and it is blanked for Bun too in case a later
327 /// Bun does not. `BUN_OPTIONS`, which Bun does honour, is not in that
328 /// allowlist.
329 /// - Bun: no ShadowRealm, engine-wide (a realm imports a fresh `bun:ffi`;
330 /// `node:vm` contexts would otherwise hand the constructor out). The host
331 /// refuses to start without it.
332 #[must_use]
333 pub fn runtime_env(kind: HostRuntimeKind) -> Vec<(String, String)> {
334 let mut env = vec![("NODE_OPTIONS".to_string(), String::new())];
335 if kind == HostRuntimeKind::Bun {
336 env.push(("BUN_JSC_useShadowRealm".to_string(), "0".to_string()));
337 env.push(("BUN_OPTIONS".to_string(), String::new()));
338 // This variable otherwise makes a standalone image act as the Bun CLI.
339 env.push(("BUN_BE_BUN".to_string(), "0".to_string()));
340 }
341 env
342 }
343
344 fn base_runtime_args(kind: HostRuntimeKind) -> &'static [&'static str] {
345 match kind {
346 #[cfg(not(windows))]
347 HostRuntimeKind::Node => &[
348 "--max-old-space-size=256",
349 "--disable-proto=throw",
350 "--no-addons",
351 ],
352 // Node resolves the entry bundle with realpathSync, which lstats every
353 // ancestor from `C:\`. A Windows LPAC cannot read the drive root, so
354 // the host died before its handshake (EPERM, lstat 'C:\'). Keep the
355 // granted path as given; the LPAC still decides every access.
356 #[cfg(windows)]
357 HostRuntimeKind::Node => &[
358 "--max-old-space-size=256",
359 "--disable-proto=throw",
360 "--no-addons",
361 "--preserve-symlinks",
362 "--preserve-symlinks-main",
363 ],
364 #[cfg(windows)]
365 HostRuntimeKind::Bun => &[
366 "--no-install",
367 "--no-env-file",
368 "--config=NUL",
369 "--no-addons",
370 ],
371 #[cfg(not(windows))]
372 HostRuntimeKind::Bun => &[
373 "--no-install",
374 "--no-env-file",
375 "--config=/dev/null",
376 "--no-addons",
377 ],
378 }
379 }
380
381 /// Top-level entries of a Codewhale home the host may read: its own bundle
382 /// and data (`extension-host`), and plugin code (the staged snapshots live
383 /// under `plugins/.runtime`). Everything else in a Codewhale home — secrets,
384 /// tokens, config and its backups, sessions, state, tool outputs, history —
385 /// is denied.
386 const HOST_READABLE_HOME_ENTRIES: &[&str] = &["extension-host", "plugins", "builtin-plugins"];
387
388 /// Codewhale-home entries denied by name even before they exist, so a store
389 /// created after the host started is still covered. Existing entries are
390 /// denied by enumeration (`host_denied_read_paths`).
391 const HOST_DENIED_HOME_ENTRIES: &[&str] = &[
392 "secrets",
393 "credentials",
394 "tokens",
395 "state",
396 "state.db",
397 "sessions",
398 "session-archives",
399 "session_index.jsonl",
400 "tool_outputs",
401 "composer_history.txt",
402 "composer_history.jsonl",
403 "remote-control",
404 "integrations",
405 "audit.log",
406 "logs",
407 "memory",
408 "mcp.json",
409 "mcp.json.bak",
410 "config.toml.bak",
411 "settings.toml",
412 ];
413
414 /// Paths the host process must never read, even though the sandbox otherwise
415 /// grants full-disk read, and the exceptions inside them: the curated
416 /// credential-store defaults; Codewhale's homes (the runtime home, the ambient
417 /// `~/.codewhale`, and the legacy `~/.deepseek`) except
418 /// [`HOST_READABLE_HOME_ENTRIES`]; and the Codex and DSH homes whose
419 /// credential files Codewhale itself reads. Blocking.
420 ///
421 /// With `whole_homes` (bubblewrap, which can mask only what exists) each home
422 /// is denied whole and its readable entries come back as exceptions to bind
423 /// again. Without it (Seatbelt, which matches paths that do not exist yet)
424 /// every other entry is denied by name and there are no exceptions.
425 ///
426 /// The plugin tier also denies the builtin tier's data directory, which lies
427 /// inside the readable `extension-host/` entry: plugin code never reads
428 /// tier-0 state. Planning materializes that sibling before the wrapper masks
429 /// it, because bubblewrap cannot mask a directory that does not exist yet.
430 pub fn host_denied_read_paths(
431 cohort: &HostCohort,
432 home: &Path,
433 whole_homes: bool,
434 ) -> (Vec<PathBuf>, Vec<PathBuf>) {
435 let mut paths =
436 codewhale_sandbox::read_guard::ReadDenylist::build(true, &[], &[]).subtree_paths();
437 let mut exceptions: Vec<PathBuf> = Vec::new();
438 let mut push = |path: PathBuf| {
439 if !paths.contains(&path) {
440 paths.push(path);
441 }
442 };
443 let user_home = codewhale_paths::user_home();
444 let mut roots = vec![home.to_path_buf()];
445 roots.extend(codewhale_config::codewhale_home().ok());
446 if let Some(user) = &user_home {
447 roots.push(user.join(codewhale_config::CODEWHALE_APP_DIR));
448 roots.push(user.join(".deepseek"));
449 }
450 for root in roots {
451 let is_plugin = cohort.tier() == HostTier::Plugin;
452 if is_plugin {
453 push(tier_data_dir(&root, HostTier::Builtin));
454 }
455 let mut sibling_agent_dirs: Vec<std::ffi::OsString> = Vec::new();
456 match cohort {
457 HostCohort::Builtin => {
458 push(tier_data_dir(&root, HostTier::Plugin));
459 push(root.join("extension-host").join("data-agent"));
460 }
461 HostCohort::Plugin(PluginCohort::Reviewed) => {
462 push(root.join("extension-host").join("data-agent"));
463 }
464 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
465 push(tier_data_dir(&root, HostTier::Plugin));
466 let own_data = cohort_data_dir(&root, cohort);
467 let agent_root = root.join("extension-host").join("data-agent");
468 if let Ok(entries) = std::fs::read_dir(&agent_root) {
469 for entry in entries.filter_map(Result::ok) {
470 let path = entry.path();
471 if path != own_data {
472 sibling_agent_dirs.push(entry.file_name());
473 push(path);
474 }
475 }
476 }
477 }
478 }
479 if whole_homes {
480 for entry in HOST_READABLE_HOME_ENTRIES {
481 let readable = root.join(entry);
482 if !exceptions.contains(&readable) {
483 exceptions.push(readable);
484 }
485 }
486 push(root);
487 continue;
488 }
489 let mut names: Vec<std::ffi::OsString> = HOST_DENIED_HOME_ENTRIES
490 .iter()
491 .chain(std::iter::once(&codewhale_config::CONFIG_FILE_NAME))
492 .map(std::ffi::OsString::from)
493 .collect();
494 if let Ok(entries) = std::fs::read_dir(&root) {
495 names.extend(
496 entries
497 .filter_map(Result::ok)
498 .map(|entry| entry.file_name()),
499 );
500 }
501 let resolved = std::fs::canonicalize(&root).ok();
502 if let Some(resolved) = &resolved {
503 if is_plugin {
504 push(tier_data_dir(resolved, HostTier::Builtin));
505 }
506 match cohort {
507 HostCohort::Builtin => {
508 push(tier_data_dir(resolved, HostTier::Plugin));
509 push(resolved.join("extension-host").join("data-agent"));
510 }
511 HostCohort::Plugin(PluginCohort::Reviewed) => {
512 push(resolved.join("extension-host").join("data-agent"));
513 }
514 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
515 push(tier_data_dir(resolved, HostTier::Plugin));
516 let agent_root = resolved.join("extension-host").join("data-agent");
517 for name in &sibling_agent_dirs {
518 push(agent_root.join(name));
519 }
520 }
521 }
522 }
523 for name in names {
524 let readable = name
525 .to_str()
526 .is_some_and(|name| HOST_READABLE_HOME_ENTRIES.contains(&name));
527 if !readable {
528 if let Some(resolved) = &resolved {
529 push(resolved.join(&name));
530 }
531 push(root.join(name));
532 }
533 }
534 }
535 if let Some(codex_home) = codewhale_runtime::oauth::auth_file_path().parent() {
536 push(codex_home.to_path_buf());
537 }
538 if let Some(user) = &user_home {
539 push(user.join(".codex"));
540 push(user.join(".dsh"));
541 }
542 if let Some(dsh_home) = codewhale_config::default_dsh_credentials_path().parent() {
543 push(dsh_home.to_path_buf());
544 }
545 (paths, exceptions)
546 }
547
548 /// Plan the host launch for `tier`: the runtime's flags, the bundle, then the
549 /// tier (`--tier=plugin|builtin`, which the host reads from its own argv).
550 /// Blocking (creates the tier's data dir, canonicalizes the deny-list, and on
551 /// Linux runs the bwrap probe); call from `spawn_blocking`.
552 pub fn plan_launch(
553 cohort: &HostCohort,
554 runtime: &HostRuntime,
555 bundle: &Path,
556 home: &Path,
557 memory_cap: u64,
558 snapshot_state_paths: &[PathBuf],
559 ) -> Result<HostLaunch, String> {
560 let tier = cohort.tier();
561 let data = host_cohort_data_dir(home, cohort)?;
562 if tier == HostTier::Plugin {
563 host_cohort_data_dir(home, HostCohort::Builtin)?;
564 }
565 let mut args = runtime_args(runtime);
566 if !runtime.compiled {
567 args.push(bundle.to_string_lossy().into_owned());
568 }
569 args.push(tier.argv_flag());
570 #[cfg(windows)]
571 if tier == HostTier::Plugin {
572 let sandbox =
573 super::windows::NativeSandbox::prepare(runtime, bundle, home, &data, memory_cap)?;
574 return Ok(HostLaunch {
575 cohort: cohort.clone(),
576 tier,
577 program: sandbox.program.clone(),
578 args,
579 cwd: data,
580 sandbox: HostSandbox::Wrapped("windows-lpac".into()),
581 sandbox_env: vec![("CODEWHALE_SANDBOX".into(), "windows-lpac".into())],
582 runtime: runtime.clone(),
583 runtime_env: runtime_env(runtime.kind),
584 memory_cap,
585 memory: MemoryEnforcement::JobObject,
586 builtin_modules: tier::BUILTIN_MODULES,
587 windows: Some(sandbox),
588 });
589 }
590 let snapshot_roots = if tier == HostTier::Plugin {
591 native_snapshot_roots(snapshot_state_paths)?
592 } else {
593 Vec::new()
594 };
595 let wrapped = wrap_host(
596 cohort,
597 &runtime.path,
598 &args,
599 &data,
600 home,
601 bundle,
602 &snapshot_roots,
603 );
604 let launch = host_launch(cohort, runtime, args, data, memory_cap, wrapped)?;
605 #[cfg(not(windows))]
606 let launch = HostLaunch {
607 native_snapshot_roots: snapshot_roots,
608 ..launch
609 };
610 Ok(launch)
611 }
612
613 /// The runtime sandbox a `tier` host would get, planned (and on Linux probed)
614 /// as [`plan_launch`] does, without package-store grants, for doctor.
615 /// Blocking; creates nothing, so a host that has not started yet is reported
616 /// as not planned, naming the first path its start would create.
617 pub fn planned_sandbox_tier(
618 tier: HostTier,
619 runtime: &HostRuntime,
620 home: &Path,
621 ) -> Result<HostSandbox, String> {
622 let cohort = match tier {
623 HostTier::Builtin => HostCohort::Builtin,
624 HostTier::Plugin => HostCohort::reviewed(),
625 };
626 planned_sandbox(&cohort, runtime, home)
627 }
628
629 pub fn planned_sandbox(
630 cohort: &HostCohort,
631 runtime: &HostRuntime,
632 home: &Path,
633 ) -> Result<HostSandbox, String> {
634 let tier = cohort.tier();
635 let data = cohort_data_dir(home, cohort);
636 let mut required = vec![data.clone()];
637 if tier == HostTier::Plugin {
638 required.push(tier_data_dir(home, HostTier::Builtin));
639 required.push(data.join("tmp"));
640 }
641 if let Some(missing) = required.iter().find(|path| !path.is_dir()) {
642 return Err(would_create(missing));
643 }
644 #[cfg(windows)]
645 if tier == HostTier::Plugin {
646 let bundle = super::materialized_bundle(home)?;
647 return Ok(
648 match super::windows::NativeSandbox::prepare(
649 runtime,
650 &bundle,
651 home,
652 &data,
653 HOST_MEMORY_CAP,
654 ) {
655 Ok(_) => HostSandbox::Wrapped("windows-lpac".into()),
656 Err(error) => HostSandbox::Unsandboxed(error),
657 },
658 );
659 }
660 let bundle = if tier == HostTier::Plugin {
661 super::materialized_bundle(home)?
662 } else {
663 PathBuf::new()
664 };
665 Ok(
666 match wrap_host(
667 cohort,
668 &runtime.path,
669 &runtime_args(runtime),
670 &data,
671 home,
672 &bundle,
673 &[],
674 ) {
675 Ok(wrapped) => HostSandbox::Wrapped(wrapped.name),
676 Err(reason) => HostSandbox::Unsandboxed(reason),
677 },
678 )
679 }
680
681 /// A tier's data directory: its host's working directory and, under the OS
682 /// sandbox, its only writable root. Pure.
683 ///
684 /// The plugin tier keeps the directory it has always had,
685 /// `extension-host/data`, because the per-plugin directories under it
686 /// ([`plugin_data_dir`]) hold installed plugins' data and moving it would lose
687 /// that. The builtin tier's is a sibling, `extension-host/data-builtin`, not a
688 /// child: a child would lie inside the plugin tier's writable root, and the
689 /// host sandbox has no per-subpath write deny, so plugin code could then write
690 /// tier-0 state.
691 pub fn agent_cohort_digest(workspace: &str) -> String {
692 use sha2::{Digest, Sha256};
693 let normalized = codewhale_config::normalize_project_workspace(Path::new(workspace))
694 .unwrap_or_else(|_| Path::new(workspace).components().collect());
695 let bytes = normalized.to_string_lossy().into_owned();
696 let digest = Sha256::digest(bytes.as_bytes());
697 digest[..16]
698 .iter()
699 .map(|byte| format!("{byte:02x}"))
700 .collect()
701 }
702
703 pub fn cohort_data_dir(home: &Path, cohort: impl Into<HostCohort>) -> PathBuf {
704 let cohort = cohort.into();
705 let base = home.join("extension-host");
706 match cohort {
707 HostCohort::Builtin => base.join("data-builtin"),
708 HostCohort::Plugin(PluginCohort::Reviewed) => base.join("data"),
709 HostCohort::Plugin(PluginCohort::Agent { workspace }) => base
710 .join("data-agent")
711 .join(agent_cohort_digest(&workspace)),
712 }
713 }
714
715 pub fn tier_data_dir(home: &Path, tier: HostTier) -> PathBuf {
716 let cohort = match tier {
717 HostTier::Builtin => HostCohort::Builtin,
718 HostTier::Plugin => HostCohort::reviewed(),
719 };
720 cohort_data_dir(home, cohort)
721 }
722
723 fn plugin_dir_name_parts(plugin_id: &str, plugin_name: &str) -> (String, String) {
724 use sha2::{Digest, Sha256};
725 let digest = Sha256::digest(plugin_id.as_bytes());
726 let short: String = digest
727 .iter()
728 .take(6)
729 .map(|byte| format!("{byte:02x}"))
730 .collect();
731 let name: String = plugin_name
732 .chars()
733 .map(|c| {
734 if c.is_ascii_alphanumeric() || c == '-' {
735 c
736 } else {
737 '_'
738 }
739 })
740 .take(64)
741 .collect();
742 (name, short)
743 }
744
745 pub fn owner_data_dir(
746 home: &Path,
747 cohort: impl Into<HostCohort>,
748 plugin_id: &str,
749 plugin_name: &str,
750 ) -> PathBuf {
751 let cohort = cohort.into();
752 match cohort {
753 HostCohort::Builtin => cohort_data_dir(home, cohort)
754 .join("modules")
755 .join(plugin_name),
756 HostCohort::Plugin(PluginCohort::Reviewed) => plugin_data_dir(home, plugin_id, plugin_name),
757 HostCohort::Plugin(PluginCohort::Agent { .. }) => {
758 let (name, short) = plugin_dir_name_parts(plugin_id, plugin_name);
759 cohort_data_dir(home, cohort)
760 .join("plugins")
761 .join(format!("{name}-{short}"))
762 }
763 }
764 }
765
766 pub fn plugin_data_dir(home: &Path, plugin_id: &str, plugin_name: &str) -> PathBuf {
767 let (name, short) = plugin_dir_name_parts(plugin_id, plugin_name);
768 home.join("extension-host")
769 .join("data")
770 .join("plugins")
771 .join(format!("{name}-{short}"))
772 }
773
774 pub fn would_create(path: &Path) -> String {
775 format!(
776 "not planned until the host first starts, which would create {}",
777 path.display()
778 )
779 }
780
781 pub fn host_cohort_data_dir(home: &Path, cohort: impl Into<HostCohort>) -> Result<PathBuf, String> {
782 let data = cohort_data_dir(home, cohort);
783 std::fs::create_dir_all(&data)
784 .map_err(|error| format!("cannot create {}: {error}", data.display()))?;
785 Ok(data)
786 }
787
788 /// A host command wrapped in an OS sandbox ([`wrap_host`]).
789 #[derive(Debug)]
790 struct Wrapped {
791 /// `sandbox::SandboxType`'s name for the wrapper.
792 name: String,
793 /// The wrapper's argv, ending with the runtime's.
794 command: Vec<String>,
795 /// Environment the wrapper adds (`CODEWHALE_SANDBOX`, …).
796 env: Vec<(String, String)>,
797 }
798
799 /// Why the host runs on Windows without an OS sandbox.
800 const WINDOWS_UNSANDBOXED: &str = "Windows has no host sandbox yet; its Job Object contains the process tree, which is not isolation";
801
802 fn native_snapshot_roots(state_paths: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
803 let mut roots = Vec::new();
804 for state in state_paths {
805 let parent = state.parent().ok_or("plugin state path has no parent")?;
806 let root = parent.join(".runtime/v2");
807 if !root.exists() {
808 continue;
809 }
810 codewhale_plugins::registry::ensure_private_plugin_state_directory(parent)?;
811 let mut path = parent.canonicalize().map_err(|error| error.to_string())?;
812 for component in [".runtime", "v2"] {
813 path.push(component);
814 let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?;
815 if !metadata.is_dir() || metadata.file_type().is_symlink() {
816 return Err(
817 "Native snapshot store must be a directory without symbolic links".into(),
818 );
819 }
820 }
821 let canonical = path.canonicalize().map_err(|error| error.to_string())?;
822 if canonical != path {
823 return Err("Native snapshot store changed its canonical path".into());
824 }
825 if !roots.contains(&path) {
826 roots.push(path);
827 }
828 }
829 Ok(roots)
830 }
831
832 fn native_readable_paths(
833 program: &Path,
834 bundle: &Path,
835 data: &Path,
836 snapshot_roots: &[PathBuf],
837 ) -> Result<Vec<PathBuf>, String> {
838 let mut check = Some(data);
839 while let Some(path) = check {
840 let metadata = std::fs::symlink_metadata(path).map_err(|error| error.to_string())?;
841 if !metadata.is_dir()
842 || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
843 {
844 return Err("Native data directory must not traverse symbolic links".into());
845 }
846 if path
847 .file_name()
848 .is_some_and(|name| name == "extension-host")
849 {
850 break;
851 }
852 check = path.parent();
853 }
854 let mut paths = vec![
855 program.to_path_buf(),
856 bundle.to_path_buf(),
857 data.to_path_buf(),
858 ];
859 paths.extend_from_slice(snapshot_roots);
860 let canonical_data = data.canonicalize().map_err(|error| error.to_string())?;
861 #[cfg(target_os = "macos")]
862 {
863 paths.extend(native_runtime_libraries(program)?);
864 for path in [
865 "/System/Library",
866 "/usr/lib",
867 "/Library/Apple/System/Library",
868 "/private/var/db/dyld",
869 "/usr/share/icu",
870 "/usr/share/zoneinfo",
871 "/private/etc/localtime",
872 "/dev/null",
873 "/dev/random",
874 "/dev/urandom",
875 ] {
876 if Path::new(path).exists() {
877 paths.push(PathBuf::from(path));
878 }
879 }
880 }
881 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
882 for path in [
883 "/usr/lib",
884 "/usr/lib64",
885 "/lib",
886 "/lib64",
887 "/usr/share/zoneinfo",
888 "/etc/ld.so.cache",
889 "/etc/ld.so.conf",
890 "/etc/localtime",
891 "/etc/nsswitch.conf",
892 "/etc/passwd",
893 "/etc/group",
894 ] {
895 if Path::new(path).exists() {
896 paths.push(PathBuf::from(path));
897 }
898 }
899 let mut canonical = Vec::new();
900 for path in &paths {
901 let resolved = path.canonicalize().map_err(|error| {
902 format!(
903 "Native read grant {} is unavailable: {error}",
904 path.display()
905 )
906 })?;
907 if path != data
908 && (resolved.starts_with(&canonical_data) || canonical_data.starts_with(&resolved))
909 {
910 return Err("Native writable data overlaps a runtime or package read grant".into());
911 }
912 canonical.push(resolved);
913 if path.is_file()
914 && let (Some(parent), Some(name)) = (path.parent(), path.file_name())
915 {
916 canonical.push(
917 parent
918 .canonicalize()
919 .map_err(|error| error.to_string())?
920 .join(name),
921 );
922 }
923 }
924 paths.extend(canonical);
925 paths.sort();
926 paths.dedup();
927 Ok(paths)
928 }
929
930 #[cfg(target_os = "macos")]
931 fn native_runtime_libraries(program: &Path) -> Result<Vec<PathBuf>, String> {
932 use std::io::{Read as _, Seek as _};
933 use wait_timeout::ChildExt as _;
934 let executable = program.canonicalize().map_err(|error| error.to_string())?;
935 let mut pending = vec![(executable.clone(), Vec::<PathBuf>::new())];
936 let mut inspected = std::collections::BTreeSet::new();
937 let mut libraries = Vec::new();
938 while let Some((binary, inherited_paths)) = pending.pop() {
939 if !inspected.insert(binary.clone()) {
940 continue;
941 }
942 if inspected.len() > 256 {
943 return Err("Native runtime library closure exceeds 256 files".into());
944 }
945 let mut output = tempfile::tempfile().map_err(|error| error.to_string())?;
946 let mut child = std::process::Command::new("/usr/bin/otool")
947 .args([
948 "-l",
949 binary.to_str().ok_or("Native runtime path is not UTF-8")?,
950 ])
951 .env_clear()
952 .stdin(Stdio::null())
953 .stdout(output.try_clone().map_err(|error| error.to_string())?)
954 .stderr(Stdio::null())
955 .spawn()
956 .map_err(|error| format!("Native runtime library inspection unavailable: {error}"))?;
957 let status = match child.wait_timeout(Duration::from_secs(10)) {
958 Ok(Some(status)) => status,
959 _ => {
960 let _ = child.kill();
961 let _ = child.wait();
962 return Err("Native runtime library inspection timed out".into());
963 }
964 };
965 if !status.success()
966 || output.metadata().map_err(|error| error.to_string())?.len() > 1024 * 1024
967 {
968 return Err("Native runtime library inspection failed or exceeded its bound".into());
969 }
970 output.rewind().map_err(|error| error.to_string())?;
971 let mut text = String::new();
972 output
973 .take(1024 * 1024)
974 .read_to_string(&mut text)
975 .map_err(|error| error.to_string())?;
976 let expand = |name: &str| -> Result<PathBuf, String> {
977 if name == "@loader_path" {
978 Ok(binary
979 .parent()
980 .ok_or("Native library has no parent")?
981 .to_path_buf())
982 } else if name == "@executable_path" {
983 Ok(executable
984 .parent()
985 .ok_or("Native runtime has no parent")?
986 .to_path_buf())
987 } else if let Some(relative) = name.strip_prefix("@loader_path/") {
988 Ok(binary
989 .parent()
990 .ok_or("Native library has no parent")?
991 .join(relative))
992 } else if let Some(relative) = name.strip_prefix("@executable_path/") {
993 Ok(executable
994 .parent()
995 .ok_or("Native runtime has no parent")?
996 .join(relative))
997 } else if Path::new(name).is_absolute() {
998 Ok(PathBuf::from(name))
999 } else {
1000 Err(format!(
1001 "Native runtime uses an unsupported library reference: {name}"
1002 ))
1003 }
1004 };
1005 let mut command = "";
1006 let mut run_paths = Vec::new();
1007 let mut dependencies = Vec::new();
1008 for line in text.lines().map(str::trim) {
1009 if let Some(value) = line.strip_prefix("cmd ") {
1010 command = value;
1011 } else if command == "LC_RPATH" {
1012 if let Some(value) = line.strip_prefix("path ") {
1013 run_paths.push(expand(value.split(" (offset ").next().unwrap_or_default())?);
1014 }
1015 } else if matches!(
1016 command,
1017 "LC_LOAD_DYLIB"
1018 | "LC_LOAD_WEAK_DYLIB"
1019 | "LC_REEXPORT_DYLIB"
1020 | "LC_LOAD_UPWARD_DYLIB"
1021 ) && let Some(value) = line.strip_prefix("name ")
1022 {
1023 dependencies.push(value.split(" (offset ").next().unwrap_or_default());
1024 }
1025 }
1026 run_paths.extend(inherited_paths);
1027 for name in dependencies {
1028 if name.starts_with("/usr/lib/") || name.starts_with("/System/Library/") {
1029 continue;
1030 }
1031 let path = if let Some(relative) = name.strip_prefix("@rpath/") {
1032 run_paths
1033 .iter()
1034 .map(|root| root.join(relative))
1035 .find(|path| path.is_file())
1036 .ok_or_else(|| format!("Native runtime library cannot be resolved: {name}"))?
1037 } else {
1038 expand(name)?
1039 };
1040 let canonical = path.canonicalize().map_err(|error| {
1041 format!(
1042 "Native runtime library {} is unavailable: {error}",
1043 path.display()
1044 )
1045 })?;
1046 if !canonical.is_file() {
1047 return Err("Native runtime library is not a regular file".into());
1048 }
1049 libraries.push(path);
1050 libraries.push(canonical.clone());
1051 pending.push((canonical, run_paths.clone()));
1052 }
1053 }
1054 Ok(libraries)
1055 }
1056
1057 /// Wrap `program args` in the host's OS sandbox (module docs), or say why it
1058 /// has none here. Blocking.
1059 fn wrap_host(
1060 cohort: &HostCohort,
1061 program: &Path,
1062 args: &[String],
1063 data: &Path,
1064 home: &Path,
1065 bundle: &Path,
1066 snapshot_roots: &[PathBuf],
1067 ) -> Result<Wrapped, String> {
1068 use codewhale_sandbox::{CommandSpec, SandboxManager, SandboxPolicy, SandboxType};
1069 if cfg!(windows) {
1070 return Err(WINDOWS_UNSANDBOXED.to_string());
1071 }
1072 let tier = cohort.tier();
1073 let spec = |args: Vec<String>| {
1074 CommandSpec::program(
1075 &program.to_string_lossy(),
1076 args,
1077 data.to_path_buf(),
1078 Duration::ZERO,
1079 )
1080 .with_policy(SandboxPolicy::WorkspaceWrite {
1081 writable_roots: Vec::new(),
1082 network_access: false,
1083 exclude_tmpdir: tier == HostTier::Plugin,
1084 exclude_slash_tmp: tier == HostTier::Plugin,
1085 })
1086 };
1087 let bwrap = cfg!(all(target_os = "linux", not(target_env = "ohos")));
1088 let mut manager = SandboxManager::with_bwrap_preference(bwrap);
1089 let (mut denied, exceptions) =
1090 host_denied_read_paths(cohort, home, bwrap && tier != HostTier::Plugin);
1091 if tier == HostTier::Plugin {
1092 let readable = native_readable_paths(program, bundle, data, snapshot_roots)?;
1093 denied.retain(|path| {
1094 readable
1095 .iter()
1096 .any(|grant| path.starts_with(grant) || grant.starts_with(path))
1097 });
1098 manager.set_readable_paths(readable);
1099 } else {
1100 manager.set_denied_read_exceptions(exceptions);
1101 }
1102 manager.set_denied_read_subpaths(denied);
1103 let env = manager.prepare(&spec(args.to_vec()));
1104 if matches!(env.sandbox_type, SandboxType::None) {
1105 return Err(no_wrapper_reason());
1106 }
1107 let mut environment: Vec<_> = env.env.into_iter().collect();
1108 if tier == HostTier::Plugin {
1109 let scratch = data.join("tmp");
1110 codewhale_plugins::registry::ensure_private_plugin_state_directory(&scratch)?;
1111 for name in ["TMPDIR", "TMP", "TEMP"] {
1112 environment.push((name.into(), scratch.to_string_lossy().into_owned()));
1113 }
1114 environment.push(("HOME".into(), data.to_string_lossy().into_owned()));
1115 environment.push(("OPENSSL_CONF".into(), "/dev/null".into()));
1116 }
1117 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
1118 if matches!(env.sandbox_type, SandboxType::LinuxBubblewrap) {
1119 probe_bwrap(
1120 &manager
1121 .prepare(&spec(vec!["--version".to_string()]))
1122 .command,
1123 data,
1124 if tier == HostTier::Plugin {
1125 &environment
1126 } else {
1127 &[]
1128 },
1129 )?;
1130 }
1131 Ok(Wrapped {
1132 name: if tier == HostTier::Plugin {
1133 format!("{}-native", env.sandbox_type)
1134 } else {
1135 env.sandbox_type.to_string()
1136 },
1137 command: env.command,
1138 env: environment,
1139 })
1140 }
1141
1142 /// The launch for a [`wrap_host`] outcome: the wrapper's argv, or the
1143 /// pinned Builtin runtime itself, carrying the reason `/plugin` shows. Native
1144 /// code is refused without the verified wrapper. Pure.
1145 fn host_launch(
1146 cohort: &HostCohort,
1147 runtime: &HostRuntime,
1148 args: Vec<String>,
1149 data: PathBuf,
1150 memory_cap: u64,
1151 wrapped: Result<Wrapped, String>,
1152 ) -> Result<HostLaunch, String> {
1153 let tier = cohort.tier();
1154 let (program, args, sandbox, sandbox_env) = match wrapped {
1155 Ok(wrapped) => {
1156 let mut command = wrapped.command.into_iter();
1157 let program = command
1158 .next()
1159 .ok_or("sandbox wrapper produced an empty command")?;
1160 (
1161 PathBuf::from(program),
1162 command.collect(),
1163 HostSandbox::Wrapped(wrapped.name),
1164 wrapped.env,
1165 )
1166 }
1167 Err(reason) if tier == HostTier::Plugin => {
1168 return Err(format!(
1169 "Native plugins require a verified OS sandbox: {reason}"
1170 ));
1171 }
1172 // Only the pinned Builtin tier may run without filesystem/network
1173 // isolation. Every effect is still admitted by Rust operation tickets.
1174 Err(reason) => (
1175 runtime.path.clone(),
1176 args,
1177 HostSandbox::Unsandboxed(reason),
1178 Vec::new(),
1179 ),
1180 };
1181 Ok(HostLaunch {
1182 cohort: cohort.clone(),
1183 tier,
1184 program,
1185 args,
1186 cwd: data,
1187 sandbox,
1188 sandbox_env,
1189 runtime: runtime.clone(),
1190 runtime_env: runtime_env(runtime.kind),
1191 memory_cap,
1192 memory: MemoryEnforcement::planned(runtime.kind),
1193 builtin_modules: tier::BUILTIN_MODULES,
1194 #[cfg(not(windows))]
1195 native_snapshot_roots: Vec::new(),
1196 #[cfg(windows)]
1197 windows: None,
1198 })
1199 }
1200
1201 /// Why [`wrap_host`] found no wrapper on this platform.
1202 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
1203 fn no_wrapper_reason() -> String {
1204 format!(
1205 "bwrap unavailable: {} is not an executable file (install bubblewrap)",
1206 codewhale_sandbox::bwrap::BWRAP_PATH
1207 )
1208 }
1209
1210 #[cfg(target_os = "macos")]
1211 fn no_wrapper_reason() -> String {
1212 "Seatbelt (sandbox-exec) is unavailable".to_string()
1213 }
1214
1215 #[cfg(not(any(
1216 target_os = "macos",
1217 all(target_os = "linux", not(target_env = "ohos"))
1218 )))]
1219 fn no_wrapper_reason() -> String {
1220 "no OS sandbox for the host on this platform".to_string()
1221 }
1222
1223 /// How long the bwrap probe may take. A working bwrap runs
1224 /// `<runtime> --version` in well under a second, even on a loaded CI runner.
1225 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
1226 const BWRAP_PROBE_DEADLINE: Duration = Duration::from_secs(10);
1227
1228 /// Run the finished bwrap wrapper around `<runtime> --version` (`command`),
1229 /// with the selected startup environment, to learn whether bwrap works here: it may be
1230 /// installed yet unable to create its namespaces. Blocking.
1231 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
1232 fn probe_bwrap(command: &[String], cwd: &Path, env: &[(String, String)]) -> Result<(), String> {
1233 use std::io::Read as _;
1234 use wait_timeout::ChildExt as _;
1235 let (program, args) = command
1236 .split_first()
1237 .ok_or("the sandbox wrapper produced an empty command")?;
1238 let mut child = std::process::Command::new(program)
1239 .args(args)
1240 .current_dir(cwd)
1241 .env_clear()
1242 .envs(env.iter().map(|(key, value)| (key, value)))
1243 .stdin(Stdio::null())
1244 .stdout(Stdio::null())
1245 .stderr(Stdio::piped())
1246 .spawn()
1247 .map_err(|error| format!("bwrap unavailable: {program} does not start ({error})"))?;
1248 let status = match child.wait_timeout(BWRAP_PROBE_DEADLINE) {
1249 Ok(Some(status)) => status,
1250 outcome => {
1251 let _ = child.kill();
1252 let _ = child.wait();
1253 return Err(match outcome {
1254 Err(error) => format!("bwrap unavailable: waiting for the probe failed ({error})"),
1255 _ => format!(
1256 "bwrap unavailable: the probe did not finish within {BWRAP_PROBE_DEADLINE:?}"
1257 ),
1258 });
1259 }
1260 };
1261 let mut stderr = String::new();
1262 if let Some(mut pipe) = child.stderr.take() {
1263 let _ = pipe.read_to_string(&mut stderr);
1264 }
1265 bwrap_probe_verdict(status.success(), &status.to_string(), &stderr)
1266 }
1267
1268 /// What a wrapped `<runtime> --version` run says about bwrap here: `Ok` when
1269 /// it ran, or when bwrap built the sandbox and only the runtime failed to
1270 /// execute in it (a script shim whose interpreter is not granted): the host
1271 /// spawn then reports that as a runtime start failure, which `auto` answers
1272 /// by falling back to Node. Otherwise the reason `/plugin` and doctor show — bwrap's first
1273 /// line of stderr (or the exit status), and a hint when that line is about
1274 /// the user namespace bwrap could not create. Pure.
1275 #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))]
1276 fn bwrap_probe_verdict(succeeded: bool, status: &str, stderr: &str) -> Result<(), String> {
1277 if succeeded {
1278 return Ok(());
1279 }
1280 let first = stderr.lines().map(str::trim).find(|line| !line.is_empty());
1281 if first.is_some_and(|line| line.starts_with("bwrap: execvp ")) {
1282 return Ok(());
1283 }
1284 let mut detail: String = first.map_or_else(
1285 || status.to_string(),
1286 |line| line.chars().take(240).collect(),
1287 );
1288 if first.is_some_and(|line| line.contains("namespace") || line.contains("uid map")) {
1289 detail.push_str(
1290 "; unprivileged user namespaces look blocked here (on Ubuntu 24.04 and later: the kernel.apparmor_restrict_unprivileged_userns sysctl)",
1291 );
1292 }
1293 Err(format!("bwrap unavailable ({detail})"))
1294 }
1295
1296 /// The kernel-enforced memory cap on Linux: `RLIMIT_DATA`, applied in the
1297 /// child between fork and exec, so only the host (and what it starts) is
1298 /// limited. Soft and hard limit are both set, so plugin code cannot raise
1299 /// it. An unprivileged process cannot raise its hard limit, so when the
1300 /// inherited hard limit is already below `cap` the host gets that lower
1301 /// limit instead of failing to spawn with `EPERM`.
1302 ///
1303 /// Known limit: in that case `/plugin` and doctor still name the configured
1304 /// cap, not the lower inherited one.
1305 #[cfg(target_os = "linux")]
1306 pub(super) fn limit_child_memory(command: &mut tokio::process::Command, cap: u64) {
1307 // SAFETY: the closure runs in the forked child before exec and calls only
1308 // `getrlimit` and `setrlimit`, which are async-signal-safe; it allocates
1309 // nothing.
1310 unsafe {
1311 command.pre_exec(move || {
1312 let mut inherited = libc::rlimit {
1313 rlim_cur: 0,
1314 rlim_max: 0,
1315 };
1316 if libc::getrlimit(libc::RLIMIT_DATA, &raw mut inherited) != 0 {
1317 return Err(std::io::Error::last_os_error());
1318 }
1319 let cap = (cap as libc::rlim_t).min(inherited.rlim_max);
1320 let limit = libc::rlimit {
1321 rlim_cur: cap,
1322 rlim_max: cap,
1323 };
1324 if libc::setrlimit(libc::RLIMIT_DATA, &raw const limit) != 0 {
1325 return Err(std::io::Error::last_os_error());
1326 }
1327 Ok(())
1328 });
1329 }
1330 }
1331
1332 #[cfg(not(target_os = "linux"))]
1333 pub(super) fn limit_child_memory(_command: &mut tokio::process::Command, _cap: u64) {}
1334
1335 /// Resident size of `pid` in bytes, for the macOS memory-cap check.
1336 #[cfg(target_os = "macos")]
1337 pub fn resident_bytes(pid: u32) -> Option<u64> {
1338 let mut info = std::mem::MaybeUninit::<libc::proc_taskinfo>::zeroed();
1339 let size = std::mem::size_of::<libc::proc_taskinfo>() as libc::c_int;
1340 // SAFETY: `info` is a correctly sized, writable `proc_taskinfo` buffer.
1341 let written = unsafe {
1342 libc::proc_pidinfo(
1343 pid as libc::c_int,
1344 libc::PROC_PIDTASKINFO,
1345 0,
1346 info.as_mut_ptr().cast(),
1347 size,
1348 )
1349 };
1350 // SAFETY: a full-size write initialized the struct.
1351 (written == size).then(|| unsafe { info.assume_init() }.pti_resident_size)
1352 }
1353
1354 /// Platforms without a supervisor-side check (Linux uses `RLIMIT_DATA`,
1355 /// Windows the Job Object).
1356 #[cfg(not(target_os = "macos"))]
1357 pub fn resident_bytes(_pid: u32) -> Option<u64> {
1358 None
1359 }
1360
1361 /// Report the observed exit and configured cap. SIGKILL alone cannot identify
1362 /// jetsam: an operator or another process can send the same signal.
1363 fn exit_reason(
1364 status: std::process::ExitStatus,
1365 memory: Option<MemoryEnforcement>,
1366 cap: u64,
1367 ) -> String {
1368 let reason = format!("exited with {status}");
1369 #[cfg(unix)]
1370 {
1371 use std::os::unix::process::ExitStatusExt as _;
1372 if status.signal() == Some(libc::SIGKILL) && memory == Some(MemoryEnforcement::Jetsam) {
1373 return format!(
1374 "{reason}; configured kernel memory limit: {} MiB; SIGKILL cause unavailable",
1375 cap / (1024 * 1024)
1376 );
1377 }
1378 }
1379 #[cfg(not(unix))]
1380 let _ = (memory, cap);
1381 reason
1382 }
1383
1384 /// What one host-originated request is told about its own life: its id on the
1385 /// channel and the token that fires when the request is cancelled (the host's
1386 /// `$/cancel`, the owner's revocation, or the host's exit). A handler that
1387 /// waits for anything must wait on `cancel` too; one that ignores it is
1388 /// abandoned [`CANCEL_GRACE`] after it fires and its answer is dropped.
1389 pub struct HostRequestContext {
1390 pub id: u64,
1391 pub cancel: CancellationToken,
1392 /// The channel's kill switch, for a handler that finds the host in
1393 /// violation of the protocol (it ends the host, like a bad frame).
1394 kill: mpsc::Sender<String>,
1395 }
1396
1397 #[cfg(any(test, feature = "test-support"))]
1398 impl HostRequestContext {
1399 /// A context not attached to any channel, with the receiver its violations
1400 /// arrive on and the token that cancels it.
1401 pub fn for_test(id: u64) -> (Self, mpsc::Receiver<String>, CancellationToken) {
1402 let (kill, violations) = mpsc::channel(8);
1403 let cancel = CancellationToken::new();
1404 (
1405 Self {
1406 id,
1407 cancel: cancel.clone(),
1408 kill,
1409 },
1410 violations,
1411 cancel,
1412 )
1413 }
1414 }
1415
1416 impl HostRequestContext {
1417 /// Report a protocol violation by the host: the host process is ended.
1418 pub fn violation(&self, reason: String) {
1419 let _ = self.kill.try_send(format!("protocol violation: {reason}"));
1420 }
1421 }
1422
1423 /// Callbacks from the channel into the manager.
1424 #[async_trait]
1425 pub trait HostEvents: Send + Sync + 'static {
1426 fn register(&self, params: &protocol::RegisterParams) -> RegisterResult;
1427 fn unregister(&self, params: &protocol::UnregisterParams);
1428 fn faulted(&self, params: &protocol::FaultedParams);
1429 fn log(&self, params: &protocol::LogParams);
1430 fn exited(&self, host_generation: u64, reason: String, stderr_tail: String);
1431
1432 /// A current, non-revoked call received a correlated reply. Late replies
1433 /// and heartbeat answers do not pass here; the monitor validates pongs.
1434 fn responded(&self) {}
1435
1436 /// Answer one host-originated request. Every such request runs as its own
1437 /// task (`start_host_request`), so a handler may take as long as it needs
1438 /// without holding up the reader. The registry requests are quick and
1439 /// synchronous; a request that has to wait (a tool call the host asked the
1440 /// core to make, later) overrides this and observes `cx.cancel`.
1441 async fn host_request(
1442 &self,
1443 request: HostRequest,
1444 cx: HostRequestContext,
1445 ) -> Result<Value, RpcErrorWire> {
1446 registry_host_request(self, request, &cx)
1447 }
1448 }
1449
1450 /// The answer to a registry request (`registry/register`,
1451 /// `registry/unregister`), which is quick and synchronous, and the refusal of a
1452 /// `core/call` an events implementation does not serve. The default
1453 /// [`HostEvents::host_request`], and what an overriding one falls back to.
1454 pub fn registry_host_request<E: HostEvents + ?Sized>(
1455 events: &E,
1456 request: HostRequest,
1457 cx: &HostRequestContext,
1458 ) -> Result<Value, RpcErrorWire> {
1459 tracing::trace!(target: "extension_host", id = cx.id, "host request");
1460 // A request cancelled before its handler began does nothing.
1461 if cx.cancel.is_cancelled() {
1462 return Err(RpcErrorWire {
1463 code: error_code::CANCELLED,
1464 message: "cancelled".to_string(),
1465 data: None,
1466 });
1467 }
1468 match request {
1469 HostRequest::Register(params) => Ok(serde_json::to_value(events.register(&params))
1470 .unwrap_or_else(|_| json!({"refused": "internal"}))),
1471 HostRequest::Unregister(params) => {
1472 events.unregister(&params);
1473 Ok(json!({}))
1474 }
1475 HostRequest::UserQuestion(_) => Err(RpcErrorWire {
1476 code: error_code::NOT_AVAILABLE,
1477 message: "user-questions/ask is not served here".to_string(),
1478 data: None,
1479 }),
1480 HostRequest::SubagentStart(_)
1481 | HostRequest::SubagentResult(_)
1482 | HostRequest::SubagentDispose(_)
1483 | HostRequest::SubagentPrompt(_) => Err(RpcErrorWire {
1484 code: error_code::NOT_AVAILABLE,
1485 message: "subagent requests are not served here".to_string(),
1486 data: None,
1487 }),
1488 HostRequest::SessionCheckpoint(_) => Err(RpcErrorWire {
1489 code: error_code::REFUSED,
1490 message: "session/checkpoint is not served here".to_string(),
1491 data: None,
1492 }),
1493 HostRequest::DshBroker(_) => Err(RpcErrorWire {
1494 code: error_code::NOT_AVAILABLE,
1495 message: "dsh/broker is not served here".to_string(),
1496 data: Some(json!({ "dsh_refusal": "not_available" })),
1497 }),
1498 HostRequest::ExecutionRedeem(_)
1499 | HostRequest::CoreCall(_)
1500 | HostRequest::ProcLaunch(_)
1501 | HostRequest::ProcRead(_)
1502 | HostRequest::ProcWrite(_)
1503 | HostRequest::ProcClose(_)
1504 | HostRequest::NetStart(_)
1505 | HostRequest::NetFetch(_)
1506 | HostRequest::NetRead(_)
1507 | HostRequest::NetRelease(_)
1508 | HostRequest::NetClose(_) => Err(RpcErrorWire {
1509 code: error_code::REFUSED,
1510 message: "core/call is not served here".to_string(),
1511 data: None,
1512 }),
1513 }
1514 }
1515
1516 /// Why an in-flight host request was cancelled; decides what the host is told.
1517 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1518 enum CancelReason {
1519 /// The host sent `$/cancel`: it has already stopped waiting, so whatever
1520 /// the handler produces afterwards is dropped.
1521 Host,
1522 /// The request's owner was revoked: the host is answered `Cancelled`.
1523 Revoked,
1524 /// The host exited: there is nobody to answer.
1525 Exit,
1526 }
1527
1528 struct InboundRequest {
1529 /// The plugin whose revocation cancels it.
1530 owner: String,
1531 cancel: CancellationToken,
1532 cancelled: Option<CancelReason>,
1533 }
1534
1535 /// The host-originated requests in flight, by the id the host gave them. At
1536 /// most [`protocol::MAX_INFLIGHT`] at a time (the same bound the host holds
1537 /// itself to), no id twice, and nothing admitted once the host has exited.
1538 #[derive(Default)]
1539 pub struct InboundRequests {
1540 table: Mutex<InboundTable>,
1541 }
1542
1543 #[derive(Default)]
1544 struct InboundTable {
1545 requests: HashMap<u64, InboundRequest>,
1546 closed: bool,
1547 }
1548
1549 impl InboundRequests {
1550 /// Start tracking request `id` of `owner`. `Err` is a protocol violation:
1551 /// the host reused an id still in flight, or has more requests in flight
1552 /// than its own limit allows.
1553 fn admit(&self, id: u64, owner: &str) -> Result<CancellationToken, String> {
1554 let mut table = self.table.lock().expect("inbound lock");
1555 if table.closed {
1556 return Err("host request after the host exited".to_string());
1557 }
1558 if table.requests.contains_key(&id) {
1559 return Err(format!("host request id {id} is already in flight"));
1560 }
1561 if table.requests.len() >= protocol::MAX_INFLIGHT {
1562 return Err(format!(
1563 "more than {} host requests in flight",
1564 protocol::MAX_INFLIGHT
1565 ));
1566 }
1567 let cancel = CancellationToken::new();
1568 table.requests.insert(
1569 id,
1570 InboundRequest {
1571 owner: owner.to_string(),
1572 cancel: cancel.clone(),
1573 cancelled: None,
1574 },
1575 );
1576 Ok(cancel)
1577 }
1578
1579 /// The host's `$/cancel {id}`. An id that is not in flight (already
1580 /// answered, or never sent) is ignored: the cancel raced the answer.
1581 fn cancel_by_host(&self, id: u64) {
1582 if let Some(request) = self
1583 .table
1584 .lock()
1585 .expect("inbound lock")
1586 .requests
1587 .get_mut(&id)
1588 {
1589 request.fire(CancelReason::Host);
1590 }
1591 }
1592
1593 /// Cancel every in-flight request of `plugin_id`: its owner was revoked.
1594 fn cancel_owner(&self, plugin_id: &str) {
1595 for request in self
1596 .table
1597 .lock()
1598 .expect("inbound lock")
1599 .requests
1600 .values_mut()
1601 .filter(|request| request.owner == plugin_id)
1602 {
1603 request.fire(CancelReason::Revoked);
1604 }
1605 }
1606
1607 /// The host exited: cancel everything and admit nothing more.
1608 fn cancel_all(&self) {
1609 let mut table = self.table.lock().expect("inbound lock");
1610 table.closed = true;
1611 for request in table.requests.values_mut() {
1612 request.fire(CancelReason::Exit);
1613 }
1614 }
1615
1616 /// The handler is done (or abandoned): forget the request and say why it
1617 /// was cancelled, if it was.
1618 fn finish(&self, id: u64) -> Option<CancelReason> {
1619 self.table
1620 .lock()
1621 .expect("inbound lock")
1622 .requests
1623 .remove(&id)
1624 .and_then(|request| request.cancelled)
1625 }
1626
1627 #[cfg(test)]
1628 fn in_flight(&self) -> usize {
1629 self.table.lock().expect("inbound lock").requests.len()
1630 }
1631 }
1632
1633 impl InboundRequest {
1634 /// Cancel for `reason`; the first reason stands.
1635 fn fire(&mut self, reason: CancelReason) {
1636 self.cancelled.get_or_insert(reason);
1637 self.cancel.cancel();
1638 }
1639 }
1640
1641 /// Receives one request's outcome.
1642 pub type CallReceiver = oneshot::Receiver<Result<Value, HostCallError>>;
1643
1644 struct PendingCall {
1645 tx: oneshot::Sender<Result<Value, HostCallError>>,
1646 /// Plugin whose revocation cancels this call.
1647 owner: Option<String>,
1648 /// Exact never-reused registration handle, when this is a contribution call.
1649 handle: Option<u64>,
1650 revoked: bool,
1651 heartbeat: bool,
1652 }
1653
1654 #[derive(Default)]
1655 struct Handshake {
1656 hello: Option<oneshot::Sender<protocol::HelloParams>>,
1657 ready: Option<oneshot::Sender<()>>,
1658 }
1659
1660 pub struct HostProcess {
1661 pub cohort: HostCohort,
1662 /// The tier this process was launched for.
1663 pub tier: HostTier,
1664 /// The generation of its tier's host this process is (what the manager
1665 /// bumps per launch); a capability ticket is bound to it.
1666 pub generation: u64,
1667 pub pid: Option<u32>,
1668 /// The runtime the Rust side launched; `host/hello` must agree.
1669 pub runtime: HostRuntime,
1670 /// Runtime version as reported by the host in `host/hello`.
1671 pub runtime_version: std::sync::OnceLock<String>,
1672 pub memory_cap: u64,
1673 /// How the cap is enforced for this process, settled at the handshake.
1674 memory: Arc<std::sync::OnceLock<MemoryEnforcement>>,
1675 pub sandbox: HostSandbox,
1676 #[cfg(not(windows))]
1677 native_snapshot_roots: Vec<PathBuf>,
1678 tree: Arc<codewhale_runtime::process_tree::ProcessTree>,
1679 #[cfg(windows)]
1680 windows: Option<super::windows::NativeSandbox>,
1681 outbound: mpsc::Sender<Vec<u8>>,
1682 pending: Arc<Mutex<HashMap<u64, PendingCall>>>,
1683 /// Requests the host sent, running as tasks ([`start_host_request`]).
1684 inbound: Arc<InboundRequests>,
1685 /// Admission checks and sealing hold `pending`; the manager also reads
1686 /// this flag to avoid activation while the exit callback is still pending.
1687 admission_closed: AtomicBool,
1688 next_id: AtomicU64,
1689 /// Heartbeat pings among those ids; tests count only the core's own work.
1690 #[cfg(any(test, feature = "test-support"))]
1691 heartbeats_sent: AtomicU64,
1692 stderr_tail: Arc<Mutex<VecDeque<u8>>>,
1693 exited: tokio::sync::watch::Receiver<bool>,
1694 kill: mpsc::Sender<String>,
1695 }
1696
1697 fn push_tail(tail: &Mutex<VecDeque<u8>>, bytes: &[u8]) {
1698 let mut tail = tail.lock().expect("stderr tail lock");
1699 tail.extend(bytes);
1700 while tail.len() > STDERR_TAIL_BYTES {
1701 tail.pop_front();
1702 }
1703 }
1704
1705 fn tail_string(tail: &Mutex<VecDeque<u8>>) -> String {
1706 let tail = tail.lock().expect("stderr tail lock");
1707 let bytes: Vec<u8> = tail.iter().copied().collect();
1708 String::from_utf8_lossy(&bytes).into_owned()
1709 }
1710
1711 /// The watcher/protocol remains one implementation for both launch mechanisms.
1712 enum HostChild {
1713 Tokio(tokio::process::Child),
1714 #[cfg(windows)]
1715 Native(super::windows::Child),
1716 }
1717 impl HostChild {
1718 async fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
1719 match self {
1720 Self::Tokio(child) => child.wait().await,
1721 #[cfg(windows)]
1722 Self::Native(child) => child.wait().await,
1723 }
1724 }
1725 async fn kill(&mut self) -> std::io::Result<()> {
1726 match self {
1727 Self::Tokio(child) => child.kill().await,
1728 #[cfg(windows)]
1729 Self::Native(child) => child.kill().await,
1730 }
1731 }
1732 }
1733 struct SpawnedHost {
1734 child: HostChild,
1735 pid: Option<u32>,
1736 tree: Arc<codewhale_runtime::process_tree::ProcessTree>,
1737 stdin: tokio::process::ChildStdin,
1738 stdout: tokio::process::ChildStdout,
1739 stderr: tokio::process::ChildStderr,
1740 }
1741 fn spawn_host(
1742 launch: &HostLaunch,
1743 mut command: tokio::process::Command,
1744 _environment: &[(std::ffi::OsString, std::ffi::OsString)],
1745 ) -> Result<SpawnedHost, String> {
1746 #[cfg(windows)]
1747 if let Some(sandbox) = &launch.windows {
1748 let native = sandbox
1749 .spawn(&launch.args, _environment, launch.memory_cap)
1750 .map_err(|error| {
1751 format!("failed to launch the verified Windows Native host: {error}")
1752 })?;
1753 let stdin =
1754 tokio::process::ChildStdin::from_std(std::process::ChildStdin::from(native.stdin))
1755 .map_err(|error| format!("host stdin conversion failed: {error}"))?;
1756 let stdout =
1757 tokio::process::ChildStdout::from_std(std::process::ChildStdout::from(native.stdout))
1758 .map_err(|error| format!("host stdout conversion failed: {error}"))?;
1759 let stderr =
1760 tokio::process::ChildStderr::from_std(std::process::ChildStderr::from(native.stderr))
1761 .map_err(|error| format!("host stderr conversion failed: {error}"))?;
1762 let tree = Arc::clone(&native.child.tree);
1763 let pid = Some(native.child.pid);
1764 return Ok(SpawnedHost {
1765 child: HostChild::Native(native.child),
1766 pid,
1767 tree,
1768 stdin,
1769 stdout,
1770 stderr,
1771 });
1772 }
1773 // On Linux a failure to apply the memory cap in the child surfaces
1774 // here as a spawn error carrying only its errno, indistinguishable
1775 // from a failed exec, so the message names both.
1776 let mut child = command.spawn().map_err(|error| {
1777 if cfg!(target_os = "linux") {
1778 format!(
1779 "failed to start {}, or to apply its {} MiB memory cap (RLIMIT_DATA) before exec: {error}",
1780 launch.program.display(),
1781 launch.memory_cap / (1024 * 1024)
1782 )
1783 } else {
1784 format!("failed to start {}: {error}", launch.program.display())
1785 }
1786 })?;
1787 let pid = child.id();
1788 let tree = match codewhale_runtime::process_tree::ProcessTree::attach_tokio(&child) {
1789 Ok(tree) => Arc::new(tree),
1790 Err(error) => {
1791 let _ = child.start_kill();
1792 return Err(format!("failed to contain the plugin host: {error}"));
1793 }
1794 };
1795 #[cfg(windows)]
1796 if let Err(error) = tree.limit_process_memory(launch.memory_cap) {
1797 let _ = tree.kill();
1798 let _ = child.start_kill();
1799 return Err(format!("failed to cap the plugin host's memory: {error}"));
1800 }
1801 let stdin = child.stdin.take().ok_or("host stdin unavailable")?;
1802 let stdout = child.stdout.take().ok_or("host stdout unavailable")?;
1803 let stderr = child.stderr.take().ok_or("host stderr unavailable")?;
1804
1805 Ok(SpawnedHost {
1806 child: HostChild::Tokio(child),
1807 pid,
1808 tree,
1809 stdin,
1810 stdout,
1811 stderr,
1812 })
1813 }
1814
1815 impl HostProcess {
1816 pub fn grant_data_dir(&self, dir: &Path) -> Result<(), String> {
1817 #[cfg(windows)]
1818 if let Some(windows) = &self.windows {
1819 return windows.grant_data_dir(dir);
1820 }
1821 let _ = dir;
1822 Ok(())
1823 }
1824
1825 pub async fn admit_native_root(
1826 &self,
1827 authority: codewhale_config::PluginAuthority,
1828 ) -> Result<(), String> {
1829 #[cfg(windows)]
1830 let sandbox = self
1831 .windows
1832 .clone()
1833 .ok_or("Native host has no verified LPAC plan")?;
1834 #[cfg(not(windows))]
1835 let snapshot_roots = self.native_snapshot_roots.clone();
1836 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
1837 if !policy {
1838 return Err("Native plugins are disabled".into());
1839 }
1840 #[cfg(any(test, feature = "test-support"))]
1841 let env_scope = crate::test_support::env_scope_ticket();
1842 tokio::task::spawn_blocking(move || {
1843 #[cfg(any(test, feature = "test-support"))]
1844 let _env_scope = crate::test_support::join_env_scope(env_scope);
1845 let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy);
1846 let capability = codewhale_plugins::activation::PluginActivationCapability::Native;
1847 codewhale_plugins::registry::verify_plugin_component_authority(&authority, capability)?;
1848 let root =
1849 codewhale_plugins::agent_plugin::plugin_root_for_manifest(&authority.staged_manifest)
1850 .ok_or("reviewed runtime manifest has no bundle root")?;
1851 #[cfg(windows)]
1852 sandbox.admit_root(root)?;
1853 #[cfg(not(windows))]
1854 {
1855 let canonical = root.canonicalize().map_err(|error| error.to_string())?;
1856 if !snapshot_roots.iter().any(|grant| canonical.starts_with(grant) && canonical != *grant) {
1857 return Err("Native snapshot store was not granted to this host; restart Codewhale to admit this store".into());
1858 }
1859 let current = native_snapshot_roots(std::slice::from_ref(&authority.state_path))?;
1860 if !current.iter().any(|grant| snapshot_roots.contains(grant) && canonical.starts_with(grant)) {
1861 return Err("Native snapshot store changed after host launch".into());
1862 }
1863 }
1864 codewhale_plugins::registry::verify_plugin_component_authority(&authority, capability)
1865 })
1866 .await
1867 .map_err(|error| format!("Native bundle admission worker failed: {error}"))?
1868 }
1869
1870 /// Spawn the host and complete the handshake. `expected_sha256` is the
1871 /// digest of the bundle this process materialized; the host's
1872 /// self-reported digest must match (a consistency check, not
1873 /// anti-substitution: the control is that Rust chooses what to exec).
1874 pub async fn spawn(
1875 generation: u64,
1876 launch: &HostLaunch,
1877 expected_sha256: &str,
1878 events: Arc<dyn HostEvents>,
1879 ) -> Result<Arc<Self>, String> {
1880 let mut command = tokio::process::Command::new(&launch.program);
1881 codewhale_util::utils::suppress_tokio_console_window(&mut command);
1882 command
1883 .args(&launch.args)
1884 .current_dir(&launch.cwd)
1885 .stdin(Stdio::piped())
1886 .stdout(Stdio::piped())
1887 .stderr(Stdio::piped())
1888 .kill_on_drop(true);
1889 // Scrubbed environment: no credentials, no ambient proxy URLs.
1890 command.env_clear();
1891 let parent_pid = std::process::id().to_string();
1892 // On Unix the host leads its own process group (below), so it may kill
1893 // that group when the core goes away (stdin EOF, or a parent change
1894 // seen by its watchdog thread).
1895 let own_group = if cfg!(unix) { "1" } else { "0" };
1896 let memory_request = (launch.memory == MemoryEnforcement::Jetsam)
1897 .then(|| (launch.memory_cap / (1024 * 1024)).max(1).to_string());
1898 let overrides = launch
1899 .sandbox_env
1900 .iter()
1901 .chain(&launch.runtime_env)
1902 .map(|(key, value)| (key.as_str(), value.as_str()))
1903 .chain(
1904 memory_request
1905 .as_deref()
1906 .map(|mib| (MEMORY_LIMIT_REQUEST_ENV, mib)),
1907 )
1908 .chain([
1909 ("CODEWHALE_HOST_PARENT_PID", parent_pid.as_str()),
1910 ("CODEWHALE_HOST_PROCESS_GROUP", own_group),
1911 ]);
1912 let environment = codewhale_runtime::child_env::sanitized_plugin_mcp_env_from(
1913 std::env::vars_os(),
1914 overrides,
1915 );
1916 command.envs(environment.iter().map(|(key, value)| (key, value)));
1917 #[cfg(unix)]
1918 command.process_group(0);
1919 limit_child_memory(&mut command, launch.memory_cap);
1920
1921 let SpawnedHost {
1922 mut child,
1923 pid,
1924 tree,
1925 stdin,
1926 stdout,
1927 stderr,
1928 } = spawn_host(launch, command, &environment)?;
1929 let memory: Arc<std::sync::OnceLock<MemoryEnforcement>> = Arc::default();
1930
1931 let (outbound, mut outbound_rx) = mpsc::channel::<Vec<u8>>(OUTBOUND_QUEUE);
1932 let pending: Arc<Mutex<HashMap<u64, PendingCall>>> = Arc::default();
1933 let inbound: Arc<InboundRequests> = Arc::default();
1934 let stderr_tail: Arc<Mutex<VecDeque<u8>>> = Arc::default();
1935 let (exited_tx, exited_rx) = tokio::sync::watch::channel(false);
1936 let (hello_tx, hello_rx) = oneshot::channel();
1937 let (ready_tx, ready_rx) = oneshot::channel();
1938 let handshake = Arc::new(Mutex::new(Handshake {
1939 hello: Some(hello_tx),
1940 ready: Some(ready_tx),
1941 }));
1942
1943 // Writer: the only task that touches stdin. Dropping every sender
1944 // closes stdin, which the host treats as "core is gone".
1945 tokio::spawn(async move {
1946 let mut stdin = stdin;
1947 while let Some(frame) = outbound_rx.recv().await {
1948 if stdin.write_all(&frame).await.is_err() || stdin.flush().await.is_err() {
1949 break;
1950 }
1951 }
1952 });
1953
1954 // stderr: a bounded tail for diagnostics, chunks into tracing. Read
1955 // in fixed-size chunks, never by line: a plugin writing endless
1956 // output without a newline must not grow this process's memory.
1957 {
1958 let tail = Arc::clone(&stderr_tail);
1959 tokio::spawn(async move {
1960 let mut stderr = stderr;
1961 let mut chunk = vec![0_u8; 4096];
1962 while let Ok(read) = stderr.read(&mut chunk).await {
1963 if read == 0 {
1964 break;
1965 }
1966 push_tail(&tail, &chunk[..read]);
1967 tracing::debug!(
1968 target: "extension_host",
1969 "host stderr: {}",
1970 String::from_utf8_lossy(&chunk[..read]).trim_end()
1971 );
1972 }
1973 });
1974 }
1975
1976 // Reader: every frame is validated strictly; a framing or protocol
1977 // violation kills the host (a plugin wrote to the channel, or the
1978 // host is not ours).
1979 let (kill_tx, mut kill_rx) = mpsc::channel::<String>(1);
1980 {
1981 let reader = Reader {
1982 kill: kill_tx.clone(),
1983 pending: Arc::clone(&pending),
1984 inbound: Arc::clone(&inbound),
1985 outbound: outbound.clone(),
1986 events: Arc::clone(&events),
1987 handshake: Arc::clone(&handshake),
1988 };
1989 let tier = launch.tier;
1990 let kill_tx = kill_tx.clone();
1991 tokio::spawn(async move {
1992 let mut stdout = stdout;
1993 loop {
1994 let value = match protocol::read_frame(&mut stdout).await {
1995 Ok(Some(value)) => value,
1996 Ok(None) => break,
1997 Err(error) => {
1998 let _ = kill_tx.try_send(format!("channel framing violation: {error}"));
1999 break;
2000 }
2001 };
2002 let message = match protocol::parse_host_message(value, tier) {
2003 Ok(message) => message,
2004 Err(error) => {
2005 let _ = kill_tx.try_send(format!("protocol violation: {error}"));
2006 break;
2007 }
2008 };
2009 if let Err(violation) = reader.handle(message) {
2010 let _ = kill_tx.try_send(format!("protocol violation: {violation}"));
2011 break;
2012 }
2013 }
2014 });
2015 }
2016
2017 // Exit watcher: owns the child. On exit, fail everything and report.
2018 {
2019 let pending = Arc::clone(&pending);
2020 let inbound = Arc::clone(&inbound);
2021 let tail = Arc::clone(&stderr_tail);
2022 let events = Arc::clone(&events);
2023 let tree = Arc::clone(&tree);
2024 let memory = Arc::clone(&memory);
2025 let memory_cap = launch.memory_cap;
2026 tokio::spawn(async move {
2027 let reason = tokio::select! {
2028 biased;
2029 status = child.wait() => match status {
2030 Ok(status) => exit_reason(status, memory.get().copied(), memory_cap),
2031 Err(error) => format!("wait failed: {error}"),
2032 },
2033 Some(reason) = kill_rx.recv() => {
2034 let _ = tree.kill();
2035 let _ = child.kill().await;
2036 reason
2037 }
2038 };
2039 // The leader is gone; take anything it left behind with it.
2040 let _ = tree.kill();
2041 let drained: Vec<PendingCall> = {
2042 let mut pending = pending.lock().expect("pending lock");
2043 // Publish exit under the admission lock before draining:
2044 // waking a failed call must not admit another orphaned call.
2045 let _ = exited_tx.send(true);
2046 pending.drain().map(|(_, call)| call).collect()
2047 };
2048 for call in drained {
2049 let _ = call.tx.send(Err(HostCallError::Exited(reason.clone())));
2050 }
2051 // Requests the host sent have nobody left to answer.
2052 inbound.cancel_all();
2053 // Give the stderr task a moment to capture the last lines.
2054 tokio::time::sleep(Duration::from_millis(50)).await;
2055 events.exited(generation, reason, tail_string(&tail));
2056 });
2057 }
2058
2059 let host = Arc::new(Self {
2060 cohort: launch.cohort.clone(),
2061 tier: launch.tier,
2062 generation,
2063 pid,
2064 runtime: launch.runtime.clone(),
2065 runtime_version: std::sync::OnceLock::new(),
2066 memory_cap: launch.memory_cap,
2067 memory,
2068 sandbox: launch.sandbox.clone(),
2069 #[cfg(not(windows))]
2070 native_snapshot_roots: launch.native_snapshot_roots.clone(),
2071 tree,
2072 #[cfg(windows)]
2073 windows: launch.windows.clone(),
2074 outbound,
2075 pending,
2076 inbound,
2077 admission_closed: AtomicBool::new(false),
2078 next_id: AtomicU64::new(1),
2079 #[cfg(any(test, feature = "test-support"))]
2080 heartbeats_sent: AtomicU64::new(0),
2081 stderr_tail,
2082 exited: exited_rx,
2083 kill: kill_tx.clone(),
2084 });
2085
2086 let handshake_result = tokio::time::timeout(HANDSHAKE_DEADLINE, async {
2087 let hello = hello_rx
2088 .await
2089 .map_err(|_| "host exited before host/hello".to_string())?;
2090 if hello.protocol.min > protocol::PROTOCOL_VERSION
2091 || hello.protocol.max < protocol::PROTOCOL_VERSION
2092 {
2093 return Err(format!(
2094 "host speaks protocol {}..={}, core speaks {}",
2095 hello.protocol.min,
2096 hello.protocol.max,
2097 protocol::PROTOCOL_VERSION
2098 ));
2099 }
2100 // Never a silent runtime switch: the host must be running on
2101 // the runtime this process chose and launched.
2102 if hello.runtime.name != launch.runtime.kind.name() {
2103 return Err(format!(
2104 "host reports runtime {} but {} was launched",
2105 hello.runtime.name,
2106 launch.runtime.kind.name()
2107 ));
2108 }
2109 check_hello_identity(&hello, launch.tier, launch.builtin_modules)?;
2110 // Restarts reuse the pinned runtime without probing it again, so
2111 // the binary at that path can have been replaced since (an
2112 // upgrade mid-session). Its flags and lockdown were chosen for
2113 // the probed version; refuse rather than run an unprobed one.
2114 if !launch.runtime.reports_version(&hello.runtime.version) {
2115 return Err(format!(
2116 "host reports {} {} but {} {} was probed at {}: the runtime binary changed mid-session; restart Codewhale to use the new version",
2117 hello.runtime.name,
2118 hello.runtime.version,
2119 launch.runtime.kind.name(),
2120 launch.runtime.version_string(),
2121 launch.runtime.path.display()
2122 ));
2123 }
2124 if hello.bundle_sha256 != expected_sha256 {
2125 return Err(format!(
2126 "host bundle digest {} does not match the materialized bundle {}",
2127 hello.bundle_sha256, expected_sha256
2128 ));
2129 }
2130 let requested = memory_request
2131 .as_deref()
2132 .and_then(|mib| mib.parse::<u64>().ok());
2133 let memory = match (hello.memory_limit_mib, requested) {
2134 (Some(applied), Some(requested)) if applied == requested => {
2135 MemoryEnforcement::Jetsam
2136 }
2137 (Some(applied), _) => {
2138 return Err(format!(
2139 "host reports a {applied} MiB memory limit the core did not ask for"
2140 ));
2141 }
2142 // The mandatory kernel cap cannot degrade to a delayed RSS
2143 // observation. Refuse before plugin initialization and keep
2144 // the host's stderr explanation in the existing diagnosis.
2145 (None, Some(requested)) => {
2146 return Err(format!(
2147 "host did not apply the requested {requested} MiB kernel memory limit; initialization refused"
2148 ));
2149 }
2150 (None, None) => launch.memory,
2151 };
2152 let _ = host.memory.set(memory);
2153 let initialize = CoreRequest::Initialize(InitializeParams {
2154 protocol: protocol::PROTOCOL_VERSION,
2155 limits: HostLimits {
2156 max_frame: protocol::MAX_FRAME as u64,
2157 max_inflight: protocol::MAX_INFLIGHT as u64,
2158 dispose_deadline_ms: DISPOSE_DEADLINE.as_millis() as u64,
2159 activate_deadline_ms: ACTIVATE_DEADLINE.as_millis() as u64,
2160 },
2161 });
2162 host.call(initialize, None)
2163 .await
2164 .map_err(|error| format!("host/initialize failed: {error}"))?;
2165 ready_rx
2166 .await
2167 .map_err(|_| "host exited before host/ready".to_string())?;
2168 Ok(hello.runtime.version)
2169 })
2170 .await;
2171 match handshake_result {
2172 Ok(Ok(runtime_version)) => {
2173 let _ = host.runtime_version.set(runtime_version);
2174 Ok(host)
2175 }
2176 Ok(Err(reason)) => {
2177 let _ = kill_tx.try_send(reason.clone());
2178 Err(format!(
2179 "{reason}; stderr: {}",
2180 tail_string(&host.stderr_tail)
2181 ))
2182 }
2183 Err(_) => {
2184 let reason = format!("handshake exceeded {HANDSHAKE_DEADLINE:?}");
2185 let _ = kill_tx.try_send(reason.clone());
2186 Err(format!(
2187 "{reason}; stderr: {}",
2188 tail_string(&host.stderr_tail)
2189 ))
2190 }
2191 }
2192 }
2193
2194 /// How the memory cap is enforced for this process (planned until the
2195 /// handshake settles it).
2196 #[must_use]
2197 pub fn memory(&self) -> MemoryEnforcement {
2198 self.memory
2199 .get()
2200 .copied()
2201 .unwrap_or_else(|| MemoryEnforcement::planned(self.runtime.kind))
2202 }
2203
2204 /// How many requests the core has sent this host (handshake included),
2205 /// excluding the monitor's heartbeat pings, which run on their own timer
2206 /// and would otherwise make a "no request yet" assertion timing-dependent.
2207 #[cfg(any(test, feature = "test-support"))]
2208 pub fn requests_started(&self) -> u64 {
2209 self.next_id.load(Ordering::Relaxed) - 1 - self.heartbeats_sent.load(Ordering::Relaxed)
2210 }
2211
2212 #[must_use]
2213 pub fn has_exited(&self) -> bool {
2214 *self.exited.borrow()
2215 }
2216
2217 pub fn terminate(&self, reason: String) {
2218 let _ = self.kill.try_send(reason);
2219 }
2220
2221 pub fn is_retiring(&self) -> bool {
2222 self.admission_closed.load(Ordering::Acquire)
2223 }
2224
2225 /// Seal admission and retire this process only if no non-heartbeat call
2226 /// is pending. The same lock guards admission in `start_request`.
2227 pub fn terminate_if_idle(&self, reason: &str) -> bool {
2228 let pending = self.pending.lock().expect("pending lock");
2229 if self.has_exited()
2230 || self.admission_closed.load(Ordering::Relaxed)
2231 || pending.values().any(|call| !call.heartbeat)
2232 {
2233 return false;
2234 }
2235 if self.kill.try_send(reason.to_string()).is_err() {
2236 return false;
2237 }
2238 self.admission_closed.store(true, Ordering::Release);
2239 true
2240 }
2241
2242 pub fn stderr_tail(&self) -> String {
2243 tail_string(&self.stderr_tail)
2244 }
2245
2246 fn send_frame(&self, value: &Value) -> Result<(), HostCallError> {
2247 let frame = protocol::encode_frame(value).map_err(|error| HostCallError::Rpc {
2248 code: error_code::INVALID_PARAMS,
2249 message: error.to_string(),
2250 })?;
2251 self.outbound.try_send(frame).map_err(|error| match error {
2252 mpsc::error::TrySendError::Full(_) => HostCallError::Busy,
2253 mpsc::error::TrySendError::Closed(_) => {
2254 HostCallError::Exited("channel closed".to_string())
2255 }
2256 })
2257 }
2258
2259 /// Send a request; the returned id can be cancelled with [`Self::cancel`].
2260 pub fn start_request(
2261 &self,
2262 request: CoreRequest,
2263 owner: Option<String>,
2264 ) -> Result<(u64, CallReceiver), HostCallError> {
2265 // A method reserved for another tier is never sent to this host.
2266 if !protocol::allowed_on(Direction::CoreToHost, request.method(), self.tier) {
2267 return Err(HostCallError::Rpc {
2268 code: error_code::METHOD_NOT_FOUND,
2269 message: format!(
2270 "`{}` is not allowed on the {} tier",
2271 request.method(),
2272 self.tier.name()
2273 ),
2274 });
2275 }
2276 if self.has_exited() {
2277 return Err(HostCallError::Exited("already exited".to_string()));
2278 }
2279 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
2280 #[cfg(any(test, feature = "test-support"))]
2281 if matches!(request, CoreRequest::Ping) {
2282 self.heartbeats_sent.fetch_add(1, Ordering::Relaxed);
2283 }
2284 let (tx, rx) = oneshot::channel();
2285 {
2286 let mut pending = self.pending.lock().expect("pending lock");
2287 // Exit may have won after the fast check above. It publishes under
2288 // this same lock, so every admitted call is either live or drained.
2289 if self.has_exited() {
2290 return Err(HostCallError::Exited("already exited".to_string()));
2291 }
2292 if self.admission_closed.load(Ordering::Relaxed) {
2293 return Err(HostCallError::Exited("host is restarting".to_string()));
2294 }
2295 // Reserve one control request for the single heartbeat monitor,
2296 // so saturated tool calls cannot make a healthy host look hung.
2297 if pending.len() >= protocol::MAX_INFLIGHT && !matches!(request, CoreRequest::Ping) {
2298 return Err(HostCallError::Busy);
2299 }
2300 pending.insert(
2301 id,
2302 PendingCall {
2303 tx,
2304 owner,
2305 handle: match &request {
2306 CoreRequest::ToolCall(params) => Some(params.handle),
2307 CoreRequest::CommandRun(params) => Some(params.handle),
2308 CoreRequest::HookEvaluate(params) => Some(params.handle),
2309 _ => None,
2310 },
2311 revoked: false,
2312 heartbeat: matches!(request, CoreRequest::Ping),
2313 },
2314 );
2315 }
2316 if let Err(error) = self.send_frame(&request.to_value(id)) {
2317 self.pending.lock().expect("pending lock").remove(&id);
2318 return Err(error);
2319 }
2320 Ok((id, rx))
2321 }
2322
2323 /// Send `request` and wait at most its method's deadline
2324 /// ([`CoreRequest::deadline`]) for the answer. On expiry the host is sent
2325 /// `$/cancel`, the call is forgotten (a late answer is dropped) and the
2326 /// caller gets [`HostCallError::Timeout`]. Dropping the returned future
2327 /// (a turn interrupt) cancels the same way. Every awaited core→host
2328 /// request goes through here; only the heartbeat drives
2329 /// [`Self::start_request`] itself, under its own timeouts.
2330 pub async fn call(
2331 &self,
2332 request: CoreRequest,
2333 owner: Option<String>,
2334 ) -> Result<Value, HostCallError> {
2335 self.call_with_clock(request, owner, None).await
2336 }
2337
2338 /// [`Self::call`] with the deadline measured on `clock`, which stops while
2339 /// the caller waits on something that is not the host's time (a
2340 /// `core/call` waiting on an approval card). `None` is a clock nothing
2341 /// pauses: the plain deadline.
2342 pub async fn call_with_clock(
2343 &self,
2344 request: CoreRequest,
2345 owner: Option<String>,
2346 clock: Option<Arc<Mutex<PauseClock>>>,
2347 ) -> Result<Value, HostCallError> {
2348 let method = request.method();
2349 let deadline = request.deadline();
2350 let clock = clock.unwrap_or_else(|| Arc::new(Mutex::new(PauseClock::new())));
2351 let (id, mut rx) = self.start_request(request, owner)?;
2352 let mut guard = CancelOnDrop {
2353 host: self,
2354 id,
2355 armed: true,
2356 };
2357 let answer = loop {
2358 let remaining = clock
2359 .lock()
2360 .expect("deadline clock lock")
2361 .remaining(deadline);
2362 let Some(remaining) = remaining else {
2363 // `guard` is still armed: dropping it sends `$/cancel`.
2364 return Err(HostCallError::Timeout {
2365 method,
2366 after: deadline,
2367 });
2368 };
2369 tokio::select! {
2370 answer = &mut rx => break answer,
2371 () = tokio::time::sleep(remaining) => {}
2372 }
2373 };
2374 // Answered, drained at exit, or resolved by revocation: nothing left
2375 // to cancel.
2376 guard.armed = false;
2377 answer.unwrap_or_else(|_| Err(HostCallError::Exited("channel closed".to_string())))
2378 }
2379
2380 /// Fire `$/cancel`. Best effort: a full or closed channel is fine, the
2381 /// caller resolves its side on its own schedule.
2382 pub fn cancel(&self, id: u64) {
2383 let _ = self.send_frame(&protocol::cancel_value(id));
2384 }
2385
2386 /// Forget a request without cancelling it (its answer will be dropped).
2387 pub fn forget(&self, id: u64) {
2388 self.pending.lock().expect("pending lock").remove(&id);
2389 }
2390
2391 /// Revocation: cancel every in-flight call owned by `plugin_id`; each
2392 /// resolves as cancelled when the host answers or after `CANCEL_GRACE`,
2393 /// whichever is first — revocation never waits on the host.
2394 pub fn revoke_calls_of(self: &Arc<Self>, plugin_id: &str) {
2395 // Requests the host sent for this owner are cancelled too (and
2396 // answered `Cancelled`), whatever they are waiting for.
2397 self.inbound.cancel_owner(plugin_id);
2398 self.revoke_pending_where(|call| call.owner.as_deref() == Some(plugin_id));
2399 }
2400
2401 /// Retiring one Native entry cancels exactly its admitted contribution
2402 /// calls. Sibling entry requests and owner-wide broker lifecycle survive.
2403 pub fn revoke_calls_for_handles(self: &Arc<Self>, plugin_id: &str, handles: &[u64]) {
2404 self.revoke_pending_where(|call| {
2405 call.owner.as_deref() == Some(plugin_id)
2406 && call.handle.is_some_and(|handle| handles.contains(&handle))
2407 });
2408 }
2409
2410 fn revoke_pending_where(self: &Arc<Self>, drop_it: impl Fn(&PendingCall) -> bool) {
2411 let ids: Vec<u64> = {
2412 let mut pending = self.pending.lock().expect("pending lock");
2413 pending
2414 .iter_mut()
2415 .filter(|(_, call)| drop_it(call))
2416 .map(|(id, call)| {
2417 call.revoked = true;
2418 *id
2419 })
2420 .collect()
2421 };
2422 for id in ids {
2423 self.cancel(id);
2424 let pending = Arc::clone(&self.pending);
2425 tokio::spawn(async move {
2426 tokio::time::sleep(CANCEL_GRACE).await;
2427 if let Some(call) = pending.lock().expect("pending lock").remove(&id) {
2428 let _ = call.tx.send(Err(HostCallError::Cancelled(
2429 "plugin was revoked".to_string(),
2430 )));
2431 }
2432 });
2433 }
2434 }
2435
2436 /// Bounded shutdown: `host/shutdown` (2 s), close stdin, then kill the
2437 /// process group at 3 s total.
2438 #[cfg(any(test, feature = "test-support"))]
2439 pub async fn shutdown(&self) {
2440 let _ = self.call(CoreRequest::Shutdown, None).await;
2441 let mut exited = self.exited.clone();
2442 let waited = tokio::time::timeout(Duration::from_secs(1), async {
2443 while !*exited.borrow() {
2444 if exited.changed().await.is_err() {
2445 break;
2446 }
2447 }
2448 })
2449 .await;
2450 if waited.is_err() {
2451 let _ = self.tree.kill();
2452 }
2453 }
2454 }
2455
2456 /// Cancels a [`HostProcess::call`] that stops waiting before its answer:
2457 /// deadline expiry, or the caller's future being dropped.
2458 struct CancelOnDrop<'a> {
2459 host: &'a HostProcess,
2460 id: u64,
2461 armed: bool,
2462 }
2463
2464 impl Drop for CancelOnDrop<'_> {
2465 fn drop(&mut self) {
2466 if self.armed {
2467 self.host.cancel(self.id);
2468 self.host.forget(self.id);
2469 }
2470 }
2471 }
2472
2473 impl Drop for HostProcess {
2474 fn drop(&mut self) {
2475 // The exit watcher also holds the tree; kill explicitly so dropping
2476 // the last handle to a live host never leaves it running.
2477 if !self.has_exited() {
2478 let _ = self.tree.kill();
2479 }
2480 }
2481 }
2482
2483 /// What the channel's reader task holds: everything one decoded host→core
2484 /// message may touch.
2485 struct Reader {
2486 kill: mpsc::Sender<String>,
2487 pending: Arc<Mutex<HashMap<u64, PendingCall>>>,
2488 inbound: Arc<InboundRequests>,
2489 outbound: mpsc::Sender<Vec<u8>>,
2490 events: Arc<dyn HostEvents>,
2491 handshake: Arc<Mutex<Handshake>>,
2492 }
2493
2494 impl Reader {
2495 /// Route one validated host→core message. `Err` is a protocol violation
2496 /// the caller ends the host for.
2497 fn handle(&self, message: HostMessage) -> Result<(), String> {
2498 match message {
2499 HostMessage::Response { id, outcome } => {
2500 let Some(call) = self.pending.lock().expect("pending lock").remove(&id) else {
2501 tracing::debug!(target: "extension_host", id, "dropping late host response");
2502 return Ok(());
2503 };
2504 if !call.revoked && !call.heartbeat {
2505 self.events.responded();
2506 }
2507 let result = if call.revoked {
2508 Err(HostCallError::Cancelled("plugin was revoked".to_string()))
2509 } else {
2510 match outcome {
2511 Ok(value) => Ok(value),
2512 Err(error) if error.code == error_code::CANCELLED => {
2513 Err(HostCallError::Cancelled(error.message))
2514 }
2515 Err(error) => Err(HostCallError::Rpc {
2516 code: error.code,
2517 message: error.message,
2518 }),
2519 }
2520 };
2521 let _ = call.tx.send(result);
2522 }
2523 HostMessage::Request { id, request } => self.start_host_request(id, *request)?,
2524 HostMessage::Notification(notification) => match notification {
2525 HostNotification::Hello(hello) => {
2526 if let Some(tx) = self.handshake.lock().expect("handshake lock").hello.take() {
2527 let _ = tx.send(hello);
2528 }
2529 }
2530 HostNotification::Ready => {
2531 if let Some(tx) = self.handshake.lock().expect("handshake lock").ready.take() {
2532 let _ = tx.send(());
2533 }
2534 }
2535 HostNotification::Faulted(params) => self.events.faulted(&params),
2536 HostNotification::Log(log) => {
2537 self.events.log(&log);
2538 let plugin = log.plugin_id.as_deref().unwrap_or("host");
2539 match log.level.as_str() {
2540 "error" => tracing::warn!(target: "extension_host", plugin, "{}", log.msg),
2541 "warn" => tracing::info!(target: "extension_host", plugin, "{}", log.msg),
2542 _ => tracing::debug!(target: "extension_host", plugin, "{}", log.msg),
2543 }
2544 }
2545 // The host withdrawing a request of its own. One that has
2546 // already been answered is not in flight: the cancel lost the
2547 // race, and nothing is owed.
2548 HostNotification::Cancel(params) => self.inbound.cancel_by_host(params.id),
2549 },
2550 }
2551 Ok(())
2552 }
2553
2554 /// Run one host-originated request as its own task: tracked by id so the
2555 /// host's `$/cancel`, the owner's revocation and the host's exit can
2556 /// cancel it, and answered when the handler finishes unless it was
2557 /// cancelled for a reason that makes the answer moot ([`CancelReason`]).
2558 /// A handler that does not stop within [`CANCEL_GRACE`] of its cancel is
2559 /// abandoned.
2560 fn start_host_request(&self, id: u64, request: HostRequest) -> Result<(), String> {
2561 let cancel = self.inbound.admit(id, request.plugin_id())?;
2562 let events = Arc::clone(&self.events);
2563 let inbound = Arc::clone(&self.inbound);
2564 let outbound = self.outbound.clone();
2565 let kill = self.kill.clone();
2566 tokio::spawn(async move {
2567 let cx = HostRequestContext {
2568 id,
2569 cancel: cancel.clone(),
2570 kill,
2571 };
2572 let mut handler = std::pin::pin!(events.host_request(request, cx));
2573 let outcome = tokio::select! {
2574 outcome = &mut handler => Some(outcome),
2575 () = async {
2576 cancel.cancelled().await;
2577 tokio::time::sleep(CANCEL_GRACE).await;
2578 } => None,
2579 };
2580 let outcome = match (inbound.finish(id), outcome) {
2581 // The host stopped waiting, or is gone: a late answer is dropped.
2582 (Some(CancelReason::Host | CancelReason::Exit), _) => return,
2583 (Some(CancelReason::Revoked), _) | (None, None) => Err(RpcErrorWire {
2584 code: error_code::CANCELLED,
2585 message: "plugin was revoked".to_string(),
2586 data: None,
2587 }),
2588 (None, Some(outcome)) => outcome,
2589 };
2590 if let Ok(frame) = protocol::encode_frame(&protocol::response_value(id, &outcome)) {
2591 let _ = outbound.send(frame).await;
2592 }
2593 });
2594 Ok(())
2595 }
2596 }
2597
2598 /// What `host/hello` must say about the host's tier and built-in modules,
2599 /// checked the way its runtime name and version are: against what the core
2600 /// launched. The tier must be the one in the launch plan (`--tier=`), and the
2601 /// module digests the bundle embeds must be exactly the ones `modules` pins, so
2602 /// a host build and a Rust table that disagree about a built-in module are
2603 /// refused before any module can run. Pure.
2604 pub fn check_hello_identity(
2605 hello: &HelloParams,
2606 tier: HostTier,
2607 modules: &[BuiltinModule],
2608 ) -> Result<(), String> {
2609 if hello.tier != tier {
2610 return Err(format!(
2611 "host reports the {} tier but the {} tier was launched",
2612 hello.tier.name(),
2613 tier.name()
2614 ));
2615 }
2616 let describe = |rows: &[(String, String)]| {
2617 rows.iter()
2618 .map(|(id, digest)| format!("{id}={}", digest.chars().take(12).collect::<String>()))
2619 .collect::<Vec<_>>()
2620 .join(", ")
2621 };
2622 let mut reported: Vec<(String, String)> = hello
2623 .builtin_modules
2624 .iter()
2625 .map(|module| (module.id.clone(), module.sha256.clone()))
2626 .collect();
2627 let mut pinned: Vec<(String, String)> = modules
2628 .iter()
2629 .map(|module| (module.id.to_string(), module.source_sha256.to_string()))
2630 .collect();
2631 reported.sort();
2632 pinned.sort();
2633 if reported != pinned {
2634 return Err(format!(
2635 "host bundle embeds the built-in module digests [{}] but the core pins [{}]",
2636 describe(&reported),
2637 describe(&pinned)
2638 ));
2639 }
2640 Ok(())
2641 }
2642
2643 /// Where the embedded bundle is written: `<root>/extension-host/<sha256>/`.
2644 #[must_use]
2645 pub fn bundle_dir(root: &Path, sha256: &str) -> PathBuf {
2646 root.join("extension-host").join(sha256)
2647 }
2648
2649 #[cfg(test)]
2650 mod tests {
2651 use super::*;
2652
2653 #[test]
2654 fn compiled_host_has_direct_argv_and_cannot_become_a_bun_cli() {
2655 let runtime = HostRuntime {
2656 kind: HostRuntimeKind::Bun,
2657 path: PathBuf::from("/opt/codewhale-extension-host"),
2658 version: (1, 4, 0),
2659 native_code_flags: Vec::new(),
2660 compiled: true,
2661 };
2662 assert!(runtime_args(&runtime).is_empty());
2663 let temp = tempfile::tempdir().unwrap();
2664 let launch = host_launch(
2665 &HostCohort::Builtin,
2666 &runtime,
2667 vec![HostTier::Builtin.argv_flag()],
2668 temp.path().to_path_buf(),
2669 HOST_MEMORY_CAP,
2670 Err("fixture unsupported platform".to_string()),
2671 )
2672 .unwrap();
2673 assert_eq!(launch.program, runtime.path);
2674 assert_eq!(launch.args, vec!["--tier=builtin".to_string()]);
2675 assert!(
2676 launch
2677 .runtime_env
2678 .contains(&("BUN_OPTIONS".to_string(), String::new()))
2679 );
2680 assert!(
2681 launch
2682 .runtime_env
2683 .contains(&("BUN_BE_BUN".to_string(), "0".to_string()))
2684 );
2685 assert_eq!(
2686 launch.memory,
2687 MemoryEnforcement::planned(HostRuntimeKind::Bun)
2688 );
2689 }
2690
2691 fn node() -> HostRuntime {
2692 HostRuntime {
2693 kind: HostRuntimeKind::Node,
2694 path: PathBuf::from("/opt/node/bin/node"),
2695 version: (22, 19, 0),
2696 native_code_flags: Vec::new(),
2697 compiled: false,
2698 }
2699 }
2700
2701 /// A failed exact sandbox probe refuses Native code on every platform.
2702 /// The pinned Builtin exception keeps the concrete diagnostic; a verified
2703 /// wrapper keeps its command and never silently falls through to raw JS.
2704 #[test]
2705 fn missing_verified_sandbox_refuses_native_but_reports_pinned_builtin_exception() {
2706 let runtime = node();
2707 let data = PathBuf::from("/home/u/.codewhale/extension-host/data");
2708 let mut args = runtime_args(&runtime);
2709 args.push("/home/u/.codewhale/extension-host/abc/host.mjs".to_string());
2710
2711 let refused = bwrap_probe_verdict(
2712 false,
2713 "exit status: 1",
2714 "\nbwrap: setting up uid map: Permission denied\n",
2715 )
2716 .unwrap_err();
2717 assert!(
2718 refused.starts_with("bwrap unavailable (bwrap: setting up uid map: Permission denied;"),
2719 "{refused}"
2720 );
2721 assert!(
2722 refused.contains("kernel.apparmor_restrict_unprivileged_userns"),
2723 "{refused}"
2724 );
2725 let error = host_launch(
2726 &HostCohort::reviewed(),
2727 &runtime,
2728 args.clone(),
2729 data.clone(),
2730 HOST_MEMORY_CAP,
2731 Err(refused.clone()),
2732 )
2733 .unwrap_err();
2734 assert!(error.contains("Native plugins require a verified OS sandbox"));
2735 assert!(error.contains(&refused));
2736 let launch = host_launch(
2737 &HostCohort::Builtin,
2738 &runtime,
2739 args.clone(),
2740 data.clone(),
2741 HOST_MEMORY_CAP,
2742 Err(refused.clone()),
2743 )
2744 .unwrap();
2745 assert_eq!(launch.program, runtime.path);
2746 assert_eq!(launch.args, args);
2747 assert!(launch.sandbox_env.is_empty());
2748 assert_eq!(launch.sandbox, HostSandbox::Unsandboxed(refused.clone()));
2749 assert_eq!(launch.sandbox.label(), format!("none: {refused}"));
2750 assert!(
2751 launch
2752 .sandbox
2753 .to_string()
2754 .starts_with(&format!("UNSANDBOXED ({refused}): ")),
2755 "{}",
2756 launch.sandbox
2757 );
2758
2759 // No stderr: the exit status is the reason, with no namespace hint.
2760 assert_eq!(
2761 bwrap_probe_verdict(false, "signal: 9 (SIGKILL)", ""),
2762 Err("bwrap unavailable (signal: 9 (SIGKILL))".to_string())
2763 );
2764
2765 // A probe that ran keeps the wrapper.
2766 assert_eq!(bwrap_probe_verdict(true, "exit status: 0", ""), Ok(()));
2767 assert_eq!(
2768 bwrap_probe_verdict(
2769 false,
2770 "exit status: 1",
2771 "bwrap: execvp /tmp/.tmp1/bun: No such file or directory\n",
2772 ),
2773 Ok(())
2774 );
2775 let command: Vec<String> = ["/usr/bin/bwrap", "--unshare-all", "--die-with-parent", "--"]
2776 .iter()
2777 .map(ToString::to_string)
2778 .chain(std::iter::once(runtime.path.to_string_lossy().into_owned()))
2779 .chain(args.iter().cloned())
2780 .collect();
2781 let launch = host_launch(
2782 &HostCohort::reviewed(),
2783 &runtime,
2784 args.clone(),
2785 data.clone(),
2786 HOST_MEMORY_CAP,
2787 Ok(Wrapped {
2788 name: "linux-bwrap".to_string(),
2789 command: command.clone(),
2790 env: vec![("CODEWHALE_SANDBOX".to_string(), "bwrap".to_string())],
2791 }),
2792 )
2793 .unwrap();
2794 assert_eq!(launch.program, PathBuf::from("/usr/bin/bwrap"));
2795 assert_eq!(launch.args, command[1..].to_vec());
2796 assert_eq!(launch.cwd, data);
2797 assert_eq!(
2798 launch.sandbox,
2799 HostSandbox::Wrapped("linux-bwrap".to_string())
2800 );
2801 assert!(
2802 launch
2803 .sandbox
2804 .to_string()
2805 .starts_with("linux-bwrap sandbox (no direct network;"),
2806 "{}",
2807 launch.sandbox
2808 );
2809 }
2810
2811 /// Each tier has its own data directory, and neither is inside the other:
2812 /// the data directory is the host's only writable root, so a nested
2813 /// builtin directory would be writable by plugin code. The plugin tier
2814 /// keeps the path it has always had, and the plugin tier's sandbox denies
2815 /// reads of the builtin tier's directory.
2816 #[test]
2817 fn each_tier_has_its_own_data_directory_and_the_plugin_tier_cannot_read_the_builtin_one() {
2818 let temp = tempfile::tempdir().unwrap();
2819 let home = temp.path().join("home");
2820 std::fs::create_dir_all(tier_data_dir(&home, HostTier::Builtin)).unwrap();
2821 let plugin = tier_data_dir(&home, HostTier::Plugin);
2822 let builtin = tier_data_dir(&home, HostTier::Builtin);
2823 assert_ne!(plugin, builtin);
2824 assert!(!builtin.starts_with(&plugin) && !plugin.starts_with(&builtin));
2825 assert_eq!(plugin, home.join("extension-host").join("data"));
2826
2827 for whole_homes in [false, true] {
2828 let (denied, _) = host_denied_read_paths(&HostCohort::reviewed(), &home, whole_homes);
2829 assert!(
2830 denied.contains(&builtin),
2831 "plugin tier (whole_homes {whole_homes}) must deny {}",
2832 builtin.display()
2833 );
2834 assert!(!denied.contains(&plugin));
2835 let (denied, _) = host_denied_read_paths(&HostCohort::Builtin, &home, whole_homes);
2836 assert!(
2837 !denied.contains(&builtin),
2838 "the builtin tier reads its own directory"
2839 );
2840 }
2841 }
2842
2843 /// The per-plugin directory plugin config and context introduced keeps its
2844 /// path, so an installed plugin's data survives the tier split; a built-in
2845 /// module's is under the builtin tier's directory.
2846 #[test]
2847 fn the_per_plugin_data_directory_keeps_its_path() {
2848 let home = PathBuf::from("/home/u/.codewhale");
2849 let id = "user/0123456789ab/demo";
2850 assert_eq!(
2851 plugin_data_dir(&home, id, "demo"),
2852 home.join("extension-host/data/plugins/demo-e9f63c6f1a7f")
2853 );
2854 assert_eq!(
2855 owner_data_dir(&home, HostCohort::reviewed(), id, "demo"),
2856 plugin_data_dir(&home, id, "demo")
2857 );
2858 assert_eq!(
2859 owner_data_dir(&home, &HostCohort::Builtin, "host:mcp", "mcp"),
2860 home.join("extension-host/data-builtin/modules/mcp")
2861 );
2862 }
2863
2864 /// bubblewrap can mask only what exists, so under it each Codewhale home
2865 /// is denied whole (an entry created later is then denied too) and its
2866 /// readable entries come back as exceptions; Seatbelt's form is unchanged.
2867 #[test]
2868 fn under_bubblewrap_a_codewhale_home_is_denied_whole_but_its_readable_entries() {
2869 let temp = tempfile::tempdir().unwrap();
2870 let home = temp.path().join("home");
2871 std::fs::create_dir_all(home.join("extension-host")).unwrap();
2872 std::fs::write(home.join("config.toml.bak-1"), "").unwrap();
2873
2874 let (seatbelt, none) = host_denied_read_paths(&HostCohort::reviewed(), &home, false);
2875 assert!(none.is_empty());
2876 assert!(seatbelt.contains(&home.join("config.toml.bak-1")));
2877 assert!(
2878 seatbelt.contains(&home.join("secrets")),
2879 "named before it exists"
2880 );
2881 assert!(!seatbelt.contains(&home));
2882 assert!(!seatbelt.contains(&home.join("extension-host")));
2883
2884 let (bwrap, exceptions) = host_denied_read_paths(&HostCohort::reviewed(), &home, true);
2885 assert!(bwrap.contains(&home));
2886 assert!(!bwrap.contains(&home.join("config.toml.bak-1")));
2887 for entry in HOST_READABLE_HOME_ENTRIES {
2888 assert!(exceptions.contains(&home.join(entry)), "{entry}");
2889 assert!(!bwrap.contains(&home.join(entry)), "{entry}");
2890 }
2891 }
2892
2893 // -----------------------------------------------------------------------
2894 // The host's tier and built-in module digests in `host/hello`
2895 // -----------------------------------------------------------------------
2896
2897 const DEMO_DIGEST: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
2898 const OTHER_DIGEST: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
2899 const PINNED: &[BuiltinModule] = &[
2900 BuiltinModule {
2901 id: "demo",
2902 source_sha256: DEMO_DIGEST,
2903 tools: &[],
2904 services: &[],
2905 },
2906 BuiltinModule {
2907 id: "other",
2908 source_sha256: OTHER_DIGEST,
2909 tools: &[],
2910 services: &[],
2911 },
2912 ];
2913
2914 fn hello(tier: HostTier, modules: &[(&str, &str)]) -> HelloParams {
2915 HelloParams {
2916 protocol: protocol::ProtocolRange { min: 1, max: 1 },
2917 host_version: "0.1.0".to_string(),
2918 bundle_sha256: "0".repeat(64),
2919 runtime: protocol::HelloRuntime {
2920 name: "node".to_string(),
2921 version: "22.20.0".to_string(),
2922 },
2923 tier,
2924 builtin_modules: modules
2925 .iter()
2926 .map(|(id, sha256)| protocol::ModuleDigestWire {
2927 id: (*id).to_string(),
2928 sha256: (*sha256).to_string(),
2929 })
2930 .collect(),
2931 memory_limit_mib: None,
2932 }
2933 }
2934
2935 #[test]
2936 fn hello_must_report_the_launched_tier_and_exactly_the_pinned_module_digests() {
2937 // Production: no module, so none may be reported, on either tier.
2938 for tier in HostTier::ALL {
2939 assert_eq!(check_hello_identity(&hello(tier, &[]), tier, &[]), Ok(()));
2940 }
2941 // Order is not part of the claim.
2942 let reported = [("other", OTHER_DIGEST), ("demo", DEMO_DIGEST)];
2943 assert_eq!(
2944 check_hello_identity(
2945 &hello(HostTier::Builtin, &reported),
2946 HostTier::Builtin,
2947 PINNED
2948 ),
2949 Ok(())
2950 );
2951
2952 let refused = |hello: HelloParams, tier: HostTier| {
2953 check_hello_identity(&hello, tier, PINNED).unwrap_err()
2954 };
2955 assert_eq!(
2956 refused(hello(HostTier::Plugin, &reported), HostTier::Builtin),
2957 "host reports the plugin tier but the builtin tier was launched"
2958 );
2959 assert_eq!(
2960 refused(hello(HostTier::Builtin, &reported), HostTier::Plugin),
2961 "host reports the builtin tier but the plugin tier was launched"
2962 );
2963 let pinned = "[demo=0123456789ab, other=fedcba987654]";
2964 for (what, rows, shown) in [
2965 ("none reported", vec![], "[]"),
2966 (
2967 "one missing",
2968 vec![("demo", DEMO_DIGEST)],
2969 "[demo=0123456789ab]",
2970 ),
2971 (
2972 "an unpinned module",
2973 vec![
2974 ("demo", DEMO_DIGEST),
2975 ("other", OTHER_DIGEST),
2976 ("extra", DEMO_DIGEST),
2977 ],
2978 "[demo=0123456789ab, extra=0123456789ab, other=fedcba987654]",
2979 ),
2980 (
2981 "a changed digest",
2982 vec![("demo", OTHER_DIGEST), ("other", OTHER_DIGEST)],
2983 "[demo=fedcba987654, other=fedcba987654]",
2984 ),
2985 (
2986 "a row twice",
2987 vec![
2988 ("demo", DEMO_DIGEST),
2989 ("demo", DEMO_DIGEST),
2990 ("other", OTHER_DIGEST),
2991 ],
2992 "[demo=0123456789ab, demo=0123456789ab, other=fedcba987654]",
2993 ),
2994 ] {
2995 assert_eq!(
2996 refused(hello(HostTier::Builtin, &rows), HostTier::Builtin),
2997 format!(
2998 "host bundle embeds the built-in module digests {shown} but the core pins {pinned}"
2999 ),
3000 "{what}"
3001 );
3002 }
3003 // A host that reports modules when the core pins none is refused too.
3004 assert!(
3005 check_hello_identity(
3006 &hello(HostTier::Plugin, &[("demo", DEMO_DIGEST)]),
3007 HostTier::Plugin,
3008 &[]
3009 )
3010 .is_err()
3011 );
3012 }
3013
3014 // -----------------------------------------------------------------------
3015 // Host-originated requests run as their own tracked tasks
3016 // -----------------------------------------------------------------------
3017
3018 use std::sync::atomic::AtomicUsize;
3019 use tokio::sync::Notify;
3020
3021 /// How a stub handler waits.
3022 #[derive(Clone, Copy)]
3023 enum Behaviour {
3024 /// Until `release`, or until its request is cancelled (then it stops).
3025 WaitsUnlessCancelled,
3026 /// Until `release`, whatever happens to its request.
3027 IgnoresCancel,
3028 /// Forever.
3029 Hangs,
3030 }
3031
3032 struct Stub {
3033 behaviour: Behaviour,
3034 release: Arc<Notify>,
3035 started: AtomicUsize,
3036 saw_cancel: AtomicBool,
3037 }
3038
3039 impl Stub {
3040 fn new(behaviour: Behaviour) -> Arc<Self> {
3041 Arc::new(Self {
3042 behaviour,
3043 release: Arc::new(Notify::new()),
3044 started: AtomicUsize::new(0),
3045 saw_cancel: AtomicBool::new(false),
3046 })
3047 }
3048 }
3049
3050 #[async_trait]
3051 impl HostEvents for Stub {
3052 fn register(&self, _: &protocol::RegisterParams) -> RegisterResult {
3053 unreachable!("the stub answers every request itself")
3054 }
3055 fn unregister(&self, _: &protocol::UnregisterParams) {}
3056 fn faulted(&self, _: &protocol::FaultedParams) {}
3057 fn log(&self, _: &protocol::LogParams) {}
3058 fn exited(&self, _: u64, _: String, _: String) {}
3059
3060 async fn host_request(
3061 &self,
3062 _request: HostRequest,
3063 cx: HostRequestContext,
3064 ) -> Result<Value, RpcErrorWire> {
3065 self.started.fetch_add(1, Ordering::SeqCst);
3066 match self.behaviour {
3067 Behaviour::WaitsUnlessCancelled => {
3068 tokio::select! {
3069 () = cx.cancel.cancelled() => {
3070 self.saw_cancel.store(true, Ordering::SeqCst);
3071 Err(RpcErrorWire {
3072 code: error_code::CANCELLED,
3073 message: "stub saw the cancel".to_string(),
3074 data: None,
3075 })
3076 }
3077 () = self.release.notified() => Ok(json!({"answered": cx.id})),
3078 }
3079 }
3080 Behaviour::IgnoresCancel => {
3081 self.release.notified().await;
3082 Ok(json!({"answered": cx.id}))
3083 }
3084 Behaviour::Hangs => std::future::pending().await,
3085 }
3086 }
3087 }
3088
3089 /// An events implementation that keeps the trait's own answers for the
3090 /// registry requests.
3091 struct Plain;
3092
3093 #[async_trait]
3094 impl HostEvents for Plain {
3095 fn register(&self, _: &protocol::RegisterParams) -> RegisterResult {
3096 RegisterResult::Admitted { handle: 9 }
3097 }
3098 fn unregister(&self, _: &protocol::UnregisterParams) {}
3099 fn faulted(&self, _: &protocol::FaultedParams) {}
3100 fn log(&self, _: &protocol::LogParams) {}
3101 fn exited(&self, _: u64, _: String, _: String) {}
3102 }
3103
3104 struct Rig {
3105 reader: Reader,
3106 frames: mpsc::Receiver<Vec<u8>>,
3107 }
3108
3109 fn new_rig(events: Arc<dyn HostEvents>) -> Rig {
3110 let (outbound, frames) = mpsc::channel(OUTBOUND_QUEUE);
3111 Rig {
3112 reader: Reader {
3113 kill: mpsc::channel(1).0,
3114 pending: Arc::default(),
3115 inbound: Arc::default(),
3116 outbound,
3117 events,
3118 handshake: Arc::default(),
3119 },
3120 frames,
3121 }
3122 }
3123
3124 fn owner(plugin: &str) -> codewhale_config::OwnerRef {
3125 codewhale_config::OwnerRef {
3126 plugin_id: plugin.to_string(),
3127 generation: 1,
3128 owner_token: "t".repeat(32),
3129 }
3130 }
3131
3132 fn register_request(plugin: &str) -> HostRequest {
3133 HostRequest::Register(protocol::RegisterParams {
3134 scope: None,
3135 owner: owner(plugin),
3136 kind: protocol::RegisterKind::Tool,
3137 spec: protocol::RegisterSpecWire {
3138 name: "t".to_string(),
3139 description: "d".to_string(),
3140 input_schema: Some(serde_json::Map::new()),
3141 argument_hint: None,
3142 },
3143 })
3144 }
3145
3146 fn request(rig: &Rig, id: u64, plugin: &str) -> Result<(), String> {
3147 rig.reader.handle(HostMessage::Request {
3148 id,
3149 request: Box::new(register_request(plugin)),
3150 })
3151 }
3152
3153 fn cancel(rig: &Rig, id: u64) {
3154 rig.reader
3155 .handle(HostMessage::Notification(HostNotification::Cancel(
3156 protocol::CancelParams { id },
3157 )))
3158 .unwrap();
3159 }
3160
3161 /// The next frame the core wrote to the host, decoded.
3162 async fn next_frame(rig: &mut Rig) -> Value {
3163 let frame = tokio::time::timeout(Duration::from_secs(5), rig.frames.recv())
3164 .await
3165 .expect("a frame within 5 s")
3166 .expect("the channel is open");
3167 serde_json::from_slice(&frame[protocol::HEADER_LEN..]).expect("a JSON frame")
3168 }
3169
3170 /// Nothing is written to the host for `ms`.
3171 async fn no_frame(rig: &mut Rig, ms: u64) {
3172 let frame = tokio::time::timeout(Duration::from_millis(ms), rig.frames.recv()).await;
3173 assert!(frame.is_err(), "unexpected frame: {frame:?}");
3174 }
3175
3176 async fn until(what: &str, mut done: impl FnMut() -> bool) {
3177 for _ in 0..200 {
3178 if done() {
3179 return;
3180 }
3181 tokio::time::sleep(Duration::from_millis(10)).await;
3182 }
3183 panic!("timed out waiting for {what}");
3184 }
3185
3186 #[tokio::test]
3187 async fn registry_requests_are_answered_through_the_generic_handler_as_before() {
3188 let mut rig = new_rig(Arc::new(Plain));
3189 request(&rig, 5, "p").unwrap();
3190 assert_eq!(
3191 next_frame(&mut rig).await,
3192 json!({"jsonrpc": "2.0", "id": 5, "result": {"handle": 9}})
3193 );
3194 rig.reader
3195 .handle(HostMessage::Request {
3196 id: 6,
3197 request: Box::new(HostRequest::Unregister(protocol::UnregisterParams {
3198 owner: owner("p"),
3199 handle: 9,
3200 })),
3201 })
3202 .unwrap();
3203 assert_eq!(
3204 next_frame(&mut rig).await,
3205 json!({"jsonrpc": "2.0", "id": 6, "result": {}})
3206 );
3207 until("the table to empty", || rig.reader.inbound.in_flight() == 0).await;
3208 }
3209
3210 #[tokio::test]
3211 async fn a_host_cancel_cancels_the_task_and_the_answer_is_dropped() {
3212 // A handler that stops when cancelled answers nothing.
3213 let stub = Stub::new(Behaviour::WaitsUnlessCancelled);
3214 let mut rig = new_rig(stub.clone());
3215 request(&rig, 1, "p").unwrap();
3216 until("the handler to start", || {
3217 stub.started.load(Ordering::SeqCst) == 1
3218 })
3219 .await;
3220 assert_eq!(rig.reader.inbound.in_flight(), 1);
3221 cancel(&rig, 1);
3222 until("the handler to see the cancel", || {
3223 stub.saw_cancel.load(Ordering::SeqCst)
3224 })
3225 .await;
3226 no_frame(&mut rig, 150).await;
3227 until("the table to empty", || rig.reader.inbound.in_flight() == 0).await;
3228 // A cancel for an id that is not in flight (answered, or never sent) is ignored.
3229 cancel(&rig, 1);
3230 cancel(&rig, 4242);
3231
3232 // A handler that ignores the cancel and finishes later: its late answer is dropped.
3233 let stub = Stub::new(Behaviour::IgnoresCancel);
3234 let mut rig = new_rig(stub.clone());
3235 request(&rig, 2, "p").unwrap();
3236 until("the handler to start", || {
3237 stub.started.load(Ordering::SeqCst) == 1
3238 })
3239 .await;
3240 cancel(&rig, 2);
3241 stub.release.notify_one();
3242 no_frame(&mut rig, 150).await;
3243 until("the table to empty", || rig.reader.inbound.in_flight() == 0).await;
3244
3245 // One that never finishes is abandoned CANCEL_GRACE after the cancel,
3246 // and frees its slot.
3247 let mut rig = new_rig(Stub::new(Behaviour::Hangs));
3248 request(&rig, 3, "p").unwrap();
3249 cancel(&rig, 3);
3250 assert_eq!(
3251 rig.reader.inbound.in_flight(),
3252 1,
3253 "held until the grace ends"
3254 );
3255 until("the abandoned request to leave the table", || {
3256 rig.reader.inbound.in_flight() == 0
3257 })
3258 .await;
3259 no_frame(&mut rig, 100).await;
3260 }
3261
3262 #[tokio::test]
3263 async fn revoking_an_owner_answers_its_requests_cancelled_and_leaves_others_alone() {
3264 let stub = Stub::new(Behaviour::WaitsUnlessCancelled);
3265 let mut rig = new_rig(stub.clone());
3266 request(&rig, 1, "a").unwrap();
3267 request(&rig, 2, "b").unwrap();
3268 until("both handlers to start", || {
3269 stub.started.load(Ordering::SeqCst) == 2
3270 })
3271 .await;
3272 rig.reader.inbound.cancel_owner("a");
3273 // The revoked owner's host is told (its own `$/cancel` never came).
3274 let frame = next_frame(&mut rig).await;
3275 assert_eq!(frame["id"], 1);
3276 assert_eq!(frame["error"]["code"], error_code::CANCELLED);
3277 assert_eq!(frame["error"]["message"], "plugin was revoked");
3278 // The other owner's request is untouched and answers when released.
3279 assert_eq!(rig.reader.inbound.in_flight(), 1);
3280 stub.release.notify_one();
3281 assert_eq!(
3282 next_frame(&mut rig).await,
3283 json!({"jsonrpc": "2.0", "id": 2, "result": {"answered": 2}})
3284 );
3285 }
3286
3287 #[tokio::test]
3288 async fn a_host_exit_cancels_every_request_answers_none_and_admits_no_more() {
3289 let stub = Stub::new(Behaviour::WaitsUnlessCancelled);
3290 let mut rig = new_rig(stub.clone());
3291 request(&rig, 1, "a").unwrap();
3292 request(&rig, 2, "b").unwrap();
3293 until("both handlers to start", || {
3294 stub.started.load(Ordering::SeqCst) == 2
3295 })
3296 .await;
3297 rig.reader.inbound.cancel_all();
3298 no_frame(&mut rig, 150).await;
3299 until("the table to empty", || rig.reader.inbound.in_flight() == 0).await;
3300 assert!(
3301 request(&rig, 3, "a")
3302 .unwrap_err()
3303 .contains("after the host exited")
3304 );
3305 }
3306
3307 #[tokio::test]
3308 async fn host_requests_are_capped_and_an_id_cannot_be_reused_in_flight() {
3309 let rig = new_rig(Stub::new(Behaviour::Hangs));
3310 for id in 1..=protocol::MAX_INFLIGHT as u64 {
3311 request(&rig, id, "p").unwrap_or_else(|reason| panic!("request {id}: {reason}"));
3312 }
3313 assert_eq!(rig.reader.inbound.in_flight(), protocol::MAX_INFLIGHT);
3314 let over = request(&rig, 9999, "p").unwrap_err();
3315 assert!(
3316 over.contains("more than 256 host requests in flight"),
3317 "{over}"
3318 );
3319 let reused = request(&rig, 1, "p").unwrap_err();
3320 assert!(reused.contains("already in flight"), "{reused}");
3321 // Both are protocol violations (the reader ends the host); neither
3322 // disturbed what was admitted.
3323 assert_eq!(rig.reader.inbound.in_flight(), protocol::MAX_INFLIGHT);
3324 rig.reader.inbound.cancel_all();
3325 }
3326 }
3327
3327 lines RUST