Skip to main content

vtcode_exec_events/
lib.rs

1#![allow(
2    missing_docs,
3    dead_code,
4    unused_imports,
5    reason = "Intentional compatibility, platform, or test-only suppression."
6)]
7//! Structured execution telemetry events shared across VT Code crates.
8//!
9//! This crate exposes the serialized schema for thread lifecycle updates,
10//! command execution results, and other timeline artifacts emitted by the
11//! automation runtime. Downstream applications can deserialize these
12//! structures to drive dashboards, logging, or auditing pipelines without
13//! depending on the full `vtcode-core` crate.
14//!
15//! # Agent Trace Support
16//!
17//! This crate implements the [Agent Trace](https://agent-trace.dev/) specification
18//! for tracking AI-generated code attribution. See the [`trace`] module for details.
19
20use serde::{Deserialize, Serialize};
21
22pub mod atif;
23pub mod diagnostic;
24pub use diagnostic::{Diagnostic, DiagnosticAction, DiagnosticSeverity};
25mod event_wire;
26pub use event_wire::wire_type;
27pub mod goal;
28pub mod items;
29pub use items::{
30    AgentMessageItem, AppPreviewItem, AppUiPosture, CommandExecutionItem, CommandExecutionStatus, DecisionItem,
31    FileChangeItem, FileUpdateChange, McpToolCallItem, McpToolCallStatus, PatchApplyStatus, PatchChangeKind, PlanItem,
32    ReasoningItem, ThreadItem, ThreadItemDetails, ToolCallStatus, ToolInvocationItem, ToolOutcome, ToolOutputItem,
33    WebSearchItem, tool_outcome_from_status,
34};
35pub mod matrix;
36pub mod planning;
37pub mod trace;
38pub mod tracker;
39
40/// Semantic version of the serialized event schema exported by this crate.
41pub const EVENT_SCHEMA_VERSION: &str = "0.29.0";
42
43/// Wraps a [`ThreadEvent`] with schema metadata so downstream consumers can
44/// negotiate compatibility before processing an event stream.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
47pub struct VersionedThreadEvent {
48    /// Semantic version describing the schema of the nested event payload.
49    schema_version: String,
50    /// Concrete event emitted by the agent runtime.
51    event: ThreadEvent,
52}
53
54impl VersionedThreadEvent {
55    /// Creates a new [`VersionedThreadEvent`] using the current
56    /// [`EVENT_SCHEMA_VERSION`].
57    pub fn new(event: ThreadEvent) -> Self {
58        Self {
59            schema_version: EVENT_SCHEMA_VERSION.to_string(),
60            event,
61        }
62    }
63
64    /// Returns the nested [`ThreadEvent`] by reference.
65    pub fn event(&self) -> &ThreadEvent {
66        &self.event
67    }
68
69    /// Returns the nested [`ThreadEvent`], consuming the wrapper.
70    pub fn into_event(self) -> ThreadEvent {
71        self.event
72    }
73}
74
75impl From<ThreadEvent> for VersionedThreadEvent {
76    fn from(event: ThreadEvent) -> Self {
77        Self::new(event)
78    }
79}
80
81/// Sink for processing [`ThreadEvent`] instances.
82pub trait EventEmitter {
83    /// Invoked for each event emitted by the automation runtime.
84    fn emit(&mut self, event: &ThreadEvent);
85}
86
87impl<F> EventEmitter for F
88where
89    F: FnMut(&ThreadEvent),
90{
91    fn emit(&mut self, event: &ThreadEvent) {
92        self(event);
93    }
94}
95
96#[cfg(feature = "serde-json")]
97pub mod json;
98
99#[cfg(feature = "telemetry-log")]
100mod log_support;
101
102#[cfg(feature = "telemetry-log")]
103pub use log_support::PublicLogEmitter as LogEmitter;
104
105#[cfg(feature = "telemetry-tracing")]
106mod tracing_support;
107
108#[cfg(feature = "telemetry-tracing")]
109pub use tracing_support::PublicTracingEmitter as TracingEmitter;
110
111#[cfg(feature = "telemetry-otel")]
112mod otel_support;
113
114#[cfg(feature = "telemetry-otel")]
115pub use otel_support::PublicOtelEmitter as OtelEmitter;
116
117#[cfg(feature = "schema-export")]
118pub mod schema;
119
120/// Structured events emitted during autonomous execution.
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
122#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
123#[serde(tag = "type")]
124pub enum ThreadEvent {
125    /// Replayable local matrix lifecycle checkpoint.
126    #[serde(rename = "matrix.updated")]
127    MatrixUpdated(Box<matrix::MatrixSnapshot>),
128    /// Bounded task-tracker checklist snapshot after a mutation.
129    #[serde(rename = "tracker.updated")]
130    TrackerUpdated(Box<tracker::TrackerSnapshot>),
131    /// Bounded thread-goal snapshot after a mutation (`None` signals a clear).
132    #[serde(rename = "goal.updated")]
133    GoalUpdated(Box<goal::GoalUpdatedEvent>),
134    /// Indicates that a new execution thread has started.
135    #[serde(rename = "thread.started")]
136    ThreadStarted(ThreadStartedEvent),
137    /// Indicates that an execution thread has reached a terminal outcome.
138    #[serde(rename = "thread.completed")]
139    ThreadCompleted(Box<ThreadCompletedEvent>),
140    /// Indicates that conversation compaction replaced older history with a boundary.
141    #[serde(rename = "thread.compact_boundary")]
142    ThreadCompactBoundary(Box<ThreadCompactBoundaryEvent>),
143    /// Indicates that the approved plan handoff rebuilt a fresh execution context.
144    #[serde(rename = "context.reset")]
145    ContextReset(ContextResetEvent),
146    /// Marks the beginning of an execution turn.
147    #[serde(rename = "turn.started")]
148    TurnStarted(TurnStartedEvent),
149    /// Marks the completion of an execution turn.
150    #[serde(rename = "turn.completed")]
151    TurnCompleted(TurnCompletedEvent),
152    /// Marks a turn as failed with additional context.
153    #[serde(rename = "turn.failed")]
154    TurnFailed(TurnFailedEvent),
155    /// Marks a turn as blocked before success could be confirmed. Emitted
156    /// alongside `turn.failed` so UI subscribers get a first-class signal
157    /// with the fuse counters and last tool instead of inferring it.
158    #[serde(rename = "turn.blocked")]
159    TurnBlocked(Box<TurnBlockedEvent>),
160    /// Indicates that an item has started processing.
161    #[serde(rename = "item.started")]
162    ItemStarted(ItemStartedEvent),
163    /// Indicates that an item has been updated.
164    #[serde(rename = "item.updated")]
165    ItemUpdated(ItemUpdatedEvent),
166    /// Indicates that an item reached a terminal state.
167    #[serde(rename = "item.completed")]
168    ItemCompleted(ItemCompletedEvent),
169    /// Emitted when an MCP server offers app UI that the `off` apps tier
170    /// refuses. No `ui://` resource was fetched and no app rows render; the
171    /// refused URIs are listed so the denial stays visible.
172    #[serde(rename = "app.sandbox_denied")]
173    AppSandboxDenied(Box<AppSandboxDeniedEvent>),
174    /// Emitted when a tool requires user permission before execution.
175    #[serde(rename = "permission.requested")]
176    PermissionRequested(PermissionRequestedEvent),
177    /// Emitted when the user resolves a permission prompt.
178    #[serde(rename = "permission.resolved")]
179    PermissionResolved(PermissionResolvedEvent),
180    /// A mid-turn user interjection was merged into the running turn.
181    #[serde(rename = "interjected")]
182    Interjected(InterjectedEvent),
183    /// Streaming delta for a plan item in Planning workflow.
184    #[serde(rename = "plan.delta")]
185    PlanDelta(Box<PlanDeltaEvent>),
186    /// Indicates that a completed plan is waiting for an implementation decision.
187    #[serde(rename = "plan.approval.requested")]
188    PlanApprovalRequested(PlanApprovalRequestedEvent),
189    /// Records the user's or policy's decision about a completed plan.
190    #[serde(rename = "plan.approval.resolved")]
191    PlanApprovalResolved(PlanApprovalResolvedEvent),
192    /// Represents a fatal error.
193    #[serde(rename = "error")]
194    Error(ThreadErrorEvent),
195    /// Catch-all for unknown event types added in newer schema versions.
196    /// Preserves forward compatibility when older binaries read newer event streams.
197    #[serde(other)]
198    Unknown,
199}
200
201#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
202#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
203pub struct ThreadStartedEvent {
204    /// Unique identifier for the thread that was started.
205    pub thread_id: String,
206}
207
208#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
209#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
210#[serde(rename_all = "snake_case")]
211pub enum ThreadCompletionSubtype {
212    Success,
213    ErrorMaxTurns,
214    ErrorMaxBudgetUsd,
215    ErrorDuringExecution,
216    Cancelled,
217    /// Catch-all for unknown completion subtypes added in newer schema versions.
218    #[serde(other)]
219    Unknown,
220}
221
222impl ThreadCompletionSubtype {
223    pub const fn as_str(&self) -> &'static str {
224        match self {
225            Self::Success => "success",
226            Self::ErrorMaxTurns => "error_max_turns",
227            Self::ErrorMaxBudgetUsd => "error_max_budget_usd",
228            Self::ErrorDuringExecution => "error_during_execution",
229            Self::Cancelled => "cancelled",
230            Self::Unknown => "unknown",
231        }
232    }
233
234    pub const fn is_success(self) -> bool {
235        matches!(self, Self::Success)
236    }
237}
238
239#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
240#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
241#[serde(rename_all = "snake_case")]
242pub enum CompactionTrigger {
243    Manual,
244    Auto,
245    Recovery,
246    /// Compaction triggered by a mid-session switch of the main model or
247    /// provider, so the newly selected model starts from a clean summary.
248    ModelSwitch,
249    /// Catch-all for unknown triggers added in newer schema versions.
250    #[serde(other)]
251    Unknown,
252}
253
254impl CompactionTrigger {
255    pub const fn as_str(self) -> &'static str {
256        match self {
257            Self::Manual => "manual",
258            Self::Auto => "auto",
259            Self::Recovery => "recovery",
260            Self::ModelSwitch => "model_switch",
261            Self::Unknown => "unknown",
262        }
263    }
264}
265
266#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
267#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
268#[serde(rename_all = "snake_case")]
269pub enum CompactionMode {
270    Provider,
271    Local,
272    /// Catch-all for unknown modes added in newer schema versions.
273    #[serde(other)]
274    Unknown,
275}
276
277impl CompactionMode {
278    pub const fn as_str(self) -> &'static str {
279        match self {
280            Self::Provider => "provider",
281            Self::Local => "local",
282            Self::Unknown => "unknown",
283        }
284    }
285}
286
287#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
288#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
289pub struct ThreadCompletedEvent {
290    /// Runtime completion timestamp, absent from legacy events.
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub completed_at: Option<String>,
293    /// Stable thread identifier for the session.
294    pub thread_id: String,
295    /// Stable session identifier for the runtime that produced the thread.
296    pub session_id: String,
297    /// Coarse result category aligned with SDK-style terminal states.
298    pub subtype: ThreadCompletionSubtype,
299    /// VT Code-specific detailed outcome code.
300    pub outcome_code: String,
301    /// Final assistant result text when the thread completed successfully.
302    #[serde(skip_serializing_if = "Option::is_none")]
303    pub result: Option<String>,
304    /// Provider stop reason or VT Code terminal reason when available.
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub stop_reason: Option<String>,
307    /// Aggregated token usage across the thread.
308    pub usage: Usage,
309    /// Optional estimated total API cost for the thread.
310    #[serde(skip_serializing_if = "Option::is_none")]
311    pub total_cost_usd: Option<serde_json::Number>,
312    /// Number of turns executed before completion.
313    pub num_turns: usize,
314}
315
316#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
317#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
318pub struct ThreadCompactBoundaryEvent {
319    /// Stable thread identifier for the session.
320    pub thread_id: String,
321    /// Whether compaction was triggered manually or automatically.
322    pub trigger: CompactionTrigger,
323    /// Whether the compaction boundary came from provider-native or local compaction.
324    pub mode: CompactionMode,
325    /// Number of messages before compaction.
326    pub original_message_count: usize,
327    /// Number of messages after compaction.
328    pub compacted_message_count: usize,
329    /// Optional persisted artifact containing the archived compaction summary/history.
330    #[serde(skip_serializing_if = "Option::is_none")]
331    pub history_artifact_path: Option<String>,
332    /// Segment identifier that contained the request prefix before compaction.
333    #[serde(skip_serializing_if = "Option::is_none")]
334    pub previous_segment_id: Option<String>,
335    /// Segment identifier created after compaction.
336    #[serde(skip_serializing_if = "Option::is_none")]
337    pub new_segment_id: Option<String>,
338    /// Hash of the immutable request prefix before compaction.
339    #[serde(skip_serializing_if = "Option::is_none")]
340    pub previous_prefix_hash: Option<String>,
341    /// Hash of the immutable request prefix after compaction.
342    #[serde(skip_serializing_if = "Option::is_none")]
343    pub new_prefix_hash: Option<String>,
344    /// Hash of the ordered tool catalog before compaction.
345    #[serde(skip_serializing_if = "Option::is_none")]
346    pub previous_catalog_hash: Option<String>,
347    /// Hash of the ordered tool catalog after compaction.
348    #[serde(skip_serializing_if = "Option::is_none")]
349    pub new_catalog_hash: Option<String>,
350}
351
352#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
353#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
354#[serde(rename_all = "snake_case")]
355pub enum ContextResetTrigger {
356    /// The user selected the fresh-context plan approval path.
357    PlanApproval,
358    /// Catch-all for triggers introduced by newer schema versions.
359    #[serde(other)]
360    Unknown,
361}
362
363#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
364#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
365pub struct ContextResetEvent {
366    /// Stable thread identifier for the session.
367    pub thread_id: String,
368    /// Identifier of the turn that approved the plan.
369    pub turn_id: String,
370    /// What initiated the context reset.
371    pub trigger: ContextResetTrigger,
372    /// Whether the approved plan and task tracker survived the reset.
373    pub plan_preserved: bool,
374    /// Context pressure reported before the reset, expressed as a percentage.
375    pub previous_context_usage_percent: u8,
376    /// Whether the per-turn and per-session tool budgets were reset.
377    pub tool_budget_reset: bool,
378}
379
380#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
381#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
382pub struct TurnStartedEvent {
383    /// Optional decomposition of the assembled first-request prefix so
384    /// downstream consumers can attribute token overhead without inventing
385    /// parallel event types.
386    #[serde(skip_serializing_if = "Option::is_none")]
387    token_breakdown: Option<Box<TokenBreakdown>>,
388    /// Task identity and public input recorded at the request boundary.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub context: Option<Box<ExecutionContext>>,
391}
392
393impl TurnStartedEvent {
394    /// Recorded prefix token breakdown, absent when the producer did not capture it.
395    pub fn token_breakdown(&self) -> Option<&TokenBreakdown> {
396        self.token_breakdown.as_deref()
397    }
398}
399
400/// Origin of a turn's input; internal turns retain their parent task.
401#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
402#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
403#[serde(rename_all = "snake_case")]
404pub enum InputOrigin {
405    User,
406    Correction,
407    PlanApproval,
408    Continuation,
409    Retry,
410}
411
412/// Optional recorded execution ancestry. Absent fields are historical gaps.
413#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
414#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
415pub struct ExecutionContext {
416    pub task_id: String,
417    pub turn_id: String,
418    pub actor_id: String,
419    #[serde(default, skip_serializing_if = "Option::is_none")]
420    pub parent_actor_id: Option<String>,
421    pub origin: InputOrigin,
422    pub timestamp: String,
423    #[serde(default, skip_serializing_if = "Option::is_none")]
424    pub goal: Option<String>,
425}
426
427/// Recorded shell classification, supplied by the runtime's shared classifier.
428#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
429#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
430#[serde(rename_all = "snake_case")]
431pub enum CommandActivity {
432    Inspection,
433    Verification,
434    Mutation,
435}
436
437/// Item identity, timing, and command semantics for explanation consumers.
438#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
439#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
440pub struct ItemContext {
441    pub task_id: String,
442    pub turn_id: String,
443    pub actor_id: String,
444    #[serde(default, skip_serializing_if = "Option::is_none")]
445    pub parent_actor_id: Option<String>,
446    pub timestamp: String,
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub activity: Option<CommandActivity>,
449}
450
451/// Per-request token-budget breakdown for the assembled first-request prefix.
452#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
453#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
454pub struct TokenBreakdown {
455    /// System prompt text tokens.
456    system_prompt_tokens: u64,
457    /// On-wire tool schema tokens.
458    tool_schema_tokens: u64,
459    /// Instruction file tokens included in the prompt.
460    instruction_file_tokens: u64,
461    /// Message history text tokens.
462    message_history_tokens: u64,
463    /// Cache read tokens (served from prior turns).
464    cache_read_tokens: u64,
465    /// Cache write tokens (new cache entries created this turn).
466    cache_write_tokens: u64,
467    /// Tokens that missed cache (neither read nor written).
468    cache_miss_tokens: u64,
469    /// Subagent bootstrap tokens, if this turn spawned a child agent.
470    #[serde(skip_serializing_if = "Option::is_none")]
471    subagent_bootstrap_tokens: Option<u64>,
472}
473
474/// Bound on exec session ids recorded in one turn's `turn.completed` event.
475/// Mirrors `SnapshotTurnDiagnostics::in_progress_exec_sessions` (cap 4,
476/// newest first) so `ThreadEvent` and checkpoint diagnostics cannot drift.
477pub const MAX_IN_PROGRESS_EXEC_SESSIONS: usize = 4;
478
479#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
480#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
481pub struct TurnCompletedEvent {
482    /// Identity of the final agent message, when known.
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub final_response_item_id: Option<Box<String>>,
485    #[serde(default, skip_serializing_if = "Option::is_none")]
486    pub completed_at: Option<Box<String>>,
487    /// Token usage summary for the completed turn.
488    pub usage: Usage,
489    /// Exec sessions still running when the turn ended (bounded, newest
490    /// first). Empty when every command settled within the turn. Correlates
491    /// with the next turn's transient exec-session resume hint without
492    /// requiring session-id reconstruction.
493    #[serde(
494        default,
495        skip_serializing_if = "Vec::is_empty",
496        deserialize_with = "deserialize_null_as_default"
497    )]
498    pub in_progress_exec_sessions: Vec<String>,
499}
500
501#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
502#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
503pub struct TurnFailedEvent {
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub completed_at: Option<Box<String>>,
506    /// Human-readable explanation describing why the turn failed.
507    pub message: String,
508    /// Optional token usage that was consumed before the failure occurred.
509    #[serde(skip_serializing_if = "Option::is_none")]
510    pub usage: Option<Usage>,
511}
512
513#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
514#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
515pub struct TurnBlockedEvent {
516    /// Runtime terminal timestamp, absent from legacy events.
517    #[serde(default, skip_serializing_if = "Option::is_none")]
518    pub completed_at: Option<String>,
519    /// Human-readable explanation describing why the turn was blocked.
520    pub message: String,
521    /// Display label of the last blocked tool call, when known.
522    #[serde(skip_serializing_if = "Option::is_none")]
523    pub last_tool: Option<String>,
524    /// Consecutive blocked tool calls observed this turn.
525    #[serde(default)]
526    pub blocked_streak: usize,
527    /// Total blocked tool calls observed this turn.
528    #[serde(default)]
529    pub blocked_total: usize,
530    /// Consecutive cap that was enforced.
531    #[serde(default)]
532    pub consecutive_cap: usize,
533    /// Total cap that was enforced.
534    #[serde(default)]
535    pub total_cap: usize,
536    /// Whether the fuse tripped while a tool-free recovery pass was active.
537    #[serde(default)]
538    pub recovery_active: bool,
539    /// Optional token usage that was consumed before the block occurred.
540    #[serde(skip_serializing_if = "Option::is_none")]
541    pub usage: Option<Usage>,
542}
543
544#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
545#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
546pub struct ThreadErrorEvent {
547    /// Fatal error message associated with the thread.
548    pub message: String,
549}
550
551#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
552#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
553pub struct AppSandboxDeniedEvent {
554    /// Tool whose result offered the refused app UI.
555    pub tool: String,
556    /// Apps tier that refused the UI (`off`).
557    pub tier: String,
558    /// Refused `ui://` URIs, in first-seen order (capped at 4).
559    pub uris: Vec<String>,
560}
561
562#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
563#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
564pub struct Usage {
565    /// Number of prompt tokens processed during the turn.
566    #[serde(default, deserialize_with = "deserialize_null_as_default")]
567    pub input_tokens: u64,
568    /// Number of cached prompt tokens reused from previous turns.
569    #[serde(default, deserialize_with = "deserialize_null_as_default")]
570    pub cached_input_tokens: u64,
571    /// Number of cache-creation tokens charged during the turn.
572    #[serde(default, deserialize_with = "deserialize_null_as_default")]
573    pub cache_creation_tokens: u64,
574    /// Number of completion tokens generated by the model.
575    #[serde(default, deserialize_with = "deserialize_null_as_default")]
576    pub output_tokens: u64,
577}
578
579/// Serde helper that accepts explicit `null` as `T::default()` for
580/// backward-compatible checkpoint/diagnostics payloads. Pair with
581/// `#[serde(default, deserialize_with = "deserialize_null_as_default")]` so
582/// both missing and `null` fields degrade to the default instead of failing
583/// deserialization. Reused by downstream crates (e.g. `vtcode-core`
584/// snapshots) so the null-tolerance rule cannot drift between copies.
585pub fn deserialize_null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
586where
587    D: serde::Deserializer<'de>,
588    T: Deserialize<'de> + Default,
589{
590    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
591}
592
593impl Usage {
594    /// Number of input tokens billed at the full input rate: neither served
595    /// from cache nor written to it. `input_tokens` is the total prompt token
596    /// count (uncached + cached + cache-creation), so both cached and
597    /// cache-creation tokens are subtracted out here.
598    #[must_use]
599    fn uncached_input_tokens(&self) -> u64 {
600        self.input_tokens
601            .saturating_sub(self.cached_input_tokens)
602            .saturating_sub(self.cache_creation_tokens)
603    }
604
605    /// Cache hit rate as a fraction (0.0 to 1.0): cached input over total input.
606    /// Returns `None` when no input tokens were recorded.
607    #[must_use]
608    pub fn cache_hit_rate(&self) -> Option<f64> {
609        if self.input_tokens == 0 {
610            return None;
611        }
612        Some(self.cached_input_tokens as f64 / self.input_tokens as f64)
613    }
614
615    /// Human-readable summary of prompt cache efficiency.
616    #[must_use]
617    pub fn cache_summary(&self) -> String {
618        let total_input = self.input_tokens;
619        if total_input == 0 {
620            return "No input tokens recorded.".to_string();
621        }
622
623        let cached = self.cached_input_tokens;
624        let creation = self.cache_creation_tokens;
625        let uncached = self.uncached_input_tokens();
626        let rate = cached as f64 / total_input as f64 * 100.0;
627        format!(
628            "Cache: {cached} cached / {total_input} total input ({rate:.1}% hit rate), \
629             {creation} cache-creation, {uncached} uncached"
630        )
631    }
632
633    /// Accumulate another usage sample into this one.
634    pub fn add(&mut self, other: &Usage) {
635        self.input_tokens = self.input_tokens.saturating_add(other.input_tokens);
636        self.cached_input_tokens = self.cached_input_tokens.saturating_add(other.cached_input_tokens);
637        self.cache_creation_tokens = self.cache_creation_tokens.saturating_add(other.cache_creation_tokens);
638        self.output_tokens = self.output_tokens.saturating_add(other.output_tokens);
639    }
640}
641
642#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
643#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
644pub struct ItemCompletedEvent {
645    /// Snapshot of the thread item that completed.
646    pub item: ThreadItem,
647}
648
649#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
650#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
651pub struct ItemStartedEvent {
652    /// Snapshot of the thread item that began processing.
653    pub item: ThreadItem,
654}
655
656#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
657#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
658pub struct ItemUpdatedEvent {
659    /// Snapshot of the thread item after it was updated.
660    pub item: ThreadItem,
661}
662
663#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
664#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
665pub struct PlanDeltaEvent {
666    /// Identifier of the thread emitting this plan delta.
667    pub thread_id: String,
668    /// Identifier of the current turn.
669    pub turn_id: String,
670    /// Identifier of the plan item receiving the delta.
671    pub item_id: String,
672    /// Incremental plan text chunk.
673    pub delta: String,
674    /// Runtime-owned recovery checkpoint; absent in older sessions.
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub recovery: Option<Box<planning::PlanningRecoverySnapshot>>,
677}
678
679#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
680#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
681pub struct PlanApprovalRequestedEvent {
682    /// Identifier of the thread emitting the approval request.
683    pub thread_id: String,
684    /// Identifier of the turn that produced the plan.
685    pub turn_id: String,
686    /// Plan file associated with the approval request, when available.
687    #[serde(skip_serializing_if = "Option::is_none")]
688    pub plan_file: Option<String>,
689}
690
691#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
692#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
693#[serde(rename_all = "snake_case")]
694pub enum PlanApprovalDecision {
695    /// Execute with normal per-edit approval prompts.
696    Execute,
697    /// Execute with automatic edit approval enabled.
698    AutoAccept,
699    /// Execute the plan after rebuilding a fresh context.
700    FreshContext,
701    /// Keep planning and revise the proposed plan.
702    Revise,
703    /// Dismiss the approval request without implementing.
704    Cancel,
705    /// Hand the plan to the build primary agent.
706    SwitchBuild,
707    /// Hand the plan to the auto primary agent.
708    SwitchAuto,
709    /// Catch-all for decisions added in newer schema versions.
710    #[serde(other)]
711    Unknown,
712}
713
714#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
715#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
716pub struct PlanApprovalResolvedEvent {
717    /// Identifier of the thread emitting the approval decision.
718    pub thread_id: String,
719    /// Identifier of the turn in which the decision was made.
720    pub turn_id: String,
721    /// Decision selected by the user or active execution policy.
722    pub decision: PlanApprovalDecision,
723    /// Whether the decision came from policy rather than an interactive user action.
724    pub automatic: bool,
725}
726
727#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
728#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
729#[serde(rename_all = "snake_case")]
730pub enum HarnessEventKind {
731    PlanningStarted,
732    PlanningCompleted,
733    ContinuationStarted,
734    ContinuationSkipped,
735    /// A turn was blocked before success could be confirmed. Carries the fuse
736    /// counters so UI layers can render without correlating multiple events.
737    TurnBlocked,
738    /// A bounded tool-free recovery pass was scheduled after blocked calls.
739    BlockedRecoveryStarted,
740    /// A bounded tool-free recovery pass finished.
741    BlockedRecoveryFinished,
742    BlockedHandoffWritten,
743    /// The owning session resolved its archived blocked handoff and removed
744    /// the live recovery pointer.
745    BlockedHandoffResolved,
746    EvaluationStarted,
747    EvaluationPassed,
748    EvaluationFailed,
749    RevisionStarted,
750    EscalationTriggered,
751    EscalationBypassed,
752    VerificationStarted,
753    VerificationPassed,
754    VerificationFailed,
755    /// Agent recovered from a transient error (e.g. after retry succeeded).
756    ErrorRecovered,
757    /// A transient tool failure triggered an automatic retry attempt.
758    ToolRetryAttempted,
759    /// Latency record for a tool execution, emitted on turn completion.
760    ToolLatencyRecorded,
761    /// A checkpoint snapshot was created for the current turn.
762    SnapshotCreated,
763    /// A checkpoint snapshot was restored (rewind operation).
764    SnapshotRestored,
765    /// The user granted additional session tool-call capacity and the
766    /// pending call will be retried in the same turn.
767    ///
768    /// No longer emitted: the per-turn/session tool-call count budget was
769    /// removed. Retained for wire compatibility with older session logs.
770    SessionToolLimitIncreased,
771    /// The user granted additional tool-loop capacity for the current turn.
772    ///
773    /// No longer emitted: the per-turn tool-loop budget was removed.
774    /// Retained for wire compatibility with older session logs.
775    ToolLoopLimitIncreased,
776    /// A background subprocess or exec session reached a terminal state.
777    BackgroundSubprocessCompleted,
778    /// A native delegated agent's public status and ancestry were observed.
779    DelegatedAgentStatus,
780    /// A message was sent to a peer session's mailbox.
781    SessionMessageSent,
782    /// A peer session's message was received from this session's mailbox.
783    SessionMessageReceived,
784    /// A mailbox message expired before delivery.
785    SessionMessageExpired,
786}
787
788#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
789#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
790#[serde(rename_all = "snake_case")]
791pub enum PermissionDecision {
792    Allow,
793    Deny,
794    Cancelled,
795    Followup,
796}
797
798#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
799#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
800pub struct PermissionRequestedEvent {
801    /// Name of the tool that requires permission.
802    pub tool_name: String,
803    /// Identifier of the tool invocation that requested permission, when known.
804    #[serde(default, skip_serializing_if = "Option::is_none")]
805    pub tool_call_id: Option<String>,
806}
807
808#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
809#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
810pub struct PermissionResolvedEvent {
811    /// Name of the tool that was permitted or denied.
812    pub tool_name: String,
813    /// Identifier of the tool invocation whose permission was resolved, when known.
814    #[serde(default, skip_serializing_if = "Option::is_none")]
815    pub tool_call_id: Option<String>,
816    /// User's decision on the permission prompt.
817    pub decision: PermissionDecision,
818    /// Wall-clock time the prompt was visible, in milliseconds.
819    pub wait_ms: u64,
820}
821
822#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
823#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
824#[serde(rename_all = "snake_case")]
825pub enum InterjectionSource {
826    Direct,
827    Queue,
828}
829
830#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
831#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
832#[serde(rename_all = "snake_case")]
833pub enum RedirectKind {
834    Interjection,
835}
836
837#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
838#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
839pub struct InterjectedEvent {
840    /// Public correction text, when recorded by the runtime.
841    #[serde(default, skip_serializing_if = "Option::is_none")]
842    pub text: Option<Box<String>>,
843    /// How the interjection reached the running turn.
844    pub source: InterjectionSource,
845    /// Number of image attachments that accompanied the interjection.
846    pub image_count: u32,
847    /// Always `Interjection` for this event; carried so the shared
848    /// `redirect_kind` field is queryable uniformly across redirect events.
849    pub redirect_kind: RedirectKind,
850}
851
852#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
853#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
854pub struct HarnessEventItem {
855    /// Specific harness event emitted by the runtime.
856    pub event: HarnessEventKind,
857    /// Optional human-readable message associated with the event.
858    #[serde(skip_serializing_if = "Option::is_none")]
859    pub message: Option<String>,
860    /// Optional verification command associated with the event.
861    #[serde(skip_serializing_if = "Option::is_none")]
862    pub command: Option<String>,
863    /// Optional artifact path associated with the event.
864    #[serde(skip_serializing_if = "Option::is_none")]
865    pub path: Option<String>,
866    /// Optional exit code associated with verification results.
867    #[serde(skip_serializing_if = "Option::is_none")]
868    pub exit_code: Option<i32>,
869    /// Retry/recovery attempt number (1-indexed). Only set for retry-related events.
870    #[serde(skip_serializing_if = "Option::is_none")]
871    pub attempt: Option<u32>,
872    /// Canonical error category for retry/recovery events.
873    #[serde(skip_serializing_if = "Option::is_none")]
874    pub error_category: Option<String>,
875    /// Latency in milliseconds for tool-execution latency events.
876    #[serde(skip_serializing_if = "Option::is_none")]
877    pub duration_ms: Option<u64>,
878    /// Stable task identifier for background completion events.
879    #[serde(skip_serializing_if = "Option::is_none")]
880    pub task_id: Option<String>,
881    /// Child session identifier for background completion events; the peer
882    /// session for session-messaging events.
883    #[serde(skip_serializing_if = "Option::is_none")]
884    pub session_id: Option<String>,
885    /// Correlation id linking related harness events (a mailbox question to
886    /// its answer for session-messaging events).
887    #[serde(skip_serializing_if = "Option::is_none")]
888    pub correlation_id: Option<String>,
889    /// Exec-session identifier for background completion events.
890    #[serde(skip_serializing_if = "Option::is_none")]
891    pub exec_session_id: Option<String>,
892    /// Terminal background status, when the event represents a subprocess.
893    #[serde(skip_serializing_if = "Option::is_none")]
894    pub status: Option<String>,
895    /// Archived transcript reference for background completion events.
896    #[serde(skip_serializing_if = "Option::is_none")]
897    pub transcript_path: Option<String>,
898    /// Archived session reference for background completion events.
899    #[serde(skip_serializing_if = "Option::is_none")]
900    pub archive_path: Option<String>,
901}
902
903impl HarnessEventItem {
904    /// A harness event with every optional field unset. Prefer this over a
905    /// struct literal so new optional fields do not break construction sites.
906    #[must_use]
907    pub fn new(event: HarnessEventKind) -> Self {
908        Self {
909            event,
910            message: None,
911            command: None,
912            path: None,
913            exit_code: None,
914            attempt: None,
915            error_category: None,
916            duration_ms: None,
917            task_id: None,
918            session_id: None,
919            correlation_id: None,
920            exec_session_id: None,
921            status: None,
922            transcript_path: None,
923            archive_path: None,
924        }
925    }
926}
927
928mod error_item;
929pub use error_item::ErrorItem;
930
931#[cfg(test)]
932mod tests;