codewhale-tui 0.9.2

Terminal UI for open-source and open-weight coding models
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Events emitted by the core engine to the UI.
//!
//! These events flow from the engine to the TUI via a channel,
//! enabling non-blocking, real-time updates.

use std::{path::PathBuf, sync::Arc};

use chrono::{DateTime, Utc};
use serde_json::Value;

use crate::config::ApiProvider;
use crate::error_taxonomy::ErrorEnvelope;
use crate::models::{Message, SystemPrompt, Tool, Usage};
use crate::tools::goal::GoalSnapshot;
use crate::tools::spec::{ToolError, ToolResult};
use crate::tools::subagent::{AgentWorkerStatus, CoordinationDetailProjection, SubAgentResult};
use crate::tools::user_input::UserInputRequest;

/// Final status for a turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnOutcomeStatus {
    Completed,
    Interrupted,
    Failed,
}

/// Provider/model route resolved for a model-backed turn.
///
/// Emitted at `RouteDispatched` so hosts retain provenance until the matching
/// `TurnComplete` without relying on mutable global selection state. Non-model
/// turns such as composer `!` shell commands use no route.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TurnRoute {
    pub provider: ApiProvider,
    /// Exact non-secret configured route key. Named custom providers all map
    /// to [`ApiProvider::Custom`], so the enum alone is not provenance.
    pub provider_identity: String,
    pub model: String,
    pub auto_model: bool,
    /// Secret-free proof of the endpoint and credential generation the turn's
    /// client was *installed* on, minted from that client rather than re-read
    /// from config later.
    ///
    /// Hosts that dispatch follow-up work derived from this turn's context must
    /// authorize it against this receipt: config is mutable and web config
    /// events are drained ahead of engine events, so anything a host resolves
    /// while handling `TurnStarted` may already describe a different route.
    /// `None` when no concrete client was installed (injected-client engines,
    /// or a client that failed to construct).
    pub receipt: Option<crate::route_receipt::TurnRouteReceipt>,
    /// Billing evidence for the request that was actually put on the wire.
    ///
    /// `None` at `TurnStarted`: a lifecycle start is not a dispatch, and a
    /// route that has not been sent has no billing time, no metering surface,
    /// and no endpoint to attest. Populated exactly once, at the wire
    /// boundary, and delivered on `RouteDispatched`. Consumers that price a
    /// turn must treat `None` as *unknown*, never as a zero-cost turn.
    pub billing: Option<RouteBillingEnvelope>,
    /// Endpoint this turn's client was frozen against, verbatim.
    ///
    /// [`crate::route_receipt::TurnRouteReceipt`] deliberately keeps only a
    /// redacted endpoint identity, which billing cannot classify from, so the
    /// non-secret URL travels here. Captured from the resolved route candidate
    /// at the client-freeze boundary, before any ambient selection state can
    /// move. Empty only when no endpoint was captured, which bills Unknown
    /// rather than guessing.
    pub base_url: String,
    /// Credential/pay-mode product truth captured from the route-scoped config
    /// at the same instant.
    ///
    /// Together with `provider_identity` and `base_url` this is a complete
    /// [`crate::route_billing::DispatchedReceipt`]: every fact billing needs,
    /// frozen at the client-freeze boundary. Consumers must classify from
    /// these fields and must never re-read an ambient `Config` after the turn
    /// starts — by `TurnComplete` a provider switch, an auto-router hop, or a
    /// `/provider` change can have moved it elsewhere.
    pub billing_product: crate::route_billing::RouteProduct,
}

/// Dispatch-time billing evidence. Separate from [`TurnRoute`] so the type
/// system — not a convention — enforces that no caller can read a billing
/// surface, endpoint fingerprint, or dispatch instant off a route that was
/// only *planned*.
///
/// This is deliberately *not* the same thing as the classification receipt
/// carried by [`TurnRoute::base_url`] / [`TurnRoute::billing_product`], and
/// the two are not merged. They are captured at different instants and answer
/// different questions:
///
/// - `base_url` + `billing_product` + `provider_identity` are frozen at the
///   **client-freeze** boundary and answer *which route is this and how does
///   it bill* — a [`crate::route_billing::DispatchedReceipt`]. They must be
///   readable from `TurnStarted` onward so a child turn arriving mid-flight
///   can be billed against the parent's frozen route.
/// - This envelope is stamped at the **wire** boundary and answers *what was
///   actually put on the wire, when*. A planned-but-unsent route has no
///   metering surface and no dispatch instant, so it must be structurally
///   absent rather than defaulted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteBillingEnvelope {
    pub billing_surface: Option<String>,
    pub endpoint_fingerprint: Option<String>,
    pub billing_mode: crate::cost_status::RouteBillingMode,
    pub dispatched_at: DateTime<Utc>,
}

impl TurnRoute {
    /// Priceable envelope for this route, or `None` when the route was never
    /// dispatched. Deliberately not a `Default`-filled envelope: an undispatched
    /// route has no cost, and "no cost" is not "zero cost".
    #[must_use]
    pub fn cost_envelope(&self) -> Option<crate::cost_status::EffectiveRouteEnvelope> {
        let billing = self.billing.as_ref()?;
        Some(crate::cost_status::EffectiveRouteEnvelope {
            provider: self.provider,
            provider_identity: self.provider_identity.clone(),
            model: self.model.clone(),
            billing_surface: billing.billing_surface.clone(),
            endpoint_fingerprint: billing.endpoint_fingerprint.clone(),
            billing_mode: billing.billing_mode,
            dispatched_at: billing.dispatched_at,
        })
    }
}

/// Structured lifecycle metadata paired with a human-readable
/// [`Event::AgentProgress`] message.
///
/// Producers own this classification. UI consumers may bound the display
/// message, but must never recover lifecycle state by parsing it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentProgressEventMeta {
    pub worker_status: AgentWorkerStatus,
    pub step: Option<u32>,
    /// Canonical action/tool name. Presentation aliases are applied by the UI
    /// when it creates the bounded current-activity projection.
    pub tool_name: Option<String>,
}

impl AgentProgressEventMeta {
    #[must_use]
    pub const fn new(worker_status: AgentWorkerStatus) -> Self {
        Self {
            worker_status,
            step: None,
            tool_name: None,
        }
    }

    #[must_use]
    pub const fn with_step(mut self, step: u32) -> Self {
        self.step = Some(step);
        self
    }

    #[must_use]
    pub fn with_tool(mut self, tool_name: impl Into<String>) -> Self {
        self.tool_name = Some(tool_name.into());
        self
    }
}

/// Events emitted by the engine to update the UI.
#[derive(Debug, Clone)]
pub enum Event {
    // === Streaming Events ===
    /// A new message block has started
    MessageStarted {
        #[allow(dead_code)]
        index: usize,
    },

    /// Incremental text content delta
    MessageDelta {
        #[allow(dead_code)]
        index: usize,
        content: String,
    },

    /// Message block completed
    MessageComplete {
        #[allow(dead_code)]
        index: usize,
    },

    /// Thinking block started
    ThinkingStarted {
        #[allow(dead_code)]
        index: usize,
    },

    /// Incremental thinking content delta
    ThinkingDelta {
        #[allow(dead_code)]
        index: usize,
        content: String,
    },

    /// Thinking block completed
    ThinkingComplete {
        #[allow(dead_code)]
        index: usize,
    },

    // === Tool Events ===
    /// Tool call initiated
    ToolCallStarted {
        id: String,
        name: String,
        input: Value,
    },

    /// Best-effort liveness pulse while a tool future remains pending.
    ///
    /// This carries no output and must not change user-visible status or the
    /// transcript. It only prevents the TUI from declaring a healthy,
    /// deliberately long-running tool turn stale.
    ToolCallHeartbeat,

    /// Tool call completed
    ToolCallComplete {
        id: String,
        name: String,
        result: Result<ToolResult, ToolError>,
    },

    // === Turn Lifecycle ===
    /// A new turn has started (user sent a message)
    TurnStarted {
        turn_id: String,
        created_at: DateTime<Utc>,
        /// Legacy/non-model hosts may still attach a route at start. Model
        /// turns emit it separately at the real provider dispatch boundary.
        route: Option<TurnRoute>,
    },

    /// Bounded tool-field projection from a prepared model-client request.
    /// Delivery remains unknown; this event is emitted before connection setup.
    ToolRequestSnapshot {
        snapshot: crate::tool_inspection::ToolInspectionSnapshot,
    },

    /// Immutable billing route captured immediately before the first provider
    /// request, after snapshots and other potentially slow pre-dispatch work.
    RouteDispatched { turn_id: String, route: TurnRoute },

    /// The turn is complete (no more tool calls)
    TurnComplete {
        usage: Usage,
        status: TurnOutcomeStatus,
        error: Option<String>,
        /// Tool catalog sent with this turn's model request.
        tool_catalog: Option<Vec<Tool>>,
        /// API base URL used by this turn's client.
        base_url: Option<String>,
    },

    /// Runtime goal state changed inside the engine, usually from model-visible
    /// `create_goal` or `update_goal` tool calls.
    GoalUpdated { snapshot: GoalSnapshot },

    /// Context compaction started.
    CompactionStarted {
        id: String,
        auto: bool,
        message: String,
    },

    /// Context compaction completed.
    CompactionCompleted {
        id: String,
        auto: bool,
        message: String,
        /// Number of messages before compaction.
        #[allow(dead_code)]
        messages_before: Option<usize>,
        /// Number of messages after compaction.
        #[allow(dead_code)]
        messages_after: Option<usize>,
        /// Rendered text of the accumulated compaction summary prompt, if any.
        /// Host layers (e.g. the /v1 runtime) persist this into the thread
        /// record so the summary survives engine reloads — without it the
        /// summary lives only in engine memory and is lost on LRU eviction
        /// or restart (SyncSession re-extracts it from the record prompt).
        summary_prompt: Option<String>,
    },

    /// Context purge started.
    PurgeStarted {
        /// Status message for display.
        message: String,
    },

    /// Context purge completed.
    PurgeCompleted {
        /// Number of messages before purge.
        messages_before: usize,
        /// Number of messages after purge.
        messages_after: usize,
        /// How many messages were removed.
        removed_count: usize,
        /// How many replace operations were applied.
        replaced_count: usize,
        /// Summary message for display.
        message: String,
    },

    /// Context purge failed.
    PurgeFailed { message: String },

    /// Context compaction failed.
    CompactionFailed {
        id: String,
        auto: bool,
        message: String,
    },

    // === Sub-Agent Events ===
    /// A sub-agent has been spawned
    AgentSpawned {
        id: String,
        prompt: String,
        parent_run_id: Option<String>,
        spawn_depth: u32,
    },

    /// Sub-agent progress update
    AgentProgress {
        id: String,
        status: String,
        activity: AgentProgressEventMeta,
        parent_run_id: Option<String>,
        spawn_depth: u32,
    },

    /// Sub-agent completed
    AgentComplete { id: String, result: String },

    /// Sub-agent listing plus the same bounded typed coordination projection
    /// used by machine-readable `agents/coordinate inspect`.
    AgentList {
        agents: Vec<SubAgentResult>,
        coordination: CoordinationDetailProjection,
    },

    /// Structured sub-agent mailbox envelope (issue #128). Carries the
    /// monotonic seq + the typed `MailboxMessage` so the UI can route each
    /// envelope to the correct in-transcript card.
    SubAgentMailbox {
        /// Engine turn identity. Sequence numbers restart for every mailbox,
        /// so consumers must deduplicate on `(turn_id, seq)`, never `seq`
        /// alone.
        turn_id: String,
        seq: u64,
        message: crate::tools::subagent::MailboxMessage,
    },

    /// Live workflow UI event (#4122). Mirrors a typed `WorkflowUiEvent` JSON
    /// object so the TUI can advance the WorkflowPanel and the compact history
    /// card while a run is still in flight (not only on tool complete).
    WorkflowUi {
        run_id: String,
        /// Flattened event JSON: `{"type":"task_started", "at_ms":…, …}`.
        /// Callers inject `run_id` on the object when available.
        event: Value,
    },

    // === System Events ===
    /// An error occurred
    Error {
        envelope: ErrorEnvelope,
        #[allow(dead_code)]
        recoverable: bool,
    },

    /// Status message for UI display
    Status { message: String },

    /// Rendered `/preview-request` manifest (#1004).
    ///
    /// The engine is the only authority that can rebuild the exact next-turn
    /// request, so the manifest is rendered there and delivered as text. The
    /// payload is normally a redacted, typed manifest — never a request body.
    /// The explicit `base-prompt` mode may instead carry only the exact base
    /// prompt; it never carries runtime/system additions. There is no error
    /// variant: a manifest that cannot describe something says so in a typed
    /// unavailable section instead.
    RequestManifestReady { rendered: String },

    /// Pause terminal input events (for interactive subprocesses).
    PauseEvents {
        /// Optional one-shot notification fired after the UI has actually
        /// released the terminal to the child process.
        ack: Option<Arc<tokio::sync::Notify>>,
    },

    /// Resume terminal input events after subprocess completion
    ResumeEvents,

    /// Request user approval for a tool call
    ApprovalRequired {
        id: String,
        tool_name: String,
        description: String,
        /// Tool parameters for approval display. Carried on the event so the
        /// TUI does not need to reconstruct them from `pending_tool_uses`.
        input: Value,
        /// Exact-argument fingerprint, used to scope *denials* (#1617).
        approval_key: String,
        /// Lossy / arity-aware fingerprint, used to scope *approvals* so an
        /// "approve for session" covers later flag variants (v0.8.37).
        approval_grouping_key: String,
        /// The model's explanation of intent before invoking write tools (#2381).
        /// Displayed in the approval view so users understand *why* the change
        /// is being made before reviewing *what* will change.
        intent_summary: Option<String>,
        /// When true, the UI must show the prompt instead of consuming
        /// session/auto approval shortcuts.
        approval_force_prompt: bool,
    },

    /// Request user input for a tool call
    UserInputRequired {
        id: String,
        request: UserInputRequest,
    },

    /// Authoritative API conversation state from the engine session.
    ///
    /// The UI receives granular display events, but those are not always a
    /// lossless representation of the API transcript. DeepSeek can emit
    /// reasoning directly followed by tool calls without a visible assistant
    /// text block, and that assistant message still has to be persisted for
    /// later `reasoning_content` replay.
    SessionUpdated {
        session_id: String,
        messages: Vec<Message>,
        system_prompt: Option<SystemPrompt>,
        model: String,
        workspace: PathBuf,
    },

    /// Request user decision after sandbox denial
    #[allow(dead_code)]
    ElevationRequired {
        tool_id: String,
        tool_name: String,
        command: Option<String>,
        denial_reason: String,
        blocked_network: bool,
        blocked_write: bool,
    },

    /// Observable LSP repair-loop update for the Turn Inspector (#4107).
    /// Carries only summary counts/state — never raw prompt internals.
    LspRepairUpdate {
        diagnostics_found: usize,
        files: usize,
        injected: bool,
    },

    // === Prefix-Cache Stability Events ===
    /// The prefix (system prompt + tool specs) changed between turns,
    /// which invalidates DeepSeek's KV prefix cache. Carries diagnostics
    /// for the TUI to surface.
    PrefixCacheChange {
        /// Human-readable description of what changed.
        description: String,
        /// Whether the system prompt component changed.
        system_prompt_changed: bool,
        /// Whether the tool set component changed.
        tools_changed: bool,
        /// Overall prefix stability percentage (100 = fully stable).
        stability_pct: u32,
        /// True when the prefix actually changed (cache invalidated).
        /// False for routine stable-check heartbeats.
        changed: bool,
        /// Current pinned prefix combined hash (SHA-256, 64 hex chars).
        /// Carried so `/cache stats` can surface it without reaching
        /// into the engine's PrefixStabilityManager.
        pinned_combined_hash: String,
    },
}

impl Event {
    /// Create an error event from a categorized envelope. The envelope's own
    /// `recoverable` flag controls whether the UI flips into offline mode.
    pub fn error(envelope: ErrorEnvelope) -> Self {
        let recoverable = envelope.recoverable;
        Event::Error {
            envelope,
            recoverable,
        }
    }

    /// Create a new status event
    pub fn status(message: impl Into<String>) -> Self {
        Event::Status {
            message: message.into(),
        }
    }
}