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            | ThreadEvent::GoalUpdated(_) => {}
186        }
187    }
188
189    fn handle_item_started<E: StreamEventEmitter>(&mut self, item: &ThreadItem, emitter: &mut E) {
190        let output_index = self.next_output_index;
191        self.next_output_index += 1;
192        self.item_id_to_index.insert(item.id.clone(), output_index);
193
194        let output_item = self.convert_thread_item(item, ItemStatus::InProgress);
195
196        // Track active item state for streaming
197        // Initialize prev_text from initial content to prevent duplicate deltas
198        let initial_text = match &item.details {
199            ThreadItemDetails::AgentMessage(msg) => msg.text.clone(),
200            ThreadItemDetails::Plan(plan) => plan.text.clone(),
201            ThreadItemDetails::Reasoning(r) => r.text.clone(),
202            _ => String::new(),
203        };
204        let tool_output_prefix = match &item.details {
205            ThreadItemDetails::ToolOutput(output) => Some(ToolOutputPrefix::new(&tool_output_text(output))),
206            _ => None,
207        };
208        let active_state = ActiveItemState {
209            output_index,
210            content_index: 0,
211            prev_text: initial_text,
212            tool_output_prefix,
213        };
214        self.active_items.insert(item.id.clone(), active_state);
215
216        self.response.add_output(output_item.clone());
217        emitter.output_item_added(&self.response.id, output_index, output_item.clone());
218
219        // Emit ContentPartAdded for items with text content
220        if let OutputItem::Message(ref msg) = output_item
221            && !msg.content.is_empty()
222        {
223            emitter.emit(ResponseStreamEvent::ContentPartAdded {
224                response_id: self.response.id.clone(),
225                item_id: item.id.clone(),
226                output_index,
227                content_index: 0,
228                part: msg.content[0].clone(),
229            });
230        }
231    }
232
233    fn emit_custom_event<E: StreamEventEmitter>(&self, emitter: &mut E, event_type: &str, data: serde_json::Value) {
234        emitter.emit(ResponseStreamEvent::CustomEvent {
235            response_id: self.response.id.clone(),
236            event_type: event_type.to_string(),
237            sequence_number: self.next_output_index as u64,
238            data,
239        });
240    }
241
242    fn handle_item_updated<E: StreamEventEmitter>(&mut self, item: &ThreadItem, emitter: &mut E) {
243        // Handle updates for items not yet started (implicit start)
244        let state = if let Some(state) = self.active_items.get_mut(&item.id) {
245            state
246        } else {
247            // Implicit start: create item and emit Added event
248            if let ThreadItemDetails::ToolOutput(output) = &item.details
249                && output.is_delta == Some(true)
250            {
251                let mut initial = item.clone();
252                if let ThreadItemDetails::ToolOutput(output) = &mut initial.details {
253                    output.output.clear();
254                }
255                self.handle_item_started(&initial, emitter);
256            } else {
257                self.handle_item_started(item, emitter);
258            }
259            match self.active_items.get_mut(&item.id) {
260                Some(s) => s,
261                None => return,
262            }
263        };
264
265        match &item.details {
266            ThreadItemDetails::AgentMessage(msg) => {
267                // Use strip_prefix for safe UTF-8 delta computation
268                let delta = if let Some(suffix) = msg.text.strip_prefix(&state.prev_text) {
269                    suffix
270                } else {
271                    // Non-append update: emit full text as delta (fallback)
272                    &msg.text
273                };
274
275                if !delta.is_empty() {
276                    emitter.output_text_delta(
277                        &self.response.id,
278                        &item.id,
279                        state.output_index,
280                        state.content_index,
281                        delta,
282                    );
283                    state.prev_text = msg.text.clone();
284                }
285            }
286
287            ThreadItemDetails::Reasoning(r) => {
288                // Use strip_prefix for safe UTF-8 delta computation
289                let delta = if let Some(suffix) = r.text.strip_prefix(&state.prev_text) {
290                    suffix
291                } else {
292                    // Non-append update: emit full text as delta (fallback)
293                    &r.text
294                };
295
296                if !delta.is_empty() {
297                    emitter.reasoning_delta(&self.response.id, &item.id, state.output_index, delta);
298                    state.prev_text = r.text.clone();
299                }
300            }
301
302            ThreadItemDetails::ToolOutput(output) => {
303                let current_text = tool_output_text(output);
304                let prefix = state.tool_output_prefix.get_or_insert_with(|| ToolOutputPrefix::new(""));
305                if output.is_delta == Some(true) {
306                    if !current_text.is_empty() {
307                        emitter.output_text_delta(
308                            &self.response.id,
309                            &item.id,
310                            state.output_index,
311                            state.content_index,
312                            &current_text,
313                        );
314                        prefix.append(&current_text);
315                    }
316                    return;
317                }
318                let delta = if let Some(suffix) = prefix.suffix(&current_text) {
319                    suffix
320                } else {
321                    current_text.as_str()
322                };
323
324                if !delta.is_empty() {
325                    emitter.output_text_delta(
326                        &self.response.id,
327                        &item.id,
328                        state.output_index,
329                        state.content_index,
330                        delta,
331                    );
332                }
333                *prefix = ToolOutputPrefix::new(&current_text);
334            }
335
336            _ => {
337                // Other item types don't have incremental updates
338            }
339        }
340    }
341
342    fn handle_item_completed<E: StreamEventEmitter>(&mut self, item: &ThreadItem, emitter: &mut E) {
343        let (was_started, output_index) = match self.item_id_to_index.get(&item.id) {
344            Some(&idx) => (true, idx),
345            None => {
346                // Item was completed without being started (atomic item)
347                let idx = self.next_output_index;
348                self.next_output_index += 1;
349                self.item_id_to_index.insert(item.id.clone(), idx);
350                (false, idx)
351            }
352        };
353
354        // Determine final status
355        let status = self.determine_item_status(&item.details);
356        let output_item = self.convert_thread_item(item, status);
357
358        // For atomic completions (never started), emit Added first, then ContentPartAdded
359        if !was_started {
360            emitter.output_item_added(&self.response.id, output_index, output_item.clone());
361
362            // Emit ContentPartAdded for Message and Reasoning items
363            match &output_item {
364                OutputItem::Message(msg) => {
365                    if !msg.content.is_empty() {
366                        emitter.emit(ResponseStreamEvent::ContentPartAdded {
367                            response_id: self.response.id.clone(),
368                            item_id: item.id.clone(),
369                            output_index,
370                            content_index: 0,
371                            part: msg.content[0].clone(),
372                        });
373                    }
374                }
375                OutputItem::Reasoning(r) => {
376                    let text = r.content.clone().unwrap_or_default();
377                    emitter.emit(ResponseStreamEvent::ContentPartAdded {
378                        response_id: self.response.id.clone(),
379                        item_id: item.id.clone(),
380                        output_index,
381                        content_index: 0,
382                        part: ContentPart::output_text(text),
383                    });
384                }
385                _ => {}
386            }
387        }
388
389        // Update the response output
390        if output_index < self.response.output.len() {
391            self.response.output[output_index] = output_item.clone();
392        } else {
393            self.response.add_output(output_item.clone());
394        }
395
396        // Emit content-specific "done" events based on item type
397        match &output_item {
398            OutputItem::Message(msg) => {
399                // Emit OutputTextDone for text content
400                if let Some(ContentPart::OutputText(text_content)) = msg.content.first() {
401                    emitter.emit(ResponseStreamEvent::OutputTextDone {
402                        response_id: self.response.id.clone(),
403                        item_id: item.id.clone(),
404                        output_index,
405                        content_index: 0,
406                        text: text_content.text.clone(),
407                    });
408                    emitter.emit(ResponseStreamEvent::ContentPartDone {
409                        response_id: self.response.id.clone(),
410                        item_id: item.id.clone(),
411                        output_index,
412                        content_index: 0,
413                        part: msg.content[0].clone(),
414                    });
415                }
416            }
417            OutputItem::Reasoning(r) => {
418                // Emit ReasoningDone then ContentPartDone
419                emitter.emit(ResponseStreamEvent::ReasoningDone {
420                    response_id: self.response.id.clone(),
421                    item_id: item.id.clone(),
422                    output_index,
423                    item: output_item.clone(),
424                });
425                let text = r.content.clone().unwrap_or_default();
426                emitter.emit(ResponseStreamEvent::ContentPartDone {
427                    response_id: self.response.id.clone(),
428                    item_id: item.id.clone(),
429                    output_index,
430                    content_index: 0,
431                    part: ContentPart::output_text(text),
432                });
433            }
434            OutputItem::FunctionCall(fc) => {
435                // Emit FunctionCallArgumentsDone
436                if let Ok(args_str) = serde_json::to_string(&fc.arguments) {
437                    emitter.emit(ResponseStreamEvent::FunctionCallArgumentsDone {
438                        response_id: self.response.id.clone(),
439                        item_id: item.id.clone(),
440                        output_index,
441                        arguments: args_str,
442                    });
443                }
444            }
445            OutputItem::FunctionCallOutput(fco) if !fco.output.is_empty() => {
446                emitter.emit(ResponseStreamEvent::OutputTextDone {
447                    response_id: self.response.id.clone(),
448                    item_id: item.id.clone(),
449                    output_index,
450                    content_index: 0,
451                    text: fco.output.clone(),
452                });
453            }
454            _ => {}
455        }
456
457        // Clean up active state
458        self.active_items.remove(&item.id);
459
460        emitter.output_item_done(&self.response.id, output_index, output_item);
461    }
462
463    fn determine_item_status(&self, details: &ThreadItemDetails) -> ItemStatus {
464        match details {
465            ThreadItemDetails::CommandExecution(cmd) => match cmd.status {
466                CommandExecutionStatus::Completed => ItemStatus::Completed,
467                CommandExecutionStatus::Failed => ItemStatus::Failed,
468                CommandExecutionStatus::InProgress => ItemStatus::InProgress,
469            },
470            ThreadItemDetails::ToolInvocation(invocation) => match invocation.status {
471                vtcode_exec_events::ToolCallStatus::Completed => ItemStatus::Completed,
472                vtcode_exec_events::ToolCallStatus::Failed => ItemStatus::Failed,
473                vtcode_exec_events::ToolCallStatus::InProgress => ItemStatus::InProgress,
474            },
475            ThreadItemDetails::ToolOutput(output) => match output.status {
476                vtcode_exec_events::ToolCallStatus::Completed => ItemStatus::Completed,
477                vtcode_exec_events::ToolCallStatus::Failed => ItemStatus::Failed,
478                vtcode_exec_events::ToolCallStatus::InProgress => ItemStatus::InProgress,
479            },
480            ThreadItemDetails::FileChange(fc) => match fc.status {
481                PatchApplyStatus::Completed => ItemStatus::Completed,
482                PatchApplyStatus::Failed => ItemStatus::Failed,
483            },
484            ThreadItemDetails::McpToolCall(tc) => match tc.status {
485                Some(McpToolCallStatus::Completed) => ItemStatus::Completed,
486                Some(McpToolCallStatus::Failed) => ItemStatus::Failed,
487                Some(McpToolCallStatus::Started) | None => ItemStatus::InProgress,
488            },
489            ThreadItemDetails::Error(_) => ItemStatus::Failed,
490            _ => ItemStatus::Completed,
491        }
492    }
493
494    fn resolve_tool_call_correlation_id(&mut self, harness_call_id: &str, raw_tool_call_id: Option<&str>) -> String {
495        if let Some(existing) = self.tool_call_correlation_ids.get(harness_call_id) {
496            return existing.clone();
497        }
498
499        let correlation_id = match raw_tool_call_id {
500            Some(raw_id) if self.used_tool_call_ids.insert(raw_id.to_string()) => raw_id.to_string(),
501            _ => harness_call_id.to_string(),
502        };
503        self.tool_call_correlation_ids
504            .insert(harness_call_id.to_string(), correlation_id.clone());
505        correlation_id
506    }
507
508    fn convert_thread_item(&mut self, item: &ThreadItem, status: ItemStatus) -> OutputItem {
509        match &item.details {
510            ThreadItemDetails::Decision(decision) => OutputItem::Custom(CustomItem {
511                id: item.id.clone().into(),
512                status,
513                custom_type: "vtcode:decision".into(),
514                data: json!({"decision": decision, "context": item.context}),
515            }),
516            ThreadItemDetails::AgentMessage(msg) => OutputItem::Message(MessageItem {
517                id: item.id.clone().into(),
518                status,
519                role: MessageRole::Assistant,
520                content: vec![ContentPart::output_text(&msg.text)],
521            }),
522
523            ThreadItemDetails::Reasoning(r) => OutputItem::Reasoning(ReasoningItem {
524                id: item.id.clone().into(),
525                status,
526                summary: None,
527                content: Some(r.text.clone()),
528                encrypted_content: None,
529            }),
530
531            ThreadItemDetails::Plan(plan) => OutputItem::Custom(CustomItem {
532                id: item.id.clone().into(),
533                status,
534                custom_type: "vtcode:plan".to_string(),
535                data: json!({
536                    "text": plan.text,
537                }),
538            }),
539
540            ThreadItemDetails::CommandExecution(cmd) => OutputItem::Custom(CustomItem {
541                id: item.id.clone().into(),
542                status,
543                custom_type: "vtcode:command_execution".to_string(),
544                data: json!({
545                    "command": cmd.command,
546                    "arguments": cmd.arguments,
547                    "aggregated_output": cmd.aggregated_output,
548                    "exit_code": cmd.exit_code,
549                    "status": serde_json::to_value(&cmd.status).unwrap_or(serde_json::Value::Null),
550                }),
551            }),
552
553            ThreadItemDetails::ToolInvocation(invocation) => OutputItem::FunctionCall(FunctionCallItem {
554                id: item.id.clone().into(),
555                status,
556                name: invocation.tool_name.clone(),
557                arguments: invocation.arguments.clone().unwrap_or(json!({})),
558                call_id: Some(self.resolve_tool_call_correlation_id(&item.id, invocation.tool_call_id.as_deref())),
559            }),
560
561            ThreadItemDetails::ToolOutput(output) => {
562                OutputItem::FunctionCallOutput(crate::open_responses::FunctionCallOutputItem {
563                    id: item.id.clone().into(),
564                    status,
565                    call_id: Some(
566                        self.resolve_tool_call_correlation_id(&output.call_id, output.tool_call_id.as_deref()),
567                    ),
568                    output: tool_output_text(output),
569                })
570            }
571
572            ThreadItemDetails::FileChange(fc) => {
573                let changes: Vec<_> = fc
574                    .changes
575                    .iter()
576                    .map(|c| {
577                        json!({
578                            "path": c.path,
579                            "kind": format!("{:?}", c.kind).to_lowercase(),
580                        })
581                    })
582                    .collect();
583
584                OutputItem::Custom(CustomItem {
585                    id: item.id.clone().into(),
586                    status,
587                    custom_type: "vtcode:file_change".to_string(),
588                    data: json!({
589                        "changes": changes,
590                        "status": format!("{:?}", fc.status).to_lowercase(),
591                    }),
592                })
593            }
594
595            ThreadItemDetails::McpToolCall(tc) => OutputItem::FunctionCall(FunctionCallItem {
596                id: item.id.clone().into(),
597                status,
598                name: tc.tool_name.clone(),
599                arguments: tc.arguments.clone().unwrap_or(json!({})),
600                call_id: Some(item.id.clone()),
601            }),
602
603            ThreadItemDetails::WebSearch(ws) => OutputItem::Custom(CustomItem {
604                id: item.id.clone().into(),
605                status,
606                custom_type: "vtcode:web_search".to_string(),
607                data: json!({
608                    "query": ws.query,
609                    "provider": ws.provider,
610                    "results": ws.results,
611                }),
612            }),
613
614            ThreadItemDetails::Harness(event) => OutputItem::Custom(CustomItem {
615                id: item.id.clone().into(),
616                status,
617                custom_type: "vtcode:harness_event".to_string(),
618                data: json!({
619                    "event": serde_json::to_value(&event.event).unwrap_or(serde_json::Value::Null),
620                    "message": event.message,
621                    "command": event.command,
622                    "path": event.path,
623                    "exit_code": event.exit_code,
624                }),
625            }),
626
627            ThreadItemDetails::Error(err) => {
628                // Errors are represented as custom items
629                OutputItem::Custom(CustomItem {
630                    id: item.id.clone().into(),
631                    status: ItemStatus::Failed,
632                    custom_type: "vtcode:error".to_string(),
633                    data: json!({
634                        "message": err.message,
635                    }),
636                })
637            }
638        }
639    }
640}