vtcode-llm 0.187.0

LLM provider abstraction, client implementations, and streaming for VT Code
Documentation
//! ACP message dispatch: session updates, permission requests, tool calls,
//! prompt updates, and runtime-request routing.

use super::*;

pub(super) fn handle_session_update(inner: &Arc<CopilotAcpClientInner>, params: Option<&Value>) -> Result<()> {
    let Some(update) = params.and_then(|params| params.get("update")) else {
        return Ok(());
    };
    let Some(kind) = update.get("sessionUpdate").and_then(Value::as_str) else {
        return Ok(());
    };

    match kind {
        "agent_message_chunk" => {
            if let Some(text) = extract_text(update.get("content")) {
                send_prompt_update(inner, PromptUpdate::Text(text))?;
            }
        }
        "agent_thought_chunk" => {
            if let Some(text) = extract_text(update.get("content")) {
                send_prompt_update(inner, PromptUpdate::Thought(text))?;
            }
        }
        "tool_call" | "tool_call_update" => {
            if let Some(tool_call) = parse_observed_tool_call(update) {
                match enqueue_runtime_request(inner, CopilotRuntimeRequest::ObservedToolCall(tool_call)) {
                    Ok(_) => {}
                    Err(err) if is_runtime_request_channel_closed_error(&err) => {}
                    Err(err) => return Err(err),
                }
            } else {
                mark_prompt_degraded(
                    inner,
                    "GitHub Copilot ACP sent an unparseable tool call update; VT Code is continuing in prompt-only degraded mode.".to_string(),
                )?;
            }
        }
        "plan" | "available_commands_update" | "mode_update" => {}
        _ => {}
    }

    Ok(())
}

pub(super) fn send_rpc_reply(inner: &CopilotAcpClientInner, id: RpcId, reply: RpcReply) -> Result<()> {
    match reply {
        RpcReply::Result(value) => inner.transport.respond(id, value).map_err(anyhow::Error::from),
        RpcReply::Error { code, message } => {
            inner.transport.respond_error(id, code, message).map_err(anyhow::Error::from)
        }
    }
}

pub(super) fn spawn_runtime_response_task<TResponse, F>(
    inner: Arc<CopilotAcpClientInner>,
    id: RpcId,
    response_rx: tokio::sync::oneshot::Receiver<TResponse>,
    build_success_reply: F,
    closed_reply: RpcReply,
    warn_context: &'static str,
) where
    TResponse: Send + 'static,
    F: FnOnce(TResponse) -> RpcReply + Send + 'static,
{
    tokio::spawn(async move {
        let reply = match response_rx.await {
            Ok(response) => build_success_reply(response),
            Err(_) => closed_reply,
        };

        if let Err(err) = send_rpc_reply(inner.as_ref(), id, reply) {
            let safe_error = sanitize_provider_diagnostic(err.to_string().as_bytes());
            tracing::warn!(target: "copilot.acp", context = warn_context, error = %safe_error, "copilot acp response failed");
        }
    });
}

pub(super) fn dispatch_runtime_request<TResponse, F>(
    inner: &Arc<CopilotAcpClientInner>,
    request: CopilotRuntimeRequest,
    response_rx: tokio::sync::oneshot::Receiver<TResponse>,
    id: RpcId,
    build_success_reply: F,
    closed_reply: RpcReply,
    unavailable_reply: RpcReply,
    warn_context: &'static str,
) -> Result<()>
where
    TResponse: Send + 'static,
    F: FnOnce(TResponse) -> RpcReply + Send + 'static,
{
    let dispatched = match enqueue_runtime_request(inner, request) {
        Ok(dispatched) => dispatched,
        Err(err) if is_runtime_request_channel_closed_error(&err) => false,
        Err(err) => return Err(err),
    };

    if !dispatched {
        return send_rpc_reply(inner.as_ref(), id, unavailable_reply);
    }

    spawn_runtime_response_task(inner.clone(), id, response_rx, build_success_reply, closed_reply, warn_context);
    Ok(())
}

pub(super) fn handle_runtime_request_message<TRequest, TResponse, Parse, Wrap, Build>(
    inner: &Arc<CopilotAcpClientInner>,
    message: &Value,
    parse_request: Parse,
    wrap_request: Wrap,
    build_success_reply: Build,
    closed_reply: RpcReply,
    unavailable_reply: RpcReply,
    warn_context: &'static str,
) -> Result<()>
where
    TResponse: Send + 'static,
    Parse: FnOnce(&Value) -> Result<TRequest>,
    Wrap: FnOnce(TRequest, tokio::sync::oneshot::Sender<TResponse>) -> CopilotRuntimeRequest,
    Build: FnOnce(TResponse) -> RpcReply + Send + 'static,
{
    let Some(id) = request_id(message) else {
        return Ok(());
    };

    let params = message.get("params").cloned().unwrap_or(Value::Null);
    let request = parse_request(&params)?;
    let (response_tx, response_rx) = tokio::sync::oneshot::channel();

    dispatch_runtime_request(
        inner,
        wrap_request(request, response_tx),
        response_rx,
        id,
        build_success_reply,
        closed_reply,
        unavailable_reply,
        warn_context,
    )
}

pub(super) fn handle_permission_request(inner: &Arc<CopilotAcpClientInner>, message: &Value) -> Result<()> {
    handle_runtime_request_message(
        inner,
        message,
        |params| {
            Ok(params
                .get("permissionRequest")
                .cloned()
                .map(parse_permission_request)
                .transpose()?
                .unwrap_or(CopilotPermissionRequest::Unknown { kind: None, raw: Value::Null }))
        },
        |request, response_tx| {
            CopilotRuntimeRequest::Permission(PendingPermissionRequest {
                request,
                response_tx,
                response_format: PermissionResponseFormat::CopilotCli,
            })
        },
        RpcReply::result,
        RpcReply::result(PermissionResponseFormat::CopilotCli.render(CopilotPermissionDecision::DeniedNoApprovalRule)),
        RpcReply::result(PermissionResponseFormat::CopilotCli.render(CopilotPermissionDecision::DeniedNoApprovalRule)),
        "permission.respond",
    )
}

pub(super) fn handle_legacy_permission_request(inner: &Arc<CopilotAcpClientInner>, message: &Value) -> Result<()> {
    handle_runtime_request_message(
        inner,
        message,
        |params| {
            let request = params
                .get("toolCall")
                .cloned()
                .map(parse_legacy_permission_request)
                .transpose()?
                .unwrap_or(CopilotPermissionRequest::Unknown {
                    kind: Some("session/request_permission".to_string()),
                    raw: Value::Null,
                });
            Ok((request, parse_permission_options(params.get("options"))))
        },
        |(request, options), response_tx| {
            CopilotRuntimeRequest::Permission(PendingPermissionRequest {
                request,
                response_tx,
                response_format: PermissionResponseFormat::AcpLegacy { options },
            })
        },
        RpcReply::result,
        RpcReply::result(json!({ "outcome": { "outcome": "cancelled" } })),
        RpcReply::result(json!({ "outcome": { "outcome": "cancelled" } })),
        "legacy_permission.respond",
    )
}

pub(super) fn handle_tool_call_request(inner: &Arc<CopilotAcpClientInner>, message: &Value) -> Result<()> {
    let Some(id) = request_id(message) else {
        return Ok(());
    };

    let params = message.get("params").cloned().unwrap_or(Value::Null);
    let request = CopilotToolCallRequest {
        tool_call_id: params.get("toolCallId").and_then(Value::as_str).unwrap_or_default().to_string(),
        tool_name: params.get("toolName").and_then(Value::as_str).unwrap_or("unknown").to_string(),
        arguments: params.get("arguments").cloned().unwrap_or(Value::Null),
    };
    let tool_name = request.tool_name.clone();
    let (response_tx, response_rx) = tokio::sync::oneshot::channel();

    dispatch_runtime_request(
        inner,
        CopilotRuntimeRequest::ToolCall(PendingToolCallRequest { request, response_tx }),
        response_rx,
        id,
        |response| RpcReply::result(build_tool_call_result(response)),
        tool_call_closed_reply(&tool_name),
        tool_call_unavailable_reply(&tool_name),
        "tool_call.respond",
    )
}

// ---------------------------------------------------------------------------
// Active prompt helpers
// ---------------------------------------------------------------------------

pub(super) fn send_prompt_update(inner: &Arc<CopilotAcpClientInner>, update: PromptUpdate) -> Result<()> {
    // Clone the sender under the lock, then drop the guard before sending or
    // clearing. `clear_active_prompt_state` re-locks the same `std::sync::Mutex`,
    // and the let-chain guard stays alive through the whole block — calling
    // into it while the guard is held self-deadlocks on a `StdMutex`.
    let sender = inner
        .active_prompt
        .lock()
        .map_err(|_e| anyhow!("copilot acp active prompt mutex poisoned"))?
        .as_ref()
        .map(|active_prompt| active_prompt.updates.clone());
    let Some(sender) = sender else {
        return Ok(());
    };

    if sender.send(update).is_err() {
        clear_active_prompt_state(inner);
    }
    Ok(())
}

pub(super) fn mark_prompt_degraded(inner: &Arc<CopilotAcpClientInner>, message: String) -> Result<()> {
    {
        let mut compatibility_state = inner
            .compatibility_state
            .lock()
            .map_err(|_e| anyhow!("copilot acp compatibility mutex poisoned"))?;
        if *compatibility_state == CopilotAcpCompatibilityState::PromptOnly {
            return Ok(());
        }
        *compatibility_state = CopilotAcpCompatibilityState::PromptOnly;
    }
    tracing::warn!(
        target: "copilot.acp",
        message = %message,
        "GitHub Copilot ACP switched to prompt-only degraded mode"
    );
    match enqueue_runtime_request(
        inner,
        CopilotRuntimeRequest::CompatibilityNotice(CopilotCompatibilityNotice {
            state: CopilotAcpCompatibilityState::PromptOnly,
            message,
        }),
    ) {
        Ok(_) => {}
        Err(err) if is_runtime_request_channel_closed_error(&err) => {}
        Err(err) => return Err(err),
    }
    Ok(())
}

pub(super) fn enqueue_runtime_request(
    inner: &Arc<CopilotAcpClientInner>,
    request: CopilotRuntimeRequest,
) -> Result<bool> {
    let sender = inner
        .active_prompt
        .lock()
        .map_err(|_e| anyhow!("copilot acp active prompt mutex poisoned"))?
        .as_ref()
        .map(|active_prompt| active_prompt.runtime_requests.clone());
    let Some(sender) = sender else {
        return Ok(false);
    };

    if sender.send(request).is_err() {
        clear_active_prompt_state(inner);
        return Err(anyhow!("copilot runtime request channel closed"));
    }
    Ok(true)
}

pub(super) fn is_runtime_request_channel_closed_error(err: &anyhow::Error) -> bool {
    err.to_string().contains("copilot runtime request channel closed")
}

pub(super) fn clear_active_prompt_state(inner: &Arc<CopilotAcpClientInner>) {
    // This is the recovery path: we are about to discard the state, so recover
    // the guard even when a panic poisoned the lock. An `if let Ok(..)` here
    // would silently skip the clear and leave a stale sender in place, causing
    // every later prompt update to fail and re-enter this same dead cleanup.
    let mut active_prompt = inner.active_prompt.lock().unwrap_or_else(|poisoned| {
        tracing::warn!("copilot acp active prompt lock was poisoned; discarding stale state");
        poisoned.into_inner()
    });
    *active_prompt = None;
    // Clear the poison while the guard is still held, so no other locker can
    // poison the lock again in between. The state is now safe to reuse.
    inner.active_prompt.clear_poison();
}

// ---------------------------------------------------------------------------
// Payload builders
// ---------------------------------------------------------------------------

/// Build the JSON-RPC `result` value for a `tool.call` response.
pub(super) fn build_tool_call_result(response: CopilotToolCallResponse) -> Value {
    let inner = match response {
        CopilotToolCallResponse::Success(success) => json!({
            "textResultForLlm": success.text_result_for_llm,
            "resultType": "success",
            "toolTelemetry": {},
        }),
        CopilotToolCallResponse::Failure(failure) => json!({
            "textResultForLlm": failure.text_result_for_llm,
            "resultType": "failure",
            "error": failure.error,
            "toolTelemetry": {},
        }),
    };
    json!({ "result": inner })
}

pub(super) fn unsupported_client_capability_message(method: &str) -> String {
    format!("VT Code's builtin Copilot client does not implement `{method}`.")
}

pub(super) fn tool_call_closed_reply(tool_name: &str) -> RpcReply {
    RpcReply::result(build_tool_call_result(CopilotToolCallResponse::Failure(CopilotToolCallFailure {
        text_result_for_llm: format!("VT Code could not complete the client tool `{tool_name}`."),
        error: format!("tool '{tool_name}' response channel closed"),
    })))
}

pub(super) fn tool_call_unavailable_reply(tool_name: &str) -> RpcReply {
    RpcReply::result(build_tool_call_result(CopilotToolCallResponse::Failure(CopilotToolCallFailure {
        text_result_for_llm: format!("VT Code does not expose the client tool `{tool_name}` to GitHub Copilot."),
        error: format!("tool '{tool_name}' not supported by VT Code"),
    })))
}

pub(super) fn derived_copilot_tool_name(title: Option<&str>, kind: Option<&str>) -> String {
    title
        .filter(|value| !value.trim().is_empty())
        .map(ToString::to_string)
        .or_else(|| {
            kind.filter(|value| !value.trim().is_empty())
                .map(|kind| format!("copilot_{kind}"))
        })
        .unwrap_or_else(|| "copilot_tool".to_string())
}