返回 CodeWhale
config.rs
根目录 / crates / command-contract / src / config.rs
1 //! Config-group command facets (FEAT-028 D3/D4).
2 //!
3 //! These traits let `/config`, `/settings`, `/mode`, `/theme`, `/verbose`,
4 //! `/login`, `/logout`, `/whale` and `/trust` express their intent without naming
5 //! `App`, a service locator, a callback, or any concrete host type. Hosts own
6 //! persistence, services and I/O; the values here grant no terminal, TUI or
7 //! runtime authority, and a missing facet must fail safely rather than panic.
8
9 use crate::outcome::ConfigAction;
10 use std::path::{Path, PathBuf};
11
12 /// A message the host raises for the command to render.
13 ///
14 /// The host never renders user-facing text for the config group: it returns a
15 /// stable key plus named replacements (each replacement is itself a message,
16 /// so a host never pre-renders a localized fragment), and the command resolves
17 /// it through the `presentation` shape. Non-localized text (protocol/config/
18 /// command names, computed values) stays a `Literal`.
19 #[derive(Debug, Clone, PartialEq, Eq)]
20 pub enum ConfigMessage {
21 /// Resolved by the presentation shape via its stable snake_case key.
22 Keyed {
23 key: String,
24 params: Vec<(String, ConfigMessage)>,
25 },
26 /// Non-localized text.
27 Literal(String),
28 /// A sequence rendered in order, for literal framing around keyed parts.
29 Concat(Vec<ConfigMessage>),
30 }
31
32 impl ConfigMessage {
33 pub fn keyed(key: impl Into<String>) -> Self {
34 Self::Keyed {
35 key: key.into(),
36 params: Vec::new(),
37 }
38 }
39 pub fn keyed_with(key: impl Into<String>, params: Vec<(String, ConfigMessage)>) -> Self {
40 Self::Keyed {
41 key: key.into(),
42 params,
43 }
44 }
45 pub fn literal(text: impl Into<String>) -> Self {
46 Self::Literal(text.into())
47 }
48 pub fn concat(parts: Vec<ConfigMessage>) -> Self {
49 Self::Concat(parts)
50 }
51 }
52
53 impl From<String> for ConfigMessage {
54 fn from(value: String) -> Self {
55 Self::Literal(value)
56 }
57 }
58
59 impl From<&str> for ConfigMessage {
60 fn from(value: &str) -> Self {
61 Self::Literal(value.to_string())
62 }
63 }
64
65 impl From<std::borrow::Cow<'_, str>> for ConfigMessage {
66 fn from(value: std::borrow::Cow<'_, str>) -> Self {
67 Self::Literal(value.into_owned())
68 }
69 }
70
71 /// Portable result of a config-group host operation.
72 ///
73 /// The host raises a [`ConfigMessage`] and the single action the request
74 /// implies; the command resolves the message through the presentation shape and
75 /// maps the reply to `CommandResult<ConfigAction>` without touching `App`.
76 #[derive(Debug, Clone, PartialEq, Eq)]
77 pub struct ConfigReply {
78 pub message: Option<ConfigMessage>,
79 pub action: Option<ConfigAction>,
80 pub is_error: bool,
81 }
82
83 impl ConfigReply {
84 pub fn ok() -> Self {
85 Self {
86 message: None,
87 action: None,
88 is_error: false,
89 }
90 }
91 pub fn message(msg: impl Into<ConfigMessage>) -> Self {
92 Self {
93 message: Some(msg.into()),
94 action: None,
95 is_error: false,
96 }
97 }
98 pub fn error(msg: impl Into<ConfigMessage>) -> Self {
99 let msg = match msg.into() {
100 ConfigMessage::Literal(text) => ConfigMessage::Literal(format!("Error: {text}")),
101 other => other,
102 };
103 Self {
104 message: Some(msg),
105 action: None,
106 is_error: true,
107 }
108 }
109 pub fn action(action: ConfigAction) -> Self {
110 Self {
111 message: None,
112 action: Some(action),
113 is_error: false,
114 }
115 }
116 pub fn with_message_and_action(msg: impl Into<ConfigMessage>, action: ConfigAction) -> Self {
117 Self {
118 message: Some(msg.into()),
119 action: Some(action),
120 is_error: false,
121 }
122 }
123 }
124
125 /// One structured `/settings` row: the label, its column width and its value.
126 #[derive(Debug, Clone, PartialEq, Eq)]
127 pub struct CommandSettingsRow {
128 pub label: String,
129 pub value: String,
130 pub label_width: usize,
131 }
132
133 /// Typed `/settings text` report.
134 ///
135 /// The host supplies display rows and the config-file path; the command owns
136 /// the title, separator, footer and joining.
137 #[derive(Debug, Clone, PartialEq, Eq)]
138 pub struct CommandSettingsReport {
139 pub rows: Vec<CommandSettingsRow>,
140 pub config_file: String,
141 pub from_settings: Vec<String>,
142 pub session_overrides: Vec<String>,
143 }
144
145 /// Typed `/config subagents [status]` report.
146 #[derive(Debug, Clone, PartialEq, Eq)]
147 pub struct CommandSubagentsReport {
148 pub disabled_reason: Option<String>,
149 pub config_path: String,
150 pub provider_key: String,
151 pub provider_label: String,
152 pub explicit_enabled: Option<bool>,
153 pub limits: Vec<CommandSubagentsLimit>,
154 /// Per-provider override rows for the active provider, when configured.
155 pub provider_rows: Option<Vec<CommandSubagentsProviderRow>>,
156 }
157
158 /// One of the five sub-agent limits: raw, resolved global and active-provider.
159 #[derive(Debug, Clone, PartialEq, Eq)]
160 pub struct CommandSubagentsLimit {
161 pub key: &'static str,
162 pub raw: String,
163 pub global: String,
164 pub provider: String,
165 }
166
167 /// One per-provider override row (already display-formatted).
168 #[derive(Debug, Clone, PartialEq, Eq)]
169 pub struct CommandSubagentsProviderRow {
170 pub key: &'static str,
171 pub value: String,
172 }
173
174 /// One row of the `/config status` editability audit.
175 ///
176 /// The host supplies typed facts; the command owns the table layout.
177 #[derive(Debug, Clone, PartialEq, Eq)]
178 pub struct CommandConfigAuditRow {
179 pub key: String,
180 pub current: String,
181 pub editability: String,
182 pub command: String,
183 /// Keyed when the note is localized, literal otherwise.
184 pub note: ConfigMessage,
185 }
186
187 /// Typed `/config status` audit: the resolved config path and its rows.
188 #[derive(Debug, Clone, PartialEq, Eq)]
189 pub struct CommandConfigAuditReport {
190 pub config_path: String,
191 pub rows: Vec<CommandConfigAuditRow>,
192 }
193
194 /// The complete reply contract for mutating config operations.
195 ///
196 /// A mutating [`CommandConfigContext`] operation MUST return a [`ConfigReply`]
197 /// whose keyed messages use only these keys, each with exactly these parameter
198 /// names. The command validates every entry (and prepares the substituted
199 /// template) *before* the effect, so rendering a mutating reply is pure
200 /// substitution and never translates after the effect. A key or parameter set
201 /// outside this contract is a host bug.
202 pub const EFFECT_REPLY_TEMPLATES: &[(&str, &[&str])] = &[
203 ("config_command_invalid_value", &["key", "value", "choices"]),
204 ("config_notification_updated", &["key", "value", "scope"]),
205 ("config_notifications_set_hint", &[]),
206 ("config_prompt_suggestion_updated", &["value", "scope"]),
207 ("config_scope_saved", &[]),
208 ("config_scope_session", &[]),
209 ("config_search_updated", &["value", "scope"]),
210 ("contextual_tips_not_saved", &["error"]),
211 ("help_usage_label", &[]),
212 ("startup_default_not_saved", &["setting", "error"]),
213 ];
214
215 /// Read/write configuration, presets, the editability audit, login state and
216 /// the config-owned view/display commands (`/mode`, `/theme`, `/verbose`,
217 /// `/statusbar`, `/workbar`, `/import-claude`).
218 ///
219 /// The host owns per-key validation, normalization, persistence and the exact
220 /// message; the portable handler owns argument parsing and subcommand routing.
221 /// A missing facet must fail safely rather than panic.
222 pub trait CommandConfigContext {
223 fn mcp_config_path(&self) -> PathBuf;
224 fn hugging_face_mcp_server_name(&self) -> Result<Option<String>, String>;
225 /// Path of the active user configuration file, when one is resolved.
226 fn config_path(&self) -> Option<PathBuf>;
227 fn translation_enabled(&self) -> bool;
228 fn set_translation_enabled(&mut self, enabled: bool);
229
230 /// `/config status|audit|editability|editable` — typed audit rows.
231 fn audit(&mut self) -> Result<CommandConfigAuditReport, String>;
232 /// `/config workflow` / `/config goal` — typed effective facts.
233 fn workflow_summary(&mut self) -> CommandWorkflowSummary;
234 /// `/config subagents status` — typed subagent facts.
235 fn subagents_status(&mut self) -> Result<CommandSubagentsReport, String>;
236 /// `/config subagents <key>` — show one subagent setting.
237 fn subagent(&mut self, key: &str) -> ConfigReply;
238 /// `/config subagents <key> <value> [--save]`.
239 fn set_subagent(&mut self, key: &str, value: &str, persist: bool) -> ConfigReply;
240 /// `/config search.provider` — the current provider and source.
241 fn search_provider_status(&mut self) -> ConfigReply;
242 /// Accepted `search.provider` values, for the portable usage message.
243 fn search_provider_names(&self) -> &'static str;
244 /// `/config search.provider <value> [--save]`.
245 fn set_search_provider(&mut self, value: &str, persist: bool) -> ConfigReply;
246 /// `/config notifications` — the notifications report.
247 fn notifications_status(&mut self) -> ConfigReply;
248 /// `/config notifications <key>` — show one notification setting.
249 fn notification(&mut self, key: &str) -> ConfigReply;
250 /// `/config notifications <key> <value> [--save]`.
251 fn set_notification(&mut self, key: &str, value: &str, persist: bool) -> ConfigReply;
252 /// `/config preset <name> [--save]`.
253 fn apply_preset(&mut self, name: &str, persist: bool) -> ConfigReply;
254 /// `/config <key>` — show the current value.
255 fn get_value(&mut self, key: &str) -> ConfigReply;
256 /// `/config <key> <value> [--save]`.
257 fn set_value(&mut self, key: &str, value: &str, persist: bool) -> ConfigReply;
258 /// `/settings text` — typed settings facts.
259 fn show_settings(&mut self) -> Result<CommandSettingsReport, String>;
260 /// `/theme schema` — the user theme JSON schema.
261 fn theme_schema(&self) -> String;
262 /// `/theme path` — the user themes directory, rendered for display.
263 fn themes_dir(&self) -> Result<String, String>;
264 /// Current verbose-transcript flag.
265 fn verbose_enabled(&self) -> bool;
266 /// Set the verbose-transcript flag (the host also marks history updated).
267 fn set_verbose_enabled(&mut self, enabled: bool);
268 /// `/import-claude` — build the plan from the host's home/workspace.
269 fn build_plan(&mut self) -> Option<CommandClaudePlan>;
270 /// `/import-claude` — persist the rendered report and optional bundle.
271 fn write_artifacts(&mut self, report: &str, bundle: Option<&str>) -> CommandClaudeArtifacts;
272 /// `/import-claude --apply` — carry over the standing instructions.
273 fn apply_import(
274 &mut self,
275 plan: &CommandClaudePlan,
276 report_path: &Path,
277 wrote_report: bool,
278 ) -> CommandClaudeApplyOutcome;
279 /// Host display form of a path.
280 fn display_path(&self, path: &Path) -> String;
281 }
282
283 /// Localized whale labels the `/whale` command composes into its messages.
284 ///
285 /// The command owns the verb parsing and message composition; the facet only
286 /// observes and mutates the whale view and resolves these labels.
287 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
288 pub enum CommandPetLabel {
289 ModeOn,
290 ModeOff,
291 StillOn,
292 StillOff,
293 Named,
294 Colored,
295 ColorReset,
296 }
297
298 pub trait CommandPetContext {
299 fn enabled(&self) -> bool;
300 fn set_enabled(&mut self, enabled: bool, persist: bool);
301 fn still(&self) -> bool;
302 fn set_still(&mut self, still: bool);
303 fn set_name(&mut self, name: &str);
304 fn set_color(&mut self, color: Option<&str>);
305 fn label(&self, which: CommandPetLabel) -> String;
306 }
307
308 /// Account sign-in state for `/login`.
309 #[derive(Debug, Clone, PartialEq, Eq)]
310 pub enum CommandAccountState {
311 SignedOut,
312 Authenticated,
313 OfflineCached,
314 Expired,
315 Revoked,
316 Unavailable(String),
317 }
318
319 /// `/login` status projection (the command composes the report text).
320 #[derive(Debug, Clone, PartialEq, Eq)]
321 pub struct CommandLoginStatus {
322 pub account: CommandAccountState,
323 pub api_base: String,
324 pub provider: String,
325 pub sign_in_open: bool,
326 }
327
328 /// Account/provider session state for `/login` and `/logout`.
329 pub trait CommandLoginContext {
330 fn login_status(&self) -> CommandLoginStatus;
331 /// `/connect [<provider>]` — plugin provider sign-in.
332 fn connect(&mut self, provider: Option<&str>) -> ConfigReply;
333 /// `/disconnect <provider>` — plugin provider sign-out.
334 fn disconnect(&mut self, provider: &str) -> ConfigReply;
335 }
336
337 /// Workbar placement/panel observation and mutation for `/workbar`.
338 pub trait CommandWorkSurfaceContext {
339 fn placement(&self) -> crate::types::CommandWorkSurfacePlacement;
340 fn panel(&self) -> crate::types::CommandRailPanel;
341 fn effective_placement(&self) -> crate::types::CommandWorkSurfacePlacement;
342 fn area_present(&self) -> bool;
343 fn panel_title(&self, panel: crate::types::CommandRailPanel) -> String;
344 /// Apply a placement; when `persist`, also writes the setting. The reply is
345 /// the key-engine result (ignored on success, returned on error).
346 fn set_placement(
347 &mut self,
348 placement: crate::types::CommandWorkSurfacePlacement,
349 persist: bool,
350 ) -> ConfigReply;
351 fn set_panel(&mut self, panel: crate::types::CommandRailPanel, persist: bool) -> ConfigReply;
352 fn mark_redraw(&mut self);
353 }
354
355 /// A path problem surfaced by `/trust add|remove`.
356 #[derive(Debug, Clone, PartialEq, Eq)]
357 pub enum TrustPathError {
358 /// The supplied path does not exist.
359 NotFound(PathBuf),
360 /// The allow-list could not be updated; carries the host error text.
361 UpdateFailed(String),
362 }
363
364 /// Workspace trust and the per-path allow-list for `/trust`.
365 pub trait CommandTrustContext {
366 fn trust_mode(&self) -> bool;
367 fn trusted_paths(&self) -> Vec<PathBuf>;
368 /// Add a path (the host expands `~` and validates existence).
369 fn add_trusted_path(&mut self, raw: &str) -> Result<PathBuf, TrustPathError>;
370 /// Returns the resolved path and whether it was removed.
371 fn remove_trusted_path(&mut self, raw: &str) -> Result<(PathBuf, bool), TrustPathError>;
372 /// The localized `Usage:` label used by the `/trust on|off` usage error.
373 fn usage_label(&self) -> String;
374 }
375
376 // ---------------------------------------------------------------------------
377 // Portable payloads for host effects that cross the config boundary (D5).
378 //
379 // The TUI conversion layer has no access to `App`, so engine-affecting actions
380 // cannot be re-derived at conversion time. These mirrors carry the exact data
381 // the host needs, and the host converts each direction faithfully.
382 // ---------------------------------------------------------------------------
383
384 /// Route capability fact, mirroring the config layer's `CapabilityState`.
385 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
386 pub enum CommandCapabilityState {
387 Supported,
388 Unsupported,
389 Unknown,
390 }
391
392 /// Compaction configuration carried by `ConfigAction::CompactionChanged`.
393 #[derive(Debug, Clone, PartialEq, Eq)]
394 pub struct CommandCompactionConfig {
395 pub enabled: bool,
396 pub token_threshold: usize,
397 pub model: String,
398 pub image_input: CommandCapabilityState,
399 pub effective_context_window: Option<u32>,
400 pub cache_summary: bool,
401 pub focus: Option<String>,
402 pub runtime_cost_owner: Option<String>,
403 pub workspace: Option<PathBuf>,
404 pub summary_instructions: Option<String>,
405 pub retained_user_message_tokens: usize,
406 }
407
408 /// Subagent runtime configuration carried by `ConfigAction::SubagentRuntimeChanged`.
409 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
410 pub struct CommandSubagentRuntimeConfig {
411 pub enabled: bool,
412 pub max_subagents: usize,
413 pub launch_concurrency: usize,
414 pub max_spawn_depth: u32,
415 pub api_timeout_secs: u64,
416 pub heartbeat_timeout_secs: u64,
417 }
418
419 /// Search provider carried by `ConfigAction::SearchProviderChanged`.
420 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
421 pub enum CommandSearchProvider {
422 Bing,
423 DuckDuckGo,
424 Firecrawl,
425 Tavily,
426 Bocha,
427 Metaso,
428 Searxng,
429 Baidu,
430 Volcengine,
431 Sofya,
432 Serply,
433 DeepSeek,
434 SearchApi,
435 }
436
437 /// Operator-notification delivery method.
438 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
439 pub enum CommandNotificationMethod {
440 Auto,
441 Osc9,
442 Bel,
443 Kitty,
444 Ghostty,
445 Off,
446 }
447
448 /// Turn-completion sound choice.
449 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
450 pub enum CommandCompletionSound {
451 Off,
452 Beep,
453 Bell,
454 Whale,
455 File,
456 }
457
458 /// When operator notifications are allowed.
459 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
460 pub enum CommandNotificationCondition {
461 Always,
462 Unfocused,
463 Never,
464 }
465
466 /// Subagent-completion notification policy.
467 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
468 pub enum CommandSubagentCompletion {
469 Always,
470 FinalOnly,
471 Off,
472 }
473
474 /// One notification event kind.
475 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
476 pub enum CommandNotificationEvent {
477 TurnComplete,
478 SubagentTerminal,
479 ApprovalNeeded,
480 InputNeeded,
481 ElevationNeeded,
482 ModelNotify,
483 }
484
485 /// One validated notification edit, mirroring `NotificationConfigUpdate`.
486 #[derive(Debug, Clone, PartialEq, Eq)]
487 pub enum CommandNotificationUpdate {
488 Method(CommandNotificationMethod),
489 ThresholdSecs(u64),
490 IncludeSummary(bool),
491 Quiet(bool),
492 Sound(Option<CommandCompletionSound>),
493 Condition(CommandNotificationCondition),
494 CompletionSound(CommandCompletionSound),
495 SubagentCompletion(CommandSubagentCompletion),
496 SoundFile(PathBuf),
497 Event(CommandNotificationEvent, bool),
498 EventSoundEnabled(bool),
499 EventSoundEvents(Vec<String>),
500 EventSoundMinIntervalMs(u64),
501 EventSoundQuiet(bool),
502 }
503
504 // ---------------------------------------------------------------------------
505 // `/import-claude` plan model (portable). The host builds the plan from the
506 // Claude sources and performs the writes/apply; the command renders it.
507 // ---------------------------------------------------------------------------
508
509 /// Effective `[workflow]`/`[goal]` facts for `/config workflow`.
510 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
511 pub struct CommandWorkflowSummary {
512 pub automatic: bool,
513 pub auto_start_read_only: bool,
514 pub require_approval_for_writes: bool,
515 pub max_children: u32,
516 pub max_concurrent: u32,
517 pub max_depth: u32,
518 pub goal_max_continuations: u32,
519 pub goal_enforce_token_budget: bool,
520 }
521
522 /// Outcome of reading one Claude source file.
523 #[derive(Debug, Clone, PartialEq, Eq)]
524 pub enum CommandSourceStatus {
525 Found,
526 NotFound,
527 Oversize(u64),
528 InvalidJson(String),
529 Unreadable(String),
530 }
531
532 impl CommandSourceStatus {
533 /// The one-line provenance entry used by the rendered plan and report.
534 ///
535 /// `display_path` is the host's display projection (for example `~/...`),
536 /// so the portable layer never leaks an absolute home path.
537 #[must_use]
538 pub fn describe(&self, display_path: &str) -> String {
539 match self {
540 Self::Found => format!("found: {display_path}"),
541 Self::NotFound => format!("not found: {display_path}"),
542 Self::Oversize(bytes) => {
543 format!("skipped, too large ({bytes} bytes): {display_path}")
544 }
545 Self::InvalidJson(error) => format!("invalid JSON: {display_path} ({error})"),
546 Self::Unreadable(error) => format!("unreadable: {display_path} ({error})"),
547 }
548 }
549 }
550
551 /// One MCP server discovered in the Claude sources.
552 #[derive(Debug, Clone, PartialEq, Eq)]
553 pub struct CommandMcpCandidate {
554 pub name: String,
555 pub summary: String,
556 pub hard_blocked: bool,
557 }
558
559 /// The full `/import-claude` plan. Pure data: building it mutates nothing.
560 #[derive(Debug, Clone, Default, PartialEq, Eq)]
561 pub struct CommandClaudePlan {
562 pub sources: Vec<(PathBuf, CommandSourceStatus)>,
563 pub mcp_candidates: Vec<CommandMcpCandidate>,
564 pub per_project_mcp: Vec<String>,
565 /// Safe env entries proposed for the portable bundle, key-sorted.
566 pub env_safe: Vec<(String, String)>,
567 pub env_skipped: Vec<String>,
568 pub permissions_default_mode: Option<String>,
569 pub permissions_allow: Vec<String>,
570 pub permissions_ask: Vec<String>,
571 pub permissions_deny: Vec<String>,
572 pub hook_events: Vec<String>,
573 pub has_claude_md: bool,
574 pub claude_projects: Vec<String>,
575 }
576
577 impl CommandClaudePlan {
578 #[must_use]
579 pub fn is_empty(&self) -> bool {
580 self.mcp_candidates.is_empty()
581 && self.per_project_mcp.is_empty()
582 && self.env_safe.is_empty()
583 && self.env_skipped.is_empty()
584 && self.permissions_default_mode.is_none()
585 && self.permissions_allow.is_empty()
586 && self.permissions_ask.is_empty()
587 && self.permissions_deny.is_empty()
588 && self.hook_events.is_empty()
589 && !self.has_claude_md
590 && self.claude_projects.is_empty()
591 }
592
593 #[must_use]
594 pub fn has_any_present_or_failed_source(&self) -> bool {
595 self.sources
596 .iter()
597 .any(|(_, status)| !matches!(status, CommandSourceStatus::NotFound))
598 }
599 }
600
601 /// One typed `/import-claude --apply` follow-up.
602 ///
603 /// The host supplies the facts; the command composes the sentences.
604 #[derive(Debug, Clone, PartialEq, Eq)]
605 pub enum CommandImportFollowUp {
606 InstructionsCopied { destination: String },
607 InstructionsKeptExisting { destination: String, source: String },
608 InstructionsCopyFailed { source: String, destination: String },
609 HomeUnresolved,
610 McpBlocked { name: String },
611 McpNeedsReview { name: String },
612 HookEvents { count: usize },
613 PermissionRules,
614 }
615
616 /// Paths and write outcomes from persisting the report/bundle.
617 #[derive(Debug, Clone, PartialEq, Eq)]
618 pub struct CommandClaudeArtifacts {
619 pub report_path: PathBuf,
620 pub bundle_path: PathBuf,
621 pub wrote_report: bool,
622 pub wrote_bundle: bool,
623 }
624
625 /// Typed `--apply` outcome; the command composes the final message.
626 #[derive(Debug, Clone, Default, PartialEq, Eq)]
627 pub struct CommandClaudeApplyOutcome {
628 pub done: Vec<CommandImportFollowUp>,
629 pub manual: Vec<CommandImportFollowUp>,
630 pub report_path: PathBuf,
631 pub wrote_report: bool,
632 }
633
633 lines RUST