Skip to main content

vtcode_llm/open_responses/bridge/
items.rs

1//! ThreadEvent item handling: started/updated/completed item conversion.
2
3use super::*;
4
5fn tool_output_text(output: &ToolOutputItem) -> String {
6    if !output.output.is_empty() {
7        return output.output.clone();
8    }
9
10    output
11        .spool_path
12        .as_deref()
13        .map(|path| format!("Output saved to {path}"))
14        .unwrap_or_default()
15}
16
17impl ResponseBuilder {
18    pub fn process_event<E: StreamEventEmitter>(&mut self, event: &ThreadEvent, emitter: &mut E) {
19        match event {
20            ThreadEvent::ThreadStarted(_) => {
21                emitter.response_created(self.response.clone());
22                self.response.status = ResponseStatus::InProgress;
23                emitter.response_in_progress(self.response.clone());
24                self.normalized.response_started = true;
25            }
26
27            ThreadEvent::TurnStarted(_) => {
28                // Turn started is internal to VT Code; no direct Open Responses equivalent
29                // The response is already in progress from ThreadStarted
30            }
31
32            ThreadEvent::TurnCompleted(evt) => {
33                if self.response.status.is_terminal() {
34                    return;
35                }
36                self.response.usage = Some(OpenUsage::from_exec_usage(&evt.usage).into());
37                self.response.status = ResponseStatus::Completed;
38                self.response.complete();
39                emitter.response_completed(self.response.clone());
40            }
41
42            ThreadEvent::TurnFailed(evt) => {
43                if self.response.status.is_terminal() {
44                    return;
45                }
46                self.response.fail(OpenResponseError::model_error(&evt.message));
47                emitter.response_failed(self.response.clone());
48            }
49
50            ThreadEvent::TurnBlocked(evt) => {
51                self.emit_custom_event(
52                    emitter,
53                    "vtcode.turn_blocked",
54                    json!({
55                        "completed_at": evt.completed_at,
56                        "message": evt.message,
57                        "last_tool": evt.last_tool,
58                        "blocked_streak": evt.blocked_streak,
59                        "blocked_total": evt.blocked_total,
60                        "consecutive_cap": evt.consecutive_cap,
61                        "total_cap": evt.total_cap,
62                        "recovery_active": evt.recovery_active,
63                    }),
64                );
65            }
66
67            ThreadEvent::AppSandboxDenied(evt) => {
68                self.emit_custom_event(
69                    emitter,
70                    "vtcode.app_sandbox_denied",
71                    json!({
72                        "tool": evt.tool,
73                        "tier": evt.tier,
74                        "uris": evt.uris,
75                    }),
76                );
77            }
78
79            ThreadEvent::ThreadCompleted(evt) => {
80                self.emit_custom_event(
81                    emitter,
82                    "vtcode.thread_completed",
83                    json!({
84                        "completed_at": evt.completed_at,
85                        "thread_id": evt.thread_id,
86                        "session_id": evt.session_id,
87                        "subtype": evt.subtype.as_str(),
88                        "outcome_code": evt.outcome_code,
89                        "result": evt.result,
90                        "stop_reason": evt.stop_reason,
91                        "usage": evt.usage,
92                        "total_cost_usd": evt.total_cost_usd,
93                        "num_turns": evt.num_turns,
94                    }),
95                );
96            }
97
98            ThreadEvent::ThreadCompactBoundary(evt) => {
99                self.emit_custom_event(
100                    emitter,
101                    "vtcode.thread_compact_boundary",
102                    json!({
103                        "thread_id": evt.thread_id,
104                        "trigger": evt.trigger.as_str(),
105                        "mode": evt.mode.as_str(),
106                        "original_message_count": evt.original_message_count,
107                        "compacted_message_count": evt.compacted_message_count,
108                        "history_artifact_path": evt.history_artifact_path,
109                    }),
110                );
111            }
112
113            ThreadEvent::ContextReset(evt) => {
114                self.emit_custom_event(
115                    emitter,
116                    "vtcode.context_reset",
117                    json!({
118                        "thread_id": evt.thread_id,
119                        "turn_id": evt.turn_id,
120                        "trigger": evt.trigger,
121                        "plan_preserved": evt.plan_preserved,
122                        "previous_context_usage_percent": evt.previous_context_usage_percent,
123                        "tool_budget_reset": evt.tool_budget_reset,
124                    }),
125                );
126            }
127
128            ThreadEvent::ItemStarted(evt) => {
129                self.handle_item_started(&evt.item, emitter);
130            }
131
132            ThreadEvent::ItemUpdated(evt) => {
133                self.handle_item_updated(&evt.item, emitter);
134            }
135
136            ThreadEvent::ItemCompleted(evt) => {
137                self.handle_item_completed(&evt.item, emitter);
138            }
139            ThreadEvent::PlanDelta(_) => {
140                // Plan deltas are VT Code-specific extension events and are intentionally
141                // ignored by the Open Responses bridge. The completed Plan item carries
142                // the full final plan content.
143            }
144
145            ThreadEvent::PlanApprovalRequested(evt) => {
146                self.emit_custom_event(
147                    emitter,
148                    "vtcode.plan_approval_requested",
149                    json!({
150                        "thread_id": evt.thread_id,
151                        "turn_id": evt.turn_id,
152                        "plan_file": evt.plan_file,
153                    }),
154                );
155            }
156
157            ThreadEvent::PlanApprovalResolved(evt) => {
158                self.emit_custom_event(
159                    emitter,
160                    "vtcode.plan_approval_resolved",
161                    json!({
162                        "thread_id": evt.thread_id,
163                        "turn_id": evt.turn_id,
164                        "decision": evt.decision,
165                        "automatic": evt.automatic,
166                    }),
167                );
168            }
169
170            ThreadEvent::Error(evt) => {
171                if self.response.status.is_terminal() {
172                    return;
173                }
174                self.response.fail(OpenResponseError::server_error(&evt.message));
175                emitter.response_failed(self.response.clone());
176            }
177
178            // Unknown events from newer schema versions are silently skipped.
179            ThreadEvent::Unknown
180            | ThreadEvent::PermissionRequested(_)
181            | ThreadEvent::PermissionResolved(_)
182            | ThreadEvent::Interjected(_)
183            | ThreadEvent::MatrixUpdated(_)
184            | ThreadEvent::TrackerUpdated(_) => {}
185        }
186    }
187
188    fn handle_item_started<E: StreamEventEmitter>(&mut self, item: &ThreadItem, emitter: &mut E) {
189        let output_index = self.next_output_index;
190        self.next_output_index += 1;
191        self.item_id_to_index.insert(item.id.clone(), output_index);
192
193        let output_item = self.convert_thread_item(item, ItemStatus::InProgress);
194
195        // Track active item state for streaming
196        // Initialize prev_text from initial content to prevent duplicate deltas
197        let initial_text = match &item.details {
198            ThreadItemDetails::AgentMessage(msg) => msg.text.clone(),
199            ThreadItemDetails::Plan(plan) => plan.text.clone(),
200            ThreadItemDetails::Reasoning(r) => r.text.clone(),
201            _ => String::new(),
202        };
203        let tool_output_prefix = match &item.details {
204            ThreadItemDetails::ToolOutput(output) => Some(ToolOutputPrefix::new(&tool_output_text(output))),
205            _ => None,
206        };
207        let active_state = ActiveItemState {
208            output_index,
209            content_index: 0,
210            prev_text: initial_text,
211            tool_output_prefix,
212        };
213        self.active_items.insert(item.id.clone(), active_state);
214
215        self.response.add_output(output_item.clone());
216        emitter.output_item_added(&self.response.id, output_index, output_item.clone());
217
218        // Emit ContentPartAdded for items with text content
219        if let OutputItem::Message(ref msg) = output_item
220            && !msg.content.is_empty()
221        {
222            emitter.emit(ResponseStreamEvent::ContentPartAdded {
223                response_id: self.response.id.clone(),
224                item_id: item.id.clone(),
225                output_index,
226                content_index: 0,
227                part: msg.content[0].clone(),
228            });
229        }
230    }
231
232    fn emit_custom_event<E: StreamEventEmitter>(&self, emitter: &mut E, event_type: &str, data: serde_json::Value) {
233        emitter.emit(ResponseStreamEvent::CustomEvent {
234            response_id: self.response.id.clone(),
235            event_type: event_type.to_string(),
236            sequence_number: self.next_output_index as u64,
237            data,
238        });
239    }
240
241    fn handle_item_updated<E: StreamEventEmitter>(&mut self, item: &ThreadItem, emitter: &mut E) {
242        // Handle updates for items not yet started (implicit start)
243        let state = if let Some(state) = self.active_items.get_mut(&item.id) {
244            state
245        } else {
246            // Implicit start: create item and emit Added event
247            if let ThreadItemDetails::ToolOutput(output) = &item.details
248                && output.is_delta == Some(true)
249            {
250                let mut initial = item.clone();
251                if let ThreadItemDetails::ToolOutput(output) = &mut initial.details {
252                    output.output.clear();
253                }
254                self.handle_item_started(&initial, emitter);
255            } else {
256                self.handle_item_started(item, emitter);
257            }
258            match self.active_items.get_mut(&item.id) {
259                Some(s) => s,
260                None => return,
261            }
262        };
263
264        match &item.details {
265            ThreadItemDetails::AgentMessage(msg) => {
266                // Use strip_prefix for safe UTF-8 delta computation
267                let delta = if let Some(suffix) = msg.text.strip_prefix(&state.prev_text) {
268                    suffix
269                } else {
270                    // Non-append update: emit full text as delta (fallback)
271                    &msg.text
272                };
273
274                if !delta.is_empty() {
275                    emitter.output_text_delta(
276                        &self.response.id,
277                        &item.id,
278                        state.output_index,
279                        state.content_index,
280                        delta,
281                    );
282                    state.prev_text = msg.text.clone();
283                }
284            }
285
286            ThreadItemDetails::Reasoning(r) => {
287                // Use strip_prefix for safe UTF-8 delta computation
288                let delta = if let Some(suffix) = r.text.strip_prefix(&state.prev_text) {
289                    suffix
290                } else {
291                    // Non-append update: emit full text as delta (fallback)
292                    &r.text
293                };
294
295                if !delta.is_empty() {
296                    emitter.reasoning_delta(&self.response.id, &item.id, state.output_index, delta);
297                    state.prev_text = r.text.clone();
298                }
299            }
300
301            ThreadItemDetails::ToolOutput(output) => {
302                let current_text = tool_output_text(output);
303                let prefix = state.tool_output_prefix.get_or_insert_with(|| ToolOutputPrefix::new(""));
304                if output.is_delta == Some(true) {
305                    if !current_text.is_empty() {
306                        emitter.output_text_delta(
307                            &self.response.id,
308                            &item.id,
309                            state.output_index,
310                            state.content_index,
311                            &current_text,
312                        );
313                        prefix.append(&current_text);
314                    }
315                    return;
316                }
317                let delta = if let Some(suffix) = prefix.suffix(&current_text) {
318                    suffix
319                } else {
320                    current_text.as_str()
321                };
322
323                if !delta.is_empty() {
324                    emitter.output_text_delta(
325                        &self.response.id,
326                        &item.id,
327                        state.output_index,
328                        state.content_index,
329                        delta,
330                    );
331                }
332                *prefix = ToolOutputPrefix::new(&current_text);
333            }
334
335            _ => {
336                // Other item types don't have incremental updates
337            }
338        }
339    }
340
341    fn handle_item_completed<E: StreamEventEmitter>(&mut self, item: &ThreadItem, emitter: &mut E) {
342        let (was_started, output_index) = match self.item_id_to_index.get(&item.id) {
343            Some(&idx) => (true, idx),
344            None => {
345                // Item was completed without being started (atomic item)
346                let idx = self.next_output_index;
347                self.next_output_index += 1;
348                self.item_id_to_index.insert(item.id.clone(), idx);
349                (false, idx)
350            }
351        };
352
353        // Determine final status
354        let status = self.determine_item_status(&item.details);
355        let output_item = self.convert_thread_item(item, status);
356
357        // For atomic completions (never started), emit Added first, then ContentPartAdded
358        if !was_started {
359            emitter.output_item_added(&self.response.id, output_index, output_item.clone());
360
361            // Emit ContentPartAdded for Message and Reasoning items
362            match &output_item {
363                OutputItem::Message(msg) => {
364                    if !msg.content.is_empty() {
365                        emitter.emit(ResponseStreamEvent::ContentPartAdded {
366                            response_id: self.response.id.clone(),
367                            item_id: item.id.clone(),
368                            output_index,
369                            content_index: 0,
370                            part: msg.content[0].clone(),
371                        });
372                    }
373                }
374                OutputItem::Reasoning(r) => {
375                    let text = r.content.clone().unwrap_or_default();
376                    emitter.emit(ResponseStreamEvent::ContentPartAdded {
377                        response_id: self.response.id.clone(),
378                        item_id: item.id.clone(),
379                        output_index,
380                        content_index: 0,
381                        part: ContentPart::output_text(text),
382                    });
383                }
384                _ => {}
385            }
386        }
387
388        // Update the response output
389        if output_index < self.response.output.len() {
390            self.response.output[output_index] = output_item.clone();
391        } else {
392            self.response.add_output(output_item.clone());
393        }
394
395        // Emit content-specific "done" events based on item type
396        match &output_item {
397            OutputItem::Message(msg) => {
398                // Emit OutputTextDone for text content
399                if let Some(ContentPart::OutputText(text_content)) = msg.content.first() {
400                    emitter.emit(ResponseStreamEvent::OutputTextDone {
401                        response_id: self.response.id.clone(),
402                        item_id: item.id.clone(),
403                        output_index,
404                        content_index: 0,
405                        text: text_content.text.clone(),
406                    });
407                    emitter.emit(ResponseStreamEvent::ContentPartDone {
408                        response_id: self.response.id.clone(),
409                        item_id: item.id.clone(),
410                        output_index,
411                        content_index: 0,
412                        part: msg.content[0].clone(),
413                    });
414                }
415            }
416            OutputItem::Reasoning(r) => {
417                // Emit ReasoningDone then ContentPartDone
418                emitter.emit(ResponseStreamEvent::ReasoningDone {
419                    response_id: self.response.id.clone(),
420                    item_id: item.id.clone(),
421                    output_index,
422                    item: output_item.clone(),
423                });
424                let text = r.content.clone().unwrap_or_default();
425                emitter.emit(ResponseStreamEvent::ContentPartDone {
426                    response_id: self.response.id.clone(),
427                    item_id: item.id.clone(),
428                    output_index,
429                    content_index: 0,
430                    part: ContentPart::output_text(text),
431                });
432            }
433            OutputItem::FunctionCall(fc) => {
434                // Emit FunctionCallArgumentsDone
435                if let Ok(args_str) = serde_json::to_string(&fc.arguments) {
436                    emitter.emit(ResponseStreamEvent::FunctionCallArgumentsDone {
437                        response_id: self.response.id.clone(),
438                        item_id: item.id.clone(),
439                        output_index,
440                        arguments: args_str,
441                    });
442                }
443            }
444            OutputItem::FunctionCallOutput(fco) if !fco.output.is_empty() => {
445                emitter.emit(ResponseStreamEvent::OutputTextDone {
446                    response_id: self.response.id.clone(),
447                    item_id: item.id.clone(),
448                    output_index,
449                    content_index: 0,
450                    text: fco.output.clone(),
451                });
452            }
453            _ => {}
454        }
455
456        // Clean up active state
457        self.active_items.remove(&item.id);
458
459        emitter.output_item_done(&self.response.id, output_index, output_item);
460    }
461
462    fn determine_item_status(&self, details: &ThreadItemDetails) -> ItemStatus {
463        match details {
464            ThreadItemDetails::CommandExecution(cmd) => match cmd.status {
465                CommandExecutionStatus::Completed => ItemStatus::Completed,
466                CommandExecutionStatus::Failed => ItemStatus::Failed,
467                CommandExecutionStatus::InProgress => ItemStatus::InProgress,
468            },
469            ThreadItemDetails::ToolInvocation(invocation) => match invocation.status {
470                vtcode_exec_events::ToolCallStatus::Completed => ItemStatus::Completed,
471                vtcode_exec_events::ToolCallStatus::Failed => ItemStatus::Failed,
472                vtcode_exec_events::ToolCallStatus::InProgress => ItemStatus::InProgress,
473            },
474            ThreadItemDetails::ToolOutput(output) => match output.status {
475                vtcode_exec_events::ToolCallStatus::Completed => ItemStatus::Completed,
476                vtcode_exec_events::ToolCallStatus::Failed => ItemStatus::Failed,
477                vtcode_exec_events::ToolCallStatus::InProgress => ItemStatus::InProgress,
478            },
479            ThreadItemDetails::FileChange(fc) => match fc.status {
480                PatchApplyStatus::Completed => ItemStatus::Completed,
481                PatchApplyStatus::Failed => ItemStatus::Failed,
482            },
483            ThreadItemDetails::McpToolCall(tc) => match tc.status {
484                Some(McpToolCallStatus::Completed) => ItemStatus::Completed,
485                Some(McpToolCallStatus::Failed) => ItemStatus::Failed,
486                Some(McpToolCallStatus::Started) | None => ItemStatus::InProgress,
487            },
488            ThreadItemDetails::Error(_) => ItemStatus::Failed,
489            _ => ItemStatus::Completed,
490        }
491    }
492
493    fn resolve_tool_call_correlation_id(&mut self, harness_call_id: &str, raw_tool_call_id: Option<&str>) -> String {
494        if let Some(existing) = self.tool_call_correlation_ids.get(harness_call_id) {
495            return existing.clone();
496        }
497
498        let correlation_id = match raw_tool_call_id {
499            Some(raw_id) if self.used_tool_call_ids.insert(raw_id.to_string()) => raw_id.to_string(),
500            _ => harness_call_id.to_string(),
501        };
502        self.tool_call_correlation_ids
503            .insert(harness_call_id.to_string(), correlation_id.clone());
504        correlation_id
505    }
506
507    fn convert_thread_item(&mut self, item: &ThreadItem, status: ItemStatus) -> OutputItem {
508        match &item.details {
509            ThreadItemDetails::Decision(decision) => OutputItem::Custom(CustomItem {
510                id: item.id.clone().into(),
511                status,
512                custom_type: "vtcode:decision".into(),
513                data: json!({"decision": decision, "context": item.context}),
514            }),
515            ThreadItemDetails::AgentMessage(msg) => OutputItem::Message(MessageItem {
516                id: item.id.clone().into(),
517                status,
518                role: MessageRole::Assistant,
519                content: vec![ContentPart::output_text(&msg.text)],
520            }),
521
522            ThreadItemDetails::Reasoning(r) => OutputItem::Reasoning(ReasoningItem {
523                id: item.id.clone().into(),
524                status,
525                summary: None,
526                content: Some(r.text.clone()),
527                encrypted_content: None,
528            }),
529
530            ThreadItemDetails::Plan(plan) => OutputItem::Custom(CustomItem {
531                id: item.id.clone().into(),
532                status,
533                custom_type: "vtcode:plan".to_string(),
534                data: json!({
535                    "text": plan.text,
536                }),
537            }),
538
539            ThreadItemDetails::CommandExecution(cmd) => OutputItem::Custom(CustomItem {
540                id: item.id.clone().into(),
541                status,
542                custom_type: "vtcode:command_execution".to_string(),
543                data: json!({
544                    "command": cmd.command,
545                    "arguments": cmd.arguments,
546                    "aggregated_output": cmd.aggregated_output,
547                    "exit_code": cmd.exit_code,
548                    "status": serde_json::to_value(&cmd.status).unwrap_or(serde_json::Value::Null),
549                }),
550            }),
551
552            ThreadItemDetails::ToolInvocation(invocation) => OutputItem::FunctionCall(FunctionCallItem {
553                id: item.id.clone().into(),
554                status,
555                name: invocation.tool_name.clone(),
556                arguments: invocation.arguments.clone().unwrap_or(json!({})),
557                call_id: Some(self.resolve_tool_call_correlation_id(&item.id, invocation.tool_call_id.as_deref())),
558            }),
559
560            ThreadItemDetails::ToolOutput(output) => {
561                OutputItem::FunctionCallOutput(crate::open_responses::FunctionCallOutputItem {
562                    id: item.id.clone().into(),
563                    status,
564                    call_id: Some(
565                        self.resolve_tool_call_correlation_id(&output.call_id, output.tool_call_id.as_deref()),
566                    ),
567                    output: tool_output_text(output),
568                })
569            }
570
571            ThreadItemDetails::FileChange(fc) => {
572                let changes: Vec<_> = fc
573                    .changes
574                    .iter()
575                    .map(|c| {
576                        json!({
577                            "path": c.path,
578                            "kind": format!("{:?}", c.kind).to_lowercase(),
579                        })
580                    })
581                    .collect();
582
583                OutputItem::Custom(CustomItem {
584                    id: item.id.clone().into(),
585                    status,
586                    custom_type: "vtcode:file_change".to_string(),
587                    data: json!({
588                        "changes": changes,
589                        "status": format!("{:?}", fc.status).to_lowercase(),
590                    }),
591                })
592            }
593
594            ThreadItemDetails::McpToolCall(tc) => OutputItem::FunctionCall(FunctionCallItem {
595                id: item.id.clone().into(),
596                status,
597                name: tc.tool_name.clone(),
598                arguments: tc.arguments.clone().unwrap_or(json!({})),
599                call_id: Some(item.id.clone()),
600            }),
601
602            ThreadItemDetails::WebSearch(ws) => OutputItem::Custom(CustomItem {
603                id: item.id.clone().into(),
604                status,
605                custom_type: "vtcode:web_search".to_string(),
606                data: json!({
607                    "query": ws.query,
608                    "provider": ws.provider,
609                    "results": ws.results,
610                }),
611            }),
612
613            ThreadItemDetails::Harness(event) => OutputItem::Custom(CustomItem {
614                id: item.id.clone().into(),
615                status,
616                custom_type: "vtcode:harness_event".to_string(),
617                data: json!({
618                    "event": serde_json::to_value(&event.event).unwrap_or(serde_json::Value::Null),
619                    "message": event.message,
620                    "command": event.command,
621                    "path": event.path,
622                    "exit_code": event.exit_code,
623                }),
624            }),
625
626            ThreadItemDetails::Error(err) => {
627                // Errors are represented as custom items
628                OutputItem::Custom(CustomItem {
629                    id: item.id.clone().into(),
630                    status: ItemStatus::Failed,
631                    custom_type: "vtcode:error".to_string(),
632                    data: json!({
633                        "message": err.message,
634                    }),
635                })
636            }
637        }
638    }
639}