返回 CodeWhale
tokens.rs
根目录 / crates / commands / src / debug / tokens.rs
1 //! Portable token, cost, system-prompt and context diagnostics.
2 //!
3 //! The host owns counting, route pricing, pressure classification and prompt
4 //! construction; these handlers compose only declared semantic projections.
5
6 use codewhale_command_contract::facets::{
7 CommandPresentationContext, DebugCostProjection, DebugSystemPrompt, DebugTokenProjection,
8 };
9 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
10 use codewhale_command_contract::metadata::{
11 CommandInfo as ContractInfo, RegisterCommand as ContractRegisterCommand,
12 };
13
14 use super::CommandResult;
15 use super::DebugAction as AppAction;
16 use crate::diagnostics_reports as reports;
17
18 pub struct TokensCmd;
19 pub struct CostCmd;
20 pub struct SystemCmd;
21 pub struct ContextCmd;
22
23 const TOKENS_INFO: ContractInfo = ContractInfo {
24 name: "tokens",
25 aliases: &[],
26 usage: "/tokens",
27 description_key: "cmd_tokens_description",
28 };
29 const COST_INFO: ContractInfo = ContractInfo {
30 name: "cost",
31 aliases: &[],
32 usage: "/cost [details]",
33 description_key: "cmd_cost_description",
34 };
35 const SYSTEM_INFO: ContractInfo = ContractInfo {
36 name: "system",
37 aliases: &["xitong"],
38 usage: "/system",
39 description_key: "cmd_system_description",
40 };
41 const CONTEXT_INFO: ContractInfo = ContractInfo {
42 name: "context",
43 aliases: &["ctx"],
44 usage: "/context [report|json|prompt-json|summary|limit <tokens|reset>]",
45 description_key: "cmd_context_description",
46 };
47
48 impl ContractRegisterCommand<CommandResult> for TokensCmd {
49 fn info() -> &'static ContractInfo {
50 &TOKENS_INFO
51 }
52 fn handler() -> CommandHandler<CommandResult> {
53 CommandHandler::Contextual {
54 capabilities: CommandCapabilities::DEBUG_DIAGNOSTICS
55 .union(CommandCapabilities::PRESENTATION),
56 handler: |contexts, _| tokens(contexts),
57 }
58 }
59 }
60 impl ContractRegisterCommand<CommandResult> for CostCmd {
61 fn info() -> &'static ContractInfo {
62 &COST_INFO
63 }
64 fn handler() -> CommandHandler<CommandResult> {
65 CommandHandler::Contextual {
66 capabilities: CommandCapabilities::DEBUG_DIAGNOSTICS
67 .union(CommandCapabilities::PRESENTATION),
68 handler: cost,
69 }
70 }
71 }
72 impl ContractRegisterCommand<CommandResult> for SystemCmd {
73 fn info() -> &'static ContractInfo {
74 &SYSTEM_INFO
75 }
76 fn handler() -> CommandHandler<CommandResult> {
77 CommandHandler::Contextual {
78 capabilities: CommandCapabilities::DEBUG_DIAGNOSTICS,
79 handler: |contexts, _| system_prompt(contexts),
80 }
81 }
82 }
83 impl ContractRegisterCommand<CommandResult> for ContextCmd {
84 fn info() -> &'static ContractInfo {
85 &CONTEXT_INFO
86 }
87 fn handler() -> CommandHandler<CommandResult> {
88 CommandHandler::Contextual {
89 capabilities: CommandCapabilities::DEBUG_DIAGNOSTICS,
90 handler: context,
91 }
92 }
93 }
94
95 const DIAGNOSTICS_UNAVAILABLE: &str = "Command capability unavailable: debug_diagnostics";
96 const PRESENTATION_UNAVAILABLE: &str = "Command capability unavailable: presentation";
97
98 fn localized(
99 presentation: &dyn CommandPresentationContext,
100 key: &str,
101 replacements: &[(&str, &str)],
102 ) -> Result<String, String> {
103 presentation.translate(key, replacements)
104 }
105
106 fn token_count(
107 value: Option<u32>,
108 presentation: &dyn CommandPresentationContext,
109 ) -> Result<String, String> {
110 value.map_or_else(
111 || localized(presentation, "cmd_tokens_not_reported", &[]),
112 |tokens| Ok(tokens.to_string()),
113 )
114 }
115
116 fn active_context_summary(
117 usage: &DebugTokenProjection,
118 presentation: &dyn CommandPresentationContext,
119 ) -> Result<String, String> {
120 let percent = (usage.active_context_used as f64 / f64::from(usage.context_window) * 100.0)
121 .clamp(0.0, 100.0);
122 localized(
123 presentation,
124 "cmd_tokens_context_with_window",
125 &[
126 ("used", &usage.active_context_used.to_string()),
127 ("window", &usage.context_window.to_string()),
128 ("percent", &format!("{percent:.1}")),
129 ],
130 )
131 }
132
133 fn cache_summary(
134 usage: &DebugTokenProjection,
135 presentation: &dyn CommandPresentationContext,
136 ) -> Result<String, String> {
137 match (usage.cache_hit, usage.cache_miss) {
138 (Some(hit), Some(miss)) => localized(
139 presentation,
140 "cmd_tokens_cache_both",
141 &[("hit", &hit.to_string()), ("miss", &miss.to_string())],
142 ),
143 (Some(hit), None) => localized(
144 presentation,
145 "cmd_tokens_cache_hit_only",
146 &[("hit", &hit.to_string())],
147 ),
148 (None, Some(miss)) => localized(
149 presentation,
150 "cmd_tokens_cache_miss_only",
151 &[("miss", &miss.to_string())],
152 ),
153 (None, None) => localized(presentation, "cmd_tokens_not_reported", &[]),
154 }
155 }
156
157 /// Show token usage for the current session, without opening host state.
158 pub fn tokens(contexts: CommandContexts<'_>) -> CommandResult {
159 let mut parts = contexts.into_parts();
160 let Some(diagnostics) = parts.debug_diagnostics.as_deref_mut() else {
161 return CommandResult::error(DIAGNOSTICS_UNAVAILABLE);
162 };
163 let Some(presentation) = parts.presentation.as_deref_mut() else {
164 return CommandResult::error(PRESENTATION_UNAVAILABLE);
165 };
166 let usage = diagnostics.token_projection();
167 match tokens_report(&usage, presentation) {
168 Ok(report) => CommandResult::message(report),
169 Err(error) => CommandResult::error(error),
170 }
171 }
172
173 fn tokens_report(
174 usage: &DebugTokenProjection,
175 presentation: &dyn CommandPresentationContext,
176 ) -> Result<String, String> {
177 let mut report = localized(
178 presentation,
179 "cmd_tokens_report",
180 &[
181 ("active", &active_context_summary(usage, presentation)?),
182 ("input", &token_count(usage.last_input, presentation)?),
183 ("output", &token_count(usage.last_output, presentation)?),
184 ("cache", &cache_summary(usage, presentation)?),
185 ("total", &usage.total_tokens.to_string()),
186 ("cost", &cost_report_amount(&usage.cost, presentation)?),
187 ("api_messages", &usage.api_message_count.to_string()),
188 ("chat_messages", &usage.chat_message_count.to_string()),
189 ("model", &usage.model),
190 ],
191 )?;
192 report.push('\n');
193 report.push_str(&localized(
194 presentation,
195 "cmd_tokens_cache_write_total",
196 &[(
197 "write",
198 &if usage.cache_write_tokens > 0 {
199 usage.cache_write_tokens.to_string()
200 } else {
201 localized(presentation, "cmd_tokens_not_reported", &[])?
202 },
203 )],
204 )?);
205 report.push_str(&cost_coverage_report(&usage.cost, presentation)?);
206 Ok(report)
207 }
208
209 /// Show session cost with the same coverage disclaimer as `/tokens`.
210 pub fn cost(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
211 let mut parts = contexts.into_parts();
212 let Some(diagnostics) = parts.debug_diagnostics.as_deref_mut() else {
213 return CommandResult::error(DIAGNOSTICS_UNAVAILABLE);
214 };
215 let Some(presentation) = parts.presentation.as_deref_mut() else {
216 return CommandResult::error(PRESENTATION_UNAVAILABLE);
217 };
218 let projection = diagnostics.cost_projection();
219 let details = arg.is_some_and(|arg| arg.trim().eq_ignore_ascii_case("details"));
220 if cost_is_subscription_only(&projection) && !details {
221 return CommandResult::message(format!(
222 "Session Cost:\n ─────────────────────────────\n {SUBSCRIPTION_ONLY_COST_NOTE}\n\n Run /cost details for the route receipts."
223 ));
224 }
225 match cost_report(&projection, presentation) {
226 Ok(report) => CommandResult::message(report),
227 Err(error) => CommandResult::error(error),
228 }
229 }
230
231 pub const SUBSCRIPTION_ONLY_COST_NOTE: &str = "These routes use subscription billing. Codewhale does not know the amount charged by your provider.";
232
233 pub fn cost_is_subscription_only(projection: &DebugCostProjection) -> bool {
234 projection.total == 0.0
235 && projection.priced_turns == 0
236 && projection.unpriced_turns == 0
237 && !projection.legacy_coverage_unknown
238 && !projection.user_declared_estimates
239 && !projection.route_receipts.is_empty()
240 && projection.route_receipts.iter().all(|receipt| {
241 receipt
242 .split_whitespace()
243 .any(|field| field == "billing_mode=subscription")
244 })
245 }
246
247 pub fn cost_report(
248 cost: &DebugCostProjection,
249 presentation: &dyn CommandPresentationContext,
250 ) -> Result<String, String> {
251 let saved_legacy_subtotal = cost.legacy_coverage_unknown && cost.total > 0.0;
252 let headline = if cost.priced_turns == 0 && !saved_legacy_subtotal {
253 "cmd_cost_report_unknown"
254 } else if cost.legacy_coverage_unknown || cost.unpriced_turns > 0 {
255 "cmd_cost_report_subtotal"
256 } else {
257 "cmd_cost_report"
258 };
259 let mut report = if cost.user_declared_estimates {
260 format!(
261 "Session cost estimate (priced subtotal): {}",
262 cost_report_amount(cost, presentation)?
263 )
264 } else if headline == "cmd_cost_report_unknown" {
265 // The unknown template has no `{cost}` placeholder; the legacy
266 // renderer's no-op replacement did not require one.
267 localized(presentation, headline, &[])?
268 } else {
269 localized(
270 presentation,
271 headline,
272 &[("cost", &cost_report_amount(cost, presentation)?)],
273 )?
274 };
275 if cost.priced_turns > 0 || saved_legacy_subtotal {
276 report.push_str(&cost_breakdown_report(cost));
277 }
278 report.push_str(&cost_coverage_report(cost, presentation)?);
279 Ok(report)
280 }
281
282 fn cost_report_amount(
283 cost: &DebugCostProjection,
284 presentation: &dyn CommandPresentationContext,
285 ) -> Result<String, String> {
286 if cost.priced_turns > 0 || (cost.legacy_coverage_unknown && cost.total > 0.0) {
287 Ok(reports::format_cost_amount_precise(
288 cost.total,
289 cost.currency,
290 ))
291 } else {
292 localized(presentation, "cmd_cost_unknown_value", &[])
293 }
294 }
295
296 fn cost_breakdown_report(cost: &DebugCostProjection) -> String {
297 let format = |value| reports::format_cost_amount_precise(value, cost.currency);
298 let mut out = String::from("\n\nBreakdown (components sum to the total above):");
299 out.push_str(&format!("\n Parent turns: {}", format(cost.parent_turns)));
300 if cost.subagents > 0.0 {
301 out.push_str(&format!("\n Sub-agents: {}", format(cost.subagents)));
302 }
303 if cost.display_floor > 0.0 {
304 out.push_str(&format!(
305 "\n Reconciliation floor: {} (monotonic display guarantee, kept after a downward cost reconciliation)",
306 format(cost.display_floor)
307 ));
308 }
309 if !cost.route_amounts.is_empty() {
310 out.push_str(&format!(
311 "\n Parent-turn spend by route ({} of {} priced turns itemized):",
312 cost.itemized_turns, cost.priced_turns
313 ));
314 for route in &cost.route_amounts {
315 out.push_str(&format!("\n {}: {}", route.route, format(route.amount)));
316 }
317 if cost.itemized_turns < cost.priced_turns {
318 out.push_str(&format!(
319 "\n (earlier turns not itemized: turn telemetry keeps the last {})",
320 cost.turn_history_capacity
321 ));
322 }
323 }
324 out
325 }
326
327 fn formatted_unpriced_reasons(
328 cost: &DebugCostProjection,
329 presentation: &dyn CommandPresentationContext,
330 ) -> Result<String, String> {
331 let mut descriptions: Vec<String> = Vec::new();
332 if cost.unpriced_reason_labels.is_empty() {
333 return localized(presentation, "cost_reason_unrecorded_coverage", &[]);
334 }
335 for reason in &cost.unpriced_reason_labels {
336 // Classification comes from the host's UnpricedReason::from_label;
337 // duplicate localized explanations collapse exactly as before.
338 let description = localized(presentation, &format!("cost_reason_{reason}"), &[])?;
339 if !descriptions.contains(&description) {
340 descriptions.push(description);
341 }
342 }
343 Ok(descriptions.join(", "))
344 }
345
346 /// The identical honesty block used by both diagnostic monetary surfaces.
347 fn cost_coverage_report(
348 cost: &DebugCostProjection,
349 presentation: &dyn CommandPresentationContext,
350 ) -> Result<String, String> {
351 let mut out = String::from("\n\n");
352 if cost.user_declared_estimates {
353 out.push_str("Includes user-declared, unverified price estimates calculated from recorded usage. These amounts do not establish provider prices, billing mode, or an invoice.");
354 } else {
355 out.push_str(&localized(presentation, "cmd_cost_estimate_only", &[])?);
356 }
357 out.push('\n');
358 if cost.legacy_coverage_unknown {
359 out.push_str(&localized(
360 presentation,
361 "cmd_cost_coverage_unknown_legacy",
362 &[],
363 )?);
364 } else if cost.user_declared_estimates {
365 out.push_str(&format!(
366 "Coverage: {} of {} tracked turns priced or estimated.",
367 cost.priced_turns,
368 cost.priced_turns.saturating_add(cost.unpriced_turns)
369 ));
370 } else {
371 out.push_str(&localized(
372 presentation,
373 "cmd_cost_coverage",
374 &[
375 ("priced", &cost.priced_turns.to_string()),
376 (
377 "turns",
378 &cost
379 .priced_turns
380 .saturating_add(cost.unpriced_turns)
381 .to_string(),
382 ),
383 ],
384 )?);
385 }
386 if cost.unpriced_turns > 0 {
387 out.push('\n');
388 let reasons = formatted_unpriced_reasons(cost, presentation)?;
389 if cost.user_declared_estimates {
390 out.push_str(&format!(
391 "Excluded: {} turns have incomplete prices ({}); their cost is unknown.",
392 cost.unpriced_turns, reasons
393 ));
394 } else {
395 out.push_str(&localized(
396 presentation,
397 "cmd_cost_unpriced_turns",
398 &[
399 ("unpriced", &cost.unpriced_turns.to_string()),
400 ("reasons", &reasons),
401 ],
402 )?);
403 }
404 }
405 for (key, placeholder, values) in [
406 (
407 "cmd_cost_unpriced_classes",
408 "classes",
409 &cost.unpriced_classes,
410 ),
411 (
412 "cmd_cost_pricing_provenance",
413 "sources",
414 &cost.pricing_provenances,
415 ),
416 (
417 "cmd_cost_live_pricing_downgraded",
418 "defects",
419 &cost.live_pricing_defects,
420 ),
421 (
422 "cmd_cost_live_pricing_unavailable",
423 "defects",
424 &cost.unusable_pricing_defects,
425 ),
426 ] {
427 if !values.is_empty() {
428 out.push('\n');
429 out.push_str(&localized(
430 presentation,
431 key,
432 &[(placeholder, &values.join(", "))],
433 )?);
434 }
435 }
436 if !cost.route_receipts.is_empty() {
437 out.push('\n');
438 out.push_str(&localized(presentation, "cmd_cost_routes_header", &[])?);
439 for receipt in &cost.route_receipts {
440 out.push_str("\n ");
441 out.push_str(receipt);
442 }
443 }
444 Ok(out)
445 }
446
447 /// The system command is the deliberate prompt-disclosing operation.
448 pub fn system_prompt(contexts: CommandContexts<'_>) -> CommandResult {
449 let mut parts = contexts.into_parts();
450 let Some(diagnostics) = parts.debug_diagnostics.as_deref_mut() else {
451 return CommandResult::error(DIAGNOSTICS_UNAVAILABLE);
452 };
453 let system = diagnostics.system_projection();
454 let prompt_text = match system.prompt {
455 DebugSystemPrompt::Text(text) => text,
456 DebugSystemPrompt::Blocks(blocks) => blocks.join("\n\n---\n\n"),
457 DebugSystemPrompt::None => "(no system prompt)".to_string(),
458 };
459 let display = if prompt_text.len() > 500 {
460 let truncate_at = prompt_text
461 .char_indices()
462 .take_while(|(i, _)| *i <= 500)
463 .last()
464 .map_or(0, |(i, _)| i);
465 format!(
466 "{}...\n\n(truncated, {} chars total)",
467 &prompt_text[..truncate_at],
468 prompt_text.chars().count()
469 )
470 } else {
471 prompt_text
472 };
473 CommandResult::message(format!(
474 "System Prompt ({} mode):\n─────────────────────────────\n{}",
475 system.mode_label, display
476 ))
477 }
478
479 /// Bare `/context` emits an inspector action without invoking a report builder.
480 pub fn context(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
481 let mut parts = contexts.into_parts();
482 let Some(diagnostics) = parts.debug_diagnostics.as_deref_mut() else {
483 return CommandResult::error(DIAGNOSTICS_UNAVAILABLE);
484 };
485 let Some(subcommand) = arg.map(str::trim).filter(|arg| !arg.is_empty()) else {
486 return CommandResult::action(AppAction::OpenContextInspector);
487 };
488 match subcommand {
489 "prompt-json" | "prompt_json" | "prompt" => {
490 CommandResult::message(reports::prompt_context_json(&diagnostics.prompt_context()))
491 }
492 "report" | "json" | "summary" => {
493 let report = diagnostics.context_source_map();
494 match subcommand {
495 "report" => CommandResult::message(reports::format_context_report(&report)),
496 "json" => CommandResult::message(reports::context_report_json(&report)),
497 "summary" => CommandResult::message(reports::format_context_summary(&report)),
498 _ => unreachable!(),
499 }
500 }
501 "limit" => CommandResult::error(
502 "Usage: /context limit <tokens|reset> (e.g. 1000000, 1m, 272k, or reset/auto).",
503 ),
504 other if other.starts_with("limit ") => {
505 let raw = other["limit ".len()..].trim();
506 if raw.eq_ignore_ascii_case("reset") || raw.eq_ignore_ascii_case("auto") {
507 CommandResult::action(AppAction::SetModelContextWindow { tokens: None })
508 } else {
509 match codewhale_command_contract::outcome::parse_context_window_limit(raw) {
510 Ok(tokens) => CommandResult::action(AppAction::SetModelContextWindow {
511 tokens: Some(tokens),
512 }),
513 Err(err) => CommandResult::error(err),
514 }
515 }
516 }
517 other => CommandResult::error(format!(
518 "Unknown /context subcommand: {other}. Use report, json, prompt-json, summary, or limit <tokens|reset>."
519 )),
520 }
521 }
522
522 lines RUST