返回 CodeWhale
cache.rs
根目录 / crates / commands / src / debug / cache.rs
1 //! `/cache` command — portable turn/call cache telemetry and inspection.
2 //!
3 //! The host resolves the request route and pricing partitions once. This
4 //! handler checks flags, observes, formats and commits that same inspection;
5 //! no prompt builder or App state is reachable from the command leaf.
6
7 use super::CommandResult;
8 use super::DebugAction as AppAction;
9 use super::cache_format::{
10 format_cache_calls, format_cache_history, format_cache_stats, format_cache_zones,
11 format_first_divergence, format_static_prefix_status, format_verbose_diff,
12 format_warmup_status, session_cache_rates_line,
13 };
14 use codewhale_command_contract::facets::{
15 CommandDebugDiagnosticsContext, CommandPresentationContext, DebugCacheInspectionObservation,
16 DebugCacheInspectionUnavailable,
17 };
18 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
19 use codewhale_command_contract::metadata::{
20 CommandInfo as ContractInfo, RegisterCommand as ContractRegisterCommand,
21 };
22
23 pub struct CacheCmd;
24
25 const CONTRACT_INFO: ContractInfo = ContractInfo {
26 name: "cache",
27 aliases: &[],
28 usage: "/cache [count|calls [count]|inspect|stats|zones|warmup]",
29 description_key: "cmd_cache_description",
30 };
31
32 impl ContractRegisterCommand<CommandResult> for CacheCmd {
33 fn info() -> &'static ContractInfo {
34 &CONTRACT_INFO
35 }
36
37 fn handler() -> CommandHandler<CommandResult> {
38 CommandHandler::Contextual {
39 capabilities: CommandCapabilities::DEBUG_DIAGNOSTICS
40 .union(CommandCapabilities::PRESENTATION),
41 handler: cache,
42 }
43 }
44 }
45
46 /// Show turn/call prefix-cache telemetry, a static status or an inspection.
47 pub fn cache(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
48 let mut parts = contexts.into_parts();
49 let Some(diagnostics) = parts.debug_diagnostics.as_deref_mut() else {
50 return CommandResult::error("Command capability unavailable: debug_diagnostics");
51 };
52 let Some(presentation) = parts.presentation.as_deref_mut() else {
53 return CommandResult::error("Command capability unavailable: presentation");
54 };
55 cache_portable(diagnostics, presentation, arg)
56 }
57
58 fn cache_portable(
59 diagnostics: &mut dyn CommandDebugDiagnosticsContext,
60 presentation: &dyn CommandPresentationContext,
61 arg: Option<&str>,
62 ) -> CommandResult {
63 let arg = arg.map(str::trim).filter(|s| !s.is_empty());
64 if let Some(count) = arg.and_then(|value| {
65 value
66 .strip_prefix("calls")
67 .filter(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
68 }) {
69 let want = if count.trim().is_empty() {
70 10
71 } else {
72 match count.trim().parse::<usize>() {
73 Ok(count) => count,
74 Err(_) => return CommandResult::error("Usage: /cache calls [count]"),
75 }
76 };
77 return CommandResult::message(format_cache_calls(&diagnostics.cache_telemetry(), want));
78 }
79 let inspect_flags = arg.and_then(|a| {
80 if a == "inspect" {
81 Some("")
82 } else {
83 a.strip_prefix("inspect")
84 .filter(|rest| rest.starts_with(char::is_whitespace))
85 }
86 });
87 if let Some(flags) = inspect_flags {
88 let flags = flags.trim();
89 let verbose = flags.split_whitespace().any(|flag| flag == "--verbose");
90 let json_mode = flags.split_whitespace().any(|flag| flag == "--json");
91 return CommandResult::message(format_cache_inspect(diagnostics, verbose, json_mode));
92 }
93 if matches!(arg, Some("warmup")) {
94 return CommandResult::action(AppAction::CacheWarmup);
95 }
96 if matches!(arg, Some("stats")) {
97 return CommandResult::message(format_cache_stats(&diagnostics.cache_telemetry()));
98 }
99 if matches!(arg, Some("zones")) {
100 return CommandResult::message(format_cache_zones(&diagnostics.cache_telemetry()));
101 }
102
103 let want = match arg {
104 None => 10,
105 Some(raw) => match raw.parse::<usize>() {
106 Ok(n) => n,
107 Err(_) => {
108 return CommandResult::error(format!(
109 "Unknown /cache argument `{raw}`. Usage: /cache [count|calls [count]|inspect [--verbose|--json]|stats|zones|warmup]"
110 ));
111 }
112 },
113 };
114 let telemetry = diagnostics.cache_telemetry();
115 if telemetry.history.is_empty() {
116 let message = (|| {
117 let mut text = presentation.translate("cmd_cache_no_data", &[])?;
118 if let Some(line) = session_cache_rates_line(&telemetry, presentation)? {
119 text.push_str("\n\n");
120 text.push_str(&line);
121 }
122 Ok::<_, String>(text)
123 })();
124 return match message {
125 Ok(text) => CommandResult::message(text),
126 Err(error) => CommandResult::error(error),
127 };
128 }
129 let count = want
130 .min(telemetry.history.len())
131 .min(telemetry.history_capacity);
132 let cost = diagnostics.cost_projection();
133 match format_cache_history(&telemetry, count, &cost, presentation) {
134 Ok(text) => CommandResult::message(text),
135 Err(error) => CommandResult::error(error),
136 }
137 }
138
139 fn format_cache_inspect(
140 diagnostics: &mut dyn CommandDebugDiagnosticsContext,
141 verbose: bool,
142 json_mode: bool,
143 ) -> String {
144 if verbose && json_mode {
145 return "cache inspect: --json and --verbose cannot be combined".to_string();
146 }
147 let observation = match diagnostics.inspect_cache() {
148 Ok(value) => value,
149 Err(DebugCacheInspectionUnavailable::NoConcreteRoute) => {
150 return "cache inspect: Auto has no concrete route yet; send a turn first".to_string();
151 }
152 Err(DebugCacheInspectionUnavailable::MissingCapturedEndpoint) => {
153 return "cache inspect: the restored Auto route has no captured endpoint; send a turn first"
154 .to_string();
155 }
156 };
157 let output = render_inspection(&observation, verbose, json_mode);
158 commit_rendered_inspection(diagnostics, observation, output)
159 }
160
161 pub(super) fn commit_rendered_inspection(
162 diagnostics: &mut dyn CommandDebugDiagnosticsContext,
163 observation: DebugCacheInspectionObservation,
164 output: String,
165 ) -> String {
166 diagnostics.remember_cache_inspection(observation.current);
167 output
168 }
169
170 pub(super) fn json_or_fallback(rendered: Result<String, serde_json::Error>) -> String {
171 rendered.unwrap_or_else(|_| "{\"error\":\"cache inspection serialization failed\"}".to_string())
172 }
173
174 fn render_inspection(
175 observation: &DebugCacheInspectionObservation,
176 verbose: bool,
177 json_mode: bool,
178 ) -> String {
179 let inspection = &observation.current;
180 let previous = observation.previous.as_ref();
181 let warmup_status = format_warmup_status(
182 observation.last_warmup_key.as_ref(),
183 &observation.current_warmup_key,
184 observation.last_warmup_hash_short.as_deref(),
185 &observation.current_warmup_hash_short,
186 );
187 if json_mode {
188 return json_or_fallback(serde_json::to_value(inspection).and_then(|mut value| {
189 if let serde_json::Value::Object(ref mut object) = value {
190 object.insert(
191 "current_warmup_key".to_string(),
192 serde_json::to_value(&observation.current_warmup_key)?,
193 );
194 object.insert(
195 "warmup_status".to_string(),
196 serde_json::Value::String(warmup_status.trim_end().to_string()),
197 );
198 }
199 serde_json::to_string_pretty(&value)
200 }));
201 }
202
203 let mut out = String::new();
204 out.push_str("Cache Inspect\n");
205 out.push_str("Full prompt text is not printed. Hashes are SHA-256 of each rendered layer.\n");
206 out.push_str(&format!(
207 "Base static prefix hash: {}\n",
208 inspection.base_static_prefix_hash
209 ));
210 out.push_str(&format!(
211 "Full request prefix hash: {}\n",
212 inspection.full_request_prefix_hash
213 ));
214 out.push_str(&format!(
215 "Tool catalog hash: {}\n",
216 if inspection.tool_catalog_hash.is_empty() {
217 "(no tools registered)".to_string()
218 } else {
219 inspection.tool_catalog_hash.clone()
220 }
221 ));
222 out.push_str(&format_static_prefix_status(previous, inspection));
223 out.push_str(&format_first_divergence(previous, inspection));
224 out.push_str(&warmup_status);
225 let total_tokens: usize = inspection
226 .layers
227 .iter()
228 .map(|layer| layer.token_estimate)
229 .sum();
230 out.push_str(&format!("Estimated reusable tokens: ~{total_tokens}\n"));
231 out.push('\n');
232
233 for layer in &inspection.layers {
234 let mut line = format!(
235 "{}: {}, chars={}, bytes={}, ~{}tok, hash={}\n",
236 layer.name,
237 layer.stability.label(),
238 layer.char_len,
239 layer.byte_len,
240 layer.token_estimate,
241 layer.sha256
242 );
243 if let Some(tool_result) = &layer.tool_result {
244 let trimmed = line.trim_end_matches('\n').to_string();
245 line = format!(
246 "{trimmed}, original_chars={}, sent_chars={}, truncated={}, deduplicated={}\n",
247 tool_result.original_chars,
248 tool_result.sent_chars,
249 tool_result.truncated,
250 tool_result.deduplicated
251 );
252 }
253 if let Some(turn_meta) = &layer.turn_meta {
254 let trimmed = line.trim_end_matches('\n').to_string();
255 line = format!(
256 "{trimmed}, turn_meta_original_chars={}, turn_meta_sent_chars={}, turn_meta_deduplicated={}, turn_meta_sha256={}\n",
257 turn_meta.original_chars,
258 turn_meta.sent_chars,
259 turn_meta.deduplicated,
260 turn_meta.sha256
261 );
262 }
263 out.push_str(&line);
264 }
265 if verbose {
266 out.push_str("\nVerbose diff\n");
267 if let Some(previous) = previous {
268 out.push_str(&format_verbose_diff(previous, inspection));
269 } else {
270 out.push_str("No previous inspection to compare against.\n");
271 }
272 }
273 out
274 }
275
275 lines RUST