返回 CodeWhale
builtin_commands.rs
根目录 / crates / app-server / src / runtime_api / builtin_commands.rs
1 //! `POST /v1/threads/{id}/commands/builtin` — execute a terminal built-in
2 //! command against a thread, remotely.
3 //!
4 //! The thread's state is assembled into the engine's
5 //! [`BuiltinCommandHostSnapshot`] (contract projections included) and handed
6 //! to the installed command catalog, whose terminal-host implementation maps
7 //! it into the facet envelope and runs the portable handlers. Which commands
8 //! this serves is the host's decision (`builtin_execution::SERVED`); a name
9 //! outside that set answers 404 the same way an unknown name does, so the
10 //! remote surface can never widen without the host widening it first.
11 //!
12 //! Phase 1 notes: executions are not receipt-tracked (the phase-1 set is
13 //! read-only — every served handler is pure over the snapshot), and the
14 //! `text_only` flag reports commands that also asked the terminal host for an
15 //! action, which a remote client cannot perform.
16
17 use axum::Json;
18 use axum::extract::{Path, State};
19 use codewhale_command_contract::facets::{
20 DebugCostProjection, DebugRouteCost, DebugSystemPrompt, DebugTokenProjection,
21 };
22 use codewhale_command_contract::types::{CommandCurrency, CommandMode};
23 use codewhale_engine::command_catalog::{self, BuiltinCommandHostSnapshot};
24 use codewhale_models::SystemPrompt;
25 use serde::Deserialize;
26
27 use super::{ApiError, RuntimeApiState};
28
29 #[derive(Deserialize)]
30 #[serde(deny_unknown_fields)]
31 pub(super) struct BuiltinCommandApiRequest {
32 /// The command name (canonical or alias), with or without the slash.
33 pub name: String,
34 /// The argument tail after the command word, if any.
35 #[serde(default)]
36 pub args: Option<String>,
37 }
38
39 #[derive(serde::Serialize)]
40 pub(super) struct BuiltinCommandApiResponse {
41 pub name: String,
42 pub text: String,
43 pub is_error: bool,
44 /// `false` when the command also asked the terminal host for an action
45 /// the remote client cannot perform.
46 pub text_only: bool,
47 }
48
49 pub(super) async fn run_builtin_command(
50 State(state): State<RuntimeApiState>,
51 Path(thread_id): Path<String>,
52 Json(request): Json<BuiltinCommandApiRequest>,
53 ) -> Result<Json<BuiltinCommandApiResponse>, ApiError> {
54 let catalog = command_catalog::installed()
55 .ok_or_else(|| ApiError::internal("command catalog is not installed"))?;
56 // Refuse a name outside the host's remote surface before reading any
57 // thread state: an unknown command and a known-but-unserved one get the
58 // same answer, and neither can be distinguished by what the read says
59 // about the daemon's idle threads.
60 if !catalog.serves_builtin(&request.name) {
61 return Err(not_served(&request.name));
62 }
63
64 let thread = state
65 .runtime_threads
66 .get_thread(&thread_id)
67 .await
68 .map_err(super::map_thread_err)?;
69
70 let snapshot = assemble_snapshot(&state, &thread_id, &thread).await?;
71
72 match catalog.execute_builtin(&request.name, request.args.as_deref(), &snapshot) {
73 Some(execution) => Ok(Json(BuiltinCommandApiResponse {
74 name: execution.name,
75 text: execution.text,
76 is_error: execution.is_error,
77 text_only: execution.text_only,
78 })),
79 // The host refused the name: the same answer an unknown command gets.
80 None => Err(not_served(&request.name)),
81 }
82 }
83
84 fn not_served(name: &str) -> ApiError {
85 const MAX_ECHOED_NAME_CHARS: usize = 64;
86 let shown: String = name.chars().take(MAX_ECHOED_NAME_CHARS).collect();
87 let ellipsis = if shown.len() < name.len() { "..." } else { "" };
88 ApiError::not_found(format!(
89 "no remotely executable builtin command '{shown}{ellipsis}'"
90 ))
91 }
92
93 /// Assemble the host snapshot for one thread from the record, the live
94 /// engine's context budget, the usage aggregate, and the canonical session
95 /// document. Every projection field is filled from measured data or left at
96 /// its honest absence encoding; nothing is estimated into place.
97 async fn assemble_snapshot(
98 state: &RuntimeApiState,
99 thread_id: &str,
100 thread: &codewhale_engine::runtime_threads::ThreadRecord,
101 ) -> Result<BuiltinCommandHostSnapshot, ApiError> {
102 // The live engine carries the context budget; an idle daemon thread has
103 // no honest context estimate, so the served diagnostics refuse rather
104 // than print zeros.
105 let engine = state
106 .runtime_threads
107 .loaded_engine(thread_id)
108 .await
109 .ok_or_else(|| {
110 ApiError::conflict("this thread's engine is not loaded; send a message first")
111 })?;
112 let budget = engine
113 .get_context_budget()
114 .await
115 .map_err(super::map_thread_err)?
116 .ok_or_else(|| {
117 ApiError::conflict("this thread has no live context estimate yet; send a message first")
118 })?;
119
120 let usage = state
121 .runtime_threads
122 .aggregate_usage_for_thread(thread_id)
123 .await
124 .map_err(super::map_thread_err)?;
125 let parent = &usage.parent;
126 let children = &usage.routed_children;
127 let combined = usage.combined();
128
129 // The daemon tracks no UI chat history (that is the client's layer), so
130 // the chat count is a true zero; the model transcript and the effective
131 // system prompt come from the live engine session.
132 let session = engine
133 .get_session_snapshot()
134 .await
135 .map_err(|err| ApiError::internal(format!("engine session snapshot unavailable: {err}")))?;
136 let api_message_count = session.messages.len();
137 let chat_message_count = 0;
138
139 // Currency follows the same rule the TUI's cost display applies, so the
140 // same config answers the same way on both surfaces: a Simplified-Chinese
141 // UI reading the default "usd" shows CNY, and every other spelling goes
142 // through the canonical parser (which accepts rmb and yuan) rather than a
143 // bare string compare. The CNY column is the provider-published subtotal
144 // only; a USD-picked currency keeps the authoritative USD numbers.
145 #[cfg(test)]
146 let env_ticket = codewhale_runtime::test_support::env_scope_ticket();
147 let settings = tokio::task::spawn_blocking(move || {
148 #[cfg(test)]
149 let _membership = codewhale_runtime::test_support::join_env_scope(env_ticket);
150 codewhale_runtime::settings::Settings::load_read_only()
151 })
152 .await
153 .map_err(|err| ApiError::internal(format!("settings task failed: {err}")))?
154 .map_err(|err| ApiError::internal(format!("settings unavailable: {err}")))?;
155 let locale = codewhale_localization::resolve_locale(&settings.locale);
156 let currency = match (settings.cost_currency.as_str(), locale.tag()) {
157 ("usd", "zh-Hans") => CommandCurrency::Cny,
158 _ => match codewhale_config::pricing::CostCurrency::from_setting(&settings.cost_currency) {
159 Some(codewhale_config::pricing::CostCurrency::Cny) => CommandCurrency::Cny,
160 _ => CommandCurrency::Usd,
161 },
162 };
163 let currency_amount =
164 |totals: &codewhale_engine::runtime_threads::manager::UsageTotals| match currency {
165 CommandCurrency::Cny => totals.cost_cny,
166 CommandCurrency::Usd => totals.cost_usd,
167 };
168 let parent_amount = currency_amount(parent);
169 let children_amount = currency_amount(children);
170 let total_amount = currency_amount(&combined);
171 let (priced_turns, unpriced_turns, unpriced_reasons) = match currency {
172 CommandCurrency::Cny => (
173 combined.cny_priced_turns,
174 combined.cny_unpriced_turns,
175 &combined.cny_unpriced_reasons,
176 ),
177 CommandCurrency::Usd => (
178 combined.priced_turns,
179 combined.unpriced_turns,
180 &combined.unpriced_reasons,
181 ),
182 };
183
184 let mode = CommandMode::parse(&session.mode).unwrap_or(CommandMode::Agent);
185 let mode_label = codewhale_config::AppMode::from_setting(&session.mode)
186 .label()
187 .to_string();
188 let system_prompt = match session.system_prompt {
189 None => DebugSystemPrompt::None,
190 Some(SystemPrompt::Text(text)) => DebugSystemPrompt::Text(text),
191 Some(SystemPrompt::Blocks(blocks)) => {
192 DebugSystemPrompt::Blocks(blocks.into_iter().map(|block| block.text).collect())
193 }
194 };
195
196 let cost = DebugCostProjection {
197 currency,
198 // The combined subtotal is the authoritative total, and it is by
199 // construction the parent and children amounts added up; the
200 // terminal's #244 reconciliation floor only exists because its
201 // display total and its recomputed components can drift apart. The
202 // remote aggregate cannot drift from itself, so there is no floor to
203 // report and none is invented.
204 total: total_amount,
205 parent_turns: parent_amount,
206 subagents: children_amount,
207 display_floor: 0.0,
208 priced_turns: priced_turns.clamp(0, u32::MAX as u64) as u32,
209 unpriced_turns: unpriced_turns.clamp(0, u32::MAX as u64) as u32,
210 legacy_coverage_unknown: !combined.cost_complete,
211 // Pricing-provenance bookkeeping (user-declared estimates, live
212 // defects, route receipts) is terminal-session state the daemon
213 // does not track; the honest encoding is "none recorded".
214 user_declared_estimates: false,
215 // Per-route attribution needs per-turn provider identities, which
216 // the remote snapshot does not assemble yet; the coverage counts
217 // above stay authoritative. With no route rows, no turn is itemized:
218 // claiming otherwise would make the renderer state a breakdown it
219 // cannot show.
220 itemized_turns: 0,
221 route_amounts: Vec::<DebugRouteCost>::new(),
222 turn_history_capacity: 0,
223 unpriced_reason_labels: unpriced_reasons.iter().cloned().collect(),
224 unpriced_classes: combined.unpriced_classes.iter().cloned().collect(),
225 pricing_provenances: Vec::new(),
226 live_pricing_defects: Vec::new(),
227 unusable_pricing_defects: Vec::new(),
228 route_receipts: Vec::new(),
229 };
230
231 Ok(BuiltinCommandHostSnapshot {
232 mode,
233 mode_label,
234 locale,
235 model: thread.model.clone(),
236 system_prompt,
237 tokens: DebugTokenProjection {
238 active_context_used: (budget.input_tokens as usize).min(budget.window_tokens as usize),
239 context_window: budget.window_tokens.clamp(0, u32::MAX as u64) as u32,
240 // The context budget carries no per-turn telemetry, so the
241 // last-turn columns take their honest absence encoding rather
242 // than a stale or fabricated value.
243 last_input: None,
244 last_output: None,
245 cache_hit: None,
246 cache_miss: None,
247 total_tokens: combined.input_tokens.saturating_add(combined.output_tokens),
248 cache_write_tokens: combined.cache_write_tokens,
249 api_message_count,
250 chat_message_count,
251 model: thread.model.clone(),
252 cost,
253 },
254 })
255 }
256
256 lines RUST