返回 CodeWhale
composition_review.rs
根目录 / crates / engine / src / extension_host / composition_review.rs
1 //! Trusted, nonexecuting DSH preparation. Runs only the embedded reviewer,
2 //! never a package-selected script. Called from the installer's blocking worker.
3 use std::sync::Arc;
4 use std::time::Duration;
5
6 use serde_json::Value;
7 use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
8
9 const REVIEW: &[u8] = include_bytes!("../../extension-host/dist/dsh-composition-review.mjs");
10 const MAX_INPUT: usize = 8 * 1024 * 1024;
11 const MAX_OUTPUT: usize = 8 * 1024 * 1024;
12 const MAX_STDERR: usize = 16 * 1024;
13 const DEADLINE: Duration = Duration::from_secs(5);
14
15 /// Synchronous installer seam; the caller must run outside a Tokio worker.
16 /// No source value or reviewer stderr becomes a public diagnostic.
17 pub fn review(input: &Value) -> Result<Value, String> {
18 let input = serde_json::to_vec(input).map_err(|_| "invalid composition request")?;
19 if input.len() > MAX_INPUT {
20 return Err("composition review request exceeds 8 MiB".into());
21 }
22 let manager = super::manager();
23 let options = &manager.shared.options;
24 let pin = manager.shared.runtime.lock().expect("runtime lock");
25 let pinned = pin.pinned.clone();
26 let bun_failed = pin.bun_failed;
27 drop(pin);
28 let root = super::host_root(options)?;
29 let review_digest = super::hex(sha2::Sha256::digest(REVIEW));
30 let dir = root
31 .join("extension-host")
32 .join(format!("review-{review_digest}"));
33 let bundle = super::materialize_file(&dir, "dsh-composition-review.mjs", REVIEW)?;
34 super::materialize_file(&dir, super::NOTICES_FILE_NAME, super::NOTICES)?;
35 let runtime = match pinned {
36 Some((runtime, _)) => runtime,
37 None => {
38 let choice = if bun_failed {
39 codewhale_config::extension_host::ExtensionHostRuntime::Node
40 } else {
41 options.runtime
42 };
43 codewhale_dependencies::resolve_extension_host_runtime(
44 choice,
45 options.node_override.as_deref(),
46 options.bun_override.as_deref(),
47 crate::extension_host::bundle_sha256(),
48 )
49 .selected
50 .ok_or("composition reviewer runtime is unavailable")?
51 }
52 };
53 let launch = super::supervisor::plan_launch(
54 &super::tier::HostCohort::reviewed(),
55 &runtime,
56 &bundle,
57 &root,
58 options.supervision.memory_cap,
59 &[],
60 )?;
61 // A bounded process runner, not another Engine or session runtime.
62 std::thread::Builder::new()
63 .name("dsh-composition-review".to_string())
64 .spawn(move || {
65 tokio::runtime::Builder::new_current_thread()
66 .enable_all()
67 .build()
68 .map_err(|_| "composition review worker is unavailable".to_string())?
69 .block_on(run(launch, input))
70 })
71 .map_err(|_| "composition review worker is unavailable".to_string())?
72 .join()
73 .map_err(|_| "composition review worker failed".to_string())?
74 }
75
76 async fn bounded_read(pipe: impl AsyncRead + Unpin, limit: usize) -> Result<Vec<u8>, String> {
77 let mut bytes = Vec::new();
78 pipe.take((limit + 1) as u64)
79 .read_to_end(&mut bytes)
80 .await
81 .map_err(|_| "composition reviewer pipe failed")?;
82 if bytes.len() > limit {
83 return Err("composition reviewer output exceeded its bound".into());
84 }
85 Ok(bytes)
86 }
87
88 async fn run(launch: super::supervisor::HostLaunch, input: Vec<u8>) -> Result<Value, String> {
89 use std::process::Stdio;
90 let mut command = tokio::process::Command::new(&launch.program);
91 codewhale_util::utils::suppress_tokio_console_window(&mut command);
92 command
93 .args(&launch.args)
94 .current_dir(&launch.cwd)
95 .env_clear()
96 .stdin(Stdio::piped())
97 .stdout(Stdio::piped())
98 .stderr(Stdio::piped())
99 .kill_on_drop(true);
100 let overrides = launch
101 .sandbox_env
102 .iter()
103 .chain(&launch.runtime_env)
104 .map(|(key, value)| (key.as_str(), value.as_str()));
105 for (key, value) in
106 codewhale_runtime::child_env::sanitized_plugin_mcp_env_from(std::env::vars_os(), overrides)
107 {
108 command.env(key, value);
109 }
110 #[cfg(unix)]
111 command.process_group(0);
112 super::supervisor::limit_child_memory(&mut command, launch.memory_cap);
113 let mut child = command
114 .spawn()
115 .map_err(|_| "composition reviewer could not start")?;
116 let tree = Arc::new(
117 codewhale_runtime::process_tree::ProcessTree::attach_tokio(&child)
118 .map_err(|_| "composition reviewer containment failed")?,
119 );
120 #[cfg(windows)]
121 tree.limit_process_memory(launch.memory_cap)
122 .map_err(|_| "composition reviewer memory cap failed")?;
123 let pid = child
124 .id()
125 .ok_or("composition reviewer pid is unavailable")?;
126 let mut stdin = child
127 .stdin
128 .take()
129 .ok_or("composition reviewer stdin is unavailable")?;
130 let stdout = child
131 .stdout
132 .take()
133 .ok_or("composition reviewer stdout is unavailable")?;
134 let stderr = child
135 .stderr
136 .take()
137 .ok_or("composition reviewer stderr is unavailable")?;
138 let feed = async move {
139 stdin
140 .write_all(&input)
141 .await
142 .map_err(|_| "composition reviewer input failed".to_string())?;
143 stdin
144 .shutdown()
145 .await
146 .map_err(|_| "composition reviewer input failed".to_string())?;
147 // The reviewer parses a finite document. Closing the pipe is its
148 // end-of-input signal; shutdown alone leaves this handle alive.
149 drop(stdin);
150 Ok::<(), String>(())
151 };
152 let work = async {
153 let (status, output, _stderr, ()) = tokio::try_join!(
154 async {
155 child
156 .wait()
157 .await
158 .map_err(|_| "composition reviewer wait failed".to_string())
159 },
160 bounded_read(stdout, MAX_OUTPUT),
161 bounded_read(stderr, MAX_STDERR),
162 feed,
163 )?;
164 if !status.success() {
165 return Err("composition reviewer refused preparation".into());
166 }
167 serde_json::from_slice(&output)
168 .map_err(|_| "composition reviewer returned invalid JSON".into())
169 };
170 let answer = tokio::select! {
171 answer = tokio::time::timeout(DEADLINE,work) => answer.map_err(|_| "composition reviewer deadline elapsed")?,
172 failure = monitor_memory(pid, launch.memory_cap) => { failure?; unreachable!() },
173 };
174 // Always reap descendants, including any that kept a pipe open; source
175 // modules were never imported. Drop/timeout kills the same guarded tree.
176 let _ = tree.kill();
177 answer
178 }
179
180 use sha2::Digest;
181
182 async fn monitor_memory(pid: u32, cap: u64) -> Result<(), String> {
183 let _ = (pid, cap);
184 loop {
185 tokio::time::sleep(Duration::from_millis(25)).await;
186 #[cfg(target_os = "macos")]
187 if super::supervisor::resident_bytes(pid).is_some_and(|bytes| bytes > cap) {
188 return Err("composition reviewer exceeded its sampled memory cap".into());
189 }
190 }
191 }
192
192 lines RUST