Files
codex-proxy-rs/backend/crates/gateway-plugin/runtime/tests/support/native.rs
T
ZyyandCodex 687ebd0331 feat(plugin): add the complete plugin development and management workflow (#256)
Introduce SDK 0.4, manifest v3, protocol v4, the isolated plugin runtime,
and cpr-plugin packaging CLI for independently maintained plugins.

Support installation, permissions, one active configuration per plugin,
version-specific settings, rollback, management pages, and CLI extensions.
Isolate plugin failures so native gateway startup and requests remain available.

Keep provider registration and UI choices fixed to built-in OpenAI and xAI.
Support nine extension capabilities with permission-scoped model and account
callbacks to the host.

Unify plugin settings and version management, support plugin icons,
and improve narrow layouts. Use the fixed GitHub UI dependency and pnpm 12
for standalone frontend and container builds. Reduce runtime test packaging
cost and align preparation modules with the repository layout.

Co-authored-by: Codex <noreply@openai.com>
2026-09-24 22:48:07 +08:00

215 lines
6.3 KiB
Rust

use std::{collections::BTreeSet, sync::Arc};
use async_trait::async_trait;
use gateway_admin::{
model::{
observability::{CalculatedBillingBreakdown, DashboardWireProfile, ProviderBillingInput},
provider_credentials::{
AuthorizationStarted, CompleteAuthorization, PendingAuthorizationMutation,
PrepareCredentialImport, PrepareCredentialRefresh, PrepareCredentialRotation,
PreparedAuthorizationCommit, PreparedCredentialImport, PreparedCredentialRotation,
ProviderExport, ProviderExportCredentialInput, ProviderModels, ProviderQuota,
ProviderQuotaRequest,
},
},
ports::provider::{
ProviderAdmin, ProviderAdminError, ProviderAdminErrorKind, ProviderAdminRegistry,
},
};
use gateway_core::{
account::ProviderAccountId,
engine::{
AttemptContext,
provider::{
Provider, ProviderCallMetadata, ProviderRegistry, ProviderRequest, ProviderStream,
},
},
error::{ProviderError, ProviderErrorKind},
event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta},
operation::{Operation, OperationKind},
routing::{
ModelCapabilities, ProviderCatalogGeneration, ProviderKind, ProviderModelCapabilities,
UpstreamModelId,
},
upstream::{UpstreamSendState, UpstreamTransport},
};
use serde_json::json;
pub const MODEL: &str = "native-fixture-model";
struct NativeProvider(&'static str);
#[async_trait]
impl Provider for NativeProvider {
fn name(&self) -> &'static str {
self.0
}
fn catalog_generation(&self) -> ProviderCatalogGeneration {
ProviderCatalogGeneration::default()
}
async fn query_model_capabilities(
&self,
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
if self.0 != "openai" {
return Ok(Vec::new());
}
Ok(vec![ProviderModelCapabilities::new(
UpstreamModelId::new(MODEL).unwrap(),
ModelCapabilities::new(BTreeSet::from([OperationKind::Generate]), None),
)])
}
async fn execute(
self: Arc<Self>,
request: ProviderRequest,
context: AttemptContext,
) -> Result<ProviderStream, ProviderError> {
let account = context.required_account().cloned().ok_or_else(|| {
ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::NotSent)
})?;
let candidate = request.candidate();
let model = candidate.upstream_model().cloned().ok_or_else(|| {
ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::NotSent)
})?;
let metadata = ProviderCallMetadata::new(
candidate.provider().clone(),
model,
account,
UpstreamTransport::new("http_sse").unwrap(),
);
let response = ResponseMeta::new("fixture-response", MODEL);
let event = |name: &str, fact| {
ProviderEvent::canonical_with_wire(
vec![fact],
ProtocolWireEvent::json(
"openai",
Some(name.to_owned()),
json!({"type":name,"response":{"id":"fixture-response","model":MODEL}}),
)
.unwrap(),
)
};
Ok(ProviderStream::new(
metadata,
Box::pin(futures::stream::iter([
Ok(event(
"response.created",
GatewayEvent::Started(response.clone()),
)),
Ok(event(
"response.completed",
GatewayEvent::Completed(response),
)),
])),
(),
))
}
}
pub fn provider_registry() -> ProviderRegistry {
ProviderRegistry::new([
Arc::new(NativeProvider("openai")) as Arc<dyn Provider>,
Arc::new(NativeProvider("xai")) as Arc<dyn Provider>,
])
.unwrap()
}
struct NativeAdmin(ProviderKind);
impl NativeAdmin {
fn unsupported() -> ProviderAdminError {
ProviderAdminError::new(ProviderAdminErrorKind::Unsupported)
}
}
#[async_trait]
impl ProviderAdmin for NativeAdmin {
fn provider_kind(&self) -> &ProviderKind {
&self.0
}
async fn account_unavailable(&self, _: &ProviderAccountId) {}
async fn connection_test_operation(
&self,
_: &UpstreamModelId,
_: &str,
) -> Result<Operation, ProviderAdminError> {
Err(Self::unsupported())
}
fn dashboard_wire_profile(&self) -> Option<DashboardWireProfile> {
None
}
fn calculated_billing(
&self,
_: &ProviderBillingInput,
) -> Result<Option<CalculatedBillingBreakdown>, ProviderAdminError> {
Ok(None)
}
async fn prepare_import(
&self,
_: PrepareCredentialImport,
) -> Result<PreparedCredentialImport, ProviderAdminError> {
Err(Self::unsupported())
}
async fn start_authorization(
&self,
_: PendingAuthorizationMutation,
) -> Result<AuthorizationStarted, ProviderAdminError> {
Err(Self::unsupported())
}
async fn complete_authorization(
&self,
_: CompleteAuthorization,
) -> Result<PreparedAuthorizationCommit, ProviderAdminError> {
Err(Self::unsupported())
}
async fn prepare_rotation(
&self,
_: PrepareCredentialRotation,
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
Err(Self::unsupported())
}
async fn prepare_refresh(
&self,
_: PrepareCredentialRefresh,
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
Err(Self::unsupported())
}
async fn quota(&self, _: ProviderQuotaRequest) -> Result<ProviderQuota, ProviderAdminError> {
Err(Self::unsupported())
}
async fn models(
&self,
_: &ProviderAccountId,
_: bool,
) -> Result<ProviderModels, ProviderAdminError> {
Err(Self::unsupported())
}
async fn export_credentials(
&self,
_: Vec<ProviderExportCredentialInput>,
) -> Result<ProviderExport, ProviderAdminError> {
Err(Self::unsupported())
}
}
pub fn admin_registry() -> ProviderAdminRegistry {
ProviderAdminRegistry::new(["openai", "xai"].map(|name| {
Arc::new(NativeAdmin(ProviderKind::new(name).unwrap())) as Arc<dyn ProviderAdmin>
}))
.unwrap()
}