vtcode-acp 0.98.7

ACP bridge and client implementation for VT Code
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
//! ACP session types and lifecycle management
//!
//! This module implements the session lifecycle as defined by ACP:
//! - Session creation (session/new)
//! - Session loading (session/load)
//! - Prompt handling (session/prompt)
//! - Session updates (session/update notifications)
//!
//! Reference: <https://agentclientprotocol.com/llms.txt>

use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Session state enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum SessionState {
    /// Session created but not yet active
    #[default]
    Created,
    /// Session is active and processing
    Active,
    /// Session is waiting for user input
    AwaitingInput,
    /// Session completed successfully
    Completed,
    /// Session was cancelled
    Cancelled,
    /// Session failed with error
    Failed,
}

/// ACP Session representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcpSession {
    /// Unique session identifier
    pub session_id: String,

    /// Current session state
    pub state: SessionState,

    /// Session creation timestamp (ISO 8601)
    pub created_at: String,

    /// Last activity timestamp (ISO 8601)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_activity_at: Option<String>,

    /// Session metadata
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, Value>,

    /// Turn counter for prompt/response cycles
    #[serde(default)]
    pub turn_count: u32,
}

impl AcpSession {
    /// Create a new session with the given ID
    pub fn new(session_id: impl Into<String>) -> Self {
        Self {
            session_id: session_id.into(),
            state: SessionState::Created,
            created_at: chrono::Utc::now().to_rfc3339(),
            last_activity_at: None,
            metadata: HashMap::new(),
            turn_count: 0,
        }
    }

    /// Update session state
    pub fn set_state(&mut self, state: SessionState) {
        self.state = state;
        self.last_activity_at = Some(chrono::Utc::now().to_rfc3339());
    }

    /// Increment turn counter
    pub fn increment_turn(&mut self) {
        self.turn_count += 1;
        self.last_activity_at = Some(chrono::Utc::now().to_rfc3339());
    }
}

// ============================================================================
// Session/New Request/Response
// ============================================================================

/// Parameters for session/new method
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SessionNewParams {
    /// Optional session metadata
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, Value>,

    /// Optional workspace context
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace: Option<WorkspaceContext>,

    /// Optional model preferences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_preferences: Option<ModelPreferences>,
}

/// Result of session/new method
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionNewResult {
    /// The created session ID
    pub session_id: String,

    /// Initial session state
    #[serde(default)]
    pub state: SessionState,
}

// ============================================================================
// Session/Load Request/Response
// ============================================================================

/// Parameters for session/load method
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionLoadParams {
    /// Session ID to load
    pub session_id: String,
}

/// Result of session/load method
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionLoadResult {
    /// The loaded session
    pub session: AcpSession,

    /// Conversation history (if available)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub history: Vec<ConversationTurn>,
}

// ============================================================================
// Session/Prompt Request/Response
// ============================================================================

/// Parameters for session/prompt method
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionPromptParams {
    /// Session ID
    pub session_id: String,

    /// Prompt content (can be text, images, etc.)
    pub content: Vec<PromptContent>,

    /// Optional turn-specific metadata
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, Value>,
}

/// Prompt content types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PromptContent {
    /// Plain text content
    Text {
        /// The text content
        text: String,
    },

    /// Image content (base64 or URL)
    Image {
        /// Image data (base64) or URL
        data: String,
        /// MIME type (e.g., "image/png")
        mime_type: String,
        /// Whether data is a URL (false = base64)
        #[serde(default)]
        is_url: bool,
    },

    /// Embedded context (file contents, etc.)
    Context {
        /// Context identifier/path
        path: String,
        /// Context content
        content: String,
        /// Language hint for syntax highlighting
        #[serde(skip_serializing_if = "Option::is_none")]
        language: Option<String>,
    },
}

impl PromptContent {
    /// Create text content
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    /// Create context content
    pub fn context(path: impl Into<String>, content: impl Into<String>) -> Self {
        Self::Context {
            path: path.into(),
            content: content.into(),
            language: None,
        }
    }
}

/// Result of session/prompt method
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionPromptResult {
    /// Turn ID for this prompt/response cycle
    pub turn_id: String,

    /// Final response content (may be streamed via notifications first)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<String>,

    /// Tool calls made during this turn
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCallRecord>,

    /// Turn completion status
    pub status: TurnStatus,
}

/// Turn completion status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TurnStatus {
    /// Turn completed successfully
    Completed,
    /// Turn was cancelled
    Cancelled,
    /// Turn failed with error
    Failed,
    /// Turn requires user input (e.g., permission approval)
    AwaitingInput,
}

// ============================================================================
// Session/RequestPermission (Client Method)
// ============================================================================

/// Parameters for session/request_permission method (client callable by agent)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestPermissionParams {
    /// Session ID
    pub session_id: String,

    /// Tool call requiring permission
    pub tool_call: ToolCallRecord,

    /// Available permission options
    pub options: Vec<PermissionOption>,
}

/// A permission option presented to the user
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionOption {
    /// Option ID
    pub id: String,

    /// Display label
    pub label: String,

    /// Detailed description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Result of session/request_permission
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum RequestPermissionResult {
    /// User selected an option
    Selected {
        /// The selected option ID
        option_id: String,
    },
    /// User cancelled the request
    Cancelled,
}

// ============================================================================
// Session/Cancel Request
// ============================================================================

/// Parameters for session/cancel method
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionCancelParams {
    /// Session ID
    pub session_id: String,

    /// Optional turn ID to cancel (if not provided, cancels current turn)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub turn_id: Option<String>,
}

// ============================================================================
// Session/Update Notification (Streaming)
// ============================================================================

/// Session update notification payload
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionUpdateNotification {
    /// Session ID
    pub session_id: String,

    /// Turn ID this update belongs to
    pub turn_id: String,

    /// Update type
    #[serde(flatten)]
    pub update: SessionUpdate,
}

/// Session update types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "update_type", rename_all = "snake_case")]
pub enum SessionUpdate {
    /// Text delta (streaming response)
    MessageDelta {
        /// Incremental text content
        delta: String,
    },

    /// Tool call started
    ToolCallStart {
        /// Tool call details
        tool_call: ToolCallRecord,
    },

    /// Tool call completed
    ToolCallEnd {
        /// Tool call ID
        tool_call_id: String,
        /// Tool result
        result: Value,
    },

    /// Turn completed
    TurnComplete {
        /// Final status
        status: TurnStatus,
    },

    /// Error occurred
    Error {
        /// Error code
        code: String,
        /// Error message
        message: String,
    },

    /// Server requests the client to execute a tool (bidirectional ACP protocol).
    ///
    /// Arrives via a `server/request` SSE event. After executing the tool,
    /// send the result back with [`crate::client_v2::AcpClientV2::session_tool_response`].
    ServerRequest {
        /// The tool execution request from the agent.
        request: ToolExecutionRequest,
    },
}

// ============================================================================
// Supporting Types
// ============================================================================

/// Workspace context for session initialization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceContext {
    /// Workspace root path
    pub root_path: String,

    /// Workspace name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Active file paths
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub active_files: Vec<String>,
}

/// Model preferences for session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelPreferences {
    /// Preferred model ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_id: Option<String>,

    /// Temperature setting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,

    /// Max tokens
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
}

/// Record of a tool call
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallRecord {
    /// Unique tool call ID
    pub id: String,

    /// Tool name
    pub name: String,

    /// Tool arguments
    pub arguments: Value,

    /// Tool result (if completed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,

    /// Timestamp
    pub timestamp: String,
}

/// Server-to-client tool execution request (arrives via `server/request` SSE event).
///
/// When the ACP agent needs the client to run a tool on its behalf it emits a
/// `server/request` SSE event containing this payload. The client must execute
/// the tool and reply with [`ToolExecutionResult`] via `client/response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolExecutionRequest {
    /// Unique request identifier used to correlate the response.
    pub request_id: String,
    /// The tool call the agent wants the client to execute.
    pub tool_call: ToolCallRecord,
}

/// Result of a client-side tool execution, sent back via `client/response`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolExecutionResult {
    /// Must match the `request_id` from [`ToolExecutionRequest`].
    pub request_id: String,
    /// ID of the tool call that was executed.
    pub tool_call_id: String,
    /// Tool output (structured or text).
    pub output: Value,
    /// Whether execution succeeded.
    pub success: bool,
    /// Error message when `success` is false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Wrapper for a `server/request` SSE event notification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerRequestNotification {
    /// Session this request belongs to.
    pub session_id: String,
    /// The tool execution request.
    pub request: ToolExecutionRequest,
}

/// A single turn in the conversation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationTurn {
    /// Turn ID
    pub turn_id: String,

    /// User prompt
    pub prompt: Vec<PromptContent>,

    /// Agent response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<String>,

    /// Tool calls made during this turn
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCallRecord>,

    /// Turn timestamp
    pub timestamp: String,
}

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

    #[test]
    fn test_session_new_params() {
        let params = SessionNewParams::default();
        let json = serde_json::to_value(&params).unwrap();
        assert_eq!(json, json!({}));
    }

    #[test]
    fn test_prompt_content_text() {
        let content = PromptContent::text("Hello, world!");
        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json["type"], "text");
        assert_eq!(json["text"], "Hello, world!");
    }

    #[test]
    fn test_session_update_message_delta() {
        let update = SessionUpdate::MessageDelta {
            delta: "Hello".to_string(),
        };
        let json = serde_json::to_value(&update).unwrap();
        assert_eq!(json["update_type"], "message_delta");
        assert_eq!(json["delta"], "Hello");
    }

    #[test]
    fn test_session_state_transitions() {
        let mut session = AcpSession::new("test-session");
        assert_eq!(session.state, SessionState::Created);

        session.set_state(SessionState::Active);
        assert_eq!(session.state, SessionState::Active);
        assert!(session.last_activity_at.is_some());
    }

    #[test]
    fn server_request_update_serializes_correctly() {
        let tool_call = ToolCallRecord {
            id: "tc-1".to_string(),
            name: "unified_search".to_string(),
            arguments: json!({"query": "fn main"}),
            result: None,
            timestamp: "2025-01-01T00:00:00Z".to_string(),
        };
        let request = ToolExecutionRequest {
            request_id: "req-1".to_string(),
            tool_call,
        };
        let update = SessionUpdate::ServerRequest { request };
        let json = serde_json::to_value(&update).unwrap();
        assert_eq!(json["update_type"], "server_request");
        assert_eq!(json["request"]["request_id"], "req-1");
    }

    #[test]
    fn tool_execution_result_success_serializes() {
        let result = ToolExecutionResult {
            request_id: "req-1".to_string(),
            tool_call_id: "tc-1".to_string(),
            output: json!({"matches": []}),
            success: true,
            error: None,
        };
        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(json["success"], true);
        assert!(json.get("error").is_none());
    }

    #[test]
    fn tool_execution_result_failure_includes_error() {
        let result = ToolExecutionResult {
            request_id: "req-1".to_string(),
            tool_call_id: "tc-1".to_string(),
            output: Value::Null,
            success: false,
            error: Some("permission denied".to_string()),
        };
        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(json["success"], false);
        assert_eq!(json["error"], "permission denied");
    }
}