| 1 | //! Operations submitted by the UI to the core engine. |
| 2 | //! |
| 3 | //! These operations flow from the TUI to the engine via a channel, |
| 4 | //! allowing the UI to remain responsive while the engine processes requests. |
| 5 | |
| 6 | use crate::compaction::CompactionConfig; |
| 7 | use crate::config::ApiProvider; |
| 8 | use crate::route_runtime::ResolvedRuntimeRoute; |
| 9 | use crate::tools::goal::GoalStatus; |
| 10 | use codewhale_config::AppMode; |
| 11 | use codewhale_execpolicy::ApprovalMode; |
| 12 | use codewhale_models::{Message, SystemPrompt}; |
| 13 | use codewhale_protocol::runtime::DynamicToolSpec; |
| 14 | use std::path::PathBuf; |
| 15 | |
| 16 | /// Prefix used for tool-call ids created by local composer shell shortcuts. |
| 17 | pub const USER_SHELL_TOOL_ID_PREFIX: &str = "user_shell_"; |
| 18 | |
| 19 | /// Snapshot of session state for saving to disk. |
| 20 | /// Returned by `Op::GetSessionSnapshot` via a oneshot channel. |
| 21 | #[derive(Debug, Clone)] |
| 22 | pub struct SessionSnapshot { |
| 23 | pub messages: Vec<Message>, |
| 24 | pub total_tokens: u64, |
| 25 | pub model: String, |
| 26 | /// Generic provider kind retained for serialized compatibility. |
| 27 | pub model_provider: String, |
| 28 | /// Exact non-secret configured provider key. |
| 29 | pub model_provider_id: Option<String>, |
| 30 | pub workspace: PathBuf, |
| 31 | pub system_prompt: Option<SystemPrompt>, |
| 32 | pub mode: String, |
| 33 | } |
| 34 | |
| 35 | /// Live context-window posture for one thread, computed where the session |
| 36 | /// state actually lives. Returned by `Op::GetContextBudget` via a oneshot |
| 37 | /// channel so HTTP clients (GPUI usage panel) never re-derive the engine's |
| 38 | /// token math or route limits at the API boundary. |
| 39 | #[derive(Debug, Clone)] |
| 40 | pub struct SessionContextBudget { |
| 41 | /// Total context window for the active route (input + output), in tokens. |
| 42 | pub window_tokens: u64, |
| 43 | /// Estimated input tokens on the same basis the visible context meter |
| 44 | /// uses (`estimate_input_tokens_conservative`, including its safety |
| 45 | /// inflation). This is the number a "context filling up" indicator shows. |
| 46 | pub input_tokens: u64, |
| 47 | /// Provider-billed prompt tokens from the most recent parent-route |
| 48 | /// request that still describes the live message list. `None` when no |
| 49 | /// provider count exists yet (fresh session) — never a fabricated zero. |
| 50 | pub billed_input_tokens: Option<u64>, |
| 51 | /// Output tokens reserved for the turn after route clamps. |
| 52 | pub output_cap_tokens: u64, |
| 53 | /// Spendable input ceiling (`window - output_cap - headroom`, intersected |
| 54 | /// with any provider-published hard input limit). |
| 55 | pub input_budget_ceiling: u64, |
| 56 | /// Input tokens still available before the reserved boundary. |
| 57 | pub available_input_tokens: u64, |
| 58 | /// Input level at which compaction is suggested. |
| 59 | pub compaction_trigger_tokens: u64, |
| 60 | /// `input_tokens / window_tokens` as a percentage (0..=100). |
| 61 | pub usage_percent: f64, |
| 62 | /// Coarse pressure label (`low`/`moderate`/`high`/`critical`). |
| 63 | pub pressure: &'static str, |
| 64 | /// Route identity the budget was computed for. |
| 65 | pub model: String, |
| 66 | pub provider: String, |
| 67 | pub model_provider_id: Option<String>, |
| 68 | } |
| 69 | |
| 70 | /// Provider request runtime state surfaced by `/provider`. |
| 71 | /// Returned by `Op::GetProviderRuntimeStatus` via a oneshot channel. |
| 72 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 73 | pub struct ProviderRuntimeStatus { |
| 74 | pub provider: ApiProvider, |
| 75 | pub request_concurrency_limit: Option<usize>, |
| 76 | pub active_provider_requests: usize, |
| 77 | } |
| 78 | |
| 79 | /// Idle Engine snapshot used by a one-shot host before shutting down. |
| 80 | /// The completion inbox belongs to the Engine; a terminal worker alone does |
| 81 | /// not prove that its parent has consumed the handback. |
| 82 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 83 | pub struct SubAgentSettlement { |
| 84 | pub running_children: usize, |
| 85 | /// A Workflow can still be coordinating between child phases. |
| 86 | pub running_workflows: usize, |
| 87 | pub pending_completions: usize, |
| 88 | } |
| 89 | |
| 90 | impl SubAgentSettlement { |
| 91 | #[must_use] |
| 92 | pub fn is_settled(self) -> bool { |
| 93 | self.running_children == 0 && self.running_workflows == 0 && self.pending_completions == 0 |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// Engine-owned MCP snapshot plus the exact event generation it supersedes. |
| 98 | /// The TUI uses the receipt to reject already-queued boot events even when it |
| 99 | /// had not rendered that generation before the direct `/mcp` action. |
| 100 | #[derive(Debug, Clone)] |
| 101 | pub struct McpManagerUpdate { |
| 102 | pub snapshot: crate::mcp::McpManagerSnapshot, |
| 103 | pub generation: u64, |
| 104 | } |
| 105 | |
| 106 | /// Result of rebuilding the engine-owned MCP pool in process. |
| 107 | pub type McpReloadResult = Result<McpManagerUpdate, String>; |
| 108 | |
| 109 | /// Result of the one-shot boot connection pass for the engine-owned MCP pool. |
| 110 | /// |
| 111 | /// This shares the reload result shape while remaining a separate operation: |
| 112 | /// boot may fill an empty live pool, but it must not force a config reload or |
| 113 | /// invalidate already-ready connections. |
| 114 | pub type McpBootstrapResult = Result<McpManagerUpdate, String>; |
| 115 | |
| 116 | /// Origin of text being introduced as a user-role turn. |
| 117 | /// |
| 118 | /// Chat providers force several runtime/control-plane signals through |
| 119 | /// `role = "user"` for compatibility, so role alone is not authority. |
| 120 | #[allow(dead_code)] // Some origins are reserved for ingestion sites landing after the first gate. |
| 121 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 122 | pub enum UserInputProvenance { |
| 123 | /// Text typed or submitted through the active UI/API input boundary. |
| 124 | ExternalUser, |
| 125 | /// Runtime-generated continuation, diagnostic, or tool feedback. |
| 126 | Runtime, |
| 127 | /// Completion/event text from a child worker or sub-agent handoff. |
| 128 | SubAgentHandoff, |
| 129 | /// A bounded, typed Agent Mail envelope delivered by the durable runtime. |
| 130 | /// Provider protocols still receive a user-role projection, but this |
| 131 | /// provenance can never inherit external-user authority. |
| 132 | AgentMail, |
| 133 | /// Text restored from a saved/imported transcript. |
| 134 | ImportedTranscript, |
| 135 | /// Text recalled from memory or another persisted source. |
| 136 | MemoryRecall, |
| 137 | /// Assistant-authored text that is shaped like a user response. |
| 138 | AssistantGenerated, |
| 139 | } |
| 140 | |
| 141 | impl UserInputProvenance { |
| 142 | pub fn as_str(self) -> &'static str { |
| 143 | match self { |
| 144 | Self::ExternalUser => "external_user", |
| 145 | Self::Runtime => "runtime", |
| 146 | Self::SubAgentHandoff => "subagent_handoff", |
| 147 | Self::AgentMail => "agent_mail", |
| 148 | Self::ImportedTranscript => "imported_transcript", |
| 149 | Self::MemoryRecall => "memory_recall", |
| 150 | Self::AssistantGenerated => "assistant_generated", |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | pub fn can_authorize_work(self) -> bool { |
| 155 | matches!(self, Self::ExternalUser) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /// Per-turn authority payload carried by [`Op::SendMessage`]. Extracted from |
| 160 | /// the enum arm so new per-turn fields accrete here instead of widening the |
| 161 | /// variant; the serializable twin is `codewhale_protocol::op::TurnSpec`. |
| 162 | #[derive(Debug)] |
| 163 | pub struct TurnSpec { |
| 164 | /// Admitted allowance for this turn only; never changes session settings. |
| 165 | pub max_output_tokens: Option<std::num::NonZeroU32>, |
| 166 | pub content: String, |
| 167 | /// Inline image bytes validated by Runtime admission; no file references. |
| 168 | pub images: Vec<codewhale_protocol::runtime::RuntimeImageInput>, |
| 169 | pub mode: AppMode, |
| 170 | /// Exact, structurally resolved route authority for this turn. The |
| 171 | /// engine activates its client before mutating turn state; injected |
| 172 | /// engines may use their already-supplied client with the same receipt. |
| 173 | pub route: Box<ResolvedRuntimeRoute>, |
| 174 | /// Compaction policy derived from the same provider route. Carrying it |
| 175 | /// atomically avoids a model/limit mismatch before `SendMessage`. |
| 176 | pub compaction: Box<CompactionConfig>, |
| 177 | /// Auxiliary provider calls completed while planning this exact turn |
| 178 | /// (currently Auto's classifier), bounded and paired with their own |
| 179 | /// immutable routes. The engine folds their tokens into total usage |
| 180 | /// only; they never enter the parent route's billing aggregate. |
| 181 | pub initial_routed_usage: Box<crate::cost_status::RuntimeUsageBatch>, |
| 182 | pub goal_objective: Option<String>, |
| 183 | pub goal_token_budget: Option<u32>, |
| 184 | pub goal_status: GoalStatus, |
| 185 | /// Reasoning-effort tier: `"off" | "low" | "medium" | "high" | "max"`. |
| 186 | /// `None` lets the provider apply its default. |
| 187 | pub reasoning_effort: Option<String>, |
| 188 | /// True when the user selected auto thinking, even though the UI sends |
| 189 | /// a concrete per-turn value to the model API. |
| 190 | pub reasoning_effort_auto: bool, |
| 191 | /// True when the user selected auto model routing. |
| 192 | pub auto_model: bool, |
| 193 | pub allow_shell: bool, |
| 194 | pub trust_mode: bool, |
| 195 | pub auto_approve: bool, |
| 196 | pub approval_mode: ApprovalMode, |
| 197 | pub translation_enabled: bool, |
| 198 | /// Tool restriction from custom slash command frontmatter. |
| 199 | /// `None` means the current turn may use the normal tool set. |
| 200 | pub allowed_tools: Option<Vec<String>>, |
| 201 | /// Runtime-supplied tools available only for this turn. |
| 202 | pub dynamic_tools: Vec<DynamicToolSpec>, |
| 203 | /// Hook executor for control-plane hooks. |
| 204 | /// `ToolCallBefore` hooks may deny a tool call with exit code 2. |
| 205 | pub hook_executor: Option<std::sync::Arc<crate::hooks::HookExecutor>>, |
| 206 | pub verbosity: Option<String>, |
| 207 | /// Structural input origin. This gates whether the turn may inherit |
| 208 | /// YOLO/auto-approval authority; user-shaped text is not enough. |
| 209 | pub provenance: UserInputProvenance, |
| 210 | } |
| 211 | |
| 212 | /// Operations that can be submitted to the engine. |
| 213 | #[derive(Debug)] |
| 214 | pub enum Op { |
| 215 | /// Send a message to the AI |
| 216 | SendMessage(TurnSpec), |
| 217 | |
| 218 | /// Re-check and dispatch an interactive goal continuation when this |
| 219 | /// operation reaches the front of the engine queue. Keeping this distinct |
| 220 | /// from `SendMessage` prevents a queued `/goal pause` or `/goal clear` |
| 221 | /// from being overwritten by a stale synthetic Active snapshot. |
| 222 | ContinueGoal { |
| 223 | /// Runtime-supplied tools remain available across the synthetic turn |
| 224 | /// that continues the same logical goal run. |
| 225 | dynamic_tools: Vec<DynamicToolSpec>, |
| 226 | /// Opaque identity for an engine-owned synthetic continuation. Direct |
| 227 | /// callers use `None`; the engine uses `Some` to coalesce one token |
| 228 | /// across capacity-waiting, enqueued, and running-adjacent states. |
| 229 | engine_schedule_id: Option<u64>, |
| 230 | }, |
| 231 | |
| 232 | /// Execute a user-submitted composer shell command (`! <command>`) without |
| 233 | /// sending a model turn. This still routes through `exec_shell`, approval, |
| 234 | /// sandbox, and command-safety handling. |
| 235 | RunShellCommand { |
| 236 | command: String, |
| 237 | mode: AppMode, |
| 238 | allow_shell: bool, |
| 239 | trust_mode: bool, |
| 240 | auto_approve: bool, |
| 241 | approval_mode: ApprovalMode, |
| 242 | }, |
| 243 | |
| 244 | /// Set the runtime goal status without dispatching a model turn. Used by |
| 245 | /// `/goal pause`, `/goal resume`, `/goal clear`, etc. so the engine's |
| 246 | /// `SharedGoalState` learns the new status immediately and a queued |
| 247 | /// continuation doesn't overwrite it back to Active. |
| 248 | SetGoalStatus { |
| 249 | status: GoalStatus, |
| 250 | /// When `true`, clear the objective entirely (`/goal clear`). |
| 251 | clear: bool, |
| 252 | /// Accepted control revision; None lets direct callers mint it. |
| 253 | goal_id: Option<String>, |
| 254 | }, |
| 255 | |
| 256 | /// Set (or replace) the active goal objective and immediately start goal |
| 257 | /// work through the runtime's continuation steering. `/goal <objective>` |
| 258 | /// is the caller; the objective is never echoed as a raw user message. |
| 259 | SetGoalObjective { |
| 260 | objective: String, |
| 261 | token_budget: Option<u32>, |
| 262 | /// Accepted control revision; None lets direct callers mint it. |
| 263 | goal_id: Option<String>, |
| 264 | }, |
| 265 | |
| 266 | /// Describe the exact request the next turn would send, without |
| 267 | /// sending it (`/preview-request`, #1004). |
| 268 | /// |
| 269 | /// Handled by the engine because only the engine can rebuild the current |
| 270 | /// tool catalog, MCP state, mode, gates, permission posture, and resolved |
| 271 | /// route. Pure inspection: it adds no message, no turn, and no tool call. |
| 272 | PreviewOutboundRequest { |
| 273 | inputs: Box<crate::core::engine::preview::PreviewRequestInputs>, |
| 274 | /// Render the manifest as JSON instead of the human-readable table. |
| 275 | json: bool, |
| 276 | /// Explicit disclosure of the base prompt only; effective system text |
| 277 | /// remains protected behind hashes. |
| 278 | base_prompt_only: bool, |
| 279 | }, |
| 280 | |
| 281 | /// List current sub-agents and their status |
| 282 | ListSubAgents, |
| 283 | |
| 284 | /// Inspect child settlement at the Engine's idle operation boundary. |
| 285 | /// This does not drain the completion inbox or dispatch a second loop. |
| 286 | GetSubAgentSettlement { |
| 287 | tx: std::sync::Arc< |
| 288 | std::sync::Mutex<Option<tokio::sync::oneshot::Sender<SubAgentSettlement>>>, |
| 289 | >, |
| 290 | }, |
| 291 | |
| 292 | /// Cancel a running sub-agent by id or session name. |
| 293 | CancelSubAgent { agent_id: String }, |
| 294 | |
| 295 | /// Deliver an operator follow-up to one child on its own fork: live |
| 296 | /// delivery to a running child, or a checkpoint continuation (new agent |
| 297 | /// id) for an interrupted or completed child. Terminal failed/cancelled |
| 298 | /// children answer with a receipt explaining why they cannot continue. |
| 299 | FollowUpSubAgent { agent_id: String, text: String }, |
| 300 | |
| 301 | /// Change the operating mode |
| 302 | ChangeMode { |
| 303 | mode: AppMode, |
| 304 | allow_shell: bool, |
| 305 | trust_mode: bool, |
| 306 | auto_approve: bool, |
| 307 | approval_mode: ApprovalMode, |
| 308 | configured_sandbox_mode: Option<String>, |
| 309 | }, |
| 310 | |
| 311 | /// Update the model being used and refresh stable prompt context. |
| 312 | SetModel { |
| 313 | model: String, |
| 314 | mode: AppMode, |
| 315 | route_limits: Option<codewhale_config::route::RouteLimits>, |
| 316 | }, |
| 317 | |
| 318 | /// Update auto-compaction settings |
| 319 | SetCompaction { config: CompactionConfig }, |
| 320 | |
| 321 | /// Update the SSE idle timeout used for subsequent streamed turns. |
| 322 | SetStreamChunkTimeout { timeout_secs: u64 }, |
| 323 | |
| 324 | /// Update sub-agent runtime controls for subsequent turns. |
| 325 | SetSubagentRuntimeConfig { |
| 326 | enabled: bool, |
| 327 | max_subagents: usize, |
| 328 | launch_concurrency: usize, |
| 329 | max_spawn_depth: u32, |
| 330 | api_timeout_secs: u64, |
| 331 | heartbeat_timeout_secs: u64, |
| 332 | }, |
| 333 | |
| 334 | /// Update the web-search backend for subsequent tool calls. |
| 335 | SetSearchProvider { |
| 336 | provider: crate::config::SearchProvider, |
| 337 | }, |
| 338 | |
| 339 | /// Replace the engine's merged Fleet roster after the setup wizard saves a |
| 340 | /// project or personal profile. Subsequent turns can use the new role |
| 341 | /// immediately instead of requiring an application restart. |
| 342 | SetFleetRoster { |
| 343 | roster: std::sync::Arc<crate::fleet::roster::FleetRoster>, |
| 344 | }, |
| 345 | |
| 346 | /// Sync engine session state (used for resume/load) |
| 347 | SyncSession { |
| 348 | session_id: Option<String>, |
| 349 | messages: Vec<Message>, |
| 350 | system_prompt: Option<SystemPrompt>, |
| 351 | system_prompt_override: bool, |
| 352 | model: String, |
| 353 | workspace: PathBuf, |
| 354 | mode: AppMode, |
| 355 | }, |
| 356 | |
| 357 | /// Run context compaction on one exact, structurally resolved provider |
| 358 | /// route with policy derived from that same descriptor. |
| 359 | CompactContext { |
| 360 | /// Stable request identity allocated before the operation enters the |
| 361 | /// bounded mailbox. Cancellation uses this id even when the provider |
| 362 | /// future has not started yet. |
| 363 | id: String, |
| 364 | route: Box<ResolvedRuntimeRoute>, |
| 365 | compaction: Box<CompactionConfig>, |
| 366 | }, |
| 367 | |
| 368 | /// Cancel one exact queued or running context-compaction request. |
| 369 | CancelCompaction { id: String }, |
| 370 | |
| 371 | /// Get a snapshot of the current session state (messages, tokens, etc.) |
| 372 | /// for saving to disk. Returns the result via the oneshot sender so |
| 373 | /// the caller doesn't have to compete with the SSE event stream. |
| 374 | GetSessionSnapshot { |
| 375 | tx: std::sync::Arc<std::sync::Mutex<Option<tokio::sync::oneshot::Sender<SessionSnapshot>>>>, |
| 376 | }, |
| 377 | |
| 378 | /// Get the live context-window budget for this session's route. Computed |
| 379 | /// on the engine so `active_route_limits`, the memoized token estimate, |
| 380 | /// and the last billed prompt size all come from one authority. |
| 381 | GetContextBudget { |
| 382 | tx: std::sync::Arc< |
| 383 | std::sync::Mutex<Option<tokio::sync::oneshot::Sender<Option<SessionContextBudget>>>>, |
| 384 | >, |
| 385 | }, |
| 386 | |
| 387 | /// Get active provider request concurrency state for readiness surfaces. |
| 388 | GetProviderRuntimeStatus { |
| 389 | tx: std::sync::Arc< |
| 390 | std::sync::Mutex<Option<tokio::sync::oneshot::Sender<ProviderRuntimeStatus>>>, |
| 391 | >, |
| 392 | }, |
| 393 | |
| 394 | /// Populate the engine-owned MCP pool once at UI boot and return a |
| 395 | /// snapshot from that exact pool. This is not a config reload and never |
| 396 | /// constructs a UI-owned discovery pool. Optional servers never block |
| 397 | /// the first model turn: that turn snapshots currently-ready tools. |
| 398 | BootstrapMcp { |
| 399 | tx: std::sync::Arc< |
| 400 | std::sync::Mutex<Option<tokio::sync::oneshot::Sender<McpBootstrapResult>>>, |
| 401 | >, |
| 402 | }, |
| 403 | |
| 404 | /// Retry one failed MCP server on the existing engine pool and return a |
| 405 | /// full snapshot. Ready siblings are never invalidated or reconnected. |
| 406 | RetryMcpServer { |
| 407 | name: String, |
| 408 | tx: std::sync::Arc< |
| 409 | std::sync::Mutex<Option<tokio::sync::oneshot::Sender<McpBootstrapResult>>>, |
| 410 | >, |
| 411 | }, |
| 412 | |
| 413 | /// Force the engine-owned MCP config/catalog to reload and reconnect. |
| 414 | /// The returned snapshot is taken from that same live pool. |
| 415 | ReloadMcp { |
| 416 | config_path: PathBuf, |
| 417 | tx: std::sync::Arc<std::sync::Mutex<Option<tokio::sync::oneshot::Sender<McpReloadResult>>>>, |
| 418 | }, |
| 419 | |
| 420 | /// Run agent-driven context purging. |
| 421 | PurgeContext, |
| 422 | |
| 423 | /// Edit the last user message: remove the last user+assistant exchange |
| 424 | /// from the session, then re-send with the new content. |
| 425 | #[cfg_attr(not(test), expect(dead_code))] |
| 426 | EditLastTurn { new_message: String }, |
| 427 | |
| 428 | /// Enable or disable the background advisor watcher for this session. |
| 429 | /// When enabled, a fire-and-forget background task runs after each turn |
| 430 | /// that contained tool calls and emits an `Event::AdvisoryNote` with |
| 431 | /// concise observations. (#3982) |
| 432 | SetAdvisorEnabled { enabled: bool }, |
| 433 | |
| 434 | /// Shutdown the engine |
| 435 | Shutdown, |
| 436 | } |
| 437 |