返回 CodeWhale
builtin_execution.rs
根目录 / crates / tui / src / commands / builtin_execution.rs
1 //! Remote built-in command execution over the engine's host snapshot.
2 //!
3 //! The app-server assembles a [`BuiltinCommandHostSnapshot`] from thread
4 //! state and calls [`execute_builtin`] through the installed catalog. This
5 //! module is the terminal host's side: it maps the snapshot into the command
6 //! contract's facet envelope and runs the portable debug handlers.
7 //!
8 //! Phase 1 serves exactly the read-only diagnostics commands whose every
9 //! data path the snapshot backs faithfully (`/system`, `/tokens`, `/cost`).
10 //! Two gates keep the surface honest: the [`SERVED`] allowlist, and the
11 //! handler-declared capability mask checked against [`PROVIDED`]. Commands
12 //! outside both are refused by returning `None`, which the API renders as
13 //! an unknown command rather than a degraded answer.
14
15 use codewhale_command_contract::facets::{
16 CommandDebugDiagnosticsContext, CommandPresentationContext, DebugBalanceProjection,
17 DebugCacheCall, DebugCacheInspectionUnavailable, DebugCacheRates, DebugCacheTelemetry,
18 DebugCostProjection, DebugPromptContext, DebugPromptSourceMap, DebugSystemProjection,
19 DebugTokenProjection, DebugToolSnapshot,
20 };
21 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
22 use codewhale_engine::command_catalog::{BuiltinCommandExecution, BuiltinCommandHostSnapshot};
23 use codewhale_localization::{Locale, tr};
24
25 use crate::commands::contract::{apply_named_replacements, resolve_message_id};
26 use codewhale_commands::debug as portable_debug;
27
28 /// Facets this remote host can honestly provide from the snapshot.
29 const PROVIDED: CommandCapabilities =
30 CommandCapabilities::DEBUG_DIAGNOSTICS.union(CommandCapabilities::PRESENTATION);
31
32 /// The phase-1 served set: read-only diagnostics whose every projection the
33 /// snapshot carries. Widening this list requires widening the snapshot with
34 /// faithfully assembled data first — never an adapter that guesses.
35 const SERVED: [&str; 3] = ["system", "tokens", "cost"];
36
37 // ---------------------------------------------------------------------------
38 // Facet adapters over the snapshot
39 // ---------------------------------------------------------------------------
40
41 struct SnapshotDiagnostics<'a> {
42 snapshot: &'a BuiltinCommandHostSnapshot,
43 }
44
45 impl CommandDebugDiagnosticsContext for SnapshotDiagnostics<'_> {
46 /// Never served remotely: the provider-balance probe is a host action,
47 /// and the allowlist keeps `/balance` off this surface. The projection
48 /// states what the snapshot genuinely knows: nothing.
49 fn balance_projection(&self) -> DebugBalanceProjection {
50 DebugBalanceProjection {
51 provider_display_name: "unavailable".to_string(),
52 supports_balance_api: false,
53 }
54 }
55
56 fn system_projection(&self) -> DebugSystemProjection {
57 DebugSystemProjection {
58 mode_label: self.snapshot.mode_label.clone(),
59 prompt: self.snapshot.system_prompt.clone(),
60 }
61 }
62
63 fn token_projection(&self) -> DebugTokenProjection {
64 self.snapshot.tokens.clone()
65 }
66
67 fn cost_projection(&self) -> DebugCostProjection {
68 self.snapshot.tokens.cost.clone()
69 }
70
71 /// Assembled prompt-layer telemetry is a terminal-host report; the
72 /// remote surface does not serve `/context`, so this stays an explicitly
73 /// empty map rather than a partial reconstruction.
74 fn context_source_map(&self) -> DebugPromptSourceMap {
75 DebugPromptSourceMap {
76 entries: Vec::new(),
77 total_estimated_tokens: 0,
78 active_context_estimated_tokens: 0,
79 overflow_guard_estimated_tokens: None,
80 context_window_tokens: None,
81 context_window_source: None,
82 budget_used_percent: None,
83 pressure_label: String::new(),
84 context_window_verified: false,
85 generated_at: String::new(),
86 note: "not assembled over the remote command surface".to_string(),
87 }
88 }
89
90 fn prompt_context(&self) -> DebugPromptContext {
91 DebugPromptContext {
92 schema_version: 0,
93 provider: String::new(),
94 model: self.snapshot.model.clone(),
95 system_prompt_state: String::new(),
96 tool_catalog_state: String::new(),
97 sections: Vec::new(),
98 tools: Vec::new(),
99 source_map: self.context_source_map(),
100 }
101 }
102
103 fn tool_snapshot(&self) -> Option<DebugToolSnapshot> {
104 None
105 }
106
107 fn inspect_cache(
108 &self,
109 ) -> Result<
110 codewhale_command_contract::DebugCacheInspectionObservation,
111 DebugCacheInspectionUnavailable,
112 > {
113 Err(DebugCacheInspectionUnavailable::NoConcreteRoute)
114 }
115
116 fn remember_cache_inspection(
117 &mut self,
118 _inspection: codewhale_command_contract::facets::DebugPromptInspection,
119 ) {
120 // Read-only surface: nothing to remember between remote executions.
121 }
122
123 /// The remote surface does not serve `/cache`; the honest encoding of
124 /// "not assembled" is absent telemetry, never zeros dressed as data.
125 fn cache_telemetry(&self) -> DebugCacheTelemetry {
126 DebugCacheTelemetry {
127 model: self.snapshot.model.clone(),
128 session_cache_rates: DebugCacheRates::default(),
129 history: Vec::new(),
130 calls: Vec::<DebugCacheCall>::new(),
131 calls_total: 0,
132 calls_currency: self.snapshot.tokens.cost.currency,
133 calls_legacy_coverage_unknown: false,
134 history_capacity: 0,
135 prefix_stability_pct: None,
136 prefix_checks_total: 0,
137 prefix_change_count: 0,
138 prefix_drift_count: 0,
139 prefix_context_updates: 0,
140 prefix_pin_reason: None,
141 prefix_last_miss_reason: None,
142 last_prefix_change_desc: None,
143 last_pinned_prefix_hash: None,
144 api_message_count: self.snapshot.tokens.api_message_count,
145 non_system_message_count: self.snapshot.tokens.chat_message_count,
146 }
147 }
148 }
149
150 struct SnapshotPresentation {
151 locale: Locale,
152 }
153
154 impl CommandPresentationContext for SnapshotPresentation {
155 fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> {
156 let message_id = resolve_message_id(key).ok_or("unknown translation key")?;
157 let template = tr(self.locale, message_id);
158 apply_named_replacements(&template, replacements)
159 .ok_or_else(|| "invalid translation replacement contract".to_string())
160 }
161
162 fn language_name(&self) -> &'static str {
163 self.locale.translation_target_name()
164 }
165 }
166
167 // ---------------------------------------------------------------------------
168 // Execution
169 // ---------------------------------------------------------------------------
170
171 /// Execute one built-in command against the snapshot, or `None` when the
172 /// command is outside the remote surface.
173 pub fn execute_builtin(
174 name: &str,
175 args: Option<&str>,
176 snapshot: &BuiltinCommandHostSnapshot,
177 ) -> Option<BuiltinCommandExecution> {
178 let (info, handler) = resolve(name)?;
179 let CommandHandler::Contextual {
180 capabilities,
181 handler: run,
182 } = handler
183 else {
184 return None;
185 };
186 // The capability mask is the second gate: a handler that grew a new
187 // facet requirement is refused until the snapshot grows the data for it.
188 if !PROVIDED.contains(capabilities) {
189 return None;
190 }
191
192 let mut diagnostics = SnapshotDiagnostics { snapshot };
193 let mut presentation = SnapshotPresentation {
194 locale: snapshot.locale,
195 };
196 let contexts = CommandContexts::empty()
197 .with_debug_diagnostics(&mut diagnostics)
198 .with_presentation(&mut presentation);
199 let result: portable_debug::CommandResult = run(contexts, args);
200 Some(BuiltinCommandExecution {
201 name: info.name.to_string(),
202 text: result.message.unwrap_or_default(),
203 is_error: result.is_error,
204 text_only: result.action.is_none(),
205 })
206 }
207
208 /// Whether `name` is on the remote surface at all. Shares [`resolve`] with
209 /// [`execute_builtin`], so the two gates can never disagree about a name.
210 pub fn serves_builtin(name: &str) -> bool {
211 resolve(name).is_some()
212 }
213
214 /// The portable handler a raised spelling (canonical name or alias) names,
215 /// gated by the [`SERVED`] allowlist and the [`PROVIDED`] capability mask.
216 fn resolve(
217 name: &str,
218 ) -> Option<(
219 &'static codewhale_command_contract::metadata::CommandInfo,
220 CommandHandler<portable_debug::CommandResult>,
221 )> {
222 let spelling = name.trim_start_matches('/').to_ascii_lowercase();
223 let (info, handler) = portable_debug::portable_handlers()
224 .into_iter()
225 .find(|(info, _)| {
226 info.name == spelling.as_str() || info.aliases.contains(&spelling.as_str())
227 })?;
228 // The allowlist gates on the canonical name, so an alias resolves to the
229 // same served command its canonical spelling is.
230 if !SERVED.contains(&info.name) {
231 return None;
232 }
233 // A non-contextual handler asks nothing of the host, so it has nothing to
234 // read and is refused here rather than served an empty envelope.
235 if !matches!(handler, CommandHandler::Contextual { capabilities, .. } if PROVIDED.contains(capabilities))
236 {
237 return None;
238 }
239 Some((info, handler))
240 }
241
242 #[cfg(test)]
243 mod tests {
244 use super::*;
245 use codewhale_command_contract::facets::DebugSystemPrompt;
246 use codewhale_command_contract::types::{CommandCurrency, CommandMode};
247
248 fn snapshot() -> BuiltinCommandHostSnapshot {
249 BuiltinCommandHostSnapshot {
250 mode: CommandMode::Agent,
251 mode_label: "WORK".to_string(),
252 locale: Locale::En,
253 model: "deepseek-v4-pro".to_string(),
254 system_prompt: DebugSystemPrompt::Text("You are helpful.".to_string()),
255 tokens: DebugTokenProjection {
256 active_context_used: 4_200,
257 context_window: 131_072,
258 last_input: Some(3_900),
259 last_output: Some(312),
260 cache_hit: Some(3_400),
261 cache_miss: Some(500),
262 total_tokens: 21_000,
263 cache_write_tokens: 640,
264 api_message_count: 12,
265 chat_message_count: 8,
266 model: "deepseek-v4-pro".to_string(),
267 cost: DebugCostProjection {
268 currency: CommandCurrency::Usd,
269 total: 0.012_5,
270 parent_turns: 0.012,
271 subagents: 0.000_5,
272 display_floor: 0.0,
273 priced_turns: 6,
274 unpriced_turns: 0,
275 legacy_coverage_unknown: false,
276 user_declared_estimates: false,
277 itemized_turns: 6,
278 route_amounts: Vec::new(),
279 turn_history_capacity: 40,
280 unpriced_reason_labels: Vec::new(),
281 unpriced_classes: Vec::new(),
282 pricing_provenances: Vec::new(),
283 live_pricing_defects: Vec::new(),
284 unusable_pricing_defects: Vec::new(),
285 route_receipts: Vec::new(),
286 },
287 },
288 }
289 }
290
291 #[test]
292 fn serves_system_with_mode_label_and_prompt() {
293 let execution = execute_builtin("system", None, &snapshot()).expect("served");
294 assert_eq!(execution.name, "system");
295 assert!(!execution.is_error);
296 assert!(execution.text_only);
297 assert!(execution.text.contains("WORK"));
298 assert!(execution.text.contains("You are helpful."));
299 }
300
301 #[test]
302 fn serves_tokens_with_published_usage() {
303 let execution = execute_builtin("/tokens", None, &snapshot()).expect("served");
304 assert_eq!(execution.name, "tokens");
305 assert!(execution.text.contains("21,000") || execution.text.contains("21000"));
306 assert!(execution.text.contains("deepseek-v4-pro"));
307 }
308
309 #[test]
310 fn serves_cost_with_the_priced_subtotal() {
311 let execution = execute_builtin("cost", None, &snapshot()).expect("served");
312 assert!(!execution.is_error);
313 assert!(!execution.text.is_empty());
314 }
315
316 #[test]
317 fn resolves_engine_aliases_to_the_canonical_command() {
318 let execution = execute_builtin("xitong", None, &snapshot()).expect("served");
319 assert_eq!(execution.name, "system");
320 }
321
322 #[test]
323 fn the_served_gate_agrees_with_execution_for_every_spelling() {
324 // The route checks `serves_builtin` before assembling any thread
325 // state, then calls `execute_builtin`: a name the first gate admits
326 // must never be refused by the second, and vice versa.
327 let snapshot = snapshot();
328 let mut spellings: Vec<String> = SERVED.iter().map(|name| (*name).to_string()).collect();
329 for (info, _) in portable_debug::portable_handlers() {
330 spellings.push(info.name.to_string());
331 spellings.extend(info.aliases.iter().map(|alias| (*alias).to_string()));
332 }
333 spellings.push("nope".to_string());
334 for name in spellings {
335 for raised in [name.clone(), format!("/{name}"), name.to_uppercase()] {
336 let served = serves_builtin(&raised);
337 let executed = execute_builtin(&raised, None, &snapshot).is_some();
338 assert_eq!(served, executed, "{raised}");
339 }
340 }
341 }
342
343 #[test]
344 fn refuses_commands_outside_the_phase1_allowlist() {
345 // /balance is a host action (FetchBalance), /cache needs assembled
346 // telemetry, /undo needs the undo facet: none are honestly served.
347 for name in [
348 "balance", "cache", "undo", "retry", "context", "tools", "nope",
349 ] {
350 assert!(execute_builtin(name, None, &snapshot()).is_none(), "{name}");
351 }
352 }
353 }
354
354 lines RUST