返回 CodeWhale
command_catalog.rs
根目录 / crates / engine / src / command_catalog.rs
1 use codewhale_command_contract::CommandDiscovery;
2 use codewhale_localization::MessageId;
3 use std::path::Path;
4 use std::sync::{Arc, OnceLock};
5
6 #[derive(Debug, Clone)]
7 pub struct BuiltinCommand {
8 pub name: String,
9 pub aliases: Vec<String>,
10 pub usage: String,
11 pub description_id: MessageId,
12 pub subcommands: Vec<String>,
13 pub takes_arguments: bool,
14 pub requires_argument: bool,
15 pub requires_required_argument: bool,
16 pub composer_wants_trailing_space: bool,
17 pub palette_runs_directly: bool,
18 pub show_in_empty_discovery: bool,
19 pub discovery: CommandDiscovery,
20 pub unlisted: bool,
21 }
22
23 #[derive(Debug, Clone)]
24 pub struct UserCommand {
25 pub name: String,
26 pub aliases: Vec<String>,
27 pub description: Option<String>,
28 pub usage: Option<String>,
29 pub takes_arguments: bool,
30 pub hidden: bool,
31 pub extension: bool,
32 pub plugin_id: Option<String>,
33 pub workspace_sourced: bool,
34 pub builtin_bindings: Vec<String>,
35 }
36
37 #[derive(Debug, Clone, PartialEq, Eq)]
38 pub struct ExpandedUserCommand {
39 pub name: String,
40 pub message: String,
41 pub allowed_tools: Option<Vec<String>>,
42 pub plugin_id: Option<String>,
43 }
44
45 /// The host’s read-only command metadata and collision checks, implemented
46 /// by the commands side.
47 pub trait CommandCatalog: Send + Sync {
48 /// Whether a built-in command answers to `name` (lower case): a canonical
49 /// name, an alias, or one of the mode aliases the dispatcher answers ahead
50 /// of the registry.
51 fn answers_to(&self, name: &str) -> bool;
52 fn builtins(&self) -> Vec<BuiltinCommand>;
53 fn user_commands(&self, workspace: &Path) -> Vec<UserCommand>;
54 fn user_commands_with_plugins(
55 &self,
56 workspace: &Path,
57 _plugins: &codewhale_plugins::PluginRegistry,
58 ) -> Vec<UserCommand> {
59 self.user_commands(workspace)
60 }
61 fn expands_user_commands(&self) -> bool {
62 false
63 }
64 fn expand_user_command(
65 &self,
66 workspace: &Path,
67 plugins: &codewhale_plugins::PluginRegistry,
68 input: &str,
69 ) -> Option<Result<ExpandedUserCommand, String>> {
70 let _ = (workspace, plugins, input);
71 None
72 }
73 /// Whether this host executes `name` remotely at all. Checked before any
74 /// thread state is assembled, so a name outside the remote surface is
75 /// refused exactly like a name no host knows. `false` is the default: a
76 /// host opts in one command at a time, and widening this must widen
77 /// [`Self::execute_builtin`] too.
78 fn serves_builtin(&self, name: &str) -> bool {
79 let _ = name;
80 false
81 }
82 /// Execute one built-in command against a host snapshot. `None` means
83 /// this host does not implement remote execution, or does not answer to
84 /// the name; `Some` carries the command's own answer.
85 fn execute_builtin(
86 &self,
87 name: &str,
88 args: Option<&str>,
89 host: &BuiltinCommandHostSnapshot,
90 ) -> Option<BuiltinCommandExecution> {
91 let _ = (name, args, host);
92 None
93 }
94 }
95
96 /// The thread state a remote built-in execution reads.
97 ///
98 /// Engine-side so the app-server can assemble it from thread state and the
99 /// terminal host can interpret it without either depending on the other. The
100 /// projections are the command contract's own data-only types: the host maps
101 /// them into the facet envelope, and the capability mask each portable
102 /// handler declares decides which commands this snapshot can honestly serve.
103 pub struct BuiltinCommandHostSnapshot {
104 pub mode: codewhale_command_contract::types::CommandMode,
105 /// The host's own label for `mode` ("WORK", "PLAN"), the same string the
106 /// terminal footer shows.
107 pub mode_label: String,
108 pub locale: codewhale_localization::Locale,
109 pub model: String,
110 pub system_prompt: codewhale_command_contract::facets::DebugSystemPrompt,
111 /// Published usage telemetry and the host's cost breakdown for the
112 /// thread — the complete data source the portable `/tokens` and `/cost`
113 /// renderers consume.
114 pub tokens: codewhale_command_contract::facets::DebugTokenProjection,
115 }
116
117 /// One remote built-in execution's outcome.
118 pub struct BuiltinCommandExecution {
119 pub name: String,
120 pub text: String,
121 pub is_error: bool,
122 /// `false` when the command also asked the terminal host for an action —
123 /// the text is still what the command answered, but no API client can
124 /// perform that action (a balance fetch, a snapshot restore) on the
125 /// host's behalf.
126 pub text_only: bool,
127 }
128
129 static CATALOG: OnceLock<Arc<dyn CommandCatalog>> = OnceLock::new();
130
131 /// Install the process's catalog, once at startup. The first install wins and
132 /// returns `true`; a later one is ignored.
133 pub fn install(catalog: Arc<dyn CommandCatalog>) -> bool {
134 CATALOG.set(catalog).is_ok()
135 }
136
137 /// The installed catalog. `None` means none was installed (or, in a test, the
138 /// thread asked for none): command registration is refused.
139 pub fn installed() -> Option<Arc<dyn CommandCatalog>> {
140 #[cfg(any(test, feature = "test-support"))]
141 if let Some(chosen) = TEST_CATALOG.with(|cell| cell.borrow().clone()) {
142 return chosen;
143 }
144 CATALOG.get().cloned()
145 }
146
147 #[cfg(any(test, feature = "test-support"))]
148 thread_local! {
149 /// `Some(None)` is a thread that asked for no catalog at all.
150 static TEST_CATALOG: std::cell::RefCell<Option<Option<Arc<dyn CommandCatalog>>>> =
151 const { std::cell::RefCell::new(None) };
152 }
153
154 /// Test-only: route [`installed`] on this thread to a catalog (or to
155 /// none) until dropped, restoring what was there before, so tests never touch
156 /// the process-wide install.
157 #[cfg(any(test, feature = "test-support"))]
158 pub struct CatalogGuard(Option<Option<Arc<dyn CommandCatalog>>>);
159
160 #[cfg(any(test, feature = "test-support"))]
161 impl CatalogGuard {
162 pub fn install(catalog: Arc<dyn CommandCatalog>) -> Self {
163 Self(TEST_CATALOG.with(|cell| cell.replace(Some(Some(catalog)))))
164 }
165
166 /// This thread has no catalog, whatever the process installed.
167 pub fn absent() -> Self {
168 Self(TEST_CATALOG.with(|cell| cell.replace(Some(None))))
169 }
170 }
171
172 #[cfg(any(test, feature = "test-support"))]
173 impl Drop for CatalogGuard {
174 fn drop(&mut self) {
175 TEST_CATALOG.with(|cell| *cell.borrow_mut() = self.0.take());
176 }
177 }
178
178 lines RUST