返回 CodeWhale
headless.rs
根目录 / crates / tui / src / commands / groups / plugins / headless.rs
1 use std::io::{self, BufRead, IsTerminal, Write};
2 use std::path::{Path, PathBuf};
3 use std::sync::Arc;
4
5 use anyhow::{Result, anyhow, bail};
6 use codewhale_command_contract::facets::CommandPresentationContext;
7 use codewhale_localization::{Locale, MessageId, tr};
8 use codewhale_plugins::PluginRegistry;
9 use codewhale_plugins::host_services::{
10 AgentPosture, PersonVia, PluginApprover, ReviewApproval, approver_label,
11 };
12 use codewhale_plugins::types::LoadedPlugin;
13
14 use super::render::{ReviewTextContext, escape_review_text, render_bundle_detail};
15 use crate::commands::contract::{apply_named_replacements, portable_detail, resolve_message_id};
16
17 const AGENT_MARK: &str = "CODEWHALE_AGENT_PROJECT";
18 const AGENT_POSTURE: &str = "CODEWHALE_AGENT_POSTURE";
19 const AGENT_THREAD_ID: &str = "CODEWHALE_AGENT_THREAD_ID";
20 const AGENT_TURN_ID: &str = "CODEWHALE_AGENT_TURN_ID";
21 const AGENT_TOOL_CALL_ID: &str = "CODEWHALE_AGENT_TOOL_CALL_ID";
22
23 #[derive(Debug, Clone, Default, PartialEq, Eq)]
24 pub(crate) struct AgentRunProvenance {
25 pub(crate) posture: Option<AgentPosture>,
26 pub(crate) thread_id: Option<String>,
27 pub(crate) turn_id: Option<String>,
28 pub(crate) tool_call_id: Option<String>,
29 }
30
31 fn non_empty_env(name: &str) -> Option<String> {
32 std::env::var(name)
33 .ok()
34 .map(|value| value.trim().to_string())
35 .filter(|value| !value.is_empty())
36 }
37
38 pub(crate) fn agent_project() -> Option<PathBuf> {
39 std::env::var_os(AGENT_MARK)
40 .filter(|value| !value.is_empty())
41 .map(PathBuf::from)
42 }
43
44 pub(crate) trait Console {
45 fn interactive(&self) -> bool;
46 fn agent_marked(&self) -> bool;
47 fn agent_provenance(&self) -> Result<AgentRunProvenance> {
48 Ok(AgentRunProvenance::default())
49 }
50 fn print(&mut self, text: &str);
51 fn confirm(&mut self, prompt: &str) -> bool;
52 }
53
54 pub(crate) struct ProcessConsole;
55
56 impl Console for ProcessConsole {
57 fn interactive(&self) -> bool {
58 io::stdin().is_terminal() && io::stdout().is_terminal() && io::stderr().is_terminal()
59 }
60
61 fn agent_marked(&self) -> bool {
62 agent_project().is_some()
63 }
64
65 fn agent_provenance(&self) -> Result<AgentRunProvenance> {
66 let posture = match non_empty_env(AGENT_POSTURE).as_deref() {
67 None | Some("command_line") => Some(AgentPosture::CommandLine),
68 Some("auto_review") => Some(AgentPosture::AutoReview),
69 Some(other) => bail!("Unsupported {AGENT_POSTURE} value `{other}`"),
70 };
71 Ok(AgentRunProvenance {
72 posture,
73 thread_id: non_empty_env(AGENT_THREAD_ID),
74 turn_id: non_empty_env(AGENT_TURN_ID),
75 tool_call_id: non_empty_env(AGENT_TOOL_CALL_ID),
76 })
77 }
78
79 fn print(&mut self, text: &str) {
80 println!("{text}");
81 }
82
83 fn confirm(&mut self, prompt: &str) -> bool {
84 let mut stderr = io::stderr();
85 let _ = write!(stderr, "{prompt} [y/N] ");
86 let _ = stderr.flush();
87 let mut answer = String::new();
88 io::stdin().lock().read_line(&mut answer).is_ok()
89 && matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
90 }
91 }
92
93 struct Presentation(Locale);
94
95 impl CommandPresentationContext for Presentation {
96 fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> {
97 let id = resolve_message_id(key).ok_or("unknown translation key")?;
98 apply_named_replacements(&tr(self.0, id), replacements)
99 .ok_or_else(|| "invalid translation replacement contract".to_string())
100 }
101
102 fn language_name(&self) -> &'static str {
103 self.0.translation_target_name()
104 }
105 }
106
107 fn text(value: &str) -> String {
108 escape_review_text(value, ReviewTextContext::Plain)
109 }
110
111 fn shell_word(value: &str) -> String {
112 if !value.is_empty()
113 && value
114 .chars()
115 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-' | '/' | ':'))
116 {
117 value.to_string()
118 } else {
119 format!("'{}'", value.replace('\'', "'\\''"))
120 }
121 }
122
123 fn find<'a>(registry: &'a PluginRegistry, locale: Locale, name: &str) -> Result<&'a LoadedPlugin> {
124 registry.get(name).ok_or_else(|| {
125 anyhow!(tr(locale, MessageId::CmdPluginBundleNotFound).replace("{name}", &text(name)))
126 })
127 }
128
129 fn agent_approver(registry: &PluginRegistry, console: &dyn Console) -> Result<PluginApprover> {
130 if !console.agent_marked() {
131 return Ok(PluginApprover::CommandLine);
132 }
133 if let Some(env_path) = agent_project() {
134 let norm_env = codewhale_config::normalize_project_workspace(&env_path)?;
135 let norm_reg = codewhale_config::normalize_project_workspace(registry.workspace())?;
136 if norm_env != norm_reg {
137 bail!(
138 "Agent environment workspace `{}` does not match current workspace `{}`",
139 env_path.display(),
140 registry.workspace().display()
141 );
142 }
143 }
144 let provenance = console.agent_provenance()?;
145 Ok(match provenance.posture {
146 None | Some(AgentPosture::CommandLine) => {
147 PluginApprover::command_line(Some(registry.workspace()))
148 }
149 Some(AgentPosture::AutoReview) => PluginApprover::auto_review(
150 registry.workspace(),
151 provenance.thread_id,
152 provenance.turn_id,
153 provenance.tool_call_id,
154 ),
155 Some(AgentPosture::FullAccess) => bail!(
156 "Unsupported {AGENT_POSTURE} value for a shell command: `full_access` is reserved for direct agent tool calls"
157 ),
158 })
159 }
160
161 fn host_service_lines(
162 registry: &PluginRegistry,
163 plugin: &LoadedPlugin,
164 approver: &PluginApprover,
165 ) -> Vec<String> {
166 let mut lines = registry
167 .host_service_review_for(plugin.name(), approver)
168 .map(|review| review.text())
169 .unwrap_or_default();
170 if !lines.is_empty() && approver.agent_workspace().is_none() {
171 lines.push("A trust from the command line grants none of these host services.".to_string());
172 }
173 lines
174 }
175
176 fn review_text(
177 registry: &PluginRegistry,
178 plugin: &LoadedPlugin,
179 locale: Locale,
180 approver: &PluginApprover,
181 ) -> String {
182 let mut output = render_bundle_detail(
183 &mut Presentation(locale),
184 &portable_detail(plugin, Some(registry), locale),
185 true,
186 ReviewTextContext::Plain,
187 );
188 if !output.ends_with('\n') {
189 output.push('\n');
190 }
191 for line in host_service_lines(registry, plugin, approver) {
192 output.push_str(&text(&line));
193 output.push('\n');
194 }
195 output.push_str(&format!("Bundle review token: {}", plugin.review_token()));
196 output
197 }
198
199 fn trust_command(plugin: &LoadedPlugin) -> String {
200 format!(
201 "codewhale plugins trust {} --review-token {} --yes",
202 shell_word(&text(plugin.name())),
203 plugin.review_token()
204 )
205 }
206
207 fn review_json(
208 registry: &PluginRegistry,
209 plugin: &LoadedPlugin,
210 locale: Locale,
211 approver: &PluginApprover,
212 ) -> serde_json::Value {
213 let mut record = crate::plugin_cli_record(plugin);
214 if let Some(object) = record.as_object_mut() {
215 object.insert("action".to_string(), "review".into());
216 object.insert("trusted_by_this_command".to_string(), false.into());
217 object.insert(
218 "bundle_review_token".to_string(),
219 plugin.review_token().into(),
220 );
221 object.insert(
222 "review".to_string(),
223 review_text(registry, plugin, locale, approver).into(),
224 );
225 }
226 record
227 }
228
229 fn trust_as(
230 registry: &mut Arc<PluginRegistry>,
231 locale: Locale,
232 name: &str,
233 approver: PluginApprover,
234 ) -> Result<()> {
235 let host_services = if let PluginApprover::Agent(ref agent) = approver {
236 if let Some(env_project) = agent_project() {
237 let norm_env = codewhale_config::normalize_project_workspace(&env_project)?;
238 let norm_agent =
239 codewhale_config::normalize_project_workspace(Path::new(&agent.workspace))?;
240 if norm_env != norm_agent {
241 bail!(
242 "Agent approval workspace `{}` does not match environment `{}`",
243 agent.workspace,
244 env_project.display()
245 );
246 }
247 }
248 installed_by_the_agent(find(registry, locale, name)?, registry.workspace())?;
249 registry
250 .host_service_review_for(name, &approver)
251 .map(|review| review.token)
252 } else {
253 None
254 };
255 Arc::make_mut(registry)
256 .trust_reviewed(
257 name,
258 ReviewApproval {
259 approved_by: approver,
260 host_services,
261 },
262 )
263 .map_err(|error| failed(locale, &error))
264 }
265
266 fn installed_by_the_agent(plugin: &LoadedPlugin, project: &Path) -> Result<()> {
267 if !codewhale_plugins::install::installed_by_the_agent(&plugin.canonical_root, project) {
268 bail!(
269 "The agent may approve only a plugin it installed with `codewhale install` from a folder inside its project, and `{}` was not installed that way. Nothing was changed; ask the person to review it.",
270 text(plugin.name())
271 );
272 }
273 Ok(())
274 }
275
276 fn failed(locale: Locale, error: &str) -> anyhow::Error {
277 anyhow!(tr(locale, MessageId::CmdPluginActionFailed).replace("{error}", &text(error)))
278 }
279
280 fn report(
281 registry: &PluginRegistry,
282 locale: Locale,
283 name: &str,
284 action: &str,
285 json: bool,
286 console: &mut dyn Console,
287 ) -> Result<()> {
288 let plugin = find(registry, locale, name)?;
289 let inactive = plugin
290 .inventory
291 .unsupported_labels()
292 .into_iter()
293 .map(str::to_string)
294 .collect::<Vec<_>>();
295 if json {
296 console.print(&serde_json::to_string_pretty(&serde_json::json!({
297 "name": text(plugin.name()),
298 "action": action,
299 "state": plugin.state_label(),
300 "trust": plugin.trust_status.as_str(),
301 "enabled": plugin.enabled,
302 "active": plugin.active(),
303 "approved_by": plugin.approved_by,
304 "enabled_by": plugin.enabled_by,
305 "host_services": plugin.host_services,
306 "content_hash": plugin.content_hash,
307 "capability_hash": plugin.capability_hash,
308 "inactive_components": inactive,
309 }))?);
310 } else {
311 console.print(
312 &tr(locale, MessageId::CmdPluginBundleMutationSuccess)
313 .replace("{name}", &text(plugin.name()))
314 .replace("{action}", action),
315 );
316 if action == "trusted" {
317 console.print(&format!(
318 "Recorded as {}.",
319 approver_label(plugin.approved_by.as_ref())
320 ));
321 }
322 if action == "enabled" && !inactive.is_empty() {
323 console.print(&format!(
324 "Compatibility: {}. Supported declarative components are active; inactive: {}.",
325 plugin.compatibility().as_str(),
326 inactive.join(", ")
327 ));
328 }
329 }
330 Ok(())
331 }
332
333 fn block_on_mutation<F: std::future::Future>(future: F) -> Result<F::Output> {
334 match tokio::runtime::Handle::try_current() {
335 Ok(handle) => Ok(handle.block_on(future)),
336 Err(_) => Ok(tokio::runtime::Builder::new_current_thread()
337 .enable_all()
338 .build()?
339 .block_on(future)),
340 }
341 }
342
343 fn manifest_version_at(path: &Path) -> Option<String> {
344 let manifest_path = codewhale_plugins::agent_plugin::resolve_manifest_path(path)?;
345 codewhale_plugins::manifest::PluginManifest::validate_from_path(&manifest_path)
346 .ok()
347 .map(|validated| validated.manifest.plugin.version)
348 }
349
350 pub(crate) fn show(
351 registry: &PluginRegistry,
352 locale: Locale,
353 name: &str,
354 json: bool,
355 console: &mut dyn Console,
356 ) -> Result<()> {
357 let approver = agent_approver(registry, console)?;
358 let plugin = find(registry, locale, name)?;
359 if json {
360 console.print(&serde_json::to_string_pretty(&review_json(
361 registry, plugin, locale, &approver,
362 ))?);
363 } else {
364 console.print(&review_text(registry, plugin, locale, &approver));
365 }
366 Ok(())
367 }
368
369 pub(crate) struct TrustRequest {
370 pub name: String,
371 pub review_token: Option<String>,
372 pub yes: bool,
373 pub json: bool,
374 }
375
376 pub(crate) fn trust(
377 registry: &mut Arc<PluginRegistry>,
378 locale: Locale,
379 request: TrustRequest,
380 console: &mut dyn Console,
381 ) -> Result<()> {
382 let TrustRequest {
383 name,
384 review_token,
385 yes,
386 json,
387 } = request;
388 let resolved_agent_approver = agent_approver(registry, console)?;
389 let plugin = find(registry, locale, &name)?;
390 let review_again = format!(
391 "run `codewhale plugins trust {}` and read the new review",
392 shell_word(&text(&name))
393 );
394 let prompted = if resolved_agent_approver.agent_workspace().is_some() {
395 resolved_agent_approver.clone()
396 } else {
397 PluginApprover::person(PersonVia::Terminal)
398 };
399
400 let Some(presented) = review_token else {
401 if yes {
402 bail!(
403 "`--yes` only skips the confirmation prompt. Trust also needs --review-token, the bundle review token that names the exact content to trust; to see it, {review_again}"
404 );
405 }
406 show(registry, locale, &name, json, console)?;
407 if json {
408 return Ok(());
409 }
410 if !console.interactive() {
411 console.print(&format!(
412 "\nNot trusted. The bundle review token ties trust to exactly the content shown above; it does not record that anyone read this review. A trust made with it is recorded as {}. To trust, run:\n {}",
413 approver_label(Some(&resolved_agent_approver)),
414 trust_command(plugin)
415 ));
416 return Ok(());
417 }
418 if !console.confirm("\nTrust this bundle with exactly the capabilities above?") {
419 console.print("Not trusted.");
420 return Ok(());
421 }
422 trust_as(registry, locale, &name, prompted)?;
423 return report(registry, locale, &name, "trusted", json, console);
424 };
425
426 if presented.split('.').next() != Some(plugin.content_hash.as_str()) {
427 bail!(
428 "Plugin bundle `{}` content changed since this bundle review token was issued (current content hash {}); {review_again}",
429 text(&name),
430 plugin.content_hash,
431 );
432 }
433 if presented != plugin.review_token() {
434 bail!(
435 "Bundle review token does not match this bundle's current content and capability set; {review_again}"
436 );
437 }
438 let approver = if yes {
439 resolved_agent_approver
440 } else {
441 if json || !console.interactive() {
442 bail!(
443 "Trust needs confirmation: pass --yes with the bundle review token, or run in a terminal to be shown the review and asked"
444 );
445 }
446 show(registry, locale, &name, false, console)?;
447 if !console.confirm("\nTrust this bundle with exactly the capabilities above?") {
448 console.print("Not trusted.");
449 return Ok(());
450 }
451 prompted
452 };
453
454 trust_as(registry, locale, &name, approver)?;
455 report(registry, locale, &name, "trusted", json, console)
456 }
457
458 pub(crate) fn update(
459 registry: &mut Arc<PluginRegistry>,
460 locale: Locale,
461 name: &str,
462 network: &codewhale_net::network_policy::NetworkPolicy,
463 json: bool,
464 console: &mut dyn Console,
465 ) -> Result<()> {
466 use codewhale_plugins::mutation::{
467 PluginMutationContext, PluginMutationOutcome, PluginMutationRequest, check_network_outcome,
468 execute,
469 };
470 let before = find(registry, locale, name)?.clone();
471 let selector = before.name().to_string();
472 let ctx = PluginMutationContext {
473 network,
474 max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
475 };
476 let receipt = block_on_mutation(execute(
477 PluginMutationRequest::Update { selector },
478 &ctx,
479 Arc::make_mut(registry),
480 ))?
481 .map_err(|error| failed(locale, &format!("{error:#}")))?;
482 check_network_outcome(&receipt.outcome)?;
483 match receipt.outcome {
484 PluginMutationOutcome::Updated => {
485 *registry = registry.rediscover_for_workspace(registry.workspace());
486 let version = registry
487 .get(&receipt.name)
488 .map(|plugin| plugin.manifest.plugin.version.clone())
489 .or_else(|| receipt.path.as_deref().and_then(manifest_version_at))
490 .unwrap_or_default();
491 if json {
492 let mut record = registry
493 .get(&receipt.name)
494 .map(crate::plugin_cli_record)
495 .unwrap_or_else(|| {
496 serde_json::json!({
497 "name": text(&receipt.name),
498 "version": text(&version),
499 "path": receipt.path.as_ref().map(|p| text(&p.to_string_lossy())),
500 "content_hash": receipt.installed_content_hash.or(receipt.content_hash),
501 })
502 });
503 if let Some(object) = record.as_object_mut() {
504 object.insert("action".to_string(), "updated".into());
505 }
506 console.print(&serde_json::to_string_pretty(&record)?);
507 } else {
508 let action = if version.is_empty() {
509 "updated".to_string()
510 } else {
511 format!("updated to {}", text(&version))
512 };
513 console.print(
514 &tr(locale, MessageId::CmdPluginBundleMutationSuccess)
515 .replace("{name}", &text(&receipt.name))
516 .replace("{action}", &action),
517 );
518 }
519 Ok(())
520 }
521 PluginMutationOutcome::NoChange => {
522 if json {
523 let mut record = crate::plugin_cli_record(&before);
524 if let Some(object) = record.as_object_mut() {
525 object.insert("action".to_string(), "already_current".into());
526 }
527 console.print(&serde_json::to_string_pretty(&record)?);
528 } else {
529 console.print(
530 &tr(locale, MessageId::CmdPluginBundleMutationSuccess)
531 .replace("{name}", &text(&receipt.name))
532 .replace("{action}", "already current"),
533 );
534 }
535 Ok(())
536 }
537 _ => bail!("Unexpected plugin update outcome"),
538 }
539 }
540
541 pub(crate) fn uninstall(
542 registry: &mut Arc<PluginRegistry>,
543 locale: Locale,
544 name: &str,
545 yes: bool,
546 json: bool,
547 console: &mut dyn Console,
548 ) -> Result<()> {
549 use codewhale_plugins::mutation::{PluginMutationContext, PluginMutationRequest, execute};
550 use codewhale_plugins::types::PluginScope;
551 let plugin = find(registry, locale, name)?.clone();
552 let plugin_name = plugin.name().to_string();
553 let version = plugin.manifest.plugin.version.clone();
554 if !yes {
555 if json || !console.interactive() {
556 bail!("Uninstall needs confirmation: pass --yes, or run in a terminal to be asked");
557 }
558 let prompt = if version.is_empty() {
559 format!("Remove {}?", text(&plugin_name))
560 } else {
561 format!("Remove {} {}?", text(&plugin_name), text(&version))
562 };
563 if !console.confirm(&prompt) {
564 console.print("Not removed.");
565 return Ok(());
566 }
567 }
568 if plugin.scope == PluginScope::User && plugin.enabled {
569 Arc::make_mut(registry)
570 .disable(&plugin_name)
571 .map_err(|error| failed(locale, &error))?;
572 }
573 let network = codewhale_net::network_policy::NetworkPolicy::default();
574 let ctx = PluginMutationContext {
575 network: &network,
576 max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
577 };
578 let receipt = block_on_mutation(execute(
579 PluginMutationRequest::Uninstall {
580 selector: plugin_name,
581 },
582 &ctx,
583 Arc::make_mut(registry),
584 ))?
585 .map_err(|error| failed(locale, &format!("{error:#}")))?;
586 if json {
587 console.print(&serde_json::to_string_pretty(&serde_json::json!({
588 "name": text(&receipt.name),
589 "version": text(&version),
590 "action": "uninstalled",
591 }))?);
592 } else {
593 console.print(
594 &tr(locale, MessageId::CmdPluginBundleMutationSuccess)
595 .replace("{name}", &text(&receipt.name))
596 .replace("{action}", "uninstalled"),
597 );
598 }
599 Ok(())
600 }
601
602 pub(crate) fn enable(
603 registry: &mut Arc<PluginRegistry>,
604 locale: Locale,
605 name: &str,
606 json: bool,
607 console: &mut dyn Console,
608 ) -> Result<()> {
609 let approver = agent_approver(registry, console)?;
610 let plugin = find(registry, locale, name)?;
611 if !plugin.trusted() {
612 if let Some(error) = registry.state_error() {
613 bail!(
614 "Plugin state could not be read, so the trust of `{}` is unknown and nothing was changed: {}",
615 text(name),
616 text(error)
617 );
618 }
619 bail!(
620 "Plugin bundle `{}` is not trusted (trust: {}), so it cannot be enabled. Review it first with `codewhale plugins trust {}`.",
621 text(name),
622 plugin.trust_status.as_str(),
623 shell_word(&text(name))
624 );
625 }
626 Arc::make_mut(registry)
627 .enable_by(name, approver)
628 .map_err(|error| failed(locale, &error))?;
629 report(registry, locale, name, "enabled", json, console)
630 }
631
632 pub(crate) fn disable(
633 registry: &mut Arc<PluginRegistry>,
634 locale: Locale,
635 name: &str,
636 json: bool,
637 console: &mut dyn Console,
638 ) -> Result<()> {
639 find(registry, locale, name)?;
640 Arc::make_mut(registry)
641 .disable(name)
642 .map_err(|error| failed(locale, &error))?;
643 report(registry, locale, name, "disabled", json, console)
644 }
645
646 pub(crate) fn revoke(
647 registry: &mut Arc<PluginRegistry>,
648 locale: Locale,
649 name: &str,
650 json: bool,
651 console: &mut dyn Console,
652 ) -> Result<()> {
653 find(registry, locale, name)?;
654 Arc::make_mut(registry)
655 .revoke_trust(name)
656 .map_err(|error| failed(locale, &error))?;
657 report(registry, locale, name, "trust-revoked", json, console)
658 }
659
659 lines RUST