cut-mp-openai-chat: add OpenAiChat backend, generic reasoning capture, and shared http
Extract shared ureq client construction (with .proxy(None) and .max_redirects(0)), credential reading, failure classification, and secret redaction from messages.rs into crate::http. Add ModelRow::thinking_active so unset_effort "none" counts as thinking-inactive for WithoutThinking. Implement OpenAiChatBackend with generic capture and byte-exact replay of non-standard message/tool_call fields into one ReasoningState, collapsed assistant turns, role: tool messages, finish_reason and usage mapping, and 402/spent-balance/insufficient_quota -> Authentication classification. Remove temporary Cut 2a OpenAiChat refusal arms in daemon.rs, router.rs, and tests/config_document.rs, and wire OpenAiChat into RouterBackend and daemon readiness/serve.
This commit is contained in:
parent
c1650d5271
commit
73aea04fb7
13 changed files with 2716 additions and 177 deletions
|
|
@ -167,7 +167,7 @@ impl ClaudeCodeBackend {
|
|||
);
|
||||
}
|
||||
if request.tool_choice == ToolChoice::Required
|
||||
&& !row.allows_forced_tool_choice(effort.is_some())
|
||||
&& !row.allows_forced_tool_choice(ModelRow::thinking_active(effort))
|
||||
{
|
||||
return failed(
|
||||
FailureKind::InvalidRequest,
|
||||
|
|
|
|||
|
|
@ -442,6 +442,7 @@ fn rig_with_secret(
|
|||
Box::new(FixedSecret(secret)),
|
||||
));
|
||||
let router = RouterBackend::from_backends(
|
||||
[],
|
||||
[],
|
||||
Some(backend.clone()),
|
||||
vec![default_row(MODEL), default_row(OTHER_MODEL)],
|
||||
|
|
@ -1225,7 +1226,8 @@ fn token_comes_from_the_credential_file_not_the_environment() {
|
|||
canary_secret(),
|
||||
));
|
||||
let router =
|
||||
RouterBackend::from_backends([], Some(backend.clone()), vec![default_row(MODEL)]).unwrap();
|
||||
RouterBackend::from_backends([], [], Some(backend.clone()), vec![default_row(MODEL)])
|
||||
.unwrap();
|
||||
let mut door = Door::new();
|
||||
|
||||
// The variable is set and the file is absent: nothing to give the child.
|
||||
|
|
@ -1896,7 +1898,8 @@ fn a_port_that_cannot_spawn_is_a_provider_failure() {
|
|||
canary_token(),
|
||||
canary_secret(),
|
||||
));
|
||||
let router = RouterBackend::from_backends([], Some(backend), vec![default_row(MODEL)]).unwrap();
|
||||
let router =
|
||||
RouterBackend::from_backends([], [], Some(backend), vec![default_row(MODEL)]).unwrap();
|
||||
let mut door = Door::new();
|
||||
let (claim, _) = door.begin(request(vec![user("hi")]));
|
||||
let result = router.execute(claim.call());
|
||||
|
|
@ -2475,7 +2478,7 @@ mod real {
|
|||
canary_secret(),
|
||||
));
|
||||
let router =
|
||||
RouterBackend::from_backends([], Some(backend), vec![default_row(MODEL)]).unwrap();
|
||||
RouterBackend::from_backends([], [], Some(backend), vec![default_row(MODEL)]).unwrap();
|
||||
Fake {
|
||||
_guard: guard,
|
||||
dir,
|
||||
|
|
|
|||
|
|
@ -77,6 +77,10 @@ impl ModelRow {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn thinking_active(effort: Option<&str>) -> bool {
|
||||
effort.is_some_and(|level| level != "none")
|
||||
}
|
||||
|
||||
pub(crate) fn allows_forced_tool_choice(&self, thinking_active: bool) -> bool {
|
||||
match self.forced_tool_choice {
|
||||
ForcedToolChoice::Always => true,
|
||||
|
|
|
|||
|
|
@ -18,8 +18,6 @@ use model_connector::{
|
|||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
#[cfg(unix)]
|
||||
use crate::MessagesConfig;
|
||||
use crate::backend::readiness;
|
||||
use crate::credential::{CredentialTokenSource, TokenSource, credential_ready};
|
||||
#[cfg(target_os = "linux")]
|
||||
|
|
@ -33,6 +31,8 @@ use crate::unit::SystemdUnits;
|
|||
use crate::{
|
||||
ClaudeCodeConfig, ClaudeCodeLimits, ModelRow, ProviderEntry, ProviderWire, StderrSink,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use crate::{MessagesConfig, OpenAiChatConfig};
|
||||
|
||||
const CONFIG_KEY: &str = "runtime";
|
||||
|
||||
|
|
@ -195,8 +195,22 @@ impl ClaudeConnectorConfig {
|
|||
return Err(ConfigError::Invalid("http limits"));
|
||||
}
|
||||
}
|
||||
ProviderWire::OpenAiChat { .. } => {
|
||||
return Err(ConfigError::Invalid("providers"));
|
||||
ProviderWire::OpenAiChat {
|
||||
base_url,
|
||||
strict_unsupported,
|
||||
deadline_ms,
|
||||
max_response_bytes,
|
||||
} => {
|
||||
let is_loopback = validate_base_url(base_url)?;
|
||||
if !is_loopback && entry.credential.is_none() {
|
||||
return Err(ConfigError::Invalid("credential"));
|
||||
}
|
||||
if *deadline_ms == 0 || *max_response_bytes == 0 {
|
||||
return Err(ConfigError::Invalid("http limits"));
|
||||
}
|
||||
if strict_unsupported.iter().any(|kw| !is_trimmed_nonempty(kw)) {
|
||||
return Err(ConfigError::Invalid("strict_unsupported"));
|
||||
}
|
||||
}
|
||||
ProviderWire::ClaudeCodeCli {
|
||||
binary,
|
||||
|
|
@ -456,6 +470,27 @@ pub(crate) fn messages_config_for(entry: &ProviderEntry) -> Option<MessagesConfi
|
|||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn openai_chat_config_for(entry: &ProviderEntry) -> Option<OpenAiChatConfig> {
|
||||
let ProviderWire::OpenAiChat {
|
||||
base_url,
|
||||
strict_unsupported,
|
||||
deadline_ms,
|
||||
max_response_bytes,
|
||||
} = &entry.wire
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
Some(OpenAiChatConfig {
|
||||
provider_id: entry.id.clone(),
|
||||
base_url: base_url.clone(),
|
||||
key_credential: entry.credential.clone(),
|
||||
strict_unsupported: strict_unsupported.clone(),
|
||||
deadline: Duration::from_millis(*deadline_ms),
|
||||
max_response_bytes: *max_response_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// A systemd service unit name: `name.service` or `name@instance.service`.
|
||||
fn is_systemd_unit_name(text: &str) -> bool {
|
||||
if text.len() > 256 {
|
||||
|
|
@ -685,7 +720,7 @@ fn entry_readiness(entry: &ProviderEntry, creds_dir: Option<&Path>) -> Result<()
|
|||
}
|
||||
})
|
||||
}
|
||||
ProviderWire::AnthropicMessages { .. } => {
|
||||
ProviderWire::AnthropicMessages { .. } | ProviderWire::OpenAiChat { .. } => {
|
||||
if let Some(credential) = &entry.credential {
|
||||
let source = token_source_in(creds_dir, credential, "credential");
|
||||
credential_ready(source.as_ref()).map_err(|field| ConfigError::UnusableEntry {
|
||||
|
|
@ -695,7 +730,6 @@ fn entry_readiness(entry: &ProviderEntry, creds_dir: Option<&Path>) -> Result<()
|
|||
}
|
||||
Ok(())
|
||||
}
|
||||
ProviderWire::OpenAiChat { .. } => Err(ConfigError::Invalid("providers")),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1038,6 +1072,7 @@ mod tests {
|
|||
#[cfg(unix)]
|
||||
struct SeenHttp {
|
||||
x_api_key: Option<String>,
|
||||
authorization: Option<String>,
|
||||
body: serde_json::Value,
|
||||
}
|
||||
|
||||
|
|
@ -1086,17 +1121,21 @@ mod tests {
|
|||
}
|
||||
let end = header_end.unwrap_or(buf.len());
|
||||
let headers = String::from_utf8_lossy(&buf[..end]);
|
||||
let x_api_key = headers.lines().skip(1).find_map(|line| {
|
||||
let (k, v) = line.split_once(':')?;
|
||||
k.eq_ignore_ascii_case("x-api-key")
|
||||
.then(|| v.trim().to_string())
|
||||
});
|
||||
let header = |name: &str| {
|
||||
headers.lines().skip(1).find_map(|line| {
|
||||
let (k, v) = line.split_once(':')?;
|
||||
k.eq_ignore_ascii_case(name).then(|| v.trim().to_string())
|
||||
})
|
||||
};
|
||||
let x_api_key = header("x-api-key");
|
||||
let authorization = header("authorization");
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&buf[end..end + content_len]).unwrap();
|
||||
seen_clone
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(SeenHttp { x_api_key, body });
|
||||
seen_clone.lock().unwrap().push(SeenHttp {
|
||||
x_api_key,
|
||||
authorization,
|
||||
body,
|
||||
});
|
||||
let payload = response_json.to_string();
|
||||
let _ = write!(
|
||||
stream,
|
||||
|
|
@ -2067,6 +2106,305 @@ mod tests {
|
|||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn openai_chat_serve_routes_isolates_state_and_checks_readiness() {
|
||||
const SECRET_OAI: &str = "sk-canary-oai-daemon-3333";
|
||||
const SECRET_MSG: &str = "sk-canary-msg-daemon-4444";
|
||||
|
||||
let _env_guard = CREDENTIALS_ENV_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("claude-connector-oai-serve-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let creds = dir.join("creds");
|
||||
std::fs::create_dir_all(&creds).unwrap();
|
||||
std::fs::write(creds.join("oai-cred"), SECRET_OAI).unwrap();
|
||||
std::fs::write(creds.join("msg-cred"), SECRET_MSG).unwrap();
|
||||
let key_file = dir.join("caller.key");
|
||||
let caller_secret = "m".repeat(48);
|
||||
std::fs::write(&key_file, &caller_secret).unwrap();
|
||||
|
||||
let (url_keyed, seen_keyed) = spawn_http_mock(vec![
|
||||
serde_json::json!({
|
||||
"id": "oai_k_1",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"reasoning_content": "oai reasoning",
|
||||
"tool_calls": [{
|
||||
"id": "call_oai_1",
|
||||
"type": "function",
|
||||
"function": {"name": "lookup", "arguments": "{\"q\":\"x\"}"}
|
||||
}]
|
||||
},
|
||||
"finish_reason": "tool_calls"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 5, "completion_tokens": 3}
|
||||
}),
|
||||
serde_json::json!({
|
||||
"id": "oai_k_2",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {"role": "assistant", "content": "replayed ok"},
|
||||
"finish_reason": "stop"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 8, "completion_tokens": 2}
|
||||
}),
|
||||
]);
|
||||
let (url_local, seen_local) = spawn_http_mock(vec![serde_json::json!({
|
||||
"id": "oai_l_1",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {"role": "assistant", "content": "local ok"},
|
||||
"finish_reason": "stop"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 4, "completion_tokens": 2}
|
||||
})]);
|
||||
let (url_msg, seen_msg) = spawn_http_mock(vec![serde_json::json!({
|
||||
"id": "msg_1",
|
||||
"content": [
|
||||
{"type": "thinking", "thinking": "msg thought", "signature": "sig-msg"},
|
||||
{"type": "text", "text": "msg ok"}
|
||||
],
|
||||
"stop_reason": "end_turn",
|
||||
"usage": {"input_tokens": 4, "output_tokens": 2}
|
||||
})]);
|
||||
|
||||
let model_row = |id: &str, provider: &str, upstream: &str| ModelRow {
|
||||
id: id.to_string(),
|
||||
provider: provider.to_string(),
|
||||
upstream: upstream.to_string(),
|
||||
..test_model(id, provider)
|
||||
};
|
||||
|
||||
let config = ClaudeConnectorConfig {
|
||||
listen: "127.0.0.1:0".to_string(),
|
||||
replay_store: dir.join("replay.cc"),
|
||||
max_frame_bytes: 2 << 20,
|
||||
max_connections: 8,
|
||||
socket_timeout_ms: 10_000,
|
||||
max_expiry_skew_ms: 300_000,
|
||||
providers: vec![
|
||||
ProviderEntry {
|
||||
id: "oai-keyed".to_string(),
|
||||
credential: Some("oai-cred".to_string()),
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: format!("{url_keyed}/v1"),
|
||||
strict_unsupported: vec!["minLength".to_string()],
|
||||
deadline_ms: 60_000,
|
||||
max_response_bytes: 16 << 20,
|
||||
},
|
||||
},
|
||||
ProviderEntry {
|
||||
id: "oai-local".to_string(),
|
||||
credential: None,
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: format!("{url_local}/v1"),
|
||||
strict_unsupported: vec![],
|
||||
deadline_ms: 60_000,
|
||||
max_response_bytes: 16 << 20,
|
||||
},
|
||||
},
|
||||
ProviderEntry {
|
||||
id: "msg-entry".to_string(),
|
||||
credential: Some("msg-cred".to_string()),
|
||||
wire: ProviderWire::AnthropicMessages {
|
||||
base_url: url_msg,
|
||||
deadline_ms: 60_000,
|
||||
max_response_bytes: 16 << 20,
|
||||
},
|
||||
},
|
||||
],
|
||||
models: vec![
|
||||
model_row("model-oai-keyed", "oai-keyed", "deepseek-chat"),
|
||||
model_row("model-oai-local", "oai-local", "local-model"),
|
||||
model_row("model-msg", "msg-entry", "claude-upstream"),
|
||||
],
|
||||
callers: vec![CallerConfig {
|
||||
caller_runtime_id: "caller-oai".to_string(),
|
||||
connection_key_file: key_file,
|
||||
connection_key_epoch: 1,
|
||||
allowed_models: vec![
|
||||
"model-oai-keyed".to_string(),
|
||||
"model-oai-local".to_string(),
|
||||
"model-msg".to_string(),
|
||||
],
|
||||
max_concurrent_requests: 4,
|
||||
max_payload_bytes: 1 << 20,
|
||||
max_output_tokens: 32_768,
|
||||
}],
|
||||
lease_socket: None,
|
||||
lease_holders: Vec::new(),
|
||||
lease_max_ms: 3_600_000,
|
||||
};
|
||||
|
||||
// Readiness check fails naming `oai-keyed` when its credential is empty and never leaks secret.
|
||||
std::fs::write(creds.join("oai-cred"), "").unwrap();
|
||||
let bad_ready = readiness_of_in(&config, Some(&creds))
|
||||
.map(drop)
|
||||
.unwrap_err();
|
||||
let rendered = format!("{bad_ready} {bad_ready:?}");
|
||||
assert!(
|
||||
matches!(
|
||||
bad_ready,
|
||||
ConfigError::UnusableEntry { ref id, field: "credential" }
|
||||
if id == "oai-keyed"
|
||||
),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(!rendered.contains(SECRET_OAI), "{rendered}");
|
||||
assert!(!rendered.contains(SECRET_MSG), "{rendered}");
|
||||
std::fs::write(creds.join("oai-cred"), SECRET_OAI).unwrap();
|
||||
assert!(readiness_of_in(&config, Some(&creds)).is_ok());
|
||||
|
||||
let cfg_path = dir.join("connector.cc");
|
||||
write_config(&cfg_path, &config).unwrap();
|
||||
// SAFETY: guarded by CREDENTIALS_ENV_LOCK across all in-process tests touching CREDENTIALS_DIRECTORY.
|
||||
unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", &creds) };
|
||||
|
||||
let (addr_tx, addr_rx) = std::sync::mpsc::channel();
|
||||
let cfg_thread = cfg_path.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = serve_bound_with(
|
||||
&cfg_thread,
|
||||
|addr| {
|
||||
let _ = addr_tx.send(addr);
|
||||
},
|
||||
|_| (),
|
||||
);
|
||||
});
|
||||
let endpoint = addr_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let client = model_connector::ConnectorClient::new(
|
||||
endpoint,
|
||||
&caller_secret,
|
||||
2 << 20,
|
||||
Some(Duration::from_secs(5)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let user_msg = vec![model_connector::InputItem::UserText {
|
||||
text: "hello".to_string(),
|
||||
}];
|
||||
let res_keyed = invoke(
|
||||
&client,
|
||||
"caller-oai",
|
||||
"req-oai-1",
|
||||
"model-oai-keyed",
|
||||
user_msg.clone(),
|
||||
);
|
||||
let res_local = invoke(
|
||||
&client,
|
||||
"caller-oai",
|
||||
"req-oai-local",
|
||||
"model-oai-local",
|
||||
user_msg.clone(),
|
||||
);
|
||||
let res_msg = invoke(
|
||||
&client,
|
||||
"caller-oai",
|
||||
"req-msg-1",
|
||||
"model-msg",
|
||||
user_msg.clone(),
|
||||
);
|
||||
|
||||
for (res, expected_provider, expected_model) in [
|
||||
(&res_keyed, "oai-keyed", "model-oai-keyed"),
|
||||
(&res_local, "oai-local", "model-oai-local"),
|
||||
(&res_msg, "msg-entry", "model-msg"),
|
||||
] {
|
||||
let model_connector::TransportDisposition::Transported { receipt, .. } =
|
||||
&res.disposition
|
||||
else {
|
||||
panic!("expected transported for {expected_provider}: {res:?}");
|
||||
};
|
||||
assert_eq!(receipt.provider, expected_provider);
|
||||
assert_eq!(receipt.model, expected_model);
|
||||
let dbg = format!("{res:?}");
|
||||
assert!(!dbg.contains(SECRET_OAI));
|
||||
assert!(!dbg.contains(SECRET_MSG));
|
||||
}
|
||||
|
||||
// Replay own OpenAiChat state + tool result back to oai-keyed succeeds.
|
||||
let mut own_replay = user_msg.clone();
|
||||
own_replay.extend(res_keyed.transcript_items());
|
||||
own_replay.push(model_connector::InputItem::ToolResult {
|
||||
call_id: "call_oai_1".to_string(),
|
||||
output: "found".to_string(),
|
||||
});
|
||||
let res_replayed = invoke(
|
||||
&client,
|
||||
"caller-oai",
|
||||
"req-oai-2",
|
||||
"model-oai-keyed",
|
||||
own_replay,
|
||||
);
|
||||
assert!(matches!(
|
||||
res_replayed.disposition,
|
||||
model_connector::TransportDisposition::Transported { .. }
|
||||
));
|
||||
|
||||
// Foreign ReasoningState between OpenAiChat and AnthropicMessages is refused in-flight.
|
||||
let mut oai_to_msg = user_msg.clone();
|
||||
oai_to_msg.extend(res_keyed.transcript_items());
|
||||
let refused_msg = invoke(
|
||||
&client,
|
||||
"caller-oai",
|
||||
"req-cross-1",
|
||||
"model-msg",
|
||||
oai_to_msg,
|
||||
);
|
||||
assert_eq!(
|
||||
refused_msg.disposition,
|
||||
model_connector::TransportDisposition::Refused(
|
||||
model_connector::Refusal::ForeignReasoningState
|
||||
)
|
||||
);
|
||||
|
||||
let mut msg_to_oai = user_msg;
|
||||
msg_to_oai.extend(res_msg.transcript_items());
|
||||
let refused_oai = invoke(
|
||||
&client,
|
||||
"caller-oai",
|
||||
"req-cross-2",
|
||||
"model-oai-keyed",
|
||||
msg_to_oai,
|
||||
);
|
||||
assert_eq!(
|
||||
refused_oai.disposition,
|
||||
model_connector::TransportDisposition::Refused(
|
||||
model_connector::Refusal::ForeignReasoningState
|
||||
)
|
||||
);
|
||||
|
||||
let sk = seen_keyed.lock().unwrap();
|
||||
assert_eq!(sk.len(), 2);
|
||||
assert_eq!(
|
||||
sk[0].authorization.as_deref(),
|
||||
Some(format!("Bearer {SECRET_OAI}").as_str())
|
||||
);
|
||||
assert_eq!(sk[0].body["model"], "deepseek-chat");
|
||||
assert_eq!(
|
||||
sk[1].body["messages"][2]["reasoning_content"],
|
||||
"oai reasoning"
|
||||
);
|
||||
|
||||
let sl = seen_local.lock().unwrap();
|
||||
assert_eq!(sl.len(), 1);
|
||||
assert_eq!(sl[0].authorization, None);
|
||||
assert_eq!(sl[0].body["model"], "local-model");
|
||||
|
||||
let sm = seen_msg.lock().unwrap();
|
||||
assert_eq!(sm.len(), 1);
|
||||
assert_eq!(sm[0].x_api_key.as_deref(), Some(SECRET_MSG));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod prompt_dir {
|
||||
use std::os::unix::fs::{PermissionsExt, chown, symlink};
|
||||
|
|
|
|||
233
crates/claude-connector/src/http.rs
Normal file
233
crates/claude-connector/src/http.rs
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use model_connector::{FailureKind, TransportEvent, TransportOutcome, Usage};
|
||||
use serde_json::Value;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::credential::TokenSource;
|
||||
|
||||
/// The longest provider message a receipt carries.
|
||||
pub(crate) const MESSAGE_BYTES: usize = 2048;
|
||||
|
||||
/// Builds the HTTP client used by every HTTP backend: global deadline, status
|
||||
/// errors returned as responses, no redirects (so credentials cannot leak to a
|
||||
/// redirect target), and no environment proxy lookup.
|
||||
pub(crate) fn build_agent(deadline: Duration) -> ureq::Agent {
|
||||
ureq::Agent::config_builder()
|
||||
.timeout_global(Some(deadline))
|
||||
.http_status_as_error(false)
|
||||
.max_redirects(0)
|
||||
.proxy(None)
|
||||
.build()
|
||||
.into()
|
||||
}
|
||||
|
||||
pub(crate) fn read_key(
|
||||
keys: Option<&dyn TokenSource>,
|
||||
label: &str,
|
||||
) -> Result<Option<Zeroizing<String>>, (Vec<TransportEvent>, TransportOutcome)> {
|
||||
match keys {
|
||||
Some(source) => match source.read() {
|
||||
Some(key) => Ok(Some(key)),
|
||||
None => Err(failed(
|
||||
FailureKind::Authentication,
|
||||
format!("{label}: the connector has no API key"),
|
||||
Some(zero_usage()),
|
||||
)),
|
||||
},
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Persona drain treats `RateLimited`, `Unavailable`, `Timeout` and
|
||||
/// `Authentication` as outages and every other kind as a strike against the
|
||||
/// line the turn was waking on. A fault of the key's account or of the path to
|
||||
/// the API is never the line's.
|
||||
///
|
||||
/// 402 is a credential-level fault, not a transient one: the key's account
|
||||
/// cannot pay and only the operator fixes it, as with 401 and 403, so it is
|
||||
/// `Authentication`; `Unavailable` would promise that it heals itself.
|
||||
pub(crate) fn kind_of_status(status: u16) -> FailureKind {
|
||||
match status {
|
||||
401..=403 => FailureKind::Authentication,
|
||||
408 | 504 => FailureKind::Timeout,
|
||||
429 => FailureKind::RateLimited,
|
||||
300..=399 | 500..=599 => FailureKind::Unavailable,
|
||||
400 => FailureKind::InvalidRequest,
|
||||
_ => FailureKind::Provider,
|
||||
}
|
||||
}
|
||||
|
||||
/// A failure the provider answered: its own type/code and message, bounded and
|
||||
/// scrubbed of any credential bytes.
|
||||
pub(crate) fn http_failure(
|
||||
label: &str,
|
||||
status: u16,
|
||||
body: &[u8],
|
||||
secret: Option<&str>,
|
||||
spend_exhausted: impl FnOnce(u16, &Value) -> bool,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let parsed: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
|
||||
let error = if parsed["error"].is_object() {
|
||||
&parsed["error"]
|
||||
} else {
|
||||
&parsed
|
||||
};
|
||||
let mut message = format!("{label}: HTTP {status}");
|
||||
if let Some(kind) = error["type"].as_str().or_else(|| error["code"].as_str()) {
|
||||
message.push(' ');
|
||||
message.push_str(kind);
|
||||
}
|
||||
if let Some(text) = error["message"].as_str().filter(|text| !text.is_empty()) {
|
||||
message.push_str(": ");
|
||||
message.push_str(text);
|
||||
}
|
||||
if let Some(secret) = secret.filter(|s| !s.is_empty()) {
|
||||
message = message.replace(secret, "[redacted]");
|
||||
}
|
||||
let kind = if spend_exhausted(status, error) {
|
||||
FailureKind::Authentication
|
||||
} else {
|
||||
kind_of_status(status)
|
||||
};
|
||||
failed(kind, bounded(message), None)
|
||||
}
|
||||
|
||||
/// A failure before an answer: the deadline, the size cap, the connection.
|
||||
pub(crate) fn transport_failure(
|
||||
label: &str,
|
||||
error: &ureq::Error,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let (kind, what) = match error {
|
||||
ureq::Error::Timeout(_) => (
|
||||
FailureKind::Timeout,
|
||||
"the deadline passed before a response",
|
||||
),
|
||||
ureq::Error::BodyExceedsLimit(_) => {
|
||||
(FailureKind::Provider, "the response passed its size cap")
|
||||
}
|
||||
ureq::Error::BadUri(_) | ureq::Error::Http(_) | ureq::Error::InvalidProxyUrl => {
|
||||
(FailureKind::Provider, "the request could not be built")
|
||||
}
|
||||
_ => (FailureKind::Unavailable, "the API could not be reached"),
|
||||
};
|
||||
failed(kind, format!("{label}: {what}"), None)
|
||||
}
|
||||
|
||||
pub(crate) fn bounded(mut message: String) -> String {
|
||||
if message.len() > MESSAGE_BYTES {
|
||||
let mut end = MESSAGE_BYTES;
|
||||
while !message.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
message.truncate(end);
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
pub(crate) fn zero_usage() -> Usage {
|
||||
Usage {
|
||||
input_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn failed(
|
||||
kind: FailureKind,
|
||||
message: String,
|
||||
usage: Option<Usage>,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
(
|
||||
Vec::new(),
|
||||
TransportOutcome::Failed {
|
||||
kind,
|
||||
message,
|
||||
usage,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) static PROXY_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::{PROXY_ENV_LOCK, build_agent};
|
||||
|
||||
struct EnvRestore {
|
||||
http: Option<std::ffi::OsString>,
|
||||
https: Option<std::ffi::OsString>,
|
||||
}
|
||||
|
||||
impl Drop for EnvRestore {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: guarded by PROXY_ENV_LOCK across tests touching proxy env vars.
|
||||
unsafe {
|
||||
match &self.http {
|
||||
Some(v) => std::env::set_var("HTTP_PROXY", v),
|
||||
None => std::env::remove_var("HTTP_PROXY"),
|
||||
}
|
||||
match &self.https {
|
||||
Some(v) => std::env::set_var("HTTPS_PROXY", v),
|
||||
None => std::env::remove_var("HTTPS_PROXY"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_agent_ignores_http_and_https_proxy_env() {
|
||||
let _guard = PROXY_ENV_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let _restore = EnvRestore {
|
||||
http: std::env::var_os("HTTP_PROXY"),
|
||||
https: std::env::var_os("HTTPS_PROXY"),
|
||||
};
|
||||
|
||||
let proxy_listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
proxy_listener.set_nonblocking(true).unwrap();
|
||||
let proxy_url = format!("http://{}", proxy_listener.local_addr().unwrap());
|
||||
|
||||
let target_listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let target_url = format!("http://{}/ok", target_listener.local_addr().unwrap());
|
||||
let target_hits = Arc::new(AtomicUsize::new(0));
|
||||
let hits = target_hits.clone();
|
||||
let handle = thread::spawn(move || {
|
||||
let (mut stream, _) = target_listener.accept().unwrap();
|
||||
hits.fetch_add(1, Ordering::SeqCst);
|
||||
let mut buf = [0u8; 512];
|
||||
let _ = stream.read(&mut buf);
|
||||
let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");
|
||||
});
|
||||
|
||||
// SAFETY: guarded by PROXY_ENV_LOCK.
|
||||
unsafe {
|
||||
std::env::set_var("HTTP_PROXY", &proxy_url);
|
||||
std::env::set_var("HTTPS_PROXY", &proxy_url);
|
||||
}
|
||||
|
||||
let agent = build_agent(Duration::from_secs(5));
|
||||
let mut resp = agent.get(&target_url).call().unwrap();
|
||||
assert_eq!(resp.status().as_u16(), 200);
|
||||
let body = resp.body_mut().read_to_string().unwrap();
|
||||
assert_eq!(body, "ok");
|
||||
|
||||
handle.join().unwrap();
|
||||
assert_eq!(target_hits.load(Ordering::SeqCst), 1);
|
||||
assert!(
|
||||
matches!(proxy_listener.accept(), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock),
|
||||
"proxy listener must never be contacted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ mod config;
|
|||
mod credential;
|
||||
mod daemon;
|
||||
mod handle;
|
||||
mod http;
|
||||
mod launch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod lease;
|
||||
|
|
@ -16,6 +17,7 @@ mod lease;
|
|||
pub mod lease_run;
|
||||
mod messages;
|
||||
mod meter;
|
||||
mod openai_chat;
|
||||
mod process;
|
||||
mod quota;
|
||||
mod router;
|
||||
|
|
@ -43,6 +45,7 @@ pub use lease::{
|
|||
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
|
||||
};
|
||||
pub use messages::{MessagesBackend, MessagesConfig};
|
||||
pub use openai_chat::{OpenAiChatBackend, OpenAiChatConfig};
|
||||
#[cfg(unix)]
|
||||
pub use process::StdProcessPort;
|
||||
pub use process::{ProcessPort, RunningChild, StdoutRead};
|
||||
|
|
|
|||
|
|
@ -47,13 +47,14 @@ use model_connector::{
|
|||
TransportEvent, TransportEventPayload, TransportOutcome, Usage,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::config::{ModelRow, OutputSchemaSupport};
|
||||
use crate::credential::{CredentialTokenSource, TokenSource, credential_ready};
|
||||
use crate::http::{build_agent, failed, http_failure, read_key, transport_failure, zero_usage};
|
||||
|
||||
const API_VERSION: &str = "2026-10-21";
|
||||
/// The longest provider message a receipt carries.
|
||||
const MESSAGE_BYTES: usize = 2048;
|
||||
const BACKEND_LABEL: &str = "anthropic-messages";
|
||||
|
||||
/// What the connector's binary hands the backend.
|
||||
#[derive(Debug, Clone)]
|
||||
|
|
@ -91,15 +92,9 @@ impl MessagesBackend {
|
|||
}
|
||||
|
||||
pub(crate) fn with_parts(config: MessagesConfig, keys: Option<Box<dyn TokenSource>>) -> Self {
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(config.deadline))
|
||||
.http_status_as_error(false)
|
||||
.max_redirects(0)
|
||||
.build()
|
||||
.into();
|
||||
Self {
|
||||
provider_id: config.provider_id,
|
||||
agent,
|
||||
agent: build_agent(config.deadline),
|
||||
base_url: config.base_url,
|
||||
keys,
|
||||
max_response_bytes: config.max_response_bytes as u64,
|
||||
|
|
@ -122,18 +117,9 @@ impl MessagesBackend {
|
|||
request: &ProviderRequest,
|
||||
row: &ModelRow,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let key = match &self.keys {
|
||||
Some(source) => match source.read() {
|
||||
Some(key) => Some(key),
|
||||
None => {
|
||||
return failed(
|
||||
FailureKind::Authentication,
|
||||
"anthropic-messages: the connector has no API key".to_string(),
|
||||
Some(zero_usage()),
|
||||
);
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
let key = match read_key(self.keys.as_deref(), BACKEND_LABEL) {
|
||||
Ok(key) => key,
|
||||
Err(failure) => return failure,
|
||||
};
|
||||
let body = match render(request, &self.provider_id, row).and_then(|body| {
|
||||
serde_json::to_vec(&body).map_err(|_| "the request could not be encoded".to_string())
|
||||
|
|
@ -142,7 +128,7 @@ impl MessagesBackend {
|
|||
Err(message) => {
|
||||
return failed(
|
||||
FailureKind::InvalidRequest,
|
||||
format!("anthropic-messages: {message}"),
|
||||
format!("{BACKEND_LABEL}: {message}"),
|
||||
Some(zero_usage()),
|
||||
);
|
||||
}
|
||||
|
|
@ -158,7 +144,7 @@ impl MessagesBackend {
|
|||
let sent = post.send(&body[..]);
|
||||
let mut response = match sent {
|
||||
Ok(response) => response,
|
||||
Err(error) => return transport_failure(&error),
|
||||
Err(error) => return transport_failure(BACKEND_LABEL, &error),
|
||||
};
|
||||
let status = response.status().as_u16();
|
||||
let text = match response
|
||||
|
|
@ -168,10 +154,16 @@ impl MessagesBackend {
|
|||
.read_to_vec()
|
||||
{
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => return transport_failure(&error),
|
||||
Err(error) => return transport_failure(BACKEND_LABEL, &error),
|
||||
};
|
||||
if !(200..300).contains(&status) {
|
||||
return http_failure(status, &text);
|
||||
return http_failure(
|
||||
BACKEND_LABEL,
|
||||
status,
|
||||
&text,
|
||||
key.as_deref().map(Zeroizing::as_str),
|
||||
spend_exhausted,
|
||||
);
|
||||
}
|
||||
let required = request.tool_choice == ToolChoice::Required && !request.tools.is_empty();
|
||||
match parse(&text, required) {
|
||||
|
|
@ -205,7 +197,7 @@ impl MessagesBackend {
|
|||
fn render(request: &ProviderRequest, provider_id: &str, row: &ModelRow) -> Result<Value, String> {
|
||||
let effort = row.resolve_effort(request.reasoning_effort)?;
|
||||
if request.tool_choice == ToolChoice::Required
|
||||
&& !row.allows_forced_tool_choice(effort.is_some())
|
||||
&& !row.allows_forced_tool_choice(ModelRow::thinking_active(effort))
|
||||
{
|
||||
return Err(format!(
|
||||
"model {} does not accept a required tool choice",
|
||||
|
|
@ -501,25 +493,6 @@ fn usage_of(usage: &Value) -> Option<Usage> {
|
|||
|
||||
// ---- failures ----
|
||||
|
||||
/// The Persona drain treats `RateLimited`, `Unavailable`, `Timeout` and
|
||||
/// `Authentication` as outages and every other kind as a strike against the
|
||||
/// line the turn was waking on. A fault of the key's account or of the path to
|
||||
/// the API is never the line's.
|
||||
///
|
||||
/// 402 is a credential-level fault, not a transient one: the key's account
|
||||
/// cannot pay and only the operator fixes it, as with 401 and 403, so it is
|
||||
/// `Authentication`; `Unavailable` would promise that it heals itself.
|
||||
fn kind_of_status(status: u16) -> FailureKind {
|
||||
match status {
|
||||
401..=403 => FailureKind::Authentication,
|
||||
408 | 504 => FailureKind::Timeout,
|
||||
429 => FailureKind::RateLimited,
|
||||
300..=399 | 500..=599 => FailureKind::Unavailable,
|
||||
400 => FailureKind::InvalidRequest,
|
||||
_ => FailureKind::Provider,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixed beginnings of the provider's 400 messages for a spent balance
|
||||
/// and a reached Console spend limit, lower-cased.
|
||||
const SPEND_EXHAUSTED: [&str; 2] = [
|
||||
|
|
@ -527,8 +500,9 @@ const SPEND_EXHAUSTED: [&str; 2] = [
|
|||
"you have reached your specified api usage limits",
|
||||
];
|
||||
|
||||
fn spend_exhausted(error: &Value) -> bool {
|
||||
error["type"].as_str() == Some("invalid_request_error")
|
||||
fn spend_exhausted(status: u16, error: &Value) -> bool {
|
||||
status == 400
|
||||
&& error["type"].as_str() == Some("invalid_request_error")
|
||||
&& error["message"].as_str().is_some_and(|text| {
|
||||
let text = text.trim_start().to_lowercase();
|
||||
SPEND_EXHAUSTED
|
||||
|
|
@ -537,79 +511,12 @@ fn spend_exhausted(error: &Value) -> bool {
|
|||
})
|
||||
}
|
||||
|
||||
/// A failure the provider answered: its own type and message, bounded.
|
||||
#[cfg(test)]
|
||||
use crate::http::{MESSAGE_BYTES, bounded};
|
||||
|
||||
#[cfg(test)]
|
||||
fn http_failure(status: u16, body: &[u8]) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let parsed: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
|
||||
let error = &parsed["error"];
|
||||
let mut message = format!("anthropic-messages: HTTP {status}");
|
||||
if let Some(kind) = error["type"].as_str() {
|
||||
message.push(' ');
|
||||
message.push_str(kind);
|
||||
}
|
||||
if let Some(text) = error["message"].as_str().filter(|text| !text.is_empty()) {
|
||||
message.push_str(": ");
|
||||
message.push_str(text);
|
||||
}
|
||||
let kind = if status == 400 && spend_exhausted(error) {
|
||||
FailureKind::Authentication
|
||||
} else {
|
||||
kind_of_status(status)
|
||||
};
|
||||
failed(kind, bounded(message), None)
|
||||
}
|
||||
|
||||
/// A failure before an answer: the deadline, the size cap, the connection.
|
||||
fn transport_failure(error: &ureq::Error) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let (kind, what) = match error {
|
||||
ureq::Error::Timeout(_) => (
|
||||
FailureKind::Timeout,
|
||||
"the deadline passed before a response",
|
||||
),
|
||||
ureq::Error::BodyExceedsLimit(_) => {
|
||||
(FailureKind::Provider, "the response passed its size cap")
|
||||
}
|
||||
ureq::Error::BadUri(_) | ureq::Error::Http(_) | ureq::Error::InvalidProxyUrl => {
|
||||
(FailureKind::Provider, "the request could not be built")
|
||||
}
|
||||
_ => (FailureKind::Unavailable, "the API could not be reached"),
|
||||
};
|
||||
failed(kind, format!("anthropic-messages: {what}"), None)
|
||||
}
|
||||
|
||||
fn bounded(mut message: String) -> String {
|
||||
if message.len() > MESSAGE_BYTES {
|
||||
let mut end = MESSAGE_BYTES;
|
||||
while !message.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
message.truncate(end);
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
fn zero_usage() -> Usage {
|
||||
Usage {
|
||||
input_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: 0,
|
||||
reasoning_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(
|
||||
kind: FailureKind,
|
||||
message: String,
|
||||
usage: Option<Usage>,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
(
|
||||
Vec::new(),
|
||||
TransportOutcome::Failed {
|
||||
kind,
|
||||
message,
|
||||
usage,
|
||||
},
|
||||
)
|
||||
crate::http::http_failure(BACKEND_LABEL, status, body, None, spend_exhausted)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -1187,8 +1187,13 @@ fn a_call_through_the_serve_loop_reaches_the_caller_as_a_valid_result() {
|
|||
);
|
||||
let (url, _) = mock(vec![(200, reply)]);
|
||||
let router = Arc::new(
|
||||
RouterBackend::from_backends([backend(url, Some(KEY))], None, vec![default_row(MODEL)])
|
||||
.unwrap(),
|
||||
RouterBackend::from_backends(
|
||||
[backend(url, Some(KEY))],
|
||||
[],
|
||||
None,
|
||||
vec![default_row(MODEL)],
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
|
|
|
|||
625
crates/claude-connector/src/openai_chat.rs
Normal file
625
crates/claude-connector/src/openai_chat.rs
Normal file
|
|
@ -0,0 +1,625 @@
|
|||
//! The OpenAI-compatible Chat Completions backend: one non-streaming
|
||||
//! `POST {base_url}/chat/completions` per call against a configured `base_url`
|
||||
//! with an optional systemd API key credential (sent as `Authorization: Bearer`,
|
||||
//! omitted only for keyless loopback HTTP).
|
||||
//!
|
||||
//! No vendor dialect enum lives here. Non-standard non-null fields on the
|
||||
//! assistant message (such as DeepSeek `reasoning_content`) and on each tool
|
||||
//! call (such as Gemini `extra_content.google.thought_signature`) are captured
|
||||
//! generically into one opaque `ReasoningState` JSON object
|
||||
//! `{"message":{...},"tool_calls":{call_id:{...}}}` and restored byte-exact on
|
||||
//! replay onto the same assistant message and tool calls. Foreign provider
|
||||
//! state is refused before sending.
|
||||
//!
|
||||
//! Per-model `ModelRow` policies govern `efforts` / `unset_effort`,
|
||||
//! `forced_tool_choice` (using `ModelRow::thinking_active` so
|
||||
//! `unset_effort: Some("none")` counts as thinking-inactive), `output_schema`,
|
||||
//! and `strict_tools`.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use model_connector::{
|
||||
FailureKind, InputItem, ProviderRequest, StopReason, ToolChoice, TransportEvent,
|
||||
TransportEventPayload, TransportOutcome, Usage,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::config::{ModelRow, OutputSchemaSupport};
|
||||
use crate::credential::{CredentialTokenSource, TokenSource, credential_ready};
|
||||
use crate::http::{build_agent, failed, http_failure, read_key, transport_failure, zero_usage};
|
||||
|
||||
const BACKEND_LABEL: &str = "openai-chat";
|
||||
|
||||
const STANDARD_MESSAGE_FIELDS: &[&str] = &[
|
||||
"role",
|
||||
"content",
|
||||
"tool_calls",
|
||||
"refusal",
|
||||
"annotations",
|
||||
"audio",
|
||||
"function_call",
|
||||
];
|
||||
|
||||
const STANDARD_TOOL_CALL_FIELDS: &[&str] = &["id", "type", "function", "index"];
|
||||
|
||||
/// What the connector's config hands the OpenAI-compatible backend.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OpenAiChatConfig {
|
||||
/// Provider tag written on receipts and matched on reasoning state items.
|
||||
pub provider_id: String,
|
||||
/// Base URL for the Chat Completions API (`https://...` or loopback `http://...`),
|
||||
/// including any version path segment (e.g. `/v1` or `/v1beta/openai`).
|
||||
pub base_url: String,
|
||||
/// The name of the systemd credential that holds the bearer token, under
|
||||
/// `$CREDENTIALS_DIRECTORY`; `None` only for a loopback HTTP `base_url`.
|
||||
pub key_credential: Option<String>,
|
||||
/// Schema keywords to strip-and-describe in strict tool mode (handled in Cut 4).
|
||||
pub strict_unsupported: Vec<String>,
|
||||
/// The whole call, connect to the last byte of the response.
|
||||
pub deadline: Duration,
|
||||
/// The largest response body read.
|
||||
pub max_response_bytes: usize,
|
||||
}
|
||||
|
||||
/// Answers each call with one HTTP request to `POST {base_url}/chat/completions`.
|
||||
pub struct OpenAiChatBackend {
|
||||
provider_id: String,
|
||||
agent: ureq::Agent,
|
||||
endpoint: String,
|
||||
keys: Option<Box<dyn TokenSource>>,
|
||||
max_response_bytes: u64,
|
||||
}
|
||||
|
||||
impl OpenAiChatBackend {
|
||||
/// The backend over the configured base URL, with an optional bearer token
|
||||
/// read from the credential `config.key_credential` names.
|
||||
pub fn new(config: OpenAiChatConfig) -> Self {
|
||||
let keys = config.key_credential.as_ref().map(|name| {
|
||||
Box::new(CredentialTokenSource::from_environment(name.clone())) as Box<dyn TokenSource>
|
||||
});
|
||||
Self::with_parts(config, keys)
|
||||
}
|
||||
|
||||
pub(crate) fn with_parts(config: OpenAiChatConfig, keys: Option<Box<dyn TokenSource>>) -> Self {
|
||||
let endpoint = format!("{}/chat/completions", config.base_url.trim_end_matches('/'));
|
||||
Self {
|
||||
provider_id: config.provider_id,
|
||||
agent: build_agent(config.deadline),
|
||||
endpoint,
|
||||
keys,
|
||||
max_response_bytes: config.max_response_bytes as u64,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn provider_id(&self) -> &str {
|
||||
&self.provider_id
|
||||
}
|
||||
|
||||
pub fn ready(&self) -> Result<(), &'static str> {
|
||||
match &self.keys {
|
||||
Some(source) => credential_ready(source.as_ref()),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run_model(
|
||||
&self,
|
||||
request: &ProviderRequest,
|
||||
row: &ModelRow,
|
||||
) -> (Vec<TransportEvent>, TransportOutcome) {
|
||||
let key = match read_key(self.keys.as_deref(), BACKEND_LABEL) {
|
||||
Ok(key) => key,
|
||||
Err(failure) => return failure,
|
||||
};
|
||||
let body = match render(request, &self.provider_id, row).and_then(|body| {
|
||||
serde_json::to_vec(&body).map_err(|_| "the request could not be encoded".to_string())
|
||||
}) {
|
||||
Ok(body) => body,
|
||||
Err(message) => {
|
||||
return failed(
|
||||
FailureKind::InvalidRequest,
|
||||
format!("{BACKEND_LABEL}: {message}"),
|
||||
Some(zero_usage()),
|
||||
);
|
||||
}
|
||||
};
|
||||
let mut post = self
|
||||
.agent
|
||||
.post(&self.endpoint)
|
||||
.header("content-type", "application/json");
|
||||
if let Some(key) = &key {
|
||||
let bearer = Zeroizing::new(format!("Bearer {}", key.as_str()));
|
||||
post = post.header("authorization", bearer.as_str());
|
||||
}
|
||||
let sent = post.send(&body[..]);
|
||||
let mut response = match sent {
|
||||
Ok(response) => response,
|
||||
Err(error) => return transport_failure(BACKEND_LABEL, &error),
|
||||
};
|
||||
let status = response.status().as_u16();
|
||||
let text = match response
|
||||
.body_mut()
|
||||
.with_config()
|
||||
.limit(self.max_response_bytes)
|
||||
.read_to_vec()
|
||||
{
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => return transport_failure(BACKEND_LABEL, &error),
|
||||
};
|
||||
if !(200..300).contains(&status) {
|
||||
return http_failure(
|
||||
BACKEND_LABEL,
|
||||
status,
|
||||
&text,
|
||||
key.as_deref().map(Zeroizing::as_str),
|
||||
spend_exhausted,
|
||||
);
|
||||
}
|
||||
let required = request.tool_choice == ToolChoice::Required && !request.tools.is_empty();
|
||||
match parse(&text, required) {
|
||||
Ok(done) => {
|
||||
let events = done
|
||||
.payloads
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(sequence, payload)| TransportEvent {
|
||||
sequence: sequence as u64,
|
||||
payload,
|
||||
})
|
||||
.collect();
|
||||
(
|
||||
events,
|
||||
TransportOutcome::Completed {
|
||||
provider_response_id: done.id,
|
||||
stop_reason: done.stop_reason,
|
||||
usage: done.usage,
|
||||
},
|
||||
)
|
||||
}
|
||||
Err(failure) => failed(failure.kind, failure.message, failure.usage),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- request ----
|
||||
|
||||
/// Lowers `request` into a Chat Completions JSON body, or explains why the
|
||||
/// request is refused before sending.
|
||||
fn render(request: &ProviderRequest, provider_id: &str, row: &ModelRow) -> Result<Value, String> {
|
||||
let effort = row.resolve_effort(request.reasoning_effort)?;
|
||||
if request.tool_choice == ToolChoice::Required
|
||||
&& !row.allows_forced_tool_choice(ModelRow::thinking_active(effort))
|
||||
{
|
||||
return Err(format!(
|
||||
"model {} does not accept a required tool choice",
|
||||
row.id
|
||||
));
|
||||
}
|
||||
if request.output_schema_json.is_some() && row.output_schema == OutputSchemaSupport::None {
|
||||
return Err(format!("model {} does not accept an output schema", row.id));
|
||||
}
|
||||
|
||||
let mut body = Map::new();
|
||||
body.insert("model".into(), json!(request.model));
|
||||
body.insert(
|
||||
"max_completion_tokens".into(),
|
||||
json!(request.max_output_tokens),
|
||||
);
|
||||
if let Some(level) = effort {
|
||||
body.insert("reasoning_effort".into(), json!(level));
|
||||
}
|
||||
|
||||
let messages = messages_of(&request.instructions, &request.input, provider_id)?;
|
||||
body.insert("messages".into(), Value::Array(messages));
|
||||
|
||||
if !request.tools.is_empty() {
|
||||
let mut tools = Vec::with_capacity(request.tools.len());
|
||||
for tool in &request.tools {
|
||||
let schema: Value = serde_json::from_str(&tool.parameters_json)
|
||||
.map_err(|_| format!("tool {} has parameters that are not JSON", tool.name))?;
|
||||
tools.push(json!({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tool.name,
|
||||
"description": tool.description,
|
||||
"parameters": schema,
|
||||
"strict": row.strict_tools,
|
||||
}
|
||||
}));
|
||||
}
|
||||
body.insert("tools".into(), Value::Array(tools));
|
||||
body.insert(
|
||||
"parallel_tool_calls".into(),
|
||||
json!(request.parallel_tool_calls),
|
||||
);
|
||||
if request.tool_choice == ToolChoice::Required {
|
||||
body.insert("tool_choice".into(), json!("required"));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(schema) = &request.output_schema_json {
|
||||
let schema: Value = serde_json::from_str(schema)
|
||||
.map_err(|_| "the output schema is not JSON".to_string())?;
|
||||
body.insert(
|
||||
"response_format".into(),
|
||||
json!({
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": "output_schema",
|
||||
"schema": schema,
|
||||
"strict": true,
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Value::Object(body))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct AssistantTurn {
|
||||
text: String,
|
||||
tool_calls: Vec<Value>,
|
||||
restored_message: Map<String, Value>,
|
||||
restored_tool_calls: Map<String, Value>,
|
||||
}
|
||||
|
||||
impl AssistantTurn {
|
||||
fn flush(mut self) -> Value {
|
||||
let mut message = Map::new();
|
||||
message.insert("role".into(), json!("assistant"));
|
||||
message.insert(
|
||||
"content".into(),
|
||||
if self.text.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
Value::String(self.text)
|
||||
},
|
||||
);
|
||||
for (key, value) in self.restored_message {
|
||||
if !matches!(key.as_str(), "role" | "content" | "tool_calls") {
|
||||
message.insert(key, value);
|
||||
}
|
||||
}
|
||||
if !self.tool_calls.is_empty() {
|
||||
for tool_call in &mut self.tool_calls {
|
||||
let Some(call_id) = tool_call["id"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(Value::Object(extra)) = self.restored_tool_calls.get(call_id)
|
||||
&& let Some(obj) = tool_call.as_object_mut()
|
||||
{
|
||||
for (key, value) in extra {
|
||||
if !matches!(key.as_str(), "id" | "type" | "function") {
|
||||
obj.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
message.insert("tool_calls".into(), Value::Array(self.tool_calls));
|
||||
}
|
||||
Value::Object(message)
|
||||
}
|
||||
}
|
||||
|
||||
fn messages_of(
|
||||
instructions: &str,
|
||||
input: &[InputItem],
|
||||
provider_id: &str,
|
||||
) -> Result<Vec<Value>, String> {
|
||||
let mut messages = Vec::with_capacity(input.len() + 1);
|
||||
messages.push(json!({
|
||||
"role": "system",
|
||||
"content": instructions,
|
||||
}));
|
||||
|
||||
let mut open_assistant: Option<AssistantTurn> = None;
|
||||
for item in input {
|
||||
match item {
|
||||
InputItem::UserText { text } => {
|
||||
if let Some(turn) = open_assistant.take() {
|
||||
messages.push(turn.flush());
|
||||
}
|
||||
messages.push(json!({
|
||||
"role": "user",
|
||||
"content": text,
|
||||
}));
|
||||
}
|
||||
InputItem::ToolResult { call_id, output } => {
|
||||
if let Some(turn) = open_assistant.take() {
|
||||
messages.push(turn.flush());
|
||||
}
|
||||
messages.push(json!({
|
||||
"role": "tool",
|
||||
"tool_call_id": call_id,
|
||||
"content": output,
|
||||
}));
|
||||
}
|
||||
InputItem::AssistantText { text } => {
|
||||
let turn = open_assistant.get_or_insert_with(AssistantTurn::default);
|
||||
turn.text.push_str(text);
|
||||
}
|
||||
InputItem::ToolCall {
|
||||
call_id,
|
||||
name,
|
||||
arguments,
|
||||
} => {
|
||||
let turn = open_assistant.get_or_insert_with(AssistantTurn::default);
|
||||
turn.tool_calls.push(json!({
|
||||
"id": call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": name,
|
||||
"arguments": arguments,
|
||||
}
|
||||
}));
|
||||
}
|
||||
InputItem::ReasoningState {
|
||||
provider, state, ..
|
||||
} => {
|
||||
if provider != provider_id {
|
||||
return Err("a reasoning state belongs to another provider".to_string());
|
||||
}
|
||||
let turn = open_assistant.get_or_insert_with(AssistantTurn::default);
|
||||
apply_reasoning_state(turn, state)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(turn) = open_assistant {
|
||||
messages.push(turn.flush());
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
fn apply_reasoning_state(turn: &mut AssistantTurn, state: &[u8]) -> Result<(), String> {
|
||||
let parsed: Value = serde_json::from_slice(state)
|
||||
.map_err(|_| "a reasoning state is not valid JSON".to_string())?;
|
||||
let Some(obj) = parsed.as_object() else {
|
||||
return Err("a reasoning state is not a JSON object".to_string());
|
||||
};
|
||||
let (Some(msg_fields), Some(tc_fields)) = (
|
||||
obj.get("message").and_then(Value::as_object),
|
||||
obj.get("tool_calls").and_then(Value::as_object),
|
||||
) else {
|
||||
return Err("a reasoning state is missing message or tool_calls maps".to_string());
|
||||
};
|
||||
for (key, value) in msg_fields {
|
||||
turn.restored_message.insert(key.clone(), value.clone());
|
||||
}
|
||||
for (call_id, value) in tc_fields {
|
||||
let Some(fields) = value.as_object() else {
|
||||
return Err("a tool call reasoning state entry is not an object".to_string());
|
||||
};
|
||||
let entry = turn
|
||||
.restored_tool_calls
|
||||
.entry(call_id.clone())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
if let Some(existing) = entry.as_object_mut() {
|
||||
for (k, v) in fields {
|
||||
existing.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- response ----
|
||||
|
||||
struct Done {
|
||||
id: Option<String>,
|
||||
payloads: Vec<TransportEventPayload>,
|
||||
stop_reason: StopReason,
|
||||
usage: Usage,
|
||||
}
|
||||
|
||||
struct Failure {
|
||||
kind: FailureKind,
|
||||
message: String,
|
||||
usage: Option<Usage>,
|
||||
}
|
||||
|
||||
/// `required`: the request forced a tool call, so an answer without one is a
|
||||
/// failure, never a completed turn.
|
||||
fn parse(bytes: &[u8], required: bool) -> Result<Done, Failure> {
|
||||
let provider_failure = |message: &str, usage: Option<Usage>| Failure {
|
||||
kind: FailureKind::Provider,
|
||||
message: format!("{BACKEND_LABEL}: {message}"),
|
||||
usage,
|
||||
};
|
||||
let response: Value = serde_json::from_slice(bytes)
|
||||
.map_err(|_| provider_failure("the response is not JSON", None))?;
|
||||
let usage = usage_of(&response["usage"]);
|
||||
let choice = response["choices"]
|
||||
.as_array()
|
||||
.and_then(|choices| choices.first())
|
||||
.ok_or_else(|| provider_failure("the response has no choices", usage.clone()))?;
|
||||
|
||||
let stop_reason = match choice["finish_reason"].as_str() {
|
||||
Some("stop") => StopReason::EndTurn,
|
||||
Some("tool_calls") => StopReason::ToolUse,
|
||||
Some("length") => StopReason::MaxOutputTokens,
|
||||
Some("content_filter") => StopReason::Refusal,
|
||||
Some("insufficient_system_resource") => {
|
||||
return Err(Failure {
|
||||
kind: FailureKind::Unavailable,
|
||||
message: format!("{BACKEND_LABEL}: insufficient system resource"),
|
||||
usage,
|
||||
});
|
||||
}
|
||||
Some("aborted") => return Err(provider_failure("the generation was aborted", usage)),
|
||||
_ => {
|
||||
return Err(provider_failure(
|
||||
"the finish reason is not one this backend maps",
|
||||
usage,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let message = choice["message"]
|
||||
.as_object()
|
||||
.ok_or_else(|| provider_failure("the response choice has no message", usage.clone()))?;
|
||||
|
||||
let mut payloads = Vec::new();
|
||||
let mut captured_message = Map::new();
|
||||
for (key, value) in message {
|
||||
if !STANDARD_MESSAGE_FIELDS.contains(&key.as_str()) && !value.is_null() {
|
||||
captured_message.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(text) = message
|
||||
.get("content")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|text| !text.is_empty())
|
||||
{
|
||||
payloads.push(TransportEventPayload::TextDelta {
|
||||
text: text.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut captured_tool_calls = Map::new();
|
||||
let mut has_tool_call = false;
|
||||
if let Some(tool_calls_val) = message.get("tool_calls").filter(|v| !v.is_null()) {
|
||||
let Some(tool_calls) = tool_calls_val.as_array() else {
|
||||
return Err(provider_failure("tool_calls is not an array", usage));
|
||||
};
|
||||
for tool_call in tool_calls {
|
||||
let Some(tc_obj) = tool_call.as_object() else {
|
||||
return Err(provider_failure("a tool call is not an object", usage));
|
||||
};
|
||||
let Some(id) = tc_obj
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|id| !id.is_empty())
|
||||
else {
|
||||
return Err(provider_failure("a tool call has no id", usage));
|
||||
};
|
||||
let Some(function) = tc_obj.get("function").and_then(Value::as_object) else {
|
||||
return Err(provider_failure("a tool call has no function", usage));
|
||||
};
|
||||
let Some(name) = function
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|name| !name.is_empty())
|
||||
else {
|
||||
return Err(provider_failure("a tool call has no function name", usage));
|
||||
};
|
||||
let Some(arguments) = function
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|args| !args.is_empty())
|
||||
else {
|
||||
return Err(provider_failure(
|
||||
"a tool call has missing or empty arguments",
|
||||
usage,
|
||||
));
|
||||
};
|
||||
has_tool_call = true;
|
||||
payloads.push(TransportEventPayload::ToolCall {
|
||||
call_id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
arguments: arguments.to_string(),
|
||||
});
|
||||
|
||||
let mut tc_extra = Map::new();
|
||||
for (key, value) in tc_obj {
|
||||
if !STANDARD_TOOL_CALL_FIELDS.contains(&key.as_str()) && !value.is_null() {
|
||||
tc_extra.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
if !tc_extra.is_empty() {
|
||||
captured_tool_calls.insert(id.to_string(), Value::Object(tc_extra));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !captured_message.is_empty() || !captured_tool_calls.is_empty() {
|
||||
let state = serde_json::to_vec(&json!({
|
||||
"message": captured_message,
|
||||
"tool_calls": captured_tool_calls,
|
||||
}))
|
||||
.unwrap_or_default();
|
||||
payloads.push(TransportEventPayload::ReasoningState { state });
|
||||
}
|
||||
|
||||
if required && !has_tool_call {
|
||||
return Err(provider_failure("a required tool call did not come", usage));
|
||||
}
|
||||
|
||||
Ok(Done {
|
||||
id: response["id"].as_str().map(str::to_string),
|
||||
payloads,
|
||||
stop_reason,
|
||||
usage: usage.unwrap_or_else(zero_usage),
|
||||
})
|
||||
}
|
||||
|
||||
fn usage_of(usage: &Value) -> Option<Usage> {
|
||||
usage.is_object().then(|| {
|
||||
let prompt_tokens = usage["prompt_tokens"].as_u64().unwrap_or(0);
|
||||
let cache_read_tokens = usage["prompt_tokens_details"]["cached_tokens"]
|
||||
.as_u64()
|
||||
.or_else(|| usage["prompt_cache_hit_tokens"].as_u64())
|
||||
.unwrap_or(0);
|
||||
Usage {
|
||||
input_tokens: prompt_tokens.saturating_sub(cache_read_tokens),
|
||||
cache_read_tokens,
|
||||
cache_write_tokens: 0,
|
||||
output_tokens: usage["completion_tokens"].as_u64().unwrap_or(0),
|
||||
reasoning_tokens: usage["completion_tokens_details"]["reasoning_tokens"].as_u64(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---- failures ----
|
||||
|
||||
const SPENT_BALANCE_TYPES_OR_CODES: &[&str] = &[
|
||||
"insufficient_balance",
|
||||
"insufficient_quota",
|
||||
"billing_hard_limit_reached",
|
||||
];
|
||||
|
||||
const SPENT_BALANCE_PREFIXES: &[&str] = &[
|
||||
"insufficient balance",
|
||||
"your credit balance is too low",
|
||||
"you have reached your specified api usage limits",
|
||||
"you exceeded your current quota",
|
||||
"insufficient quota",
|
||||
"billing hard limit",
|
||||
];
|
||||
|
||||
fn spend_exhausted(status: u16, error: &Value) -> bool {
|
||||
let tag_matches = |tag: Option<&str>, allowed: &[&str]| {
|
||||
tag.is_some_and(|v| {
|
||||
let lowered = v.trim().to_ascii_lowercase();
|
||||
allowed.iter().any(|candidate| lowered == *candidate)
|
||||
})
|
||||
};
|
||||
let msg_starts_with = |prefixes: &[&str]| {
|
||||
error["message"].as_str().is_some_and(|text| {
|
||||
let lowered = text.trim_start().to_ascii_lowercase();
|
||||
prefixes.iter().any(|prefix| lowered.starts_with(prefix))
|
||||
})
|
||||
};
|
||||
match status {
|
||||
400 => {
|
||||
tag_matches(error["type"].as_str(), SPENT_BALANCE_TYPES_OR_CODES)
|
||||
|| tag_matches(error["code"].as_str(), SPENT_BALANCE_TYPES_OR_CODES)
|
||||
|| msg_starts_with(SPENT_BALANCE_PREFIXES)
|
||||
}
|
||||
429 => {
|
||||
tag_matches(error["type"].as_str(), &["insufficient_quota"])
|
||||
|| tag_matches(error["code"].as_str(), &["insufficient_quota"])
|
||||
|| msg_starts_with(&[
|
||||
"you exceeded your current quota",
|
||||
"insufficient quota",
|
||||
"insufficient_quota",
|
||||
])
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
1011
crates/claude-connector/src/openai_chat/tests.rs
Normal file
1011
crates/claude-connector/src/openai_chat/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -14,11 +14,15 @@ use crate::config::ModelRow;
|
|||
use crate::config::ProviderWire;
|
||||
use crate::daemon::ConfigError;
|
||||
#[cfg(unix)]
|
||||
use crate::daemon::{ClaudeConnectorConfig, backend_config_for, messages_config_for};
|
||||
use crate::daemon::{
|
||||
ClaudeConnectorConfig, backend_config_for, messages_config_for, openai_chat_config_for,
|
||||
};
|
||||
use crate::messages::MessagesBackend;
|
||||
use crate::openai_chat::OpenAiChatBackend;
|
||||
|
||||
enum RouteBackend {
|
||||
Messages(MessagesBackend),
|
||||
OpenAiChat(OpenAiChatBackend),
|
||||
Cli(Arc<ClaudeCodeBackend>),
|
||||
}
|
||||
|
||||
|
|
@ -40,6 +44,7 @@ impl RouterBackend {
|
|||
config.validate()?;
|
||||
let mut cli_sink = Some(cli_sink);
|
||||
let mut messages = Vec::new();
|
||||
let mut openai_chats = Vec::new();
|
||||
let mut cli = None;
|
||||
for entry in &config.providers {
|
||||
match &entry.wire {
|
||||
|
|
@ -63,22 +68,30 @@ impl RouterBackend {
|
|||
cli = Some(backend);
|
||||
}
|
||||
ProviderWire::OpenAiChat { .. } => {
|
||||
return Err(ConfigError::Invalid("providers"));
|
||||
let cfg =
|
||||
openai_chat_config_for(entry).ok_or(ConfigError::Unusable("providers"))?;
|
||||
let backend = OpenAiChatBackend::new(cfg);
|
||||
if backend.provider_id() != entry.id {
|
||||
return Err(ConfigError::Invalid("providers"));
|
||||
}
|
||||
openai_chats.push(backend);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::from_backends(messages, cli, config.models.clone())
|
||||
Self::from_backends(messages, openai_chats, cli, config.models.clone())
|
||||
}
|
||||
|
||||
pub fn from_backends(
|
||||
messages: impl IntoIterator<Item = MessagesBackend>,
|
||||
openai_chats: impl IntoIterator<Item = OpenAiChatBackend>,
|
||||
cli: Option<Arc<ClaudeCodeBackend>>,
|
||||
models: Vec<ModelRow>,
|
||||
) -> Result<Self, ConfigError> {
|
||||
let mut providers = BTreeMap::new();
|
||||
for backend in messages {
|
||||
let id = backend.provider_id().trim();
|
||||
let id = backend.provider_id();
|
||||
if id.is_empty()
|
||||
|| id.trim() != id
|
||||
|| providers
|
||||
.insert(id.to_string(), RouteBackend::Messages(backend))
|
||||
.is_some()
|
||||
|
|
@ -86,9 +99,21 @@ impl RouterBackend {
|
|||
return Err(ConfigError::Invalid("providers"));
|
||||
}
|
||||
}
|
||||
if let Some(cli_backend) = &cli {
|
||||
let id = cli_backend.provider_id().trim();
|
||||
for backend in openai_chats {
|
||||
let id = backend.provider_id();
|
||||
if id.is_empty()
|
||||
|| id.trim() != id
|
||||
|| providers
|
||||
.insert(id.to_string(), RouteBackend::OpenAiChat(backend))
|
||||
.is_some()
|
||||
{
|
||||
return Err(ConfigError::Invalid("providers"));
|
||||
}
|
||||
}
|
||||
if let Some(cli_backend) = &cli {
|
||||
let id = cli_backend.provider_id();
|
||||
if id.is_empty()
|
||||
|| id.trim() != id
|
||||
|| providers
|
||||
.insert(id.to_string(), RouteBackend::Cli(cli_backend.clone()))
|
||||
.is_some()
|
||||
|
|
@ -125,6 +150,7 @@ impl ProviderBackend for RouterBackend {
|
|||
for backend in self.providers.values() {
|
||||
match backend {
|
||||
RouteBackend::Messages(messages) => messages.ready()?,
|
||||
RouteBackend::OpenAiChat(openai) => openai.ready()?,
|
||||
RouteBackend::Cli(cli) => cli.ready()?,
|
||||
}
|
||||
}
|
||||
|
|
@ -161,6 +187,7 @@ impl ProviderBackend for RouterBackend {
|
|||
wire_request.model = row.upstream.clone();
|
||||
let (events, outcome) = match backend {
|
||||
RouteBackend::Messages(messages) => messages.run_model(&wire_request, row),
|
||||
RouteBackend::OpenAiChat(openai) => openai.run_model(&wire_request, row),
|
||||
RouteBackend::Cli(cli) => cli.run_model(&wire_request, call.caller_runtime_id(), row),
|
||||
};
|
||||
call.transported(events, outcome)
|
||||
|
|
@ -183,6 +210,7 @@ mod tests {
|
|||
use crate::config::{EffortMap, ForcedToolChoice, OutputSchemaSupport};
|
||||
use crate::credential::TokenSource;
|
||||
use crate::messages::MessagesConfig;
|
||||
use crate::openai_chat::OpenAiChatConfig;
|
||||
|
||||
struct FixedKey(&'static str);
|
||||
impl TokenSource for FixedKey {
|
||||
|
|
@ -211,6 +239,20 @@ mod tests {
|
|||
)
|
||||
}
|
||||
|
||||
fn oai_backend(id: &str, url: &str, key: Option<Box<dyn TokenSource>>) -> OpenAiChatBackend {
|
||||
OpenAiChatBackend::with_parts(
|
||||
OpenAiChatConfig {
|
||||
provider_id: id.to_string(),
|
||||
base_url: url.to_string(),
|
||||
key_credential: key.as_ref().map(|_| format!("{id}-cred")),
|
||||
strict_unsupported: Vec::new(),
|
||||
deadline: Duration::from_secs(5),
|
||||
max_response_bytes: 1 << 20,
|
||||
},
|
||||
key,
|
||||
)
|
||||
}
|
||||
|
||||
fn row(id: &str, provider: &str, upstream: &str) -> ModelRow {
|
||||
ModelRow {
|
||||
id: id.to_string(),
|
||||
|
|
@ -228,20 +270,59 @@ mod tests {
|
|||
fn from_backends_validates_providers_models_and_readiness() {
|
||||
let ok = msg_backend("entry-a", "http://127.0.0.1:9", None);
|
||||
assert!(matches!(
|
||||
RouterBackend::from_backends([ok], None, vec![]),
|
||||
RouterBackend::from_backends([ok], [], None, vec![]),
|
||||
Err(ConfigError::Invalid("models"))
|
||||
));
|
||||
|
||||
let dup_a = msg_backend("entry-a", "http://127.0.0.1:9", None);
|
||||
let dup_b = msg_backend("entry-a", "http://127.0.0.1:10", None);
|
||||
assert!(matches!(
|
||||
RouterBackend::from_backends([dup_a, dup_b], None, vec![row("m1", "entry-a", "u1")]),
|
||||
RouterBackend::from_backends(
|
||||
[dup_a, dup_b],
|
||||
[],
|
||||
None,
|
||||
vec![row("m1", "entry-a", "u1")]
|
||||
),
|
||||
Err(ConfigError::Invalid("providers"))
|
||||
));
|
||||
|
||||
let untrimmed_msg = msg_backend(" entry-a", "http://127.0.0.1:9", None);
|
||||
assert!(matches!(
|
||||
RouterBackend::from_backends(
|
||||
[untrimmed_msg],
|
||||
[],
|
||||
None,
|
||||
vec![row("m1", "entry-a", "u1")]
|
||||
),
|
||||
Err(ConfigError::Invalid("providers"))
|
||||
));
|
||||
|
||||
let untrimmed_oai = oai_backend("entry-oai ", "http://127.0.0.1:9", None);
|
||||
assert!(matches!(
|
||||
RouterBackend::from_backends(
|
||||
[],
|
||||
[untrimmed_oai],
|
||||
None,
|
||||
vec![row("m1", "entry-oai", "u1")]
|
||||
),
|
||||
Err(ConfigError::Invalid("providers"))
|
||||
));
|
||||
|
||||
let dup_cross_msg = msg_backend("shared-id", "http://127.0.0.1:9", None);
|
||||
let dup_cross_oai = oai_backend("shared-id", "http://127.0.0.1:10", None);
|
||||
assert!(matches!(
|
||||
RouterBackend::from_backends(
|
||||
[dup_cross_msg],
|
||||
[dup_cross_oai],
|
||||
None,
|
||||
vec![row("m1", "shared-id", "u1")]
|
||||
),
|
||||
Err(ConfigError::Invalid("providers"))
|
||||
));
|
||||
|
||||
let ok = msg_backend("entry-a", "http://127.0.0.1:9", None);
|
||||
assert!(matches!(
|
||||
RouterBackend::from_backends([ok], None, vec![row("m1", "unknown-entry", "u1")]),
|
||||
RouterBackend::from_backends([ok], [], None, vec![row("m1", "unknown-entry", "u1")]),
|
||||
Err(ConfigError::Invalid("model_provider"))
|
||||
));
|
||||
|
||||
|
|
@ -249,6 +330,7 @@ mod tests {
|
|||
assert!(matches!(
|
||||
RouterBackend::from_backends(
|
||||
[ok],
|
||||
[],
|
||||
None,
|
||||
vec![row("m1", "entry-a", "u1"), row("m1", "entry-a", "u2")]
|
||||
),
|
||||
|
|
@ -265,15 +347,39 @@ mod tests {
|
|||
"https://example.test",
|
||||
Some(Box::new(FixedKey("k"))),
|
||||
);
|
||||
let oai_ready = oai_backend(
|
||||
"entry-oai",
|
||||
"https://oai.example.test/v1",
|
||||
Some(Box::new(FixedKey("k2"))),
|
||||
);
|
||||
let router = RouterBackend::from_backends(
|
||||
[ready, failing],
|
||||
[oai_ready],
|
||||
None,
|
||||
vec![row("m1", "entry-a", "u1"), row("m2", "entry-b", "u2")],
|
||||
vec![
|
||||
row("m1", "entry-a", "u1"),
|
||||
row("m2", "entry-b", "u2"),
|
||||
row("m3", "entry-oai", "u3"),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(router.ready(), Err("token_credential"));
|
||||
assert!(router.plan_quota().is_none());
|
||||
assert!(router.cli_backend().is_none());
|
||||
|
||||
let oai_failing = oai_backend(
|
||||
"entry-oai-missing",
|
||||
"https://oai.example.test/v1",
|
||||
Some(Box::new(MissingKey)),
|
||||
);
|
||||
let oai_router = RouterBackend::from_backends(
|
||||
[],
|
||||
[oai_failing],
|
||||
None,
|
||||
vec![row("m1", "entry-oai-missing", "u1")],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(oai_router.ready(), Err("token_credential"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -344,6 +450,7 @@ mod tests {
|
|||
);
|
||||
let router = RouterBackend::from_backends(
|
||||
[backend],
|
||||
[],
|
||||
None,
|
||||
vec![row("caller-alias", "custom-entry", "wire-upstream-name")],
|
||||
)
|
||||
|
|
@ -397,30 +504,129 @@ mod tests {
|
|||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn from_config_refuses_openai_chat_until_cut_3() {
|
||||
fn from_config_accepts_and_routes_openai_chat_through_service() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::sync::Mutex;
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let seen = Arc::new(Mutex::new(Vec::<(String, serde_json::Value)>::new()));
|
||||
let seen_clone = seen.clone();
|
||||
let responses = vec![
|
||||
serde_json::json!({
|
||||
"id": "oai_resp_1",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"reasoning_content": "thought line",
|
||||
"tool_calls": [{
|
||||
"id": "call_r1",
|
||||
"type": "function",
|
||||
"function": {"name": "ping", "arguments": "{\"x\":1}"},
|
||||
"extra_content": {"google": {"thought_signature": "sig-router"}}
|
||||
}]
|
||||
},
|
||||
"finish_reason": "tool_calls"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5}
|
||||
}),
|
||||
serde_json::json!({
|
||||
"id": "oai_resp_2",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {"role": "assistant", "content": "done"},
|
||||
"finish_reason": "stop"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 20, "completion_tokens": 3}
|
||||
}),
|
||||
];
|
||||
std::thread::spawn(move || {
|
||||
for resp in responses {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
let mut header_end = None;
|
||||
let mut content_len = 0usize;
|
||||
loop {
|
||||
let n = stream.read(&mut chunk).unwrap_or(0);
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
if header_end.is_none()
|
||||
&& let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n")
|
||||
{
|
||||
let end = pos + 4;
|
||||
header_end = Some(end);
|
||||
let headers = String::from_utf8_lossy(&buf[..pos]);
|
||||
for line in headers.lines().skip(1) {
|
||||
if let Some((k, v)) = line.split_once(':')
|
||||
&& k.eq_ignore_ascii_case("content-length")
|
||||
{
|
||||
content_len = v.trim().parse().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(end) = header_end
|
||||
&& buf.len() >= end + content_len
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = header_end.unwrap_or(buf.len());
|
||||
let path = String::from_utf8_lossy(&buf[..end])
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|l| l.split_whitespace().nth(1))
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&buf[end..end + content_len]).unwrap();
|
||||
seen_clone.lock().unwrap().push((path, body));
|
||||
let payload = resp.to_string();
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
|
||||
payload.len(),
|
||||
payload
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("router-oai-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let caller_key_file = dir.join("c1.key");
|
||||
let caller_secret = "caller-1-secret-0123456789abcdef0123456789";
|
||||
std::fs::write(&caller_key_file, caller_secret).unwrap();
|
||||
|
||||
let cfg = ClaudeConnectorConfig {
|
||||
listen: "127.0.0.1:4110".to_string(),
|
||||
replay_store: PathBuf::from("/tmp/replay.cc"),
|
||||
replay_store: dir.join("replay.cc"),
|
||||
max_frame_bytes: 2 << 20,
|
||||
max_connections: 8,
|
||||
socket_timeout_ms: 10_000,
|
||||
max_expiry_skew_ms: 300_000,
|
||||
providers: vec![crate::ProviderEntry {
|
||||
id: "oai".to_string(),
|
||||
id: "oai-entry".to_string(),
|
||||
credential: None,
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "http://127.0.0.1:8080/v1".to_string(),
|
||||
base_url: format!("http://{addr}/v1"),
|
||||
strict_unsupported: vec![],
|
||||
deadline_ms: 10_000,
|
||||
max_response_bytes: 1 << 20,
|
||||
},
|
||||
}],
|
||||
models: vec![row("m1", "oai", "u1")],
|
||||
models: vec![row("ds-flash", "oai-entry", "deepseek-chat")],
|
||||
callers: vec![model_connector::CallerConfig {
|
||||
caller_runtime_id: "c1".to_string(),
|
||||
connection_key_file: PathBuf::from("/tmp/c1.key"),
|
||||
connection_key_file: caller_key_file,
|
||||
connection_key_epoch: 1,
|
||||
allowed_models: vec!["m1".to_string()],
|
||||
allowed_models: vec!["ds-flash".to_string()],
|
||||
max_concurrent_requests: 2,
|
||||
max_payload_bytes: 1 << 20,
|
||||
max_output_tokens: 4_096,
|
||||
|
|
@ -429,10 +635,92 @@ mod tests {
|
|||
lease_holders: vec![],
|
||||
lease_max_ms: 60_000,
|
||||
};
|
||||
let router = RouterBackend::from_config(&cfg, Box::new(NoSink)).unwrap();
|
||||
|
||||
let admission = CallerAdmission::new(
|
||||
"c1",
|
||||
caller_secret,
|
||||
1,
|
||||
["ds-flash".to_string()],
|
||||
2,
|
||||
1 << 20,
|
||||
4_096,
|
||||
)
|
||||
.unwrap();
|
||||
let routes =
|
||||
ProviderRoutes::new([("ds-flash".to_string(), "oai-entry".to_string())]).unwrap();
|
||||
let mut service =
|
||||
TransportService::open(&cfg.replay_store, routes, [admission], 5_000).unwrap();
|
||||
let key = TransportKey::from_connection_secret(caller_secret).unwrap();
|
||||
|
||||
let mut req1 = ProviderRequest::new("r1", "c1", "ds-flash", "Be brief.", 128);
|
||||
req1.input = vec![model_connector::InputItem::UserText {
|
||||
text: "ping".to_string(),
|
||||
}];
|
||||
req1.tools = vec![model_connector::ToolDefinition {
|
||||
name: "ping".to_string(),
|
||||
description: "ping".to_string(),
|
||||
parameters_json: r#"{"type":"object","properties":{"x":{"type":"integer"}}}"#
|
||||
.to_string(),
|
||||
}];
|
||||
let inv1 = TransportInvocation::new("c1", 2_000, [1; 32], req1.clone()).unwrap();
|
||||
let env1 = encrypt_invocation(&inv1, &key).unwrap();
|
||||
let TransportAdmission::Execute(claim1) =
|
||||
service.begin(&env1, 1_000, None, 1 << 20).unwrap()
|
||||
else {
|
||||
panic!("expected execute");
|
||||
};
|
||||
let sealed1 = service
|
||||
.complete(*claim1, router.execute(claim1.call()), 1 << 20)
|
||||
.unwrap();
|
||||
let opened1 = decrypt_result(&sealed1, &key, &inv1).unwrap();
|
||||
let TransportDisposition::Transported {
|
||||
receipt: ref receipt1,
|
||||
..
|
||||
} = opened1.disposition
|
||||
else {
|
||||
panic!("expected transported");
|
||||
};
|
||||
assert_eq!(receipt1.provider, "oai-entry");
|
||||
assert_eq!(receipt1.model, "ds-flash");
|
||||
|
||||
let mut req2 = req1;
|
||||
req2.request_id = "r2".to_string();
|
||||
req2.input.extend(opened1.transcript_items());
|
||||
req2.input.push(model_connector::InputItem::ToolResult {
|
||||
call_id: "call_r1".to_string(),
|
||||
output: "pong".to_string(),
|
||||
});
|
||||
let inv2 = TransportInvocation::new("c1", 2_000, [2; 32], req2).unwrap();
|
||||
let env2 = encrypt_invocation(&inv2, &key).unwrap();
|
||||
let TransportAdmission::Execute(claim2) =
|
||||
service.begin(&env2, 1_000, None, 1 << 20).unwrap()
|
||||
else {
|
||||
panic!("expected execute");
|
||||
};
|
||||
let sealed2 = service
|
||||
.complete(*claim2, router.execute(claim2.call()), 1 << 20)
|
||||
.unwrap();
|
||||
let opened2 = decrypt_result(&sealed2, &key, &inv2).unwrap();
|
||||
assert!(matches!(
|
||||
RouterBackend::from_config(&cfg, Box::new(NoSink)),
|
||||
Err(ConfigError::Invalid("providers"))
|
||||
opened2.disposition,
|
||||
TransportDisposition::Transported { .. }
|
||||
));
|
||||
|
||||
let seen = seen.lock().unwrap();
|
||||
assert_eq!(seen.len(), 2);
|
||||
assert_eq!(seen[0].0, "/v1/chat/completions");
|
||||
assert_eq!(seen[0].1["model"], "deepseek-chat");
|
||||
assert_eq!(seen[1].1["model"], "deepseek-chat");
|
||||
assert_eq!(
|
||||
seen[1].1["messages"][2]["reasoning_content"],
|
||||
"thought line"
|
||||
);
|
||||
assert_eq!(
|
||||
seen[1].1["messages"][2]["tool_calls"][0]["extra_content"],
|
||||
serde_json::json!({"google": {"thought_signature": "sig-router"}})
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
|
|
|||
|
|
@ -600,6 +600,7 @@ fn t_c0_oauth_still_cli_a_tools_request_is_refused_and_no_child_starts() {
|
|||
)),
|
||||
);
|
||||
let router = RouterBackend::from_backends(
|
||||
[],
|
||||
[],
|
||||
Some(Arc::new(backend)),
|
||||
vec![ModelRow {
|
||||
|
|
|
|||
|
|
@ -351,19 +351,87 @@ fn v3_validation_refuses_invalid_providers_models_and_urls() {
|
|||
});
|
||||
assert_eq!(refused(&two_cli), "providers");
|
||||
|
||||
// OpenAiChat entry refused until Cut 3.
|
||||
let mut openai = valid();
|
||||
openai.providers.push(ProviderEntry {
|
||||
// Valid keyed HTTPS and keyless loopback OpenAiChat entries pass validate().
|
||||
let mut oai_https = valid();
|
||||
oai_https.providers.push(ProviderEntry {
|
||||
id: "deepseek".to_string(),
|
||||
credential: Some("ds-key".to_string()),
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "https://api.deepseek.com".to_string(),
|
||||
strict_unsupported: vec!["minLength".to_string()],
|
||||
strict_unsupported: vec!["minLength".to_string(), "maxItems".to_string()],
|
||||
deadline_ms: 600_000,
|
||||
max_response_bytes: 64 << 20,
|
||||
},
|
||||
});
|
||||
assert_eq!(refused(&openai), "providers");
|
||||
assert!(oai_https.validate().is_ok());
|
||||
|
||||
let mut oai_loopback = valid();
|
||||
oai_loopback.providers.push(ProviderEntry {
|
||||
id: "local-oai".to_string(),
|
||||
credential: None,
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "http://127.0.0.1:8080/v1".to_string(),
|
||||
strict_unsupported: Vec::new(),
|
||||
deadline_ms: 60_000,
|
||||
max_response_bytes: 16 << 20,
|
||||
},
|
||||
});
|
||||
assert!(oai_loopback.validate().is_ok());
|
||||
|
||||
// OpenAiChat validation refuses bad base_url, keyless non-loopback, zero HTTP limits, and empty/untrimmed strict_unsupported.
|
||||
let mut oai_bad_url = valid();
|
||||
oai_bad_url.providers.push(ProviderEntry {
|
||||
id: "deepseek".to_string(),
|
||||
credential: Some("ds-key".to_string()),
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "http://api.deepseek.com".to_string(),
|
||||
strict_unsupported: Vec::new(),
|
||||
deadline_ms: 600_000,
|
||||
max_response_bytes: 64 << 20,
|
||||
},
|
||||
});
|
||||
assert_eq!(refused(&oai_bad_url), "base_url");
|
||||
|
||||
let mut oai_keyless_remote = valid();
|
||||
oai_keyless_remote.providers.push(ProviderEntry {
|
||||
id: "deepseek".to_string(),
|
||||
credential: None,
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "https://api.deepseek.com".to_string(),
|
||||
strict_unsupported: Vec::new(),
|
||||
deadline_ms: 600_000,
|
||||
max_response_bytes: 64 << 20,
|
||||
},
|
||||
});
|
||||
assert_eq!(refused(&oai_keyless_remote), "credential");
|
||||
|
||||
let mut oai_zero_limit = valid();
|
||||
oai_zero_limit.providers.push(ProviderEntry {
|
||||
id: "deepseek".to_string(),
|
||||
credential: Some("ds-key".to_string()),
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "https://api.deepseek.com".to_string(),
|
||||
strict_unsupported: Vec::new(),
|
||||
deadline_ms: 0,
|
||||
max_response_bytes: 64 << 20,
|
||||
},
|
||||
});
|
||||
assert_eq!(refused(&oai_zero_limit), "http limits");
|
||||
|
||||
for bad_kw in ["", " ", " minLength", "minLength "] {
|
||||
let mut oai_bad_kw = valid();
|
||||
oai_bad_kw.providers.push(ProviderEntry {
|
||||
id: "deepseek".to_string(),
|
||||
credential: Some("ds-key".to_string()),
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "https://api.deepseek.com".to_string(),
|
||||
strict_unsupported: vec![bad_kw.to_string()],
|
||||
deadline_ms: 600_000,
|
||||
max_response_bytes: 64 << 20,
|
||||
},
|
||||
});
|
||||
assert_eq!(refused(&oai_bad_kw), "strict_unsupported");
|
||||
}
|
||||
|
||||
// Reserved stand-in provider id and oversized ids refused.
|
||||
let mut stand_in = valid();
|
||||
|
|
@ -912,22 +980,75 @@ fn config_add_provider_and_add_model_append_and_validate() {
|
|||
assert_eq!(loaded.models[1].output_schema, OutputSchemaSupport::None);
|
||||
assert!(loaded.models[1].strict_tools);
|
||||
|
||||
let added_oai = run(&[
|
||||
"config",
|
||||
"add-provider",
|
||||
p,
|
||||
"--provider",
|
||||
"ds",
|
||||
"--wire",
|
||||
"openai-chat",
|
||||
"--base-url",
|
||||
"https://api.deepseek.com",
|
||||
"--credential",
|
||||
"ds-cred",
|
||||
"--strict-unsupported",
|
||||
"minLength",
|
||||
"--strict-unsupported",
|
||||
"maxItems",
|
||||
]);
|
||||
assert!(added_oai.status.success(), "{added_oai:?}");
|
||||
|
||||
let added_oai_model = run(&[
|
||||
"config",
|
||||
"add-model",
|
||||
p,
|
||||
"--model",
|
||||
"ds-chat",
|
||||
"--provider",
|
||||
"ds",
|
||||
"--upstream",
|
||||
"deepseek-chat",
|
||||
"--unset-effort",
|
||||
"none",
|
||||
"--forced-tool-choice",
|
||||
"without-thinking",
|
||||
"--output-schema",
|
||||
"none",
|
||||
"--strict-tools",
|
||||
"true",
|
||||
]);
|
||||
assert!(added_oai_model.status.success(), "{added_oai_model:?}");
|
||||
|
||||
let loaded_oai = load_config(&config_path).unwrap();
|
||||
assert_eq!(loaded_oai.providers.len(), 3);
|
||||
assert_eq!(
|
||||
loaded_oai.providers[2],
|
||||
ProviderEntry {
|
||||
id: "ds".to_string(),
|
||||
credential: Some("ds-cred".to_string()),
|
||||
wire: ProviderWire::OpenAiChat {
|
||||
base_url: "https://api.deepseek.com".to_string(),
|
||||
strict_unsupported: vec!["minLength".to_string(), "maxItems".to_string()],
|
||||
deadline_ms: 600_000,
|
||||
max_response_bytes: 64 << 20,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
let creds = scratch.path("creds");
|
||||
std::fs::create_dir_all(&creds).unwrap();
|
||||
std::fs::write(creds.join("cred-one"), "k1").unwrap();
|
||||
std::fs::write(creds.join("ds-cred"), "k2").unwrap();
|
||||
let check_ok = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
|
||||
.args(["config", "check", p])
|
||||
.env("CREDENTIALS_DIRECTORY", &creds)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(check_ok.status.success(), "{check_ok:?}");
|
||||
|
||||
let before_invalid = std::fs::read(&config_path).unwrap();
|
||||
for bad_args in [
|
||||
// OpenAiChat refused until Cut 3.
|
||||
vec![
|
||||
"config",
|
||||
"add-provider",
|
||||
p,
|
||||
"--provider",
|
||||
"ds",
|
||||
"--wire",
|
||||
"openai-chat",
|
||||
"--base-url",
|
||||
"https://api.deepseek.com",
|
||||
"--credential",
|
||||
"ds-cred",
|
||||
],
|
||||
// Duplicate credential refused.
|
||||
vec![
|
||||
"config",
|
||||
|
|
|
|||
Loading…
Reference in a new issue