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