返回 CodeWhale
command.rs
根目录 / crates / engine / src / extension_host / command.rs
1 //! Extension slash commands: owned registrations in the user command registry.
2 //!
3 //! A command mirrors a tool. The host proposes it with `registry/register`
4 //! (`kind = "command"`); [`super::registry::OwnerRegistry`] admits or refuses
5 //! it under the same owner/generation/handle rules; the admitted commands of
6 //! the owners an engine's workspace desires are loaded into the existing user
7 //! command registry (`commands::user_registry`, at the lowest
8 //! precedence, so a built-in or a markdown command always wins the spelling);
9 //! and a user invocation becomes `command/run` to the host. Revocation,
10 //! deactivation, crash and generation change remove the registrations the
11 //! same way they remove tools, and each change bumps [`epoch`] so the user
12 //! registry reloads.
13 //!
14 //! What a command can return, chosen from what the user-command machinery
15 //! already does: text shown to the user and/or a prompt submitted through the
16 //! normal turn path. The terminal uses a `System` transcript cell and
17 //! `AppAction::SendMessage`; the native Runtime API persists a command receipt
18 //! and admits generated prompts with Runtime provenance.
19 //! The host never calls the model or a tool itself: anything the model does
20 //! after a `submit` goes through the normal turn, tool approval included.
21 //! Invoking a command is the user's own action, so it needs no approval of
22 //! its own; it still re-checks that the owner is live, that its reviewed
23 //! receipt is current, and that the host is running before anything is sent.
24 //!
25 //! **The built-in command table is a port.** This module is runtime-side and
26 //! may not reach into `commands`, so registration asks
27 //! `command_catalog::CommandCatalog` whether a built-in command answers to a name. The
28 //! host command table implements it and the
29 //! composition root installs it once at startup (`command_catalog::install`).
30 //! With none installed a command registration is refused, never accepted
31 //! unchecked.
32 //!
33 //! Known limitations:
34 //! * The terminal event loop awaits the command (like `/balance`), bounded by
35 //! `SupervisionOptions::command_run_deadline` (30 s) and then cancelled with
36 //! `$/cancel`. A terminal keypress does not cancel it earlier; the native
37 //! Runtime command endpoint supports explicit cancellation.
38 //! * A clash with a user, workspace or manifest (markdown) command is not a
39 //! registration-time refusal, because only the user registry knows the
40 //! workspace: the markdown command wins and the extension command is left
41 //! out with a load error.
42 //! * The handler gets no mutable agent or session handle, and no attachments. It is
43 //! told the workspace the command was loaded for (`ExtensionCommandRef`) and
44 //! its plugin's data directory, plus the invoking session id when known,
45 //! all read-only strings. User commands have no Engine turn or agent identity.
46 //! * A command's result text is bounded and stripped of terminal escapes; a
47 //! prompt over [`MAX_PROMPT_BYTES`] is refused, never truncated.
48
49 use std::sync::Arc;
50 use std::sync::atomic::{AtomicU64, Ordering};
51
52 use serde_json::Value;
53
54 use super::ManagerShared;
55 use super::protocol::{CommandResultWire, CommandRunParams, CoreRequest};
56 use super::registry::CommandRegistration;
57 use super::supervisor::HostCallError;
58 use codewhale_config::PluginAuthority;
59
60 /// How long the user waits for one command before it is cancelled.
61 pub const COMMAND_RUN_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
62 /// Longest result text shown; the rest is cut with a marker.
63 pub const MAX_TEXT_BYTES: usize = 64 * 1024;
64 /// Longest prompt a command may submit. Over this it is refused outright.
65 pub const MAX_PROMPT_BYTES: usize = 128 * 1024;
66
67 static EPOCH: AtomicU64 = AtomicU64::new(0);
68
69 /// Something that may have changed which commands are live: a registration,
70 /// a revocation, an activation, a host exit, an attachment's desired set.
71 /// Spurious bumps are harmless (one extra registry reload).
72 pub fn bump_epoch() {
73 EPOCH.fetch_add(1, Ordering::SeqCst);
74 }
75
76 /// The user registry reloads when this moves.
77 #[must_use]
78 pub fn epoch() -> u64 {
79 EPOCH.load(Ordering::SeqCst)
80 }
81
82 /// A reference to one admitted command, carried by the user-registry entry
83 /// and the dispatch action. It names the exact registration: a handle is
84 /// never reused, so a stale reference can only fail, never run a newer one.
85 /// It holds no owner token.
86 #[derive(Debug, Clone, PartialEq, Eq)]
87 pub struct ExtensionCommandRef {
88 pub handle: u64,
89 pub plugin_id: String,
90 pub generation: u64,
91 /// `extension:<plugin>`, the origin shown beside the command's output.
92 pub origin: String,
93 /// The workspace whose user registry loaded the command: what the handler
94 /// is told as the place the user ran it.
95 pub workspace: std::path::PathBuf,
96 pub selection: Option<codewhale_plugins::composition_scope::SelectionRevision>,
97 pub scope: Option<codewhale_config::EntryRef>,
98 pub content_hash: String,
99 }
100
101 impl ExtensionCommandRef {
102 pub fn receipt(&self) -> Value {
103 serde_json::json!({
104 "plugin_id": self.plugin_id,
105 "content_hash": self.content_hash,
106 "entry": self.scope,
107 "generation": self.generation,
108 "selection": self.selection,
109 "handle": self.handle,
110 "origin": self.origin,
111 "boot_id": crate::session_manager::current_session_boot_id(),
112 })
113 }
114
115 pub fn registration_id(&self, session_id: &str) -> String {
116 codewhale_runtime::hashing::sha256_hex(codewhale_runtime::hashing::canonical_json(
117 &serde_json::json!({
118 "registration": self.receipt(),
119 "workspace": self.workspace,
120 "session_id": session_id,
121 }),
122 ))
123 }
124 }
125
126 pub fn validate_selected_registration(
127 command: &ExtensionCommandRef,
128 session_id: &str,
129 ) -> Result<(), String> {
130 let manager = super::manager();
131 let caller = super::caller_view(&command.workspace, Some(session_id), None)
132 .ok_or_else(|| "Native command caller is no longer available".to_string())?;
133 if command.selection != caller.caller_selection() {
134 return Err("Native command belongs to a different caller; select it again".into());
135 }
136 manager.shared.check_selection(
137 command.selection,
138 Some(caller.as_ref()),
139 &command.plugin_id,
140 &command.content_hash,
141 command.scope.as_ref(),
142 )?;
143 let registry = manager.shared.registry.lock().expect("registry lock");
144 let current = registry
145 .live_command(command.handle, &command.plugin_id, command.generation)
146 .ok_or_else(|| "Native command registration is no longer available".to_string())?;
147 if current.content_hash != command.content_hash || current.scope != command.scope {
148 return Err("Native command registration changed; select it again".into());
149 }
150 Ok(())
151 }
152
153 pub async fn validate_reference(
154 command: &ExtensionCommandRef,
155 session_id: &str,
156 ) -> Result<(), String> {
157 validate_selected_registration(command, session_id)?;
158 super::manager()
159 .shared
160 .live_host_for_command(command)
161 .await?;
162 validate_selected_registration(command, session_id)
163 }
164
165 /// One live command as the user registry loads it.
166 #[derive(Debug, Clone)]
167 pub struct ExtensionCommandEntry {
168 pub registration: CommandRegistration,
169 /// The owner's reviewed authority, so the user registry hides the command
170 /// the moment the plugin is disabled or loses trust.
171 pub authority: PluginAuthority,
172 /// The workspace this entry was loaded for.
173 pub workspace: std::path::PathBuf,
174 pub selection: Option<codewhale_plugins::composition_scope::SelectionRevision>,
175 }
176
177 impl ExtensionCommandEntry {
178 #[must_use]
179 pub fn reference(&self) -> ExtensionCommandRef {
180 ExtensionCommandRef {
181 handle: self.registration.handle,
182 plugin_id: self.registration.owner.plugin_id.clone(),
183 generation: self.registration.owner.generation,
184 origin: format!("extension:{}", self.registration.plugin_name),
185 workspace: self.workspace.clone(),
186 selection: self.selection,
187 scope: self.registration.scope.clone(),
188 content_hash: self.registration.content_hash.clone(),
189 }
190 }
191 }
192
193 /// What a command asked the core to do with its answer.
194 #[derive(Debug, Clone, PartialEq, Eq)]
195 pub enum CommandOutcome {
196 /// Show `text` (possibly empty) to the user.
197 Show { text: String },
198 /// Submit `prompt` through the invoking client's normal turn path; show `note` beside it.
199 Submit {
200 prompt: String,
201 note: Option<String>,
202 },
203 }
204
205 const TRUNCATED_SUFFIX: &str = "\n… (output truncated)";
206
207 fn strip_escapes_bounded(text: &str, max_bytes: usize, reserve_extra: usize) -> (String, bool) {
208 let extra = if text.len() > max_bytes {
209 reserve_extra
210 } else {
211 0
212 };
213 let mut clean = String::with_capacity(text.len().min(max_bytes).saturating_add(extra));
214 let mut truncated = false;
215 codewhale_sanitize::sanitize::visit_ansi_text(text, |chunk| {
216 if truncated {
217 return;
218 }
219 let remaining = max_bytes.saturating_sub(clean.len());
220 if chunk.len() <= remaining {
221 clean.push_str(chunk);
222 } else {
223 let mut end = remaining;
224 while !chunk.is_char_boundary(end) {
225 end -= 1;
226 }
227 clean.push_str(&chunk[..end]);
228 truncated = true;
229 }
230 });
231 (clean, truncated)
232 }
233
234 /// Strip terminal escapes and bound the text. A command's output is
235 /// plugin-controlled and goes straight into the transcript.
236 fn display_text(text: &str) -> String {
237 let (mut clean, truncated) =
238 strip_escapes_bounded(text, MAX_TEXT_BYTES, TRUNCATED_SUFFIX.len());
239 if truncated {
240 clean.push_str(TRUNCATED_SUFFIX);
241 }
242 clean
243 }
244
245 fn decode_command_result(mut value: Value) -> Result<CommandOutcome, String> {
246 let mut pretruncated_text = None;
247 if let Some(obj) = value.as_object_mut() {
248 if obj.get("kind").and_then(Value::as_str) == Some("submit")
249 && let Some(prompt) = obj.get("prompt").and_then(Value::as_str)
250 && prompt.len() > MAX_PROMPT_BYTES
251 {
252 return Err(format!(
253 "returned a prompt of {} bytes, over the {MAX_PROMPT_BYTES}-byte limit; it was not submitted",
254 prompt.len()
255 ));
256 }
257 if let Some(Value::String(raw_text)) = obj.get_mut("text")
258 && raw_text.len() > MAX_TEXT_BYTES
259 {
260 pretruncated_text = Some(display_text(raw_text));
261 raw_text.clear();
262 raw_text.shrink_to_fit();
263 }
264 }
265 let wire: CommandResultWire = serde_json::from_value(value)
266 .map_err(|error| format!("returned a malformed result: {error}"))?;
267 match wire {
268 CommandResultWire::Success { text } => Ok(CommandOutcome::Show {
269 text: pretruncated_text
270 .or_else(|| text.as_deref().map(display_text))
271 .unwrap_or_default(),
272 }),
273 CommandResultWire::Error { text } => {
274 Err(pretruncated_text.unwrap_or_else(|| display_text(&text)))
275 }
276 CommandResultWire::Submit { prompt, text } => {
277 let (prompt, exceeded) = strip_escapes_bounded(&prompt, MAX_PROMPT_BYTES, 0);
278 if prompt.trim().is_empty() {
279 return Err("submitted an empty prompt".to_string());
280 }
281 if exceeded {
282 return Err(format!(
283 "returned a prompt over the {MAX_PROMPT_BYTES}-byte limit; it was not submitted"
284 ));
285 }
286 Ok(CommandOutcome::Submit {
287 prompt,
288 note: pretruncated_text
289 .or_else(|| text.as_deref().map(display_text))
290 .filter(|t| !t.is_empty()),
291 })
292 }
293 }
294 }
295
296 /// The phrase shown after `/<name> (extension:<plugin>):` on failure.
297 fn map_call_error(error: HostCallError) -> String {
298 match error {
299 HostCallError::Cancelled(reason) => format!("cancelled: {reason}"),
300 HostCallError::Timeout { after, .. } => {
301 format!("timed out after {}s and was cancelled", after.as_secs())
302 }
303 HostCallError::Exited(reason) => format!("plugin host is down: exited: {reason}"),
304 HostCallError::Busy => "plugin host is busy; try again".to_string(),
305 HostCallError::Rpc { code, message } => {
306 if code == super::protocol::error_code::NOT_AVAILABLE {
307 format!("not available: {message}")
308 } else {
309 format!("failed: {message}")
310 }
311 }
312 }
313 }
314
315 /// Run one command for the user. Errors are the text to show as a failure.
316 pub async fn run(
317 shared: &ManagerShared,
318 command: &ExtensionCommandRef,
319 raw_input: &str,
320 session_id: Option<&str>,
321 ) -> Result<CommandOutcome, String> {
322 let bound = command
323 .selection
324 .and_then(|revision| shared.plugins_for_selection(revision, session_id));
325 let caller = bound.as_ref().map(|(plugins, _)| Arc::clone(plugins));
326 let agent_id = bound.and_then(|(_, agent_id)| agent_id);
327 shared.check_selection(
328 command.selection,
329 caller.as_deref(),
330 &command.plugin_id,
331 &command.content_hash,
332 command.scope.as_ref(),
333 )?;
334 let (host, registration) = shared.live_host_for_command(command).await?;
335 shared.check_selection(
336 command.selection,
337 caller.as_deref(),
338 &command.plugin_id,
339 &command.content_hash,
340 command.scope.as_ref(),
341 )?;
342 let deadline = shared.options.supervision.command_run_deadline;
343 let request = CoreRequest::CommandRun(CommandRunParams {
344 handle: registration.handle,
345 command_id: uuid::Uuid::new_v4().simple().to_string(),
346 raw_input: raw_input.to_string(),
347 deadline_ms: u64::try_from(deadline.as_millis()).unwrap_or(u64::MAX),
348 workspace: command.workspace.to_str().map(str::to_owned),
349 session_id: session_id.filter(|id| !id.is_empty()).map(str::to_owned),
350 agent_id,
351 origin_turn_id: None,
352 });
353 let value: Value = host
354 .call(request, Some(registration.owner.plugin_id.clone()))
355 .await
356 .map_err(map_call_error)?;
357 shared.check_selection(
358 command.selection,
359 caller.as_deref(),
360 &command.plugin_id,
361 &command.content_hash,
362 command.scope.as_ref(),
363 )?;
364 shared.live_host_for_command(command).await?;
365 shared.check_selection(
366 command.selection,
367 caller.as_deref(),
368 &command.plugin_id,
369 &command.content_hash,
370 command.scope.as_ref(),
371 )?;
372 decode_command_result(value)
373 }
374
375 #[cfg(test)]
376 mod tests {
377 use super::*;
378 use serde_json::json;
379
380 #[test]
381 fn oversized_submit_prompt_is_rejected_before_deserialization() {
382 let payload = json!({
383 "kind": "submit",
384 "prompt": "p".repeat(MAX_PROMPT_BYTES + 1),
385 "text": 12345,
386 });
387 let err = decode_command_result(payload).unwrap_err();
388 assert!(
389 err.contains("not submitted"),
390 "expected pre-deserialize prompt cap error, got: {err}"
391 );
392 }
393
394 #[test]
395 fn oversized_display_text_bounds_allocation_capacity() {
396 let huge = "x".repeat(MAX_TEXT_BYTES * 8);
397 let out = display_text(&huge);
398 assert!(out.ends_with(TRUNCATED_SUFFIX));
399 assert!(out.len() <= MAX_TEXT_BYTES + TRUNCATED_SUFFIX.len());
400 assert!(
401 out.capacity() <= MAX_TEXT_BYTES + 64,
402 "display_text allocated {} bytes for a {} byte cap",
403 out.capacity(),
404 MAX_TEXT_BYTES
405 );
406
407 let decoded = decode_command_result(json!({
408 "kind": "success",
409 "text": huge,
410 }))
411 .unwrap();
412 match decoded {
413 CommandOutcome::Show { text } => {
414 assert!(text.ends_with(TRUNCATED_SUFFIX));
415 assert!(text.capacity() <= MAX_TEXT_BYTES + 64);
416 }
417 other => panic!("unexpected outcome: {other:?}"),
418 }
419 }
420
421 #[test]
422 fn ansi_heavy_text_within_clean_cap_is_not_truncated() {
423 let ansi = format!("{}ok", "\u{001b}[31m".repeat(MAX_TEXT_BYTES));
424 let out = display_text(&ansi);
425 assert_eq!(out, "ok");
426 assert!(out.capacity() <= MAX_TEXT_BYTES + 64);
427 }
428 }
429
429 lines RUST