返回 CodeWhale
plugins.rs
根目录 / crates / app-server / src / runtime_api / plugins.rs
1 //! Plugin bundle and marketplace management over the Runtime API.
2 //!
3 //! `GET /v1/apps/plugins` and `GET /v1/apps/plugins/{selector}` expose the
4 //! same registry the TUI reads, with the same honest state vocabulary
5 //! (`active`, `enabled-untrusted`, `unstaged`, …) and the same capability
6 //! inventory a terminal review shows. Mutations run through the exact
7 //! reviewed paths the TUI uses — `plugins::mutation::execute` for
8 //! install/update/uninstall (installs always land disabled and untrusted)
9 //! and the registry's hash-bound receipt flow for trust/enable/disable —
10 //! so a GUI client can never bypass a review the TUI would require.
11 //!
12 //! Marketplace endpoints share `plugins::marketplace::document` with the
13 //! `/plugin marketplace` command: local catalog documents only, tiers are
14 //! display-only, and installs route through the same reviewed installer.
15
16 use std::collections::{BTreeMap, HashMap};
17 use std::io::Read;
18 use std::net::SocketAddr;
19 use std::path::{Path as FsPath, PathBuf};
20 use std::sync::Arc;
21
22 use axum::Json;
23 use axum::body::{Body, to_bytes};
24 use axum::extract::{ConnectInfo, Path, Query, RawQuery, State};
25 use axum::http::uri::Authority;
26 use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode, Uri, header};
27 use axum::response::Response;
28 use serde::{Deserialize, Serialize};
29 use serde_json::Value;
30 use sha2::{Digest, Sha256};
31
32 use codewhale_plugins::host_services::{
33 HostServiceWireState, PersonVia, PluginApprover, PluginCohort, ReviewApproval, ReviewPeer,
34 cohort_of, host_service_wire_state, offered,
35 };
36 use codewhale_plugins::marketplace::document::{
37 CatalogInstallResolution, load_catalog_document, resolve_candidate_install,
38 };
39 use codewhale_plugins::marketplace::store::MarketplaceStore;
40 use codewhale_plugins::mutation::{
41 PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
42 };
43 use codewhale_plugins::types::{
44 LoadedPlugin, PluginDiagnostic, PluginDiagnosticLevel, PluginReviewEntry,
45 };
46
47 use super::{ApiError, PolicyOrApiError, RuntimeApiState};
48
49 const PLUGIN_UI_MAX_BYTES: u64 = 8 * 1024 * 1024;
50 const PLUGIN_UI_SLOT: &str = "customize.plugins.detail";
51 const PLUGIN_UI_SEATS: [&str; 6] = [
52 PLUGIN_UI_SLOT,
53 "conversation.composer.dock",
54 "conversation.chat.node",
55 "workpane.panel",
56 "sidebar.section",
57 "command.row",
58 ];
59 const DSH_BOOTSTRAP_ENTRY: &str = "__codewhale_dsh_bootstrap.js";
60 const DSH_FRAME_MODULES: [&str; 9] = [
61 "react",
62 "react-dom",
63 "react-dom/client",
64 "react/jsx-runtime",
65 "@deepseek-ai/dsh-client-store",
66 "@deepseek-ai/dsh-client-ui-primitives",
67 "@deepseek-ai/dsh-settings",
68 "@deepseek-ai/dsh-tools",
69 "@deepseek-ai/dsh-credentials",
70 ];
71 const DSH_ROUTE_METHODS: [&str; 5] = ["GET", "POST", "PUT", "PATCH", "DELETE"];
72
73 enum DshSeat {
74 Seat(&'static str),
75 Unsupported(&'static str),
76 }
77
78 const DSH_SEAT_TABLE: [(&str, DshSeat); 41] = [
79 ("plugins.bundle.config", DshSeat::Seat(PLUGIN_UI_SLOT)),
80 ("plugins.row.config", DshSeat::Seat(PLUGIN_UI_SLOT)),
81 ("plugins.tab", DshSeat::Seat(PLUGIN_UI_SLOT)),
82 ("plugins.detail.section", DshSeat::Seat(PLUGIN_UI_SLOT)),
83 ("plugins.item", DshSeat::Seat(PLUGIN_UI_SLOT)),
84 ("plugins.detail.actions", DshSeat::Seat(PLUGIN_UI_SLOT)),
85 ("plugins.detail.badge", DshSeat::Seat(PLUGIN_UI_SLOT)),
86 ("settings.section", DshSeat::Seat(PLUGIN_UI_SLOT)),
87 ("settings.section.icon", DshSeat::Seat(PLUGIN_UI_SLOT)),
88 ("settings.plugin.item", DshSeat::Seat(PLUGIN_UI_SLOT)),
89 ("settings.general.item", DshSeat::Seat(PLUGIN_UI_SLOT)),
90 ("settings.plugins.tab", DshSeat::Seat(PLUGIN_UI_SLOT)),
91 ("web-ui.plugin.item", DshSeat::Seat(PLUGIN_UI_SLOT)),
92 (
93 "conversation.chat.node",
94 DshSeat::Seat("conversation.chat.node"),
95 ),
96 (
97 "conversation.chat.turnTail",
98 DshSeat::Seat("conversation.chat.node"),
99 ),
100 (
101 "conversation.chat.assistant-actions",
102 DshSeat::Seat("conversation.chat.node"),
103 ),
104 (
105 "conversation.chat.commandview",
106 DshSeat::Seat("conversation.chat.node"),
107 ),
108 (
109 "conversation.chat.text-interaction",
110 DshSeat::Seat("conversation.chat.node"),
111 ),
112 (
113 "conversation.user.text.node",
114 DshSeat::Seat("conversation.chat.node"),
115 ),
116 (
117 "tool.call.toolview",
118 DshSeat::Seat("conversation.chat.node"),
119 ),
120 ("conversation.view", DshSeat::Seat("conversation.chat.node")),
121 (
122 "conversation.input.dock",
123 DshSeat::Seat("conversation.composer.dock"),
124 ),
125 (
126 "conversation.input.overlay",
127 DshSeat::Seat("conversation.composer.dock"),
128 ),
129 (
130 "conversation.input.right",
131 DshSeat::Seat("conversation.composer.dock"),
132 ),
133 (
134 "conversation.composer.dock",
135 DshSeat::Seat("conversation.composer.dock"),
136 ),
137 ("sidebar.right.pane.tab", DshSeat::Seat("workpane.panel")),
138 (
139 "sidebar.right.pane.tab.title",
140 DshSeat::Seat("workpane.panel"),
141 ),
142 ("shell.overlay", DshSeat::Seat("workpane.panel")),
143 ("main", DshSeat::Seat("workpane.panel")),
144 ("main.conversation", DshSeat::Seat("workpane.panel")),
145 ("main.page-menu", DshSeat::Seat("workpane.panel")),
146 ("sidebar.panellist", DshSeat::Seat("sidebar.section")),
147 ("sidebar.channels", DshSeat::Seat("sidebar.section")),
148 ("sidebar.workspaces", DshSeat::Seat("sidebar.section")),
149 ("sidebar.footer.action", DshSeat::Seat("sidebar.section")),
150 (
151 "sidebar.session.row.leading",
152 DshSeat::Seat("sidebar.section"),
153 ),
154 (
155 "sidebar.workspaces.session.row.action",
156 DshSeat::Seat("sidebar.section"),
157 ),
158 (
159 "conversation.session.header.actions",
160 DshSeat::Seat("command.row"),
161 ),
162 (
163 "conversation.session.header.lineage",
164 DshSeat::Seat("command.row"),
165 ),
166 (
167 "conversation.session.header.utilities",
168 DshSeat::Seat("command.row"),
169 ),
170 ("contextMenu.icon", DshSeat::Unsupported("no ADE seat yet")),
171 ];
172
173 // ---------------------------------------------------------------------------
174 // Response shapes
175 // ---------------------------------------------------------------------------
176
177 #[derive(Debug, Serialize)]
178 pub(super) struct PluginInventorySummary {
179 pub(super) skills: usize,
180 pub(super) mcp_servers: usize,
181 pub(super) stdio_mcp_servers: usize,
182 pub(super) remote_mcp_servers: usize,
183 pub(super) commands: usize,
184 pub(super) agents: usize,
185 pub(super) hooks: usize,
186 pub(super) lsp: usize,
187 pub(super) native: usize,
188 pub(super) filesystem_roots: Vec<String>,
189 pub(super) network_hosts: Vec<String>,
190 pub(super) lifecycle_mutation: bool,
191 }
192
193 #[derive(Debug, Serialize)]
194 pub(super) struct PluginDiagnosticEntry {
195 pub(super) level: &'static str,
196 pub(super) code: String,
197 pub(super) message: String,
198 pub(super) path: Option<String>,
199 }
200
201 #[derive(Debug, Serialize)]
202 pub(super) struct PluginSummaryEntry {
203 pub(super) id: String,
204 pub(super) name: String,
205 pub(super) display_name: Option<String>,
206 pub(super) icon: Option<String>,
207 pub(super) author: Option<String>,
208 pub(super) homepage: Option<String>,
209 pub(super) platforms: Vec<String>,
210 pub(super) version: String,
211 pub(super) description: Option<String>,
212 pub(super) scope: &'static str,
213 pub(super) origin: &'static str,
214 pub(super) path: String,
215 pub(super) state: &'static str,
216 pub(super) enabled: bool,
217 pub(super) trust_status: &'static str,
218 pub(super) active: bool,
219 #[serde(skip_serializing_if = "Option::is_none")]
220 pub(super) native_service_state: Option<&'static str>,
221 pub(super) approved_by: Option<PluginApprover>,
222 pub(super) enabled_by: Option<PluginApprover>,
223 pub(super) cohort: PluginCohort,
224 pub(super) outside_reach: bool,
225 pub(super) host_services: Vec<PluginHostServiceEntry>,
226 pub(super) compatibility: &'static str,
227 pub(super) inventory: PluginInventorySummary,
228 pub(super) content_hash: String,
229 pub(super) capability_hash: String,
230 pub(super) state_generation: u64,
231 pub(super) diagnostics: Vec<PluginDiagnosticEntry>,
232 }
233
234 #[derive(Debug, Serialize)]
235 pub(super) struct PluginHostServiceEntry {
236 pub(super) service: &'static str,
237 pub(super) state: HostServiceWireState,
238 #[serde(skip_serializing_if = "Vec::is_empty")]
239 pub(super) withheld_by: Vec<ReviewPeer>,
240 }
241
242 #[derive(Debug, Serialize)]
243 pub(super) struct PluginsResponse {
244 pub(super) workspace: String,
245 pub(super) plugins: Vec<PluginSummaryEntry>,
246 pub(super) registry_diagnostics: Vec<PluginDiagnosticEntry>,
247 pub(super) validation_clean: bool,
248 }
249
250 /// One reviewed-plugin MCP server in the trust-review payload. Environment
251 /// and header maps expose only key names; URLs expose only their network
252 /// authority. Command and argument text remain the bundle's declared launch
253 /// instructions for review, so bundles should pass credentials through env.
254 #[derive(Debug, Serialize)]
255 pub(super) struct PluginMcpServerReview {
256 pub(super) name: String,
257 pub(super) kind: &'static str,
258 pub(super) command: Option<String>,
259 pub(super) args: Vec<String>,
260 pub(super) url: Option<String>,
261 pub(super) env_keys: Vec<String>,
262 pub(super) header_keys: Vec<String>,
263 }
264
265 #[derive(Debug, Serialize)]
266 pub(super) struct PluginSkillReview {
267 pub(super) name: String,
268 pub(super) description: String,
269 }
270
271 /// The capability review a human approves (or rejects) before trusting a
272 /// bundle. Structured so a GUI renders it without parsing prose.
273 #[derive(Debug, Serialize)]
274 pub(super) struct PluginReviewPayload {
275 /// Confirmation token binding a trust call to this exact content and
276 /// capability set (`POST .../trust {"token": ...}`).
277 pub(super) token: String,
278 pub(super) capabilities: Vec<&'static str>,
279 pub(super) unsupported_capabilities: Vec<&'static str>,
280 pub(super) filesystem_roots: Vec<String>,
281 pub(super) network_hosts: Vec<String>,
282 pub(super) lifecycle_mutation: bool,
283 pub(super) mcp_servers: Vec<PluginMcpServerReview>,
284 pub(super) skills: Vec<PluginSkillReview>,
285 pub(super) commands: Vec<String>,
286 pub(super) agents: Vec<String>,
287 pub(super) hooks: Vec<String>,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub(super) host_services: Option<codewhale_plugins::host_services::HostServiceReview>,
290 }
291
292 #[derive(Debug, Serialize)]
293 pub(super) struct PluginDetailResponse {
294 #[serde(flatten)]
295 pub(super) summary: PluginSummaryEntry,
296 pub(super) repository: Option<String>,
297 pub(super) license: Option<String>,
298 pub(super) keywords: Vec<String>,
299 pub(super) staged: bool,
300 pub(super) reviewed_at: Option<String>,
301 pub(super) review_history: Vec<PluginReviewEntry>,
302 pub(super) review: PluginReviewPayload,
303 pub(super) ui_slots: Vec<PluginUiSlotDeclaration>,
304 #[serde(skip_serializing_if = "Option::is_none")]
305 pub(super) ui_slots_unavailable: Option<PluginUiSlotsUnavailable>,
306 }
307
308 #[derive(Debug, Serialize)]
309 pub(super) struct PluginUiSlotDeclaration {
310 pub(super) slot: &'static str,
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub(super) dsh_slot: Option<String>,
313 }
314
315 #[derive(Debug, Serialize)]
316 pub(super) struct PluginUiSlotsUnavailable {
317 #[serde(skip_serializing_if = "Option::is_none")]
318 pub(super) code: Option<&'static str>,
319 pub(super) message: String,
320 }
321
322 #[derive(Debug, Serialize)]
323 pub(super) struct PluginMutationResponse {
324 pub(super) outcome: &'static str,
325 pub(super) name: String,
326 pub(super) path: Option<String>,
327 pub(super) content_hash: Option<String>,
328 pub(super) note: Option<&'static str>,
329 /// Fresh post-mutation state of the affected bundle, when it still
330 /// exists (uninstall removes it).
331 pub(super) plugin: Option<PluginSummaryEntry>,
332 }
333
334 #[derive(Debug, Serialize)]
335 pub(super) struct PluginActionResponse {
336 pub(super) name: String,
337 pub(super) action: &'static str,
338 pub(super) state: &'static str,
339 pub(super) note: Option<&'static str>,
340 }
341
342 #[derive(Debug, Serialize)]
343 pub(super) struct PluginUiBridge {
344 pub(super) kind: &'static str,
345 pub(super) dsh_version: String,
346 pub(super) compatibility_digest: String,
347 }
348
349 #[derive(Debug, Serialize)]
350 pub(super) struct PluginUiSlotResponse {
351 pub(super) slot: String,
352 #[serde(skip_serializing_if = "Option::is_none")]
353 pub(super) dsh_slot: Option<String>,
354 #[serde(skip_serializing_if = "Option::is_none")]
355 pub(super) bridge: Option<PluginUiBridge>,
356 pub(super) base: String,
357 pub(super) entry: String,
358 pub(super) revision: String,
359 }
360
361 #[derive(Debug)]
362 enum UiFileError {
363 Missing,
364 TooLarge,
365 Invalid(String),
366 Internal(String),
367 }
368
369 // ---------------------------------------------------------------------------
370 // Request shapes
371 // ---------------------------------------------------------------------------
372
373 #[derive(Debug, Deserialize)]
374 pub(super) struct InstallPluginRequest {
375 /// Install spec accepted by `PluginInstallSource::parse`: a local path
376 /// (plain or `path:<dir>`), `github:owner/repo`, or an HTTPS tarball URL.
377 pub(super) source: String,
378 /// When present, the install is refused (and rolled back) unless the
379 /// installed tree matches this reviewed content hash.
380 #[serde(default)]
381 pub(super) expected_content_hash: Option<String>,
382 }
383
384 #[derive(Debug, Deserialize)]
385 pub(super) struct PluginUiQuery {
386 pub(super) slot: Option<String>,
387 pub(super) dsh_slot: Option<String>,
388 }
389
390 #[derive(Debug, Deserialize)]
391 pub(super) struct DshPreviewRequest {
392 /// DeepSeek Harness bundle package directory; relative paths resolve
393 /// against the workspace.
394 pub(super) path: String,
395 }
396
397 #[derive(Debug, Serialize)]
398 pub(super) struct DshPreviewResponse {
399 /// Pass to `POST /v1/apps/plugins/install` as `source`, with
400 /// `content_hash` as `expected_content_hash`, to install exactly this
401 /// reviewed bundle.
402 pub(super) install_source: String,
403 pub(super) content_hash: String,
404 pub(super) conversion: codewhale_plugins::install::dsh::DshConversion,
405 }
406
407 #[derive(Debug, Deserialize)]
408 pub(super) struct TrustPluginRequest {
409 /// Review token from `GET /v1/apps/plugins/{selector}`. Required: trust
410 /// is an explicit confirmation bound to both SHA-256 receipts.
411 pub(super) token: String,
412 #[serde(default)]
413 pub(super) host_services_token: Option<String>,
414 }
415
416 #[derive(Debug, Deserialize)]
417 pub(super) struct AddMarketplaceRequest {
418 pub(super) name: String,
419 /// LOCAL catalog document path (kimi/claude/codex/dsh/codewhale format,
420 /// auto-detected). Never fetched over the network.
421 pub(super) path: String,
422 }
423
424 #[derive(Debug, Deserialize)]
425 pub(super) struct InstallMarketplaceCandidateRequest {
426 pub(super) candidate: String,
427 }
428
429 // ---------------------------------------------------------------------------
430 // Shared helpers
431 // ---------------------------------------------------------------------------
432
433 fn registry_for_state(state: &RuntimeApiState) -> Arc<codewhale_plugins::PluginRegistry> {
434 state
435 .plugin_discovery
436 .registry_for_workspace(&state.workspace)
437 }
438
439 fn diagnostic_entry(diagnostic: &PluginDiagnostic) -> PluginDiagnosticEntry {
440 PluginDiagnosticEntry {
441 level: match diagnostic.level {
442 PluginDiagnosticLevel::Warning => "warning",
443 PluginDiagnosticLevel::Error => "error",
444 },
445 code: diagnostic.code.to_string(),
446 message: diagnostic.message.clone(),
447 path: diagnostic.path.as_ref().map(|p| p.display().to_string()),
448 }
449 }
450
451 fn inventory_summary(plugin: &LoadedPlugin) -> PluginInventorySummary {
452 let inventory = &plugin.inventory;
453 PluginInventorySummary {
454 skills: inventory.skills,
455 mcp_servers: inventory.mcp_servers,
456 stdio_mcp_servers: inventory.stdio_mcp_servers,
457 remote_mcp_servers: inventory.remote_mcp_servers,
458 commands: inventory.commands,
459 agents: inventory.agents,
460 hooks: inventory.hooks,
461 lsp: inventory.lsp,
462 native: inventory.native,
463 filesystem_roots: inventory.filesystem_roots.clone(),
464 network_hosts: inventory.network_hosts.clone(),
465 lifecycle_mutation: inventory.lifecycle_mutation,
466 }
467 }
468
469 fn summary_host_services(
470 plugin: &LoadedPlugin,
471 registry: Option<&codewhale_plugins::PluginRegistry>,
472 ) -> Vec<PluginHostServiceEntry> {
473 if let Some(review) = registry.and_then(|reg| match plugin.approved_by.as_ref() {
474 Some(approver) => reg.host_service_review_for(plugin.id.as_str(), approver),
475 None => reg.host_service_review(plugin.id.as_str()),
476 }) {
477 return review
478 .lines
479 .into_iter()
480 .map(|line| {
481 let state = host_service_wire_state(&plugin.host_services, &line);
482 let withheld_by = if state == HostServiceWireState::CanUse {
483 line.withheld_by
484 } else {
485 Vec::new()
486 };
487 PluginHostServiceEntry {
488 service: line.service.name(),
489 state,
490 withheld_by,
491 }
492 })
493 .collect();
494 }
495 plugin
496 .inventory
497 .host_services
498 .iter()
499 .copied()
500 .map(|service| PluginHostServiceEntry {
501 service: service.name(),
502 state: if offered(service) && plugin.host_services.contains(&service) {
503 HostServiceWireState::CanUse
504 } else {
505 HostServiceWireState::NotOffered
506 },
507 withheld_by: Vec::new(),
508 })
509 .collect()
510 }
511
512 fn plugin_summary(
513 plugin: &LoadedPlugin,
514 registry: Option<&codewhale_plugins::PluginRegistry>,
515 ) -> PluginSummaryEntry {
516 PluginSummaryEntry {
517 id: plugin.id.as_str().to_string(),
518 name: plugin.name().to_string(),
519 display_name: plugin.manifest.plugin.display_name.clone(),
520 icon: plugin.manifest.plugin.icon.clone(),
521 author: plugin.manifest.plugin.author.clone(),
522 homepage: plugin.manifest.plugin.homepage.clone(),
523 platforms: plugin
524 .manifest
525 .when
526 .as_ref()
527 .and_then(|when| when.os.clone())
528 .unwrap_or_default(),
529 version: plugin.manifest.plugin.version.clone(),
530 description: plugin.manifest.plugin.description.clone(),
531 scope: plugin.scope.as_str(),
532 origin: plugin.origin.as_str(),
533 path: plugin.canonical_root.display().to_string(),
534 state: plugin.state_label(),
535 enabled: plugin.enabled,
536 trust_status: plugin.trust_status.as_str(),
537 active: plugin.active(),
538 native_service_state: (plugin.inventory.native > 0).then(|| {
539 if !plugin.active() || !codewhale_plugins::activation::extension_host_policy_enabled() {
540 return "disabled";
541 }
542 registry
543 .and_then(|registry| registry.authority_for(plugin.id.as_str()))
544 .map_or("not_started", |authority| {
545 codewhale_engine::extension_host::manager().native_service_state(&authority)
546 })
547 }),
548 approved_by: plugin.approved_by.clone(),
549 enabled_by: plugin.enabled_by.clone(),
550 cohort: cohort_of(plugin.approved_by.as_ref()),
551 outside_reach: plugin.outside_reach,
552 host_services: summary_host_services(plugin, registry),
553 compatibility: plugin.compatibility().as_str(),
554 inventory: inventory_summary(plugin),
555 content_hash: plugin.content_hash.clone(),
556 capability_hash: plugin.capability_hash.clone(),
557 state_generation: plugin.state_generation,
558 diagnostics: plugin.diagnostics.iter().map(diagnostic_entry).collect(),
559 }
560 }
561
562 fn mcp_server_review(
563 name: &str,
564 cfg: &codewhale_mcp::config::McpServerConfig,
565 ) -> PluginMcpServerReview {
566 let mut env_keys: Vec<String> = cfg.env.keys().cloned().collect();
567 env_keys.sort();
568 let mut header_keys: Vec<String> = cfg.headers.keys().cloned().collect();
569 header_keys.sort();
570 PluginMcpServerReview {
571 name: name.to_string(),
572 kind: if cfg.url.is_some() { "remote" } else { "stdio" },
573 command: cfg.command.clone(),
574 args: cfg.args.clone(),
575 url: cfg
576 .url
577 .as_deref()
578 .map(codewhale_config::structural_url_authority),
579 env_keys,
580 header_keys,
581 }
582 }
583
584 async fn component_names(
585 paths: &[std::path::PathBuf],
586 extension: Option<&str>,
587 lowercase: bool,
588 ) -> Vec<String> {
589 codewhale_plugins::runtime::component_file_names(paths, extension, lowercase, 512)
590 .await
591 .0
592 }
593
594 async fn review_payload(
595 plugin: &LoadedPlugin,
596 registry: Option<&codewhale_plugins::PluginRegistry>,
597 ) -> PluginReviewPayload {
598 let mut mcp_servers: Vec<_> = plugin
599 .manifest
600 .mcp_servers
601 .as_ref()
602 .map(|servers| {
603 servers
604 .iter()
605 .map(|(name, cfg)| mcp_server_review(name, cfg))
606 .collect()
607 })
608 .unwrap_or_default();
609 mcp_servers.sort_by(|a, b| a.name.cmp(&b.name));
610 let commands = component_names(&plugin.components.commands, Some("md"), true).await;
611 let agents = component_names(&plugin.components.agents, Some("toml"), false).await;
612 let hooks = component_names(&plugin.components.hooks, None, false).await;
613 let mut skills: Vec<_> = plugin
614 .skill_snapshots
615 .iter()
616 .map(|skill| PluginSkillReview {
617 name: skill.name.clone(),
618 description: skill.description.clone(),
619 })
620 .collect();
621 skills.sort_by(|a, b| a.name.cmp(&b.name));
622
623 let host_services = registry
624 .and_then(|reg| {
625 reg.host_service_review_for(plugin.name(), &PluginApprover::person(PersonVia::App))
626 })
627 .filter(|review| !review.lines.is_empty());
628
629 PluginReviewPayload {
630 token: plugin.review_token(),
631 capabilities: plugin.inventory.supported_labels(),
632 unsupported_capabilities: plugin.inventory.unsupported_labels(),
633 filesystem_roots: plugin.inventory.filesystem_roots.clone(),
634 network_hosts: plugin.inventory.network_hosts.clone(),
635 lifecycle_mutation: plugin.inventory.lifecycle_mutation,
636 mcp_servers,
637 skills,
638 commands,
639 agents,
640 hooks,
641 host_services,
642 }
643 }
644
645 async fn plugin_detail(
646 plugin: &LoadedPlugin,
647 registry: Option<&codewhale_plugins::PluginRegistry>,
648 ) -> PluginDetailResponse {
649 PluginDetailResponse {
650 summary: plugin_summary(plugin, registry),
651 repository: plugin.manifest.plugin.repository.clone(),
652 license: plugin.manifest.plugin.license.clone(),
653 keywords: plugin.manifest.plugin.keywords.clone(),
654 staged: plugin.staged_root.is_some(),
655 reviewed_at: plugin.reviewed_at.clone(),
656 review_history: plugin.review_history.clone(),
657 review: review_payload(plugin, registry).await,
658 ui_slots: Vec::new(),
659 ui_slots_unavailable: None,
660 }
661 }
662
663 fn find_plugin(state: &RuntimeApiState, selector: &str) -> Result<LoadedPlugin, ApiError> {
664 registry_for_state(state)
665 .get(selector)
666 .cloned()
667 .ok_or_else(|| ApiError::not_found(format!("plugin '{selector}' not found")))
668 }
669
670 fn ui_relative_path(raw: &str) -> Result<PathBuf, &'static str> {
671 let raw = raw.strip_prefix("./").unwrap_or(raw);
672 if raw.is_empty() {
673 return Err("it is empty");
674 }
675 if raw.starts_with('/') || raw.contains('\\') {
676 return Err("it must be a relative path without backslashes");
677 }
678 if raw.contains('\0') {
679 return Err("it contains a NUL byte");
680 }
681 let mut relative = PathBuf::new();
682 for component in FsPath::new(raw).components() {
683 match component {
684 std::path::Component::Normal(part) => relative.push(part),
685 std::path::Component::CurDir => {}
686 std::path::Component::ParentDir => return Err("it must not contain '..'"),
687 std::path::Component::RootDir | std::path::Component::Prefix(_) => {
688 return Err("it must be relative");
689 }
690 }
691 }
692 if relative.as_os_str().is_empty() {
693 return Err("it is empty");
694 }
695 Ok(relative)
696 }
697
698 fn ui_relative_display(relative: &FsPath) -> String {
699 relative
700 .components()
701 .filter_map(|component| match component {
702 std::path::Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
703 _ => None,
704 })
705 .collect::<Vec<_>>()
706 .join("/")
707 }
708
709 fn ui_client_entry(manifest: &Value) -> Option<String> {
710 let export = manifest.get("exports")?.get("./client")?;
711 match export {
712 Value::String(target) => Some(target.clone()),
713 Value::Object(targets) => ["import", "default", "."]
714 .iter()
715 .find_map(|key| targets.get(*key).and_then(Value::as_str))
716 .map(str::to_string),
717 _ => None,
718 }
719 }
720
721 fn ui_content_type(path: &FsPath) -> &'static str {
722 match path
723 .extension()
724 .and_then(std::ffi::OsStr::to_str)
725 .map(str::to_ascii_lowercase)
726 .as_deref()
727 {
728 Some("js" | "mjs" | "cjs") => "text/javascript; charset=utf-8",
729 Some("css") => "text/css; charset=utf-8",
730 Some("json") => "application/json; charset=utf-8",
731 Some("svg") => "image/svg+xml",
732 Some("png") => "image/png",
733 Some("jpg" | "jpeg") => "image/jpeg",
734 Some("webp") => "image/webp",
735 Some("gif") => "image/gif",
736 Some("ico") => "image/x-icon",
737 Some("woff") => "font/woff",
738 Some("woff2") => "font/woff2",
739 Some("ttf") => "font/ttf",
740 _ => "application/octet-stream",
741 }
742 }
743
744 fn is_dsh_static_ui_asset(path: &FsPath) -> bool {
745 let ext = path
746 .extension()
747 .and_then(std::ffi::OsStr::to_str)
748 .map(str::to_ascii_lowercase);
749 match ext.as_deref() {
750 Some(
751 "css" | "svg" | "png" | "jpg" | "jpeg" | "webp" | "gif" | "ico" | "woff" | "woff2"
752 | "ttf",
753 ) => true,
754 Some("json") => !matches!(
755 path.file_name().and_then(std::ffi::OsStr::to_str),
756 Some("package.json" | "CONVERSION.json")
757 ),
758 _ => false,
759 }
760 }
761
762 fn ui_asset_response(bytes: Vec<u8>, content_type: &'static str) -> Response {
763 let mut response = Response::new(Body::from(bytes));
764 let headers = response.headers_mut();
765 headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
766 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
767 headers.insert(
768 header::X_CONTENT_TYPE_OPTIONS,
769 HeaderValue::from_static("nosniff"),
770 );
771 headers.insert(
772 header::REFERRER_POLICY,
773 HeaderValue::from_static("no-referrer"),
774 );
775 if content_type == "image/svg+xml" {
776 headers.insert(
777 header::CONTENT_SECURITY_POLICY,
778 HeaderValue::from_static("default-src 'none'; style-src 'unsafe-inline'; sandbox"),
779 );
780 } else {
781 headers.insert(
782 header::CONTENT_SECURITY_POLICY,
783 HeaderValue::from_static("default-src 'none'; sandbox"),
784 );
785 }
786 response
787 }
788
789 #[derive(Clone)]
790 struct PluginUiGrant {
791 service: Arc<tokio::sync::OnceCell<PluginRouteService>>,
792 selector: String,
793 authority: codewhale_config::PluginAuthority,
794 state_file: Arc<std::fs::File>,
795 root: PathBuf,
796 root_file: Arc<std::fs::File>,
797 ui_prefix: PathBuf,
798 file_hashes: Arc<BTreeMap<PathBuf, String>>,
799 expires: std::time::Instant,
800 dsh: Option<Arc<DshServed>>,
801 }
802
803 struct PluginRouteService {
804 _attachment: codewhale_engine::extension_host::HostAttachment,
805 _expiry_cancel: tokio::sync::oneshot::Sender<()>,
806 }
807
808 struct DshClosure {
809 package: String,
810 entry: String,
811 files: BTreeMap<String, String>,
812 imports: BTreeMap<String, BTreeMap<String, Option<String>>>,
813 host_provided: Vec<String>,
814 }
815
816 struct DshServed {
817 closure: DshClosure,
818 }
819
820 #[derive(Default)]
821 pub(super) struct PluginUiGrants {
822 entries: parking_lot::Mutex<HashMap<String, PluginUiGrant>>,
823 }
824
825 impl PluginUiGrants {
826 fn insert(&self, grant: PluginUiGrant) -> String {
827 let mut entries = self.entries.lock();
828 let now = std::time::Instant::now();
829 entries.retain(|_, value| value.expires > now);
830 if entries.len() >= 256
831 && let Some(oldest) = entries
832 .iter()
833 .min_by_key(|(_, value)| value.expires)
834 .map(|(key, _)| key.clone())
835 {
836 entries.remove(&oldest);
837 }
838 loop {
839 let revision = format!("\"{}\"", uuid::Uuid::new_v4());
840 if !entries.contains_key(&revision) {
841 entries.insert(revision.clone(), grant);
842 return revision;
843 }
844 }
845 }
846
847 fn revoke_selector(&self, selector: &str) {
848 self.entries
849 .lock()
850 .retain(|_, value| value.selector != selector);
851 }
852
853 fn get(&self, revision: &str) -> Option<PluginUiGrant> {
854 let mut entries = self.entries.lock();
855 let now = std::time::Instant::now();
856 entries.retain(|_, value| value.expires > now);
857 entries.get(revision).cloned()
858 }
859 }
860
861 fn ui_file_refusal(plugin: &LoadedPlugin, display: &str, error: UiFileError) -> ApiError {
862 match error {
863 UiFileError::Missing => ApiError::not_found(format!(
864 "plugin '{}' has no staged file '{display}'",
865 plugin.name()
866 ))
867 .with_code("plugin_ui_file_not_reviewed"),
868 UiFileError::TooLarge => ApiError::payload_too_large(format!(
869 "plugin '{}' file '{display}' exceeds the 8 MiB plugin UI limit",
870 plugin.name()
871 )),
872 UiFileError::Invalid(reason) => ApiError::bad_request(format!(
873 "plugin '{}' file '{display}' is not a readable staged file: {reason}",
874 plugin.name()
875 )),
876 UiFileError::Internal(reason) => ApiError::internal(format!(
877 "plugin '{}' file '{display}' could not be read: {reason}",
878 plugin.name()
879 )),
880 }
881 }
882
883 fn ui_root_matches(grant: &PluginUiGrant) -> Result<(), UiFileError> {
884 let metadata = std::fs::symlink_metadata(&grant.root)
885 .map_err(|error| UiFileError::Internal(error.to_string()))?;
886 if !metadata.is_dir() || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) {
887 return Err(UiFileError::Invalid("the staged root changed".into()));
888 }
889 let (canonical, current) = codewhale_util::workspace_dir::open_workspace_directory(&grant.root)
890 .map_err(|error| UiFileError::Internal(error.to_string()))?;
891 if canonical != grant.root
892 || !codewhale_util::files::same_file(&grant.root_file, &current)
893 .map_err(|error| UiFileError::Internal(error.to_string()))?
894 {
895 return Err(UiFileError::Invalid("the staged root changed".into()));
896 }
897 Ok(())
898 }
899
900 fn verified_ui_file(grant: &PluginUiGrant, relative: &FsPath) -> Result<Vec<u8>, UiFileError> {
901 let expected = grant
902 .file_hashes
903 .get(relative)
904 .ok_or(UiFileError::Missing)?;
905 ui_root_matches(grant)?;
906 let file = codewhale_util::fs_confined::open_read(&grant.root, &grant.root.join(relative))
907 .map_err(|error| match error.kind() {
908 std::io::ErrorKind::NotFound => UiFileError::Missing,
909 _ => UiFileError::Invalid(error.to_string()),
910 })?;
911 let metadata = file
912 .metadata()
913 .map_err(|error| UiFileError::Internal(error.to_string()))?;
914 if metadata.len() > PLUGIN_UI_MAX_BYTES {
915 return Err(UiFileError::TooLarge);
916 }
917 let mut bytes = Vec::with_capacity(metadata.len() as usize);
918 file.take(PLUGIN_UI_MAX_BYTES + 1)
919 .read_to_end(&mut bytes)
920 .map_err(|error| UiFileError::Internal(error.to_string()))?;
921 if bytes.len() as u64 > PLUGIN_UI_MAX_BYTES {
922 return Err(UiFileError::TooLarge);
923 }
924 let mut hash = Sha256::new();
925 hash.update(b"codewhale-plugin-file-bytes-v1\0");
926 hash.update(&bytes);
927 let actual = hash
928 .finalize()
929 .iter()
930 .map(|byte| format!("{byte:02x}"))
931 .collect::<String>();
932 if actual != *expected {
933 return Err(UiFileError::Invalid(
934 "the file no longer matches its reviewed bytes".into(),
935 ));
936 }
937 ui_root_matches(grant)?;
938 Ok(bytes)
939 }
940
941 fn admit_ui_grant(
942 state: &RuntimeApiState,
943 grant: &PluginUiGrant,
944 ) -> Result<Arc<codewhale_plugins::PluginRegistry>, ApiError> {
945 if grant.expires <= std::time::Instant::now() {
946 return Err(ui_stale_revision());
947 }
948 let registry = registry_for_state(state);
949 if !registry
950 .get(&grant.selector)
951 .is_some_and(LoadedPlugin::active)
952 || registry.authority_for(&grant.selector).as_ref() != Some(&grant.authority)
953 {
954 return Err(ui_stale_revision());
955 }
956 codewhale_plugins::registry::capture_plugin_state_authority(
957 &grant.authority,
958 Some(&grant.state_file),
959 )
960 .map_err(|_| ui_stale_revision())?;
961 ui_root_matches(grant).map_err(|_| ui_stale_revision())?;
962 Ok(registry)
963 }
964
965 fn valid_dsh_slot_key(key: &str) -> bool {
966 let mut chars = key.chars();
967 key.len() <= 128
968 && chars
969 .next()
970 .is_some_and(|first| first.is_ascii_alphanumeric())
971 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
972 }
973
974 fn ui_stale_revision() -> ApiError {
975 ApiError {
976 status: StatusCode::PRECONDITION_FAILED,
977 message: "plugin UI authorization has expired or changed; reopen the plugin".into(),
978 code: None,
979 }
980 }
981
982 struct PreparedPluginUi {
983 entry: String,
984 dsh_slot: Option<String>,
985 bridge: Option<PluginUiBridge>,
986 grant: PluginUiGrant,
987 }
988
989 fn seat_not_admitted(plugin: &LoadedPlugin, seat: &str, dsh_slot: Option<&str>) -> ApiError {
990 let key = dsh_slot
991 .map(|key| format!(" key '{key}'"))
992 .unwrap_or_default();
993 ApiError::not_found(format!(
994 "plugin '{}' has no admitted client for seat '{seat}'{key}",
995 plugin.name()
996 ))
997 .with_code("plugin_ui_seat_not_admitted")
998 }
999
1000 fn ui_unsupported(message: impl Into<String>) -> ApiError {
1001 ApiError::bad_request(message).with_code("plugin_ui_unsupported")
1002 }
1003
1004 fn sha256_hex(bytes: &[u8]) -> String {
1005 Sha256::digest(bytes)
1006 .iter()
1007 .map(|byte| format!("{byte:02x}"))
1008 .collect()
1009 }
1010
1011 fn dsh_client_closure(conversion: &Value) -> Option<DshClosure> {
1012 let closure = conversion
1013 .get("client_closures")?
1014 .as_array()?
1015 .iter()
1016 .find(|closure| closure.get("root").and_then(Value::as_str) == Some(""))?;
1017 let files = closure
1018 .get("files")?
1019 .as_object()?
1020 .iter()
1021 .map(|(path, hash)| Some((path.clone(), hash.as_str()?.to_string())))
1022 .collect::<Option<BTreeMap<_, _>>>()?;
1023 let entry = closure.get("entry")?.as_str()?.to_string();
1024 if !files.contains_key(&entry) {
1025 return None;
1026 }
1027 let imports: BTreeMap<String, BTreeMap<String, Option<String>>> =
1028 serde_json::from_value(closure.get("imports")?.clone()).ok()?;
1029 for (from, edges) in &imports {
1030 if !files.contains_key(from)
1031 || edges
1032 .values()
1033 .flatten()
1034 .any(|target| !files.contains_key(target))
1035 {
1036 return None;
1037 }
1038 }
1039 Some(DshClosure {
1040 package: closure
1041 .get("package")
1042 .and_then(Value::as_str)
1043 .unwrap_or_default()
1044 .to_string(),
1045 entry,
1046 files,
1047 imports,
1048 host_provided: closure
1049 .get("host_provided")
1050 .and_then(Value::as_array)
1051 .map(|items| {
1052 items
1053 .iter()
1054 .filter_map(|item| item.as_str().map(str::to_string))
1055 .collect()
1056 })
1057 .unwrap_or_default(),
1058 })
1059 }
1060
1061 fn verify_dsh_closure(
1062 grant: &PluginUiGrant,
1063 closure: &DshClosure,
1064 ) -> Result<Vec<(String, Vec<u8>)>, UiFileError> {
1065 let mut verified = Vec::with_capacity(closure.files.len());
1066 for (path, expected) in &closure.files {
1067 let relative = ui_relative_path(path)
1068 .map_err(|reason| UiFileError::Invalid(format!("closure file '{path}': {reason}")))?;
1069 let bytes = verified_ui_file(grant, &relative)?;
1070 if sha256_hex(&bytes) != *expected {
1071 return Err(UiFileError::Invalid(format!(
1072 "closure file '{path}' no longer matches its reviewed hash"
1073 )));
1074 }
1075 verified.push((path.clone(), bytes));
1076 }
1077 Ok(verified)
1078 }
1079
1080 fn has_esm_syntax(text: &str) -> bool {
1081 text.contains("import.meta")
1082 || text.lines().any(|line| {
1083 let line = line.trim_start();
1084 [
1085 "import ", "import{", "import\"", "import'", "export ", "export{", "export*",
1086 ]
1087 .iter()
1088 .any(|prefix| line.starts_with(prefix))
1089 })
1090 }
1091
1092 fn dsh_closure_unsupported(closure: &DshClosure, verified: &[(String, Vec<u8>)]) -> Option<String> {
1093 let missing: Vec<&str> = closure
1094 .host_provided
1095 .iter()
1096 .map(String::as_str)
1097 .filter(|module| !DSH_FRAME_MODULES.contains(module))
1098 .take(5)
1099 .collect();
1100 if !missing.is_empty() {
1101 return Some(format!(
1102 "this DSH client requires modules the plugin frame does not provide yet: {}",
1103 missing.join(", ")
1104 ));
1105 }
1106 for (path, bytes) in verified {
1107 let Ok(text) = std::str::from_utf8(bytes) else {
1108 return Some(format!("closure file '{path}' is not UTF-8 text"));
1109 };
1110 if path.ends_with(".json") {
1111 if serde_json::from_str::<Value>(text).is_err() {
1112 return Some(format!("closure file '{path}' is not valid JSON"));
1113 }
1114 } else if has_esm_syntax(text) {
1115 return Some(format!(
1116 "closure file '{path}' uses ES module syntax; only CommonJS closures are served"
1117 ));
1118 }
1119 }
1120 None
1121 }
1122
1123 fn quoted_in(text: &str, key: &str) -> bool {
1124 ['"', '\'', '`']
1125 .iter()
1126 .any(|quote| text.contains(&format!("{quote}{key}{quote}")))
1127 }
1128
1129 fn declared_dsh_keys(verified: &[(String, Vec<u8>)]) -> Vec<&'static (&'static str, DshSeat)> {
1130 let texts: Vec<String> = verified
1131 .iter()
1132 .map(|(_, bytes)| String::from_utf8_lossy(bytes).into_owned())
1133 .collect();
1134 DSH_SEAT_TABLE
1135 .iter()
1136 .filter(|(key, _)| texts.iter().any(|text| quoted_in(text, key)))
1137 .collect()
1138 }
1139
1140 fn admit_dsh_seat(
1141 plugin: &LoadedPlugin,
1142 seat: &str,
1143 requested: Option<&str>,
1144 declared: &[&'static (&'static str, DshSeat)],
1145 ) -> Result<String, ApiError> {
1146 if let Some(key) = requested {
1147 let Some((_, mapped)) = declared.iter().find(|(name, _)| *name == key) else {
1148 return Err(seat_not_admitted(plugin, seat, requested));
1149 };
1150 return match mapped {
1151 DshSeat::Unsupported(reason) => Err(ApiError {
1152 status: StatusCode::UNPROCESSABLE_ENTITY,
1153 message: format!(
1154 "plugin '{}' declares '{key}', which has no Codewhale seat: {reason}",
1155 plugin.name()
1156 ),
1157 code: Some("plugin_ui_seat_unsupported"),
1158 }),
1159 DshSeat::Seat(mapped_seat) if *mapped_seat == seat => Ok(key.to_string()),
1160 DshSeat::Seat(_) => Err(seat_not_admitted(plugin, seat, requested)),
1161 };
1162 }
1163 let mut on_seat = declared.iter().filter_map(|(name, mapped)| match mapped {
1164 DshSeat::Seat(mapped_seat) if *mapped_seat == seat => Some(*name),
1165 _ => None,
1166 });
1167 match (on_seat.next(), on_seat.next()) {
1168 (None, _) => Err(seat_not_admitted(plugin, seat, None)),
1169 (Some(key), None) => Ok(key.to_string()),
1170 (Some(_), Some(_)) => Err(ApiError::bad_request(format!(
1171 "plugin '{}' admits more than one client key on seat '{seat}'; pass dsh_slot",
1172 plugin.name()
1173 ))
1174 .with_code("plugin_ui_dsh_slot_required")),
1175 }
1176 }
1177
1178 fn dsh_bridge() -> Result<PluginUiBridge, ApiError> {
1179 let receipt: Value = serde_json::from_slice(codewhale_plugins::activation::DSH_COMPATIBILITY)
1180 .map_err(|_| {
1181 ApiError::internal("the pinned DSH compatibility receipt is unreadable")
1182 })?;
1183 let version = receipt
1184 .get("target_dsh_version")
1185 .and_then(Value::as_str)
1186 .ok_or_else(|| ApiError::internal("the pinned DSH compatibility receipt has no version"))?;
1187 Ok(PluginUiBridge {
1188 kind: "dsh-client",
1189 dsh_version: version.to_string(),
1190 compatibility_digest: sha256_hex(codewhale_plugins::activation::DSH_COMPATIBILITY),
1191 })
1192 }
1193
1194 const DSH_BOOTSTRAP_HEAD: &str = r#""use strict";
1195 (function () {
1196 var files = {
1197 "#;
1198
1199 const DSH_BOOTSTRAP_TAIL: &str = r#" var cache = Object.create(null);
1200 var hostRequire = null;
1201 function load(path) {
1202 if (Object.prototype.hasOwnProperty.call(cache, path)) return cache[path].exports;
1203 var module = { exports: {} };
1204 cache[path] = module;
1205 files[path].call(module.exports, module, module.exports, makeRequire(path));
1206 return module.exports;
1207 }
1208 function makeRequire(from) {
1209 return function (id) {
1210 var edges = imports[from];
1211 if (typeof id !== "string" || !edges || !Object.prototype.hasOwnProperty.call(edges, id)) {
1212 throw new Error("the plugin client requires an undeclared module: " + id);
1213 }
1214 var resolved = edges[id];
1215 if (resolved !== null) return load(resolved);
1216 if (hosts.indexOf(id) < 0) throw new Error("the plugin client requires an undeclared host service: " + id);
1217 return hostRequire(id);
1218 };
1219 }
1220 window.__ModuleLoader__.load({
1221 id: PLUGIN_ID,
1222 factory: function (require) {
1223 hostRequire = require;
1224 return load(ENTRY);
1225 }
1226 });
1227 })();
1228 "#;
1229
1230 fn dsh_bootstrap(
1231 selector: &str,
1232 closure: &DshClosure,
1233 verified: &[(String, Vec<u8>)],
1234 ) -> Result<Vec<u8>, UiFileError> {
1235 let quote = |text: &str| {
1236 serde_json::to_string(text).map_err(|error| UiFileError::Internal(error.to_string()))
1237 };
1238 let mut out = String::from(DSH_BOOTSTRAP_HEAD);
1239 for (path, bytes) in verified {
1240 let text = std::str::from_utf8(bytes)
1241 .map_err(|_| UiFileError::Invalid(format!("closure file '{path}' is not UTF-8")))?;
1242 out.push_str(" ");
1243 out.push_str(&quote(path)?);
1244 out.push_str(": function (module, exports, require) {\n");
1245 if path.ends_with(".json") {
1246 out.push_str("module.exports = JSON.parse(");
1247 out.push_str(&quote(text)?);
1248 out.push_str(");");
1249 } else {
1250 out.push_str(text);
1251 }
1252 out.push_str("\n},\n");
1253 }
1254 out.push_str(" };\n");
1255 out.push_str(&format!(
1256 " var PLUGIN_ID = {};\n var ENTRY = {};\n",
1257 quote(if closure.package.is_empty() {
1258 selector
1259 } else {
1260 &closure.package
1261 })?,
1262 quote(&closure.entry)?
1263 ));
1264 let imports = serde_json::to_string(&closure.imports)
1265 .map_err(|error| UiFileError::Internal(error.to_string()))?;
1266 let hosts = serde_json::to_string(&closure.host_provided)
1267 .map_err(|error| UiFileError::Internal(error.to_string()))?;
1268 out.push_str(&format!(
1269 " var imports = JSON.parse({});\n var hosts = JSON.parse({});\n",
1270 quote(&imports)?,
1271 quote(&hosts)?
1272 ));
1273 out.push_str(DSH_BOOTSTRAP_TAIL);
1274 Ok(out.into_bytes())
1275 }
1276
1277 enum PluginUiSource {
1278 Dsh {
1279 closure: DshClosure,
1280 declared: Vec<&'static (&'static str, DshSeat)>,
1281 },
1282 Native {
1283 raw_entry: String,
1284 },
1285 }
1286
1287 struct LoadedPluginUi {
1288 plugin: LoadedPlugin,
1289 grant: PluginUiGrant,
1290 source: PluginUiSource,
1291 }
1292
1293 fn load_plugin_ui(state: &RuntimeApiState, selector: &str) -> Result<LoadedPluginUi, ApiError> {
1294 let registry = registry_for_state(state);
1295 let plugin = registry
1296 .get(selector)
1297 .cloned()
1298 .ok_or_else(|| ApiError::not_found(format!("plugin '{selector}' not found")))?;
1299 if !plugin.active() {
1300 return Err(ApiError::bad_request(format!(
1301 "plugin '{}' must be active before loading its client UI",
1302 plugin.name()
1303 )));
1304 }
1305 let staged_root = plugin.staged_root.as_ref().ok_or_else(|| {
1306 ApiError::bad_request(format!(
1307 "plugin '{}' has no staged runtime snapshot",
1308 plugin.name()
1309 ))
1310 })?;
1311 let authority = registry
1312 .authority_for(selector)
1313 .ok_or_else(|| ApiError::bad_request("plugin UI has no reviewed authority"))?;
1314 let state_file = codewhale_plugins::registry::capture_plugin_state_authority(&authority, None)
1315 .map_err(|_| ui_stale_revision())?;
1316 codewhale_plugins::registry::verify_plugin_authority(&authority)
1317 .map_err(|_| ui_stale_revision())?;
1318 let validated =
1319 codewhale_plugins::manifest::PluginManifest::validate_from_path(&authority.staged_manifest)
1320 .map_err(|_| ui_stale_revision())?;
1321 if validated.content_hash != authority.content_hash
1322 || validated.capability_hash != authority.capability_hash
1323 {
1324 return Err(ui_stale_revision());
1325 }
1326 let metadata = std::fs::symlink_metadata(staged_root).map_err(|_| ui_stale_revision())?;
1327 if !metadata.is_dir() || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) {
1328 return Err(ui_stale_revision());
1329 }
1330 let (root, root_file) = codewhale_util::workspace_dir::open_workspace_directory(staged_root)
1331 .map_err(|_| ui_stale_revision())?;
1332 if root != validated.canonical_root {
1333 return Err(ui_stale_revision());
1334 }
1335 let mut grant = PluginUiGrant {
1336 service: Default::default(),
1337 selector: selector.to_string(),
1338 authority,
1339 state_file: Arc::new(state_file),
1340 root,
1341 root_file: Arc::new(root_file),
1342 ui_prefix: PathBuf::new(),
1343 file_hashes: Arc::new(validated.file_hashes),
1344 expires: std::time::Instant::now() + std::time::Duration::from_secs(3600),
1345 dsh: None,
1346 };
1347 let mut found = None;
1348 for candidate in ["package.json", "source/package.json"] {
1349 let relative = FsPath::new(candidate);
1350 if grant.file_hashes.contains_key(relative) {
1351 let bytes = verified_ui_file(&grant, relative)
1352 .map_err(|error| ui_file_refusal(&plugin, candidate, error))?;
1353 found = Some((relative.to_path_buf(), bytes));
1354 break;
1355 }
1356 }
1357 let (manifest_path, bytes) = found.ok_or_else(|| ApiError::not_found(format!("plugin '{}' declares no dsh.client UI; package.json is absent from its staged bundle and source/ directory", plugin.name())).with_code("plugin_ui_not_declared"))?;
1358 let manifest: Value = serde_json::from_slice(&bytes).map_err(|error| {
1359 ApiError::bad_request(format!(
1360 "plugin '{}' {} is not valid JSON: {error}",
1361 plugin.name(),
1362 ui_relative_display(&manifest_path)
1363 ))
1364 })?;
1365 if manifest
1366 .get("dsh")
1367 .and_then(|dsh| dsh.get("client"))
1368 .is_none_or(Value::is_null)
1369 {
1370 return Err(ApiError::not_found(format!("plugin '{}' declares no dsh.client UI in {}; add dsh.client and exports[\"./client\"] to expose client assets", plugin.name(), ui_relative_display(&manifest_path))).with_code("plugin_ui_not_declared"));
1371 }
1372 let conversion_path = FsPath::new("CONVERSION.json");
1373 let mut closure = None;
1374 if grant.file_hashes.contains_key(conversion_path) {
1375 let bytes = verified_ui_file(&grant, conversion_path)
1376 .map_err(|error| ui_file_refusal(&plugin, "CONVERSION.json", error))?;
1377 let conversion: Value = serde_json::from_slice(&bytes).map_err(|_| {
1378 ApiError::bad_request("plugin UI conversion report is invalid")
1379 .with_code("plugin_ui_unsupported")
1380 })?;
1381 if conversion.get("schema").and_then(Value::as_str)
1382 == Some("codewhale.plugin-conversion.v1")
1383 && conversion
1384 .pointer("/source/dialect")
1385 .and_then(Value::as_str)
1386 == Some("dsh")
1387 {
1388 closure = Some(dsh_client_closure(&conversion).ok_or_else(|| {
1389 ui_unsupported(
1390 "this DSH client UI was not converted and is not supported by Codewhale yet",
1391 )
1392 })?);
1393 }
1394 }
1395 grant.ui_prefix = manifest_path
1396 .parent()
1397 .unwrap_or(FsPath::new(""))
1398 .to_path_buf();
1399 if let Some(closure) = closure {
1400 let verified = verify_dsh_closure(&grant, &closure)
1401 .map_err(|error| ui_file_refusal(&plugin, "client closure", error))?;
1402 if let Some(reason) = dsh_closure_unsupported(&closure, &verified) {
1403 return Err(ui_unsupported(format!(
1404 "plugin '{}': {reason}",
1405 plugin.name()
1406 )));
1407 }
1408 let declared = declared_dsh_keys(&verified);
1409 return Ok(LoadedPluginUi {
1410 plugin,
1411 grant,
1412 source: PluginUiSource::Dsh { closure, declared },
1413 });
1414 }
1415 let raw_entry = ui_client_entry(&manifest).unwrap_or_else(|| "client.js".into());
1416 Ok(LoadedPluginUi {
1417 plugin,
1418 grant,
1419 source: PluginUiSource::Native { raw_entry },
1420 })
1421 }
1422
1423 fn admit_native_seat(
1424 plugin: &LoadedPlugin,
1425 seat: &str,
1426 dsh_slot: Option<&str>,
1427 ) -> Result<(), ApiError> {
1428 if seat != PLUGIN_UI_SLOT || dsh_slot.is_some() {
1429 return Err(seat_not_admitted(plugin, seat, dsh_slot));
1430 }
1431 Ok(())
1432 }
1433
1434 fn verified_native_entry(
1435 plugin: &LoadedPlugin,
1436 grant: &PluginUiGrant,
1437 raw: &str,
1438 ) -> Result<PathBuf, ApiError> {
1439 let relative = ui_relative_path(raw).map_err(|reason| {
1440 ApiError::bad_request(format!(
1441 "plugin '{}' dsh.client entry '{raw}' is invalid: {reason}",
1442 plugin.name()
1443 ))
1444 })?;
1445 verified_ui_file(grant, &grant.ui_prefix.join(&relative))
1446 .map_err(|error| ui_file_refusal(plugin, &ui_relative_display(&relative), error))?;
1447 Ok(relative)
1448 }
1449
1450 fn prepare_plugin_ui(
1451 state: &RuntimeApiState,
1452 selector: &str,
1453 seat: &str,
1454 dsh_slot: Option<&str>,
1455 ) -> Result<PreparedPluginUi, ApiError> {
1456 let LoadedPluginUi {
1457 plugin,
1458 mut grant,
1459 source,
1460 } = load_plugin_ui(state, selector)?;
1461 match source {
1462 PluginUiSource::Dsh { closure, declared } => {
1463 let key = admit_dsh_seat(&plugin, seat, dsh_slot, &declared)?;
1464 grant.dsh = Some(Arc::new(DshServed { closure }));
1465 admit_ui_grant(state, &grant)?;
1466 Ok(PreparedPluginUi {
1467 entry: DSH_BOOTSTRAP_ENTRY.to_string(),
1468 dsh_slot: Some(key),
1469 bridge: Some(dsh_bridge()?),
1470 grant,
1471 })
1472 }
1473 PluginUiSource::Native { raw_entry } => {
1474 admit_native_seat(&plugin, seat, dsh_slot)?;
1475 let relative = verified_native_entry(&plugin, &grant, &raw_entry)?;
1476 admit_ui_grant(state, &grant)?;
1477 Ok(PreparedPluginUi {
1478 entry: ui_relative_display(&relative),
1479 dsh_slot: None,
1480 bridge: None,
1481 grant,
1482 })
1483 }
1484 }
1485 }
1486
1487 fn admitted_ui_slots(
1488 state: &RuntimeApiState,
1489 selector: &str,
1490 ) -> Result<Vec<PluginUiSlotDeclaration>, ApiError> {
1491 let LoadedPluginUi {
1492 plugin,
1493 grant,
1494 source,
1495 } = load_plugin_ui(state, selector)?;
1496 let mut slots = Vec::new();
1497 match &source {
1498 PluginUiSource::Dsh { declared, .. } => {
1499 for seat in PLUGIN_UI_SEATS {
1500 for (key, _) in declared.iter().copied() {
1501 if admit_dsh_seat(&plugin, seat, Some(*key), declared).is_ok() {
1502 slots.push(PluginUiSlotDeclaration {
1503 slot: seat,
1504 dsh_slot: Some((*key).to_string()),
1505 });
1506 }
1507 }
1508 }
1509 }
1510 PluginUiSource::Native { raw_entry } => {
1511 verified_native_entry(&plugin, &grant, raw_entry)?;
1512 slots.extend(
1513 PLUGIN_UI_SEATS
1514 .into_iter()
1515 .filter(|seat| admit_native_seat(&plugin, seat, None).is_ok())
1516 .map(|slot| PluginUiSlotDeclaration {
1517 slot,
1518 dsh_slot: None,
1519 }),
1520 );
1521 }
1522 }
1523 admit_ui_grant(state, &grant)?;
1524 Ok(slots)
1525 }
1526
1527 fn plugin_ui_base(
1528 state: &RuntimeApiState,
1529 selector: &str,
1530 headers: &HeaderMap,
1531 uri: &Uri,
1532 ) -> Result<String, ApiError> {
1533 let raw = headers
1534 .get(header::HOST)
1535 .and_then(|value| value.to_str().ok())
1536 .or_else(|| uri.authority().map(Authority::as_str))
1537 .ok_or_else(|| {
1538 ApiError::bad_request(
1539 "plugin UI requires a loopback Host header so the sandboxed client can build an absolute asset base",
1540 )
1541 })?;
1542 if raw.is_empty()
1543 || raw.contains('@')
1544 || raw.contains('/')
1545 || raw.contains('?')
1546 || raw.contains('#')
1547 || raw.bytes().any(|byte| byte <= b' ' || byte == 0x7f)
1548 {
1549 return Err(ApiError::bad_request(
1550 "plugin UI Host must be a loopback authority with no credentials, path, query or fragment",
1551 ));
1552 }
1553 let authority: Authority = raw
1554 .parse()
1555 .map_err(|_| ApiError::bad_request("plugin UI Host is not a valid loopback authority"))?;
1556 if !super::host_header_is_loopback(raw) {
1557 return Err(ApiError::bad_request(format!(
1558 "plugin UI Host '{raw}' is not a loopback host; expected 127.0.0.1, [::1] or localhost"
1559 )));
1560 }
1561 let port_specified = if let Some(rest) = raw.strip_prefix('[') {
1562 match rest.split_once(']') {
1563 Some((_, "")) => false,
1564 Some((_, after)) if after.starts_with(':') => true,
1565 _ => {
1566 return Err(ApiError::bad_request(
1567 "plugin UI Host must be a loopback authority with no credentials, path, query or fragment",
1568 ));
1569 }
1570 }
1571 } else {
1572 raw.contains(':')
1573 };
1574 let host_port = authority.port_u16().filter(|port| *port != 0);
1575 if port_specified && host_port.is_none() {
1576 return Err(ApiError::bad_request(
1577 "plugin UI Host must carry a numeric listener port",
1578 ));
1579 }
1580 let host = authority.host();
1581 let host = if host.contains(':') {
1582 format!("[{host}]")
1583 } else {
1584 host.to_string()
1585 };
1586 let port = host_port
1587 .or_else(|| (state.bind_port != 0).then_some(state.bind_port))
1588 .ok_or_else(|| ApiError::bad_request("plugin UI Host is missing the listener port"))?;
1589 Ok(format!(
1590 "http://{host}:{port}/v1/apps/plugins/{}/ui/",
1591 urlencoding::encode(selector)
1592 ))
1593 }
1594
1595 /// Execute an install/update/uninstall through the reviewed mutation
1596 /// controller using the server's own config for network policy, then
1597 /// invalidate the MCP pool so merged plugin servers reload on next use.
1598 async fn run_plugin_mutation(
1599 state: &RuntimeApiState,
1600 request: PluginMutationRequest,
1601 ) -> Result<PluginMutationResponse, PolicyOrApiError> {
1602 let network = {
1603 let config = state.config.read();
1604 config
1605 .network
1606 .clone()
1607 .map(codewhale_net::network_policy::NetworkPolicy::from)
1608 .unwrap_or_default()
1609 };
1610 let ctx = PluginMutationContext {
1611 network: &network,
1612 max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
1613 };
1614 let mut registry = (*registry_for_state(state)).clone();
1615 let receipt = codewhale_plugins::mutation::execute(request, &ctx, &mut registry)
1616 .await
1617 .map_err(|error| {
1618 if error
1619 .downcast_ref::<codewhale_plugins::install::PluginNameConflict>()
1620 .is_some()
1621 || error
1622 .downcast_ref::<codewhale_plugins::install::PluginContentMismatch>()
1623 .is_some()
1624 || error
1625 .downcast_ref::<codewhale_plugins::install::PluginArchiveMismatch>()
1626 .is_some()
1627 {
1628 ApiError::conflict(format!("plugin mutation failed: {error:#}"))
1629 } else {
1630 ApiError::internal(format!("plugin mutation failed: {error:#}"))
1631 }
1632 })?;
1633
1634 // Policy outcomes are not server errors: report the blocked host with
1635 // the same wording the skill lifecycle API uses.
1636 let outcome = match &receipt.outcome {
1637 PluginMutationOutcome::NeedsApproval(host) => {
1638 return Err(PolicyOrApiError::Policy {
1639 message: format!(
1640 "network access to '{host}' requires explicit approval; \
1641 approve the host in your network policy before installing this plugin"
1642 ),
1643 code: "network_approval_required",
1644 host: host.clone(),
1645 });
1646 }
1647 PluginMutationOutcome::NetworkDenied(host) => {
1648 return Err(PolicyOrApiError::Policy {
1649 message: format!(
1650 "network access to '{host}' was denied by the active network policy"
1651 ),
1652 code: "network_denied",
1653 host: host.clone(),
1654 });
1655 }
1656 PluginMutationOutcome::Installed => "installed",
1657 PluginMutationOutcome::Updated => "updated",
1658 PluginMutationOutcome::NoChange => "no_change",
1659 PluginMutationOutcome::Uninstalled => "uninstalled",
1660 };
1661
1662 state.plugin_ui_grants.revoke_selector(&receipt.name);
1663
1664 // Mutations can change merged plugin MCP servers. Advance the existing
1665 // shared generation so each captured workspace pool reloads on next use.
1666 state
1667 .workspace_scopes
1668 .mcp_generation
1669 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1670
1671 let registry = registry_for_state(state);
1672 let plugin = registry
1673 .get(receipt.name.as_str())
1674 .map(|plugin| plugin_summary(plugin, Some(&registry)));
1675 let note = match receipt.outcome {
1676 PluginMutationOutcome::Installed => Some(
1677 "Installed disabled and untrusted. Open this plugin's detail \
1678 to review its capabilities, then trust and enable it.",
1679 ),
1680 PluginMutationOutcome::Updated => Some(
1681 "Installed content refreshed. Review its current capabilities \
1682 and trust it if needed before enabling.",
1683 ),
1684 _ => None,
1685 };
1686 Ok(PluginMutationResponse {
1687 outcome,
1688 name: receipt.name.clone(),
1689 path: receipt.path.as_ref().map(|p| p.display().to_string()),
1690 content_hash: receipt.installed_content_hash.or(receipt.content_hash),
1691 note,
1692 plugin,
1693 })
1694 }
1695
1696 /// Run a registry state mutation (`trust`/`enable`/`restage`/`disable`/`revoke`)
1697 /// against a fresh registry, then invalidate the MCP pool. Trust is the only
1698 /// one with a precondition beyond the registry's own checks: the request
1699 /// token must match the bundle's review token.
1700 async fn run_registry_mutation(
1701 state: &RuntimeApiState,
1702 selector: &str,
1703 mutation: RegistryMutation<'_>,
1704 ) -> Result<PluginActionResponse, ApiError> {
1705 let registry = registry_for_state(state);
1706 if let RegistryMutation::Trust { token, .. } = &mutation {
1707 let Some(plugin) = registry.get(selector) else {
1708 return Err(ApiError::not_found(format!(
1709 "plugin '{selector}' not found"
1710 )));
1711 };
1712 if token != &plugin.review_token() {
1713 return Err(ApiError::bad_request(
1714 "review token does not match this bundle's content and capability set; \
1715 reload this plugin's detail and confirm the current review token",
1716 ));
1717 }
1718 }
1719
1720 let action = match mutation {
1721 RegistryMutation::Trust { .. } => "trusted",
1722 RegistryMutation::Enable => "enabled",
1723 RegistryMutation::Restage => "restaged",
1724 RegistryMutation::Disable => "disabled",
1725 RegistryMutation::Revoke => "trust-revoked",
1726 };
1727
1728 let mut registry = (*registry).clone();
1729 let result = match mutation {
1730 RegistryMutation::Trust {
1731 host_services_token,
1732 ..
1733 } => registry.trust_reviewed(
1734 selector,
1735 ReviewApproval {
1736 approved_by: PluginApprover::person(PersonVia::App),
1737 host_services: host_services_token.map(str::to_owned),
1738 },
1739 ),
1740 RegistryMutation::Enable => {
1741 registry.enable_by(selector, PluginApprover::person(PersonVia::App))
1742 }
1743 RegistryMutation::Restage => registry.restage(selector),
1744 RegistryMutation::Disable => registry.disable(selector),
1745 RegistryMutation::Revoke => registry.revoke_trust(selector),
1746 };
1747 result.map_err(|error| {
1748 ApiError::conflict(format!("{action} failed for '{selector}': {error}"))
1749 })?;
1750
1751 state.plugin_ui_grants.revoke_selector(selector);
1752
1753 state
1754 .workspace_scopes
1755 .mcp_generation
1756 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1757
1758 let fresh = registry_for_state(state);
1759 codewhale_engine::extension_host::plugins_changed(Arc::clone(&fresh));
1760 let Some(plugin) = fresh.get(selector) else {
1761 return Ok(PluginActionResponse {
1762 name: selector.to_string(),
1763 action,
1764 state: "removed",
1765 note: None,
1766 });
1767 };
1768 let note = match (action, plugin.state_label()) {
1769 ("enabled", "enabled-untrusted") => Some(
1770 "enabled-untrusted: the bundle is not trusted; open this plugin's \
1771 detail, review its capabilities and trust it first",
1772 ),
1773 ("enabled", _) => {
1774 let inactive = plugin.inventory.unsupported_labels();
1775 (!inactive.is_empty()).then_some(
1776 "supported declarative components are active; inventory-only \
1777 capabilities stay inactive",
1778 )
1779 }
1780 _ => None,
1781 };
1782 Ok(PluginActionResponse {
1783 name: selector.to_string(),
1784 action,
1785 state: plugin.state_label(),
1786 note,
1787 })
1788 }
1789
1790 enum RegistryMutation<'a> {
1791 Trust {
1792 token: &'a str,
1793 host_services_token: Option<&'a str>,
1794 },
1795 Enable,
1796 Restage,
1797 Disable,
1798 Revoke,
1799 }
1800
1801 fn open_marketplace_store(state: &RuntimeApiState) -> Result<MarketplaceStore, ApiError> {
1802 MarketplaceStore::open(registry_for_state(state).state_path()).ok_or_else(|| {
1803 ApiError::internal(
1804 "this plugin registry has no persistence store; \
1805 marketplace catalogs cannot be saved",
1806 )
1807 })
1808 }
1809
1810 fn load_marketplace_state(
1811 store: &MarketplaceStore,
1812 ) -> Result<codewhale_plugins::marketplace::store::MarketplaceState, ApiError> {
1813 store.load().map_err(|error| {
1814 ApiError::internal(format!(
1815 "marketplace state is fail-closed and will not be rewritten: {error}"
1816 ))
1817 })
1818 }
1819
1820 // ---------------------------------------------------------------------------
1821 // Marketplace DTOs
1822 // ---------------------------------------------------------------------------
1823
1824 #[derive(Debug, Serialize)]
1825 pub(super) struct MarketplaceInstallPlanEntry {
1826 pub(super) installable: bool,
1827 pub(super) spec: Option<String>,
1828 pub(super) source_kind: Option<String>,
1829 pub(super) reason: Option<String>,
1830 }
1831
1832 #[derive(Debug, Serialize)]
1833 pub(super) struct MarketplaceCandidateEntry {
1834 pub(super) name: String,
1835 pub(super) display_name: Option<String>,
1836 pub(super) icon: Option<String>,
1837 pub(super) platforms: Vec<String>,
1838 pub(super) description: Option<String>,
1839 pub(super) version: Option<String>,
1840 pub(super) author: Option<String>,
1841 pub(super) homepage: Option<String>,
1842 pub(super) repository: Option<String>,
1843 pub(super) license: Option<String>,
1844 pub(super) keywords: Vec<String>,
1845 pub(super) categories: Vec<String>,
1846 pub(super) tier: String,
1847 pub(super) compatibility: Option<&'static str>,
1848 pub(super) install: MarketplaceInstallPlanEntry,
1849 /// Name occupancy, not an assertion that the catalog and local bytes match.
1850 pub(super) existing_plugin: Option<PluginSummaryEntry>,
1851 pub(super) diagnostics: Vec<PluginDiagnosticEntry>,
1852 }
1853
1854 #[derive(Debug, Serialize)]
1855 pub(super) struct MarketplaceCatalogEntry {
1856 pub(super) name: String,
1857 pub(super) display_name: Option<String>,
1858 pub(super) description: Option<String>,
1859 pub(super) format: &'static str,
1860 pub(super) tier: String,
1861 pub(super) added_at: String,
1862 pub(super) source_path: String,
1863 pub(super) candidate_count: usize,
1864 pub(super) warning_count: usize,
1865 pub(super) error_count: usize,
1866 pub(super) diagnostics: Vec<PluginDiagnosticEntry>,
1867 pub(super) candidates: Vec<MarketplaceCandidateEntry>,
1868 }
1869
1870 #[derive(Debug, Serialize)]
1871 pub(super) struct MarketplacesResponse {
1872 pub(super) marketplaces: Vec<MarketplaceCatalogEntry>,
1873 }
1874
1875 #[derive(Debug, Serialize)]
1876 pub(super) struct MarketplaceActionResponse {
1877 pub(super) name: String,
1878 pub(super) action: &'static str,
1879 pub(super) candidate_count: Option<usize>,
1880 pub(super) warning_count: Option<usize>,
1881 }
1882
1883 fn marketplace_candidate_entry(
1884 entry: &codewhale_plugins::marketplace::store::StoredMarketplaceCatalog,
1885 candidate: &codewhale_plugins::marketplace::types::MarketplaceCandidate,
1886 registry: &codewhale_plugins::PluginRegistry,
1887 ) -> MarketplaceCandidateEntry {
1888 let mut existing_plugin = None;
1889 let install = match resolve_candidate_install(entry, candidate, registry) {
1890 CatalogInstallResolution::Supported { spec, source_kind } => MarketplaceInstallPlanEntry {
1891 installable: true,
1892 spec: Some(spec),
1893 source_kind: Some(source_kind),
1894 reason: None,
1895 },
1896 CatalogInstallResolution::AlreadyPresent { plugin, reason } => {
1897 existing_plugin = Some(plugin_summary(plugin, Some(registry)));
1898 MarketplaceInstallPlanEntry {
1899 installable: false,
1900 spec: None,
1901 source_kind: None,
1902 reason: Some(reason),
1903 }
1904 }
1905 CatalogInstallResolution::Unsupported { reason } => MarketplaceInstallPlanEntry {
1906 installable: false,
1907 spec: None,
1908 source_kind: None,
1909 reason: Some(reason),
1910 },
1911 CatalogInstallResolution::HasErrors { diagnostics } => MarketplaceInstallPlanEntry {
1912 installable: false,
1913 spec: None,
1914 source_kind: None,
1915 reason: Some(format!("candidate has parse errors: {diagnostics}")),
1916 },
1917 };
1918 MarketplaceCandidateEntry {
1919 name: candidate.name.clone(),
1920 display_name: candidate.display_name.clone(),
1921 icon: candidate.icon.clone(),
1922 platforms: candidate
1923 .when
1924 .as_ref()
1925 .and_then(|when| when.os.clone())
1926 .unwrap_or_default(),
1927 description: candidate.description.clone(),
1928 version: candidate.version.clone(),
1929 author: candidate.author.clone(),
1930 homepage: candidate.homepage.clone(),
1931 repository: candidate.repository.clone(),
1932 license: candidate.license.clone(),
1933 keywords: candidate.keywords.clone(),
1934 categories: candidate.categories.clone(),
1935 tier: candidate.provenance.tier.to_string(),
1936 compatibility: candidate.compatibility.as_ref().map(|c| c.as_str()),
1937 install,
1938 existing_plugin,
1939 diagnostics: candidate
1940 .diagnostics
1941 .iter()
1942 .map(|d| PluginDiagnosticEntry {
1943 level: match d.level {
1944 PluginDiagnosticLevel::Warning => "warning",
1945 PluginDiagnosticLevel::Error => "error",
1946 },
1947 code: d.code.to_string(),
1948 message: d.message.clone(),
1949 path: None,
1950 })
1951 .collect(),
1952 }
1953 }
1954
1955 fn marketplace_catalog_entry(
1956 name: &str,
1957 entry: &codewhale_plugins::marketplace::store::StoredMarketplaceCatalog,
1958 registry: &codewhale_plugins::PluginRegistry,
1959 ) -> MarketplaceCatalogEntry {
1960 MarketplaceCatalogEntry {
1961 name: name.to_string(),
1962 display_name: entry.catalog.display_name.clone(),
1963 description: entry.catalog.description.clone(),
1964 format: entry.catalog.format.as_str(),
1965 tier: entry.catalog.provenance.tier.to_string(),
1966 added_at: entry.added_at.clone(),
1967 source_path: entry.source_path.clone(),
1968 candidate_count: entry.catalog.total_candidates(),
1969 warning_count: entry.catalog.warning_count(),
1970 error_count: entry.catalog.error_count(),
1971 diagnostics: entry
1972 .catalog
1973 .diagnostics
1974 .iter()
1975 .map(|d| PluginDiagnosticEntry {
1976 level: match d.level {
1977 PluginDiagnosticLevel::Warning => "warning",
1978 PluginDiagnosticLevel::Error => "error",
1979 },
1980 code: d.code.to_string(),
1981 message: d.message.clone(),
1982 path: None,
1983 })
1984 .collect(),
1985 candidates: entry
1986 .catalog
1987 .candidates
1988 .iter()
1989 .map(|candidate| marketplace_candidate_entry(entry, candidate, registry))
1990 .collect(),
1991 }
1992 }
1993
1994 // ---------------------------------------------------------------------------
1995 // Handlers — plugins
1996 // ---------------------------------------------------------------------------
1997
1998 /// `GET /v1/apps/plugins`
1999 pub(super) async fn list_plugins(
2000 State(state): State<RuntimeApiState>,
2001 ) -> Result<Json<PluginsResponse>, ApiError> {
2002 let registry = registry_for_state(&state);
2003 Ok(Json(PluginsResponse {
2004 workspace: state.workspace.display().to_string(),
2005 plugins: registry
2006 .list()
2007 .iter()
2008 .map(|p| plugin_summary(p, Some(&registry)))
2009 .collect(),
2010 registry_diagnostics: registry
2011 .diagnostics()
2012 .iter()
2013 .map(diagnostic_entry)
2014 .collect(),
2015 validation_clean: registry.validation_is_clean(),
2016 }))
2017 }
2018
2019 /// `GET /v1/apps/plugins/{selector}`
2020 pub(super) async fn get_plugin(
2021 State(state): State<RuntimeApiState>,
2022 Path(selector): Path<String>,
2023 ) -> Result<Json<PluginDetailResponse>, ApiError> {
2024 let registry = registry_for_state(&state);
2025 let plugin = registry
2026 .get(&selector)
2027 .cloned()
2028 .ok_or_else(|| ApiError::not_found(format!("plugin '{selector}' not found")))?;
2029 let mut detail = plugin_detail(&plugin, Some(&registry)).await;
2030 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
2031 let state_for_slots = state.clone();
2032 let slots = tokio::task::spawn_blocking(move || {
2033 let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy);
2034 admitted_ui_slots(&state_for_slots, &selector)
2035 })
2036 .await
2037 .map_err(|_| ApiError::internal("plugin UI slot listing failed"))?;
2038 match slots {
2039 Ok(slots) => detail.ui_slots = slots,
2040 Err(error) if error.code == Some("plugin_ui_not_declared") => {}
2041 Err(error) => {
2042 detail.ui_slots_unavailable = Some(PluginUiSlotsUnavailable {
2043 code: error.code,
2044 message: error.message,
2045 });
2046 }
2047 }
2048 Ok(Json(detail))
2049 }
2050
2051 pub(super) async fn get_plugin_ui(
2052 State(state): State<RuntimeApiState>,
2053 ConnectInfo(peer): ConnectInfo<SocketAddr>,
2054 Path(selector): Path<String>,
2055 Query(query): Query<PluginUiQuery>,
2056 headers: HeaderMap,
2057 uri: Uri,
2058 ) -> Result<Json<PluginUiSlotResponse>, ApiError> {
2059 if !peer.ip().is_loopback() {
2060 return Err(ApiError::forbidden(
2061 "plugin UI metadata is available only from loopback",
2062 ));
2063 }
2064 let slot = query.slot.ok_or_else(|| {
2065 ApiError::bad_request(format!(
2066 "the 'slot' query parameter is required; seats: {}",
2067 PLUGIN_UI_SEATS.join(", ")
2068 ))
2069 .with_code("plugin_ui_seat_unknown")
2070 })?;
2071 if !PLUGIN_UI_SEATS.contains(&slot.as_str()) {
2072 return Err(ApiError::bad_request(format!(
2073 "slot '{slot}' is not a plugin UI seat; seats: {}",
2074 PLUGIN_UI_SEATS.join(", ")
2075 ))
2076 .with_code("plugin_ui_seat_unknown"));
2077 }
2078 if let Some(key) = &query.dsh_slot
2079 && !valid_dsh_slot_key(key)
2080 {
2081 return Err(ApiError::bad_request(
2082 "dsh_slot must be 1 to 128 characters of letters, digits, '.', '_' or '-', starting with a letter or digit",
2083 )
2084 .with_code("plugin_ui_dsh_slot_invalid"));
2085 }
2086 let state_for_prepare = state.clone();
2087 let selector_for_prepare = selector.clone();
2088 let seat = slot.clone();
2089 let requested_key = query.dsh_slot.clone();
2090 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
2091 let prepared = tokio::task::spawn_blocking(move || {
2092 let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy);
2093 prepare_plugin_ui(
2094 &state_for_prepare,
2095 &selector_for_prepare,
2096 &seat,
2097 requested_key.as_deref(),
2098 )
2099 })
2100 .await
2101 .map_err(|_| ApiError::internal("plugin UI preparation failed"))??;
2102 let base = plugin_ui_base(&state, &selector, &headers, &uri)?;
2103 let revision = state.plugin_ui_grants.insert(prepared.grant);
2104 Ok(Json(PluginUiSlotResponse {
2105 slot,
2106 dsh_slot: prepared.dsh_slot,
2107 bridge: prepared.bridge,
2108 base,
2109 entry: prepared.entry,
2110 revision,
2111 }))
2112 }
2113
2114 const MAX_PLUGIN_ROUTE_RESPONSE_HEADERS: usize = 64;
2115 const MAX_PLUGIN_ROUTE_HEADER_VALUE_BYTES: usize = 8 * 1024;
2116
2117 fn grant_for_request(
2118 state: &RuntimeApiState,
2119 selector: &str,
2120 headers: &HeaderMap,
2121 ) -> Result<(PluginUiGrant, String), ApiError> {
2122 let mut values = headers.get_all(header::IF_MATCH).iter();
2123 let first = values.next().ok_or_else(|| ApiError {
2124 status: StatusCode::PRECONDITION_REQUIRED,
2125 message: "plugin UI revision is required".into(),
2126 code: None,
2127 })?;
2128 if values.next().is_some() {
2129 return Err(ui_stale_revision());
2130 }
2131 let revision = first.to_str().map_err(|_| ui_stale_revision())?.to_string();
2132 let grant = state
2133 .plugin_ui_grants
2134 .get(&revision)
2135 .ok_or_else(ui_stale_revision)?;
2136 if grant.selector != selector || grant.authority.workspace != state.workspace {
2137 return Err(ui_stale_revision());
2138 }
2139 Ok((grant, revision))
2140 }
2141
2142 fn allowlisted_plugin_route_request_headers(headers: &HeaderMap) -> Vec<(String, String)> {
2143 let mut out = Vec::new();
2144 for (name, value) in headers {
2145 let lower = name.as_str().to_ascii_lowercase();
2146 let allowed = matches!(
2147 lower.as_str(),
2148 "content-type" | "accept" | "accept-language"
2149 ) || (lower.starts_with("x-")
2150 && !lower.starts_with("x-codewhale-")
2151 && !lower.starts_with("x-deepseek-")
2152 && !lower.starts_with("x-forwarded-")
2153 && !lower.starts_with("x-auth-")
2154 && lower != "x-real-ip"
2155 && lower != "x-api-key");
2156 if !allowed {
2157 continue;
2158 }
2159 if let Ok(text) = value.to_str() {
2160 out.push((lower, text.to_string()));
2161 }
2162 }
2163 out
2164 }
2165
2166 fn is_stripped_plugin_route_response_header(name: &str) -> bool {
2167 let lower = name.to_ascii_lowercase();
2168 matches!(
2169 lower.as_str(),
2170 "set-cookie"
2171 | "authorization"
2172 | "cookie"
2173 | "www-authenticate"
2174 | "proxy-authenticate"
2175 | "content-security-policy"
2176 | "content-security-policy-report-only"
2177 | "referrer-policy"
2178 | "location"
2179 | "content-length"
2180 | "transfer-encoding"
2181 | "connection"
2182 | "keep-alive"
2183 | "upgrade"
2184 | "strict-transport-security"
2185 | "x-frame-options"
2186 | "cache-control"
2187 | "x-content-type-options"
2188 ) || lower.starts_with("access-control-")
2189 }
2190
2191 async fn validated_service_grant(
2192 state: &RuntimeApiState,
2193 selector: &str,
2194 headers: &HeaderMap,
2195 ) -> Result<
2196 (
2197 PluginUiGrant,
2198 String,
2199 Arc<codewhale_plugins::PluginRegistry>,
2200 ),
2201 ApiError,
2202 > {
2203 let (grant, revision) = grant_for_request(state, selector, headers)?;
2204 let state = state.clone();
2205 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
2206 tokio::task::spawn_blocking(move || {
2207 let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy);
2208 codewhale_plugins::registry::verify_plugin_authority(&grant.authority)
2209 .map_err(|_| ui_stale_revision())?;
2210 let registry = admit_ui_grant(&state, &grant)?;
2211 if state.plugin_ui_grants.get(&revision).is_none() {
2212 return Err(ui_stale_revision());
2213 }
2214 Ok((grant, revision, registry))
2215 })
2216 .await
2217 .map_err(|_| ApiError::internal("plugin service check failed"))?
2218 }
2219
2220 pub(super) async fn get_plugin_service(
2221 State(state): State<RuntimeApiState>,
2222 ConnectInfo(peer): ConnectInfo<SocketAddr>,
2223 Path(selector): Path<String>,
2224 headers: HeaderMap,
2225 ) -> Result<Json<Value>, ApiError> {
2226 if !peer.ip().is_loopback() {
2227 return Err(ApiError::forbidden(
2228 "plugin service state is available only from loopback",
2229 ));
2230 }
2231 let (grant, revision, registry) = validated_service_grant(&state, &selector, &headers).await?;
2232 let plugin = registry.get(&selector).ok_or_else(ui_stale_revision)?;
2233 let (service_state, reason) = if plugin.inventory.native == 0 {
2234 ("not_declared", None)
2235 } else if !codewhale_plugins::activation::extension_host_policy_enabled() {
2236 ("disabled", None)
2237 } else {
2238 codewhale_engine::extension_host::manager().native_service_status(&grant.authority)
2239 };
2240 let mut payload = serde_json::json!({"revision":revision,"state":service_state});
2241 if let Some(reason) = reason {
2242 payload["reason"] = serde_json::json!(reason);
2243 }
2244 Ok(Json(payload))
2245 }
2246
2247 pub(super) async fn plugin_route_bridge(
2248 State(state): State<RuntimeApiState>,
2249 ConnectInfo(peer): ConnectInfo<SocketAddr>,
2250 Path((selector, path)): Path<(String, String)>,
2251 RawQuery(raw_query): RawQuery,
2252 method: axum::http::Method,
2253 headers: HeaderMap,
2254 body: Body,
2255 ) -> Result<Response, ApiError> {
2256 if !peer.ip().is_loopback() {
2257 return Err(ApiError::forbidden(
2258 "plugin routes are available only from loopback",
2259 ));
2260 }
2261 let (grant, revision, registry) = validated_service_grant(&state, &selector, &headers).await?;
2262 if grant.dsh.is_none() {
2263 return Err(ApiError::forbidden(
2264 "this plugin UI grant has no DSH client and no plugin routes",
2265 )
2266 .with_code("plugin_route_not_admitted"));
2267 }
2268 let authority = grant.authority.clone();
2269 let service = grant.service.clone();
2270 let expires = grant.expires;
2271 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
2272 let relative = ui_relative_path(&path).map_err(|reason| {
2273 ApiError::bad_request(format!("plugin route path '{path}' is invalid: {reason}"))
2274 })?;
2275 if !DSH_ROUTE_METHODS.contains(&method.as_str()) {
2276 return Err(ApiError {
2277 status: StatusCode::METHOD_NOT_ALLOWED,
2278 message: format!("plugin routes do not accept {method}"),
2279 code: None,
2280 });
2281 }
2282 let max_req = codewhale_engine::extension_host::MAX_PLUGIN_ROUTE_REQUEST_BYTES;
2283 let body_bytes = to_bytes(body, max_req).await.map_err(|_| {
2284 ApiError::payload_too_large("plugin route request body exceeds the 4 MiB limit")
2285 })?;
2286 let request = codewhale_engine::extension_host::PluginRouteRequest {
2287 method: method.as_str().to_string(),
2288 path: format!("/{}", ui_relative_display(&relative)),
2289 query: raw_query.filter(|q| !q.is_empty()),
2290 headers: allowlisted_plugin_route_request_headers(&headers),
2291 body: body_bytes.to_vec(),
2292 };
2293 if policy
2294 && registry
2295 .get(&selector)
2296 .is_some_and(|plugin| plugin.inventory.native > 0)
2297 {
2298 service
2299 .get_or_try_init(|| async {
2300 if state.plugin_ui_grants.get(&revision).is_none() {
2301 return Err(ui_stale_revision());
2302 }
2303 let host = codewhale_engine::extension_host::manager();
2304 let attachment = host.attach_plugin_route(registry, authority.clone());
2305 attachment.reconcile().await.map_err(|_| ApiError {
2306 status: StatusCode::SERVICE_UNAVAILABLE,
2307 message: "the plugin service could not start".into(),
2308 code: Some("plugin_host_unavailable"),
2309 })?;
2310 let grants = Arc::downgrade(&state.plugin_ui_grants);
2311 let expiry_revision = revision.clone();
2312 let (cancel, cancelled) = tokio::sync::oneshot::channel();
2313 tokio::spawn(async move {
2314 tokio::select! {
2315 () = tokio::time::sleep_until(expires.into()) => {
2316 if let Some(grants) = grants.upgrade() {
2317 grants.entries.lock().remove(&expiry_revision);
2318 }
2319 }
2320 _ = cancelled => {}
2321 }
2322 });
2323 Ok::<_, ApiError>(PluginRouteService {
2324 _attachment: attachment,
2325 _expiry_cancel: cancel,
2326 })
2327 })
2328 .await?;
2329 }
2330 if state.plugin_ui_grants.get(&revision).is_none() {
2331 return Err(ui_stale_revision());
2332 }
2333 let result = codewhale_engine::extension_host::dispatch_plugin_route(&authority, request)
2334 .await
2335 .map_err(|error| match error {
2336 codewhale_engine::extension_host::PluginRouteError::NotFound => {
2337 ApiError::not_found("plugin did not register a handler for this route")
2338 .with_code("plugin_route_not_found")
2339 }
2340 codewhale_engine::extension_host::PluginRouteError::HostUnavailable(reason) => {
2341 ApiError {
2342 status: StatusCode::SERVICE_UNAVAILABLE,
2343 message: format!("plugin host is unavailable: {reason}"),
2344 code: Some("plugin_host_unavailable"),
2345 }
2346 }
2347 codewhale_engine::extension_host::PluginRouteError::RequestTooLarge => {
2348 ApiError::payload_too_large("plugin route request body exceeds the 4 MiB limit")
2349 }
2350 codewhale_engine::extension_host::PluginRouteError::ResponseTooLarge => ApiError {
2351 status: StatusCode::BAD_GATEWAY,
2352 message: "plugin route response body exceeds the 8 MiB limit".into(),
2353 code: Some("plugin_route_response_too_large"),
2354 },
2355 codewhale_engine::extension_host::PluginRouteError::Timeout => ApiError {
2356 status: StatusCode::GATEWAY_TIMEOUT,
2357 message: "plugin route timed out".into(),
2358 code: Some("plugin_route_timeout"),
2359 },
2360 codewhale_engine::extension_host::PluginRouteError::ExecutionFailed(reason) => {
2361 ApiError {
2362 status: StatusCode::BAD_GATEWAY,
2363 message: format!("plugin route failed: {reason}"),
2364 code: Some("plugin_route_failed"),
2365 }
2366 }
2367 })?;
2368 let status = StatusCode::from_u16(result.status).unwrap_or(StatusCode::BAD_GATEWAY);
2369 let mut response = Response::new(Body::from(result.body));
2370 *response.status_mut() = status;
2371 let out_headers = response.headers_mut();
2372 let mut forwarded_count = 0usize;
2373 for (name, value) in result.headers {
2374 if forwarded_count >= MAX_PLUGIN_ROUTE_RESPONSE_HEADERS {
2375 break;
2376 }
2377 if value.len() > MAX_PLUGIN_ROUTE_HEADER_VALUE_BYTES
2378 || is_stripped_plugin_route_response_header(&name)
2379 {
2380 continue;
2381 }
2382 let Ok(header_name) = HeaderName::from_bytes(name.as_bytes()) else {
2383 continue;
2384 };
2385 let Ok(header_value) = HeaderValue::from_str(&value) else {
2386 continue;
2387 };
2388 out_headers.append(header_name, header_value);
2389 forwarded_count += 1;
2390 }
2391 out_headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
2392 out_headers.insert(
2393 header::X_CONTENT_TYPE_OPTIONS,
2394 HeaderValue::from_static("nosniff"),
2395 );
2396 out_headers.insert(
2397 header::CONTENT_SECURITY_POLICY,
2398 HeaderValue::from_static("default-src 'none'; sandbox"),
2399 );
2400 out_headers.insert(
2401 header::REFERRER_POLICY,
2402 HeaderValue::from_static("no-referrer"),
2403 );
2404 Ok(response)
2405 }
2406
2407 pub(super) async fn get_plugin_ui_asset(
2408 State(state): State<RuntimeApiState>,
2409 ConnectInfo(peer): ConnectInfo<SocketAddr>,
2410 Path((selector, path)): Path<(String, String)>,
2411 headers: HeaderMap,
2412 ) -> Result<Response, ApiError> {
2413 if !peer.ip().is_loopback() {
2414 return Err(ApiError::forbidden(
2415 "plugin UI assets are available only from loopback",
2416 ));
2417 }
2418 let (grant, revision) = grant_for_request(&state, &selector, &headers)?;
2419 let relative = ui_relative_path(&path).map_err(|reason| {
2420 ApiError::bad_request(format!("plugin UI path '{path}' is invalid: {reason}"))
2421 })?;
2422 let content_type = ui_content_type(&relative);
2423 let is_dsh_bootstrap = grant.dsh.is_some() && relative == FsPath::new(DSH_BOOTSTRAP_ENTRY);
2424 if grant.dsh.is_some() && !is_dsh_bootstrap && !is_dsh_static_ui_asset(&relative) {
2425 return Err(
2426 ApiError::not_found("plugin UI file is not in the reviewed client closure")
2427 .with_code("plugin_ui_file_not_reviewed"),
2428 );
2429 }
2430 let state_for_asset = state.clone();
2431 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
2432 let bytes = tokio::task::spawn_blocking(move || {
2433 let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy);
2434 codewhale_plugins::registry::verify_plugin_authority(&grant.authority)
2435 .map_err(|_| ui_stale_revision())?;
2436 let bytes = if is_dsh_bootstrap {
2437 let dsh = grant
2438 .dsh
2439 .as_ref()
2440 .expect("is_dsh_bootstrap requires a DSH grant");
2441 let verified =
2442 verify_dsh_closure(&grant, &dsh.closure).map_err(|_| ui_stale_revision())?;
2443 dsh_bootstrap(&grant.selector, &dsh.closure, &verified)
2444 .map_err(|_| ui_stale_revision())?
2445 } else {
2446 let bundle_path = if grant.dsh.is_some() {
2447 relative.clone()
2448 } else {
2449 grant.ui_prefix.join(&relative)
2450 };
2451 verified_ui_file(&grant, &bundle_path).map_err(|error| match error {
2452 UiFileError::Missing => {
2453 ApiError::not_found("plugin UI file is not in the reviewed bundle")
2454 .with_code("plugin_ui_file_not_reviewed")
2455 }
2456 UiFileError::TooLarge => {
2457 ApiError::payload_too_large("plugin UI file exceeds the 8 MiB limit")
2458 }
2459 _ => ui_stale_revision(),
2460 })?
2461 };
2462 admit_ui_grant(&state_for_asset, &grant)?;
2463 if state_for_asset.plugin_ui_grants.get(&revision).is_none() {
2464 return Err(ui_stale_revision());
2465 }
2466 Ok::<_, ApiError>(bytes)
2467 })
2468 .await
2469 .map_err(|_| ApiError::internal("plugin UI read failed"))??;
2470 Ok(ui_asset_response(bytes, content_type))
2471 }
2472
2473 /// `POST /v1/apps/plugins/install`
2474 pub(super) async fn install_plugin_api(
2475 State(state): State<RuntimeApiState>,
2476 Json(req): Json<InstallPluginRequest>,
2477 ) -> Result<(StatusCode, Json<PluginMutationResponse>), PolicyOrApiError> {
2478 let source =
2479 codewhale_plugins::install::PluginInstallSource::parse(&req.source).map_err(|error| {
2480 ApiError::bad_request(format!(
2481 "invalid plugin install source '{}': {error:#}; expected a local \
2482 path, github:owner/repo, npm:<pkg>, git:<url>, dsh:<pkg-or-path>, \
2483 or an HTTPS tarball URL",
2484 req.source
2485 ))
2486 })?;
2487 let request = match req.expected_content_hash {
2488 Some(expected) => PluginMutationRequest::InstallExact {
2489 source,
2490 expected_content_hash: expected,
2491 },
2492 None => PluginMutationRequest::Install { source },
2493 };
2494 let response = run_plugin_mutation(&state, request).await?;
2495 Ok((StatusCode::CREATED, Json(response)))
2496 }
2497
2498 /// `POST /v1/apps/plugins/import/dsh/preview`: convert a DeepSeek Harness
2499 /// bundle package into scratch and return its receipt and review hash.
2500 /// Nothing is installed; the install endpoint does that with the same hash.
2501 pub(super) async fn preview_dsh_plugin_api(
2502 State(state): State<RuntimeApiState>,
2503 Json(req): Json<DshPreviewRequest>,
2504 ) -> Result<Json<DshPreviewResponse>, ApiError> {
2505 let requested = std::path::PathBuf::from(req.path.trim());
2506 let path = if requested.is_absolute() {
2507 requested
2508 } else {
2509 state.workspace.join(requested)
2510 };
2511 let network = {
2512 let config = state.config.read();
2513 config
2514 .network
2515 .clone()
2516 .map(codewhale_net::network_policy::NetworkPolicy::from)
2517 .unwrap_or_default()
2518 };
2519 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
2520 let preview = tokio::task::spawn_blocking(move || {
2521 let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy);
2522 let canonical = path
2523 .canonicalize()
2524 .map_err(|_| format!("DSH package not found at {}", path.display()))?;
2525 codewhale_plugins::install::preview_dsh_with_network(&canonical, &network)
2526 .map(|(conversion, content_hash)| (canonical, conversion, content_hash))
2527 .map_err(|error| format!("{error:#}"))
2528 })
2529 .await
2530 .map_err(|error| ApiError::internal(format!("DSH preview task failed: {error}")))?;
2531 let (canonical, conversion, content_hash) =
2532 preview.map_err(|error| ApiError::bad_request(format!("DSH import refused: {error}")))?;
2533 Ok(Json(DshPreviewResponse {
2534 install_source: format!("dsh:{}", canonical.display()),
2535 content_hash,
2536 conversion,
2537 }))
2538 }
2539
2540 /// `POST /v1/apps/plugins/{selector}/update`
2541 pub(super) async fn update_plugin_api(
2542 State(state): State<RuntimeApiState>,
2543 Path(selector): Path<String>,
2544 ) -> Result<Json<PluginMutationResponse>, PolicyOrApiError> {
2545 find_plugin(&state, &selector)?;
2546 Ok(Json(
2547 run_plugin_mutation(
2548 &state,
2549 PluginMutationRequest::Update {
2550 selector: selector.clone(),
2551 },
2552 )
2553 .await?,
2554 ))
2555 }
2556
2557 /// `DELETE /v1/apps/plugins/{selector}`
2558 pub(super) async fn uninstall_plugin_api(
2559 State(state): State<RuntimeApiState>,
2560 Path(selector): Path<String>,
2561 ) -> Result<Json<PluginMutationResponse>, PolicyOrApiError> {
2562 find_plugin(&state, &selector)?;
2563 Ok(Json(
2564 run_plugin_mutation(
2565 &state,
2566 PluginMutationRequest::Uninstall {
2567 selector: selector.clone(),
2568 },
2569 )
2570 .await?,
2571 ))
2572 }
2573
2574 /// `POST /v1/apps/plugins/{selector}/trust`
2575 pub(super) async fn trust_plugin_api(
2576 State(state): State<RuntimeApiState>,
2577 Path(selector): Path<String>,
2578 Json(req): Json<TrustPluginRequest>,
2579 ) -> Result<Json<PluginActionResponse>, ApiError> {
2580 Ok(Json(
2581 run_registry_mutation(
2582 &state,
2583 &selector,
2584 RegistryMutation::Trust {
2585 token: &req.token,
2586 host_services_token: req.host_services_token.as_deref(),
2587 },
2588 )
2589 .await?,
2590 ))
2591 }
2592
2593 /// `POST /v1/apps/plugins/{selector}/enable`
2594 pub(super) async fn enable_plugin_api(
2595 State(state): State<RuntimeApiState>,
2596 Path(selector): Path<String>,
2597 ) -> Result<Json<PluginActionResponse>, ApiError> {
2598 Ok(Json(
2599 run_registry_mutation(&state, &selector, RegistryMutation::Enable).await?,
2600 ))
2601 }
2602
2603 pub(super) async fn restage_plugin_api(
2604 State(state): State<RuntimeApiState>,
2605 Path(selector): Path<String>,
2606 ) -> Result<Json<PluginActionResponse>, ApiError> {
2607 Ok(Json(
2608 run_registry_mutation(&state, &selector, RegistryMutation::Restage).await?,
2609 ))
2610 }
2611
2612 /// `POST /v1/apps/plugins/{selector}/disable`
2613 pub(super) async fn disable_plugin_api(
2614 State(state): State<RuntimeApiState>,
2615 Path(selector): Path<String>,
2616 ) -> Result<Json<PluginActionResponse>, ApiError> {
2617 Ok(Json(
2618 run_registry_mutation(&state, &selector, RegistryMutation::Disable).await?,
2619 ))
2620 }
2621
2622 /// `POST /v1/apps/plugins/{selector}/revoke`
2623 pub(super) async fn revoke_plugin_api(
2624 State(state): State<RuntimeApiState>,
2625 Path(selector): Path<String>,
2626 ) -> Result<Json<PluginActionResponse>, ApiError> {
2627 Ok(Json(
2628 run_registry_mutation(&state, &selector, RegistryMutation::Revoke).await?,
2629 ))
2630 }
2631
2632 // ---------------------------------------------------------------------------
2633 // Handlers — marketplaces
2634 // ---------------------------------------------------------------------------
2635
2636 async fn with_marketplace_store<T: Send + 'static>(
2637 state: &RuntimeApiState,
2638 work: impl FnOnce(RuntimeApiState, MarketplaceStore) -> Result<T, ApiError> + Send + 'static,
2639 ) -> Result<T, ApiError> {
2640 let state = state.clone();
2641 tokio::task::spawn_blocking(move || {
2642 let store = open_marketplace_store(&state)?;
2643 work(state, store)
2644 })
2645 .await
2646 .map_err(|_| ApiError::internal("marketplace store task failed"))?
2647 }
2648
2649 /// `GET /v1/apps/marketplaces`
2650 pub(super) async fn list_marketplaces(
2651 State(state): State<RuntimeApiState>,
2652 ) -> Result<Json<MarketplacesResponse>, ApiError> {
2653 let marketplaces = with_marketplace_store(&state, |state, store| {
2654 let marketplace_state = load_marketplace_state(&store)?;
2655 let registry = registry_for_state(&state);
2656 Ok(marketplace_state
2657 .catalogs()
2658 .iter()
2659 .map(|(name, entry)| marketplace_catalog_entry(name, entry, &registry))
2660 .collect())
2661 })
2662 .await?;
2663 Ok(Json(MarketplacesResponse { marketplaces }))
2664 }
2665
2666 /// `GET /v1/apps/marketplaces/{name}`
2667 pub(super) async fn get_marketplace(
2668 State(state): State<RuntimeApiState>,
2669 Path(name): Path<String>,
2670 ) -> Result<Json<MarketplaceCatalogEntry>, ApiError> {
2671 let entry = with_marketplace_store(&state, move |state, store| {
2672 let marketplace_state = load_marketplace_state(&store)?;
2673 let entry = marketplace_state
2674 .get(&name)
2675 .ok_or_else(|| ApiError::not_found(format!("marketplace '{name}' not found")))?;
2676 Ok(marketplace_catalog_entry(
2677 &name,
2678 entry,
2679 &registry_for_state(&state),
2680 ))
2681 })
2682 .await?;
2683 Ok(Json(entry))
2684 }
2685
2686 /// `POST /v1/apps/marketplaces`
2687 pub(super) async fn add_marketplace(
2688 State(state): State<RuntimeApiState>,
2689 Json(req): Json<AddMarketplaceRequest>,
2690 ) -> Result<(StatusCode, Json<MarketplaceActionResponse>), ApiError> {
2691 let response = with_marketplace_store(&state, move |state, store| {
2692 let loaded = load_catalog_document(&req.name, &state.workspace, &req.path)
2693 .map_err(ApiError::bad_request)?;
2694 let candidate_count = loaded.candidate_count;
2695 let warning_count = loaded.warning_count;
2696 store
2697 .add(&loaded.entry.catalog.id.clone(), loaded.entry)
2698 .map_err(ApiError::conflict)?;
2699 Ok(MarketplaceActionResponse {
2700 name: req.name,
2701 action: "added",
2702 candidate_count: Some(candidate_count),
2703 warning_count: Some(warning_count),
2704 })
2705 })
2706 .await?;
2707 Ok((StatusCode::CREATED, Json(response)))
2708 }
2709
2710 /// `DELETE /v1/apps/marketplaces/{name}`
2711 pub(super) async fn remove_marketplace(
2712 State(state): State<RuntimeApiState>,
2713 Path(name): Path<String>,
2714 ) -> Result<Json<MarketplaceActionResponse>, ApiError> {
2715 let target = name.clone();
2716 let removed = with_marketplace_store(&state, move |_, store| {
2717 store
2718 .remove(&target)
2719 .map_err(|error| ApiError::internal(format!("remove marketplace: {error}")))
2720 })
2721 .await?;
2722 if !removed {
2723 return Err(ApiError::not_found(format!(
2724 "marketplace '{name}' not found"
2725 )));
2726 }
2727 Ok(Json(MarketplaceActionResponse {
2728 name,
2729 action: "removed",
2730 candidate_count: None,
2731 warning_count: None,
2732 }))
2733 }
2734
2735 /// `POST /v1/apps/marketplaces/{name}/install`
2736 ///
2737 /// Resolves the stored candidate through the shared plan resolver, then
2738 /// routes through the reviewed installer exactly like
2739 /// `POST /v1/apps/plugins/install`.
2740 pub(super) async fn install_marketplace_candidate_api(
2741 State(state): State<RuntimeApiState>,
2742 Path(name): Path<String>,
2743 Json(req): Json<InstallMarketplaceCandidateRequest>,
2744 ) -> Result<(StatusCode, Json<PluginMutationResponse>), PolicyOrApiError> {
2745 let spec = with_marketplace_store(&state, move |state, store| {
2746 let marketplace_state = load_marketplace_state(&store)?;
2747 let entry = marketplace_state
2748 .get(&name)
2749 .ok_or_else(|| ApiError::not_found(format!("marketplace '{name}' not found")))?;
2750 let candidate = entry
2751 .catalog
2752 .candidate_by_name(&req.candidate)
2753 .ok_or_else(|| {
2754 ApiError::not_found(format!(
2755 "candidate '{}' not found in marketplace '{name}'",
2756 req.candidate
2757 ))
2758 })?;
2759 let registry = registry_for_state(&state);
2760 match resolve_candidate_install(entry, candidate, &registry) {
2761 CatalogInstallResolution::Supported { spec, .. } => Ok(spec),
2762 CatalogInstallResolution::AlreadyPresent { reason, .. } => {
2763 Err(ApiError::conflict(reason))
2764 }
2765 CatalogInstallResolution::Unsupported { reason } => Err(ApiError::conflict(format!(
2766 "candidate '{}' cannot be installed by Codewhale: {reason}",
2767 req.candidate
2768 ))),
2769 CatalogInstallResolution::HasErrors { diagnostics } => {
2770 Err(ApiError::conflict(format!(
2771 "candidate '{}' has parse errors and cannot be installed: {diagnostics}",
2772 req.candidate
2773 )))
2774 }
2775 }
2776 })
2777 .await?;
2778 let response = run_plugin_mutation(
2779 &state,
2780 PluginMutationRequest::Install {
2781 source: codewhale_plugins::install::PluginInstallSource::parse(&spec).map_err(
2782 |error| {
2783 ApiError::internal(format!(
2784 "resolved install spec '{spec}' no longer parses: {error:#}"
2785 ))
2786 },
2787 )?,
2788 },
2789 )
2790 .await?;
2791 Ok((StatusCode::CREATED, Json(response)))
2792 }
2793
2794 // ---------------------------------------------------------------------------
2795 // Plugin catalog: built-in and experimental rows backed by `[features]`
2796 // ---------------------------------------------------------------------------
2797
2798 #[derive(Debug, Serialize)]
2799 pub(super) struct CatalogRow {
2800 pub(super) id: String,
2801 pub(super) title: String,
2802 pub(super) description: Option<String>,
2803 pub(super) icon: Option<String>,
2804 pub(super) experimental: bool,
2805 pub(super) enabled: bool,
2806 pub(super) available: bool,
2807 pub(super) unavailable_reason: Option<String>,
2808 pub(super) settings_schema: Option<Value>,
2809 pub(super) settings: Option<Value>,
2810 pub(super) restart_required: bool,
2811 pub(super) backing: &'static str,
2812 pub(super) dsh_package: Option<String>,
2813 }
2814
2815 #[derive(Debug, Serialize)]
2816 pub(super) struct CatalogResponse {
2817 pub(super) builtin: Vec<CatalogRow>,
2818 pub(super) experimental: Vec<CatalogRow>,
2819 pub(super) more: Vec<CatalogRow>,
2820 }
2821
2822 #[derive(Debug, Serialize)]
2823 pub(super) struct CatalogRowEnvelope {
2824 pub(super) row: CatalogRow,
2825 }
2826
2827 const CATALOG_BUILTIN_KEYS: &[&str] = &["subagents", "web_search", "shell_tool", "plugin_creator"];
2828 const AGENT_LOOP_ID: &str = "agent_loop";
2829
2830 fn catalog_title(key: &str) -> String {
2831 match key {
2832 "subagents" => "Subagent".to_string(),
2833 "web_search" => "Web search".to_string(),
2834 "shell_tool" => "Shell".to_string(),
2835 "plugin_creator" => "Plugin creator".to_string(),
2836 other => super::humanize_schema_key(other),
2837 }
2838 }
2839
2840 fn catalog_description(key: &str) -> Option<String> {
2841 let text = match key {
2842 "subagents" => "Delegate bounded tasks to focused child agents with isolated context.",
2843 "web_search" => "Search and fetch live web pages while answering.",
2844 "shell_tool" => "Run commands in your workspace terminal with approval controls.",
2845 "plugin_creator" => "Enable the built-in plugin_manager tool and Creator mode host module.",
2846 "apply_patch" => "Apply structured multi-file patches as one reviewed change.",
2847 "mcp" => "Connect Model Context Protocol servers and their tools.",
2848 "exec_policy" => "Check shell commands against your exec policy before they run.",
2849 "vision_model" => "Send images to a vision-capable model for analysis.",
2850 "code_mode" => "Compose MCP and plugin tools through one eager execute_tools call.",
2851 "extension_host" => {
2852 "Run reviewed plugins' native code in the TypeScript plugin host. Changing this re-reviews every plugin after a restart."
2853 }
2854 "data_host" => "Present data validation results with the pinned TypeScript presenter.",
2855 "speech_host" => "Prepare speech input and output with the pinned TypeScript adapter.",
2856 "pdf_host" => "Orchestrate PDF outcomes with the pinned TypeScript adapter.",
2857 "ocr_host" => "Choose the OCR engine with the pinned TypeScript adapter.",
2858 "web_search_host" => "Run web queries through the pinned TypeScript provider adapters.",
2859 "web_extract_host" => "Select readable page regions with the pinned TypeScript adapter.",
2860 "github_host" => "Present GitHub and local reports with the pinned TypeScript adapter.",
2861 "review_host" => "Present captured reviews with the pinned TypeScript adapter.",
2862 _ => return None,
2863 };
2864 Some(text.to_string())
2865 }
2866
2867 fn subagents_settings(config: &codewhale_runtime::config::Config) -> (Value, Value) {
2868 let max_concurrent = config
2869 .subagents
2870 .as_ref()
2871 .and_then(|subagents| subagents.max_concurrent)
2872 .map_or_else(
2873 || config.max_subagents(),
2874 |max| max.min(codewhale_runtime::config::MAX_SUBAGENTS),
2875 );
2876 let schema = serde_json::json!({
2877 "fields": [{
2878 "key": "max_concurrent",
2879 "label": "Maximum concurrent subagents",
2880 "kind": "number",
2881 "default": max_concurrent,
2882 }]
2883 });
2884 let settings = serde_json::json!({ "max_concurrent": max_concurrent });
2885 (schema, settings)
2886 }
2887
2888 fn catalog_feature_row(
2889 config: &codewhale_runtime::config::Config,
2890 spec: &codewhale_runtime::features::FeatureSpec,
2891 creator_reason: Option<&str>,
2892 ) -> CatalogRow {
2893 let (settings_schema, settings) = if spec.key == "subagents" {
2894 let (schema, settings) = subagents_settings(config);
2895 (Some(schema), Some(settings))
2896 } else {
2897 (None, None)
2898 };
2899 let (available, unavailable_reason) = if spec.key == "plugin_creator" {
2900 (creator_reason.is_none(), creator_reason.map(str::to_string))
2901 } else {
2902 (true, None)
2903 };
2904 CatalogRow {
2905 id: spec.key.to_string(),
2906 title: catalog_title(spec.key),
2907 description: catalog_description(spec.key),
2908 icon: Some(spec.key.to_string()),
2909 experimental: spec.stage == codewhale_runtime::features::Stage::Experimental,
2910 enabled: config.features().enabled(spec.id),
2911 available,
2912 unavailable_reason,
2913 settings_schema,
2914 settings,
2915 restart_required: spec.key == "extension_host",
2916 backing: "feature",
2917 dsh_package: None,
2918 }
2919 }
2920
2921 fn agent_loop_row() -> CatalogRow {
2922 CatalogRow {
2923 id: AGENT_LOOP_ID.to_string(),
2924 title: "Agent loop".to_string(),
2925 description: Some(
2926 "The planning, tool-use and verification loop every turn runs in. Always on."
2927 .to_string(),
2928 ),
2929 icon: Some(AGENT_LOOP_ID.to_string()),
2930 experimental: false,
2931 enabled: true,
2932 available: true,
2933 unavailable_reason: None,
2934 settings_schema: None,
2935 settings: None,
2936 restart_required: false,
2937 backing: "native",
2938 dsh_package: None,
2939 }
2940 }
2941
2942 fn build_catalog(
2943 config: &codewhale_runtime::config::Config,
2944 creator_reason: Option<&str>,
2945 ) -> CatalogResponse {
2946 let mut builtin = Vec::new();
2947 let mut experimental = Vec::new();
2948 let mut more = Vec::new();
2949 for spec in codewhale_runtime::features::FEATURES {
2950 let row = catalog_feature_row(config, spec, creator_reason);
2951 if CATALOG_BUILTIN_KEYS.contains(&spec.key) {
2952 builtin.push(row);
2953 } else if spec.stage == codewhale_runtime::features::Stage::Experimental {
2954 experimental.push(row);
2955 } else {
2956 more.push(row);
2957 }
2958 }
2959 builtin.sort_by_key(|row| {
2960 CATALOG_BUILTIN_KEYS
2961 .iter()
2962 .position(|key| *key == row.id)
2963 .unwrap_or(usize::MAX)
2964 });
2965 builtin.push(agent_loop_row());
2966 CatalogResponse {
2967 builtin,
2968 experimental,
2969 more,
2970 }
2971 }
2972
2973 fn find_catalog_row(
2974 config: &codewhale_runtime::config::Config,
2975 creator_reason: Option<&str>,
2976 id: &str,
2977 ) -> Option<CatalogRow> {
2978 let catalog = build_catalog(config, creator_reason);
2979 catalog
2980 .builtin
2981 .into_iter()
2982 .chain(catalog.experimental)
2983 .chain(catalog.more)
2984 .find(|row| row.id == id)
2985 }
2986
2987 async fn catalog_creator_reason_for(state: &RuntimeApiState, id: Option<&str>) -> Option<String> {
2988 if matches!(id, Some(other) if other != "plugin_creator") {
2989 return None;
2990 }
2991 let plugin_creator_enabled = state
2992 .config
2993 .read()
2994 .features()
2995 .enabled(codewhale_runtime::features::Feature::PluginCreator);
2996 codewhale_engine::conversation_modes::creator_unavailable_reason(
2997 state.runtime_threads.extension_host_options(),
2998 plugin_creator_enabled,
2999 )
3000 .await
3001 }
3002
3003 /// `GET /v1/apps/plugins/catalog`
3004 pub(super) async fn list_plugin_catalog(
3005 State(state): State<RuntimeApiState>,
3006 ) -> Result<Json<CatalogResponse>, ApiError> {
3007 let creator_reason = catalog_creator_reason_for(&state, None).await;
3008 let config = state.config.read();
3009 Ok(Json(build_catalog(&config, creator_reason.as_deref())))
3010 }
3011
3012 async fn reload_after_catalog_write(state: RuntimeApiState) -> Result<(), ApiError> {
3013 tokio::spawn(async move {
3014 let _credential_change = state.provider_switches.lock().await;
3015 let mut reloaded = codewhale_plugins::providers::load_config(
3016 state.config_path.clone(),
3017 state.config_profile.as_deref(),
3018 )
3019 .map_err(|e| ApiError::internal(format!("Failed to reload config: {e}")))?;
3020 reloaded.preserve_runtime_credentials(&state.config.read());
3021 state
3022 .runtime_threads
3023 .reload_config(reloaded.clone())
3024 .await
3025 .map_err(|err| ApiError::bad_request(format!("Config reload rejected: {err}")))?;
3026 *state.config.write() = reloaded;
3027 Ok(())
3028 })
3029 .await
3030 .map_err(|_| ApiError::internal("config reload task failed"))?
3031 }
3032
3033 async fn set_catalog_enabled(
3034 state: RuntimeApiState,
3035 id: String,
3036 on: bool,
3037 ) -> Result<Json<CatalogRowEnvelope>, ApiError> {
3038 if id == AGENT_LOOP_ID {
3039 if !on {
3040 return Err(ApiError::conflict(
3041 "The agent loop is always on; it cannot be turned off.",
3042 ));
3043 }
3044 return Ok(Json(CatalogRowEnvelope {
3045 row: agent_loop_row(),
3046 }));
3047 }
3048 let Some(spec) = codewhale_runtime::features::FEATURES
3049 .iter()
3050 .find(|spec| spec.key == id)
3051 else {
3052 return Err(ApiError::not_found(format!(
3053 "catalog plugin '{id}' not found"
3054 )));
3055 };
3056 codewhale_runtime::config_persistence::persist_table_bool_key(
3057 state.config_path.as_deref(),
3058 "features",
3059 spec.key,
3060 on,
3061 )
3062 .map_err(|e| ApiError::internal(format!("Failed to persist setting: {e}")))?;
3063 reload_after_catalog_write(state.clone()).await?;
3064 let creator_reason = catalog_creator_reason_for(&state, Some(&id)).await;
3065 let config = state.config.read();
3066 let row = find_catalog_row(&config, creator_reason.as_deref(), &id).ok_or_else(|| {
3067 ApiError::internal(format!("catalog plugin '{id}' vanished after reload"))
3068 })?;
3069 Ok(Json(CatalogRowEnvelope { row }))
3070 }
3071
3072 /// `POST /v1/apps/plugins/catalog/{id}/enable`
3073 pub(super) async fn enable_catalog_plugin(
3074 State(state): State<RuntimeApiState>,
3075 Path(id): Path<String>,
3076 ) -> Result<Json<CatalogRowEnvelope>, ApiError> {
3077 set_catalog_enabled(state, id, true).await
3078 }
3079
3080 /// `POST /v1/apps/plugins/catalog/{id}/disable`
3081 pub(super) async fn disable_catalog_plugin(
3082 State(state): State<RuntimeApiState>,
3083 Path(id): Path<String>,
3084 ) -> Result<Json<CatalogRowEnvelope>, ApiError> {
3085 set_catalog_enabled(state, id, false).await
3086 }
3087
3088 #[derive(Debug, Deserialize)]
3089 pub(super) struct CatalogSettingsRequest {
3090 settings: Value,
3091 }
3092
3093 /// `PUT /v1/apps/plugins/catalog/{id}/settings`
3094 pub(super) async fn put_catalog_settings(
3095 State(state): State<RuntimeApiState>,
3096 Path(id): Path<String>,
3097 Json(req): Json<CatalogSettingsRequest>,
3098 ) -> Result<Json<CatalogRowEnvelope>, ApiError> {
3099 let creator_reason = catalog_creator_reason_for(&state, Some(&id)).await;
3100 {
3101 let config = state.config.read();
3102 if find_catalog_row(&config, creator_reason.as_deref(), &id).is_none() {
3103 return Err(ApiError::not_found(format!(
3104 "catalog plugin '{id}' not found"
3105 )));
3106 }
3107 }
3108 if id != "subagents" {
3109 return Err(ApiError::bad_request(format!(
3110 "catalog plugin '{id}' has no editable settings"
3111 )));
3112 }
3113 let Value::Object(settings) = &req.settings else {
3114 return Err(ApiError::bad_request("settings must be an object"));
3115 };
3116 for key in settings.keys() {
3117 if key != "max_concurrent" {
3118 return Err(ApiError::bad_request(format!(
3119 "unknown subagents setting '{key}'"
3120 )));
3121 }
3122 }
3123 if let Some(value) = settings.get("max_concurrent") {
3124 let Some(max) = value.as_u64() else {
3125 return Err(ApiError::bad_request(
3126 "max_concurrent must be a positive integer",
3127 ));
3128 };
3129 if max == 0 || max > codewhale_runtime::config::MAX_SUBAGENTS as u64 {
3130 return Err(ApiError::bad_request(format!(
3131 "max_concurrent must be between 1 and {}",
3132 codewhale_runtime::config::MAX_SUBAGENTS
3133 )));
3134 }
3135 codewhale_runtime::config_persistence::persist_subagents_integer_key(
3136 state.config_path.as_deref(),
3137 "max_concurrent",
3138 max,
3139 )
3140 .map_err(|e| ApiError::internal(format!("Failed to persist setting: {e}")))?;
3141 reload_after_catalog_write(state.clone()).await?;
3142 }
3143 let creator_reason = catalog_creator_reason_for(&state, Some(&id)).await;
3144 let config = state.config.read();
3145 let row = find_catalog_row(&config, creator_reason.as_deref(), &id).ok_or_else(|| {
3146 ApiError::internal(format!("catalog plugin '{id}' vanished after reload"))
3147 })?;
3148 Ok(Json(CatalogRowEnvelope { row }))
3149 }
3150
3151 #[derive(Debug, Deserialize)]
3152 #[serde(deny_unknown_fields)]
3153 pub(super) struct PluginSettingsPutRequest {
3154 value: serde_json::Map<String, Value>,
3155 #[serde(default)]
3156 expected_revision: Option<String>,
3157 }
3158
3159 async fn admit_plugin_settings(
3160 state: &RuntimeApiState,
3161 selector: &str,
3162 ) -> Result<(String, PathBuf), ApiError> {
3163 let state_for_check = state.clone();
3164 let selector = selector.to_string();
3165 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
3166 let plugin_name = tokio::task::spawn_blocking(move || {
3167 let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy);
3168 let registry = registry_for_state(&state_for_check);
3169 let plugin = registry
3170 .get(&selector)
3171 .cloned()
3172 .ok_or_else(|| ApiError::not_found(format!("plugin '{selector}' not found")))?;
3173 if !plugin.active() {
3174 return Err(ApiError::forbidden(
3175 "plugin must be trusted and enabled to access settings",
3176 )
3177 .with_code("plugin_settings_not_admitted"));
3178 }
3179 let service = codewhale_plugins::host_services::HostService::Settings;
3180 let entry = offered(service)
3181 .then(|| {
3182 summary_host_services(&plugin, Some(&registry))
3183 .into_iter()
3184 .find(|entry| entry.service == service.name())
3185 })
3186 .flatten();
3187 match entry {
3188 Some(entry) if entry.state == HostServiceWireState::CanUse => {
3189 if !entry.withheld_by.is_empty() {
3190 return Err(ApiError::forbidden(
3191 "settings host service is withheld while another active plugin lacks that grant",
3192 )
3193 .with_code("plugin_settings_withheld"));
3194 }
3195 }
3196 _ => {
3197 return Err(ApiError::forbidden(
3198 "plugin has not been granted the settings host service",
3199 )
3200 .with_code("plugin_settings_not_granted"));
3201 }
3202 }
3203 Ok(plugin.name().to_string())
3204 })
3205 .await
3206 .map_err(|_| ApiError::internal("plugin settings check failed"))??;
3207
3208 let config_path = state
3209 .config_path
3210 .clone()
3211 .or_else(|| state.config.read().loaded_config_path.clone())
3212 .or_else(|| {
3213 codewhale_runtime::config::resolve_load_config_path(None)
3214 .ok()
3215 .flatten()
3216 })
3217 .or_else(|| {
3218 codewhale_config::codewhale_home()
3219 .ok()
3220 .map(|home| home.join("config.toml"))
3221 })
3222 .ok_or_else(|| ApiError::internal("cannot resolve config.toml path for plugin settings"))?;
3223 Ok((plugin_name, config_path))
3224 }
3225
3226 /// `GET /v1/apps/plugins/{selector}/settings`
3227 pub(super) async fn get_plugin_settings(
3228 State(state): State<RuntimeApiState>,
3229 Path(selector): Path<String>,
3230 ) -> Result<Json<codewhale_engine::extension_host::dsh_settings::PluginSettingsSnapshot>, ApiError>
3231 {
3232 let (plugin_name, config_path) = admit_plugin_settings(&state, &selector).await?;
3233 let snapshot = codewhale_engine::extension_host::dsh_settings::read_plugin_config_settings(
3234 config_path,
3235 plugin_name,
3236 )
3237 .await
3238 .map_err(|error| match error {
3239 codewhale_engine::extension_host::dsh_settings::PluginSettingsError::Invalid(message) => {
3240 ApiError::bad_request(message).with_code("plugin_settings_invalid")
3241 }
3242 codewhale_engine::extension_host::dsh_settings::PluginSettingsError::Store => {
3243 ApiError::internal("the plugin settings could not be read")
3244 }
3245 })?;
3246 Ok(Json(snapshot))
3247 }
3248
3249 /// `PUT /v1/apps/plugins/{selector}/settings`
3250 pub(super) async fn put_plugin_settings(
3251 State(state): State<RuntimeApiState>,
3252 Path(selector): Path<String>,
3253 Json(req): Json<PluginSettingsPutRequest>,
3254 ) -> Result<
3255 Json<codewhale_engine::extension_host::dsh_settings::PluginSettingsWriteOutcome>,
3256 ApiError,
3257 > {
3258 let (plugin_name, config_path) = admit_plugin_settings(&state, &selector).await?;
3259 let outcome = codewhale_engine::extension_host::dsh_settings::write_plugin_config_settings(
3260 config_path,
3261 plugin_name,
3262 req.value,
3263 req.expected_revision,
3264 )
3265 .await
3266 .map_err(|error| match error {
3267 codewhale_engine::extension_host::dsh_settings::PluginSettingsError::Invalid(message) => {
3268 ApiError::bad_request(message).with_code("plugin_settings_invalid")
3269 }
3270 codewhale_engine::extension_host::dsh_settings::PluginSettingsError::Store => {
3271 ApiError::internal("the plugin settings could not be saved")
3272 }
3273 })?;
3274 if outcome.written {
3275 reload_after_catalog_write(state).await?;
3276 }
3277 Ok(Json(outcome))
3278 }
3279
3280 #[cfg(test)]
3281 mod review_tests {
3282 use super::{
3283 DshSeat, PLUGIN_UI_SLOT, allowlisted_plugin_route_request_headers, declared_dsh_keys,
3284 dsh_bootstrap, dsh_client_closure, dsh_closure_unsupported,
3285 is_stripped_plugin_route_response_header, mcp_server_review,
3286 };
3287 use axum::http::{HeaderMap, HeaderName, HeaderValue, header};
3288
3289 #[test]
3290 fn dsh_bootstrap_root_entry_closure_resolves_relative_requires_in_node() {
3291 let closure = dsh_client_closure(&serde_json::json!({
3292 "client_closures": [{
3293 "root": "",
3294 "entry": "client.js",
3295 "files": { "client.js": "h1", "util.js": "h2" },
3296 "imports": { "client.js": { "./util": "util.js" } }
3297 }]
3298 }))
3299 .expect("authored closure");
3300 let verified = vec![
3301 (
3302 "client.js".to_string(),
3303 b"var util = require(\"./util\");\nexports.apply = function apply() { return [util.v]; };\n".to_vec(),
3304 ),
3305 ("util.js".to_string(), b"exports.v = 1;\n".to_vec()),
3306 ];
3307 let bootstrap = dsh_bootstrap("rootentry", &closure, &verified)
3308 .unwrap_or_else(|_| panic!("dsh_bootstrap failed"));
3309 let source = String::from_utf8(bootstrap).unwrap();
3310 assert!(source.contains("\"client.js\""));
3311 if let Some(out) = crate::runtime_api::tests::bootstrap_loads_in_node(&source) {
3312 let out: serde_json::Value = serde_json::from_str(&out).unwrap();
3313 assert_eq!(out["apply"], "function");
3314 assert_eq!(out["out"][0], 1);
3315 }
3316 }
3317
3318 #[test]
3319 fn dsh_bootstrap_uses_only_admitted_edges_for_cycles_json_packages_and_hosts() {
3320 for prefix in ["", "lib/"] {
3321 let entry = format!("{prefix}client.js");
3322 let helper = format!("{prefix}helper.cjs");
3323 let verified = vec![
3324 (
3325 entry.clone(),
3326 br#"exports.ready = 7;
3327 var helper = require('./helper');
3328 var data = require('./data.json');
3329 var packageValue = require('mapped');
3330 exports.apply = function () {
3331 var denied = 0;
3332 for (var id of ['./unlisted', 'unknown-service', './helper.cjs']) {
3333 try { require(id); } catch (_) { denied++; }
3334 }
3335 return [helper.ready, data.value, packageValue.value, require('react').id, denied];
3336 };"#
3337 .to_vec(),
3338 ),
3339 (
3340 helper.clone(),
3341 b"exports.ready = require('./client').ready;".to_vec(),
3342 ),
3343 ("data.json".into(), br#"{"value":2}"#.to_vec()),
3344 (
3345 "node_modules/mapped/selected.cjs".into(),
3346 b"exports.value = 3;".to_vec(),
3347 ),
3348 (
3349 "unlisted.js".into(),
3350 b"throw new Error('must not execute');".to_vec(),
3351 ),
3352 ];
3353 let files: std::collections::BTreeMap<_, _> = verified
3354 .iter()
3355 .map(|(path, _)| (path.clone(), "hash"))
3356 .collect();
3357 let conversion = serde_json::json!({"client_closures": [{
3358 "root": "", "entry": entry, "files": files, "host_provided": ["react"],
3359 "imports": {
3360 (entry.clone()): {"./helper": helper, "./data.json": "data.json", "mapped": "node_modules/mapped/selected.cjs", "react": null},
3361 (helper.clone()): {"./client": entry}
3362 }
3363 }]});
3364 let closure = dsh_client_closure(&conversion).unwrap();
3365 let source =
3366 String::from_utf8(dsh_bootstrap("mapped", &closure, &verified).unwrap()).unwrap();
3367 let out = crate::runtime_api::tests::bootstrap_loads_in_node(&source)
3368 .expect("node required for module map regression");
3369 let out: serde_json::Value = serde_json::from_str(&out).unwrap();
3370 assert_eq!(out["out"], serde_json::json!([7, 2, 3, "react", 3]));
3371 let mut missing = conversion.clone();
3372 missing["client_closures"][0]
3373 .as_object_mut()
3374 .unwrap()
3375 .remove("imports");
3376 assert!(dsh_client_closure(&missing).is_none());
3377 let mut outside = conversion;
3378 outside["client_closures"][0]["imports"][&entry]["./helper"] =
3379 serde_json::json!("outside.js");
3380 assert!(dsh_client_closure(&outside).is_none());
3381 }
3382 }
3383
3384 #[test]
3385 fn plugin_mcp_review_omits_url_credentials_without_changing_the_bundle() {
3386 for (raw, expected) in [
3387 (
3388 "https://review-user:review-password@mcp.example.invalid:8443/review-path?arbitrary=review-query#review-fragment",
3389 "https://mcp.example.invalid:8443",
3390 ),
3391 (
3392 "http://[::1]:9000/mcp?token=review-query",
3393 "http://[::1]:9000",
3394 ),
3395 (
3396 "https://mcp.example.invalid/mcp",
3397 "https://mcp.example.invalid",
3398 ),
3399 (
3400 "not a URL review-secret",
3401 "unparseable (configured value omitted)",
3402 ),
3403 (
3404 "data:text/plain,review-secret",
3405 "unparseable (configured value omitted)",
3406 ),
3407 ] {
3408 let cfg: codewhale_mcp::config::McpServerConfig =
3409 serde_json::from_value(serde_json::json!({
3410 "url": raw,
3411 "env": { "REVIEW_ENV": "review-env-value" },
3412 "headers": { "Authorization": "review-header-value" }
3413 }))
3414 .unwrap();
3415 let review = mcp_server_review("demo", &cfg);
3416 assert_eq!(review.url.as_deref(), Some(expected));
3417 assert_eq!(review.kind, "remote");
3418 assert_eq!(review.env_keys, ["REVIEW_ENV"]);
3419 assert_eq!(review.header_keys, ["Authorization"]);
3420 let payload = serde_json::to_string(&review).unwrap();
3421 for secret in [
3422 "review-user",
3423 "review-password",
3424 "review-path",
3425 "review-query",
3426 "review-fragment",
3427 "review-secret",
3428 "review-env-value",
3429 "review-header-value",
3430 ] {
3431 assert!(!payload.contains(secret), "review exposed {secret}");
3432 }
3433 // Display redaction must not change the endpoint used at execution
3434 // or the manifest from which the trust receipt is derived.
3435 assert_eq!(cfg.url.as_deref(), Some(raw));
3436 }
3437 let stdio: codewhale_mcp::config::McpServerConfig =
3438 serde_json::from_value(serde_json::json!({
3439 "command": "npx", "args": ["demo-server"]
3440 }))
3441 .unwrap();
3442 let review = mcp_server_review("stdio", &stdio);
3443 assert_eq!(review.kind, "stdio");
3444 assert_eq!(review.url, None);
3445 assert_eq!(review.command, stdio.command);
3446 assert_eq!(review.args, stdio.args);
3447 }
3448
3449 #[test]
3450 fn dsh_closure_admits_client_store_and_ui_primitives_but_not_unknown_hosts() {
3451 let conversion = |hosts: &[&str]| {
3452 serde_json::json!({"client_closures": [{
3453 "root": "", "entry": "client.js", "files": {"client.js": "hash"},
3454 "host_provided": hosts,
3455 "imports": {"client.js": {}}
3456 }]})
3457 };
3458 let verified = vec![(
3459 "client.js".to_string(),
3460 b"exports.apply = function () { return [require('@deepseek-ai/dsh-client-store'), require('@deepseek-ai/dsh-client-ui-primitives')]; };".to_vec(),
3461 )];
3462 let admitted = dsh_client_closure(&conversion(&[
3463 "react",
3464 "@deepseek-ai/dsh-client-store",
3465 "@deepseek-ai/dsh-client-ui-primitives",
3466 "@deepseek-ai/dsh-settings",
3467 "@deepseek-ai/dsh-tools",
3468 "@deepseek-ai/dsh-credentials",
3469 ]))
3470 .unwrap();
3471 assert_eq!(dsh_closure_unsupported(&admitted, &verified), None);
3472 let refused = dsh_client_closure(&conversion(&["@deepseek-ai/dsh-client-api"])).unwrap();
3473 assert!(
3474 dsh_closure_unsupported(&refused, &verified)
3475 .is_some_and(|reason| reason.contains("@deepseek-ai/dsh-client-api"))
3476 );
3477
3478 let seat_script = vec![(
3479 "client.js".to_string(),
3480 br#"exports.slots = ["shell.overlay", "main", "sidebar.channels", "conversation.session.header.actions", "conversation.session.header.lineage", "conversation.session.header.utilities", "settings.section.icon", "web-ui.plugin.item", "conversation.chat.commandview", "sidebar.right.pane.tab.title"];"#.to_vec(),
3481 )];
3482 let declared = declared_dsh_keys(&seat_script);
3483 for (slot, expected_seat) in [
3484 ("shell.overlay", "workpane.panel"),
3485 ("main", "workpane.panel"),
3486 ("sidebar.right.pane.tab.title", "workpane.panel"),
3487 ("sidebar.channels", "sidebar.section"),
3488 ("conversation.session.header.actions", "command.row"),
3489 ("conversation.session.header.lineage", "command.row"),
3490 ("conversation.session.header.utilities", "command.row"),
3491 ("settings.section.icon", PLUGIN_UI_SLOT),
3492 ("web-ui.plugin.item", PLUGIN_UI_SLOT),
3493 ("conversation.chat.commandview", "conversation.chat.node"),
3494 ] {
3495 assert!(
3496 declared.iter().any(|(key, seat)| *key == slot
3497 && matches!(seat, DshSeat::Seat(s) if *s == expected_seat)),
3498 "expected '{slot}' to map to '{expected_seat}'"
3499 );
3500 }
3501 }
3502
3503 #[test]
3504 fn plugin_route_header_allowlist_and_stripping() {
3505 for stripped in [
3506 "set-cookie",
3507 "Set-Cookie",
3508 "authorization",
3509 "cookie",
3510 "www-authenticate",
3511 "proxy-authenticate",
3512 "content-security-policy",
3513 "content-security-policy-report-only",
3514 "referrer-policy",
3515 "location",
3516 "access-control-allow-origin",
3517 "access-control-allow-credentials",
3518 "x-frame-options",
3519 "strict-transport-security",
3520 ] {
3521 assert!(
3522 is_stripped_plugin_route_response_header(stripped),
3523 "expected response header '{stripped}' to be stripped"
3524 );
3525 }
3526 assert!(!is_stripped_plugin_route_response_header("content-type"));
3527 assert!(!is_stripped_plugin_route_response_header("x-plugin-echo"));
3528
3529 let mut req_headers = HeaderMap::new();
3530 req_headers.insert(
3531 header::CONTENT_TYPE,
3532 HeaderValue::from_static("application/json"),
3533 );
3534 req_headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
3535 req_headers.insert(
3536 header::AUTHORIZATION,
3537 HeaderValue::from_static("Bearer secret"),
3538 );
3539 req_headers.insert(header::COOKIE, HeaderValue::from_static("sid=secret"));
3540 req_headers.insert(
3541 HeaderName::from_static("x-codewhale-runtime-token"),
3542 HeaderValue::from_static("secret"),
3543 );
3544 req_headers.insert(
3545 HeaderName::from_static("x-plugin-trace"),
3546 HeaderValue::from_static("ok"),
3547 );
3548 let forwarded = allowlisted_plugin_route_request_headers(&req_headers);
3549 assert!(forwarded.contains(&("content-type".into(), "application/json".into())));
3550 assert!(forwarded.contains(&("accept".into(), "application/json".into())));
3551 assert!(forwarded.contains(&("x-plugin-trace".into(), "ok".into())));
3552 assert!(!forwarded.iter().any(|(k, _)| {
3553 k == "authorization" || k == "cookie" || k == "x-codewhale-runtime-token"
3554 }));
3555 }
3556 }
3557
3557 lines RUST