Skip to main content

vtcode_core/core/agent/events/
context.rs

1//! Runtime-owned task identity and item annotation shared by both runners.
2use crate::exec::events::{
3    CommandActivity, ExecutionContext, InputOrigin, ItemContext, ThreadEvent, ThreadItemDetails,
4};
5use crate::tools::tool_intent::{ShellActivity, classify_shell_activity};
6use std::collections::VecDeque;
7
8const MAX_TRACKED_EXEC_LAUNCHES: usize = 256;
9const MAX_EXEC_ID_BYTES: usize = 256;
10
11struct ExecSessionLaunch {
12    session_id: Option<String>,
13    call_item_id: String,
14    tool_call_id: Option<String>,
15    context: Box<ItemContext>,
16}
17
18/// Validate public rationale bounds at the tool boundary, independent of schemas.
19pub fn validate_decision_input(args: serde_json::Value) -> anyhow::Result<crate::exec::events::DecisionItem> {
20    use anyhow::{Context, bail};
21    crate::tools::output_limits::max_output_tokens(&args)?;
22    let args = crate::tools::output_limits::args_without_output_metadata(&args);
23    if args.as_object().is_none_or(|o| {
24        o.keys()
25            .any(|k| !matches!(k.as_str(), "summary" | "rationale" | "alternatives" | "evidence_ids"))
26    }) {
27        bail!("invalid decision fields");
28    }
29    let d: crate::exec::events::DecisionItem = serde_json::from_value(args).context("invalid public decision")?;
30    if d.summary.trim().is_empty()
31        || d.summary.chars().count() > 240
32        || d.rationale.trim().is_empty()
33        || d.rationale.chars().count() > 1000
34        || d.alternatives.len() > 3
35        || d.evidence_ids.len() > 8
36        || d.alternatives.iter().any(|a| a.chars().count() > 1000)
37        || d.evidence_ids.iter().any(|id| id.is_empty() || id.chars().count() > 240)
38    {
39        bail!("public decision exceeds input bounds");
40    }
41    Ok(d)
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47    use serde_json::json;
48
49    fn track_launch(tracker: &mut ExecutionContextTracker, item: &str, session: &str) {
50        let args = json!({"cmd":"cargo check --locked"});
51        let mut started = super::super::tool_started_event(item.into(), "exec_command", Some(&args), Some(item));
52        tracker.annotate(&mut started);
53        let pending = tracker
54            .exec_session_output_event(item, "exec_command", &args, &json!({"session_id":session}))
55            .unwrap();
56        let ThreadEvent::ItemCompleted(completed) = pending else {
57            panic!("canonical output expected")
58        };
59        let ThreadItemDetails::ToolOutput(output) = completed.item.details else {
60            panic!("tool output expected")
61        };
62        assert_eq!(output.call_id, item);
63        assert_eq!(output.status, crate::exec::events::ToolCallStatus::InProgress);
64    }
65
66    fn background(session: &str, task: &str, exit_code: Option<i32>) -> ThreadEvent {
67        ThreadEvent::ItemCompleted(crate::exec::events::ItemCompletedEvent { item: crate::exec::events::ThreadItem {
68            id: "background".into(), context: None,
69            details: ThreadItemDetails::Harness(Box::new(serde_json::from_value(json!({
70                "event":crate::exec::events::HarnessEventKind::BackgroundSubprocessCompleted,
71                "task_id":task,"session_id":session,"exec_session_id":session,"exit_code":exit_code,"message":"observed exit",
72            })).unwrap())),
73        }})
74    }
75
76    #[test]
77    fn native_delegation_status_is_captured_only_for_its_recorded_parent() {
78        let mut tracker = ExecutionContextTracker::default();
79        let current = tracker.begin("parent", "turn", "Delegate", InputOrigin::User);
80        let output = json!({
81            "id":"agent-1", "session_id":"child", "parent_thread_id":"parent", "agent_name":"reviewer", "display_label":"Review", "description":"Check storage", "source":"builtin", "status":"running", "background":true, "depth":1, "created_at":"2026-10-03T00:00:00Z", "updated_at":"2026-10-03T00:00:01Z",
82        });
83        let event = tracker.delegation_status_event("call", "agent", &output).unwrap();
84        let ThreadEvent::ItemCompleted(completed) = event else {
85            panic!("status event expected")
86        };
87        let context = completed.item.context.unwrap();
88        assert_eq!(context.task_id, current.task_id);
89        assert_eq!(context.actor_id, "child");
90        assert_eq!(context.parent_actor_id.as_deref(), Some("parent"));
91        let ThreadItemDetails::Harness(status) = completed.item.details else {
92            panic!("harness status expected")
93        };
94        assert_eq!(status.status.as_deref(), Some("running"));
95        assert!(tracker.delegation_status_event("call", "exec_command", &output).is_none());
96        assert!(
97            tracker
98                .delegation_status_event("call", "agent", &json!({"session_id":"child"}))
99                .is_none()
100        );
101        let mut unrelated = output.clone();
102        unrelated["parent_thread_id"] = json!("unrelated");
103        assert!(tracker.delegation_status_event("call", "agent", &unrelated).is_none());
104        assert!(
105            tracker
106                .delegation_status_event("wait", "agent", &json!({"completed":true,"entry":output}))
107                .is_some()
108        );
109    }
110
111    #[test]
112    fn session_message_sends_emit_correlated_harness_status() {
113        let mut tracker = ExecutionContextTracker::default();
114        let current = tracker.begin("sess-a", "turn", "Ask peer", InputOrigin::User);
115        let output = json!({"message_id": "msg-1", "to_session": "sess-b"});
116
117        for tool in ["ask_session", "answer_session"] {
118            let event = tracker.session_message_event("call", tool, &output).unwrap();
119            let ThreadEvent::ItemCompleted(completed) = event else {
120                panic!("status event expected for {tool}")
121            };
122            assert_eq!(completed.item.id, "call:session-message");
123            let context = completed.item.context.unwrap();
124            assert_eq!(context.task_id, current.task_id);
125            assert_eq!(context.actor_id, "sess-a");
126            let ThreadItemDetails::Harness(status) = completed.item.details else {
127                panic!("harness status expected for {tool}")
128            };
129            assert_eq!(status.event, crate::exec::events::HarnessEventKind::SessionMessageSent);
130            assert_eq!(status.session_id.as_deref(), Some("sess-b"));
131            assert_eq!(status.correlation_id.as_deref(), Some("msg-1"));
132        }
133
134        // Discovery and unrelated tools produce no status event.
135        assert!(tracker.session_message_event("call", "list_sessions", &output).is_none());
136        assert!(tracker.session_message_event("call", "exec_command", &output).is_none());
137        // Malformed outputs (missing routing fields) are ignored, not panicked on.
138        assert!(
139            tracker
140                .session_message_event("call", "ask_session", &json!({"to_session": "sess-b"}))
141                .is_none()
142        );
143        assert!(
144            tracker
145                .session_message_event("call", "ask_session", &json!({"message_id": "msg-1"}))
146                .is_none()
147        );
148    }
149
150    #[test]
151    fn exec_session_mapping_is_bounded_and_isolates_actors_and_unrelated_sessions() {
152        let mut tracker = ExecutionContextTracker::default();
153        let original = tracker.begin("root", "turn-1", "Verify", InputOrigin::User);
154        for index in 0..=MAX_TRACKED_EXEC_LAUNCHES {
155            track_launch(&mut tracker, &format!("launch-{index}"), &format!("session-{index}"));
156        }
157        assert_eq!(tracker.exec_launches.len(), MAX_TRACKED_EXEC_LAUNCHES);
158        assert!(
159            tracker
160                .exec_session_output_event(
161                    "poll",
162                    "write_stdin",
163                    &json!({"session_id":"session-0","chars":""}),
164                    &json!({"exit_code":0})
165                )
166                .is_none()
167        );
168        assert!(
169            tracker
170                .exec_session_output_event(
171                    "poll",
172                    "write_stdin",
173                    &json!({"session_id":"unknown","chars":""}),
174                    &json!({"exit_code":0})
175                )
176                .is_none()
177        );
178        tracker.begin("other-actor", "turn-2", "Unrelated actor", InputOrigin::User);
179        assert!(
180            tracker
181                .exec_session_output_event(
182                    "poll",
183                    "write_stdin",
184                    &json!({"session_id":"session-1","chars":""}),
185                    &json!({"exit_code":0})
186                )
187                .is_none()
188        );
189        tracker.begin("root", "turn-3", "Another task", InputOrigin::User);
190        let completed = tracker
191            .exec_session_output_event(
192                "poll",
193                "write_stdin",
194                &json!({"session_id":"session-1","chars":""}),
195                &json!({"exit_code":0}),
196            )
197            .unwrap();
198        let ThreadEvent::ItemCompleted(completed) = completed else {
199            panic!("completion expected")
200        };
201        let context = completed.item.context.unwrap();
202        assert_eq!(context.task_id, original.task_id);
203        assert_eq!(context.turn_id, "turn-1");
204        assert_eq!(context.actor_id, "root");
205        assert_eq!(tracker.exec_launches.len(), MAX_TRACKED_EXEC_LAUNCHES - 1);
206    }
207
208    #[test]
209    fn raw_background_exit_correlates_to_the_original_verifier_only() {
210        let mut tracker = ExecutionContextTracker::default();
211        let original = tracker.begin("root", "turn", "Verify", InputOrigin::User);
212        track_launch(&mut tracker, "original-call", "session");
213        assert!(
214            tracker
215                .background_exec_output_event(&mut background("other", "exec:other", Some(0)))
216                .is_none()
217        );
218        assert!(
219            tracker
220                .background_exec_output_event(&mut background("session", "managed-task", Some(0)))
221                .is_none()
222        );
223        let pending = tracker
224            .background_exec_output_event(&mut background("session", "exec:session", None))
225            .unwrap();
226        let ThreadEvent::ItemCompleted(pending) = pending else {
227            panic!("pending output expected")
228        };
229        let ThreadItemDetails::ToolOutput(output) = pending.item.details else {
230            panic!("tool output expected")
231        };
232        assert_eq!(output.status, crate::exec::events::ToolCallStatus::InProgress);
233        tracker.begin("root", "new-turn", "Another task", InputOrigin::User);
234        let mut raw = background("session", "exec:session", Some(7));
235        tracker.annotate(&mut raw);
236        let terminal = tracker.background_exec_output_event(&mut raw).unwrap();
237        tracker.annotate(&mut raw);
238        let ThreadEvent::ItemCompleted(raw) = raw else {
239            panic!("raw completion expected")
240        };
241        assert_eq!(raw.item.context.unwrap().task_id, original.task_id);
242        assert_eq!(tracker.current.as_ref().unwrap().turn_id, "new-turn");
243        let ThreadEvent::ItemCompleted(terminal) = terminal else {
244            panic!("terminal output expected")
245        };
246        assert_eq!(terminal.item.context.unwrap().task_id, original.task_id);
247        let ThreadItemDetails::ToolOutput(output) = terminal.item.details else {
248            panic!("tool output expected")
249        };
250        assert_eq!(output.call_id, "original-call");
251        assert_eq!(output.status, crate::exec::events::ToolCallStatus::Failed);
252        assert_eq!(output.exit_code, Some(7));
253        assert!(
254            tracker
255                .background_exec_output_event(&mut background("session", "exec:session", Some(0)))
256                .is_none()
257        );
258    }
259
260    #[test]
261    fn execution_task_identity_survives_corrections_and_handoffs() {
262        let mut tracker = ExecutionContextTracker::default();
263        let first = tracker.begin("root", "turn-1", "Fix login", InputOrigin::User);
264        for (turn, origin) in [
265            ("turn-2", InputOrigin::Correction),
266            ("turn-3", InputOrigin::PlanApproval),
267            ("turn-4", InputOrigin::Continuation),
268            ("turn-5", InputOrigin::Retry),
269        ] {
270            let current = tracker.begin("root", turn, "changed input", origin);
271            assert_eq!(current.task_id, first.task_id);
272            assert_eq!(current.goal.as_deref(), Some("Fix login"));
273            assert_eq!(current.turn_id, turn);
274        }
275        let next = tracker.begin("root", "turn-6", "Add logging", InputOrigin::User);
276        assert_ne!(next.task_id, first.task_id);
277        assert_eq!(next.goal.as_deref(), Some("Add logging"));
278    }
279
280    #[test]
281    fn public_decision_bounds_are_validated_in_characters_and_fail_closed() {
282        assert!(validate_decision_input(json!({"summary":"é".repeat(240),"rationale":"r".repeat(1000),"alternatives":["a","b","c"],"evidence_ids":vec!["id";8]})).is_ok());
283        for invalid in [
284            json!({"summary":"a".repeat(241),"rationale":"why"}),
285            json!({"summary":"choice","rationale":"a".repeat(1001)}),
286            json!({"summary":"choice","rationale":"why","alternatives":["a","b","c","d"]}),
287            json!({"summary":"choice","rationale":"why","evidence_ids":[""]}),
288            json!({"summary":"choice","rationale":"why","private_reasoning":"hidden"}),
289            json!({"summary":" ","rationale":"why"}),
290        ] {
291            assert!(validate_decision_input(invalid).is_err());
292        }
293    }
294
295    #[test]
296    fn public_decision_accepts_valid_common_output_metadata() {
297        let args = json!({"summary":"Reuse parser","rationale":"Preserve validation","max_output_tokens":100});
298        let decision = validate_decision_input(args.clone()).unwrap();
299        assert_eq!(decision.summary, "Reuse parser");
300        let event = super::super::tool_invocation_completed_event(
301            "decision-call".into(),
302            "record_decision",
303            Some(&args),
304            None,
305            crate::exec::events::ToolCallStatus::Completed,
306            crate::exec::events::ToolOutcome::Success,
307        );
308        assert!(decision_completed_event(&event).is_some());
309        for invalid in [json!(0), json!(50_001), json!("100"), json!(1.5)] {
310            let mut args = args.clone();
311            args["max_output_tokens"] = invalid;
312            assert!(validate_decision_input(args).is_err());
313        }
314    }
315}
316
317/// Convert a successful decision call into a canonical public decision item.
318pub fn decision_completed_event(event: &ThreadEvent) -> Option<ThreadEvent> {
319    let ThreadEvent::ItemCompleted(e) = event else {
320        return None;
321    };
322    let ThreadItemDetails::ToolInvocation(t) = &e.item.details else {
323        return None;
324    };
325    if t.tool_name != crate::config::constants::tools::RECORD_DECISION
326        || t.status != crate::exec::events::ToolCallStatus::Completed
327        || t.outcome != Some(crate::exec::events::ToolOutcome::Success)
328    {
329        return None;
330    }
331    let decision = validate_decision_input(t.arguments.clone()?).ok()?;
332    Some(ThreadEvent::ItemCompleted(crate::exec::events::ItemCompletedEvent {
333        item: crate::exec::events::ThreadItem {
334            id: format!("{}:decision", e.item.id),
335            context: e.item.context.clone(),
336            details: ThreadItemDetails::Decision(Box::new(decision)),
337        },
338    }))
339}
340
341#[derive(Default)]
342pub struct ExecutionContextTracker {
343    current: Option<ExecutionContext>,
344    exec_launches: VecDeque<ExecSessionLaunch>,
345}
346
347impl ExecutionContextTracker {
348    /// Preserve native delegation metadata before tool-output compaction.
349    pub fn delegation_status_event(
350        &self,
351        call_item_id: &str,
352        tool_name: &str,
353        output: &serde_json::Value,
354    ) -> Option<ThreadEvent> {
355        use crate::config::constants::tools;
356        use crate::exec::events::{HarnessEventItem, HarnessEventKind, ItemCompletedEvent, ThreadItem};
357        if !matches!(
358            tool_name,
359            tools::AGENT
360                | tools::SPAWN_AGENT
361                | tools::WAIT_AGENT
362                | tools::RESUME_AGENT
363                | tools::CLOSE_AGENT
364                | tools::SEND_INPUT
365        ) {
366            return None;
367        }
368        let value = output.get("entry").unwrap_or(output);
369        let entry: crate::subagents::SubagentStatusEntry = serde_json::from_value(value.clone()).ok()?;
370        let current = self.current.as_ref()?;
371        if entry.session_id.is_empty()
372            || entry.session_id.len() > MAX_EXEC_ID_BYTES
373            || entry.parent_thread_id != current.actor_id
374        {
375            return None;
376        }
377        let item: HarnessEventItem = serde_json::from_value(serde_json::json!({
378            "event": HarnessEventKind::DelegatedAgentStatus,
379            "message": format!("Delegated {}: {}", entry.display_label, entry.description),
380            "task_id": entry.id,
381            "session_id": entry.session_id,
382            "status": entry.status.as_str(),
383        }))
384        .ok()?;
385        Some(ThreadEvent::ItemCompleted(ItemCompletedEvent {
386            item: ThreadItem {
387                id: format!("{call_item_id}:delegated-agent"),
388                context: Some(Box::new(ItemContext {
389                    task_id: current.task_id.clone(),
390                    turn_id: current.turn_id.clone(),
391                    actor_id: entry.session_id,
392                    parent_actor_id: Some(entry.parent_thread_id),
393                    timestamp: entry.updated_at.to_rfc3339(),
394                    activity: None,
395                })),
396                details: ThreadItemDetails::Harness(Box::new(item)),
397            },
398        }))
399    }
400
401    /// Preserve peer-messaging sends as harness status before tool-output compaction.
402    ///
403    /// Mirrors [`Self::delegation_status_event`]: a successful `ask_session` or
404    /// `answer_session` call fans out a `SessionMessageSent` event carrying the
405    /// peer session and the mailbox message id as `correlation_id`, so the
406    /// later `SessionMessageReceived` drain event can be linked to this send.
407    pub fn session_message_event(
408        &self,
409        call_item_id: &str,
410        tool_name: &str,
411        output: &serde_json::Value,
412    ) -> Option<ThreadEvent> {
413        use crate::config::constants::tools;
414        use crate::exec::events::{HarnessEventItem, HarnessEventKind, ItemCompletedEvent, ThreadItem};
415        if !matches!(tool_name, tools::ASK_SESSION | tools::ANSWER_SESSION) {
416            return None;
417        }
418        let current = self.current.as_ref()?;
419        let message_id = output.get("message_id")?.as_str()?;
420        let to_session = output.get("to_session")?.as_str()?;
421        if message_id.is_empty() || to_session.is_empty() || to_session.len() > MAX_EXEC_ID_BYTES {
422            return None;
423        }
424        let item: HarnessEventItem = serde_json::from_value(serde_json::json!({
425            "event": HarnessEventKind::SessionMessageSent,
426            "message": format!("Message to session {to_session}"),
427            "task_id": current.task_id,
428            "session_id": to_session,
429            "correlation_id": message_id,
430        }))
431        .ok()?;
432        Some(ThreadEvent::ItemCompleted(ItemCompletedEvent {
433            item: ThreadItem {
434                id: format!("{call_item_id}:session-message"),
435                context: Some(Box::new(ItemContext {
436                    task_id: current.task_id.clone(),
437                    turn_id: current.turn_id.clone(),
438                    actor_id: current.actor_id.clone(),
439                    parent_actor_id: None,
440                    timestamp: chrono::Utc::now().to_rfc3339(),
441                    activity: None,
442                })),
443                details: ThreadItemDetails::Harness(Box::new(item)),
444            },
445        }))
446    }
447
448    /// A new idle user request starts a task; other origins retain its root goal.
449    pub fn begin(&mut self, actor: &str, turn: &str, input: &str, origin: InputOrigin) -> ExecutionContext {
450        let previous = self.current.as_ref().filter(|_| origin != InputOrigin::User);
451        let context = ExecutionContext {
452            task_id: previous.map_or_else(|| format!("task-{}", uuid::Uuid::new_v4()), |c| c.task_id.clone()),
453            turn_id: turn.to_owned(),
454            actor_id: actor.to_owned(),
455            parent_actor_id: None,
456            origin,
457            timestamp: chrono::Utc::now().to_rfc3339(),
458            goal: previous.and_then(|c| c.goal.clone()).or_else(|| Some(input.to_owned())),
459        };
460        self.current = Some(context.clone());
461        context
462    }
463
464    /// Annotate before persistence and exporter fanout so all consumers agree.
465    pub fn annotate(&mut self, event: &mut ThreadEvent) {
466        let now = chrono::Utc::now().to_rfc3339();
467        match event {
468            ThreadEvent::TurnStarted(e) => {
469                if let Some(context) = e.context.as_deref() {
470                    self.current = Some(context.clone());
471                } else {
472                    e.context = self.current.clone().map(Box::new);
473                }
474            }
475            ThreadEvent::TurnCompleted(e) => {
476                e.completed_at.get_or_insert_with(|| Box::new(now));
477            }
478            ThreadEvent::TurnFailed(e) => {
479                e.completed_at.get_or_insert_with(|| Box::new(now));
480            }
481            ThreadEvent::ThreadCompleted(e) => {
482                e.completed_at.get_or_insert(now);
483            }
484            ThreadEvent::TurnBlocked(e) => {
485                e.completed_at.get_or_insert(now);
486            }
487            ThreadEvent::ItemStarted(e) => self.annotate_item(&mut e.item, now),
488            ThreadEvent::ItemUpdated(e) => self.annotate_item(&mut e.item, now),
489            ThreadEvent::ItemCompleted(e) => self.annotate_item(&mut e.item, now),
490            _ => {}
491        }
492    }
493
494    fn annotate_item(&mut self, item: &mut crate::exec::events::ThreadItem, timestamp: String) {
495        let Some(c) = &self.current else {
496            return;
497        };
498        let activity = match &item.details {
499            ThreadItemDetails::ToolInvocation(t) => t
500                .arguments
501                .as_ref()
502                .filter(|_| crate::tools::tool_intent::is_command_session_tool(&t.tool_name))
503                .map(|args| classify_shell_activity(&t.tool_name, args)),
504            ThreadItemDetails::CommandExecution(t) => {
505                Some(classify_shell_activity("exec_command", &serde_json::json!({"cmd": t.command})))
506            }
507            _ => None,
508        }
509        .map(|a| match a {
510            ShellActivity::Inspection => CommandActivity::Inspection,
511            ShellActivity::Verification => CommandActivity::Verification,
512            ShellActivity::Mutation => CommandActivity::Mutation,
513        });
514        item.context.get_or_insert_with(|| {
515            Box::new(ItemContext {
516                task_id: c.task_id.clone(),
517                turn_id: c.turn_id.clone(),
518                actor_id: c.actor_id.clone(),
519                parent_actor_id: c.parent_actor_id.clone(),
520                timestamp,
521                activity,
522            })
523        });
524        let ThreadItemDetails::ToolInvocation(invocation) = &item.details else {
525            return;
526        };
527        let Some(args) = invocation.arguments.as_ref() else {
528            return;
529        };
530        let Some(context) = item.context.as_ref() else { return };
531        if invocation.status == crate::exec::events::ToolCallStatus::Failed {
532            self.exec_launches.retain(|launch| {
533                launch.call_item_id != item.id
534                    || launch.context.task_id != context.task_id
535                    || launch.context.actor_id != context.actor_id
536            });
537            return;
538        }
539        if context.activity != Some(CommandActivity::Verification)
540            || !crate::tools::tool_intent::is_command_run_tool_call(&invocation.tool_name, args)
541            || item.id.len() > MAX_EXEC_ID_BYTES
542            || invocation.tool_call_id.as_ref().is_some_and(|id| id.len() > MAX_EXEC_ID_BYTES)
543            || [
544                &context.task_id,
545                &context.turn_id,
546                &context.actor_id,
547                &context.timestamp,
548            ]
549            .into_iter()
550            .any(|id| id.len() > MAX_EXEC_ID_BYTES)
551            || context.parent_actor_id.as_ref().is_some_and(|id| id.len() > MAX_EXEC_ID_BYTES)
552            || self.exec_launches.iter().any(|launch| {
553                launch.call_item_id == item.id
554                    && launch.context.task_id == context.task_id
555                    && launch.context.actor_id == context.actor_id
556            })
557        {
558            return;
559        }
560        if self.exec_launches.len() == MAX_TRACKED_EXEC_LAUNCHES {
561            self.exec_launches.pop_front();
562        }
563        self.exec_launches.push_back(ExecSessionLaunch {
564            session_id: None,
565            call_item_id: item.id.clone(),
566            tool_call_id: invocation.tool_call_id.clone(),
567            context: context.clone(),
568        });
569    }
570
571    /// Link authoritative exec results to their original verifier invocation.
572    /// Session identities, never repeated command text, own this association.
573    pub fn exec_session_output_event(
574        &mut self,
575        call_item_id: &str,
576        tool_name: &str,
577        args: &serde_json::Value,
578        output: &serde_json::Value,
579    ) -> Option<ThreadEvent> {
580        crate::tools::tool_intent::canonical_command_session_tool_name(tool_name)?;
581        let current = self.current.as_ref()?;
582        let is_launch = crate::tools::tool_intent::is_command_run_tool_call(tool_name, args);
583        let response_session = crate::tools::command_args::session_id_text(output);
584        let requested_session = crate::tools::command_args::session_id_text(args);
585        if response_session.is_some_and(|id| id.len() > MAX_EXEC_ID_BYTES)
586            || (!is_launch && response_session.is_some() && response_session != requested_session)
587        {
588            return None;
589        }
590        let position = self.exec_launches.iter().position(|launch| {
591            launch.context.actor_id == current.actor_id
592                && if is_launch {
593                    launch.context.task_id == current.task_id && launch.call_item_id == call_item_id
594                } else {
595                    requested_session.is_some() && launch.session_id.as_deref() == requested_session
596                }
597        })?;
598        let exit_code = output
599            .get("exit_code")
600            .and_then(serde_json::Value::as_i64)
601            .and_then(|code| i32::try_from(code).ok());
602        if exit_code == Some(0)
603            && (output.get("success").and_then(serde_json::Value::as_bool) == Some(false)
604                || output.get("error").is_some_and(|error| !error.is_null()))
605        {
606            return None;
607        }
608        if is_launch {
609            if exit_code.is_some() || response_session.is_none() {
610                self.exec_launches.remove(position);
611                return None;
612            }
613            self.exec_launches.get_mut(position)?.session_id = response_session.map(str::to_owned);
614        }
615        let payload = super::tool_output_payload_from_value(output);
616        self.exec_session_completion_event(
617            position,
618            exit_code,
619            payload.spool_path.as_deref(),
620            payload.aggregated_output,
621        )
622    }
623
624    /// Resolve raw subprocess completion facts through the same launch mapping.
625    pub fn background_exec_output_event(&mut self, event: &mut ThreadEvent) -> Option<ThreadEvent> {
626        let ThreadEvent::ItemCompleted(completed) = event else {
627            return None;
628        };
629        let ThreadItemDetails::Harness(harness) = &completed.item.details else {
630            return None;
631        };
632        if harness.event != crate::exec::events::HarnessEventKind::BackgroundSubprocessCompleted {
633            return None;
634        }
635        let session_id = harness.exec_session_id.as_deref()?;
636        // Raw exec completions carry this exact runtime-owned identity. Managed
637        // subagents use their own task/session identities and cannot alias it.
638        if harness.task_id.as_deref() != Some(format!("exec:{session_id}").as_str())
639            || harness.session_id.as_deref() != Some(session_id)
640        {
641            return None;
642        }
643        let current = self.current.as_ref()?;
644        let position = self.exec_launches.iter().position(|launch| {
645            launch.context.actor_id == current.actor_id && launch.session_id.as_deref() == Some(session_id)
646        })?;
647        let output = self.exec_session_completion_event(
648            position,
649            harness.exit_code,
650            None,
651            harness.message.clone().unwrap_or_default(),
652        )?;
653        if let ThreadEvent::ItemCompleted(output) = &output {
654            completed.item.context = output.item.context.clone();
655        }
656        Some(output)
657    }
658
659    fn exec_session_completion_event(
660        &mut self,
661        position: usize,
662        exit_code: Option<i32>,
663        spool_path: Option<&str>,
664        output: String,
665    ) -> Option<ThreadEvent> {
666        let launch = self.exec_launches.get(position)?;
667        let status = match exit_code {
668            Some(0) => crate::exec::events::ToolCallStatus::Completed,
669            Some(_) => crate::exec::events::ToolCallStatus::Failed,
670            None => crate::exec::events::ToolCallStatus::InProgress,
671        };
672        let mut event = super::tool_output_completed_event(
673            launch.call_item_id.clone(),
674            launch.tool_call_id.as_deref(),
675            status,
676            exit_code,
677            spool_path,
678            output,
679            Vec::new(),
680        );
681        if let ThreadEvent::ItemCompleted(completed) = &mut event {
682            completed.item.id = format!("{}:exec-session-output", launch.call_item_id);
683            let mut context = launch.context.clone();
684            context.timestamp = chrono::Utc::now().to_rfc3339();
685            completed.item.context = Some(context);
686        }
687        if exit_code.is_some() {
688            self.exec_launches.remove(position);
689        }
690        Some(event)
691    }
692}