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