返回 CodeWhale
ops.rs
根目录 / crates / engine / src / core / ops.rs
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::route_runtime::ResolvedRuntimeRoute;
8 use crate::tools::goal::GoalStatus;
9 use codewhale_app_server_protocol::runtime::DynamicToolSpec;
10 use codewhale_config::AppMode;
11 use codewhale_config::ProviderKind;
12 use codewhale_execpolicy::ApprovalMode;
13 use codewhale_models::{Message, SystemPrompt};
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 pub type FleetMemberStarted = Result<String, String>;
20
21 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
22 pub struct SessionControlId(String);
23
24 impl Default for SessionControlId {
25 fn default() -> Self {
26 Self::new()
27 }
28 }
29
30 impl SessionControlId {
31 pub fn new() -> Self {
32 Self(uuid::Uuid::new_v4().to_string())
33 }
34
35 pub(crate) fn for_admitted_history(id: String) -> Self {
36 Self(id)
37 }
38 }
39
40 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
41 pub struct SessionSnapshotSource {
42 pub turn_id: Option<String>,
43 pub submission_id: Option<String>,
44 pub compaction_id: Option<String>,
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub control_id: Option<SessionControlId>,
47 }
48
49 impl SessionSnapshotSource {
50 pub fn turn(turn_id: String, submission_id: Option<String>) -> Self {
51 Self {
52 turn_id: Some(turn_id),
53 submission_id,
54 compaction_id: None,
55 control_id: None,
56 }
57 }
58
59 pub fn control(control_id: SessionControlId) -> Self {
60 Self {
61 turn_id: None,
62 submission_id: None,
63 compaction_id: None,
64 control_id: Some(control_id),
65 }
66 }
67
68 pub fn compaction(compaction_id: String) -> Self {
69 Self {
70 turn_id: None,
71 submission_id: None,
72 compaction_id: Some(compaction_id),
73 control_id: None,
74 }
75 }
76
77 pub fn terminal(
78 turn_id: Option<String>,
79 submission_id: Option<String>,
80 compaction_id: Option<String>,
81 ) -> Option<Self> {
82 if turn_id.is_some() == compaction_id.is_some() {
83 return None;
84 }
85 Some(Self {
86 turn_id,
87 submission_id,
88 compaction_id,
89 control_id: None,
90 })
91 }
92 }
93
94 /// Snapshot of session state for saving to disk.
95 /// Returned by `Op::GetSessionSnapshot` via a oneshot channel.
96 #[derive(Debug, Clone, PartialEq, serde::Serialize)]
97 pub struct SessionSnapshot {
98 #[serde(skip_serializing_if = "Option::is_none")]
99 pub source: Option<SessionSnapshotSource>,
100 /// The live conversation id this engine session is running under.
101 ///
102 /// Every workspace snapshot the conversation takes is tagged with it. A
103 /// Runtime thread's engine runs under the thread's own id; a save that
104 /// names no document persists under this id, so one conversation keeps
105 /// one document. Runtime snapshot ownership is the receipts recorded on
106 /// the thread's turns, not this binding (see `patch_undo_workspace_files`).
107 pub session_id: String,
108 pub messages: Vec<Message>,
109 pub total_tokens: u64,
110 pub model: String,
111 /// Generic provider kind retained for serialized compatibility.
112 pub model_provider: String,
113 /// Exact non-secret configured provider key.
114 pub model_provider_id: Option<String>,
115 pub workspace: PathBuf,
116 pub system_prompt: Option<SystemPrompt>,
117 #[serde(skip_serializing_if = "Option::is_none")]
118 pub instruction_assembly: Option<serde_json::Value>,
119 pub mode: String,
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub agent_preset: Option<String>,
122 }
123
124 /// Live context-window posture for one thread, computed where the session
125 /// state actually lives. Returned by `Op::GetContextBudget` via a oneshot
126 /// channel so HTTP clients (GPUI usage panel) never re-derive the engine's
127 /// token math or route limits at the API boundary.
128 #[derive(Debug, Clone)]
129 pub struct SessionContextBudget {
130 /// Total context window for the active route (input + output), in tokens.
131 pub window_tokens: u64,
132 /// Estimated input tokens on the same basis the visible context meter
133 /// and the auto-compaction gate use (`estimate_input_tokens_for_pressure`,
134 /// without the overflow guard's 1.5x inflation). This is the number a
135 /// "context filling up" indicator shows.
136 pub input_tokens: u64,
137 /// Provider-billed prompt tokens from the most recent parent-route
138 /// request that still describes the live message list. `None` when no
139 /// provider count exists yet (fresh session) — never a fabricated zero.
140 pub billed_input_tokens: Option<u64>,
141 /// Output tokens reserved for the turn after route clamps.
142 pub output_cap_tokens: u64,
143 /// Spendable input ceiling (`window - output_cap - headroom`, intersected
144 /// with any provider-published hard input limit).
145 pub input_budget_ceiling: u64,
146 /// Input tokens still available before the reserved boundary.
147 pub available_input_tokens: u64,
148 /// Input level at which compaction is suggested.
149 pub compaction_trigger_tokens: u64,
150 /// `input_tokens / window_tokens` as a percentage (0..=100).
151 pub usage_percent: f64,
152 /// Coarse pressure label (`low`/`moderate`/`high`/`critical`).
153 pub pressure: &'static str,
154 /// Route identity the budget was computed for.
155 pub model: String,
156 pub provider: String,
157 pub model_provider_id: Option<String>,
158 }
159
160 /// Provider request runtime state surfaced by `/provider`.
161 /// Returned by `Op::GetProviderRuntimeStatus` via a oneshot channel.
162 #[derive(Debug, Clone, PartialEq, Eq)]
163 pub struct ProviderRuntimeStatus {
164 pub provider: ProviderKind,
165 pub request_concurrency_limit: Option<usize>,
166 pub active_provider_requests: usize,
167 }
168
169 /// Idle Engine snapshot used by a one-shot host before shutting down.
170 /// The completion inbox belongs to the Engine; a terminal worker alone does
171 /// not prove that its parent has consumed the handback.
172 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
173 pub struct SubAgentSettlement {
174 pub running_children: usize,
175 /// A Workflow can still be coordinating between child phases.
176 pub running_workflows: usize,
177 pub pending_completions: usize,
178 }
179
180 impl SubAgentSettlement {
181 #[must_use]
182 pub fn is_settled(self) -> bool {
183 self.running_children == 0 && self.running_workflows == 0 && self.pending_completions == 0
184 }
185 }
186
187 /// Engine-owned MCP snapshot plus the exact event generation it supersedes.
188 /// The TUI uses the receipt to reject already-queued boot events even when it
189 /// had not rendered that generation before the direct `/mcp` action.
190 #[derive(Debug, Clone)]
191 pub struct McpManagerUpdate {
192 pub snapshot: crate::mcp::McpManagerSnapshot,
193 pub generation: u64,
194 }
195
196 /// Result of rebuilding the engine-owned MCP pool in process.
197 pub type McpReloadResult = Result<McpManagerUpdate, String>;
198
199 /// Result of the one-shot boot connection pass for the engine-owned MCP pool.
200 ///
201 /// This shares the reload result shape while remaining a separate operation:
202 /// boot may fill an empty live pool, but it must not force a config reload or
203 /// invalidate already-ready connections.
204 pub type McpBootstrapResult = Result<McpManagerUpdate, String>;
205
206 /// Origin of text being introduced as a user-role turn.
207 ///
208 /// Chat providers force several runtime/control-plane signals through
209 /// `role = "user"` for compatibility, so role alone is not authority.
210 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
211 pub enum UserInputProvenance {
212 /// Text typed or submitted through the active UI/API input boundary.
213 ExternalUser,
214 /// Runtime-generated diagnostic or tool feedback.
215 Runtime,
216 GoalContinuation,
217 /// Completion/event text from a child worker or sub-agent handoff.
218 SubAgentHandoff,
219 /// A bounded, typed Agent Mail envelope delivered by the durable runtime.
220 /// Provider protocols still receive a user-role projection, but this
221 /// provenance can never inherit external-user authority.
222 AgentMail,
223 /// Text restored from a saved/imported transcript.
224 ImportedTranscript,
225 /// Text recalled from memory or another persisted source.
226 MemoryRecall,
227 /// Assistant-authored text that is shaped like a user response.
228 AssistantGenerated,
229 }
230
231 impl UserInputProvenance {
232 pub fn as_str(self) -> &'static str {
233 match self {
234 Self::ExternalUser => "external_user",
235 Self::Runtime => "runtime",
236 Self::GoalContinuation => "goal_continuation",
237 Self::SubAgentHandoff => "subagent_handoff",
238 Self::AgentMail => "agent_mail",
239 Self::ImportedTranscript => "imported_transcript",
240 Self::MemoryRecall => "memory_recall",
241 Self::AssistantGenerated => "assistant_generated",
242 }
243 }
244
245 pub fn can_authorize_work(self) -> bool {
246 matches!(self, Self::ExternalUser)
247 }
248 }
249
250 #[derive(Clone, Debug, PartialEq, Eq, Default)]
251 pub enum TurnInputAuthorship {
252 #[default]
253 NotPerson,
254 Person(String),
255 ApprovedPlan(String),
256 }
257
258 /// Per-turn authority payload carried by [`Op::SendMessage`]. Extracted from
259 /// the enum arm so new per-turn fields accrete here instead of widening the
260 /// variant; the serializable twin is `codewhale_protocol::op::TurnSpec`.
261 #[derive(Debug)]
262 pub struct TurnSpec {
263 pub profile_constitution:
264 Option<codewhale_config::user_constitution::ProfileConstitutionSnapshot>,
265 /// Admitted allowance for this turn only; never changes session settings.
266 pub max_output_tokens: Option<std::num::NonZeroU32>,
267 pub content: String,
268 /// Inline image bytes validated by Runtime admission; no file references.
269 pub images: Vec<codewhale_app_server_protocol::runtime::RuntimeImageInput>,
270 pub mode: AppMode,
271 /// Exact, structurally resolved route authority for this turn. The
272 /// engine activates its client before mutating turn state; injected
273 /// engines may use their already-supplied client with the same receipt.
274 pub route: Box<ResolvedRuntimeRoute>,
275 /// Compaction policy derived from the same provider route. Carrying it
276 /// atomically avoids a model/limit mismatch before `SendMessage`.
277 pub compaction: Box<CompactionConfig>,
278 /// Auxiliary provider calls completed while planning this exact turn
279 /// (currently Auto's classifier), bounded and paired with their own
280 /// immutable routes. The engine folds their tokens into total usage
281 /// only; they never enter the parent route's billing aggregate.
282 pub initial_routed_usage: Box<crate::cost_status::RuntimeUsageBatch>,
283 pub goal_objective: Option<String>,
284 pub goal_token_budget: Option<u32>,
285 pub goal_status: GoalStatus,
286 /// Reasoning-effort tier: `"off" | "low" | "medium" | "high" | "max"`.
287 /// `None` lets the provider apply its default.
288 pub reasoning_effort: Option<String>,
289 /// True when the user selected auto thinking, even though the UI sends
290 /// a concrete per-turn value to the model API.
291 pub reasoning_effort_auto: bool,
292 /// True when the user selected auto model routing.
293 pub auto_model: bool,
294 pub allow_shell: bool,
295 pub trust_mode: bool,
296 pub auto_approve: bool,
297 pub approval_mode: ApprovalMode,
298 pub translation_enabled: bool,
299 /// Tool restriction from custom slash command frontmatter.
300 /// `None` means the current turn may use the normal tool set.
301 pub allowed_tools: Option<Vec<String>>,
302 /// Runtime-supplied tools available only for this turn.
303 pub dynamic_tools: Vec<DynamicToolSpec>,
304 /// Hook executor for control-plane hooks.
305 /// `ToolCallBefore` hooks may deny a tool call with exit code 2.
306 pub hook_executor: Option<std::sync::Arc<crate::hooks::HookExecutor>>,
307 pub verbosity: Option<String>,
308 /// Structural input origin. This gates whether the turn may inherit
309 /// YOLO/auto-approval authority; user-shaped text is not enough.
310 pub provenance: UserInputProvenance,
311 pub input_authorship: TurnInputAuthorship,
312 /// Host-supplied correlation token for this submission, echoed verbatim on
313 /// the turn's `Event::TurnStarted`. Hosts that arm submit→`TurnStarted`
314 /// window actions (e.g. a deferred stop replay) use the echo to bind those
315 /// actions to the turn that actually started: every engine self-started
316 /// turn (idle sub-agent completion, background shell wake, goal
317 /// continuation) and the composer shell command turn carry no token, so
318 /// their start cannot be mistaken for a pending submission even when it
319 /// overtakes it in the event stream. `None` for callers that do not
320 /// correlate. The token only survives the in-process engine path: the
321 /// wire op projection and the durable-runtime submission path carry none,
322 /// so hosts submitting over those channels cannot correlate.
323 pub submission_id: Option<String>,
324 }
325
326 /// Operations that can be submitted to the engine.
327 #[derive(Debug)]
328 pub enum Op {
329 Review {
330 turn: Box<TurnSpec>,
331 request: codewhale_protocol::op::ReviewOperation,
332 },
333 /// Send a message to the AI
334 SendMessage(TurnSpec),
335
336 /// Re-check and dispatch an interactive goal continuation when this
337 /// operation reaches the front of the engine queue. Keeping this distinct
338 /// from `SendMessage` prevents a queued `/goal pause` or `/goal clear`
339 /// from being overwritten by a stale synthetic Active snapshot.
340 ContinueGoal {
341 /// Runtime-supplied tools remain available across the synthetic turn
342 /// that continues the same logical goal run.
343 dynamic_tools: Vec<DynamicToolSpec>,
344 /// Opaque identity for an engine-owned synthetic continuation. Direct
345 /// callers use `None`; the engine uses `Some` to coalesce one token
346 /// across capacity-waiting, enqueued, and running-adjacent states.
347 engine_schedule_id: Option<u64>,
348 },
349
350 /// Execute a user-submitted composer shell command (`! <command>`) without
351 /// sending a model turn. This still routes through `exec_shell`, approval,
352 /// sandbox, and command-safety handling.
353 RunShellCommand {
354 command: String,
355 mode: AppMode,
356 allow_shell: bool,
357 trust_mode: bool,
358 auto_approve: bool,
359 approval_mode: ApprovalMode,
360 },
361
362 /// Set the runtime goal status without dispatching a model turn. Used by
363 /// `/goal pause`, `/goal resume`, `/goal clear`, etc. so the engine's
364 /// `SharedGoalState` learns the new status immediately and a queued
365 /// continuation doesn't overwrite it back to Active.
366 SetGoalStatus {
367 status: GoalStatus,
368 /// When `true`, clear the objective entirely (`/goal clear`).
369 clear: bool,
370 /// Accepted control revision; None lets direct callers mint it.
371 goal_id: Option<String>,
372 },
373
374 /// Set (or replace) the active goal objective and immediately start goal
375 /// work through the runtime's continuation steering. `/goal <objective>`
376 /// is the caller; the objective is never echoed as a raw user message.
377 SetGoalObjective {
378 objective: String,
379 token_budget: Option<u32>,
380 /// Accepted control revision; None lets direct callers mint it.
381 goal_id: Option<String>,
382 },
383
384 /// Describe the exact request the next turn would send, without
385 /// sending it (`/preview-request`, #1004).
386 ///
387 /// Handled by the engine because only the engine can rebuild the current
388 /// tool catalog, MCP state, mode, gates, permission posture, and resolved
389 /// route. Pure inspection: it adds no message, no turn, and no tool call.
390 PreviewOutboundRequest {
391 inputs: Box<crate::core::engine::preview::PreviewRequestInputs>,
392 /// Render the manifest as JSON instead of the human-readable table.
393 json: bool,
394 /// Explicit disclosure of the base prompt only; effective system text
395 /// remains protected behind hashes.
396 base_prompt_only: bool,
397 },
398
399 /// List current sub-agents and their status
400 ListSubAgents,
401
402 /// Inspect child settlement at the Engine's idle operation boundary.
403 /// This does not drain the completion inbox or dispatch a second loop.
404 GetSubAgentSettlement {
405 tx: std::sync::Arc<
406 std::sync::Mutex<Option<tokio::sync::oneshot::Sender<SubAgentSettlement>>>,
407 >,
408 },
409
410 /// Cancel a running sub-agent by id or session name.
411 CancelSubAgent {
412 agent_id: String,
413 },
414
415 /// Deliver an operator follow-up to one child on its own fork: live
416 /// delivery to a running child, or a checkpoint continuation (new agent
417 /// id) for an interrupted or completed child. Terminal failed/cancelled
418 /// children answer with a receipt explaining why they cannot continue.
419 FollowUpSubAgent {
420 agent_id: String,
421 text: String,
422 },
423
424 StartFleetMember {
425 start: Box<crate::tools::subagent::FleetMemberStart>,
426 tx: std::sync::Arc<
427 std::sync::Mutex<Option<tokio::sync::oneshot::Sender<FleetMemberStarted>>>,
428 >,
429 },
430
431 /// Change the operating mode
432 ChangeMode {
433 mode: AppMode,
434 allow_shell: bool,
435 trust_mode: bool,
436 auto_approve: bool,
437 approval_mode: ApprovalMode,
438 configured_sandbox_mode: Option<String>,
439 },
440
441 /// Update the model being used and refresh stable prompt context.
442 SetModel {
443 model: String,
444 mode: AppMode,
445 route_limits: Option<codewhale_config::route::RouteLimits>,
446 },
447
448 SetRoute {
449 route: Box<ResolvedRuntimeRoute>,
450 mode: AppMode,
451 },
452
453 /// Update auto-compaction settings
454 SetCompaction {
455 config: CompactionConfig,
456 },
457
458 /// Update the SSE idle timeout used for subsequent streamed turns.
459 SetStreamChunkTimeout {
460 timeout_secs: u64,
461 },
462
463 SetAutoReviewReviewerModel {
464 reviewer_model: Option<String>,
465 },
466
467 /// Update sub-agent runtime controls for subsequent turns.
468 SetSubagentRuntimeConfig {
469 enabled: bool,
470 max_subagents: usize,
471 launch_concurrency: usize,
472 max_spawn_depth: u32,
473 api_timeout_secs: u64,
474 heartbeat_timeout_secs: u64,
475 },
476
477 /// Update the web-search backend for subsequent tool calls.
478 SetSearchProvider {
479 provider: codewhale_runtime::config::SearchProvider,
480 },
481
482 /// Replace the engine's merged Fleet roster after the setup wizard saves a
483 /// project or personal profile. Subsequent turns can use the new role
484 /// immediately instead of requiring an application restart.
485 SetFleetRoster {
486 roster: std::sync::Arc<crate::fleet::roster::FleetRoster>,
487 },
488
489 /// Sync engine session state (used for resume/load)
490 SyncSession {
491 expected: Option<Box<SessionSnapshot>>,
492 control: SessionControlId,
493 session_id: Option<String>,
494 messages: Vec<Message>,
495 system_prompt: Option<SystemPrompt>,
496 system_prompt_override: bool,
497 model: String,
498 workspace: PathBuf,
499 mode: AppMode,
500 agent_preset: Option<String>,
501 },
502
503 /// Rewind only the exact conversation observed by the caller. The Engine
504 /// compares the full expected state before changing history or caches.
505 /// A rejected rewind returns None and performs no mutation or inference.
506 RewindConversation {
507 control: SessionControlId,
508 expected: Box<SessionSnapshot>,
509 messages: Vec<Message>,
510 tx: tokio::sync::oneshot::Sender<Option<SessionSnapshot>>,
511 },
512
513 /// Run context compaction on one exact, structurally resolved provider
514 /// route with policy derived from that same descriptor.
515 CompactContext {
516 /// Stable request identity allocated before the operation enters the
517 /// bounded mailbox. Cancellation uses this id even when the provider
518 /// future has not started yet.
519 id: String,
520 route: Box<ResolvedRuntimeRoute>,
521 compaction: Box<CompactionConfig>,
522 },
523
524 /// Cancel one exact queued or running context-compaction request.
525 CancelCompaction {
526 id: String,
527 },
528
529 /// Get a snapshot of the current session state (messages, tokens, etc.)
530 /// for saving to disk. Returns the result via the oneshot sender so
531 /// the caller doesn't have to compete with the SSE event stream.
532 GetSessionSnapshot {
533 tx: std::sync::Arc<std::sync::Mutex<Option<tokio::sync::oneshot::Sender<SessionSnapshot>>>>,
534 },
535
536 /// Get the live context-window budget for this session's route. Computed
537 /// on the engine so `active_route_limits`, the memoized token estimate,
538 /// and the last billed prompt size all come from one authority.
539 GetContextBudget {
540 tx: std::sync::Arc<
541 std::sync::Mutex<Option<tokio::sync::oneshot::Sender<Option<SessionContextBudget>>>>,
542 >,
543 },
544
545 /// Get active provider request concurrency state for readiness surfaces.
546 GetProviderRuntimeStatus {
547 tx: std::sync::Arc<
548 std::sync::Mutex<Option<tokio::sync::oneshot::Sender<ProviderRuntimeStatus>>>,
549 >,
550 },
551
552 /// Populate the engine-owned MCP pool once at UI boot and return a
553 /// snapshot from that exact pool. This is not a config reload and never
554 /// constructs a UI-owned discovery pool. Optional servers never block
555 /// the first model turn: that turn snapshots currently-ready tools.
556 BootstrapMcp {
557 tx: std::sync::Arc<
558 std::sync::Mutex<Option<tokio::sync::oneshot::Sender<McpBootstrapResult>>>,
559 >,
560 },
561
562 /// Retry one failed MCP server on the existing engine pool and return a
563 /// full snapshot. Ready siblings are never invalidated or reconnected.
564 RetryMcpServer {
565 name: String,
566 tx: std::sync::Arc<
567 std::sync::Mutex<Option<tokio::sync::oneshot::Sender<McpBootstrapResult>>>,
568 >,
569 },
570
571 /// Force the engine-owned MCP config/catalog to reload and reconnect.
572 /// The returned snapshot is taken from that same live pool.
573 ReloadMcp {
574 config_path: PathBuf,
575 tx: std::sync::Arc<std::sync::Mutex<Option<tokio::sync::oneshot::Sender<McpReloadResult>>>>,
576 },
577
578 /// Run agent-driven context purging.
579 PurgeContext,
580
581 /// Edit the last user message: remove the last user+assistant exchange
582 /// from the session, then re-send with the new content.
583 EditLastTurn {
584 new_message: String,
585 /// Host-supplied correlation token, echoed on the replayed turn's
586 /// `Event::TurnStarted` (see `TurnSpec::submission_id`).
587 submission_id: Option<String>,
588 },
589
590 /// Enable or disable the background advisor watcher for this session.
591 /// When enabled, a fire-and-forget background task runs after each turn
592 /// that contained tool calls and emits an `Event::AdvisoryNote` with
593 /// concise observations. (#3982)
594 SetAdvisorEnabled {
595 enabled: bool,
596 },
597
598 /// Shutdown the engine
599 Shutdown,
600 }
601
601 lines RUST