harn_vm/agent_events/agent.rs
1use serde::{Deserialize, Serialize};
2
3use crate::composition::{CompositionChildCall, CompositionChildResult, CompositionRunEnvelope};
4use crate::llm::receipts::ToolCallReceipt;
5use crate::orchestration::{HandoffArtifact, MutationSessionRecord};
6use crate::tool_annotations::ToolKind;
7
8use super::tool::{ToolCallErrorCategory, ToolCallStatus, ToolExecutor};
9use super::worker::{FsWatchEvent, WorkerEvent};
10
11/// Events emitted by the agent loop. Some variants map 1:1 to ACP
12/// `sessionUpdate` variants; Harn-specific lifecycle events ride on the
13/// extension stream.
14#[derive(Clone, Debug, Serialize, Deserialize)]
15#[serde(tag = "type", rename_all = "snake_case")]
16pub enum AgentEvent {
17 AgentMessageChunk {
18 session_id: String,
19 content: String,
20 },
21 AgentThoughtChunk {
22 session_id: String,
23 content: String,
24 },
25 UserMessage {
26 session_id: String,
27 message_id: String,
28 content: Vec<serde_json::Value>,
29 },
30 ToolCall {
31 session_id: String,
32 tool_call_id: String,
33 tool_name: String,
34 kind: Option<ToolKind>,
35 status: ToolCallStatus,
36 raw_input: serde_json::Value,
37 /// Set to `Some(true)` by the streaming candidate detector
38 /// (harn#692) when this event represents a tool-call shape
39 /// detected in the model's in-flight assistant text but whose
40 /// arguments have not finished parsing yet. Clients can render a
41 /// spinner / placeholder while the model writes the body. The
42 /// detector follows up with a `ToolCallUpdate { parsing: false,
43 /// .. }` carrying either `status: pending` (promoted) or
44 /// `status: failed` with `error_category: parse_aborted`.
45 /// `None` (the default) means "this is a normal post-parse tool
46 /// call, no candidate phase was active" so the on-disk shape
47 /// stays compatible with replays recorded before this field
48 /// existed.
49 #[serde(default, skip_serializing_if = "Option::is_none")]
50 parsing: Option<bool>,
51 /// Mutation-session audit context active when the tool was
52 /// dispatched (see harn#699). Hosts use it to group every tool
53 /// emission belonging to the same write-capable session.
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 audit: Option<MutationSessionRecord>,
56 },
57 ToolCallUpdate {
58 session_id: String,
59 tool_call_id: String,
60 tool_name: String,
61 status: ToolCallStatus,
62 raw_output: Option<serde_json::Value>,
63 error: Option<String>,
64 /// Wall-clock milliseconds from the parse-to-execution boundary
65 /// to the terminal `Completed`/`Failed` update. Includes the
66 /// time spent in any wrapping orchestration logic (loop checks,
67 /// post-tool hooks, microcompaction). Populated only on the
68 /// terminal update — `None` on intermediate `Pending` /
69 /// `InProgress` updates so clients can ignore the field until
70 /// it shows up.
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 duration_ms: Option<u64>,
73 /// Milliseconds spent in the actual host/builtin/MCP dispatch
74 /// call only (the inner `dispatch_tool_execution` window).
75 /// Populated only on the terminal update; `None` otherwise.
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 execution_duration_ms: Option<u64>,
78 /// Structured classification of the failure (when `status` is
79 /// `Failed`). Paired with `error` so clients can render each
80 /// category distinctly without parsing free-form strings. Always
81 /// `None` for non-Failed updates and serialized as
82 /// `errorCategory` in the ACP wire format.
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 error_category: Option<ToolCallErrorCategory>,
85 /// Where the tool actually ran. `None` only for events emitted
86 /// from sites that pre-date the dispatch decision (e.g. the
87 /// pending → in-progress transition the loop emits before the
88 /// dispatcher picks a backend).
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 executor: Option<ToolExecutor>,
91 /// Companion to `ToolCall.parsing` (harn#692). The streaming
92 /// candidate detector emits the *terminal* candidate event as a
93 /// `ToolCallUpdate` with `parsing: Some(false)` to retract the
94 /// in-flight `parsing: true` chip — either by promoting the
95 /// candidate (`status: pending`, populated `raw_output: None`,
96 /// `error: None`) or aborting it (`status: failed`,
97 /// `error_category: parse_aborted`). `None` means this update is
98 /// not part of a candidate-phase transition.
99 #[serde(default, skip_serializing_if = "Option::is_none")]
100 parsing: Option<bool>,
101 /// Best-effort partial parse of the streamed tool-call arguments.
102 /// Populated by the SSE transport on `Pending` updates as the
103 /// model streams `input_json_delta` (Anthropic) or
104 /// `tool_calls[].function.arguments` deltas (OpenAI). `None` on
105 /// terminal updates and on emissions from non-streaming paths
106 /// (#693). When the partial bytes are not yet parseable as JSON
107 /// the transport falls back to `raw_input_partial`.
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 raw_input: Option<serde_json::Value>,
110 /// Raw concatenated bytes of the streamed tool-call arguments
111 /// when a permissive parse failed (#693). Mutually exclusive
112 /// with `raw_input`: clients render whichever is present.
113 #[serde(default, skip_serializing_if = "Option::is_none")]
114 raw_input_partial: Option<String>,
115 /// Mutation-session audit context for the tool call. Carries the
116 /// same payload as on the paired `ToolCall` event so a host
117 /// processing a single update doesn't have to correlate against
118 /// the prior pending event.
119 #[serde(default, skip_serializing_if = "Option::is_none")]
120 audit: Option<MutationSessionRecord>,
121 },
122 Plan {
123 session_id: String,
124 plan: serde_json::Value,
125 },
126 ProgressReported {
127 session_id: String,
128 message: Option<String>,
129 entries: serde_json::Value,
130 replace: bool,
131 metadata: serde_json::Value,
132 },
133 /// Emitted when the Burin compass observes a freeform edit and either
134 /// suggests a structural primitive, rewrites the tool call, or falls
135 /// back because rewrite mode could not prove equivalence.
136 CompassRoutingDecision {
137 session_id: String,
138 tool_call_id: String,
139 mode: String,
140 action: String,
141 persona: String,
142 original_tool: String,
143 routed_tool: String,
144 target_tool: String,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 path: Option<String>,
147 },
148 /// Emitted after an agent scratchpad reorganization attempt. The
149 /// scratchpad body itself stays in session state; this event carries
150 /// status and count/error metadata so live UIs and eval harnesses can
151 /// audit whether reorganization helped or damaged the working set.
152 AgentScratchpadReorganization {
153 session_id: String,
154 iteration: usize,
155 status: String,
156 details: serde_json::Value,
157 },
158 /// A renderable, declarative artifact spec emitted by an agent. Harn
159 /// validates the payload and transports it; host surfaces own rendering
160 /// and may fall back to the plain-text representation.
161 Artifact {
162 session_id: String,
163 artifact_id: String,
164 kind: String,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
166 title: Option<String>,
167 mime_type: String,
168 spec: serde_json::Value,
169 fallback: String,
170 size_bytes: u64,
171 provenance: serde_json::Value,
172 metadata: serde_json::Value,
173 },
174 /// Fires at the top of every model round-trip inside an
175 /// `agent_loop` invocation. Maps to the `iteration_start` steering
176 /// seam. Not the same as ACP's outer `prompt_turn` boundary; an
177 /// `agent_turn`/`prompt_turn` cycle contains many of these.
178 IterationStart {
179 session_id: String,
180 iteration: usize,
181 /// Configured provider for the impending LLM call. Empty when the
182 /// caller defers provider selection to the routing layer.
183 /// Surfaces here so observers can show "about to call X/Y" before
184 /// the call returns — previously this only landed in the
185 /// transcript after the response, leaving live pulse-check
186 /// consumers without a model attribution for in-flight iterations.
187 #[serde(default, skip_serializing_if = "String::is_empty")]
188 provider: String,
189 /// Configured model id. Same semantics as `provider`.
190 #[serde(default, skip_serializing_if = "String::is_empty")]
191 model: String,
192 },
193 /// Fires at the bottom of every model round-trip, after tool
194 /// dispatch (or after the dispatch was skipped). Sibling of
195 /// `IterationStart`.
196 IterationEnd {
197 session_id: String,
198 iteration: usize,
199 /// Free-form dict carrying the post-call snapshot. Stable keys
200 /// emitted by the agent loop: `tool_count`, `text`, plus the
201 /// LLM-result projection — `provider`, `model`, `response_ms`,
202 /// `input_tokens`, `output_tokens`, `thinking_chars`. Hosts that
203 /// surface latency/cost panes key off these without re-parsing
204 /// the transcript JSONL.
205 iteration_info: serde_json::Value,
206 },
207 /// Emitted when a first-class agent session is explicitly closed by
208 /// `agent_session_close`. This gives event-log consumers a typed
209 /// terminal marker even when no final model turn runs.
210 SessionClosed {
211 session_id: String,
212 reason: String,
213 status: String,
214 metadata: serde_json::Value,
215 },
216 /// Emitted when `agent_session_reanchor` swaps the primary workspace
217 /// anchor (#2218). Hosts use this to drive cross-project handoff UX.
218 /// Carries the previous and current anchors so consumers can diff
219 /// without re-fetching session state.
220 AnchorChanged {
221 session_id: String,
222 previous: Option<serde_json::Value>,
223 current: serde_json::Value,
224 carry_transcript: bool,
225 compacted: bool,
226 reason: Option<String>,
227 },
228 JudgeDecision {
229 session_id: String,
230 iteration: usize,
231 verdict: String,
232 reasoning: String,
233 next_step: Option<String>,
234 judge_duration_ms: u64,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
236 trigger: Option<String>,
237 },
238 /// Per-step critique decision emitted by `agent_step_judge`.
239 /// Sibling of [`JudgeDecision`] but fired BEFORE tool dispatch on
240 /// every assistant turn (when configured), not just at completion.
241 /// `on_veto` carries the configured remediation shape
242 /// (`"replace"` or `"retain"`); `cost_usd` is best-effort from the
243 /// stdlib economics estimator and may be 0 when pricing is unknown.
244 /// `skipped` marks configured short-circuits that did not call the
245 /// judge model.
246 StepJudgeDecision {
247 session_id: String,
248 iteration: usize,
249 verdict: String,
250 reasoning: String,
251 critique: String,
252 confidence: f64,
253 judge_duration_ms: u64,
254 vetoed: bool,
255 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
256 skipped: bool,
257 #[serde(default, skip_serializing_if = "Option::is_none")]
258 reason: Option<String>,
259 on_veto: String,
260 input_tokens: u64,
261 output_tokens: u64,
262 cost_usd: f64,
263 provider: String,
264 model: String,
265 },
266 /// Deterministic pre-dispatch critique emitted by the structural
267 /// validator middleware. Fires before any LLM-backed judge so hosts
268 /// can distinguish "$0 structural retry" from semantic critique.
269 StructuralValidatorDecision {
270 session_id: String,
271 iteration: usize,
272 rule: String,
273 diagnostic: String,
274 recommended_action: String,
275 vetoed: bool,
276 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
277 skipped: bool,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 reason: Option<String>,
280 on_failure: String,
281 attempts: usize,
282 max_attempts: usize,
283 },
284 ScopeClassifierVerdict {
285 session_id: String,
286 iteration: usize,
287 label: String,
288 original_label: String,
289 confidence: f64,
290 confidence_threshold: f64,
291 evidence: String,
292 skip_main_turn: bool,
293 #[serde(default, skip_serializing_if = "Option::is_none")]
294 classifier_kind: Option<String>,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 model: Option<String>,
297 #[serde(default, skip_serializing_if = "Option::is_none")]
298 error: Option<String>,
299 },
300 TypedCheckpoint {
301 session_id: String,
302 checkpoint: serde_json::Value,
303 },
304 FeedbackInjected {
305 session_id: String,
306 kind: String,
307 content: String,
308 },
309 /// Emitted when the agent loop exhausts `max_iterations` without any
310 /// explicit break condition firing. Distinct from a natural "done" or
311 /// a "stuck" nudge-exhaustion: this is strictly a budget cap.
312 BudgetExhausted {
313 session_id: String,
314 max_iterations: usize,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
316 kind: Option<String>,
317 #[serde(default, skip_serializing_if = "Option::is_none")]
318 cost_usd: Option<f64>,
319 #[serde(default, skip_serializing_if = "Option::is_none")]
320 wall_clock_ms: Option<u64>,
321 },
322 /// Emitted when a loop-level budget circuit breaker trips after N
323 /// consecutive retryable failures. `paused_for_ms` is the mock-time-aware
324 /// backoff already honored before the terminal budget event.
325 BudgetCircuitBreaker {
326 session_id: String,
327 kind: String,
328 consecutive_count: usize,
329 paused_for_ms: u64,
330 },
331 /// Emitted when the loop breaks because consecutive text-only turns
332 /// hit `max_nudges`. Parity with `BudgetExhausted` / `IterationEnd` for
333 /// hosts that key off agent-terminal events.
334 LoopStuck {
335 session_id: String,
336 max_nudges: usize,
337 last_iteration: usize,
338 tail_excerpt: String,
339 },
340 /// Emitted when the daemon idle-wait loop trips its watchdog because
341 /// every configured wake source returned `None` for N consecutive
342 /// attempts. Exists so a broken daemon doesn't hang the session
343 /// silently.
344 DaemonWatchdogTripped {
345 session_id: String,
346 attempts: usize,
347 elapsed_ms: u64,
348 },
349 /// Emitted when a skill is activated. Carries the match reason so
350 /// replayers can reconstruct *why* a given skill took effect at
351 /// this iteration.
352 SkillActivated {
353 session_id: String,
354 skill_name: String,
355 iteration: usize,
356 reason: String,
357 },
358 /// Emitted when a previously-active skill is deactivated because
359 /// the reassess phase no longer matches it.
360 SkillDeactivated {
361 session_id: String,
362 skill_name: String,
363 iteration: usize,
364 },
365 /// Emitted once per activation when the skill's `allowed_tools` filter
366 /// narrows the effective tool surface exposed to the model.
367 SkillScopeTools {
368 session_id: String,
369 skill_name: String,
370 allowed_tools: Vec<String>,
371 },
372 /// Emitted when the agent loop ratchets the model-visible tool
373 /// surface narrower after observing recent tool-call usage. Unlike
374 /// `SkillScopeTools`, this is session-local and can only remove
375 /// tools from the currently-effective surface.
376 SkillNarrow {
377 session_id: String,
378 reason: String,
379 removed_tools: Vec<String>,
380 remaining_tools: Vec<String>,
381 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
382 policy: serde_json::Value,
383 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
384 removed_tool_details: serde_json::Value,
385 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
386 kept_tool_details: serde_json::Value,
387 },
388 /// Emitted when a `tool_search` query is issued by the model. Carries
389 /// the raw query args, the configured strategy, and a `mode` tag
390 /// distinguishing the client-executed fallback (`"client"`) from
391 /// provider-native paths (`"anthropic"` / `"openai"`). Mirrors the
392 /// transcript event shape so hosts can render a search-in-progress
393 /// chip in real time — the replay path walks the transcript after
394 /// the turn, which is too late for live UX.
395 ToolSearchQuery {
396 session_id: String,
397 tool_use_id: String,
398 name: String,
399 query: serde_json::Value,
400 strategy: String,
401 mode: String,
402 },
403 /// Emitted when `tool_search` resolves — carries the list of tool
404 /// names newly promoted into the model's effective surface for the
405 /// next turn. Pair-emitted with `ToolSearchQuery` on every search.
406 ToolSearchResult {
407 session_id: String,
408 tool_use_id: String,
409 promoted: Vec<String>,
410 strategy: String,
411 mode: String,
412 },
413 TranscriptCompacted {
414 session_id: String,
415 mode: String,
416 reason: String,
417 strategy: String,
418 archived_messages: usize,
419 estimated_tokens_before: usize,
420 estimated_tokens_after: usize,
421 snapshot_asset_id: Option<String>,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 instruction_mode: Option<String>,
424 #[serde(default, skip_serializing_if = "Option::is_none")]
425 instruction_source: Option<String>,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
427 compaction_policy: Option<serde_json::Value>,
428 },
429 /// Emitted whenever `transcript_project` derives a model-visible
430 /// prefix from the immutable raw transcript. Hosts that render a
431 /// side-by-side raw/projected view subscribe to this — the typed
432 /// payload mirrors the metadata on the persisted
433 /// `transcript.projection` transcript event so clients don't have to
434 /// re-parse the transcript to sync UI state.
435 TranscriptProjected {
436 session_id: String,
437 policy: String,
438 reason: String,
439 prefix_hash: String,
440 kept_count: usize,
441 dropped_count: usize,
442 provider_safety_blocked: bool,
443 #[serde(default, skip_serializing_if = "is_zero_usize")]
444 redacted_count: usize,
445 #[serde(default, skip_serializing_if = "is_zero_usize")]
446 reclaimed_tokens: usize,
447 #[serde(default, skip_serializing_if = "Vec::is_empty")]
448 roots_consulted: Vec<String>,
449 #[serde(default, skip_serializing_if = "Vec::is_empty")]
450 redaction_pointers: Vec<serde_json::Value>,
451 },
452 /// Emitted when a pending `system_reminder` is rendered into the
453 /// next provider request. ACP clients show these in a reminder lane
454 /// instead of mixing them into assistant text chunks.
455 ReminderEmitted {
456 session_id: String,
457 reminder_id: String,
458 tags: Vec<String>,
459 body: String,
460 role_hint: String,
461 rendered_role: String,
462 source: String,
463 ttl_turns: Option<i64>,
464 },
465 Handoff {
466 session_id: String,
467 artifact_id: String,
468 handoff: Box<HandoffArtifact>,
469 },
470 FsWatch {
471 session_id: String,
472 subscription_id: String,
473 events: Vec<FsWatchEvent>,
474 },
475 /// Emitted when hostlib staged filesystem state changes for a session.
476 /// The ACP adapter maps this to the existing `progress` extension so
477 /// clients can update rollup-diff badges without waiting for a prompt
478 /// turn boundary.
479 StagedWritesPending {
480 session_id: String,
481 pending_count: usize,
482 total_bytes: u64,
483 },
484 /// Per-call outcome of `hostlib_fs_safe_text_patch`. Hosts subscribe to
485 /// this to roll up stale-base / hunk-conflict rates and average
486 /// hunks-per-patch without scraping result dicts out of pipeline logs.
487 /// Fired from both the staged-overlay and direct-disk code paths so
488 /// the rollup is comprehensive.
489 SafeTextPatchResult {
490 session_id: String,
491 path: String,
492 result: String,
493 hunks_count: usize,
494 bytes_written: u64,
495 #[serde(default, skip_serializing_if = "Option::is_none")]
496 failed_hunk_index: Option<usize>,
497 },
498 /// ACP control-plane arbitration outcome. Emitted for accepted,
499 /// idempotent, and rejected controls so replay/audit consumers can show
500 /// who acted and why a late or unauthorized action lost.
501 ControlOutcome {
502 session_id: String,
503 control_id: String,
504 method: String,
505 outcome: String,
506 status: String,
507 actor: serde_json::Value,
508 target: serde_json::Value,
509 #[serde(default, skip_serializing_if = "Option::is_none")]
510 reason: Option<String>,
511 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
512 metadata: serde_json::Value,
513 },
514 /// Lifecycle update for a delegated/background worker. Carries the
515 /// canonical typed `event` variant alongside the worker's current
516 /// `status` string and the structured `metadata` payload that
517 /// `worker_bridge_metadata` builds (task, mode, timing, child
518 /// run/snapshot paths, audit-session, etc.). The `audit` field is
519 /// the same `MutationSessionRecord` JSON serialization carried on
520 /// the bridge wire so ACP/A2A consumers don't need to re-derive it.
521 ///
522 /// One-to-one with the bridge-side `worker_update` session-update
523 /// notification: ACP and A2A adapters subscribe to this variant
524 /// and translate it into their respective wire formats. The
525 /// `session_id` is the parent agent session that owns the worker
526 /// (i.e. the session whose VM spawned the worker), so a single
527 /// host stays subscribed to the same sink for both message and
528 /// worker traffic.
529 WorkerUpdate {
530 session_id: String,
531 worker_id: String,
532 worker_name: String,
533 worker_task: String,
534 worker_mode: String,
535 event: WorkerEvent,
536 status: String,
537 metadata: serde_json::Value,
538 audit: Option<serde_json::Value>,
539 },
540 /// A human-in-the-loop primitive (`ask_user`, `request_approval`,
541 /// `dual_control`, `escalate`) has just suspended the script and is
542 /// waiting on a response. Hosts that bridge the VM onto a remote
543 /// transport (ACP, A2A) translate this into a "paused / awaiting
544 /// input" wire signal so the client knows the task isn't stuck —
545 /// it's blocked on the human side. Pair-emitted with `HitlResolved`
546 /// when the waitpoint completes/cancels/times out.
547 HitlRequested {
548 session_id: String,
549 request_id: String,
550 kind: String,
551 payload: serde_json::Value,
552 },
553 /// Companion to `HitlRequested`: the waitpoint has resolved (either
554 /// a response arrived, the deadline elapsed, or the request was
555 /// cancelled). `outcome` is one of `"answered"`, `"timeout"`,
556 /// `"cancelled"`. Hosts use this to flip task state back to
557 /// `working` after an `input-required` pause.
558 HitlResolved {
559 session_id: String,
560 request_id: String,
561 kind: String,
562 outcome: String,
563 },
564 /// Emitted by the agent loop's adaptive iteration budget /
565 /// `loop_control` policy when a budget extension or early stop fires.
566 /// Generic enough to cover both shapes — `action` distinguishes them.
567 /// Carries the iteration the decision applied to, the previous /
568 /// resulting iteration limit, the policy reason string, and (for
569 /// stops) the loop status.
570 LoopControlDecision {
571 session_id: String,
572 iteration: usize,
573 action: String,
574 old_limit: usize,
575 new_limit: usize,
576 reason: String,
577 status: String,
578 },
579 /// Emitted when `agent_loop` detects adjacent repeated tool calls with
580 /// identical arguments. The warning payload avoids raw arguments by
581 /// default and carries digests so hosts can correlate repeats without
582 /// exposing potentially sensitive tool inputs.
583 AgentLoopStallWarning {
584 session_id: String,
585 warning: serde_json::Value,
586 },
587 /// Emitted when a concrete provider/model pair lacks a catalog
588 /// recommendation for a capability and the runtime chooses a fallback.
589 CapabilityGap {
590 session_id: String,
591 level: String,
592 capability: String,
593 provider: String,
594 model: String,
595 fallback_tool_format: String,
596 #[serde(default, skip_serializing_if = "Option::is_none")]
597 requested_tool_format: Option<String>,
598 message: String,
599 },
600 /// Emitted when a caller explicitly forces a tool format that
601 /// differs from the capability catalog's recommendation or known
602 /// native/text parity guidance.
603 ToolFormatOverride {
604 session_id: String,
605 provider: String,
606 model: String,
607 requested_format: String,
608 recommended_format: String,
609 catalog_parity: String,
610 #[serde(default, skip_serializing_if = "Option::is_none")]
611 override_reason: Option<String>,
612 },
613 /// Emitted when a `tool_caller` middleware (see std/llm/tool_middleware)
614 /// attaches structured audit metadata to a tool call — typically a
615 /// user-facing `summary`, a `description`, an ACP-style `kind`, an MCP
616 /// `hints` block, a `consent` decision, the per-layer `layers` log, or
617 /// free-form `metadata` keys (A2A-style extension slot).
618 ///
619 /// One-to-one with the underlying tool-call: hosts can join on
620 /// `tool_call_id` to render middleware-attached chips alongside the
621 /// existing `ToolCall` / `ToolCallUpdate` stream. The `audit` payload
622 /// is intentionally free-form JSON so middleware can carry whatever
623 /// shape the harness author chooses without needing protocol-level
624 /// changes per new middleware. When present, `receipt` carries the
625 /// stable typed, privacy-preserving record hosts can persist or mirror.
626 ToolCallAudit {
627 session_id: String,
628 tool_call_id: String,
629 tool_name: String,
630 audit: serde_json::Value,
631 #[serde(default, skip_serializing_if = "Option::is_none")]
632 receipt: Option<ToolCallReceipt>,
633 },
634 /// Emitted by `std/cache::with_cache` (both the generic and LLM
635 /// forms) when a cached lookup returns a hit. Carries the
636 /// content-addressed key, the backend that served the value, and a
637 /// `metrics` block with the cost-moat receipts the persona value
638 /// ledger (harn-cloud#58) and crystallization receipts read:
639 /// `model_calls_avoided`, plus `tokens_saved` / `latency_saved_ms`
640 /// when the cached envelope carried `usage` / `latency_ms`.
641 CacheHit {
642 session_id: String,
643 key: String,
644 backend: String,
645 namespace: String,
646 payload: serde_json::Value,
647 },
648 /// Paired with `CacheHit`. Emitted on the miss path when the
649 /// fresh result is stored. `payload.metrics.compute_ms` carries
650 /// the wall-clock cost of the underlying computation, which
651 /// callers can feed back as `estimate.latency_saved_ms` on the
652 /// next hit.
653 CacheMiss {
654 session_id: String,
655 key: String,
656 backend: String,
657 namespace: String,
658 payload: serde_json::Value,
659 },
660 /// A language-neutral tool-composition snippet has started. The envelope
661 /// identifies the snippet and binding manifest hashes plus the side-effect
662 /// ceiling requested for the whole parent run.
663 CompositionStart {
664 session_id: String,
665 run: CompositionRunEnvelope,
666 },
667 /// A composition snippet is dispatching a child binding call. The child
668 /// remains visible as its own operation with annotations and policy context
669 /// instead of being hidden inside the parent composition blob.
670 CompositionChildCall {
671 session_id: String,
672 call: CompositionChildCall,
673 },
674 /// A child binding operation emitted a status/result update.
675 CompositionChildResult {
676 session_id: String,
677 result: CompositionChildResult,
678 },
679 /// A composition run finished successfully and carries stdout/stderr,
680 /// artifacts, and the structured result in the terminal envelope.
681 CompositionFinish {
682 session_id: String,
683 run: CompositionRunEnvelope,
684 },
685 /// A composition run failed before producing a successful terminal result.
686 /// The terminal envelope carries the failure category and optional error.
687 CompositionError {
688 session_id: String,
689 run: CompositionRunEnvelope,
690 },
691 /// Emitted once per `__agent_loop_checkpoint(...)` pass. The single
692 /// named seam through which the agent loop drains queued bridge
693 /// injections and inbox feedback. Hosts use it to debug "did the
694 /// loop check for steering at the expected boundary" without having
695 /// to grep the loop body for inline drain calls.
696 ///
697 /// `kind` is one of the documented seam names: `iteration_start`,
698 /// `pre_tool_dispatch`, `post_tool_dispatch`, `iteration_end`,
699 /// `pre_compact`, `post_compact`, `daemon_idle_pre`,
700 /// `daemon_idle_post`, `loop_exit`. `delivered` is the count of
701 /// bridge injections drained at this seam (inbox drains are
702 /// reported separately under `inbox_delivered`). `dispatch_skipped`
703 /// is true only when an `interrupt_immediate` injection arrived at
704 /// `pre_tool_dispatch` and the pending tool batch was skipped.
705 LoopCheckpoint {
706 session_id: String,
707 iteration: usize,
708 kind: String,
709 delivered: usize,
710 #[serde(default, skip_serializing_if = "is_zero_usize")]
711 inbox_delivered: usize,
712 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
713 dispatch_skipped: bool,
714 },
715 /// Surfaced when Harn is acting as an MCP **client** and a peer
716 /// server sends a server-to-client message during an agent session:
717 /// a `notifications/progress` / `notifications/message` /
718 /// `notifications/*/list_changed` notification, or an inbound
719 /// `elicitation/create` / `sampling/createMessage` request.
720 ///
721 /// Emitted alongside (not in place of) the existing agent-inbox
722 /// relay so a thin ACP client can render a live progress bar, log
723 /// line, elicitation prompt, or sampling affordance without parsing
724 /// the inbox transcript. `direction` is `"notification"` for
725 /// fire-and-forget server notifications and `"request"` for inbound
726 /// requests that still resolve through the existing client-role
727 /// dispatch path (this event does not change that response). `method`
728 /// is the raw MCP JSON-RPC method; `params` is its untouched payload.
729 McpNotification {
730 session_id: String,
731 server: String,
732 method: String,
733 direction: String,
734 params: serde_json::Value,
735 },
736 /// Surfaced when the effective MCP catalog changes — either because a
737 /// server emitted a `notifications/tools/list_changed` (or the
738 /// resource/prompt equivalents), or because the persisted enable/disable
739 /// allowlist was edited. A thin ACP client (the burin-code TUI / GUI)
740 /// treats this as a cue to re-fetch the catalog (e.g. via the
741 /// `mcp/catalog` request) and re-render its toggle UI, rather than
742 /// reconciling any local state. `server` is the server whose list
743 /// changed, or `None` when the change is allowlist-wide. `reason` is a
744 /// short tag (`"list_changed"` or `"allowlist_updated"`).
745 McpCatalogChanged {
746 session_id: String,
747 #[serde(default, skip_serializing_if = "Option::is_none")]
748 server: Option<String>,
749 reason: String,
750 },
751 /// Surfaced when an MCP server harn is acting as a client for answers a
752 /// request with `401 Unauthorized` mid-session, meaning its OAuth token is
753 /// missing or expired. This is a cue for a thin ACP client (the burin-code
754 /// TUI / GUI) to start an authorization: call `mcp/authorize` to mint a
755 /// browser URL, open it, and forward the redirect's `code`+`state` back via
756 /// `mcp/oauth_callback`. Token exchange and storage stay in harn. `server`
757 /// is the configured server name; `resource` is its canonical RFC 8707
758 /// resource indicator; `scope` is the `scope` parameter from the
759 /// `WWW-Authenticate` challenge, when present.
760 McpAuthRequired {
761 session_id: String,
762 server: String,
763 resource: String,
764 #[serde(default, skip_serializing_if = "Option::is_none")]
765 scope: Option<String>,
766 },
767}
768
769fn is_zero_usize(value: &usize) -> bool {
770 *value == 0
771}
772
773impl AgentEvent {
774 pub fn session_id(&self) -> &str {
775 match self {
776 Self::AgentMessageChunk { session_id, .. }
777 | Self::AgentThoughtChunk { session_id, .. }
778 | Self::UserMessage { session_id, .. }
779 | Self::ToolCall { session_id, .. }
780 | Self::ToolCallUpdate { session_id, .. }
781 | Self::Plan { session_id, .. }
782 | Self::ProgressReported { session_id, .. }
783 | Self::CompassRoutingDecision { session_id, .. }
784 | Self::AgentScratchpadReorganization { session_id, .. }
785 | Self::Artifact { session_id, .. }
786 | Self::IterationStart { session_id, .. }
787 | Self::IterationEnd { session_id, .. }
788 | Self::SessionClosed { session_id, .. }
789 | Self::AnchorChanged { session_id, .. }
790 | Self::JudgeDecision { session_id, .. }
791 | Self::StepJudgeDecision { session_id, .. }
792 | Self::StructuralValidatorDecision { session_id, .. }
793 | Self::ScopeClassifierVerdict { session_id, .. }
794 | Self::TypedCheckpoint { session_id, .. }
795 | Self::FeedbackInjected { session_id, .. }
796 | Self::BudgetExhausted { session_id, .. }
797 | Self::BudgetCircuitBreaker { session_id, .. }
798 | Self::LoopStuck { session_id, .. }
799 | Self::DaemonWatchdogTripped { session_id, .. }
800 | Self::SkillActivated { session_id, .. }
801 | Self::SkillDeactivated { session_id, .. }
802 | Self::SkillScopeTools { session_id, .. }
803 | Self::SkillNarrow { session_id, .. }
804 | Self::ToolSearchQuery { session_id, .. }
805 | Self::ToolSearchResult { session_id, .. }
806 | Self::TranscriptCompacted { session_id, .. }
807 | Self::TranscriptProjected { session_id, .. }
808 | Self::ReminderEmitted { session_id, .. }
809 | Self::Handoff { session_id, .. }
810 | Self::FsWatch { session_id, .. }
811 | Self::StagedWritesPending { session_id, .. }
812 | Self::SafeTextPatchResult { session_id, .. }
813 | Self::ControlOutcome { session_id, .. }
814 | Self::WorkerUpdate { session_id, .. }
815 | Self::HitlRequested { session_id, .. }
816 | Self::HitlResolved { session_id, .. }
817 | Self::LoopControlDecision { session_id, .. }
818 | Self::AgentLoopStallWarning { session_id, .. }
819 | Self::CapabilityGap { session_id, .. }
820 | Self::ToolFormatOverride { session_id, .. }
821 | Self::ToolCallAudit { session_id, .. }
822 | Self::CacheHit { session_id, .. }
823 | Self::CacheMiss { session_id, .. }
824 | Self::CompositionStart { session_id, .. }
825 | Self::CompositionChildCall { session_id, .. }
826 | Self::CompositionChildResult { session_id, .. }
827 | Self::CompositionFinish { session_id, .. }
828 | Self::CompositionError { session_id, .. }
829 | Self::LoopCheckpoint { session_id, .. }
830 | Self::McpNotification { session_id, .. }
831 | Self::McpCatalogChanged { session_id, .. }
832 | Self::McpAuthRequired { session_id, .. } => session_id,
833 }
834 }
835}