use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashSet;
use std::fmt;
use thiserror::Error;
pub const OLLAMA_CHAT_PATH: &str = "/api/chat";
pub const OLLAMA_RELAY_ORIGIN: &str = "http://127.0.0.1:11434";
pub const OLLAMA_CLOUD_ORIGIN: &str = "https://ollama.com";
pub const OLLAMA_GLM_5_2_MODEL: &str = "glm-5.2";
pub const OPENROUTER_ORIGIN: &str = "https://openrouter.ai";
pub const OPENROUTER_CHAT_PATH: &str = "/api/v1/chat/completions";
pub const DASHSCOPE_ORIGIN: &str = "https://dashscope-intl.aliyuncs.com";
pub const DASHSCOPE_TOKEN_PLAN_ORIGIN: &str = "https://token-plan.ap-southeast-1.maas.aliyuncs.com";
pub const DASHSCOPE_CHAT_PATH: &str = "/compatible-mode/v1/chat/completions";
pub const XAI_ORIGIN: &str = "https://api.x.ai";
pub const XAI_CHAT_PATH: &str = "/v1/chat/completions";
pub const ZAI_ORIGIN: &str = "https://api.z.ai";
pub const ZAI_CHAT_PATH: &str = "/api/paas/v4/chat/completions";
pub const MOONSHOT_ORIGIN: &str = "https://api.moonshot.ai";
pub const MOONSHOT_CHAT_PATH: &str = "/v1/chat/completions";
pub const DEEPSEEK_ORIGIN: &str = "https://api.deepseek.com";
pub const DEEPSEEK_CHAT_PATH: &str = "/chat/completions";
pub const ANTHROPIC_ORIGIN: &str = "https://api.anthropic.com";
pub const ANTHROPIC_CHAT_PATH: &str = "/v1/messages";
pub const ANTHROPIC_API_KEY_HEADER: &str = "x-api-key";
pub const ANTHROPIC_VERSION_HEADER: &str = "anthropic-version";
pub const ANTHROPIC_VERSION: &str = "2023-06-01";
pub const GEMINI_ORIGIN: &str = "https://generativelanguage.googleapis.com";
pub const GEMINI_GENERATE_CONTENT_PATH: &str = "/v1beta/models/{model}:generateContent";
pub const GEMINI_API_KEY_HEADER: &str = "x-goog-api-key";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PhaseKind {
OpenaiSubscription,
OllamaCloud,
OpenrouterApi,
OllamaLocal,
QwenSubscription,
QwenApi,
GrokSubscription,
GrokApi,
ZaiSubscription,
ZaiApi,
KimiSubscription,
KimiApi,
DeepseekApi,
ClaudeSubscription,
ClaudeApi,
GeminiSubscription,
GeminiApi,
DirectMoonshotKimiExtension,
XaiGrokExtension,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct PhaseId(String);
impl PhaseId {
pub const OPENAI_SUBSCRIPTION: &'static str = "openai_subscription";
pub const OLLAMA_CLOUD: &'static str = "ollama_cloud";
pub const OPENROUTER_API: &'static str = "openrouter_api";
pub const OLLAMA_LOCAL: &'static str = "ollama_local";
pub const QWEN_SUBSCRIPTION: &'static str = "qwen_subscription";
pub const QWEN_API: &'static str = "qwen_api";
pub const GROK_SUBSCRIPTION: &'static str = "grok_subscription";
pub const GROK_API: &'static str = "grok_api";
pub const ZAI_SUBSCRIPTION: &'static str = "zai_subscription";
pub const ZAI_API: &'static str = "zai_api";
pub const KIMI_SUBSCRIPTION: &'static str = "kimi_subscription";
pub const KIMI_API: &'static str = "kimi_api";
pub const DEEPSEEK_API: &'static str = "deepseek_api";
pub const CLAUDE_SUBSCRIPTION: &'static str = "claude_subscription";
pub const CLAUDE_API: &'static str = "claude_api";
pub const GEMINI_SUBSCRIPTION: &'static str = "gemini_subscription";
pub const GEMINI_API: &'static str = "gemini_api";
pub fn parse(value: impl Into<String>) -> Result<Self, RouteIdentityError> {
let value = value.into();
if value.is_empty()
|| value.len() > 128
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
{
return Err(RouteIdentityError::InvalidPhaseId);
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for PhaseId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl<'de> Deserialize<'de> for PhaseId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Self::parse(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl PhaseKind {
pub const BUILTIN_ORDER: [Self; 4] = [
Self::OpenaiSubscription,
Self::OllamaCloud,
Self::OpenrouterApi,
Self::OllamaLocal,
];
pub const fn is_builtin(self) -> bool {
matches!(
self,
Self::OpenaiSubscription
| Self::OllamaCloud
| Self::OpenrouterApi
| Self::OllamaLocal
| Self::QwenSubscription
| Self::QwenApi
| Self::GrokSubscription
| Self::GrokApi
| Self::ZaiSubscription
| Self::ZaiApi
| Self::KimiSubscription
| Self::KimiApi
| Self::DeepseekApi
| Self::ClaudeSubscription
| Self::ClaudeApi
| Self::GeminiSubscription
| Self::GeminiApi
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderService {
Openai,
OllamaCloud,
Openrouter,
OllamaLocal,
Qwen,
Grok,
Zai,
MoonshotKimi,
Xai,
Deepseek,
Claude,
Gemini,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransportKind {
HarnessManaged,
OllamaSignedInRelay,
DirectHttps,
OllamaLocalDaemon,
DisabledExtension,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CredentialSourceKind {
HarnessManaged,
OllamaDaemonSession,
SecretRef,
None,
Unconfigured,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CatalogSourceKind {
OpenaiHarnessCatalog,
OllamaCloudCatalog,
OpenrouterCatalog,
OllamaLocalInventory,
QwenCatalog,
GrokCatalog,
ZaiCatalog,
KimiCatalog,
DeepseekCatalog,
ClaudeCatalog,
GeminiCatalog,
ExtensionCatalog,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BillingAuthorityClass {
OpenaiSubscription,
OllamaCloud,
OpenrouterMeteredApi,
LocalCompute,
QwenSubscription,
QwenMeteredApi,
GrokSubscription,
GrokMeteredApi,
ZaiSubscription,
ZaiMeteredApi,
KimiSubscription,
KimiMeteredApi,
DeepseekMeteredApi,
ClaudeSubscription,
ClaudeMeteredApi,
GeminiSubscription,
GeminiMeteredApi,
ExtensionProvider,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelNamespace {
Openai,
OllamaCloud,
Openrouter,
OllamaLocal,
Qwen,
Grok,
Zai,
MoonshotKimi,
Xai,
Deepseek,
Claude,
Gemini,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionLocation {
RemoteCloud,
LocalMachine,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PhasePlacement {
Builtin,
DisabledUnplacedExtension,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MultiAgentCapability {
Native,
NamespaceUnsupported,
Disabled,
}
impl MultiAgentCapability {
pub const fn serves_subagents_natively(self) -> bool {
matches!(self, Self::Native)
}
}
impl PhaseKind {
pub const fn multi_agent_capability(self) -> MultiAgentCapability {
match self {
Self::OpenaiSubscription => MultiAgentCapability::Native,
Self::OllamaCloud
| Self::OpenrouterApi
| Self::OllamaLocal
| Self::QwenSubscription
| Self::QwenApi
| Self::GrokSubscription
| Self::GrokApi
| Self::ZaiSubscription
| Self::ZaiApi
| Self::KimiSubscription
| Self::KimiApi
| Self::DeepseekApi
| Self::ClaudeSubscription
| Self::ClaudeApi
| Self::GeminiSubscription
| Self::GeminiApi
| Self::DirectMoonshotKimiExtension
| Self::XaiGrokExtension => MultiAgentCapability::NamespaceUnsupported,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MultiAgentVersion {
V1,
V2,
Disabled,
}
impl MultiAgentVersion {
pub const fn as_str(self) -> &'static str {
match self {
Self::V1 => "v1",
Self::V2 => "v2",
Self::Disabled => "disabled",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MultiAgentWireApi {
Responses,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ObservedNamespaceCallBehavior {
ReturnsNamespaceField,
BareNameNoNamespace,
FlattenedNamespaceName,
Disabled,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MultiAgentCapabilityProjection {
pub namespace_tools: bool,
pub multi_agent_version: MultiAgentVersion,
pub wire_api: MultiAgentWireApi,
pub observed_namespace_calls: ObservedNamespaceCallBehavior,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MultiAgentNamespace {
Collaboration,
Agents,
}
impl MultiAgentNamespace {
pub const fn as_str(self) -> &'static str {
match self {
Self::Collaboration => "collaboration",
Self::Agents => "agents",
}
}
}
impl PhaseKind {
pub const fn multi_agent_v2_projection(self) -> MultiAgentCapabilityProjection {
match self {
Self::OpenaiSubscription => MultiAgentCapabilityProjection {
namespace_tools: true,
multi_agent_version: MultiAgentVersion::V2,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::ReturnsNamespaceField,
},
Self::OllamaCloud
| Self::OpenrouterApi
| Self::OllamaLocal
| Self::QwenSubscription
| Self::QwenApi
| Self::GrokSubscription
| Self::GrokApi
| Self::ZaiSubscription
| Self::ZaiApi
| Self::KimiSubscription
| Self::KimiApi
| Self::DeepseekApi
| Self::ClaudeSubscription
| Self::ClaudeApi
| Self::GeminiSubscription
| Self::GeminiApi
| Self::DirectMoonshotKimiExtension
| Self::XaiGrokExtension => MultiAgentCapabilityProjection {
namespace_tools: false,
multi_agent_version: MultiAgentVersion::V2,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::BareNameNoNamespace,
},
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EndpointIdentity {
pub origin: String,
pub path: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RouteIdentity {
pub phase: PhaseKind,
pub placement: PhasePlacement,
pub provider: ProviderService,
pub transport: TransportKind,
pub endpoint: EndpointIdentity,
pub credential_source: CredentialSourceKind,
pub credential_ref: Option<String>,
#[serde(default)]
pub credential_refs: Vec<String>,
pub catalog_source: CatalogSourceKind,
pub catalog_ref: String,
pub billing_authority: BillingAuthorityClass,
pub model_namespace: ModelNamespace,
pub model_id: String,
pub execution_location: ExecutionLocation,
pub account_ref: String,
pub capacity_domain_ref: String,
#[serde(default)]
pub local_execution_proof: bool,
#[serde(default)]
pub approved_local_inventory: Vec<String>,
#[serde(default)]
pub reasoning_modes: Vec<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum RouteIdentityError {
#[error("phase identity is invalid")]
InvalidPhaseId,
#[error("route identity is ambiguous or internally inconsistent")]
AmbiguousIdentity,
#[error("route endpoint does not match the frozen transport contract")]
InvalidEndpoint,
#[error("route credential source does not match its transport")]
InvalidCredentialSource,
#[error("local Ollama route lacks local execution and inventory proof")]
MissingLocalProof,
#[error("route reasoning mode claim is invalid")]
InvalidReasoningModes,
#[error("disabled extension cannot be placed or enabled")]
ExtensionMustRemainUnplaced,
}
impl RouteIdentity {
pub fn multi_agent_capability(&self) -> MultiAgentCapability {
if self.placement == PhasePlacement::DisabledUnplacedExtension {
return MultiAgentCapability::Disabled;
}
self.phase.multi_agent_capability()
}
pub fn multi_agent_v2_projection(&self) -> MultiAgentCapabilityProjection {
if self.placement == PhasePlacement::DisabledUnplacedExtension {
return MultiAgentCapabilityProjection {
namespace_tools: false,
multi_agent_version: MultiAgentVersion::Disabled,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::Disabled,
};
}
self.phase.multi_agent_v2_projection()
}
pub fn mav2_namespace_choice(&self) -> MultiAgentNamespace {
match self.phase {
PhaseKind::OpenaiSubscription => MultiAgentNamespace::Collaboration,
PhaseKind::OllamaCloud
| PhaseKind::OpenrouterApi
| PhaseKind::OllamaLocal
| PhaseKind::QwenSubscription
| PhaseKind::QwenApi
| PhaseKind::GrokSubscription
| PhaseKind::GrokApi
| PhaseKind::ZaiSubscription
| PhaseKind::ZaiApi
| PhaseKind::KimiSubscription
| PhaseKind::KimiApi
| PhaseKind::DeepseekApi
| PhaseKind::ClaudeSubscription
| PhaseKind::ClaudeApi
| PhaseKind::GeminiSubscription
| PhaseKind::GeminiApi
| PhaseKind::DirectMoonshotKimiExtension
| PhaseKind::XaiGrokExtension => MultiAgentNamespace::Agents,
}
}
pub fn multi_agent_version_served(&self) -> MultiAgentVersion {
self.multi_agent_v2_projection().multi_agent_version
}
pub fn validate(&self) -> Result<(), RouteIdentityError> {
if !valid_ref(&self.account_ref)
|| !valid_ref(&self.capacity_domain_ref)
|| !valid_ref(&self.catalog_ref)
|| !valid_model_id(&self.model_id)
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
if self.reasoning_modes.len() > 8
|| self.reasoning_modes.iter().any(|mode| !valid_ref(mode))
|| self.reasoning_modes.iter().collect::<HashSet<_>>().len()
!= self.reasoning_modes.len()
{
return Err(RouteIdentityError::InvalidReasoningModes);
}
self.validate_credential_pool()?;
if self.phase.is_builtin() != (self.placement == PhasePlacement::Builtin) {
return Err(RouteIdentityError::ExtensionMustRemainUnplaced);
}
if !self.phase.is_builtin() {
return self.validate_extension();
}
match self.phase {
PhaseKind::OpenaiSubscription => self.validate_openai_subscription(),
PhaseKind::OllamaCloud => self.validate_ollama_cloud(),
PhaseKind::OpenrouterApi => self.validate_openrouter(),
PhaseKind::OllamaLocal => self.validate_ollama_local(),
PhaseKind::QwenSubscription => self.validate_qwen_subscription(),
PhaseKind::QwenApi => self.validate_qwen_api(),
PhaseKind::GrokSubscription => self.validate_grok_subscription(),
PhaseKind::GrokApi => self.validate_grok_api(),
PhaseKind::ZaiSubscription => self.validate_zai_subscription(),
PhaseKind::ZaiApi => self.validate_zai_api(),
PhaseKind::KimiSubscription => self.validate_kimi_subscription(),
PhaseKind::KimiApi => self.validate_kimi_api(),
PhaseKind::DeepseekApi => self.validate_deepseek_api(),
PhaseKind::ClaudeSubscription => self.validate_claude_subscription(),
PhaseKind::ClaudeApi => self.validate_claude_api(),
PhaseKind::GeminiSubscription => self.validate_gemini_subscription(),
PhaseKind::GeminiApi => self.validate_gemini_api(),
PhaseKind::DirectMoonshotKimiExtension | PhaseKind::XaiGrokExtension => {
Err(RouteIdentityError::ExtensionMustRemainUnplaced)
}
}
}
fn validate_credential_pool(&self) -> Result<(), RouteIdentityError> {
if self.credential_refs.is_empty() {
return Ok(());
}
if self.credential_refs.iter().collect::<HashSet<_>>().len() != self.credential_refs.len() {
return Err(RouteIdentityError::AmbiguousIdentity);
}
if self
.credential_refs
.iter()
.any(|reference| !valid_secret_ref(reference))
{
return Err(RouteIdentityError::InvalidCredentialSource);
}
if self.credential_ref.as_deref() != self.credential_refs.first().map(String::as_str) {
return Err(RouteIdentityError::AmbiguousIdentity);
}
Ok(())
}
fn validate_openai_subscription(&self) -> Result<(), RouteIdentityError> {
if self.provider != ProviderService::Openai
|| self.transport != TransportKind::HarnessManaged
|| self.credential_source != CredentialSourceKind::HarnessManaged
|| self.credential_ref.is_some()
|| self.catalog_source != CatalogSourceKind::OpenaiHarnessCatalog
|| self.billing_authority != BillingAuthorityClass::OpenaiSubscription
|| self.model_namespace != ModelNamespace::Openai
|| self.execution_location != ExecutionLocation::RemoteCloud
|| self.endpoint.origin != "harness://codex-app-server"
|| self.endpoint.path != "/responses"
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
Ok(())
}
fn validate_ollama_cloud(&self) -> Result<(), RouteIdentityError> {
if self.provider != ProviderService::OllamaCloud
|| self.catalog_source != CatalogSourceKind::OllamaCloudCatalog
|| self.billing_authority != BillingAuthorityClass::OllamaCloud
|| self.model_namespace != ModelNamespace::OllamaCloud
|| self.execution_location != ExecutionLocation::RemoteCloud
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
match self.transport {
TransportKind::OllamaSignedInRelay => {
if self.endpoint.origin != OLLAMA_RELAY_ORIGIN
|| self.endpoint.path != OLLAMA_CHAT_PATH
{
return Err(RouteIdentityError::InvalidEndpoint);
}
if self.credential_source != CredentialSourceKind::OllamaDaemonSession
|| self.credential_ref.is_some()
|| !valid_ollama_cloud_wire_model(
&self.model_id,
TransportKind::OllamaSignedInRelay,
)
{
return Err(RouteIdentityError::InvalidCredentialSource);
}
}
TransportKind::DirectHttps => {
if self.endpoint.origin != OLLAMA_CLOUD_ORIGIN
|| self.endpoint.path != OLLAMA_CHAT_PATH
{
return Err(RouteIdentityError::InvalidEndpoint);
}
if self.credential_source != CredentialSourceKind::SecretRef
|| self
.credential_ref
.as_deref()
.is_none_or(|value| !valid_secret_ref(value))
|| !valid_ollama_cloud_wire_model(&self.model_id, TransportKind::DirectHttps)
{
return Err(RouteIdentityError::InvalidCredentialSource);
}
}
_ => return Err(RouteIdentityError::AmbiguousIdentity),
}
Ok(())
}
fn validate_openrouter(&self) -> Result<(), RouteIdentityError> {
if self.provider != ProviderService::Openrouter
|| self.transport != TransportKind::DirectHttps
|| self.endpoint.origin != OPENROUTER_ORIGIN
|| self.endpoint.path != OPENROUTER_CHAT_PATH
|| self.credential_source != CredentialSourceKind::SecretRef
|| self
.credential_ref
.as_deref()
.is_none_or(|value| !valid_secret_ref(value))
|| self.catalog_source != CatalogSourceKind::OpenrouterCatalog
|| self.billing_authority != BillingAuthorityClass::OpenrouterMeteredApi
|| self.model_namespace != ModelNamespace::Openrouter
|| self.execution_location != ExecutionLocation::RemoteCloud
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
Ok(())
}
fn validate_ollama_local(&self) -> Result<(), RouteIdentityError> {
if self.provider != ProviderService::OllamaLocal
|| self.transport != TransportKind::OllamaLocalDaemon
|| self.endpoint.origin != OLLAMA_RELAY_ORIGIN
|| self.endpoint.path != OLLAMA_CHAT_PATH
|| self.credential_source != CredentialSourceKind::None
|| self.credential_ref.is_some()
|| self.catalog_source != CatalogSourceKind::OllamaLocalInventory
|| self.billing_authority != BillingAuthorityClass::LocalCompute
|| self.model_namespace != ModelNamespace::OllamaLocal
|| self.execution_location != ExecutionLocation::LocalMachine
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
if !self.local_execution_proof
|| has_ollama_cloud_wire_suffix(&self.model_id)
|| !self
.approved_local_inventory
.iter()
.any(|model| model == &self.model_id && !has_ollama_cloud_wire_suffix(model))
{
return Err(RouteIdentityError::MissingLocalProof);
}
Ok(())
}
fn validate_follow_on_route(
&self,
provider: ProviderService,
origin: &str,
path: &str,
catalog_source: CatalogSourceKind,
billing_authority: BillingAuthorityClass,
namespace: ModelNamespace,
) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route_any(
provider,
&[origin],
path,
catalog_source,
billing_authority,
namespace,
)
}
fn validate_follow_on_route_any(
&self,
provider: ProviderService,
origins: &[&str],
path: &str,
catalog_source: CatalogSourceKind,
billing_authority: BillingAuthorityClass,
namespace: ModelNamespace,
) -> Result<(), RouteIdentityError> {
if self.provider != provider
|| self.transport != TransportKind::DirectHttps
|| !origins.contains(&self.endpoint.origin.as_str())
|| self.endpoint.path != path
|| self.credential_source != CredentialSourceKind::SecretRef
|| self
.credential_ref
.as_deref()
.is_none_or(|value| !valid_secret_ref(value))
|| self.catalog_source != catalog_source
|| self.billing_authority != billing_authority
|| self.model_namespace != namespace
|| self.execution_location != ExecutionLocation::RemoteCloud
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
Ok(())
}
fn validate_qwen_subscription(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route_any(
ProviderService::Qwen,
&[DASHSCOPE_ORIGIN, DASHSCOPE_TOKEN_PLAN_ORIGIN],
DASHSCOPE_CHAT_PATH,
CatalogSourceKind::QwenCatalog,
BillingAuthorityClass::QwenSubscription,
ModelNamespace::Qwen,
)
}
fn validate_qwen_api(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route_any(
ProviderService::Qwen,
&[DASHSCOPE_ORIGIN, DASHSCOPE_TOKEN_PLAN_ORIGIN],
DASHSCOPE_CHAT_PATH,
CatalogSourceKind::QwenCatalog,
BillingAuthorityClass::QwenMeteredApi,
ModelNamespace::Qwen,
)
}
fn validate_grok_subscription(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::Grok,
XAI_ORIGIN,
XAI_CHAT_PATH,
CatalogSourceKind::GrokCatalog,
BillingAuthorityClass::GrokSubscription,
ModelNamespace::Grok,
)
}
fn validate_grok_api(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::Grok,
XAI_ORIGIN,
XAI_CHAT_PATH,
CatalogSourceKind::GrokCatalog,
BillingAuthorityClass::GrokMeteredApi,
ModelNamespace::Grok,
)
}
fn validate_zai_subscription(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::Zai,
ZAI_ORIGIN,
ZAI_CHAT_PATH,
CatalogSourceKind::ZaiCatalog,
BillingAuthorityClass::ZaiSubscription,
ModelNamespace::Zai,
)
}
fn validate_zai_api(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::Zai,
ZAI_ORIGIN,
ZAI_CHAT_PATH,
CatalogSourceKind::ZaiCatalog,
BillingAuthorityClass::ZaiMeteredApi,
ModelNamespace::Zai,
)
}
fn validate_kimi_subscription(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::MoonshotKimi,
MOONSHOT_ORIGIN,
MOONSHOT_CHAT_PATH,
CatalogSourceKind::KimiCatalog,
BillingAuthorityClass::KimiSubscription,
ModelNamespace::MoonshotKimi,
)
}
fn validate_kimi_api(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::MoonshotKimi,
MOONSHOT_ORIGIN,
MOONSHOT_CHAT_PATH,
CatalogSourceKind::KimiCatalog,
BillingAuthorityClass::KimiMeteredApi,
ModelNamespace::MoonshotKimi,
)
}
fn validate_deepseek_api(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::Deepseek,
DEEPSEEK_ORIGIN,
DEEPSEEK_CHAT_PATH,
CatalogSourceKind::DeepseekCatalog,
BillingAuthorityClass::DeepseekMeteredApi,
ModelNamespace::Deepseek,
)
}
fn validate_claude_subscription(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::Claude,
ANTHROPIC_ORIGIN,
ANTHROPIC_CHAT_PATH,
CatalogSourceKind::ClaudeCatalog,
BillingAuthorityClass::ClaudeSubscription,
ModelNamespace::Claude,
)
}
fn validate_claude_api(&self) -> Result<(), RouteIdentityError> {
self.validate_follow_on_route(
ProviderService::Claude,
ANTHROPIC_ORIGIN,
ANTHROPIC_CHAT_PATH,
CatalogSourceKind::ClaudeCatalog,
BillingAuthorityClass::ClaudeMeteredApi,
ModelNamespace::Claude,
)
}
fn validate_gemini_subscription(&self) -> Result<(), RouteIdentityError> {
self.validate_gemini_route(BillingAuthorityClass::GeminiSubscription)
}
fn validate_gemini_api(&self) -> Result<(), RouteIdentityError> {
self.validate_gemini_route(BillingAuthorityClass::GeminiMeteredApi)
}
fn validate_gemini_route(
&self,
billing_authority: BillingAuthorityClass,
) -> Result<(), RouteIdentityError> {
if self.provider != ProviderService::Gemini
|| self.transport != TransportKind::DirectHttps
|| self.endpoint.origin != GEMINI_ORIGIN
|| self.endpoint.path != GEMINI_GENERATE_CONTENT_PATH
|| self.credential_source != CredentialSourceKind::SecretRef
|| self
.credential_ref
.as_deref()
.is_none_or(|value| !valid_secret_ref(value))
|| self.catalog_source != CatalogSourceKind::GeminiCatalog
|| self.billing_authority != billing_authority
|| self.model_namespace != ModelNamespace::Gemini
|| self.execution_location != ExecutionLocation::RemoteCloud
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
Ok(())
}
fn validate_extension(&self) -> Result<(), RouteIdentityError> {
let expected = match self.phase {
PhaseKind::DirectMoonshotKimiExtension => {
(ProviderService::MoonshotKimi, ModelNamespace::MoonshotKimi)
}
PhaseKind::XaiGrokExtension => (ProviderService::Xai, ModelNamespace::Xai),
_ => return Err(RouteIdentityError::ExtensionMustRemainUnplaced),
};
if self.placement != PhasePlacement::DisabledUnplacedExtension
|| self.provider != expected.0
|| self.model_namespace != expected.1
|| self.transport != TransportKind::DisabledExtension
|| self.credential_source != CredentialSourceKind::Unconfigured
|| self.credential_ref.is_some()
|| self.catalog_source != CatalogSourceKind::ExtensionCatalog
|| self.billing_authority != BillingAuthorityClass::ExtensionProvider
{
return Err(RouteIdentityError::ExtensionMustRemainUnplaced);
}
Ok(())
}
}
pub fn ollama_cloud_wire_model(
provider_neutral_model: &str,
transport: TransportKind,
) -> Result<String, RouteIdentityError> {
if !valid_model_id(provider_neutral_model)
|| has_ollama_cloud_wire_suffix(provider_neutral_model)
{
return Err(RouteIdentityError::AmbiguousIdentity);
}
match transport {
TransportKind::OllamaSignedInRelay => Ok(format!("{provider_neutral_model}:cloud")),
TransportKind::DirectHttps => Ok(provider_neutral_model.to_owned()),
_ => Err(RouteIdentityError::AmbiguousIdentity),
}
}
pub fn ollama_cloud_provider_neutral_model(
wire_model: &str,
transport: TransportKind,
) -> Result<String, RouteIdentityError> {
if !valid_model_id(wire_model) {
return Err(RouteIdentityError::AmbiguousIdentity);
}
match transport {
TransportKind::OllamaSignedInRelay => cloud_base_model_id(wire_model)
.map(str::to_owned)
.ok_or(RouteIdentityError::AmbiguousIdentity),
TransportKind::DirectHttps if !has_ollama_cloud_wire_suffix(wire_model) => {
Ok(wire_model.to_owned())
}
_ => Err(RouteIdentityError::AmbiguousIdentity),
}
}
fn valid_ollama_cloud_wire_model(model_id: &str, transport: TransportKind) -> bool {
ollama_cloud_provider_neutral_model(model_id, transport).is_ok()
}
fn cloud_base_model_id(value: &str) -> Option<&str> {
let base = value
.strip_suffix(":cloud")
.or_else(|| value.strip_suffix("-cloud"))?;
(!base.is_empty() && valid_model_id(base) && !has_ollama_cloud_wire_suffix(base))
.then_some(base)
}
fn has_ollama_cloud_wire_suffix(value: &str) -> bool {
value.ends_with(":cloud") || value.ends_with("-cloud")
}
fn valid_ref(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 256
&& value.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/')
})
}
fn valid_model_id(value: &str) -> bool {
valid_ref(value) && !value.contains("..")
}
fn valid_secret_ref(value: &str) -> bool {
if !valid_ref(value) {
return false;
}
if let Some(name) = value.strip_prefix("env:") {
return valid_environment_name(name);
}
[
"local-file-v1:",
"command:",
"keychain:",
"secret-service:",
"credential-manager:",
]
.iter()
.any(|prefix| value.starts_with(prefix))
}
fn valid_environment_name(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 256
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
}
#[cfg(test)]
mod tests {
use super::*;
fn cloud_identity(transport: TransportKind, model_id: &str) -> RouteIdentity {
let direct = transport == TransportKind::DirectHttps;
RouteIdentity {
phase: PhaseKind::OllamaCloud,
placement: PhasePlacement::Builtin,
provider: ProviderService::OllamaCloud,
transport,
endpoint: EndpointIdentity {
origin: if direct {
OLLAMA_CLOUD_ORIGIN
} else {
OLLAMA_RELAY_ORIGIN
}
.to_owned(),
path: OLLAMA_CHAT_PATH.to_owned(),
},
credential_source: if direct {
CredentialSourceKind::SecretRef
} else {
CredentialSourceKind::OllamaDaemonSession
},
credential_ref: direct.then(|| "keychain:ollama-cloud-device".to_owned()),
credential_refs: Vec::new(),
catalog_source: CatalogSourceKind::OllamaCloudCatalog,
catalog_ref: "catalog:v2:ollama-cloud".to_owned(),
billing_authority: BillingAuthorityClass::OllamaCloud,
model_namespace: ModelNamespace::OllamaCloud,
model_id: model_id.to_owned(),
execution_location: ExecutionLocation::RemoteCloud,
account_ref: "ollama-cloud-held".to_owned(),
capacity_domain_ref: "capacity:ollama-cloud-held".to_owned(),
local_execution_proof: false,
approved_local_inventory: Vec::new(),
reasoning_modes: vec!["reasoning".to_owned()],
}
}
#[test]
fn ollama_cloud_wire_model_is_transport_specific_and_single_suffix() {
assert_eq!(
ollama_cloud_wire_model(OLLAMA_GLM_5_2_MODEL, TransportKind::OllamaSignedInRelay),
Ok("glm-5.2:cloud".to_owned())
);
assert_eq!(
ollama_cloud_wire_model(OLLAMA_GLM_5_2_MODEL, TransportKind::DirectHttps),
Ok("glm-5.2".to_owned())
);
assert!(
ollama_cloud_wire_model("glm-5.2:cloud", TransportKind::OllamaSignedInRelay).is_err()
);
assert!(
ollama_cloud_wire_model("qwen3-coder:480b-cloud", TransportKind::OllamaSignedInRelay)
.is_err()
);
assert!(
ollama_cloud_wire_model(OLLAMA_GLM_5_2_MODEL, TransportKind::OllamaLocalDaemon)
.is_err()
);
assert!(
cloud_identity(TransportKind::OllamaSignedInRelay, "glm-5.2:cloud")
.validate()
.is_ok()
);
assert!(
cloud_identity(TransportKind::OllamaSignedInRelay, "qwen3-coder:480b-cloud")
.validate()
.is_ok()
);
assert!(
cloud_identity(TransportKind::OllamaSignedInRelay, "gpt-oss:120b-cloud")
.validate()
.is_ok()
);
assert!(
cloud_identity(TransportKind::OllamaSignedInRelay, "kimi-k2.6:cloud")
.validate()
.is_ok()
);
assert!(
cloud_identity(TransportKind::DirectHttps, "glm-5.2")
.validate()
.is_ok()
);
assert!(
cloud_identity(TransportKind::OllamaSignedInRelay, "glm-5.2:cloud:cloud")
.validate()
.is_err()
);
for invalid in [
"model-cloud-cloud",
"model:cloud-cloud",
"model-cloud:cloud",
"model:cloud:cloud",
] {
assert!(
cloud_identity(TransportKind::OllamaSignedInRelay, invalid)
.validate()
.is_err(),
"accepted non-canonical double suffix {invalid}"
);
}
assert!(
cloud_identity(TransportKind::DirectHttps, "glm-5.2:cloud")
.validate()
.is_err()
);
assert!(
cloud_identity(TransportKind::DirectHttps, "qwen3-coder:480b-cloud")
.validate()
.is_err()
);
assert_eq!(
ollama_cloud_provider_neutral_model(
"qwen3-coder:480b-cloud",
TransportKind::OllamaSignedInRelay
),
Ok("qwen3-coder:480b".to_owned())
);
assert_eq!(
ollama_cloud_provider_neutral_model("glm-5.2", TransportKind::DirectHttps),
Ok("glm-5.2".to_owned())
);
}
#[test]
fn multi_agent_capability_projection_matches_phase_kind() {
assert_eq!(
PhaseKind::OpenaiSubscription.multi_agent_capability(),
MultiAgentCapability::Native
);
assert!(
PhaseKind::OpenaiSubscription
.multi_agent_capability()
.serves_subagents_natively()
);
for phase in [
PhaseKind::OllamaCloud,
PhaseKind::OpenrouterApi,
PhaseKind::OllamaLocal,
PhaseKind::DirectMoonshotKimiExtension,
PhaseKind::XaiGrokExtension,
] {
assert_eq!(
phase.multi_agent_capability(),
MultiAgentCapability::NamespaceUnsupported
);
assert!(!phase.multi_agent_capability().serves_subagents_natively());
}
}
#[test]
fn disabled_extension_route_is_never_native() {
let mut identity = cloud_identity(TransportKind::OllamaSignedInRelay, "glm-5.2");
identity.placement = PhasePlacement::DisabledUnplacedExtension;
assert_eq!(
identity.multi_agent_capability(),
MultiAgentCapability::Disabled
);
assert!(
!identity
.multi_agent_capability()
.serves_subagents_natively()
);
}
#[test]
fn mav2_projection_is_per_route_and_matches_phase_kind() {
let openai = RouteIdentity {
phase: PhaseKind::OpenaiSubscription,
placement: PhasePlacement::Builtin,
provider: ProviderService::Openai,
transport: TransportKind::HarnessManaged,
endpoint: EndpointIdentity {
origin: "harness://codex-app-server".to_owned(),
path: "/responses".to_owned(),
},
credential_source: CredentialSourceKind::HarnessManaged,
credential_ref: None,
credential_refs: Vec::new(),
catalog_source: CatalogSourceKind::OpenaiHarnessCatalog,
catalog_ref: "catalog:v2:openai-harness".to_owned(),
billing_authority: BillingAuthorityClass::OpenaiSubscription,
model_namespace: ModelNamespace::Openai,
model_id: "gpt-5.6-sol".to_owned(),
execution_location: ExecutionLocation::RemoteCloud,
account_ref: "openai-subscription-held".to_owned(),
capacity_domain_ref: "capacity:openai-subscription-held".to_owned(),
local_execution_proof: false,
approved_local_inventory: Vec::new(),
reasoning_modes: vec!["reasoning".to_owned()],
};
assert!(openai.validate().is_ok());
let openai_projection = openai.multi_agent_v2_projection();
assert_eq!(
openai_projection,
MultiAgentCapabilityProjection {
namespace_tools: true,
multi_agent_version: MultiAgentVersion::V2,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::ReturnsNamespaceField,
}
);
assert_eq!(
openai.mav2_namespace_choice(),
MultiAgentNamespace::Collaboration
);
assert_eq!(openai.mav2_namespace_choice().as_str(), "collaboration");
let cloud = cloud_identity(TransportKind::OllamaSignedInRelay, "glm-5.2:cloud");
let cloud_projection = cloud.multi_agent_v2_projection();
assert_eq!(
cloud_projection,
MultiAgentCapabilityProjection {
namespace_tools: false,
multi_agent_version: MultiAgentVersion::V2,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::BareNameNoNamespace,
}
);
assert_eq!(cloud.mav2_namespace_choice(), MultiAgentNamespace::Agents);
assert_eq!(cloud.mav2_namespace_choice().as_str(), "agents");
}
#[test]
fn mav2_projection_for_disabled_extension_is_never_namespace_capable() {
let mut identity = cloud_identity(TransportKind::OllamaSignedInRelay, "glm-5.2");
identity.placement = PhasePlacement::DisabledUnplacedExtension;
assert_eq!(
identity.multi_agent_v2_projection(),
MultiAgentCapabilityProjection {
namespace_tools: false,
multi_agent_version: MultiAgentVersion::Disabled,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::Disabled,
}
);
assert_eq!(
identity.multi_agent_version_served(),
MultiAgentVersion::Disabled
);
}
#[test]
fn credential_pool_invariant_rejects_invalid_entries() {
let mut valid = cloud_identity(TransportKind::DirectHttps, "glm-5.2");
valid.credential_refs = vec![
"keychain:ollama-cloud-device".to_owned(),
"keychain:ollama-cloud-device-2".to_owned(),
];
assert!(valid.validate().is_ok());
let mut duplicate = cloud_identity(TransportKind::DirectHttps, "glm-5.2");
duplicate.credential_refs = vec![
"keychain:ollama-cloud-device".to_owned(),
"keychain:ollama-cloud-device".to_owned(),
];
assert!(duplicate.validate().is_err());
let mut invalid = cloud_identity(TransportKind::DirectHttps, "glm-5.2");
invalid.credential_refs = vec!["not-a-secret-ref".to_owned()];
assert!(invalid.validate().is_err());
let mut fallback = cloud_identity(TransportKind::DirectHttps, "glm-5.2");
fallback.credential_refs = vec![
"keychain:ollama-cloud-device".to_owned(),
"keychain:ollama-cloud-device-2".to_owned(),
];
fallback.credential_ref = Some("keychain:ollama-cloud-device-2".to_owned());
assert!(fallback.validate().is_err());
let mut relay = cloud_identity(TransportKind::OllamaSignedInRelay, "glm-5.2:cloud");
relay.credential_refs = vec!["keychain:ollama-cloud-device".to_owned()];
assert!(relay.validate().is_err());
}
fn follow_on_identity(
phase: PhaseKind,
provider: ProviderService,
origin: &str,
path: &str,
catalog_source: CatalogSourceKind,
billing_authority: BillingAuthorityClass,
namespace: ModelNamespace,
) -> RouteIdentity {
RouteIdentity {
phase,
placement: PhasePlacement::Builtin,
provider,
transport: TransportKind::DirectHttps,
endpoint: EndpointIdentity {
origin: origin.to_owned(),
path: path.to_owned(),
},
credential_source: CredentialSourceKind::SecretRef,
credential_ref: Some("env:STEADYMUX_FOLLOW_ON_KEY".to_owned()),
credential_refs: vec!["env:STEADYMUX_FOLLOW_ON_KEY".to_owned()],
catalog_source,
catalog_ref: "catalog:v2:follow-on".to_owned(),
billing_authority,
model_namespace: namespace,
model_id: "follow-on/fixture".to_owned(),
execution_location: ExecutionLocation::RemoteCloud,
account_ref: "account:follow-on".to_owned(),
capacity_domain_ref: "capacity:follow-on".to_owned(),
local_execution_proof: false,
approved_local_inventory: Vec::new(),
reasoning_modes: Vec::new(),
}
}
#[test]
fn follow_on_provider_phases_validate_as_first_class_routes() {
let cases = [
(
PhaseKind::QwenSubscription,
ProviderService::Qwen,
DASHSCOPE_ORIGIN,
DASHSCOPE_CHAT_PATH,
CatalogSourceKind::QwenCatalog,
BillingAuthorityClass::QwenSubscription,
ModelNamespace::Qwen,
),
(
PhaseKind::QwenApi,
ProviderService::Qwen,
DASHSCOPE_ORIGIN,
DASHSCOPE_CHAT_PATH,
CatalogSourceKind::QwenCatalog,
BillingAuthorityClass::QwenMeteredApi,
ModelNamespace::Qwen,
),
(
PhaseKind::QwenApi,
ProviderService::Qwen,
DASHSCOPE_TOKEN_PLAN_ORIGIN,
DASHSCOPE_CHAT_PATH,
CatalogSourceKind::QwenCatalog,
BillingAuthorityClass::QwenMeteredApi,
ModelNamespace::Qwen,
),
(
PhaseKind::GrokSubscription,
ProviderService::Grok,
XAI_ORIGIN,
XAI_CHAT_PATH,
CatalogSourceKind::GrokCatalog,
BillingAuthorityClass::GrokSubscription,
ModelNamespace::Grok,
),
(
PhaseKind::GrokApi,
ProviderService::Grok,
XAI_ORIGIN,
XAI_CHAT_PATH,
CatalogSourceKind::GrokCatalog,
BillingAuthorityClass::GrokMeteredApi,
ModelNamespace::Grok,
),
(
PhaseKind::ZaiSubscription,
ProviderService::Zai,
ZAI_ORIGIN,
ZAI_CHAT_PATH,
CatalogSourceKind::ZaiCatalog,
BillingAuthorityClass::ZaiSubscription,
ModelNamespace::Zai,
),
(
PhaseKind::ZaiApi,
ProviderService::Zai,
ZAI_ORIGIN,
ZAI_CHAT_PATH,
CatalogSourceKind::ZaiCatalog,
BillingAuthorityClass::ZaiMeteredApi,
ModelNamespace::Zai,
),
(
PhaseKind::KimiSubscription,
ProviderService::MoonshotKimi,
MOONSHOT_ORIGIN,
MOONSHOT_CHAT_PATH,
CatalogSourceKind::KimiCatalog,
BillingAuthorityClass::KimiSubscription,
ModelNamespace::MoonshotKimi,
),
(
PhaseKind::KimiApi,
ProviderService::MoonshotKimi,
MOONSHOT_ORIGIN,
MOONSHOT_CHAT_PATH,
CatalogSourceKind::KimiCatalog,
BillingAuthorityClass::KimiMeteredApi,
ModelNamespace::MoonshotKimi,
),
(
PhaseKind::DeepseekApi,
ProviderService::Deepseek,
DEEPSEEK_ORIGIN,
DEEPSEEK_CHAT_PATH,
CatalogSourceKind::DeepseekCatalog,
BillingAuthorityClass::DeepseekMeteredApi,
ModelNamespace::Deepseek,
),
(
PhaseKind::ClaudeSubscription,
ProviderService::Claude,
ANTHROPIC_ORIGIN,
ANTHROPIC_CHAT_PATH,
CatalogSourceKind::ClaudeCatalog,
BillingAuthorityClass::ClaudeSubscription,
ModelNamespace::Claude,
),
(
PhaseKind::ClaudeApi,
ProviderService::Claude,
ANTHROPIC_ORIGIN,
ANTHROPIC_CHAT_PATH,
CatalogSourceKind::ClaudeCatalog,
BillingAuthorityClass::ClaudeMeteredApi,
ModelNamespace::Claude,
),
(
PhaseKind::GeminiSubscription,
ProviderService::Gemini,
GEMINI_ORIGIN,
GEMINI_GENERATE_CONTENT_PATH,
CatalogSourceKind::GeminiCatalog,
BillingAuthorityClass::GeminiSubscription,
ModelNamespace::Gemini,
),
(
PhaseKind::GeminiApi,
ProviderService::Gemini,
GEMINI_ORIGIN,
GEMINI_GENERATE_CONTENT_PATH,
CatalogSourceKind::GeminiCatalog,
BillingAuthorityClass::GeminiMeteredApi,
ModelNamespace::Gemini,
),
];
for (phase, provider, origin, path, catalog, billing, namespace) in cases {
let identity =
follow_on_identity(phase, provider, origin, path, catalog, billing, namespace);
assert!(identity.validate().is_ok(), "{phase:?} should validate");
assert!(identity.phase.is_builtin(), "{phase:?} is first-class");
assert_eq!(
identity.phase.multi_agent_capability(),
MultiAgentCapability::NamespaceUnsupported
);
assert_eq!(
identity
.multi_agent_v2_projection()
.observed_namespace_calls,
ObservedNamespaceCallBehavior::BareNameNoNamespace
);
assert_eq!(identity.multi_agent_version_served(), MultiAgentVersion::V2);
assert_eq!(
identity.mav2_namespace_choice(),
MultiAgentNamespace::Agents
);
}
}
#[test]
fn claude_routes_validate_with_verified_anthropic_wire_contract() {
for (phase, billing) in [
(
PhaseKind::ClaudeSubscription,
BillingAuthorityClass::ClaudeSubscription,
),
(
PhaseKind::ClaudeApi,
BillingAuthorityClass::ClaudeMeteredApi,
),
] {
let identity = follow_on_identity(
phase,
ProviderService::Claude,
ANTHROPIC_ORIGIN,
ANTHROPIC_CHAT_PATH,
CatalogSourceKind::ClaudeCatalog,
billing,
ModelNamespace::Claude,
);
assert!(identity.validate().is_ok());
assert!(identity.phase.is_builtin(), "Claude is first-class");
assert_eq!(
identity.multi_agent_v2_projection(),
MultiAgentCapabilityProjection {
namespace_tools: false,
multi_agent_version: MultiAgentVersion::V2,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::BareNameNoNamespace,
}
);
assert_eq!(
identity.mav2_namespace_choice(),
MultiAgentNamespace::Agents
);
}
assert_eq!(ANTHROPIC_ORIGIN, "https://api.anthropic.com");
assert_eq!(ANTHROPIC_CHAT_PATH, "/v1/messages");
assert_eq!(ANTHROPIC_API_KEY_HEADER, "x-api-key");
assert_eq!(ANTHROPIC_VERSION_HEADER, "anthropic-version");
assert_eq!(ANTHROPIC_VERSION, "2023-06-01");
assert_eq!(PhaseId::CLAUDE_SUBSCRIPTION, "claude_subscription");
assert_eq!(PhaseId::CLAUDE_API, "claude_api");
let mut wrong_origin = follow_on_identity(
PhaseKind::ClaudeApi,
ProviderService::Claude,
ANTHROPIC_ORIGIN,
ANTHROPIC_CHAT_PATH,
CatalogSourceKind::ClaudeCatalog,
BillingAuthorityClass::ClaudeMeteredApi,
ModelNamespace::Claude,
);
wrong_origin.endpoint = EndpointIdentity {
origin: "https://api.anthropic.example.com".to_owned(),
path: ANTHROPIC_CHAT_PATH.to_owned(),
};
assert!(wrong_origin.validate().is_err());
let mut wrong_billing = follow_on_identity(
PhaseKind::ClaudeApi,
ProviderService::Claude,
ANTHROPIC_ORIGIN,
ANTHROPIC_CHAT_PATH,
CatalogSourceKind::ClaudeCatalog,
BillingAuthorityClass::ClaudeMeteredApi,
ModelNamespace::Claude,
);
wrong_billing.billing_authority = BillingAuthorityClass::ClaudeSubscription;
assert!(wrong_billing.validate().is_err());
}
#[test]
fn gemini_routes_and_verified_generate_content_wire_contract() {
for (phase, billing) in [
(
PhaseKind::GeminiSubscription,
BillingAuthorityClass::GeminiSubscription,
),
(
PhaseKind::GeminiApi,
BillingAuthorityClass::GeminiMeteredApi,
),
] {
let identity = follow_on_identity(
phase,
ProviderService::Gemini,
GEMINI_ORIGIN,
GEMINI_GENERATE_CONTENT_PATH,
CatalogSourceKind::GeminiCatalog,
billing,
ModelNamespace::Gemini,
);
assert!(identity.validate().is_ok());
assert!(identity.phase.is_builtin(), "Gemini is first-class");
assert_eq!(
identity.multi_agent_v2_projection(),
MultiAgentCapabilityProjection {
namespace_tools: false,
multi_agent_version: MultiAgentVersion::V2,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::BareNameNoNamespace,
}
);
assert_eq!(
identity.mav2_namespace_choice(),
MultiAgentNamespace::Agents
);
}
assert_eq!(GEMINI_ORIGIN, "https://generativelanguage.googleapis.com");
assert_eq!(
GEMINI_GENERATE_CONTENT_PATH,
"/v1beta/models/{model}:generateContent"
);
assert_eq!(GEMINI_API_KEY_HEADER, "x-goog-api-key");
assert_eq!(PhaseId::GEMINI_SUBSCRIPTION, "gemini_subscription");
assert_eq!(PhaseId::GEMINI_API, "gemini_api");
let mut wrong_origin = follow_on_identity(
PhaseKind::GeminiApi,
ProviderService::Gemini,
GEMINI_ORIGIN,
GEMINI_GENERATE_CONTENT_PATH,
CatalogSourceKind::GeminiCatalog,
BillingAuthorityClass::GeminiMeteredApi,
ModelNamespace::Gemini,
);
wrong_origin.endpoint.origin = "https://generativelanguage.example.com".to_owned();
assert!(wrong_origin.validate().is_err());
let mut wrong_path = follow_on_identity(
PhaseKind::GeminiApi,
ProviderService::Gemini,
GEMINI_ORIGIN,
GEMINI_GENERATE_CONTENT_PATH,
CatalogSourceKind::GeminiCatalog,
BillingAuthorityClass::GeminiMeteredApi,
ModelNamespace::Gemini,
);
wrong_path.endpoint.path = "/v1beta/models/gemini-2.5-flash:generateContent".to_owned();
assert!(
wrong_path.validate().is_err(),
"the concrete model path is a template the adapter materializes"
);
let mut wrong_billing = follow_on_identity(
PhaseKind::GeminiApi,
ProviderService::Gemini,
GEMINI_ORIGIN,
GEMINI_GENERATE_CONTENT_PATH,
CatalogSourceKind::GeminiCatalog,
BillingAuthorityClass::GeminiMeteredApi,
ModelNamespace::Gemini,
);
wrong_billing.billing_authority = BillingAuthorityClass::GeminiSubscription;
assert!(wrong_billing.validate().is_err());
}
#[test]
fn follow_on_phase_rejects_wrong_provider_or_billing() {
let mut identity = follow_on_identity(
PhaseKind::QwenApi,
ProviderService::Qwen,
DASHSCOPE_ORIGIN,
DASHSCOPE_CHAT_PATH,
CatalogSourceKind::QwenCatalog,
BillingAuthorityClass::QwenMeteredApi,
ModelNamespace::Qwen,
);
assert!(identity.validate().is_ok());
identity.provider = ProviderService::Zai;
assert!(identity.validate().is_err());
let mut billing = follow_on_identity(
PhaseKind::QwenApi,
ProviderService::Qwen,
DASHSCOPE_ORIGIN,
DASHSCOPE_CHAT_PATH,
CatalogSourceKind::QwenCatalog,
BillingAuthorityClass::QwenMeteredApi,
ModelNamespace::Qwen,
);
billing.billing_authority = BillingAuthorityClass::QwenSubscription;
assert!(billing.validate().is_err());
let mut missing = follow_on_identity(
PhaseKind::KimiApi,
ProviderService::MoonshotKimi,
MOONSHOT_ORIGIN,
MOONSHOT_CHAT_PATH,
CatalogSourceKind::KimiCatalog,
BillingAuthorityClass::KimiMeteredApi,
ModelNamespace::MoonshotKimi,
);
missing.credential_ref = None;
missing.credential_refs = Vec::new();
assert!(missing.validate().is_err());
}
#[test]
fn deepseek_api_route_is_first_class_openai_compat() {
let identity = follow_on_identity(
PhaseKind::DeepseekApi,
ProviderService::Deepseek,
DEEPSEEK_ORIGIN,
DEEPSEEK_CHAT_PATH,
CatalogSourceKind::DeepseekCatalog,
BillingAuthorityClass::DeepseekMeteredApi,
ModelNamespace::Deepseek,
);
assert!(identity.validate().is_ok());
assert!(identity.phase.is_builtin(), "DeepSeek API is first-class");
assert_eq!(
identity.phase.multi_agent_capability(),
MultiAgentCapability::NamespaceUnsupported
);
assert_eq!(
identity.multi_agent_v2_projection(),
MultiAgentCapabilityProjection {
namespace_tools: false,
multi_agent_version: MultiAgentVersion::V2,
wire_api: MultiAgentWireApi::Responses,
observed_namespace_calls: ObservedNamespaceCallBehavior::BareNameNoNamespace,
}
);
assert_eq!(
identity.mav2_namespace_choice(),
MultiAgentNamespace::Agents
);
assert_eq!(DEEPSEEK_ORIGIN, "https://api.deepseek.com");
assert_eq!(DEEPSEEK_CHAT_PATH, "/chat/completions");
assert_eq!(PhaseId::DEEPSEEK_API, "deepseek_api");
let mut wrong_origin = identity.clone();
wrong_origin.endpoint = EndpointIdentity {
origin: "https://api.deepseek.example.com".to_owned(),
path: DEEPSEEK_CHAT_PATH.to_owned(),
};
assert!(wrong_origin.validate().is_err());
let mut wrong_billing = identity;
wrong_billing.billing_authority = BillingAuthorityClass::KimiMeteredApi;
assert!(wrong_billing.validate().is_err());
}
#[test]
fn env_secret_refs_restrict_to_resolver_charset() {
for invalid in ["env:has-dash", "env:a.b", "env:a/b", "env:"] {
assert!(
!valid_secret_ref(invalid),
"{invalid} should be rejected as an env secret ref"
);
}
assert!(valid_secret_ref("env:MY_VAR"));
assert!(valid_secret_ref("env:STEADYMUX_FOLLOW_ON_KEY"));
assert!(valid_secret_ref("env:A1_B2"));
assert!(valid_secret_ref("keychain:service/account"));
assert!(valid_secret_ref("command:fetch-token"));
}
}