| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use super::{ApiProvider, Configuration, Selection, route}; | |
| use maka_agent_facts::configuration::ModelInfo; | |
| use maka_agent_ports::model::Credentials; | |
| use maka_agent_ports::model::{ProviderKind, RequestCompression}; | |
| use maka_agent_ports::provider::Context; | |
| use maka_agent_ports::provider::Discovery; | |
| use maka_agent_ports::provider::Error; | |
| use maka_agent_ports::provider::Verification; | |
| use maka_capabilities::http; | |
| use serde_json::json; | |
| use std::collections::BTreeMap; | |
| pub(super) async fn discover( | |
| provider: &ApiProvider, | |
| request: Discovery, | |
| context: Context, | |
| ) -> Result<Vec<ModelInfo>, Error> { | |
| super::discovery::discover(provider, request, context).await | |
| } | |
| pub(super) async fn verify( | |
| provider: &ApiProvider, | |
| request: Verification, | |
| context: Context, | |
| ) -> Result<(), Error> { | |
| let configuration = Configuration::read(&request.connection.configuration)?; | |
| let route = route::resolve( | |
| &Selection { | |
| provider: provider.id, | |
| connection: &request.connection, | |
| base_url: &configuration.base_url, | |
| model: &request.model, | |
| overrides: request.overrides.as_ref(), | |
| }, | |
| provider.facts, | |
| )?; | |
| route.check_probe()?; | |
| let kind = match route.kind { | |
| ProviderKind::Anthropic => HeaderAuth::Anthropic, | |
| _ => HeaderAuth::Bearer, | |
| }; | |
| let credentials = | |
| super::authentication::authorize(provider.facts.auth_kind, request.credential)?; | |
| let mut headers = headers(kind, credentials, request.request_headers)?; | |
| if let Some(encoding) = configuration.request_compression.header_value() { | |
| if let Some((_, existing)) = headers | |
| .iter() | |
| .find(|(name, _)| name.eq_ignore_ascii_case("content-encoding")) | |
| { | |
| if !existing.trim().eq_ignore_ascii_case(encoding) { | |
| return Err(Error::Invalid( | |
| "request headers conflict with request compression".into(), | |
| )); | |
| } | |
| } else { | |
| headers.insert("content-encoding".into(), encoding.into()); | |
| } | |
| } | |
| let base = route.base_url.trim_end_matches('/'); | |
| let (path, mut body) = match route.kind { | |
| ProviderKind::OpenaiResponses | ProviderKind::OpenResponses(_) => ( | |
| "responses", | |
| json!({"model":request.model.id, "store":false, "max_output_tokens":16, | |
| "input":[{"role":"user","content":"Hi"}]}), | |
| ), | |
| ProviderKind::Anthropic => ( | |
| "messages", | |
| json!({"model":request.model.id,"max_tokens":16,"messages":[{"role":"user","content":"Hi"}]}), | |
| ), | |
| _ => ( | |
| "chat/completions", | |
| json!({"model":request.model.id,"max_tokens":16,"messages":[{"role":"user","content":"Hi"}]}), | |
| ), | |
| }; | |
| if let Some(overlay) = request.request_body_overlay { | |
| let overlay = overlay | |
| .as_object() | |
| .ok_or_else(|| Error::Invalid("invalid request overlay".into()))?; | |
| let target = body.as_object_mut().expect("verification body"); | |
| if overlay.keys().any(|key| target.contains_key(key)) { | |
| return Err(Error::Invalid( | |
| "request overlay conflicts with verification".into(), | |
| )); | |
| } | |
| target.extend(overlay.clone()); | |
| } | |
| let body = std::sync::Arc::new(body); | |
| let request_body = match configuration.request_compression { | |
| RequestCompression::None => { | |
| let length = json_byte_length(body.clone()).await?; | |
| streaming_json_body(body, Some(length)) | |
| } | |
| RequestCompression::Zstd => { | |
| crate::compression::zstd_request_body(streaming_json_body(body, None)) | |
| } | |
| }; | |
| // Verification proves HTTP acceptance, not a full agent inference. | |
| match send( | |
| &context, | |
| http::Request { | |
| url: format!("{base}/{path}"), | |
| method: maka_plugin_core::http::Method::Post, | |
| headers: headers.into_iter().collect(), | |
| body: request_body, | |
| }, | |
| ResponseBody::Discard, | |
| ) | |
| .await | |
| { | |
| Ok(_) => Ok(()), | |
| Err(Error::Http(415)) if configuration.request_compression == RequestCompression::Zstd => { | |
| Err(Error::Rejected( | |
| "endpoint rejected Content-Encoding: zstd (HTTP 415); disable request compression for this connection" | |
| .into(), | |
| )) | |
| } | |
| Err(error) => Err(error), | |
| } | |
| } | |
| async fn json_byte_length(value: std::sync::Arc<serde_json::Value>) -> Result<u64, Error> { | |
| struct CountingWriter(u64); | |
| impl std::io::Write for CountingWriter { | |
| fn write(&mut self, data: &[u8]) -> std::io::Result<usize> { | |
| self.0 = self | |
| .0 | |
| .checked_add(data.len() as u64) | |
| .ok_or_else(|| std::io::Error::other("verification body length overflow"))?; | |
| Ok(data.len()) | |
| } | |
| fn flush(&mut self) -> std::io::Result<()> { | |
| Ok(()) | |
| } | |
| } | |
| tokio::task::spawn_blocking(move || { | |
| let mut counter = CountingWriter(0); | |
| serde_json::to_writer(&mut counter, value.as_ref()) | |
| .map_err(|_| Error::Invalid("invalid verification body".into()))?; | |
| Ok(counter.0) | |
| }) | |
| .await | |
| .map_err(|_| Error::Invalid("failed to measure verification body".into()))? | |
| } | |
| fn streaming_json_body( | |
| value: std::sync::Arc<serde_json::Value>, | |
| length: Option<u64>, | |
| ) -> http::RequestBody { | |
| const CHUNK_BYTES: usize = 16 * 1024; | |
| struct ChunkWriter { | |
| tx: tokio::sync::mpsc::Sender<Result<http::Bytes, http::Error>>, | |
| buf: Vec<u8>, | |
| } | |
| impl ChunkWriter { | |
| fn flush_chunk(&mut self) -> std::io::Result<()> { | |
| if self.buf.is_empty() { | |
| return Ok(()); | |
| } | |
| let chunk = http::Bytes::from(std::mem::replace( | |
| &mut self.buf, | |
| Vec::with_capacity(CHUNK_BYTES), | |
| )); | |
| self.tx | |
| .blocking_send(Ok(chunk)) | |
| .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "closed")) | |
| } | |
| } | |
| impl std::io::Write for ChunkWriter { | |
| fn write(&mut self, data: &[u8]) -> std::io::Result<usize> { | |
| let mut rest = data; | |
| while !rest.is_empty() { | |
| let space = CHUNK_BYTES.saturating_sub(self.buf.len()); | |
| if space == 0 { | |
| self.flush_chunk()?; | |
| continue; | |
| } | |
| let take = rest.len().min(space); | |
| self.buf.extend_from_slice(&rest[..take]); | |
| rest = &rest[take..]; | |
| if self.buf.len() >= CHUNK_BYTES { | |
| self.flush_chunk()?; | |
| } | |
| } | |
| Ok(data.len()) | |
| } | |
| fn flush(&mut self) -> std::io::Result<()> { | |
| self.flush_chunk() | |
| } | |
| } | |
| http::RequestBody::replayable(move || { | |
| let value = value.clone(); | |
| let (tx, rx) = tokio::sync::mpsc::channel(2); | |
| tokio::task::spawn_blocking(move || { | |
| let mut writer = ChunkWriter { | |
| tx: tx.clone(), | |
| buf: Vec::with_capacity(CHUNK_BYTES), | |
| }; | |
| let result = serde_json::to_writer(&mut writer, value.as_ref()) | |
| .and_then(|()| std::io::Write::flush(&mut writer).map_err(serde_json::Error::io)); | |
| if let Err(error) = result | |
| && error.io_error_kind() != Some(std::io::ErrorKind::BrokenPipe) | |
| { | |
| let _ = tx.blocking_send(Err(http::Error::Failed(format!( | |
| "verification JSON serialization failed: {error}" | |
| )))); | |
| } | |
| }); | |
| let stream = futures_util::stream::unfold(rx, |mut rx| async move { | |
| rx.recv().await.map(|item| (item, rx)) | |
| }); | |
| match length { | |
| Some(length) => http::RequestBody::with_length(stream, length), | |
| None => http::RequestBody::stream(stream), | |
| } | |
| }) | |
| } | |
| #[derive(Clone, Copy, PartialEq, Eq)] | |
| pub(super) enum HeaderAuth { | |
| Bearer, | |
| Anthropic, | |
| } | |
| pub(super) fn headers( | |
| kind: HeaderAuth, | |
| credentials: Credentials, | |
| custom: BTreeMap<String, String>, | |
| ) -> Result<BTreeMap<String, String>, Error> { | |
| let mut headers = BTreeMap::from([("content-type".into(), "application/json".into())]); | |
| if kind == HeaderAuth::Anthropic { | |
| headers.insert("anthropic-version".into(), "2023-06-01".into()); | |
| } | |
| let authenticated = match credentials { | |
| Credentials::ApiKey(key) if kind == HeaderAuth::Anthropic => { | |
| BTreeMap::from([("x-api-key".into(), key)]) | |
| } | |
| Credentials::ApiKey(key) if !key.is_empty() => { | |
| BTreeMap::from([("authorization".into(), format!("Bearer {key}"))]) | |
| } | |
| Credentials::ApiKey(_) => BTreeMap::new(), | |
| Credentials::RequestHeaders(headers) => headers, | |
| }; | |
| for (name, value) in authenticated.into_iter().chain(custom) { | |
| let name = name.to_ascii_lowercase(); | |
| if headers | |
| .get(&name) | |
| .is_some_and(|existing| existing != &value) | |
| { | |
| return Err(Error::Invalid( | |
| "request headers conflict with provider authentication".into(), | |
| )); | |
| } | |
| headers.insert(name, value); | |
| } | |
| Ok(headers) | |
| } | |
| pub(super) enum ResponseBody { | |
| Inventory, | |
| Discard, | |
| } | |
| pub(super) async fn send( | |
| context: &Context, | |
| request: http::Request, | |
| body: ResponseBody, | |
| ) -> Result<Vec<u8>, Error> { | |
| if context.cancellation.is_cancelled() { | |
| return Err(Error::Cancelled); | |
| } | |
| let response = context | |
| .transport | |
| .request(request, context.cancellation.clone()) | |
| .await | |
| .map_err(|_| { | |
| if context.cancellation.is_cancelled() { | |
| Error::Cancelled | |
| } else { | |
| Error::Transport("provider request failed".into()) | |
| } | |
| })?; | |
| let result = async { | |
| if !(200..300).contains(&response.head.status) { | |
| return Err(Error::Http(response.head.status)); | |
| } | |
| if matches!(body, ResponseBody::Discard) { | |
| return Ok(Vec::new()); | |
| } | |
| let mut bytes = Vec::new(); | |
| while let Some(chunk) = response | |
| .body | |
| .next() | |
| .await | |
| .map_err(|_| Error::Transport("provider response read failed".into()))? | |
| { | |
| bytes.extend_from_slice(&chunk); | |
| } | |
| Ok(bytes) | |
| }; | |
| let result = tokio::select! { | |
| biased; | |
| _ = context.cancellation.cancelled() => Err(Error::Cancelled), | |
| result = result => result, | |
| }; | |
| response.body.cancel(); | |
| response | |
| .body | |
| .close() | |
| .await | |
| .map_err(|_| Error::Transport("provider cleanup failed".into()))?; | |
| result | |
| } |