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 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 #[serde(default, skip_serializing_if = "Option::is_none")]
238 reason: Option<String>,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
240 confirm: Option<bool>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
242 converted_from: Option<String>,
243 },
244 /// Per-step critique decision emitted by `agent_step_judge`.
245 /// Sibling of [`JudgeDecision`] but fired BEFORE tool dispatch on
246 /// every assistant turn (when configured), not just at completion.
247 /// `on_veto` carries the configured remediation shape
248 /// (`"replace"` or `"retain"`); `cost_usd` is best-effort from the
249 /// stdlib economics estimator and may be 0 when pricing is unknown.
250 /// `skipped` marks configured short-circuits that did not call the
251 /// judge model.
252 StepJudgeDecision {
253 session_id: String,
254 iteration: usize,
255 verdict: String,
256 reasoning: String,
257 critique: String,
258 confidence: f64,
259 judge_duration_ms: u64,
260 vetoed: bool,
261 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
262 skipped: bool,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
264 reason: Option<String>,
265 /// True when this `verdict: "pass"` is the result of the step-judge
266 /// model itself erroring and `fail_open` swallowing the error — the
267 /// turn proceeded, but the adversarial-review surface was UNAVAILABLE
268 /// (not a genuine approval). Lets telemetry tell an inert reviewer
269 /// apart from a real pass. Mirrors `reason: "judge_unavailable"`.
270 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
271 judge_error: bool,
272 on_veto: String,
273 input_tokens: u64,
274 output_tokens: u64,
275 cost_usd: f64,
276 provider: String,
277 model: String,
278 },
279 /// Deterministic pre-dispatch critique emitted by the structural
280 /// validator middleware. Fires before any LLM-backed judge so hosts
281 /// can distinguish "$0 structural retry" from semantic critique.
282 StructuralValidatorDecision {
283 session_id: String,
284 iteration: usize,
285 rule: String,
286 diagnostic: String,
287 recommended_action: String,
288 vetoed: bool,
289 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
290 skipped: bool,
291 #[serde(default, skip_serializing_if = "Option::is_none")]
292 reason: Option<String>,
293 on_failure: String,
294 attempts: usize,
295 max_attempts: usize,
296 },
297 ScopeClassifierVerdict {
298 session_id: String,
299 iteration: usize,
300 label: String,
301 original_label: String,
302 confidence: f64,
303 confidence_threshold: f64,
304 evidence: String,
305 skip_main_turn: bool,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 classifier_kind: Option<String>,
308 #[serde(default, skip_serializing_if = "Option::is_none")]
309 model: Option<String>,
310 #[serde(default, skip_serializing_if = "Option::is_none")]
311 error: Option<String>,
312 },
313 InputGuardrailVerdict {
314 session_id: String,
315 iteration: usize,
316 tripwire: bool,
317 reason: String,
318 label: String,
319 confidence: f64,
320 confidence_threshold: f64,
321 #[serde(default, skip_serializing_if = "Option::is_none")]
322 classifier_kind: Option<String>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
324 model: Option<String>,
325 #[serde(default, skip_serializing_if = "Option::is_none")]
326 error: Option<String>,
327 },
328 MissingToolCallVerdict {
329 session_id: String,
330 iteration: usize,
331 action: String,
332 original_action: String,
333 tool_name: String,
334 confidence: f64,
335 confidence_threshold: f64,
336 evidence: String,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
338 language: Option<String>,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
340 classifier_kind: Option<String>,
341 #[serde(default, skip_serializing_if = "Option::is_none")]
342 model: Option<String>,
343 #[serde(default, skip_serializing_if = "Option::is_none")]
344 error: Option<String>,
345 },
346 TypedCheckpoint {
347 session_id: String,
348 checkpoint: serde_json::Value,
349 },
350 FeedbackInjected {
351 session_id: String,
352 kind: String,
353 content: String,
354 },
355 /// Emitted when the agent loop exhausts `max_iterations` without any
356 /// explicit break condition firing. Distinct from a natural "done" or
357 /// a "stuck" nudge-exhaustion: this is strictly a budget cap.
358 BudgetExhausted {
359 session_id: String,
360 max_iterations: usize,
361 #[serde(default, skip_serializing_if = "Option::is_none")]
362 kind: Option<String>,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 cost_usd: Option<f64>,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
366 wall_clock_ms: Option<u64>,
367 },
368 /// Emitted when a loop-level budget circuit breaker trips after N
369 /// consecutive retryable failures. `paused_for_ms` is the mock-time-aware
370 /// backoff already honored before the terminal budget event.
371 BudgetCircuitBreaker {
372 session_id: String,
373 kind: String,
374 consecutive_count: usize,
375 paused_for_ms: u64,
376 },
377 /// Emitted when the loop breaks because consecutive text-only turns
378 /// hit `max_nudges`. Parity with `BudgetExhausted` / `IterationEnd` for
379 /// hosts that key off agent-terminal events.
380 LoopStuck {
381 session_id: String,
382 max_nudges: usize,
383 last_iteration: usize,
384 tail_excerpt: String,
385 },
386 /// Pipeline-authored stuck/escalation signal emitted through
387 /// `agent_emit_event("loop_stuck", payload)`. The runtime-level
388 /// `LoopStuck` variant above remains the built-in max-nudge terminal event;
389 /// this variant preserves the pipeline payload so hosts can surface richer
390 /// handoff/escalation details without inventing another wire kind.
391 LoopStuckSignal {
392 session_id: String,
393 payload: serde_json::Value,
394 },
395 /// Emitted by the reserved-budget terminal-verify guard
396 /// (`agent_emit_event("reserved_terminal_verify", payload)`). The guard
397 /// holds back a small iteration reserve the main loop cannot consume; when
398 /// the loop would otherwise terminate on a budget/stuck boundary with an
399 /// unverified source write, it spends the reserve on a final verify(+repair)
400 /// instead of ending blind on a red build. The payload's `phase` field tags
401 /// the step (`grant` / `verify_passed` / `verify_failed`) so replayers and
402 /// operators can see the guard fire and its outcome. Payload-preserving like
403 /// `LoopStuckSignal` so the guard can carry richer detail without inventing
404 /// another wire kind.
405 ReservedTerminalVerify {
406 session_id: String,
407 payload: serde_json::Value,
408 },
409 /// Emitted when the daemon idle-wait loop trips its watchdog because
410 /// every configured wake source returned `None` for N consecutive
411 /// attempts. Exists so a broken daemon doesn't hang the session
412 /// silently.
413 DaemonWatchdogTripped {
414 session_id: String,
415 attempts: usize,
416 elapsed_ms: u64,
417 },
418 /// Emitted when a skill is activated. Carries the match reason so
419 /// replayers can reconstruct *why* a given skill took effect at
420 /// this iteration.
421 SkillActivated {
422 session_id: String,
423 skill_name: String,
424 iteration: usize,
425 reason: String,
426 },
427 /// Emitted when a previously-active skill is deactivated because
428 /// the reassess phase no longer matches it.
429 SkillDeactivated {
430 session_id: String,
431 skill_name: String,
432 iteration: usize,
433 },
434 /// Emitted once per activation when the skill's `allowed_tools` filter
435 /// narrows the effective tool surface exposed to the model.
436 SkillScopeTools {
437 session_id: String,
438 skill_name: String,
439 allowed_tools: Vec<String>,
440 },
441 /// Emitted when the agent loop ratchets the model-visible tool
442 /// surface narrower after observing recent tool-call usage. Unlike
443 /// `SkillScopeTools`, this is session-local and can only remove
444 /// tools from the currently-effective surface.
445 SkillNarrow {
446 session_id: String,
447 reason: String,
448 removed_tools: Vec<String>,
449 remaining_tools: Vec<String>,
450 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
451 policy: serde_json::Value,
452 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
453 removed_tool_details: serde_json::Value,
454 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
455 kept_tool_details: serde_json::Value,
456 },
457 /// Read-only stance lifecycle (std/agent/stance): `phase` is one of
458 /// `armed`, `write_access_granted`, `write_access_denied`,
459 /// `disarmed`. Arming carries the permitted tool window; the
460 /// grant/deny phases carry the escape-hatch justification and the
461 /// consent verdict so a trace viewer can explain every elevation.
462 StanceTransition {
463 session_id: String,
464 phase: String,
465 escape_tool: String,
466 #[serde(default, skip_serializing_if = "Vec::is_empty")]
467 allowed_tools: Vec<String>,
468 #[serde(default, skip_serializing_if = "String::is_empty")]
469 justification: String,
470 #[serde(default, skip_serializing_if = "String::is_empty")]
471 consent: String,
472 #[serde(default, skip_serializing_if = "String::is_empty")]
473 reason: String,
474 },
475 /// Emitted when a `tool_search` query is issued by the model. Carries
476 /// the raw query args, the configured strategy, and a `mode` tag
477 /// distinguishing the client-executed fallback (`"client"`) from
478 /// provider-native paths (`"anthropic"` / `"openai"`). Mirrors the
479 /// transcript event shape so hosts can render a search-in-progress
480 /// chip in real time — the replay path walks the transcript after
481 /// the turn, which is too late for live UX.
482 ToolSearchQuery {
483 session_id: String,
484 tool_use_id: String,
485 name: String,
486 query: serde_json::Value,
487 strategy: String,
488 mode: String,
489 },
490 /// Emitted when `tool_search` resolves — carries the list of tool
491 /// names newly promoted into the model's effective surface for the
492 /// next turn. Pair-emitted with `ToolSearchQuery` on every search.
493 ToolSearchResult {
494 session_id: String,
495 tool_use_id: String,
496 promoted: Vec<String>,
497 strategy: String,
498 mode: String,
499 },
500 TranscriptCompacted {
501 session_id: String,
502 mode: String,
503 reason: String,
504 strategy: String,
505 archived_messages: usize,
506 estimated_tokens_before: usize,
507 estimated_tokens_after: usize,
508 snapshot_asset_id: Option<String>,
509 #[serde(default, skip_serializing_if = "Option::is_none")]
510 instruction_mode: Option<String>,
511 #[serde(default, skip_serializing_if = "Option::is_none")]
512 instruction_source: Option<String>,
513 #[serde(default, skip_serializing_if = "Option::is_none")]
514 compaction_policy: Option<serde_json::Value>,
515 },
516 /// Emitted whenever `transcript_project` derives a model-visible
517 /// prefix from the immutable raw transcript. Hosts that render a
518 /// side-by-side raw/projected view subscribe to this — the typed
519 /// payload mirrors the metadata on the persisted
520 /// `transcript.projection` transcript event so clients don't have to
521 /// re-parse the transcript to sync UI state.
522 TranscriptProjected {
523 session_id: String,
524 policy: String,
525 reason: String,
526 prefix_hash: String,
527 kept_count: usize,
528 dropped_count: usize,
529 provider_safety_blocked: bool,
530 #[serde(default, skip_serializing_if = "is_zero_usize")]
531 redacted_count: usize,
532 #[serde(default, skip_serializing_if = "is_zero_usize")]
533 reclaimed_tokens: usize,
534 #[serde(default, skip_serializing_if = "Vec::is_empty")]
535 roots_consulted: Vec<String>,
536 #[serde(default, skip_serializing_if = "Vec::is_empty")]
537 redaction_pointers: Vec<serde_json::Value>,
538 },
539 /// Emitted when a pending `system_reminder` is rendered into the
540 /// next provider request. ACP clients show these in a reminder lane
541 /// instead of mixing them into assistant text chunks.
542 ReminderEmitted {
543 session_id: String,
544 reminder_id: String,
545 tags: Vec<String>,
546 body: String,
547 role_hint: String,
548 rendered_role: String,
549 source: String,
550 ttl_turns: Option<i64>,
551 },
552 Handoff {
553 session_id: String,
554 artifact_id: String,
555 handoff: Box<HandoffArtifact>,
556 },
557 FsWatch {
558 session_id: String,
559 subscription_id: String,
560 events: Vec<FsWatchEvent>,
561 },
562 /// Emitted when hostlib staged filesystem state changes for a session.
563 /// The ACP adapter maps this to the existing `progress` extension so
564 /// clients can update rollup-diff badges without waiting for a prompt
565 /// turn boundary.
566 StagedWritesPending {
567 session_id: String,
568 pending_count: usize,
569 total_bytes: u64,
570 },
571 /// Per-call outcome of `hostlib_fs_safe_text_patch`. Hosts subscribe to
572 /// this to roll up stale-base / hunk-conflict rates and average
573 /// hunks-per-patch without scraping result dicts out of pipeline logs.
574 /// Fired from both the staged-overlay and direct-disk code paths so
575 /// the rollup is comprehensive.
576 SafeTextPatchResult {
577 session_id: String,
578 path: String,
579 result: String,
580 hunks_count: usize,
581 bytes_written: u64,
582 #[serde(default, skip_serializing_if = "Option::is_none")]
583 failed_hunk_index: Option<usize>,
584 },
585 /// ACP control-plane arbitration outcome. Emitted for accepted,
586 /// idempotent, and rejected controls so replay/audit consumers can show
587 /// who acted and why a late or unauthorized action lost.
588 ControlOutcome {
589 session_id: String,
590 control_id: String,
591 method: String,
592 outcome: String,
593 status: String,
594 actor: serde_json::Value,
595 target: serde_json::Value,
596 #[serde(default, skip_serializing_if = "Option::is_none")]
597 reason: Option<String>,
598 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
599 metadata: serde_json::Value,
600 },
601 /// Lifecycle update for a delegated/background worker. Carries the
602 /// canonical typed `event` variant alongside the worker's current
603 /// `status` string and the structured `metadata` payload that
604 /// `worker_bridge_metadata` builds (task, mode, timing, child
605 /// run/snapshot paths, audit-session, etc.). The `audit` field is
606 /// the same `MutationSessionRecord` JSON serialization carried on
607 /// the bridge wire so ACP/A2A consumers don't need to re-derive it.
608 ///
609 /// One-to-one with the bridge-side `worker_update` session-update
610 /// notification: ACP and A2A adapters subscribe to this variant
611 /// and translate it into their respective wire formats. The
612 /// `session_id` is the parent agent session that owns the worker
613 /// (i.e. the session whose VM spawned the worker), so a single
614 /// host stays subscribed to the same sink for both message and
615 /// worker traffic.
616 WorkerUpdate {
617 session_id: String,
618 worker_id: String,
619 worker_name: String,
620 worker_task: String,
621 worker_mode: String,
622 event: WorkerEvent,
623 status: String,
624 metadata: serde_json::Value,
625 audit: Option<serde_json::Value>,
626 },
627 /// A human-in-the-loop primitive (`ask_user`, `request_approval`,
628 /// `dual_control`, `escalate`) has just suspended the script and is
629 /// waiting on a response. Hosts that bridge the VM onto a remote
630 /// transport (ACP, A2A) translate this into a "paused / awaiting
631 /// input" wire signal so the client knows the task isn't stuck —
632 /// it's blocked on the human side. Pair-emitted with `HitlResolved`
633 /// when the waitpoint completes/cancels/times out.
634 HitlRequested {
635 session_id: String,
636 request_id: String,
637 kind: String,
638 payload: serde_json::Value,
639 },
640 /// Companion to `HitlRequested`: the waitpoint has resolved (either
641 /// a response arrived, the deadline elapsed, or the request was
642 /// cancelled). `outcome` is one of `"answered"`, `"timeout"`,
643 /// `"cancelled"`. Hosts use this to flip task state back to
644 /// `working` after an `input-required` pause.
645 HitlResolved {
646 session_id: String,
647 request_id: String,
648 kind: String,
649 outcome: String,
650 },
651 /// Emitted by the agent loop's adaptive iteration budget /
652 /// `loop_control` policy when a budget extension or early stop fires.
653 /// Generic enough to cover both shapes — `action` distinguishes them.
654 /// Carries the iteration the decision applied to, the previous /
655 /// resulting iteration limit, the policy reason string, and (for
656 /// stops) the loop status.
657 LoopControlDecision {
658 session_id: String,
659 iteration: usize,
660 action: String,
661 old_limit: usize,
662 new_limit: usize,
663 reason: String,
664 status: String,
665 },
666 /// Emitted when `agent_loop` detects adjacent repeated tool calls with
667 /// identical arguments. The warning payload avoids raw arguments by
668 /// default and carries digests so hosts can correlate repeats without
669 /// exposing potentially sensitive tool inputs.
670 AgentLoopStallWarning {
671 session_id: String,
672 warning: serde_json::Value,
673 },
674 /// Emitted when a concrete provider/model pair lacks a catalog
675 /// recommendation for a capability and the runtime chooses a fallback.
676 CapabilityGap {
677 session_id: String,
678 level: String,
679 capability: String,
680 provider: String,
681 model: String,
682 fallback_tool_format: String,
683 #[serde(default, skip_serializing_if = "Option::is_none")]
684 requested_tool_format: Option<String>,
685 message: String,
686 },
687 /// Emitted when a caller explicitly forces a tool format that
688 /// differs from the capability catalog's recommendation or known
689 /// native/text parity guidance.
690 ToolFormatOverride {
691 session_id: String,
692 provider: String,
693 model: String,
694 requested_format: String,
695 recommended_format: String,
696 catalog_parity: String,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
698 override_reason: Option<String>,
699 },
700 /// Emitted when a `tool_caller` middleware (see std/llm/tool_middleware)
701 /// attaches structured audit metadata to a tool call — typically a
702 /// user-facing `summary`, a `description`, an ACP-style `kind`, an MCP
703 /// `hints` block, a `consent` decision, the per-layer `layers` log, or
704 /// free-form `metadata` keys (A2A-style extension slot).
705 ///
706 /// One-to-one with the underlying tool-call: hosts can join on
707 /// `tool_call_id` to render middleware-attached chips alongside the
708 /// existing `ToolCall` / `ToolCallUpdate` stream. The `audit` payload
709 /// is intentionally free-form JSON so middleware can carry whatever
710 /// shape the harness author chooses without needing protocol-level
711 /// changes per new middleware. When present, `receipt` carries the
712 /// stable typed, privacy-preserving record hosts can persist or mirror.
713 ToolCallAudit {
714 session_id: String,
715 tool_call_id: String,
716 tool_name: String,
717 audit: serde_json::Value,
718 #[serde(default, skip_serializing_if = "Option::is_none")]
719 receipt: Option<ToolCallReceipt>,
720 },
721 /// Emitted by `std/cache::with_cache` (both the generic and LLM
722 /// forms) when a cached lookup returns a hit. Carries the
723 /// content-addressed key, the backend that served the value, and a
724 /// `metrics` block with the cost-moat receipts the persona value
725 /// ledger (a cloud platform) and crystallization receipts read:
726 /// `model_calls_avoided`, plus `tokens_saved` / `latency_saved_ms`
727 /// when the cached envelope carried `usage` / `latency_ms`.
728 CacheHit {
729 session_id: String,
730 key: String,
731 backend: String,
732 namespace: String,
733 payload: serde_json::Value,
734 },
735 /// Paired with `CacheHit`. Emitted on the miss path when the
736 /// fresh result is stored. `payload.metrics.compute_ms` carries
737 /// the wall-clock cost of the underlying computation, which
738 /// callers can feed back as `estimate.latency_saved_ms` on the
739 /// next hit.
740 CacheMiss {
741 session_id: String,
742 key: String,
743 backend: String,
744 namespace: String,
745 payload: serde_json::Value,
746 },
747 /// A language-neutral tool-composition snippet has started. The envelope
748 /// identifies the snippet and binding manifest hashes plus the side-effect
749 /// ceiling requested for the whole parent run.
750 CompositionStart {
751 session_id: String,
752 run: CompositionRunEnvelope,
753 },
754 /// A composition snippet is dispatching a child binding call. The child
755 /// remains visible as its own operation with annotations and policy context
756 /// instead of being hidden inside the parent composition blob.
757 CompositionChildCall {
758 session_id: String,
759 call: CompositionChildCall,
760 },
761 /// A child binding operation emitted a status/result update.
762 CompositionChildResult {
763 session_id: String,
764 result: CompositionChildResult,
765 },
766 /// A composition run finished successfully and carries stdout/stderr,
767 /// artifacts, and the structured result in the terminal envelope.
768 CompositionFinish {
769 session_id: String,
770 run: CompositionRunEnvelope,
771 },
772 /// A composition run failed before producing a successful terminal result.
773 /// The terminal envelope carries the failure category and optional error.
774 CompositionError {
775 session_id: String,
776 run: CompositionRunEnvelope,
777 },
778 /// Emitted once per `__agent_loop_checkpoint(...)` pass. The single
779 /// named seam through which the agent loop drains queued bridge
780 /// injections and inbox feedback. Hosts use it to debug "did the
781 /// loop check for steering at the expected boundary" without having
782 /// to grep the loop body for inline drain calls.
783 ///
784 /// `kind` is one of the documented seam names: `iteration_start`,
785 /// `pre_tool_dispatch`, `post_tool_dispatch`, `iteration_end`,
786 /// `pre_compact`, `post_compact`, `daemon_idle_pre`,
787 /// `daemon_idle_post`, `loop_exit`. `delivered` is the count of
788 /// bridge injections drained at this seam (inbox drains are
789 /// reported separately under `inbox_delivered`). `dispatch_skipped`
790 /// is true only when an `interrupt_immediate` injection arrived at
791 /// `pre_tool_dispatch` and the pending tool batch was skipped.
792 LoopCheckpoint {
793 session_id: String,
794 iteration: usize,
795 kind: String,
796 delivered: usize,
797 #[serde(default, skip_serializing_if = "is_zero_usize")]
798 inbox_delivered: usize,
799 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
800 dispatch_skipped: bool,
801 },
802 /// Surfaced when Harn is acting as an MCP **client** and a peer
803 /// server sends a server-to-client message during an agent session:
804 /// a `notifications/progress` / `notifications/message` /
805 /// `notifications/*/list_changed` notification, or an inbound
806 /// `elicitation/create` / `sampling/createMessage` request.
807 ///
808 /// Emitted alongside (not in place of) the existing agent-inbox
809 /// relay so a thin ACP client can render a live progress bar, log
810 /// line, elicitation prompt, or sampling affordance without parsing
811 /// the inbox transcript. `direction` is `"notification"` for
812 /// fire-and-forget server notifications and `"request"` for inbound
813 /// requests that still resolve through the existing client-role
814 /// dispatch path (this event does not change that response). `method`
815 /// is the raw MCP JSON-RPC method; `params` is its untouched payload.
816 McpNotification {
817 session_id: String,
818 server: String,
819 method: String,
820 direction: String,
821 params: serde_json::Value,
822 },
823 /// Surfaced when the effective MCP catalog changes — either because a
824 /// server emitted a `notifications/tools/list_changed` (or the
825 /// resource/prompt equivalents), or because the persisted enable/disable
826 /// allowlist was edited. A thin ACP client (an IDE host's TUI / GUI)
827 /// treats this as a cue to re-fetch the catalog (e.g. via the
828 /// `mcp/catalog` request) and re-render its toggle UI, rather than
829 /// reconciling any local state. `server` is the server whose list
830 /// changed, or `None` when the change is allowlist-wide. `reason` is a
831 /// short tag (`"list_changed"` or `"allowlist_updated"`).
832 McpCatalogChanged {
833 session_id: String,
834 #[serde(default, skip_serializing_if = "Option::is_none")]
835 server: Option<String>,
836 reason: String,
837 },
838 /// Surfaced when an MCP server harn is acting as a client for answers a
839 /// request with `401 Unauthorized` mid-session, meaning its OAuth token is
840 /// missing or expired. This is a cue for a thin ACP client (an IDE host's
841 /// TUI / GUI) to start an authorization: call `mcp/authorize` to mint a
842 /// browser URL, open it, and forward the redirect's `code`+`state` back via
843 /// `mcp/oauth_callback`. Token exchange and storage stay in harn. `server`
844 /// is the configured server name; `resource` is its canonical RFC 8707
845 /// resource indicator; `scope` is the `scope` parameter from the
846 /// `WWW-Authenticate` challenge, when present.
847 McpAuthRequired {
848 session_id: String,
849 server: String,
850 resource: String,
851 #[serde(default, skip_serializing_if = "Option::is_none")]
852 scope: Option<String>,
853 },
854}
855
856fn is_zero_usize(value: &usize) -> bool {
857 *value == 0
858}
859
860impl AgentEvent {
861 pub fn session_id(&self) -> &str {
862 match self {
863 Self::AgentMessageChunk { session_id, .. }
864 | Self::AgentThoughtChunk { session_id, .. }
865 | Self::UserMessage { session_id, .. }
866 | Self::ToolCall { session_id, .. }
867 | Self::ToolCallUpdate { session_id, .. }
868 | Self::Plan { session_id, .. }
869 | Self::ProgressReported { session_id, .. }
870 | Self::CompassRoutingDecision { session_id, .. }
871 | Self::AgentScratchpadReorganization { session_id, .. }
872 | Self::Artifact { session_id, .. }
873 | Self::IterationStart { session_id, .. }
874 | Self::IterationEnd { session_id, .. }
875 | Self::SessionClosed { session_id, .. }
876 | Self::AnchorChanged { session_id, .. }
877 | Self::JudgeDecision { session_id, .. }
878 | Self::StepJudgeDecision { session_id, .. }
879 | Self::StructuralValidatorDecision { session_id, .. }
880 | Self::ScopeClassifierVerdict { session_id, .. }
881 | Self::InputGuardrailVerdict { session_id, .. }
882 | Self::MissingToolCallVerdict { session_id, .. }
883 | Self::TypedCheckpoint { session_id, .. }
884 | Self::FeedbackInjected { session_id, .. }
885 | Self::BudgetExhausted { session_id, .. }
886 | Self::BudgetCircuitBreaker { session_id, .. }
887 | Self::LoopStuck { session_id, .. }
888 | Self::LoopStuckSignal { session_id, .. }
889 | Self::ReservedTerminalVerify { session_id, .. }
890 | Self::DaemonWatchdogTripped { session_id, .. }
891 | Self::SkillActivated { session_id, .. }
892 | Self::SkillDeactivated { session_id, .. }
893 | Self::SkillScopeTools { session_id, .. }
894 | Self::SkillNarrow { session_id, .. }
895 | Self::StanceTransition { session_id, .. }
896 | Self::ToolSearchQuery { session_id, .. }
897 | Self::ToolSearchResult { session_id, .. }
898 | Self::TranscriptCompacted { session_id, .. }
899 | Self::TranscriptProjected { session_id, .. }
900 | Self::ReminderEmitted { session_id, .. }
901 | Self::Handoff { session_id, .. }
902 | Self::FsWatch { session_id, .. }
903 | Self::StagedWritesPending { session_id, .. }
904 | Self::SafeTextPatchResult { session_id, .. }
905 | Self::ControlOutcome { session_id, .. }
906 | Self::WorkerUpdate { session_id, .. }
907 | Self::HitlRequested { session_id, .. }
908 | Self::HitlResolved { session_id, .. }
909 | Self::LoopControlDecision { session_id, .. }
910 | Self::AgentLoopStallWarning { session_id, .. }
911 | Self::CapabilityGap { session_id, .. }
912 | Self::ToolFormatOverride { session_id, .. }
913 | Self::ToolCallAudit { session_id, .. }
914 | Self::CacheHit { session_id, .. }
915 | Self::CacheMiss { session_id, .. }
916 | Self::CompositionStart { session_id, .. }
917 | Self::CompositionChildCall { session_id, .. }
918 | Self::CompositionChildResult { session_id, .. }
919 | Self::CompositionFinish { session_id, .. }
920 | Self::CompositionError { session_id, .. }
921 | Self::LoopCheckpoint { session_id, .. }
922 | Self::McpNotification { session_id, .. }
923 | Self::McpCatalogChanged { session_id, .. }
924 | Self::McpAuthRequired { session_id, .. } => session_id,
925 }
926 }
927}