| 1 | #[cfg(test)] |
| 2 | use crate::bridge::invalidate_runtime_bridge; |
| 3 | use crate::http::ADVERTISED_ROUTES; |
| 4 | use crate::owner_calls::runtime_app_models; |
| 5 | use crate::{AppState, AppTransport}; |
| 6 | use anyhow::Context as _; |
| 7 | #[cfg(not(test))] |
| 8 | use anyhow::bail; |
| 9 | use anyhow::{Result, anyhow}; |
| 10 | use codewhale_config::ConfigStore; |
| 11 | use codewhale_protocol::{AppRequest, AppResponse}; |
| 12 | use serde_json::json; |
| 13 | use std::time::Duration; |
| 14 | |
| 15 | pub(crate) async fn process_app_request( |
| 16 | state: &AppState, |
| 17 | req: AppRequest, |
| 18 | _transport: AppTransport, |
| 19 | ) -> AppResponse { |
| 20 | match req { |
| 21 | AppRequest::Capabilities => AppResponse { |
| 22 | ok: true, |
| 23 | data: json!({ |
| 24 | "routes": ADVERTISED_ROUTES, |
| 25 | "interactive_execution": false, |
| 26 | "goal_execution": false, |
| 27 | "tool_free_turns": true, |
| 28 | "full_api_entrypoint": "codewhale app-server --http", |
| 29 | "config": ["get", "set", "unset", "list", "reload"], |
| 30 | "events": ["response_start", "response_delta", "response_end"], |
| 31 | "transport": "stdio+http", |
| 32 | "config_path": state.config_path.as_ref().map(|p| p.display().to_string()), |
| 33 | }), |
| 34 | events: Vec::new(), |
| 35 | }, |
| 36 | AppRequest::ConfigGet { key } => { |
| 37 | let cfg = state.config.read().await; |
| 38 | let value = cfg.get_display_value(&key); |
| 39 | AppResponse { |
| 40 | ok: true, |
| 41 | data: json!({ "key": key, "value": value }), |
| 42 | events: Vec::new(), |
| 43 | } |
| 44 | } |
| 45 | AppRequest::ConfigSet { key, value } => { |
| 46 | // Only propagate a mutation that actually happened. `set_value` |
| 47 | // leaves the config untouched on an unknown key or invalid value, |
| 48 | // so this is a no-op from the caller's point of view — but |
| 49 | // `propagate_config` invalidates the cached stdio bridge |
| 50 | // regardless, and dropping the last reference kills the running |
| 51 | // child runtime along with its thread map. A single typo'd key |
| 52 | // would orphan every in-flight thread on that bridge. |
| 53 | let result = { |
| 54 | let (key, value) = (key.clone(), value.clone()); |
| 55 | persist_config_mutation(state, move |cfg| cfg.set_value(&key, &value)).await |
| 56 | }; |
| 57 | let ok = result.is_ok(); |
| 58 | let message = result.err().map(|e| e.to_string()); |
| 59 | let value = if ok { |
| 60 | value |
| 61 | } else { |
| 62 | codewhale_config::persistence::redact_secrets(&value) |
| 63 | }; |
| 64 | AppResponse { |
| 65 | ok, |
| 66 | data: json!({ "key": key, "value": value, "error": message }), |
| 67 | events: Vec::new(), |
| 68 | } |
| 69 | } |
| 70 | AppRequest::ConfigUnset { key } => { |
| 71 | // See ConfigSet: a failed unset changed nothing and must not tear |
| 72 | // down the runtime bridge. |
| 73 | let result = { |
| 74 | let key = key.clone(); |
| 75 | persist_config_mutation(state, move |cfg| cfg.unset_value(&key)).await |
| 76 | }; |
| 77 | let ok = result.is_ok(); |
| 78 | let message = result.err().map(|e| e.to_string()); |
| 79 | AppResponse { |
| 80 | ok, |
| 81 | data: json!({ "key": key, "error": message }), |
| 82 | events: Vec::new(), |
| 83 | } |
| 84 | } |
| 85 | AppRequest::ConfigList => { |
| 86 | let cfg = state.config.read().await; |
| 87 | AppResponse { |
| 88 | ok: true, |
| 89 | data: json!({ "values": cfg.list_values() }), |
| 90 | events: Vec::new(), |
| 91 | } |
| 92 | } |
| 93 | AppRequest::ConfigReload => { |
| 94 | if let Err(error) = |
| 95 | update_config_store(state, |store| store.config.validate_configured_model()).await |
| 96 | { |
| 97 | return AppResponse { |
| 98 | ok: false, |
| 99 | data: json!({ "error": error.to_string() }), |
| 100 | events: Vec::new(), |
| 101 | }; |
| 102 | } |
| 103 | |
| 104 | AppResponse { |
| 105 | ok: true, |
| 106 | data: json!({ "reloaded": true }), |
| 107 | events: Vec::new(), |
| 108 | } |
| 109 | } |
| 110 | AppRequest::Models => { |
| 111 | let result = tokio::time::timeout(Duration::from_secs(30), runtime_app_models(state)) |
| 112 | .await |
| 113 | .context("Runtime model catalog request timed out") |
| 114 | .and_then(|result| result); |
| 115 | match result { |
| 116 | Ok(models) => AppResponse { |
| 117 | ok: true, |
| 118 | data: json!({ "models": models }), |
| 119 | events: Vec::new(), |
| 120 | }, |
| 121 | Err(error) => AppResponse { |
| 122 | ok: false, |
| 123 | data: json!({ "error": error.to_string() }), |
| 124 | events: Vec::new(), |
| 125 | }, |
| 126 | } |
| 127 | } |
| 128 | AppRequest::ThreadLoadedList => { |
| 129 | let response = crate::thread_control::loaded(state).await; |
| 130 | match response { |
| 131 | Ok(thread_resp) => AppResponse { |
| 132 | ok: true, |
| 133 | data: json!({ "threads": thread_resp.threads }), |
| 134 | events: thread_resp.events, |
| 135 | }, |
| 136 | Err(err) => AppResponse { |
| 137 | ok: false, |
| 138 | data: json!({ "error": err.to_string() }), |
| 139 | events: Vec::new(), |
| 140 | }, |
| 141 | } |
| 142 | } |
| 143 | AppRequest::SubmitUserInput { request_id, .. } => { |
| 144 | // This transport cannot deliver a clarification answer, and |
| 145 | // saying otherwise was the bug: the previous implementation |
| 146 | // reported `resolved: true` and filed the answers in a map with |
| 147 | // no reader anywhere in this crate. |
| 148 | // |
| 149 | // It cannot be made to work here. `handle_line_during_turn` |
| 150 | // executes exactly one method while a turn is streaming — |
| 151 | // `thread/interrupt`. Everything else, `app/request` included, |
| 152 | // queues until the turn ends, so an answer sent over this |
| 153 | // transport would wait on the very turn that is waiting for it. |
| 154 | // The runtime API owns the pending request and can resume the |
| 155 | // turn, so that is where the reply belongs. |
| 156 | AppResponse { |
| 157 | ok: false, |
| 158 | data: json!({ |
| 159 | "error": "user_input_reply_unsupported", |
| 160 | "request_id": request_id, |
| 161 | "message": concat!( |
| 162 | "the app-server control transport cannot deliver clarification answers: ", |
| 163 | "only `thread/interrupt` runs while a turn is streaming, so an answer sent ", |
| 164 | "here would queue behind the turn waiting for it. Reply on the runtime API ", |
| 165 | "instead: POST /v1/user-input/{thread_id}/{request_id}." |
| 166 | ), |
| 167 | }), |
| 168 | events: Vec::new(), |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Install the saved config in the bookkeeping Runtime, then apply it through |
| 175 | /// the already captured canonical owner. Unbound production frontends refuse |
| 176 | /// application while retaining the saved config for explicit recovery. |
| 177 | /// A saved config whose owner reload fails is reported as retained but unapplied. |
| 178 | pub(crate) async fn propagate_config(state: &AppState) -> Result<()> { |
| 179 | { |
| 180 | let mut runtime = state.runtime.write().await; |
| 181 | let snapshot = state.config.read().await.clone(); |
| 182 | runtime.update_config(snapshot); |
| 183 | } |
| 184 | if state.captured_owner.is_some() { |
| 185 | let owner = crate::owner_calls::captured(state) |
| 186 | .context("config saved but captured Runtime owner is unavailable")?; |
| 187 | tokio::time::timeout( |
| 188 | Duration::from_secs(10), |
| 189 | crate::owner_calls::execute(&owner, crate::RuntimeOwnerRequest::ReloadConfig), |
| 190 | ) |
| 191 | .await |
| 192 | .context("config saved; captured owner reload outcome is uncertain, not replayed")? |
| 193 | .context("config saved but captured owner rejected reload")?; |
| 194 | } else { |
| 195 | #[cfg(test)] |
| 196 | invalidate_runtime_bridge(state).await; |
| 197 | #[cfg(not(test))] |
| 198 | bail!("config saved but no captured Runtime owner can apply it"); |
| 199 | } |
| 200 | Ok(()) |
| 201 | } |
| 202 | |
| 203 | /// Prefix of a config error that is the server's fault (the file could not |
| 204 | /// be read, parsed, or written), reported over HTTP `/app` as a 500 rather |
| 205 | /// than the 400 a rejected key or value gets. |
| 206 | pub(crate) const CONFIG_LOAD_ERROR: &str = "failed to load config"; |
| 207 | |
| 208 | /// See [`CONFIG_LOAD_ERROR`]. |
| 209 | pub(crate) const CONFIG_SAVE_ERROR: &str = "failed to save config"; |
| 210 | |
| 211 | /// Apply `mutate` to the config on disk, then propagate the saved result. |
| 212 | /// |
| 213 | /// The mutation runs against a freshly loaded store, not the in-memory |
| 214 | /// snapshot, so edits another process (TUI, `codewhale login`) saved since |
| 215 | /// startup survive. With no explicit `--config` the store resolves the same |
| 216 | /// default path the runtime child reads, so the change reaches turns and |
| 217 | /// survives a restart. Any load, mutation, or save failure is returned and |
| 218 | /// nothing is propagated, so the caller never reports `ok` for a change |
| 219 | /// that was not kept. |
| 220 | /// |
| 221 | /// The work runs on its own task: once the file is written, a caller that |
| 222 | /// goes away (an HTTP client disconnect) must not leave disk ahead of |
| 223 | /// `state.config`, the live runtime, and the cached bridge. |
| 224 | pub(crate) async fn persist_config_mutation( |
| 225 | state: &AppState, |
| 226 | mutate: impl FnOnce(&mut codewhale_config::ConfigToml) -> Result<()> + Send + 'static, |
| 227 | ) -> Result<()> { |
| 228 | update_config_store(state, move |store| { |
| 229 | mutate(&mut store.config)?; |
| 230 | store.config.validate_configured_model()?; |
| 231 | store |
| 232 | .save() |
| 233 | .map_err(|err| anyhow!("{CONFIG_SAVE_ERROR}: {err}")) |
| 234 | }) |
| 235 | .await |
| 236 | } |
| 237 | |
| 238 | /// Serialize reloads and writes before reading disk, and finish propagation |
| 239 | /// even if the requesting connection disappears. A reload mutates nothing. |
| 240 | pub(crate) async fn update_config_store( |
| 241 | state: &AppState, |
| 242 | update: impl FnOnce(&mut ConfigStore) -> Result<()> + Send + 'static, |
| 243 | ) -> Result<()> { |
| 244 | let state = state.clone(); |
| 245 | tokio::spawn(async move { |
| 246 | // Own the write guard across load→mutate→save→install so two |
| 247 | // concurrent mutations cannot overwrite one another. All disk work |
| 248 | // runs off-runtime; the owned operation still finishes propagation |
| 249 | // when the requesting connection goes away. |
| 250 | let mut config = state.config.clone().write_owned().await; |
| 251 | let config_path = state.config_path.clone(); |
| 252 | tokio::task::spawn_blocking(move || -> Result<()> { |
| 253 | let mut store = ConfigStore::load(config_path) |
| 254 | .map_err(|err| anyhow!("{CONFIG_LOAD_ERROR}: {err}"))?; |
| 255 | update(&mut store)?; |
| 256 | *config = store.config; |
| 257 | Ok(()) |
| 258 | }) |
| 259 | .await |
| 260 | .map_err(|err| anyhow!("config store task failed: {err}"))??; |
| 261 | propagate_config(&state).await?; |
| 262 | Ok(()) |
| 263 | }) |
| 264 | .await |
| 265 | .map_err(|err| anyhow!("config update task failed: {err}"))? |
| 266 | } |
| 267 |