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