1use 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
18pub 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
44fn tracker_item_state(
52 item: &serde_json::Value,
53 position: usize,
54) -> Option<crate::exec::events::tracker::TrackerItemState> {
55 use crate::exec::events::tracker::{TrackerItemState, TrackerItemStatus};
56 use std::str::FromStr;
57
58 let index_path = item
59 .get("index_path")
60 .and_then(serde_json::Value::as_str)
61 .filter(|path| !path.trim().is_empty())
62 .map(str::to_string)
63 .or_else(|| {
64 item.get("index")
65 .and_then(serde_json::Value::as_u64)
66 .map(|index| index.to_string())
67 })
68 .unwrap_or_else(|| (position + 1).to_string());
69 let status = match item.get("status").and_then(serde_json::Value::as_str) {
70 Some(raw) => TrackerItemStatus::from_str(raw).ok()?,
71 None => TrackerItemStatus::Pending,
72 };
73 let description = item
74 .get("description")
75 .and_then(serde_json::Value::as_str)
76 .or_else(|| item.get("text").and_then(serde_json::Value::as_str))
77 .filter(|description| !description.trim().is_empty())?;
78 let short = crate::tools::handlers::task_tracking::short_task_description(description);
79 let description = if short.trim().is_empty() {
80 description.trim().to_string()
81 } else {
82 short
83 };
84 Some(TrackerItemState { index_path, description, status })
85}
86
87fn tracker_snapshot_counts(
93 checklist: &serde_json::Map<String, serde_json::Value>,
94 items: &[crate::exec::events::tracker::TrackerItemState],
95) -> Option<(usize, usize)> {
96 use crate::exec::events::tracker::TrackerItemStatus;
97
98 if let (Some(completed), Some(total)) = (
99 checklist.get("completed").and_then(serde_json::Value::as_u64),
100 checklist.get("total").and_then(serde_json::Value::as_u64),
101 ) {
102 return Some((usize::try_from(completed).unwrap_or(usize::MAX), usize::try_from(total).unwrap_or(usize::MAX)));
103 }
104 if items.is_empty() {
105 return None;
106 }
107 let completed = items.iter().filter(|item| item.status == TrackerItemStatus::Completed).count();
108 Some((completed, items.len()))
109}
110
111#[cfg(test)]
112mod tests;
113
114pub fn decision_completed_event(event: &ThreadEvent) -> Option<ThreadEvent> {
116 let ThreadEvent::ItemCompleted(e) = event else {
117 return None;
118 };
119 let ThreadItemDetails::ToolInvocation(t) = &e.item.details else {
120 return None;
121 };
122 if t.tool_name != crate::config::constants::tools::RECORD_DECISION
123 || t.status != crate::exec::events::ToolCallStatus::Completed
124 || t.outcome != Some(crate::exec::events::ToolOutcome::Success)
125 {
126 return None;
127 }
128 let decision = validate_decision_input(t.arguments.clone()?).ok()?;
129 Some(ThreadEvent::ItemCompleted(crate::exec::events::ItemCompletedEvent {
130 item: crate::exec::events::ThreadItem {
131 id: format!("{}:decision", e.item.id),
132 context: e.item.context.clone(),
133 details: ThreadItemDetails::Decision(Box::new(decision)),
134 },
135 }))
136}
137
138#[derive(Default)]
139pub struct ExecutionContextTracker {
140 current: Option<ExecutionContext>,
141 exec_launches: VecDeque<ExecSessionLaunch>,
142}
143
144impl ExecutionContextTracker {
145 pub fn delegation_status_event(
147 &self,
148 call_item_id: &str,
149 tool_name: &str,
150 output: &serde_json::Value,
151 ) -> Option<ThreadEvent> {
152 use crate::config::constants::tools;
153 use crate::exec::events::{HarnessEventItem, HarnessEventKind, ItemCompletedEvent, ThreadItem};
154 if !matches!(
155 tool_name,
156 tools::AGENT
157 | tools::SPAWN_AGENT
158 | tools::WAIT_AGENT
159 | tools::RESUME_AGENT
160 | tools::CLOSE_AGENT
161 | tools::SEND_INPUT
162 ) {
163 return None;
164 }
165 let value = output.get("entry").unwrap_or(output);
166 let entry: crate::subagents::SubagentStatusEntry = serde_json::from_value(value.clone()).ok()?;
167 let current = self.current.as_ref()?;
168 if entry.session_id.is_empty()
169 || entry.session_id.len() > MAX_EXEC_ID_BYTES
170 || entry.parent_thread_id != current.actor_id
171 {
172 return None;
173 }
174 let item: HarnessEventItem = serde_json::from_value(serde_json::json!({
175 "event": HarnessEventKind::DelegatedAgentStatus,
176 "message": format!("Delegated {}: {}", entry.display_label, entry.description),
177 "task_id": entry.id,
178 "session_id": entry.session_id,
179 "status": entry.status.as_str(),
180 }))
181 .ok()?;
182 Some(ThreadEvent::ItemCompleted(ItemCompletedEvent {
183 item: ThreadItem {
184 id: format!("{call_item_id}:delegated-agent"),
185 context: Some(Box::new(ItemContext {
186 task_id: current.task_id.clone(),
187 turn_id: current.turn_id.clone(),
188 actor_id: entry.session_id,
189 parent_actor_id: Some(entry.parent_thread_id),
190 timestamp: entry.updated_at.to_rfc3339(),
191 activity: None,
192 })),
193 details: ThreadItemDetails::Harness(Box::new(item)),
194 },
195 }))
196 }
197
198 pub fn session_message_event(
205 &self,
206 call_item_id: &str,
207 tool_name: &str,
208 output: &serde_json::Value,
209 ) -> Option<ThreadEvent> {
210 use crate::config::constants::tools;
211 use crate::exec::events::{HarnessEventItem, HarnessEventKind, ItemCompletedEvent, ThreadItem};
212 if !matches!(tool_name, tools::ASK_SESSION | tools::ANSWER_SESSION) {
213 return None;
214 }
215 let current = self.current.as_ref()?;
216 let message_id = output.get("message_id")?.as_str()?;
217 let to_session = output.get("to_session")?.as_str()?;
218 if message_id.is_empty() || to_session.is_empty() || to_session.len() > MAX_EXEC_ID_BYTES {
219 return None;
220 }
221 let item: HarnessEventItem = serde_json::from_value(serde_json::json!({
222 "event": HarnessEventKind::SessionMessageSent,
223 "message": format!("Message to session {to_session}"),
224 "task_id": current.task_id,
225 "session_id": to_session,
226 "correlation_id": message_id,
227 }))
228 .ok()?;
229 Some(ThreadEvent::ItemCompleted(ItemCompletedEvent {
230 item: ThreadItem {
231 id: format!("{call_item_id}:session-message"),
232 context: Some(Box::new(ItemContext {
233 task_id: current.task_id.clone(),
234 turn_id: current.turn_id.clone(),
235 actor_id: current.actor_id.clone(),
236 parent_actor_id: None,
237 timestamp: chrono::Utc::now().to_rfc3339(),
238 activity: None,
239 })),
240 details: ThreadItemDetails::Harness(Box::new(item)),
241 },
242 }))
243 }
244
245 pub fn tracker_status_event(&self, tool_name: &str, output: &serde_json::Value) -> Option<ThreadEvent> {
255 use crate::config::constants::tools;
256 use crate::exec::events::tracker::TrackerSnapshot;
257
258 if tool_name != tools::TASK_TRACKER {
259 return None;
260 }
261 let checklist = output.get("checklist")?.as_object()?;
262 let mut items = Vec::new();
263 if let Some(raw_items) = checklist.get("items").and_then(serde_json::Value::as_array) {
264 for (position, item) in raw_items.iter().enumerate() {
265 if let Some(state) = tracker_item_state(item, position) {
266 items.push(state);
267 }
268 }
269 }
270 let (completed, total) = tracker_snapshot_counts(checklist, &items)?;
271 let title = checklist
272 .get("title")
273 .and_then(serde_json::Value::as_str)
274 .unwrap_or_default()
275 .to_string();
276 Some(ThreadEvent::TrackerUpdated(Box::new(TrackerSnapshot { title, completed, total, items })))
277 }
278
279 pub fn begin(&mut self, actor: &str, turn: &str, input: &str, origin: InputOrigin) -> ExecutionContext {
281 let previous = self.current.as_ref().filter(|_| origin != InputOrigin::User);
282 let context = ExecutionContext {
283 task_id: previous.map_or_else(|| format!("task-{}", uuid::Uuid::new_v4()), |c| c.task_id.clone()),
284 turn_id: turn.to_owned(),
285 actor_id: actor.to_owned(),
286 parent_actor_id: None,
287 origin,
288 timestamp: chrono::Utc::now().to_rfc3339(),
289 goal: previous.and_then(|c| c.goal.clone()).or_else(|| Some(input.to_owned())),
290 };
291 self.current = Some(context.clone());
292 context
293 }
294
295 pub fn annotate(&mut self, event: &mut ThreadEvent) {
297 let now = chrono::Utc::now().to_rfc3339();
298 match event {
299 ThreadEvent::TurnStarted(e) => {
300 if let Some(context) = e.context.as_deref() {
301 self.current = Some(context.clone());
302 } else {
303 e.context = self.current.clone().map(Box::new);
304 }
305 }
306 ThreadEvent::TurnCompleted(e) => {
307 e.completed_at.get_or_insert_with(|| Box::new(now));
308 }
309 ThreadEvent::TurnFailed(e) => {
310 e.completed_at.get_or_insert_with(|| Box::new(now));
311 }
312 ThreadEvent::ThreadCompleted(e) => {
313 e.completed_at.get_or_insert(now);
314 }
315 ThreadEvent::TurnBlocked(e) => {
316 e.completed_at.get_or_insert(now);
317 }
318 ThreadEvent::ItemStarted(e) => self.annotate_item(&mut e.item, now),
319 ThreadEvent::ItemUpdated(e) => self.annotate_item(&mut e.item, now),
320 ThreadEvent::ItemCompleted(e) => self.annotate_item(&mut e.item, now),
321 _ => {}
322 }
323 }
324
325 fn annotate_item(&mut self, item: &mut crate::exec::events::ThreadItem, timestamp: String) {
326 let Some(c) = &self.current else {
327 return;
328 };
329 let activity = match &item.details {
330 ThreadItemDetails::ToolInvocation(t) => t
331 .arguments
332 .as_ref()
333 .filter(|_| crate::tools::tool_intent::is_command_session_tool(&t.tool_name))
334 .map(|args| classify_shell_activity(&t.tool_name, args)),
335 ThreadItemDetails::CommandExecution(t) => {
336 Some(classify_shell_activity("exec_command", &serde_json::json!({"cmd": t.command})))
337 }
338 _ => None,
339 }
340 .map(|a| match a {
341 ShellActivity::Inspection => CommandActivity::Inspection,
342 ShellActivity::Verification => CommandActivity::Verification,
343 ShellActivity::Mutation => CommandActivity::Mutation,
344 });
345 item.context.get_or_insert_with(|| {
346 Box::new(ItemContext {
347 task_id: c.task_id.clone(),
348 turn_id: c.turn_id.clone(),
349 actor_id: c.actor_id.clone(),
350 parent_actor_id: c.parent_actor_id.clone(),
351 timestamp,
352 activity,
353 })
354 });
355 let ThreadItemDetails::ToolInvocation(invocation) = &item.details else {
356 return;
357 };
358 let Some(args) = invocation.arguments.as_ref() else {
359 return;
360 };
361 let Some(context) = item.context.as_ref() else { return };
362 if invocation.status == crate::exec::events::ToolCallStatus::Failed {
363 self.exec_launches.retain(|launch| {
364 launch.call_item_id != item.id
365 || launch.context.task_id != context.task_id
366 || launch.context.actor_id != context.actor_id
367 });
368 return;
369 }
370 if context.activity != Some(CommandActivity::Verification)
371 || !crate::tools::tool_intent::is_command_run_tool_call(&invocation.tool_name, args)
372 || item.id.len() > MAX_EXEC_ID_BYTES
373 || invocation.tool_call_id.as_ref().is_some_and(|id| id.len() > MAX_EXEC_ID_BYTES)
374 || [
375 &context.task_id,
376 &context.turn_id,
377 &context.actor_id,
378 &context.timestamp,
379 ]
380 .into_iter()
381 .any(|id| id.len() > MAX_EXEC_ID_BYTES)
382 || context.parent_actor_id.as_ref().is_some_and(|id| id.len() > MAX_EXEC_ID_BYTES)
383 || self.exec_launches.iter().any(|launch| {
384 launch.call_item_id == item.id
385 && launch.context.task_id == context.task_id
386 && launch.context.actor_id == context.actor_id
387 })
388 {
389 return;
390 }
391 if self.exec_launches.len() == MAX_TRACKED_EXEC_LAUNCHES {
392 self.exec_launches.pop_front();
393 }
394 self.exec_launches.push_back(ExecSessionLaunch {
395 session_id: None,
396 call_item_id: item.id.clone(),
397 tool_call_id: invocation.tool_call_id.clone(),
398 context: context.clone(),
399 });
400 }
401
402 pub fn exec_session_output_event(
405 &mut self,
406 call_item_id: &str,
407 tool_name: &str,
408 args: &serde_json::Value,
409 output: &serde_json::Value,
410 ) -> Option<ThreadEvent> {
411 crate::tools::tool_intent::canonical_command_session_tool_name(tool_name)?;
412 let current = self.current.as_ref()?;
413 let is_launch = crate::tools::tool_intent::is_command_run_tool_call(tool_name, args);
414 let response_session = crate::tools::command_args::session_id_text(output);
415 let requested_session = crate::tools::command_args::session_id_text(args);
416 if response_session.is_some_and(|id| id.len() > MAX_EXEC_ID_BYTES)
417 || (!is_launch && response_session.is_some() && response_session != requested_session)
418 {
419 return None;
420 }
421 let position = self.exec_launches.iter().position(|launch| {
422 launch.context.actor_id == current.actor_id
423 && if is_launch {
424 launch.context.task_id == current.task_id && launch.call_item_id == call_item_id
425 } else {
426 requested_session.is_some() && launch.session_id.as_deref() == requested_session
427 }
428 })?;
429 let exit_code = output
430 .get("exit_code")
431 .and_then(serde_json::Value::as_i64)
432 .and_then(|code| i32::try_from(code).ok());
433 if exit_code == Some(0)
434 && (output.get("success").and_then(serde_json::Value::as_bool) == Some(false)
435 || output.get("error").is_some_and(|error| !error.is_null()))
436 {
437 return None;
438 }
439 if is_launch {
440 if exit_code.is_some() || response_session.is_none() {
441 self.exec_launches.remove(position);
442 return None;
443 }
444 self.exec_launches.get_mut(position)?.session_id = response_session.map(str::to_owned);
445 }
446 let payload = super::tool_output_payload_from_value(output);
447 self.exec_session_completion_event(
448 position,
449 exit_code,
450 payload.spool_path.as_deref(),
451 payload.aggregated_output,
452 )
453 }
454
455 pub fn background_exec_output_event(&mut self, event: &mut ThreadEvent) -> Option<ThreadEvent> {
457 let ThreadEvent::ItemCompleted(completed) = event else {
458 return None;
459 };
460 let ThreadItemDetails::Harness(harness) = &completed.item.details else {
461 return None;
462 };
463 if harness.event != crate::exec::events::HarnessEventKind::BackgroundSubprocessCompleted {
464 return None;
465 }
466 let session_id = harness.exec_session_id.as_deref()?;
467 if harness.task_id.as_deref() != Some(format!("exec:{session_id}").as_str())
470 || harness.session_id.as_deref() != Some(session_id)
471 {
472 return None;
473 }
474 let current = self.current.as_ref()?;
475 let position = self.exec_launches.iter().position(|launch| {
476 launch.context.actor_id == current.actor_id && launch.session_id.as_deref() == Some(session_id)
477 })?;
478 let output = self.exec_session_completion_event(
479 position,
480 harness.exit_code,
481 None,
482 harness.message.clone().unwrap_or_default(),
483 )?;
484 if let ThreadEvent::ItemCompleted(output) = &output {
485 completed.item.context = output.item.context.clone();
486 }
487 Some(output)
488 }
489
490 fn exec_session_completion_event(
491 &mut self,
492 position: usize,
493 exit_code: Option<i32>,
494 spool_path: Option<&str>,
495 output: String,
496 ) -> Option<ThreadEvent> {
497 let launch = self.exec_launches.get(position)?;
498 let status = match exit_code {
499 Some(0) => crate::exec::events::ToolCallStatus::Completed,
500 Some(_) => crate::exec::events::ToolCallStatus::Failed,
501 None => crate::exec::events::ToolCallStatus::InProgress,
502 };
503 let mut event = super::tool_output_completed_event(
504 launch.call_item_id.clone(),
505 launch.tool_call_id.as_deref(),
506 status,
507 exit_code,
508 spool_path,
509 output,
510 Vec::new(),
511 );
512 if let ThreadEvent::ItemCompleted(completed) = &mut event {
513 completed.item.id = format!("{}:exec-session-output", launch.call_item_id);
514 let mut context = launch.context.clone();
515 context.timestamp = chrono::Utc::now().to_rfc3339();
516 completed.item.context = Some(context);
517 }
518 if exit_code.is_some() {
519 self.exec_launches.remove(position);
520 }
521 Some(event)
522 }
523}