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