vtcode-core 0.103.1

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Output item types for Open Responses.
//!
//! Items are the fundamental unit of context in Open Responses. They represent
//! atomic units of model output, tool invocation, or reasoning state.

use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

use super::{ContentPart, ItemStatus};

/// Unique identifier for an output item.
pub type OutputItemId = String;

/// Output items generated by the model.
///
/// Per the Open Responses specification, items are polymorphic (discriminated by `type`),
/// state machines (with status transitions), and streamable (through delta events).
///
/// Custom items serialize with their `custom_type` as the actual `type` field value
/// (e.g., `"type": "vtcode:file_change"`), per the extension convention.
#[derive(Debug, Clone, PartialEq)]
pub enum OutputItem {
    /// A message from the assistant, user, system, or developer.
    Message(MessageItem),

    /// Model reasoning/thinking content.
    Reasoning(ReasoningItem),

    /// A function/tool call request from the model.
    FunctionCall(FunctionCallItem),

    /// Output from a function/tool call execution.
    FunctionCallOutput(FunctionCallOutputItem),

    /// Custom/extension item type (prefixed with implementor slug).
    Custom(CustomItem),
}

impl Serialize for OutputItem {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Message(item) => {
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry("type", "message")?;
                map.serialize_entry("id", &item.id)?;
                map.serialize_entry("status", &item.status)?;
                map.serialize_entry("role", &item.role)?;
                map.serialize_entry("content", &item.content)?;
                map.end()
            }
            Self::Reasoning(item) => {
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry("type", "reasoning")?;
                map.serialize_entry("id", &item.id)?;
                map.serialize_entry("status", &item.status)?;
                if let Some(ref summary) = item.summary {
                    map.serialize_entry("summary", summary)?;
                }
                if let Some(ref content) = item.content {
                    map.serialize_entry("content", content)?;
                }
                if let Some(ref encrypted) = item.encrypted_content {
                    map.serialize_entry("encrypted_content", encrypted)?;
                }
                map.end()
            }
            Self::FunctionCall(item) => {
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry("type", "function_call")?;
                map.serialize_entry("id", &item.id)?;
                map.serialize_entry("status", &item.status)?;
                map.serialize_entry("name", &item.name)?;
                map.serialize_entry("arguments", &item.arguments)?;
                if let Some(ref call_id) = item.call_id {
                    map.serialize_entry("call_id", call_id)?;
                }
                map.end()
            }
            Self::FunctionCallOutput(item) => {
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry("type", "function_call_output")?;
                map.serialize_entry("id", &item.id)?;
                map.serialize_entry("status", &item.status)?;
                if let Some(ref call_id) = item.call_id {
                    map.serialize_entry("call_id", call_id)?;
                }
                map.serialize_entry("output", &item.output)?;
                map.end()
            }
            Self::Custom(item) => {
                // Custom items use their custom_type as the type discriminator
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry("type", &item.custom_type)?;
                map.serialize_entry("id", &item.id)?;
                map.serialize_entry("status", &item.status)?;
                map.serialize_entry("data", &item.data)?;
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for OutputItem {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OutputItemVisitor;

        impl<'de> Visitor<'de> for OutputItemVisitor {
            type Value = OutputItem;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("an output item object with a type field")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut type_field: Option<String> = None;
                let mut id: Option<String> = None;
                let mut status: Option<ItemStatus> = None;
                let mut role: Option<MessageRole> = None;
                let mut content: Option<Vec<ContentPart>> = None;
                let mut summary: Option<String> = None;
                let mut reasoning_content: Option<String> = None;
                let mut encrypted_content: Option<String> = None;
                let mut name: Option<String> = None;
                let mut arguments: Option<Value> = None;
                let mut call_id: Option<String> = None;
                let mut output: Option<String> = None;
                let mut data: Option<Value> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "type" => type_field = Some(map.next_value()?),
                        "id" => id = Some(map.next_value()?),
                        "status" => status = Some(map.next_value()?),
                        "role" => role = Some(map.next_value()?),
                        "content" => {
                            // content can be Vec<ContentPart> or String
                            let val: Value = map.next_value()?;
                            if let Value::Array(_) = &val {
                                content =
                                    Some(serde_json::from_value(val).map_err(de::Error::custom)?);
                            } else if let Value::String(s) = val {
                                reasoning_content = Some(s);
                            }
                        }
                        "summary" => summary = Some(map.next_value()?),
                        "encrypted_content" => encrypted_content = Some(map.next_value()?),
                        "name" => name = Some(map.next_value()?),
                        "arguments" => arguments = Some(map.next_value()?),
                        "call_id" => call_id = Some(map.next_value()?),
                        "output" => output = Some(map.next_value()?),
                        "data" => data = Some(map.next_value()?),
                        _ => {
                            // Skip unknown fields
                            let _: Value = map.next_value()?;
                        }
                    }
                }

                let type_str = type_field.ok_or_else(|| de::Error::missing_field("type"))?;
                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
                let status = status.unwrap_or(ItemStatus::InProgress);

                match type_str.as_str() {
                    "message" => Ok(OutputItem::Message(MessageItem {
                        id,
                        status,
                        role: role.unwrap_or_default(),
                        content: content.unwrap_or_default(),
                    })),
                    "reasoning" => Ok(OutputItem::Reasoning(ReasoningItem {
                        id,
                        status,
                        summary,
                        content: reasoning_content,
                        encrypted_content,
                    })),
                    "function_call" => Ok(OutputItem::FunctionCall(FunctionCallItem {
                        id,
                        status,
                        name: name.ok_or_else(|| de::Error::missing_field("name"))?,
                        arguments: arguments.unwrap_or(Value::Null),
                        call_id,
                    })),
                    "function_call_output" => {
                        Ok(OutputItem::FunctionCallOutput(FunctionCallOutputItem {
                            id,
                            status,
                            call_id,
                            output: output.ok_or_else(|| de::Error::missing_field("output"))?,
                        }))
                    }
                    // Any other type is treated as a custom extension type
                    custom_type => Ok(OutputItem::Custom(CustomItem {
                        id,
                        status,
                        custom_type: custom_type.to_string(),
                        data: data.unwrap_or(Value::Null),
                    })),
                }
            }
        }

        deserializer.deserialize_map(OutputItemVisitor)
    }
}

impl OutputItem {
    /// Returns the unique identifier for this item.
    pub fn id(&self) -> &str {
        match self {
            Self::Message(m) => &m.id,
            Self::Reasoning(r) => &r.id,
            Self::FunctionCall(f) => &f.id,
            Self::FunctionCallOutput(f) => &f.id,
            Self::Custom(c) => &c.id,
        }
    }

    /// Returns the current status of this item.
    pub fn status(&self) -> ItemStatus {
        match self {
            Self::Message(m) => m.status,
            Self::Reasoning(r) => r.status,
            Self::FunctionCall(f) => f.status,
            Self::FunctionCallOutput(f) => f.status,
            Self::Custom(c) => c.status,
        }
    }

    /// Returns the type name for this item.
    pub fn type_name(&self) -> &str {
        match self {
            Self::Message(_) => "message",
            Self::Reasoning(_) => "reasoning",
            Self::FunctionCall(_) => "function_call",
            Self::FunctionCallOutput(_) => "function_call_output",
            Self::Custom(c) => &c.custom_type,
        }
    }

    /// Creates a new message item with the given parameters (status: `InProgress`).
    pub fn message(id: impl Into<String>, role: MessageRole, content: Vec<ContentPart>) -> Self {
        Self::Message(MessageItem {
            id: id.into(),
            status: ItemStatus::InProgress,
            role,
            content,
        })
    }

    /// Creates a new completed message item with the given parameters.
    pub fn completed_message(
        id: impl Into<String>,
        role: MessageRole,
        content: Vec<ContentPart>,
    ) -> Self {
        Self::Message(MessageItem {
            id: id.into(),
            status: ItemStatus::Completed,
            role,
            content,
        })
    }

    /// Creates a new reasoning item.
    pub fn reasoning(id: impl Into<String>) -> Self {
        Self::Reasoning(ReasoningItem {
            id: id.into(),
            status: ItemStatus::InProgress,
            summary: None,
            content: None,
            encrypted_content: None,
        })
    }

    /// Creates a new function call item.
    pub fn function_call(id: impl Into<String>, name: impl Into<String>, arguments: Value) -> Self {
        Self::FunctionCall(FunctionCallItem {
            id: id.into(),
            status: ItemStatus::InProgress,
            name: name.into(),
            arguments,
            call_id: None,
        })
    }

    /// Creates a new function call output item (status: `InProgress`).
    ///
    /// Use this for streaming scenarios. For completed tool results, use
    /// [`completed_function_call_output`](Self::completed_function_call_output).
    pub fn function_call_output(
        id: impl Into<String>,
        call_id: Option<String>,
        output: impl Into<String>,
    ) -> Self {
        Self::FunctionCallOutput(FunctionCallOutputItem {
            id: id.into(),
            status: ItemStatus::InProgress,
            call_id,
            output: output.into(),
        })
    }

    /// Creates a new completed function call output item.
    ///
    /// Use this when the tool execution has finished and the output is final.
    pub fn completed_function_call_output(
        id: impl Into<String>,
        call_id: Option<String>,
        output: impl Into<String>,
    ) -> Self {
        Self::FunctionCallOutput(FunctionCallOutputItem {
            id: id.into(),
            status: ItemStatus::Completed,
            call_id,
            output: output.into(),
        })
    }
}

/// A message item representing conversation content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MessageItem {
    /// Unique identifier for this item.
    pub id: OutputItemId,

    /// Current lifecycle status.
    pub status: ItemStatus,

    /// Role of the message author.
    pub role: MessageRole,

    /// Content parts that make up this message.
    pub content: Vec<ContentPart>,
}

/// Role of a message author.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum MessageRole {
    /// User message.
    User,
    /// Assistant/model message.
    #[default]
    Assistant,
    /// System message.
    System,
    /// Developer message (for instructions).
    Developer,
}

impl std::fmt::Display for MessageRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::User => write!(f, "user"),
            Self::Assistant => write!(f, "assistant"),
            Self::System => write!(f, "system"),
            Self::Developer => write!(f, "developer"),
        }
    }
}

/// A reasoning item containing model's internal thought process.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReasoningItem {
    /// Unique identifier for this item.
    pub id: OutputItemId,

    /// Current lifecycle status.
    pub status: ItemStatus,

    /// Summary of the reasoning (human-readable).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,

    /// Raw reasoning trace content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,

    /// Encrypted reasoning content for rehydration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encrypted_content: Option<String>,
}

/// A function call item representing a tool invocation request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionCallItem {
    /// Unique identifier for this item.
    pub id: OutputItemId,

    /// Current lifecycle status.
    pub status: ItemStatus,

    /// Name of the function to call.
    pub name: String,

    /// Arguments to pass to the function (JSON object).
    pub arguments: Value,

    /// Optional call ID for correlating with output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call_id: Option<String>,
}

/// Output from a function call execution.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionCallOutputItem {
    /// Unique identifier for this item.
    pub id: OutputItemId,

    /// Current lifecycle status.
    pub status: ItemStatus,

    /// ID of the function call this output corresponds to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call_id: Option<String>,

    /// Output content from the function execution.
    pub output: String,
}

/// Custom/extension item type.
///
/// Custom types must be prefixed with an implementor slug (e.g., `vtcode:file_change`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CustomItem {
    /// Unique identifier for this item.
    pub id: OutputItemId,

    /// Current lifecycle status.
    pub status: ItemStatus,

    /// Custom type identifier (must be prefixed, e.g., `vtcode:file_change`).
    pub custom_type: String,

    /// Custom data payload.
    pub data: Value,
}

impl CustomItem {
    /// Creates a new custom item with VT Code prefix.
    pub fn vtcode(id: impl Into<String>, name: &str, data: Value) -> Self {
        Self {
            id: id.into(),
            status: ItemStatus::InProgress,
            custom_type: format!("vtcode:{name}"),
            data,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_output_item_id() {
        let item = OutputItem::message("msg_1", MessageRole::Assistant, vec![]);
        assert_eq!(item.id(), "msg_1");
        assert_eq!(item.type_name(), "message");
    }

    #[test]
    fn test_function_call_serialization() {
        let item = OutputItem::function_call(
            "fc_1",
            "read_file",
            serde_json::json!({"path": "/etc/passwd"}),
        );
        let json = serde_json::to_string(&item).unwrap();
        assert!(json.contains("\"type\":\"function_call\""));
        assert!(json.contains("\"name\":\"read_file\""));
    }

    #[test]
    fn test_custom_item_vtcode() {
        let item = CustomItem::vtcode(
            "custom_1",
            "file_change",
            serde_json::json!({"path": "test.rs", "kind": "update"}),
        );
        assert_eq!(item.custom_type, "vtcode:file_change");
    }

    #[test]
    fn test_custom_item_serializes_with_custom_type_as_type() {
        let item = OutputItem::Custom(CustomItem::vtcode(
            "custom_1",
            "file_change",
            serde_json::json!({"path": "test.rs"}),
        ));
        let json = serde_json::to_string(&item).unwrap();
        // Custom type should be the type discriminator, not "custom"
        assert!(json.contains("\"type\":\"vtcode:file_change\""));
        assert!(!json.contains("\"type\":\"custom\""));
        assert!(!json.contains("\"custom_type\""));
    }

    #[test]
    fn test_custom_item_roundtrip() {
        let original = OutputItem::Custom(CustomItem::vtcode(
            "custom_1",
            "file_change",
            serde_json::json!({"path": "test.rs", "kind": "update"}),
        ));
        let json = serde_json::to_string(&original).unwrap();
        let parsed: OutputItem = serde_json::from_str(&json).unwrap();
        assert_eq!(original, parsed);

        if let OutputItem::Custom(c) = &parsed {
            assert_eq!(c.custom_type, "vtcode:file_change");
            assert_eq!(c.data["path"], "test.rs");
        } else {
            panic!("Expected Custom variant");
        }
    }

    #[test]
    fn test_deserialize_unknown_type_as_custom() {
        let json = r#"{"type":"vendor:special_item","id":"item_1","status":"completed","data":{"key":"value"}}"#;
        let item: OutputItem = serde_json::from_str(json).unwrap();
        if let OutputItem::Custom(c) = item {
            assert_eq!(c.custom_type, "vendor:special_item");
            assert_eq!(c.id, "item_1");
            assert_eq!(c.status, ItemStatus::Completed);
            assert_eq!(c.data["key"], "value");
        } else {
            panic!("Expected Custom variant for unknown type");
        }
    }

    #[test]
    fn test_completed_message_has_completed_status() {
        let item = OutputItem::completed_message("msg_1", MessageRole::Assistant, vec![]);
        assert_eq!(item.status(), ItemStatus::Completed);
        if let OutputItem::Message(m) = item {
            assert_eq!(m.status, ItemStatus::Completed);
        } else {
            panic!("Expected Message variant");
        }
    }

    #[test]
    fn test_completed_function_call_output_has_completed_status() {
        let item =
            OutputItem::completed_function_call_output("fco_1", Some("fc_1".to_string()), "result");
        assert_eq!(item.status(), ItemStatus::Completed);
        if let OutputItem::FunctionCallOutput(f) = item {
            assert_eq!(f.status, ItemStatus::Completed);
            assert_eq!(f.call_id, Some("fc_1".to_string()));
            assert_eq!(f.output, "result");
        } else {
            panic!("Expected FunctionCallOutput variant");
        }
    }
}