1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3use std::sync::Mutex as StdMutex;
4
5use anyhow::{Context, Result, anyhow};
6use serde_json::{Value, json};
7use tokio::time::timeout;
8use vtcode_commons::sanitizer::sanitize_provider_diagnostic;
9use vtcode_commons::serde_helpers::json_to_string_pretty;
10use vtcode_config::auth::CopilotAuthConfig;
11
12use super::command::{CopilotModelSelectionMode, resolve_copilot_command, spawn_copilot_acp_process};
13use super::transport::StdioTransport;
14use super::types::{
15 CopilotAcpCompatibilityState, CopilotObservedToolCall, CopilotObservedToolCallStatus, CopilotPermissionDecision,
16 CopilotPermissionRequest, CopilotShellCommandSummary, CopilotTerminalCreateRequest, CopilotTerminalCreateResponse,
17 CopilotTerminalEnvVar, CopilotTerminalExitStatus, CopilotTerminalKillRequest, CopilotTerminalOutputRequest,
18 CopilotTerminalOutputResponse, CopilotTerminalReleaseRequest, CopilotTerminalWaitForExitRequest,
19 CopilotToolCallFailure, CopilotToolCallRequest, CopilotToolCallResponse,
20};
21use crate::provider::ToolDefinition;
22use vtcode_config::constants::tools;
23
24type RpcId = i64;
25
26const ACP_METHOD_NOT_FOUND_CODE: i32 = -32601;
27const ACP_RUNTIME_UNAVAILABLE_CODE: i32 = -32000;
28const MAX_TERMINAL_OUTPUT_BYTE_LIMIT: usize = 1_048_576;
29const MAX_TERMINAL_ARG_COUNT: usize = 256;
30const MAX_TERMINAL_ENV_VAR_COUNT: usize = 128;
31
32#[derive(Debug)]
33pub enum PromptUpdate {
34 Text(String),
35 Thought(String),
36}
37
38#[derive(Debug)]
39pub struct PromptCompletion {
40 pub stop_reason: String,
41}
42
43pub struct PromptSession {
44 updates: tokio::sync::mpsc::UnboundedReceiver<PromptUpdate>,
45 runtime_requests: tokio::sync::mpsc::UnboundedReceiver<CopilotRuntimeRequest>,
46 completion: tokio::task::JoinHandle<Result<PromptCompletion>>,
47 cancel_handle: PromptSessionCancelHandle,
48}
49
50#[derive(Clone)]
51pub struct PromptSessionCancelHandle {
52 client: CopilotAcpClient,
53 completion_abort: tokio::task::AbortHandle,
54}
55
56impl PromptSessionCancelHandle {
57 pub fn cancel(&self) {
58 let _ = self.client.cancel();
59 self.client.clear_active_prompt();
60 self.completion_abort.abort();
61 }
62}
63
64impl PromptSession {
65 pub fn into_parts(
66 self,
67 ) -> (
68 tokio::sync::mpsc::UnboundedReceiver<PromptUpdate>,
69 tokio::sync::mpsc::UnboundedReceiver<CopilotRuntimeRequest>,
70 tokio::task::JoinHandle<Result<PromptCompletion>>,
71 PromptSessionCancelHandle,
72 ) {
73 (self.updates, self.runtime_requests, self.completion, self.cancel_handle)
74 }
75}
76
77#[derive(Debug)]
78pub enum CopilotRuntimeRequest {
79 Permission(PendingPermissionRequest),
80 ToolCall(PendingToolCallRequest),
81 TerminalCreate(PendingTerminalCreateRequest),
82 TerminalOutput(PendingTerminalOutputRequest),
83 TerminalRelease(PendingTerminalReleaseRequest),
84 TerminalKill(PendingTerminalKillRequest),
85 TerminalWaitForExit(PendingTerminalWaitForExitRequest),
86 ObservedToolCall(CopilotObservedToolCall),
87 CompatibilityNotice(CopilotCompatibilityNotice),
88}
89
90#[derive(Debug)]
91pub struct PendingPermissionRequest {
92 pub request: CopilotPermissionRequest,
93 response_tx: tokio::sync::oneshot::Sender<Value>,
94 response_format: PermissionResponseFormat,
95}
96
97impl PendingPermissionRequest {
98 pub fn respond(self, decision: CopilotPermissionDecision) -> Result<()> {
99 self.response_tx
100 .send(self.response_format.render(decision))
101 .map_err(|_e| anyhow!("copilot permission response channel closed"))
102 }
103}
104
105macro_rules! define_pending_request {
106 ($name:ident, $request_ty:ty, $response_ty:ty, $error_message:literal) => {
107 #[derive(Debug)]
108 pub struct $name {
109 pub request: $request_ty,
110 response_tx: tokio::sync::oneshot::Sender<$response_ty>,
111 }
112
113 impl $name {
114 pub fn respond(self, response: $response_ty) -> Result<()> {
115 self.response_tx.send(response).map_err(|_e| anyhow!($error_message))
116 }
117 }
118 };
119}
120
121macro_rules! define_pending_signal_request {
122 ($name:ident, $request_ty:ty, $error_message:literal) => {
123 #[derive(Debug)]
124 pub struct $name {
125 pub request: $request_ty,
126 response_tx: tokio::sync::oneshot::Sender<()>,
127 }
128
129 impl $name {
130 pub fn respond(self) -> Result<()> {
131 self.response_tx.send(()).map_err(|_e| anyhow!($error_message))
132 }
133 }
134 };
135}
136
137define_pending_request!(
138 PendingToolCallRequest,
139 CopilotToolCallRequest,
140 CopilotToolCallResponse,
141 "copilot tool response channel closed"
142);
143define_pending_request!(
144 PendingTerminalCreateRequest,
145 CopilotTerminalCreateRequest,
146 CopilotTerminalCreateResponse,
147 "copilot terminal create response channel closed"
148);
149define_pending_request!(
150 PendingTerminalOutputRequest,
151 CopilotTerminalOutputRequest,
152 CopilotTerminalOutputResponse,
153 "copilot terminal output response channel closed"
154);
155define_pending_signal_request!(
156 PendingTerminalReleaseRequest,
157 CopilotTerminalReleaseRequest,
158 "copilot terminal release response channel closed"
159);
160define_pending_signal_request!(
161 PendingTerminalKillRequest,
162 CopilotTerminalKillRequest,
163 "copilot terminal kill response channel closed"
164);
165define_pending_request!(
166 PendingTerminalWaitForExitRequest,
167 CopilotTerminalWaitForExitRequest,
168 CopilotTerminalExitStatus,
169 "copilot terminal wait response channel closed"
170);
171
172#[derive(Clone)]
173pub struct CopilotAcpClient {
174 pub(super) inner: Arc<CopilotAcpClientInner>,
175}
176
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct CopilotCompatibilityNotice {
179 pub state: CopilotAcpCompatibilityState,
180 pub message: String,
181}
182
183pub(super) struct CopilotAcpClientInner {
190 pub(super) transport: StdioTransport,
192 pub(super) active_prompt: StdMutex<Option<ActivePrompt>>,
194 pub(super) session_id: StdMutex<Option<String>>,
196 pub(super) compatibility_state: StdMutex<CopilotAcpCompatibilityState>,
198}
199
200pub(super) struct ActivePrompt {
201 pub(super) updates: tokio::sync::mpsc::UnboundedSender<PromptUpdate>,
202 pub(super) runtime_requests: tokio::sync::mpsc::UnboundedSender<CopilotRuntimeRequest>,
203}
204
205#[derive(Debug, Clone)]
206enum PermissionResponseFormat {
207 CopilotCli,
208 AcpLegacy { options: Vec<AcpPermissionOption> },
209}
210
211impl PermissionResponseFormat {
212 fn render(self, decision: CopilotPermissionDecision) -> Value {
213 match self {
214 Self::CopilotCli => json!({
215 "result": decision.to_rpc_result(),
216 }),
217 Self::AcpLegacy { options } => json!({
218 "outcome": legacy_permission_outcome(&options, &decision),
219 }),
220 }
221 }
222}
223
224#[derive(Debug, Clone)]
225struct AcpPermissionOption {
226 option_id: String,
227 kind: AcpPermissionOptionKind,
228}
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum AcpPermissionOptionKind {
232 AllowOnce,
233 AllowAlways,
234 RejectOnce,
235 RejectAlways,
236 Other,
237}
238
239#[derive(Clone)]
240enum RpcReply {
241 Result(Value),
242 Error { code: i32, message: &'static str },
243}
244
245impl RpcReply {
246 fn result(value: Value) -> Self {
247 Self::Result(value)
248 }
249
250 fn runtime_error(message: &'static str) -> Self {
251 Self::Error { code: ACP_RUNTIME_UNAVAILABLE_CODE, message }
252 }
253}
254
255mod client;
256mod dispatch;
257mod terminal;
258
259use terminal::{
260 handle_terminal_create_request, handle_terminal_kill_request, handle_terminal_output_request,
261 handle_terminal_release_request, handle_terminal_wait_for_exit_request,
262};
263
264use dispatch::{
272 build_tool_call_result, clear_active_prompt_state, derived_copilot_tool_name, dispatch_runtime_request,
273 enqueue_runtime_request, handle_legacy_permission_request, handle_permission_request,
274 handle_runtime_request_message, handle_session_update, handle_tool_call_request,
275 is_runtime_request_channel_closed_error, mark_prompt_degraded, send_prompt_update, send_rpc_reply,
276 spawn_runtime_response_task, tool_call_closed_reply, tool_call_unavailable_reply,
277 unsupported_client_capability_message,
278};
279
280pub(super) fn handle_acp_message(inner: &Arc<CopilotAcpClientInner>, message: Value) -> Result<()> {
284 let Some(method) = message.get("method").and_then(Value::as_str) else {
285 return Ok(());
286 };
287
288 match method {
289 "session/update" => handle_session_update(inner, message.get("params"))?,
290 "permission.request" => handle_permission_request(inner, &message)?,
291 "session/request_permission" => handle_legacy_permission_request(inner, &message)?,
292 "tool.call" => handle_tool_call_request(inner, &message)?,
293 "terminal/create" => handle_terminal_create_request(inner, &message)?,
294 "terminal/output" => handle_terminal_output_request(inner, &message)?,
295 "terminal/release" => handle_terminal_release_request(inner, &message)?,
296 "terminal/kill" => handle_terminal_kill_request(inner, &message)?,
297 "terminal/wait_for_exit" => handle_terminal_wait_for_exit_request(inner, &message)?,
298 client_method => {
299 if let Some(id) = request_id(&message) {
300 let error_message = unsupported_client_capability_message(client_method);
301 mark_prompt_degraded(inner, error_message.clone())?;
302 inner
303 .transport
304 .respond_error(id, ACP_METHOD_NOT_FOUND_CODE, error_message)
305 .map_err(anyhow::Error::from)?;
306 }
307 }
308 }
309
310 Ok(())
311}
312
313mod observed;
314
315use observed::parse_observed_tool_call;
316
317fn parse_legacy_permission_request(value: Value) -> Result<CopilotPermissionRequest> {
318 let Some(object) = value.as_object() else {
319 return Ok(CopilotPermissionRequest::Unknown {
320 kind: Some("session/request_permission".to_string()),
321 raw: value,
322 });
323 };
324
325 let tool_call_id = object.get("toolCallId").and_then(Value::as_str).map(ToString::to_string);
326 let tool_name = derived_copilot_tool_name(
327 object.get("title").and_then(Value::as_str),
328 object.get("kind").and_then(Value::as_str),
329 );
330
331 Ok(CopilotPermissionRequest::CustomTool {
332 tool_call_id,
333 tool_name: tool_name.clone(),
334 tool_description: object
335 .get("title")
336 .and_then(Value::as_str)
337 .unwrap_or("GitHub Copilot ACP permission request")
338 .to_string(),
339 args: object.get("rawInput").cloned(),
340 })
341}
342
343fn parse_permission_options(value: Option<&Value>) -> Vec<AcpPermissionOption> {
344 value
345 .and_then(Value::as_array)
346 .map(|items| {
347 items
348 .iter()
349 .filter_map(|item| {
350 Some(AcpPermissionOption {
351 option_id: item.get("optionId")?.as_str()?.to_string(),
352 kind: parse_permission_option_kind(item.get("kind").and_then(Value::as_str)),
353 })
354 })
355 .collect()
356 })
357 .unwrap_or_default()
358}
359
360fn parse_permission_option_kind(kind: Option<&str>) -> AcpPermissionOptionKind {
361 match kind {
362 Some("allow_once") => AcpPermissionOptionKind::AllowOnce,
363 Some("allow_always") => AcpPermissionOptionKind::AllowAlways,
364 Some("reject_once") => AcpPermissionOptionKind::RejectOnce,
365 Some("reject_always") => AcpPermissionOptionKind::RejectAlways,
366 _ => AcpPermissionOptionKind::Other,
367 }
368}
369
370fn legacy_permission_outcome(options: &[AcpPermissionOption], decision: &CopilotPermissionDecision) -> Value {
371 let selected = match decision {
372 CopilotPermissionDecision::Approved => {
373 pick_permission_option(options, &[AcpPermissionOptionKind::AllowOnce, AcpPermissionOptionKind::AllowAlways])
374 }
375 CopilotPermissionDecision::ApprovedAlways => {
376 pick_permission_option(options, &[AcpPermissionOptionKind::AllowAlways, AcpPermissionOptionKind::AllowOnce])
377 }
378 CopilotPermissionDecision::DeniedByRules | CopilotPermissionDecision::DeniedByContentExclusionPolicy { .. } => {
379 pick_permission_option(
380 options,
381 &[
382 AcpPermissionOptionKind::RejectAlways,
383 AcpPermissionOptionKind::RejectOnce,
384 ],
385 )
386 }
387 CopilotPermissionDecision::DeniedNoApprovalRule
388 | CopilotPermissionDecision::DeniedInteractivelyByUser { .. } => pick_permission_option(
389 options,
390 &[
391 AcpPermissionOptionKind::RejectOnce,
392 AcpPermissionOptionKind::RejectAlways,
393 ],
394 ),
395 };
396
397 if let Some(option_id) = selected {
398 json!({
399 "outcome": "selected",
400 "optionId": option_id,
401 })
402 } else {
403 json!({
404 "outcome": "cancelled",
405 })
406 }
407}
408
409fn pick_permission_option(
410 options: &[AcpPermissionOption],
411 preferred_kinds: &[AcpPermissionOptionKind],
412) -> Option<String> {
413 preferred_kinds.iter().find_map(|preferred| {
414 options
415 .iter()
416 .find(|option| option.kind == *preferred)
417 .map(|option| option.option_id.clone())
418 })
419}
420
421fn extract_text(content: Option<&Value>) -> Option<String> {
422 match content {
423 Some(Value::Object(map)) => {
424 if map.get("type").and_then(Value::as_str) == Some("text") {
425 map.get("text").and_then(Value::as_str).map(ToString::to_string)
426 } else {
427 None
428 }
429 }
430 Some(Value::String(text)) => Some(text.clone()),
431 _ => None,
432 }
433}
434
435fn custom_tools_payload(custom_tools: &[ToolDefinition]) -> Vec<Value> {
436 custom_tools
437 .iter()
438 .filter_map(|tool| {
439 let function = tool.function.as_ref()?;
440 Some(json!({
441 "name": function.name,
442 "description": function.description,
443 "parameters": function.parameters,
444 "skipPermission": true,
445 }))
446 })
447 .collect()
448}
449
450fn parse_permission_request(value: Value) -> Result<CopilotPermissionRequest> {
451 let Some(object) = value.as_object() else {
452 return Ok(CopilotPermissionRequest::Unknown { kind: None, raw: value });
453 };
454
455 let kind = object.get("kind").and_then(Value::as_str).map(ToString::to_string);
456 let tool_call_id = object.get("toolCallId").and_then(Value::as_str).map(ToString::to_string);
457
458 Ok(match kind.as_deref() {
459 Some(tools::SHELL) => CopilotPermissionRequest::Shell {
460 tool_call_id,
461 full_command_text: object
462 .get("fullCommandText")
463 .and_then(Value::as_str)
464 .unwrap_or_default()
465 .to_string(),
466 intention: object.get("intention").and_then(Value::as_str).unwrap_or_default().to_string(),
467 commands: object
468 .get("commands")
469 .and_then(Value::as_array)
470 .map(|commands| {
471 commands
472 .iter()
473 .filter_map(|command| {
474 Some(CopilotShellCommandSummary {
475 identifier: command.get("identifier").and_then(Value::as_str)?.to_string(),
476 read_only: command.get("readOnly").and_then(Value::as_bool).unwrap_or(false),
477 })
478 })
479 .collect::<Vec<_>>()
480 })
481 .unwrap_or_default(),
482 possible_paths: string_array(object.get("possiblePaths")),
483 possible_urls: object
484 .get("possibleUrls")
485 .and_then(Value::as_array)
486 .map(|urls| {
487 urls.iter()
488 .filter_map(|entry| entry.get("url").and_then(Value::as_str).map(ToString::to_string))
489 .collect::<Vec<_>>()
490 })
491 .unwrap_or_default(),
492 has_write_file_redirection: object.get("hasWriteFileRedirection").and_then(Value::as_bool).unwrap_or(false),
493 can_offer_session_approval: object.get("canOfferSessionApproval").and_then(Value::as_bool).unwrap_or(false),
494 warning: object.get("warning").and_then(Value::as_str).map(ToString::to_string),
495 },
496 Some("write") => CopilotPermissionRequest::Write {
497 tool_call_id,
498 intention: object.get("intention").and_then(Value::as_str).unwrap_or_default().to_string(),
499 file_name: object.get("fileName").and_then(Value::as_str).unwrap_or_default().to_string(),
500 diff: object.get("diff").and_then(Value::as_str).unwrap_or_default().to_string(),
501 new_file_contents: object.get("newFileContents").and_then(Value::as_str).map(ToString::to_string),
502 },
503 Some("read") => CopilotPermissionRequest::Read {
504 tool_call_id,
505 intention: object.get("intention").and_then(Value::as_str).unwrap_or_default().to_string(),
506 path: object.get("path").and_then(Value::as_str).unwrap_or_default().to_string(),
507 },
508 Some("mcp") => CopilotPermissionRequest::Mcp {
509 tool_call_id,
510 server_name: object.get("serverName").and_then(Value::as_str).unwrap_or_default().to_string(),
511 tool_name: object.get("toolName").and_then(Value::as_str).unwrap_or_default().to_string(),
512 tool_title: object.get("toolTitle").and_then(Value::as_str).unwrap_or_default().to_string(),
513 args: object.get("args").cloned(),
514 read_only: object.get("readOnly").and_then(Value::as_bool).unwrap_or(false),
515 },
516 Some("url") => CopilotPermissionRequest::Url {
517 tool_call_id,
518 intention: object.get("intention").and_then(Value::as_str).unwrap_or_default().to_string(),
519 url: object.get("url").and_then(Value::as_str).unwrap_or_default().to_string(),
520 },
521 Some("memory") => CopilotPermissionRequest::Memory {
522 tool_call_id,
523 subject: object.get("subject").and_then(Value::as_str).unwrap_or_default().to_string(),
524 fact: object.get("fact").and_then(Value::as_str).unwrap_or_default().to_string(),
525 citations: object.get("citations").and_then(Value::as_str).unwrap_or_default().to_string(),
526 },
527 Some("custom-tool") => CopilotPermissionRequest::CustomTool {
528 tool_call_id,
529 tool_name: object.get("toolName").and_then(Value::as_str).unwrap_or_default().to_string(),
530 tool_description: object
531 .get("toolDescription")
532 .and_then(Value::as_str)
533 .unwrap_or_default()
534 .to_string(),
535 args: object.get("args").cloned(),
536 },
537 Some("hook") => CopilotPermissionRequest::Hook {
538 tool_call_id,
539 tool_name: object.get("toolName").and_then(Value::as_str).unwrap_or_default().to_string(),
540 tool_args: object.get("toolArgs").cloned(),
541 hook_message: object.get("hookMessage").and_then(Value::as_str).map(ToString::to_string),
542 },
543 _ => CopilotPermissionRequest::Unknown { kind, raw: value },
544 })
545}
546
547fn string_array(value: Option<&Value>) -> Vec<String> {
548 value
549 .and_then(Value::as_array)
550 .map(|items| {
551 items
552 .iter()
553 .filter_map(|item| item.as_str().map(ToString::to_string))
554 .collect::<Vec<_>>()
555 })
556 .unwrap_or_default()
557}
558
559fn request_id(message: &Value) -> Option<i64> {
560 message.get("id").and_then(Value::as_i64)
561}
562
563#[cfg(test)]
564mod tests;