From bb4ba63ff4abf8f1208e7ae51ba566345b9e53fb Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 2 Dec 2026 14:04:40 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=82=E9=85=8D=2098k=20New=20API=20?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E7=9B=AE=E5=BD=95=E4=B8=8E=E6=96=87=E5=AD=97?= =?UTF-8?q?=E7=BA=BF=E8=B7=AF=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/desktop/[...path]/route.ts | 1 + .../apps/photocraft/src/jiansun_backend.rs | 129 +++++---- .../apps/photocraft/src/jiansun_creation.rs | 41 +-- .../photocraft/src/jiansun_image_protocol.rs | 39 ++- .../apps/photocraft/src/jiansun_images.rs | 35 ++- .../apps/photocraft/src/jiansun_models.rs | 263 +++++++++++++++--- .../apps/photocraft/src/jiansun_pi.rs | 182 +++++++++--- .../apps/photocraft/src/jiansun_pi_runtime.rs | 58 +++- lib/__tests__/ai-model-service.test.ts | 29 +- lib/ai-model-capabilities.ts | 78 +++++- lib/ai-model-http.ts | 10 +- lib/ai-model-protocol.ts | 4 +- lib/ai-model-service.ts | 35 ++- 13 files changed, 710 insertions(+), 194 deletions(-) diff --git a/app/api/desktop/[...path]/route.ts b/app/api/desktop/[...path]/route.ts index 4917444b..64e7776d 100644 --- a/app/api/desktop/[...path]/route.ts +++ b/app/api/desktop/[...path]/route.ts @@ -121,6 +121,7 @@ async function route(request:Request,{params}:{params:{path:string[]}}){ }catch(error){ const known=error instanceof DesktopClientError||Boolean(error&&typeof error==='object'&&'status'in error) const item=error as {status?:number;code?:string;message?:string} + if(!known)console.error('[desktop-proxy] unexpected error',{status:503,route:'/api/desktop/[...path]'}) return NextResponse.json({error:known?item.message:'客户端服务暂不可用,请稍后重试',code:known?item.code||'invalid_request':'service_unavailable'},{status:known?item.status||400:503,headers}) } } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 816a7d93..c3db4215 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -1,5 +1,5 @@ //! Native reuse of the existing /api/desktop and 98k public execution contracts. -//! No production database, server shell, provider internals or automatic POST retries. +//! The native client uses public HTTP contracts. Text requests can switch routes before response headers. use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use photocraft_doc::Document; use photocraft_ui_egui::jiansun::{Edit, Event, Request, Workspace}; @@ -1050,12 +1050,12 @@ impl Backend { .unwrap_or_default().into_iter().filter(|option| keys.contains(&&option["key"])).collect() } - fn text_models(catalog: &Value, aliases: &[Value]) -> R> { + fn text_models(catalog: &Value, aliases: &[Value], key: Option<&crate::jiansun_models::KeyCatalog>) -> R> { let mut models = Vec::new(); let mut seen = std::collections::HashSet::new(); - for row in crate::jiansun_image_protocol::catalog_models(catalog)? { + for row in crate::jiansun_image_protocol::catalog_models(catalog, key)? { let alias = aliases.iter().find(|option| option["id"] == row["id"]); - if let Some(model) = crate::jiansun_models::text_model(row, alias.and_then(|item| item["key"].as_str())) { + if let Some(model) = crate::jiansun_models::text_model(&row, alias.and_then(|item| item["key"].as_str())) { if seen.insert(model["id"].as_str().unwrap_or_default().to_owned()) { models.push(model); } @@ -1073,21 +1073,29 @@ impl Backend { } } - fn live_text_choice(&self, choice: &str) -> R { - self.text_choice_from_catalog(choice, &self.text_choice_id(choice)?, &self.public_model_catalog()?, false) + fn live_text_choice(&self, choice: &str, key: &str) -> R { + let id = self.text_choice_id(choice)?; + let authorized = self.key_catalog_full(key)?; + if !authorized.ids.contains(&id) { + return Err("个人Key未开放所选模型".into()); + } + let mut model = self.text_choice_from_catalog(choice, &id, &self.public_model_catalog()?, &authorized, false)?; + if model["catalogFormat"] == "newapi-pricing" { + pi_runtime::enrich_models(std::slice::from_mut(&mut model))?; + } + Ok(model) } - fn text_choice_from_catalog(&self, choice: &str, id: &str, catalog: &Value, responses: bool) -> R { - crate::jiansun_image_protocol::catalog_models(catalog)? + fn text_choice_from_catalog(&self, choice: &str, id: &str, catalog: &Value, key: &crate::jiansun_models::KeyCatalog, responses: bool) -> R { + crate::jiansun_image_protocol::catalog_models(catalog, Some(key))? .filter(|row| row["id"] == id) - .find_map(|row| crate::jiansun_models::text_model_for(row, Some(choice), responses)) + .find_map(|row| crate::jiansun_models::text_model_for(&row, Some(choice), responses)) .ok_or_else(|| "98K 当前未发布此模型的可用对话契约,请重新选择".into()) } - fn refresh_models(&mut self, catalog: &Value, saved: &Value) -> R<()> { + fn refresh_models(&mut self, catalog: &Value, saved: &Value, key: Option<&crate::jiansun_models::KeyCatalog>) -> R<()> { let aliases = self.legacy_text_choices(saved); - self.models = Self::text_models(catalog, &aliases)?; - // The bundled provider database supplies optional capacity metadata only. + self.models = Self::text_models(catalog, &aliases, key)?; let _ = pi_runtime::enrich_models(&mut self.models); self.copy_models = self.models.clone(); self.copy_error.clear(); @@ -1108,11 +1116,17 @@ impl Backend { return Err("本地模型目录过大".into()); } let catalog = serde_json::from_slice(&bytes).map_err(|_| "本地模型目录格式无效")?; - return Ok((catalog, json!({"source":"local","elapsedMs":start.elapsed().as_millis()}))); + let format = if crate::jiansun_models::is_pricing_catalog(&catalog) { "newapi-pricing" } else { "v2" }; + return Ok((catalog, json!({"source":"local","catalogFormat":format,"elapsedMs":start.elapsed().as_millis()}))); } - let request = self.http.get(format!("{UPSTREAM}/api/v2/catalog/models")) - .header(reqwest::header::ACCEPT_ENCODING, "gzip"); - let response = self.http.read(request).map_err(|error| catalog_transport_error(&error))?; + let fetch = |path| self.http.read(self.http.get(format!("{UPSTREAM}{path}")) + .header(reqwest::header::ACCEPT_ENCODING, "gzip")).map_err(|error| catalog_transport_error(&error)); + let mut response = fetch("/api/v2/catalog/models")?; + let format = if matches!(response.status().as_u16(), 404 | 410 | 405) { + drop(response); + response = fetch("/api/pricing")?; + "newapi-pricing" + } else { "v2" }; let headers_ms = start.elapsed().as_millis(); let status = response.status().as_u16(); if status != 200 { return Err(format!("98k公开模型目录暂不可用(HTTP {status})")); } @@ -1129,7 +1143,7 @@ impl Backend { let body_ms = start.elapsed().as_millis() - headers_ms; if bytes.len() as u64 > LIMIT { return Err("服务响应超过客户端限制".into()); } let catalog = serde_json::from_slice(&bytes).map_err(|_| "98k公开模型目录格式无效")?; - Ok((catalog, json!({"source":"https","encoding":if gzip {"gzip"} else {"identity"}, + Ok((catalog, json!({"source":"https","catalogFormat":format,"encoding":if gzip {"gzip"} else {"identity"}, "wireBytes":content_length,"decodedBytes":bytes.len(),"headersMs":headers_ms,"bodyMs":body_ms, "decodeJsonMs":start.elapsed().as_millis() - headers_ms - body_ms}))) } @@ -1141,17 +1155,17 @@ impl Backend { } fn image_contract(&self, key: &str, choice: &str) -> R<(String, Value)> { let id = self.image_model_id(choice)?; - let permitted = self.key_catalog(key) + let permitted = self.key_catalog_full(key) .map_err(|error| format!("本次生图未提交。模型权限检查失败:{error}"))?; - if !permitted.contains(&id) { + if !permitted.ids.contains(&id) { return Err("个人Key未开放此模型,本次生图未提交".into()); } let catalog = self.public_model_catalog() .map_err(|error| format!("本次生图未提交。{error}"))?; - let contract = crate::jiansun_image_protocol::select(&catalog, &id)?; + let contract = crate::jiansun_image_protocol::select(&catalog, &id, Some(&permitted))?; Ok((id, contract)) } - fn refresh_image_models(&mut self, catalog: &Value, saved: &Value, available: Option<&[String]>) { + fn refresh_image_models(&mut self, catalog: &Value, saved: &Value, available: Option<&crate::jiansun_models::KeyCatalog>) { let choice = saved["imageModel"].as_str().unwrap_or_default(); let legacy = Uuid::parse_str(choice).is_ok().then(|| self.image_model_id(choice)); let previous = legacy.as_ref().and_then(|result| result.as_deref().ok()).map(|id| (choice, id)); @@ -1166,7 +1180,7 @@ impl Backend { } } } - fn key_catalog(&self, key: &str) -> R> { + fn key_catalog_full(&self, key: &str) -> R { let request = self.http.get(format!("{UPSTREAM}/v1/models")).bearer_auth(key); let response = self.http.read(request).map_err(|error| catalog_transport_error(&error))?; if response.status().as_u16() == 401 { return Err("个人Key校验失败(HTTP 401)".into()); } @@ -1174,7 +1188,7 @@ impl Backend { if status != 200 { return Err(format!("个人Key校验失败(HTTP {status})")); } - crate::jiansun_models::key_models(&value) + crate::jiansun_models::key_catalog_full(&value) } fn check_model_authority(&self, response: &Response, key: &str) -> R<()> { if response.status().as_u16() != 401 { return Ok(()); } @@ -1185,7 +1199,7 @@ impl Backend { fn refresh_model_authority(&self, previous: &str) { let settings = self.settings().ok(); let key = settings.as_ref().and_then(|value| value["key"].as_str()).unwrap_or(previous); - let _ = self.key_catalog(key); + let _ = self.key_catalog_full(key); } fn connection_data(&self, saved: &Value, available: Option<&[String]>) -> Value { let key_saved = saved["key"].as_str().is_some_and(|k| (12..=500).contains(&k.len())); @@ -1235,7 +1249,7 @@ impl Backend { if library_status == "connected" || library_status == "unavailable" { let has_key = saved["key"].as_str().filter(|key| !key.is_empty()); if let Some(key) = has_key { - match self.key_catalog(key) { + match self.key_catalog_full(key) { Ok(items) => available = Some(items), Err(error) => { self.image_error = error.clone(); @@ -1246,9 +1260,9 @@ impl Backend { match load_catalog(self) { Ok(catalog) => { if has_key.is_none() || available.is_some() { - self.refresh_image_models(&catalog, &saved, available.as_deref()); + self.refresh_image_models(&catalog, &saved, available.as_ref()); } - if let Err(error) = self.refresh_models(&catalog, &saved) { + if let Err(error) = self.refresh_models(&catalog, &saved, available.as_ref()) { self.copy_error.clone_from(&error); if message.is_empty() { message = error; } } @@ -1273,7 +1287,7 @@ impl Backend { } } }; - let mut result = self.connection_data(&saved, available.as_deref()); + let mut result = self.connection_data(&saved, available.as_ref().map(|catalog| catalog.ids.as_slice())); result["account"] = self.auth["account"].clone(); result["xiaoyiKeySaved"] = json!(knowledge_http::xiaoyi_key_saved()); let knowledge = if library_status == "connected" { @@ -1637,11 +1651,7 @@ impl Backend { if settings["model"].as_str() != Some(chosen) { return Err("请先保存对话模型选择".into()); } - let model = self.live_text_choice(chosen)?; - let available = self.key_catalog(key)?; - if !available.iter().any(|id| model["id"] == id.as_str()) { - return Err("此Key未开放所选对话模型,请在对话栏重新选择".into()); - } + let model = self.live_text_choice(chosen, key)?; let text = input["text"].as_str().filter(|s| !s.trim().is_empty() && s.chars().count() <= 6000).ok_or("请输入6000字以内的要求")?; if !matches!( (model["protocol"].as_str(), model["path"].as_str()), @@ -1658,6 +1668,7 @@ impl Backend { let response = if recover { let id = task["requestId"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("原请求没有可公开查询的编号;保持待核查,不会重发")?; self.http.read(self.http.get(format!("{UPSTREAM}/api/external/requests/{id}/result")).bearer_auth(key)) + .map_err(|error| format!("{};原请求保留待核查", network_message(&error))) } else { let system = format!( "你是由壹点详情页画布 Agent。使用中文,简洁,不虚构产品事实。只能修改当前已存在且未锁定的图层。返回严格 JSON:{{\"reply\":\"简短说明\",\"edits\":[{{\"command\":\"type.edit\",\"params\":{{\"layer\":数字图层ID,\"text\":\"新文字\"}},\"label\":\"修改标题\"}}]}}。最多20步。可用命令仅 type.edit(layer,text,size,color,name)、layer.translate(layer,dx,dy,整数像素)、layer.setProps(layer,name,opacity 0到1,visible)。不能执行文件、终端、代码、脚本、网络。未要求改变的参数保持原样。分析产品或生成图片的请求不要伪装成已完成。文档:{}", @@ -1674,24 +1685,26 @@ impl Backend { self.check_dispatch()?; task["phase"] = json!("dispatched"); write_json(&file, &task)?; - let mut r = self - .http - .post(format!("{UPSTREAM}{}", task["model"]["path"].as_str().ok_or("模型路径无效")?)) - .timeout(Duration::from_secs(180)) - .bearer_auth(key) - .header("Idempotency-Key", task["id"].as_str().ok_or("请求身份无效")?) - .json(&payload); - for (name, value) in pi::invocation_headers(&json!({"invocationHeaders":invocation["headers"]}))? { - r = r.header(name, value); - } - if task["model"]["protocol"] == "anthropic-messages" { - r = r.header("Anthropic-Version", "2023-06-01"); - } - if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); } - r.send() + let model = task["model"].clone(); + let id = task["id"].as_str().ok_or("请求身份无效")?.to_owned(); + let mut requested = model.clone(); + requested["headers"] = invocation["headers"].clone(); + pi::send_text(self, &model, &requested, key, &id, Duration::from_secs(180), |_| true, |request, candidate, attempt_id| { + if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); } + self.check_dispatch()?; + if attempt_id != id { + task["dispatchIdempotencyKey"] = json!(attempt_id); + write_json(&file, &task)?; + } + let mut payload = payload.clone(); + if let Some(max) = candidate["maxTokens"].as_u64() { + payload["max_tokens"] = json!(max.min(4096)); + } + request.json(&payload).send().map_err(|error| format!("{};原请求保留待核查", network_message(&error))) + }) }; let result = (|| -> R { - let response = response.map_err(|error| format!("{};原请求保留待核查", network_message(&error)))?; + let response = response?; if !recover && let Some(id) = response.headers().get("x-request-id").and_then(|v| v.to_str().ok()).filter(|s| Uuid::parse_str(s).is_ok()) { task["requestId"] = json!(id); write_json(&file, &task)?; @@ -1868,19 +1881,19 @@ impl Backend { self.validate()?; let saved = self.settings().unwrap_or_else(|_| json!({})); let catalog = self.public_model_catalog()?; - self.refresh_models(&catalog, &saved)?; let key = input["key"] .as_str() .filter(|s| !s.is_empty()) .or_else(|| saved["key"].as_str()) .filter(|s| (12..=500).contains(&s.len())) .ok_or("请填写个人98k Key")?; - let available = self.key_catalog(key)?; + let available = self.key_catalog_full(key)?; + self.refresh_models(&catalog, &saved, Some(&available))?; self.refresh_image_models(&catalog, &saved, Some(&available)); - let settings = crate::jiansun_models::selection(input, &saved, &self.models, &self.copy_models, &self.image_models, &available)?; + let settings = crate::jiansun_models::selection(input, &saved, &self.models, &self.copy_models, &self.image_models, &available.ids)?; vault(&format!("models:{}", self.scope()))?.set_password(&settings.to_string()).map_err(|_| "个人Key未能保存到系统凭据库")?; self.model = settings["model"].as_str().unwrap_or("").into(); - Ok(self.connection_data(&settings, Some(&available))) + Ok(self.connection_data(&settings, Some(&available.ids))) } "draft" => self.draft(input["doc"].as_u64().ok_or("项目编号无效")?), "production-settings" => { @@ -3130,19 +3143,19 @@ mod tests { b.validate().unwrap(); let saved = b.settings().unwrap(); let catalog = b.public_model_catalog().unwrap(); - b.refresh_models(&catalog, &saved).unwrap(); - let available = b.key_catalog(saved["key"].as_str().unwrap()).unwrap(); + let available = b.key_catalog_full(saved["key"].as_str().unwrap()).unwrap(); + b.refresh_models(&catalog, &saved, Some(&available)).unwrap(); b.refresh_image_models(&catalog, &saved, Some(&available)); - let selectable_text: Vec<_> = b.models.iter().filter(|m| m["id"].as_str().is_some_and(|id| available.iter().any(|item| item == id))) + let selectable_text: Vec<_> = b.models.iter().filter(|m| m["id"].as_str().is_some_and(|id| available.ids.iter().any(|item| item == id))) .filter_map(|m| m["id"].as_str()).collect(); assert!(!selectable_text.is_empty()); println!("{} {}", "可选对话模型", selectable_text.join(", ")); - let public = b.connection_data(&saved, Some(&available)); + let public = b.connection_data(&saved, Some(&available.ids)); assert!(!b.image_models.is_empty(), "{}", b.image_error); assert_eq!(public["keySaved"], true); println!( "{}", - json!({"chatModels":b.models.len(),"imageModels":b.image_models.len(),"keyCatalogue":available.len(),"savedChatReady":public["modelReady"],"imageChoices":b.image_models.iter().map(|m|json!({"id":m["id"],"available":available.iter().any(|id|m["id"]==*id)})).collect::>()}) + json!({"chatModels":b.models.len(),"imageModels":b.image_models.len(),"keyCatalogue":available.ids.len(),"savedChatReady":public["modelReady"],"imageChoices":b.image_models.iter().map(|m|json!({"id":m["id"],"available":available.ids.iter().any(|id|m["id"]==*id)})).collect::>()}) ); } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index f7471153..02ddc887 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -792,12 +792,12 @@ impl Backend { let key = settings["key"].as_str().ok_or("请连接个人98k Key")?; let choice = crate::jiansun_models::text_selection(&settings,stage).as_str().filter(|key| !key.is_empty()) .ok_or(if stage == "facts" { "请选择可读图的对话模型" } else { "请选择文案模型" })?; - let selected = self.live_text_choice(choice)?; + let mut selected = self.live_text_choice(choice, key)?; if stage == "facts" && selected["supportsImageInput"] != true { return Err("资料分析需要可读图的对话模型".into()); } - if !self.key_catalog(key)?.iter().any(|id| selected["id"] == id.as_str()) { - return Err("个人Key尚未开放所选模型".into()); + if stage == "facts" && let Some(candidates) = selected["candidates"].as_array_mut() { + candidates.retain(|candidate| candidate["supportsImageInput"] == true); } Ok((settings, selected)) } @@ -870,6 +870,7 @@ impl Backend { task["requestId"] = json!(rid); task_save(&dir, &task)?; self.http.get(format!("{UPSTREAM}/api/external/requests/{rid}/result")).bearer_auth(key).send() + .map_err(|error| stream::transport_error(&error)) } else { let mut pictures = Vec::new(); let mut total = 0usize; @@ -892,24 +893,24 @@ impl Backend { task["phase"] = json!("dispatched"); task["message"] = json!("模型处理中;不会自动重发"); task_save(&dir, &task)?; - let mut req = self - .http - .post(format!("{UPSTREAM}{}", task["model"]["path"].as_str().ok_or("模型路径无效")?)) - .timeout(CREATION_REQUEST_TIMEOUT) - .bearer_auth(key) - .header("Idempotency-Key", task["id"].as_str().ok_or("任务身份无效")?) - .json(&payload); - for (name, value) in pi::invocation_headers(&json!({"invocationHeaders":invocation["headers"]}))? { - req = req.header(name, value); - } - if anthropic { - req = req.header("Anthropic-Version", "2023-06-01"); - } - if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); } - self.check_dispatch()?; - req.send() + let id = task["id"].as_str().ok_or("任务身份无效")?.to_owned(); + request_model["headers"] = invocation["headers"].clone(); + pi::send_text(self, &request_model, &request_model, key, &id, CREATION_REQUEST_TIMEOUT, |_| true, + |request, candidate, attempt_id| { + if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); } + self.check_dispatch()?; + if attempt_id != id { + task["dispatchIdempotencyKey"] = json!(attempt_id); + task_save(&dir, &task)?; + } + let mut payload = payload.clone(); + if let Some(max) = candidate["maxTokens"].as_u64() { + payload["max_tokens"] = json!(payload["max_tokens"].as_u64().map_or(max, |limit| limit.min(max))); + } + request.json(&payload).send().map_err(|error| stream::transport_error(&error)) + }) }; - let response = response.map_err(|error| stream::transport_error(&error))?; + let response = response?; if !recover && let Some(rid) = response.headers().get("x-request-id").and_then(|s| s.to_str().ok()).filter(|s| Uuid::parse_str(s).is_ok()) { task["requestId"] = json!(rid); task_save(&dir, &task)?; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs index e98fed08..645224c8 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_protocol.rs @@ -177,14 +177,20 @@ pub(super) fn requested_dimensions(contract: &Value) -> Option<[u32; 2]> { dimensions.iter().all(|edge| (1..=30000).contains(edge)).then_some(dimensions) } -pub fn catalog_models(catalog: &Value) -> Result, String> { - let sections = catalog["data"]["sections"].as_array().ok_or("98k没有返回有效的公开模型目录")?; - Ok(sections.iter().take(20).flat_map(|section| section["models"].as_array().into_iter().flatten().take(5000))) +pub(super) fn catalog_models<'a>(catalog: &'a Value, key: Option<&super::jiansun_models::KeyCatalog>) -> Result>, String> { + use std::borrow::Cow; + let pricing = super::jiansun_models::is_pricing_catalog(catalog); + let sections = if pricing { &[][..] } else { + catalog["data"]["sections"].as_array().ok_or("98k没有返回有效的公开模型目录")?.as_slice() + }; + let rows = if pricing { super::jiansun_models::pricing_models(catalog, key) } else { Vec::new() }; + Ok(sections.iter().take(20).flat_map(|section| section["models"].as_array().into_iter().flatten().take(5000)) + .map(Cow::Borrowed).chain(rows.into_iter().map(Cow::Owned))) } -pub fn select(catalog: &Value, model: &str) -> Result { - let model = catalog_models(catalog)?.find(|row| row["id"] == model).ok_or("98k目录没有所选模型")?; - select_model(model) +pub(super) fn select(catalog: &Value, model: &str, key: Option<&super::jiansun_models::KeyCatalog>) -> Result { + let model = catalog_models(catalog, key)?.find(|row| row["id"] == model).ok_or("98k目录没有所选模型")?; + select_model(&model) } pub fn select_model(m: &Value) -> Result { @@ -194,6 +200,15 @@ pub fn select_model(m: &Value) -> Result { fn select_model_route(m: &Value, pinned: Option<&str>) -> Result { let model = m["id"].as_str().ok_or("98k模型编号无效")?; + if m["catalogFormat"] == "newapi-pricing" { + let endpoints = m["endpoints"].as_array().ok_or("98k模型接口无效")?; + let path = ["/v1/images/generations", "/v1/images/edits"].into_iter() + .find(|path| endpoints.iter().any(|endpoint| endpoint == *path)) + .ok_or("所选生图模型当前不可用")?; + let multipart = path == "/v1/images/edits"; + return Ok(json!({"path":path,"route":null,"field":"image","multipart":multipart, + "probe":true,"maxImages":8,"schema":{},"parameters":{"n":1,"response_format":"b64_json"},"jpegReferences":false})); + } if m["available"] == false || m["status"].as_str().is_some_and(|s| s != "available") || m["modality"] != "image" { return Err("所选生图模型当前不可用".into()); } @@ -387,7 +402,7 @@ mod tests { #[test] fn published_open_contract_matches_the_existing_adapter_probe() { let c = catalog(); - let p = select(&c, "test-image").unwrap(); + let p = select(&c, "test-image", None).unwrap(); assert_eq!(p["field"], "image"); assert_eq!(p["probe"], true); assert_eq!(p["maxImages"], 8); @@ -399,7 +414,7 @@ mod tests { invocation["path"] = json!(path); invocation["content_type"] = json!(content_type); invocation["input_schema"] = schema; - select(&c, "test-image") + select(&c, "test-image", None) } fn edit_schema(output_format: Value, output_compression: Option, background: &str) -> Value { let mut schema = json!({"type":"object","additionalProperties":true,"properties":{"model":{"type":"string"},"prompt":{"type":"string"}, @@ -456,7 +471,7 @@ mod tests { assert_eq!(format(Some(json!({"enum":["b64_json"]}))), "b64_json"); assert_eq!(format(Some(json!({"type":["string","null"]}))), "b64_json", "an open string does not list URL delivery"); assert_eq!(format(None), "b64_json"); - assert_eq!(select(&catalog(), "test-image").unwrap()["parameters"]["response_format"], "b64_json"); + assert_eq!(select(&catalog(), "test-image", None).unwrap()["parameters"]["response_format"], "b64_json"); } #[test] fn references_compress_only_where_the_route_accepts_a_jpeg_reference() { @@ -469,17 +484,17 @@ mod tests { assert_eq!(png_only["jpegReferences"], false); let any_image = route("/v1/images/edits", "application/json", schema("^data:image/[^;,]+;base64,")).unwrap(); assert_eq!(any_image["jpegReferences"], true); - assert_eq!(select(&catalog(), "test-image").unwrap()["jpegReferences"], true, "an open probe field is unrestricted"); + assert_eq!(select(&catalog(), "test-image", None).unwrap()["jpegReferences"], true, "an open probe field is unrestricted"); } #[test] fn explicit_reference_denial_and_nondefault_scopes_are_not_probed() { let mut c = catalog(); let m = &mut c["data"]["sections"][0]["models"][0]; m["service_offers"][0]["route_options"][0]["invocation"]["input_schema"]["properties"]["image"] = json!(false); - assert!(select(&c, "test-image").is_err()); + assert!(select(&c, "test-image", None).is_err()); let mut c = catalog(); c["data"]["sections"][0]["models"][0]["default_service_scope_id"] = json!("different-scope"); - assert!(select(&c, "test-image").is_err()); + assert!(select(&c, "test-image", None).is_err()); } #[test] fn schema_restrictions_are_not_overridden() { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index efdf3d6a..afea21d5 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -505,6 +505,9 @@ fn locate_original( ) -> R { let task_id = task["id"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("原任务身份无效,未发起查询")?.to_owned(); let (code, body) = get("/api/external/requests/by-idempotency-key", Some(&task_id))?; + if code == 404 && task["protocol"].is_object() && task["protocol"]["route"].is_null() { + return Err("98k 标准接口未提供原请求查询(HTTP 404),保留待核查".into()); + } if observed_wait("lookup", code, &body) == Some(RecoveryWait::RequestNotFound) && task["requestNotFoundSince"].is_null() { @@ -1179,6 +1182,7 @@ impl Backend { Value::Null } else { let session = Uuid::new_v4().to_string(); + let standard_route = t["protocol"]["route"].is_null(); match checked_original_response( &mut t, |path, idempotency| { @@ -1213,8 +1217,12 @@ impl Backend { return Ok((410, Value::Null)); } self.check_model_authority(&response, key)?; - let decoded = body(response, if matches!(kind, "lookup" | "task-status") { 64 * 1024 } else { RESPONSE_BYTES }) - .inspect_err(|_| wait.set(Some(RecoveryWait::Network)))?; + let decoded = if kind == "lookup" && response.status().as_u16() == 404 && standard_route { + (404, Value::Null) + } else { + body(response, if matches!(kind, "lookup" | "task-status") { 64 * 1024 } else { RESPONSE_BYTES }) + .inspect_err(|_| wait.set(Some(RecoveryWait::Network)))? + }; if let Some(observed) = observed_wait(kind, decoded.0, &decoded.1) { wait.set(Some(observed)); } @@ -1256,8 +1264,10 @@ impl Backend { .post(format!("{UPSTREAM}{}", p["path"].as_str().ok_or("模型路径无效")?)) .timeout(IMAGE_POST_TIMEOUT) .bearer_auth(key) - .header("Idempotency-Key", t["id"].as_str().ok_or("任务身份无效")?) - .header("X-Relay-Route-Option", p["route"].as_str().ok_or("线路身份无效")?); + .header("Idempotency-Key", t["id"].as_str().ok_or("任务身份无效")?); + if let Some(route) = p["route"].as_str().filter(|route| !route.is_empty()) { + req = req.header("X-Relay-Route-Option", route); + } if p["multipart"] == true { req = req.multipart(multipart_form(&t, files)?); } else { @@ -2231,6 +2241,23 @@ mod tests { fn attempt_receipt(outcome: R, wait: Option) -> R { Ok(outcome.unwrap_or_else(|reason| json!({"phase":"unknown","reply":reason,"recoveryWait":wait.map(RecoveryWait::name)}))) } + + #[test] + fn missing_standard_lookup_keeps_the_original_image_pending() { + let mut task = json!({"id":Uuid::new_v4().to_string(),"phase":"unknown", + "protocol":{"path":"/v1/images/generations","route":null}}); + let saved = task.clone(); + let mut queries = 0; + let result = original_response(&mut task, |path, idempotency| { + queries += 1; + assert_eq!(path, "/api/external/requests/by-idempotency-key"); + assert_eq!(idempotency, saved["id"].as_str()); + Ok((404, Value::Null)) + }, |_| panic!("unsupported lookup must not update the paid task")); + assert!(matches!(result, Err(message) if message.contains("HTTP 404"))); + assert_eq!(queries, 1); + assert_eq!(task, saved); + } fn observing<'a>(wait: &'a std::cell::Cell>, mut get: impl FnMut(&str, Option<&str>) -> R<(u16, Value)> + 'a) -> impl FnMut(&str, Option<&str>) -> R<(u16, Value)> + 'a { move |path, key| { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs index 0873ba15..fe4e5e31 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_models.rs @@ -1,6 +1,6 @@ //! Personal-key model selections. Platform policy and the key's catalogue both apply. use serde_json::{Value, json}; -use std::{collections::HashSet, path::Path}; +use std::{collections::{HashMap, HashSet}, path::Path}; type R = Result; pub fn legacy_image_id(catalog: &Value, choice: &str) -> R { @@ -12,15 +12,15 @@ pub fn legacy_image_id(catalog: &Value, choice: &str) -> R { .ok_or_else(|| "原生图模型无法识别,请在设置中重新选择".into()) } -pub fn image_choices(catalog: &Value, available: Option<&[String]>, previous: Option<(&str, &str)>) -> R> { +pub(super) fn image_choices(catalog: &Value, available: Option<&KeyCatalog>, previous: Option<(&str, &str)>) -> R> { use crate::jiansun_image_protocol::{catalog_models, select_model}; - let allowed = available.map(|ids| ids.iter().map(String::as_str).collect::>()); + let allowed = available.map(|key| key.ids.iter().map(String::as_str).collect::>()); let mut seen = HashSet::new(); let mut out = Vec::new(); - for model in catalog_models(catalog)? { + for model in catalog_models(catalog, available)? { let Some(id) = model["id"].as_str().filter(|id| !id.is_empty() && id.len() <= 200) else { continue }; - if !seen.insert(id) || allowed.as_ref().is_some_and(|ids| !ids.contains(id)) || select_model(model).is_err() { + if !seen.insert(id.to_owned()) || allowed.as_ref().is_some_and(|ids| !ids.contains(id)) || select_model(&model).is_err() { continue; } let key = previous.filter(|(_, legacy_id)| *legacy_id == id).map_or(id, |(key, _)| key); @@ -31,6 +31,85 @@ pub fn image_choices(catalog: &Value, available: Option<&[String]>, previous: Op pub(super) const DETAIL_ROUTE_UNVERIFIED: &str = "当前模型暂无同时开放读图和工具调用的线路。请换一个可制作的对话模型。"; +#[derive(Default)] +pub(super) struct KeyCatalog { + pub ids: Vec, + pub endpoints: HashMap>, +} + +pub(super) fn is_pricing_catalog(catalog: &Value) -> bool { + catalog["success"] == true && catalog["data"].is_array() +} + +pub(super) fn pricing_models(catalog: &Value, authorized: Option<&KeyCatalog>) -> Vec { + let rows = catalog["data"].as_array().into_iter().flatten().take(5000); + let published: HashMap<_, _> = rows.clone().filter_map(|row| Some((row["model_name"].as_str()?, row))).collect(); + let ids: Vec<_> = match authorized { + Some(key) => key.ids.iter().map(String::as_str).collect(), + None => rows.filter_map(|row| row["model_name"].as_str()).collect(), + }; + ids.into_iter().filter(|id| !id.is_empty() && id.len() <= 200).map(|id| { + let row = published.get(id).copied().unwrap_or(&Value::Null); + let types: Vec<_> = authorized.and_then(|key| key.endpoints.get(id)) + .map(|types| types.iter().map(String::as_str).collect()) + .unwrap_or_else(|| row["supported_endpoint_types"].as_array().into_iter().flatten().filter_map(Value::as_str).collect()); + let default = row["default_endpoint_type"].as_str().filter(|kind| types.contains(kind)); + let mut seen = HashSet::new(); + let endpoints: Vec<_> = default.into_iter().chain(types).filter_map(|kind| { + let declared = &catalog["supported_endpoint"][kind]; + if !declared.is_null() { + return (declared["method"] == "POST").then(|| declared["path"].as_str()).flatten(); + } + match kind { + "openai" => Some("/v1/chat/completions"), + "openai-response" | "openai-responses" => Some("/v1/responses"), + "anthropic" => Some("/v1/messages"), + "image-generation" | "openai-image" => Some("/v1/images/generations"), + "image-edit" => Some("/v1/images/edits"), + _ => None, + } + }).filter(|path| seen.insert(*path)).collect(); + json!({"id":id,"catalogFormat":"newapi-pricing","endpoints":endpoints}) + }).collect() +} + +fn chat_protocol(path: &str, responses: bool) -> Option<&'static str> { + match path { + "/v1/chat/completions" => Some("openai-chat"), + "/v1/responses" if responses => Some("openai-responses"), + "/v1/messages" => Some("anthropic-messages"), + _ => None, + } +} + +fn standard_candidate(path: &str, protocol: &str, image_input: bool) -> Value { + let anthropic = protocol == "anthropic-messages"; + json!({"protocol":protocol,"path":path,"headers":{},"routeId":null,"requireSingleTool":false, + "requiresOutputLimit":anthropic,"maxTokens":anthropic.then_some(8192),"reasoning":false, + "reasoningEfforts":[],"supportsImageInput":image_input,"hasSchema":false}) +} + +fn model_with_candidates(id: &str, key: Option<&str>, candidates: Vec, format: &str) -> Option { + let mut model = candidates.first()?.clone(); + model["key"] = json!(key.unwrap_or(id)); + model["id"] = json!(id); + model["label"] = json!(id); + model["catalogFormat"] = json!(format); + model["productionReady"] = model["supportsImageInput"].clone(); + model["candidates"] = json!(candidates); + Some(model) +} + +fn add_openai_alternate(candidates: &mut Vec, image_input: bool) { + let chat = candidates.iter().any(|candidate| candidate["protocol"] == "openai-chat"); + let responses = candidates.iter().any(|candidate| candidate["protocol"] == "openai-responses"); + if chat && !responses { + candidates.push(standard_candidate("/v1/responses", "openai-responses", image_input)); + } else if responses && !chat { + candidates.push(standard_candidate("/v1/chat/completions", "openai-chat", image_input)); + } +} + fn text_protocol(invocation: &Value, responses: bool) -> Option<&'static str> { if invocation["method"] != "POST" || invocation["content_type"] != "application/json" { return None; @@ -49,11 +128,28 @@ fn text_protocol(invocation: &Value, responses: bool) -> Option<&'static str> { pub(super) fn text_routes(row: &Value) -> impl Iterator { row["service_offers"].as_array().into_iter().flatten() + .filter(|offer| offer["available"] != false && offer["status"] != "disabled") .filter_map(|offer| offer["route_options"].as_array()).flatten() - .filter(|route| route["available"] == true && route["id"].is_string() + .filter(|route| route["available"] == true && route["status"] != "disabled" && route["id"].is_string() && route["id"] == route["invocation"]["headers"]["X-Relay-Route-Option"]) } +pub(super) fn text_catalog_headers(invocation: &Value, protocol: &str) -> R { + let mut headers = invocation.get("headers").cloned().unwrap_or_else(|| json!({})); + let fields = headers.as_object_mut().ok_or("公开调用头无效")?; + if let Some(version) = fields.remove("Anthropic-Version") + && (protocol != "anthropic-messages" || version != "2023-06-01") + { + return Err("当前模型版本与客户端协议不一致,未调用".into()); + } + for (name, value) in fields { + if name != "X-Relay-Route-Option" || value.as_str().is_none_or(|id| uuid::Uuid::parse_str(id).is_err()) { + return Err("公开调用头未授权".into()); + } + } + Ok(headers) +} + pub(super) fn reasoning_options<'a>(protocol: &str, properties: &'a Value) -> (bool, Vec<&'a str>) { let effort = if protocol == "openai-responses" { &properties["reasoning"]["properties"]["effort"] } else { &properties["reasoning_effort"] }; @@ -97,6 +193,18 @@ pub(super) fn text_model(row: &Value, key: Option<&str>) -> Option { pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> Option { let id = row["id"].as_str().filter(|id| !id.is_empty() && id.len() <= 200)?; + if row["catalogFormat"] == "newapi-pricing" { + let mut candidates: Vec<_> = row["endpoints"].as_array()?.iter().filter_map(|path| { + let path = path.as_str()?; + Some(standard_candidate(path, chat_protocol(path, responses)?, true)) + }).collect(); + if responses { + add_openai_alternate(&mut candidates, true); + } else if candidates.is_empty() && row["endpoints"].as_array()?.iter().any(|path| path == "/v1/responses") { + candidates.push(standard_candidate("/v1/chat/completions", "openai-chat", true)); + } + return model_with_candidates(id, key, candidates, "newapi-pricing"); + } if row["status"] != "available" || row["available"] != true || !matches!(row["modality"].as_str(), Some("text" | "multimodal")) { @@ -107,21 +215,46 @@ pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> let preferred = |route: &Value| route["is_default"] == true || route["id"] == row["default_route_option_id"]; let image_preference = |route: &Value| image_input && allows_image_tools(route); - let route = text_routes(row).filter(|route| allows_streaming_tools(route)) - .filter_map(|route| Some((route, text_protocol(&route["invocation"], responses)?))) - .min_by(|(a, _), (b, _)| { - let (a_input, a_output) = token_prices(a); - let (b_input, b_output) = token_prices(b); - image_preference(b).cmp(&image_preference(a)) - .then(a_input.total_cmp(&b_input)).then(a_output.total_cmp(&b_output)) - .then_with(|| preferred(b).cmp(&preferred(a))) - }); - let (contract, protocol, route_id) = match route { - Some((route, protocol)) => (route, protocol, route["id"].as_str()), - None if row["service_offers"].is_null() && allows_streaming_tools(row) => - (row, text_protocol(&row["invocation"], responses)?, None), - None => return None, + let verified = |route: &Value| { + let capabilities = &route["chat_capabilities"]; + capabilities["streaming_tools"] == "verified" + || image_preference(route) && capabilities["image_base64_streaming_tools"] == "verified" }; + let mut routes: Vec<_> = text_routes(row).filter(|route| allows_streaming_tools(route)) + .filter_map(|route| Some((route, text_protocol(&route["invocation"], responses)?))) + .collect(); + routes.sort_by(|(a, _), (b, _)| { + let (a_input, a_output) = token_prices(a); + let (b_input, b_output) = token_prices(b); + image_preference(b).cmp(&image_preference(a)).then_with(|| verified(b).cmp(&verified(a))) + .then(a_input.total_cmp(&b_input)).then(a_output.total_cmp(&b_output)) + .then_with(|| preferred(b).cmp(&preferred(a))) + }); + let mut candidates: Vec<_> = routes.into_iter().filter_map(|(route, protocol)| { + typed_candidate(route, protocol, route["id"].as_str(), image_input) + }).collect(); + if candidates.is_empty() && row["service_offers"].is_null() && allows_streaming_tools(row) { + candidates.push(typed_candidate(row, text_protocol(&row["invocation"], responses)?, None, image_input)?); + } + let mut unpinned = Vec::new(); + for candidate in &candidates { + if candidate["headers"] != json!({}) && !unpinned.iter().any(|other: &Value| other["path"] == candidate["path"]) { + let mut fallback = candidate.clone(); + fallback["routeId"] = Value::Null; + fallback["headers"] = json!({}); + fallback["productionVerified"] = json!(false); + unpinned.push(fallback); + } + } + candidates.extend(unpinned); + if responses { + let image_ready = candidates.iter().any(|candidate| candidate["supportsImageInput"] == true); + add_openai_alternate(&mut candidates, image_ready); + } + model_with_candidates(id, key, candidates, "v2") +} + +fn typed_candidate(contract: &Value, protocol: &str, route_id: Option<&str>, image_input: bool) -> Option { let path = contract["invocation"]["path"].as_str()?; let properties = &contract["invocation"]["input_schema"]["properties"]; let (reasoning, reasoning_efforts) = reasoning_options(protocol, properties); @@ -131,19 +264,33 @@ pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> let capabilities = &contract["chat_capabilities"]; let image_status = capabilities["image_base64"].as_str().unwrap_or("unverified"); let image_ready = image_input && allows_image_tools(contract); - Some(json!({"key":key.unwrap_or(id),"id":id,"label":id,"protocol":protocol,"path":path, + let output_field = if protocol == "openai-responses" { "max_output_tokens" } else { "max_tokens" }; + let requires_output = contract["invocation"]["input_schema"]["required"].as_array().into_iter().flatten() + .any(|field| field == output_field || field == "max_completion_tokens"); + let headers = text_catalog_headers(&contract["invocation"], protocol).ok()?; + Some(json!({"protocol":protocol,"path":path,"headers":headers,"hasSchema":true, "routeId":route_id,"imageInputStatus":image_status,"supportsImageInput":image_ready, - "productionReady":image_ready,"productionVerified":capabilities["image_base64_streaming_tools"] == "verified", + "requiresOutputLimit":requires_output,"maxTokens":properties[output_field]["maximum"].as_u64().filter(|n| (1..=9_007_199_254_740_991).contains(n)), + "productionVerified":capabilities["image_base64_streaming_tools"] == "verified", "requireSingleTool":require_single_tool,"reasoning":reasoning,"reasoningEfforts":reasoning_efforts})) } -pub fn key_models(catalog: &Value) -> R> { - let rows = catalog["data"].as_array().filter(|a| a.len() <= 2000).ok_or("98k没有返回有效的模型目录")?; - let mut out = Vec::new(); +pub(super) fn key_catalog_full(catalog: &Value) -> R { + let rows = catalog["data"].as_array().filter(|a| a.len() <= 5000).ok_or("98k没有返回有效的模型目录")?; + let mut out = KeyCatalog::default(); + let mut seen = HashSet::new(); for row in rows { let id = row["id"].as_str().filter(|s| !s.is_empty() && s.len() <= 200).ok_or("98k模型编号无效")?; - if !out.iter().any(|s| s == id) { - out.push(id.to_owned()); + if seen.insert(id) { + out.ids.push(id.to_owned()); + } + if let Some(types) = row["supported_endpoint_types"].as_array() { + let endpoints = out.endpoints.entry(id.to_owned()).or_default(); + for kind in types.iter().filter_map(Value::as_str) { + if !endpoints.iter().any(|value| value == kind) { + endpoints.push(kind.to_owned()); + } + } } } Ok(out) @@ -231,7 +378,11 @@ pub(super) fn detail_selection(models: &[Value], settings: &Value, authorized: & if model["productionReady"] != true { return Err(DETAIL_ROUTE_UNVERIFIED.into()); } - Ok(model.clone()) + let mut model = model.clone(); + if let Some(candidates) = model["candidates"].as_array_mut() { + candidates.retain(|candidate| candidate["supportsImageInput"] == true); + } + Ok(model) } pub(super) fn load_pi_catalog(root:&Path)->R> { @@ -293,6 +444,22 @@ pub(super) fn apply_pi_capacity(model: &mut Value, catalog: &[Value]) { model["maxTokens"] = chosen["maxTokens"].clone(); model["maxTokensSource"] = json!(source); } + if model["catalogFormat"] == "newapi-pricing" { + if let Some(chosen) = output_entry.or(context_entry) { + if let Some(input) = chosen["input"].as_array() { + let image = input.iter().any(|mode| mode == "image"); + model["supportsImageInput"] = json!(image); + model["productionReady"] = json!(image); + } + model["reasoning"] = json!(chosen["reasoning"] == true); + if chosen["reasoning"] == true { + let levels: Vec<_> = ["minimal", "low", "medium", "high", "xhigh", "max"].into_iter() + .filter(|level| chosen["thinkingLevelMap"].get(*level).is_some_and(|value| !value.is_null())) + .collect(); + model["reasoningEfforts"] = json!(levels); + } + } + } let context_declared = model["contextWindow"].as_u64().is_some_and(|limit| limit > 0) && model["contextWindowSource"].as_str().is_some_and(|source| !source.is_empty()); if let Some(chosen) = context_entry.filter(|_| !context_declared) { @@ -305,6 +472,27 @@ pub(super) fn apply_pi_capacity(model: &mut Value, catalog: &[Value]) { mod tests { use super::*; + #[test] + fn pricing_uses_key_endpoints_and_keeps_private_models() { + let pricing = json!({"success":true,"supported_endpoint":{"vip-messages":{"method":"POST","path":"/v1/messages"}}, + "data":[{"model_name":"shared","default_endpoint_type":"openai","supported_endpoint_types":["openai"]}, + {"model_name":"public-only","supported_endpoint_types":["openai"]}]}); + let authorized = key_catalog_full(&json!({"data":[ + {"id":"shared","supported_endpoint_types":["vip-messages"]}, + {"id":"private-image","supported_endpoint_types":["image-edit"]}, + ]})).unwrap(); + let rows = pricing_models(&pricing, Some(&authorized)); + assert_eq!(rows.len(), 2); + let shared = text_model(&rows[0], None).unwrap(); + assert_eq!(shared["candidates"].as_array().unwrap().len(), 1); + assert_eq!(shared["protocol"], "anthropic-messages"); + assert_eq!(shared["maxTokens"], 8192); + let image = crate::jiansun_image_protocol::select(&pricing, "private-image", Some(&authorized)).unwrap(); + assert_eq!(image["path"], "/v1/images/edits"); + assert_eq!(image["multipart"], true); + assert!(image["route"].is_null()); + } + #[test] fn missing_model_data_tells_the_user_to_install_the_complete_client() { let root = tempfile::tempdir().unwrap(); @@ -409,7 +597,7 @@ mod tests { } #[test] - fn selects_the_cheapest_compatible_chat_route() { + fn prefers_verified_routes_then_uses_price_for_equally_verified_routes() { let catalog = priced_catalog(); let mut row = catalog["data"]["sections"][0]["models"][0].clone(); let settings = json!({"model":"gpt-6.1-sol"}); @@ -418,9 +606,9 @@ mod tests { detail_selection(&[text_model(row, None).unwrap()], &settings, &authorized).unwrap() }; let chosen = selected(&row); - assert_eq!(chosen["routeId"], "ec73a238-b634-429e-b137-6f7c925fbec6"); - assert_eq!(chosen["protocol"], "openai-chat"); - assert_eq!(chosen["imageInputStatus"], "unverified"); + assert_eq!(chosen["routeId"], "fc285847-523f-4b4e-b4d1-b70ad0c5044b"); + assert_eq!(chosen["protocol"], "openai-responses"); + assert_eq!(chosen["imageInputStatus"], "verified"); assert_eq!(chosen["productionReady"], true); for route in row["service_offers"].as_array_mut().unwrap().iter_mut() @@ -428,7 +616,7 @@ mod tests { { if route["chat_capabilities"]["streaming_tools"] == "disabled" { route["pricing"]["token_intervals"][0]["input_price_per_million"] = json!(0.0); - } else if route["id"] == chosen["routeId"] { + } else if route["id"] == chosen["routeId"] || route["is_default"] == true { route["chat_capabilities"]["image_base64_streaming_tools"] = json!("disabled"); } } @@ -441,7 +629,7 @@ mod tests { } #[test] - fn uses_the_default_chat_route_when_prices_match() { + fn uses_the_default_route_when_prices_and_verification_match() { let catalog = priced_catalog(); let mut row = catalog["data"]["sections"][0]["models"][0].clone(); let routes = row["service_offers"].as_array_mut().unwrap(); @@ -449,6 +637,9 @@ mod tests { .find(|route| route["is_default"] == true).unwrap().clone(); for route in routes.iter_mut().flat_map(|offer| offer["route_options"].as_array_mut().unwrap()) { route["pricing"] = default["pricing"].clone(); + if route["chat_capabilities"]["streaming_tools"] != "disabled" { + route["chat_capabilities"] = default["chat_capabilities"].clone(); + } } routes.reverse(); assert_eq!(text_model(&row, None).unwrap()["routeId"], default["id"]); @@ -457,7 +648,7 @@ mod tests { #[test] fn selects_the_lowest_priced_image_edit_route() { let mut catalog = priced_catalog(); - let route = crate::jiansun_image_protocol::select(&catalog, "gpt-image-2.6-sunburst").unwrap(); + let route = crate::jiansun_image_protocol::select(&catalog, "gpt-image-2.6-sunburst", None).unwrap(); assert_eq!(route["route"], "5f6271d9-55a2-444f-a999-5165d2230ab0"); assert_eq!(route["path"], "/v1/images/edits"); @@ -558,7 +749,7 @@ mod tests { let legacy = json!({"modelOptions":{"image":[{"value":"saved-key","label":"previous"},{"value":"another-key","label":"new"}]}}); let saved_id = legacy_image_id(&legacy, "saved-key").unwrap(); let allowed = ["previous","new","down","text","video-contract"].map(str::to_owned); - let list = image_choices(&catalog, Some(&allowed), Some(("saved-key", &saved_id))).unwrap(); + let list = image_choices(&catalog, Some(&KeyCatalog { ids: allowed.to_vec(), ..KeyCatalog::default() }), Some(("saved-key", &saved_id))).unwrap(); assert_eq!(list.iter().map(|row| row["key"].as_str().unwrap()).collect::>(), ["saved-key", "new"]); assert_eq!(list[0]["id"], "previous"); assert_eq!(image_choices(&catalog, None, None).unwrap().len(), 3); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs index 9deb4bf8..5e9e12ac 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi.rs @@ -145,6 +145,71 @@ pub(super) fn invocation_headers(input: &Value) -> R> { } Ok(result) } + +fn authorized_candidate(model: &Value, legacy_headers: &Value, input: &Value) -> Option { + if let Some(candidates) = model["candidates"].as_array() { + return candidates.iter().find(|candidate| candidate["path"] == input["invocationPath"] + && candidate["headers"] == input["invocationHeaders"]).cloned(); + } + if input["invocationPath"] != model["path"] || input["invocationHeaders"] != *legacy_headers { + return None; + } + let mut candidate = model.clone(); + candidate["headers"] = legacy_headers.clone(); + Some(candidate) +} + +fn same_protocol_attempts(model: &Value, requested: &Value, mut compatible: impl FnMut(&Value) -> bool) -> Vec { + let mut attempts = vec![requested.clone()]; + let candidates = model["candidates"].as_array().into_iter().flatten().filter(|candidate| { + candidate["protocol"] == requested["protocol"] && candidate["path"] == requested["path"] + && candidate["headers"] != requested["headers"] + }); + if let Some(route) = candidates.clone().find(|candidate| candidate["routeId"].is_string() && compatible(candidate)) { + attempts.push(route.clone()); + } + if let Some(unpinned) = candidates.filter(|candidate| candidate["headers"] == json!({})).find(|candidate| compatible(candidate)) { + attempts.push(unpinned.clone()); + } + attempts +} + +pub(super) fn send_text( + backend: &Backend, model: &Value, requested: &Value, key: &str, id: &str, timeout: Duration, + compatible: impl FnMut(&Value) -> bool, + mut send: impl FnMut(reqwest::blocking::RequestBuilder, &Value, &str) -> R, +) -> R { + let attempts = same_protocol_attempts(model, requested, compatible); + let mut attempts = attempts.iter().peekable(); + let mut request_id = id.to_owned(); + while let Some(candidate) = attempts.next() { + let path = candidate["path"].as_str().ok_or("模型路径无效")?; + if !matches!(path, "/v1/chat/completions" | "/v1/responses" | "/v1/messages") { + return Err("模型路径无效".into()); + } + let mut request = backend.http.post(format!("{UPSTREAM}{path}")).timeout(timeout) + .bearer_auth(key).header("Idempotency-Key", &request_id); + for (name, value) in invocation_headers(&json!({"invocationHeaders":candidate["headers"]}))? { + request = request.header(name, value); + } + if path == "/v1/messages" { + request = request.header("Anthropic-Version", "2023-06-01").header("X-Api-Key", key); + } + let response = send(request, candidate, &request_id)?; + if !matches!(response.status().as_u16(), 502 | 503) { + return Ok(response); + } + let mut failed = candidate.clone(); + failed["id"] = model["id"].clone(); + pi_runtime::invalidate_invocation(backend, &failed); + if attempts.peek().is_none() { + return Ok(response); + } + request_id = Uuid::new_v4().to_string(); + } + Err("没有可用的对话线路".into()) +} + fn selected(backend: &mut Backend, role: &str) -> R<(Value, Value, Value, Value)> { if role == "copy" { let settings = backend.settings()?; @@ -153,9 +218,10 @@ fn selected(backend: &mut Backend, role: &str) -> R<(Value, Value, Value, Value) .filter(|choice| !choice.is_empty()).ok_or("请选择文案模型")?; backend.validate()?; let id = backend.text_choice_id(choice)?; - if !backend.key_catalog(key)?.contains(&id) { return Err("个人Key未开放此模型".into()); } + let authorized = backend.key_catalog_full(key)?; + if !authorized.ids.contains(&id) { return Err("个人Key未开放此模型".into()); } let catalog = backend.public_model_catalog()?; - let model = backend.text_choice_from_catalog(choice, &id, &catalog, true)?; + let model = backend.text_choice_from_catalog(choice, &id, &catalog, &authorized, true)?; let invocation = pi_runtime::invocation_from(&catalog, &model)?; return Ok((settings, model, invocation, Value::Null)); } @@ -175,7 +241,7 @@ fn selected(backend: &mut Backend, role: &str) -> R<(Value, Value, Value, Value) (result, start.elapsed().as_millis()) }); let start = std::time::Instant::now(); - let authorized = backend.key_catalog(key); + let authorized = backend.key_catalog_full(key); (session.join(), (authorized, start.elapsed().as_millis()), catalog.join()) }); let (session, session_ms) = session.map_err(|_| "素材库会话校验失败")?; @@ -187,13 +253,17 @@ fn selected(backend: &mut Backend, role: &str) -> R<(Value, Value, Value, Value) let (catalog, catalog_phases) = catalog?; let model = if role == "detail" { let aliases = backend.legacy_text_choices(&settings); - let published = Backend::text_models(&catalog, &aliases)?; - crate::jiansun_models::detail_selection(&published, &settings, &authorized)? + let mut published = Backend::text_models(&catalog, &aliases, Some(&authorized))?; + if crate::jiansun_models::is_pricing_catalog(&catalog) { + published.retain(|model| model["key"] == settings["model"] || model["id"] == settings["model"]); + pi_runtime::enrich_models(&mut published)?; + } + crate::jiansun_models::detail_selection(&published, &settings, &authorized.ids)? } else { let choice = settings["model"].as_str().filter(|key| !key.is_empty()).ok_or("请选择对话模型")?; let id = backend.text_choice_id(choice)?; - if !authorized.contains(&id) { return Err("个人Key未开放此模型".into()); } - backend.text_choice_from_catalog(choice, &id, &catalog, true)? + if !authorized.ids.contains(&id) { return Err("个人Key未开放此模型".into()); } + backend.text_choice_from_catalog(choice, &id, &catalog, &authorized, true)? }; let timings = json!({"portalMs":session_ms,"keyMs":key_ms,"catalogMs":catalog_ms,"catalogPhases":catalog_phases}); let invocation = pi_runtime::invocation_from(&catalog, &model)?; @@ -347,7 +417,7 @@ fn verified_detail_model(record: &Value, input: &Value, settings: &Value, scope: let model = &record["model"]; (input["modelRole"] == "detail" && record["id"] == id && record["scope"] == scope && record["keyFingerprint"] == hash(key) && record["choice"] == settings["model"] - && input["invocationHeaders"] == record["headers"] && input["invocationPath"] == model["path"]) + && authorized_candidate(model, &record["headers"], input).is_some()) .then(|| model.clone()) } @@ -402,13 +472,13 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m settings["key"].as_str().and_then(|key| { let id = Uuid::new_v4().to_string(); let record = json!({"id":id,"scope":backend.scope(),"choice":settings["model"],"keyFingerprint":hash(key), - "model":model,"headers":invocation["headers"]}); + "model":model,"headers":invocation["headers"],"candidates":model["candidates"]}); write_task(&selection_file, &record).is_ok().then_some(id) }) } else { None }; *selection = Some((backend.scope(), role.to_owned(), settings, model.clone(), invocation.clone())); return emit( - json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"],"origin":backend.origin,"model":model,"thinkingLevel":thinking,"invocationHeaders":invocation["headers"],"selectionTimings":selection_timings,"selectionId":selection_id}}), + json!({"type":"result","value":{"accountScope":backend.scope(),"accountId":backend.auth["account"]["id"],"origin":backend.origin,"model":model,"candidates":model["candidates"],"thinkingLevel":thinking,"invocationHeaders":invocation["headers"],"selectionTimings":selection_timings,"selectionId":selection_id}}), ); } if method == "knowledge" { @@ -422,6 +492,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m } let id = uuid(&input, "id")?; *new_request_preflight = true; + invocation_headers(&input)?; let (settings, model) = { let role = input["modelRole"].as_str().unwrap_or("chat"); let settings = backend.settings()?; @@ -430,7 +501,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m } else { selection.as_ref().filter(|(scope, cached_role, cached, model, invocation)| scope == &backend.scope() && cached_role == role && cached == &settings - && input["invocationHeaders"] == invocation["headers"] && input["invocationPath"] == model["path"]) + && authorized_candidate(model, &invocation["headers"], &input).is_some()) .map(|(_, _, _, model, _)| model.clone()) }; if let Some(model) = scoped_model { @@ -439,7 +510,7 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m } else { let (settings, mut model, invocation, _) = selected(&mut backend, role)?; pi_runtime::apply_invocation_capacity(&mut model, &invocation)?; - if input["invocationHeaders"] != invocation["headers"] || input["invocationPath"] != model["path"] { + if authorized_candidate(&model, &invocation["headers"], &input).is_none() { *selection = None; return Err("模型调用路由已更新,本次尚未提交".into()); } @@ -450,25 +521,17 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m let key = settings["key"].as_str().ok_or("个人Key缺失")?; let payload = input["body"].as_str().filter(|body| body.len() <= LIMIT).ok_or("模型输入过大")?; let value: Value = serde_json::from_str(payload).map_err(|_| "模型输入不是JSON")?; - validate_provider_payload(&value, &model)?; - let model_path = model["path"].as_str().ok_or("模型路径无效")?; - let mut request = backend.http - .post(format!("{UPSTREAM}{model_path}")) - .timeout(Duration::from_secs(600)) - .header("Idempotency-Key", &id) - .header("Content-Type", "application/json") - .body(payload.to_owned()); - for (name, value) in invocation_headers(&input)? { - request = request.header(name, value); - } - if model["protocol"] == "anthropic-messages" { - request = request.header("Anthropic-Version", "2023-06-01").header("X-Api-Key", key); - } else { - request = request.bearer_auth(key); - } - check_dispatch_lease(&input["dispatchLease"])?; - *new_request_preflight = false; - let mut response = request.send().map_err(|_| "98k连接中断")?; + let mut requested = authorized_candidate(&model, &input["invocationHeaders"], &input) + .ok_or("模型调用路由已更新,本次尚未提交")?; + requested["id"] = model["id"].clone(); + validate_provider_payload(&value, &requested)?; + let mut response = send_text(&backend, &model, &requested, key, &id, Duration::from_secs(600), + |candidate| validate_provider_payload(&value, candidate).is_ok(), + |request, _, _| { + check_dispatch_lease(&input["dispatchLease"])?; + *new_request_preflight = false; + request.header("Content-Type", "application/json").body(payload.to_owned()).send().map_err(|_| "98k连接中断".into()) + })?; let status = response.status().as_u16(); if matches!(status, 401 | 403) { *selection = None; @@ -500,6 +563,63 @@ fn dispatch(input: Value, shared_http: &mut Option, selection: &m mod tests { use super::*; + #[test] + fn model_alternates_are_authorized_by_path_and_headers_but_failover_stays_on_protocol() { + let chat = |route: Option<&str>| json!({"protocol":"openai-chat","path":"/v1/chat/completions", + "routeId":route,"headers":route.map_or_else(|| json!({}), |id| json!({"X-Relay-Route-Option":id}))}); + let pinned = chat(Some("6db9b40d-ad0d-4dd1-b7b9-bb0b3cf8040a")); + let backup = chat(Some("bc5fa545-59d5-4b95-b4df-bd9b53b37906")); + let unpinned = chat(None); + let alternate = json!({"protocol":"openai-responses","path":"/v1/responses","routeId":null,"headers":{}}); + let model = json!({"candidates":[pinned,alternate,backup,unpinned]}); + let requested = json!({"invocationPath":"/v1/responses","invocationHeaders":{}}); + assert_eq!(authorized_candidate(&model, &Value::Null, &requested), Some(alternate)); + let invalid = json!({"invocationPath":"/v1/responses","invocationHeaders":pinned["headers"]}); + assert!(authorized_candidate(&model, &Value::Null, &invalid).is_none()); + assert_eq!(same_protocol_attempts(&model, &pinned, |_| true), vec![pinned, backup, unpinned]); + } + + #[test] + fn text_failover_uses_new_keys_only_for_gateway_failures_before_headers() { + let temp = tempfile::tempdir().unwrap(); + let backend = Backend::new(temp.path().to_owned()).unwrap(); + let route = |id: Option<&str>| json!({"id":"chat","protocol":"openai-chat","path":"/v1/chat/completions", + "routeId":id,"headers":id.map_or_else(|| json!({}), |id| json!({"X-Relay-Route-Option":id}))}); + let primary = route(Some("6db9b40d-ad0d-4dd1-b7b9-bb0b3cf8040a")); + let backup = route(Some("bc5fa545-59d5-4b95-b4df-bd9b53b37906")); + let model = json!({"id":"chat","candidates":[primary,backup,route(None)]}); + let client = reqwest::blocking::Client::builder().no_proxy().build().unwrap(); + for (statuses, expected) in [(vec![502, 503, 200], 200), (vec![429], 429), (vec![200], 200), (vec![502, 503, 502], 502)] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let count = statuses.len(); + let server = std::thread::spawn(move || { + for status in statuses { + let (mut socket, _) = listener.accept().unwrap(); + socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + let mut request = [0; 4096]; + assert!(socket.read(&mut request).unwrap() > 0); + write!(socket, "HTTP/1.1 {status} test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap(); + } + }); + let id = Uuid::new_v4().to_string(); + let mut seen = std::collections::HashSet::new(); + let response = send_text(&backend, &model, &primary, "fixture-key", &id, Duration::from_secs(3), |_| true, + |request, candidate, key| { + let mut request = request.build().unwrap(); + assert_eq!(request.headers()["Idempotency-Key"], key); + assert_eq!(request.headers().get("X-Relay-Route-Option").and_then(|value| value.to_str().ok()), candidate["routeId"].as_str()); + assert!(seen.insert(key.to_owned())); + *request.url_mut() = format!("http://{address}/v1/chat/completions").parse().unwrap(); + client.execute(request).map_err(|error| error.to_string()) + }).unwrap(); + assert_eq!(response.status().as_u16(), expected); + assert_eq!(seen.len(), count); + assert!(seen.contains(&id)); + server.join().unwrap(); + } + } + #[test] fn production_worker_uses_only_the_verified_selection_for_its_bound_turn() { let id = Uuid::new_v4().to_string(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index 231170cd..9f4474b4 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -170,6 +170,13 @@ fn knowledge_rule(b:&Backend,doc:u64,production:bool) -> R } pub(super) fn invocation_from(catalog: &Value, model: &Value) -> R { + if crate::jiansun_models::is_pricing_catalog(catalog) { + if model["catalogFormat"] != "newapi-pricing" || !model["routeId"].is_null() || model["headers"] != json!({}) { + return Err("当前模型公开契约与已选协议不一致,未调用".into()); + } + return Ok(json!({"version":5,"catalogFormat":"newapi-pricing","hasSchema":false,"headers":{},"model":model["id"], + "path":model["path"],"routeId":null,"at":now(),"requiresOutputLimit":model["protocol"] == "anthropic-messages"})); + } let sections = catalog["data"]["sections"].as_array().or_else(|| catalog["sections"].as_array()).ok_or("98k公开模型目录格式已改变")?; let found = sections.iter().filter_map(|s| s["models"].as_array()).flatten().find(|m| m["id"] == model["id"]).ok_or("当前模型尚未发布调用契约")?; let route = model["routeId"].as_str().map(|id| { @@ -180,12 +187,7 @@ pub(super) fn invocation_from(catalog: &Value, model: &Value) -> R { if invocation["method"] != "POST" || invocation["path"] != model["path"] || invocation["content_type"] != "application/json" { return Err("当前模型公开契约与已选协议不一致,未调用".into()); } - let mut headers = invocation.get("headers").cloned().unwrap_or(json!({})); - if let Some(version)=headers.get("Anthropic-Version") { - if model["protocol"]!="anthropic-messages"||version!="2023-06-01" {return Err("当前模型版本与客户端协议不一致,未调用".into());} - if let Some(headers)=headers.as_object_mut() {headers.remove("Anthropic-Version");} - } - super::pi::invocation_headers(&json!({"invocationHeaders":headers}))?; + let headers = crate::jiansun_models::text_catalog_headers(invocation, model["protocol"].as_str().unwrap_or_default())?; // Capacity is a declaration, never a pricing tier or an inferred model-name match. // A selected route's explicit limit takes precedence over the model declaration. let capacity_route = route.or_else(|| crate::jiansun_models::text_routes(found) @@ -201,7 +203,8 @@ pub(super) fn invocation_from(catalog: &Value, model: &Value) -> R { model["protocol"].as_str().unwrap_or_default(), properties); let requires_output = invocation["input_schema"]["required"].as_array().into_iter().flatten() .any(|field| field == output_field || field == "max_completion_tokens"); - Ok(json!({"version":4,"headers":headers,"model":model["id"],"path":model["path"],"routeId":model["routeId"],"at":now(),"contextWindow":limit, + Ok(json!({"version":5,"catalogFormat":"v2","hasSchema":invocation["input_schema"]["properties"].is_object(), + "headers":headers,"model":model["id"],"path":model["path"],"routeId":model["routeId"],"at":now(),"contextWindow":limit, "reasoning":reasoning,"reasoningEfforts":reasoning_efforts, "requiresOutputLimit":requires_output, "contextWindowSource":limit.map(|_| format!("{UPSTREAM}/api/v2/catalog/models")), @@ -209,8 +212,10 @@ pub(super) fn invocation_from(catalog: &Value, model: &Value) -> R { } pub(super) fn apply_invocation_capacity(model: &mut Value, invocation: &Value) -> R<()> { enrich_models(std::slice::from_mut(model))?; - model["reasoning"] = invocation["reasoning"].clone(); - model["reasoningEfforts"] = invocation["reasoningEfforts"].clone(); + if invocation["hasSchema"] == true { + model["reasoning"] = invocation["reasoning"].clone(); + model["reasoningEfforts"] = invocation["reasoningEfforts"].clone(); + } model["requiresOutputLimit"] = invocation["requiresOutputLimit"].clone(); if invocation["contextWindow"].as_u64().is_some_and(|limit| limit > 0) { model["contextWindow"] = invocation["contextWindow"].clone(); @@ -222,13 +227,25 @@ pub(super) fn apply_invocation_capacity(model: &mut Value, invocation: &Value) - } Ok(()) } -pub(super) fn invocation(b: &Backend, model: &Value) -> R { +fn invocation_path(b: &Backend, model: &Value) -> R { let id = model["id"].as_str().ok_or("模型编号无效")?; let route = model["routeId"].as_str().unwrap_or_default(); - let file = b.root.join("public-invocations").join(format!("{}.json", hash(&format!("{id}:{route}")))); + let path = model["path"].as_str().ok_or("模型路径无效")?; + Ok(b.root.join("public-invocations").join(format!("{}.json", hash(&format!("{id}:{path}:{route}"))))) +} + +pub(super) fn invalidate_invocation(b: &Backend, model: &Value) { + if let Ok(path) = invocation_path(b, model) { + let _ = fs::remove_file(path); + } +} + +pub(super) fn invocation(b: &Backend, model: &Value) -> R { + let file = invocation_path(b, model)?; if file.exists() { let value = read_json(&file)?; - if value["version"] == 4 && value["model"] == model["id"] && value["path"] == model["path"] + if value["version"] == 5 && value["catalogFormat"] == model["catalogFormat"] + && value["model"] == model["id"] && value["path"] == model["path"] && value["routeId"] == model["routeId"] && value["at"].as_u64().is_some_and(|at| now().saturating_sub(at) < 300) { return Ok(value); } @@ -332,7 +349,22 @@ pub(super) fn enrich_models(models:&mut [Value])->R<()> { let root=script.parent().and_then(Path::parent).ok_or("小壹的模型资料位置不可用")?.join("node_modules/@earendil-works/pi-ai/dist/providers/data"); crate::jiansun_models::load_pi_catalog(&root) }).as_ref().map_err(Clone::clone)?; - for model in models {crate::jiansun_models::apply_pi_capacity(model,catalog);} + for model in models { + crate::jiansun_models::apply_pi_capacity(model, catalog); + let id = model["id"].clone(); + let format = model["catalogFormat"].clone(); + if let Some(candidates) = model["candidates"].as_array_mut() { + for candidate in candidates { + let declared = candidate["maxTokens"].as_u64(); + candidate["id"] = id.clone(); + candidate["catalogFormat"] = format.clone(); + crate::jiansun_models::apply_pi_capacity(candidate, catalog); + if format == "v2" && let Some(limit) = declared { + candidate["maxTokens"] = json!(candidate["maxTokens"].as_u64().map_or(limit, |pi| pi.min(limit))); + } + } + } + } Ok(()) } diff --git a/lib/__tests__/ai-model-service.test.ts b/lib/__tests__/ai-model-service.test.ts index a2d4650b..6d56cfd6 100644 --- a/lib/__tests__/ai-model-service.test.ts +++ b/lib/__tests__/ai-model-service.test.ts @@ -4,7 +4,7 @@ import { AiModelError } from '@/lib/ai-model-access' import { isSuperAdmin } from '@/lib/department-permission' import { configureAiModels, editAiModelProvider, getAiModelAdminState, getAiModelRuntimeState, parseAiModelCatalog, resolveAiModel, syncAiModelProvider,listAiModelExecutionContracts } from '@/lib/ai-model-service' import { encryptAiModelKey } from '@/lib/ai-model-crypto' -import { requestAiModel, requestAiModelCapabilityCatalog } from '@/lib/ai-model-http' +import { requestAiModel, requestAiModelCapabilityCatalog, requestAiModelPricingCatalog } from '@/lib/ai-model-http' import { getAiModelStageProtocol, parseAiModelCapabilityMetadata } from '@/lib/ai-model-capabilities' import { aiModelVerificationContext, listAiModelVerifications } from '@/lib/ai-model-verification-state' import { aiModelAudit, getAiModelConfiguration, getAiModelProviderRow, listAiModelProviderRows, listAiModelRows, saveAiModelDefaults, type AiModelProviderRow, type AiModelRow } from '@/lib/ai-model-repository' @@ -13,7 +13,7 @@ jest.mock('next-auth', () => ({ getServerSession: jest.fn() })) jest.mock('@/lib/auth', () => ({ authOptions: {} })) jest.mock('@/lib/department-permission', () => ({ isSuperAdmin: jest.fn() })) jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() } } })) -jest.mock('@/lib/ai-model-http', () => ({ ...jest.requireActual('@/lib/ai-model-http'), requestAiModel: jest.fn(), requestAiModelCapabilityCatalog: jest.fn() })) +jest.mock('@/lib/ai-model-http', () => ({ ...jest.requireActual('@/lib/ai-model-http'), requestAiModel: jest.fn(), requestAiModelCapabilityCatalog: jest.fn(), requestAiModelPricingCatalog: jest.fn() })) jest.mock('@/lib/ai-model-verification-state', () => ({ ...jest.requireActual('@/lib/ai-model-verification-state'), listAiModelVerifications: jest.fn() })) const mockDb = { $executeRawUnsafe: jest.fn(), $queryRawUnsafe: jest.fn(async () => [{ isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null }]) } jest.mock('@/lib/ai-model-repository', () => ({ @@ -351,6 +351,31 @@ test('failure of public capability discovery aborts both catalog and capability await expect(syncAiModelProvider('admin', legacyId, { revision: 1 })).rejects.toMatchObject({ code: 'capability_catalog_failed' }) expect(mockDb.$executeRawUnsafe).not.toHaveBeenCalled() }) + +test.each([404, 410])('98k sync uses New API pricing after V2 HTTP %i and honors Key-scoped endpoints', async status => { + process.env.DETAIL_GENERATOR_BASE_URL = providers[0].baseUrl = 'https://api.vip98k.com/v1' + ;(requestAiModel as jest.Mock).mockResolvedValue(Response.json({ data: [ + { id: 'shared', supported_endpoint_types: ['vip-messages'] }, + { id: 'private-image', supported_endpoint_types: ['image-generation'] }, + ] })) + ;(requestAiModelCapabilityCatalog as jest.Mock).mockResolvedValue(new Response('', { status })) + ;(requestAiModelPricingCatalog as jest.Mock).mockImplementation(async (_base, beforeRequest) => { + await beforeRequest() + return Response.json({ success: true, supported_endpoint: { 'vip-messages': { method: 'POST', path: '/v1/messages' } }, data: [ + { model_name: 'shared', supported_endpoint_types: ['openai'], quota_type: 0, model_ratio: 2 }, + { model_name: 'public-only', supported_endpoint_types: ['anthropic'] }, + ] }) + }) + await syncAiModelProvider('admin', legacyId, { revision: 1 }) + const rows = mockDb.$executeRawUnsafe.mock.calls.filter(([sql]) => sql.startsWith('INSERT INTO ai_model_catalog')) + expect(rows.map(row => row[3])).toEqual(['private-image', 'shared']) + const shared = JSON.parse(rows[1][4]) + expect(shared).toMatchObject({ endpoints: ['/v1/messages'], pricing: { quotaType: 0, modelRatio: 2 } }) + expect(getAiModelStageProtocol(shared, 'copy')).toMatchObject({ id: 'anthropic-messages', headers: { 'Anthropic-Version': '2023-06-01' } }) + const image = getAiModelStageProtocol(JSON.parse(rows[0][4]), 'image') + expect(image).toMatchObject({ referenceContract: 'probe-required', headers: {}, inputField: 'image' }) + expect(image).not.toHaveProperty('routeId') +}) test('identical capabilities do not bump provider revision after JSONB field reordering', async () => { const declaration = { input_modalities: ['text'], output_modalities: ['text'], endpoints: ['/chat/completions'] } models = [{ ...models[0], capabilityMetadata: Object.fromEntries(Object.entries(parseAiModelCapabilityMetadata(declaration, providers[0].baseUrl + '/models')!).reverse()) }] diff --git a/lib/ai-model-capabilities.ts b/lib/ai-model-capabilities.ts index 2f212b65..0f5673d4 100644 --- a/lib/ai-model-capabilities.ts +++ b/lib/ai-model-capabilities.ts @@ -15,6 +15,7 @@ export interface AiModelCapabilityMetadata { endpointsDeclared?: boolean unavailable?: boolean protocols?: AiModelProtocol[] + pricing?: { quotaType?: number; modelRatio?: number; completionRatio?: number; modelPrice?: number } } function object(value: unknown): Record | null { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : null } @@ -23,12 +24,26 @@ function strings(value: unknown): string[] | null { } /** Explicit metadata contract used by standard model directories. Missing fields stay unknown. */ -export function parseAiModelCapabilityMetadata(value: unknown, sourceUrl: string | null = null): AiModelCapabilityMetadata | null { +export function parseAiModelCapabilityMetadata(value: unknown, sourceUrl: string | null = null, endpointMap?: unknown): AiModelCapabilityMetadata | null { const raw = object(value) if (!raw) return null const inputModalities = strings(raw.input_modalities) const outputModalities = strings(raw.output_modalities) const endpoints = strings(raw.endpoints) + if (raw.supported_endpoint_types !== undefined) { + if (!strings(raw.supported_endpoint_types) || raw.input_modalities !== undefined && !inputModalities || raw.output_modalities !== undefined && !outputModalities) { + throw new AiModelError('上游模型能力字段无效,未保存本次同步', 502, 'catalog_invalid') + } + const metadata = newApiMetadata(raw.supported_endpoint_types as string[], endpointMap, sourceUrl) + if (inputModalities?.includes('image')) { + for (const protocol of metadata.protocols ?? []) protocol.supportsImageInput = true + if (metadata.kindHint === 'text') metadata.kindHint = 'vision' + } + return { ...metadata, + ...(inputModalities ? { inputModalities, inputDeclared: true } : {}), + ...(outputModalities ? { outputModalities, outputDeclared: true } : {}), + unavailable: raw.available === false } + } if (!inputModalities || !outputModalities || !endpoints) { if (['input_modalities', 'output_modalities', 'endpoints'].some(field => Object.prototype.hasOwnProperty.call(raw, field))) throw new AiModelError('上游模型能力字段不完整,未保存本次同步', 502, 'catalog_invalid') if (raw.available === false) return { version: 1, inputModalities: [], outputModalities: [], endpoints: [], sourceUrl, unavailable: true } @@ -57,6 +72,55 @@ function publicKind(model: Record, section: Record { + const entry = published && Object.prototype.hasOwnProperty.call(published, type) ? object(published[type]) : null + if (entry) return entry.method === 'POST' && typeof entry.path === 'string' && /^\/v1\/[a-z0-9/-]+$/.test(entry.path) ? [entry.path] : [] + const path = endpointPaths.get(type) + return path ? [path] : [] + }))) + const protocols: AiModelProtocol[] = [] + for (const path of endpoints) { + if (path === '/v1/chat/completions') protocols.push({ id: 'openai-chat', path, headers: {}, supportsImageInput: false }) + if (path === '/v1/messages') protocols.push({ id: 'anthropic-messages', path, headers: { 'Anthropic-Version': '2023-06-01' }, supportsImageInput: false }) + if (path === '/v1/images/edits') protocols.push({ id: 'openai-image-edit', path, headers: {}, inputField: 'image', supportsImageInput: true, maxImages: 8 }) + if (path === '/v1/images/generations') protocols.push({ id: 'openai-image-generate', path, headers: {}, inputField: 'image', supportsImageInput: true, + referenceTransport: 'json-inline', referenceContract: 'probe-required', maxImages: 8, requestParameters: { n: 1, response_format: 'b64_json' } }) + } + const image = protocols.some(protocol => protocol.id === 'openai-image-edit' || protocol.id === 'openai-image-generate') + const text = endpoints.some(path => ['/v1/chat/completions', '/v1/responses', '/v1/messages'].includes(path)) + return { version: 1, inputModalities: image || text ? ['text'] : [], outputModalities: [...(image ? ['image'] : []), ...(text ? ['text'] : [])], + endpoints, sourceUrl, protocols, endpointsDeclared: true, + kindHint: image ? 'image' : text ? 'text' : endpoints.includes('/v1/embeddings') ? 'embedding' : undefined } +} + +export function parseAiModelNewApiPricingCatalog(value: unknown): Map { + const raw = object(value) + if (raw?.success !== true || !Array.isArray(raw.data) || raw.data.length > 5000) throw new AiModelError('上游能力目录格式不兼容', 502, 'capability_catalog_invalid') + const result = new Map() + for (const entry of raw.data) { + const model = object(entry), id = model?.model_name + if (!model || typeof id !== 'string' || !id || id.length > 200 || result.has(id) || !strings(model.supported_endpoint_types)) throw new AiModelError('上游能力目录模型或接口字段无效', 502, 'capability_catalog_invalid') + const types = model.supported_endpoint_types as string[] + const preferred = model.default_endpoint_type + const metadata = newApiMetadata(typeof preferred === 'string' && types.includes(preferred) ? [preferred, ...types] : types, raw.supported_endpoint, pricingUrl) + const pricing: NonNullable = {} + for (const [field, key] of [['quota_type', 'quotaType'], ['model_ratio', 'modelRatio'], ['completion_ratio', 'completionRatio'], ['model_price', 'modelPrice']] as const) { + const value = model[field] + if (typeof value === 'number' && Number.isFinite(value)) pricing[key] = value + } + result.set(id, { ...metadata, endpointsDeclared: false, pricing }) + } + return result +} /** Known provider's public schema, joined only to IDs already authorized by its private /models response. */ export function parseAiModelPublicCapabilityCatalog(value: unknown): Map { @@ -121,10 +185,18 @@ export function aiModelCapabilityFingerprint(value: unknown): string { return JS export function mergeAiModelCapabilityMetadata(primary: AiModelCapabilityMetadata | null, additional: AiModelCapabilityMetadata | null): AiModelCapabilityMetadata | null { if (!primary || !additional) return primary || additional + if (additional.sourceUrl === pricingUrl) { + const keyEndpoints = primary.endpointsDeclared + return { ...additional, ...primary, kindHint: keyEndpoints ? primary.kindHint || additional.kindHint : additional.kindHint || primary.kindHint, + endpoints: keyEndpoints ? primary.endpoints : additional.endpoints, + protocols: keyEndpoints ? primary.protocols : additional.protocols, + inputModalities: primary.inputDeclared || keyEndpoints ? primary.inputModalities : additional.inputModalities, + outputModalities: primary.outputDeclared || keyEndpoints ? primary.outputModalities : additional.outputModalities } + } if (primary.unavailable && !primary.inputDeclared && !primary.outputDeclared && !primary.endpointsDeclared) return { ...additional, unavailable: true } return { ...primary, kindHint: additional.kindHint || primary.kindHint, protocols: additional.protocols || [], endpoints: additional.endpoints, - inputModalities: additional.inputDeclared ? primary.inputModalities.filter(value => additional.inputModalities.includes(value)) : primary.inputModalities, - outputModalities: additional.outputDeclared ? primary.outputModalities.filter(value => additional.outputModalities.includes(value)) : primary.outputModalities, + inputModalities: !primary.inputDeclared ? additional.inputModalities : additional.inputDeclared ? primary.inputModalities.filter(value => additional.inputModalities.includes(value)) : primary.inputModalities, + outputModalities: !primary.outputDeclared ? additional.outputModalities : additional.outputDeclared ? primary.outputModalities.filter(value => additional.outputModalities.includes(value)) : primary.outputModalities, unavailable: primary.unavailable === true || additional.unavailable === true } } diff --git a/lib/ai-model-http.ts b/lib/ai-model-http.ts index 69599fb7..799ae655 100644 --- a/lib/ai-model-http.ts +++ b/lib/ai-model-http.ts @@ -48,12 +48,13 @@ export async function requestAiModelOperation(baseUrl: string, apiKey: string, p if ((retainedResult || taskResult) && (body !== undefined || idempotencyKey !== undefined || Object.keys(protocolHeaders).length)) throw new AiModelError('原请求结果仅允许只读查询', 400, 'protocol_invalid') if (!retainedResult && !['/v1/chat/completions', '/v1/messages', '/v1/images/edits', '/v1/images/generations', '/extensions/v1/tasks'].includes(path) && !/^\/extensions\/v1\/tasks\/[A-Za-z0-9_-]{1,160}\/result$/.test(path)) throw new AiModelError('模型接口尚未适配', 400, 'protocol_unsupported') const headers: Record = { Authorization: `Bearer ${apiKey}` } + if (path === '/v1/messages' && body !== undefined) headers['X-Api-Key'] = apiKey if (idempotencyKey) { if (!/^[\x21-\x7e]{1,128}$/.test(idempotencyKey)) throw new AiModelError('模型请求编号无效') headers['Idempotency-Key'] = idempotencyKey } for (const [key, value] of Object.entries(protocolHeaders)) { - if (!['X-Relay-Route-Option', 'Anthropic-Version'].includes(key) || !/^[A-Za-z0-9._-]{1,160}$/.test(value)) throw new AiModelError('模型协议请求头无效', 400, 'protocol_invalid') + if (!(key === 'X-Relay-Route-Option' || key === 'Anthropic-Version' && path === '/v1/messages') || !/^[A-Za-z0-9._-]{1,160}$/.test(value)) throw new AiModelError('模型协议请求头无效', 400, 'protocol_invalid') headers[key] = value } const target = path.startsWith('/v1/') ? new URL(normalized + path.slice(3)) : new URL(path, normalized) @@ -77,6 +78,11 @@ export async function requestAiModelCapabilityCatalog(baseUrl: string, beforeReq return requestAiModelUrl(normalized, new URL('https://api.vip98k.com/api/v2/catalog/models'), {}, true, undefined, beforeRequest) } +export async function requestAiModelPricingCatalog(baseUrl: string, beforeRequest?: () => Promise): Promise { + const normalized = normalizeAiModelBaseUrl(baseUrl) + return requestAiModelUrl(normalized, new URL('/api/pricing', normalized), {}, true, undefined, beforeRequest) +} + async function requestAiModelUrl(normalized: string, target: URL, headers: Record, catalog: boolean, body?: string | FormData, beforeRequest?: () => Promise, timeoutMs?: number, execution?: AiModelTransportExecution): Promise { execution?.signal?.throwIfAborted() const addresses = await resolveAiModelPublicAddresses(normalized) @@ -107,7 +113,7 @@ async function requestAiModelUrl(normalized: string, target: URL, headers: Recor // Persist the customer request number before accepting the body as complete. Promise.resolve(checkpoint).catch(() => { res.destroy(); finish(new Error('Provider request checkpoint failed')) }) if ((res.statusCode || 0) >= 300 && (res.statusCode || 0) < 400) { res.destroy(); finish(new AiModelError('模型服务重定向已拒绝,请配置最终服务地址', 502, 'provider_redirect_rejected')); return } - const limit = catalog ? (target.pathname === '/api/v2/catalog/models' ? 8 : 2) * 1024 * 1024 : 32 * 1024 * 1024 + const limit = catalog ? (['/api/v2/catalog/models', '/api/pricing'].includes(target.pathname) ? 8 : 2) * 1024 * 1024 : 32 * 1024 * 1024 const chunks: Buffer[] = []; let size = 0 if (Number(res.headers['content-length'] || 0) > limit) { res.destroy(); finish(new Error('Provider response exceeds limit')); return } res.on('data', (chunk: Buffer) => { size += chunk.length; if (size > limit) { res.destroy(); finish(new Error('Provider response exceeds limit')) } else chunks.push(chunk) }) diff --git a/lib/ai-model-protocol.ts b/lib/ai-model-protocol.ts index 70aa3ee7..c4491f9e 100644 --- a/lib/ai-model-protocol.ts +++ b/lib/ai-model-protocol.ts @@ -172,7 +172,7 @@ function parseInvocation(model: Record, offer: Record, let inputField: string | undefined, supportsImageInput = false let referenceTransport: AiModelProtocol['referenceTransport'], referenceContract: AiModelProtocol['referenceContract'], requestParameters: AiModelProtocol['requestParameters'] if (id === 'openai-chat' || id === 'anthropic-messages') { - if (!isTextModel) return null + if (!isTextModel || record(route.chat_capabilities ?? model.chat_capabilities)?.streaming_tools === 'disabled') return null supportsImageInput = modes.some(mode => ['image', 'image_url', 'image_base64'].includes(mode)) || (!modes.length && model.modality === 'multimodal') } else { if (!isImageModel) return null @@ -279,7 +279,7 @@ export function validateStoredAiModelProtocols(value: unknown): AiModelProtocol[ if (['maxImages', 'maxPromptLength'].some(field => raw[field] !== undefined && (!Number.isInteger(raw[field]) || raw[field] < 1 || raw[field] > (field === 'maxImages' ? 8 : 1000000)))) return [] if (raw.imageQuality !== undefined && (raw.id !== 'openai-image-generate' || raw.imageQuality !== 'medium')) return [] if (raw.referenceTransport !== undefined && (!['json-inline', 'multipart'].includes(raw.referenceTransport) || raw.id !== 'openai-image-generate' || !raw.supportsImageInput || !['image', 'images', 'file_urls'].includes(raw.inputField) || raw.referenceTransport === 'multipart' && raw.inputField !== 'image')) return [] - if (raw.referenceContract !== undefined && (raw.referenceContract !== 'probe-required' || raw.id !== 'openai-image-generate' || raw.referenceTransport !== 'json-inline' || raw.inputField !== 'image' || !Number.isInteger(raw.maxImages) || raw.maxImages < 1 || raw.maxImages > 8 || !raw.routeId || !raw.scopeId)) return [] + if (raw.referenceContract !== undefined && (raw.referenceContract !== 'probe-required' || raw.id !== 'openai-image-generate' || raw.referenceTransport !== 'json-inline' || raw.inputField !== 'image' || !Number.isInteger(raw.maxImages) || raw.maxImages < 1 || raw.maxImages > 8 || Boolean(raw.routeId) !== Boolean(raw.scopeId) || !raw.routeId && headers['X-Relay-Route-Option'])) return [] const requestParameters = raw.requestParameters !== undefined ? safeImageParameters(raw.requestParameters) : undefined if (raw.referenceTransport !== undefined && (!requestParameters || requestParameters.n !== 1 || !requestParameters.response_format) || raw.requestParameters !== undefined && (raw.referenceTransport === undefined && raw.id !== 'async-image-task' || !requestParameters)) return [] if (raw.id === 'async-image-task' && (!raw.supportsImageInput || raw.inputField !== 'file_urls') || raw.id === 'openai-image-generate' && raw.supportsImageInput && !raw.inputField || raw.id === 'openai-image-edit' && (!raw.supportsImageInput || !['image', 'image[]'].includes(raw.inputField))) return [] diff --git a/lib/ai-model-service.ts b/lib/ai-model-service.ts index f8bbc568..2a6ca386 100644 --- a/lib/ai-model-service.ts +++ b/lib/ai-model-service.ts @@ -2,8 +2,8 @@ import { createHash, randomUUID } from 'node:crypto' import { z } from 'zod' import { AiModelError, assertAiModelAdmin, assertAiModelAdminForWrite } from './ai-model-access' import { decryptAiModelKey, encryptAiModelKey, isAiModelEncryptionConfigured } from './ai-model-crypto' -import { normalizeAiModelBaseUrl, requestAiModel, requestAiModelCapabilityCatalog } from './ai-model-http' -import { aiModelCapabilityFingerprint, getAiModelCapabilities, getAiModelStageProtocol, mergeAiModelCapabilityMetadata, parseAiModelCapabilityMetadata, parseAiModelPublicCapabilityCatalog, type AiModelCapabilityMetadata } from './ai-model-capabilities' +import { normalizeAiModelBaseUrl, requestAiModel, requestAiModelCapabilityCatalog, requestAiModelPricingCatalog } from './ai-model-http' +import { aiModelCapabilityFingerprint, getAiModelCapabilities, getAiModelStageProtocol, mergeAiModelCapabilityMetadata, parseAiModelCapabilityMetadata, parseAiModelNewApiPricingCatalog, parseAiModelPublicCapabilityCatalog, type AiModelCapabilityMetadata } from './ai-model-capabilities' import { aiModelAudit, aiModelTransaction, assertAiModelRevision, encryptedAiModelFields, getAiModelConfiguration, getAiModelProviderRow, insertAiModelProvider, listAiModelProviderRows, listAiModelRows, saveAiModelDefaults, updateAiModelProvider, type AiModelDatabase, type AiModelProviderRow, type AiModelRow } from './ai-model-repository' import { AI_MODEL_STAGES, type AiModelAdminState, type AiModelBinding, type AiModelBindings, type AiModelConfigurationInput, type AiModelDefaults, type AiModelRuntimeState, type AiModelStage } from './ai-model-types' import { DETAIL_MODEL_DEFAULTS } from './detail-generator/types' @@ -156,21 +156,34 @@ export async function syncAiModelProvider(userId: string, providerId: string, bo let value: unknown; try { value = await response.json() } catch { throw new AiModelError('上游模型目录不是有效 JSON', 502, 'catalog_invalid') } const models = parseAiModelCatalog(value) if (models.some(model => model.includes(apiKey))) throw new AiModelError('上游模型目录包含敏感内容,已拒绝保存', 502, 'catalog_invalid') - const metadata = new Map() - for (const entry of (value as { data: Array> }).data) { - const normalized = parseAiModelCapabilityMetadata(entry, source.baseUrl + '/models') - if (metadata.has(entry.id as string) && JSON.stringify(metadata.get(entry.id as string)) !== JSON.stringify(normalized)) throw new AiModelError('上游同名模型能力冲突,未保存本次同步', 502, 'catalog_invalid') - metadata.set(entry.id as string, normalized) - } + let capabilities: Map | undefined + let endpointMap: unknown if (source.baseUrl === 'https://api.vip98k.com/v1') { let publicResponse: Response - try { publicResponse = await requestAiModelCapabilityCatalog(source.baseUrl, async () => { const current = await getAiModelProviderRow(providerId); assertAiModelRevision(current.revision, source.revision); await assertAiModelAdmin(userId) }) } + let usePricing = false + const beforeRequest = async () => { + const current = await getAiModelProviderRow(providerId) + assertAiModelRevision(current.revision, source.revision) + await assertAiModelAdmin(userId) + } + try { + publicResponse = await requestAiModelCapabilityCatalog(source.baseUrl, beforeRequest) + usePricing = [404, 410].includes(publicResponse.status) + if (usePricing) publicResponse = await requestAiModelPricingCatalog(source.baseUrl, beforeRequest) + } catch (error) { if (error instanceof AiModelError) throw error; throw new AiModelError('上游能力目录连接失败,未保存本次同步', 502, 'capability_catalog_failed') } if (!publicResponse.ok) throw new AiModelError('上游能力目录请求失败,未保存本次同步', 502, 'capability_catalog_failed') let publicValue: unknown try { publicValue = await publicResponse.json() } catch { throw new AiModelError('上游能力目录不是有效 JSON', 502, 'capability_catalog_invalid') } - const capabilities = parseAiModelPublicCapabilityCatalog(publicValue) - for (const modelId of models) metadata.set(modelId, mergeAiModelCapabilityMetadata(metadata.get(modelId) || null, capabilities.get(modelId) || null)) + capabilities = usePricing ? parseAiModelNewApiPricingCatalog(publicValue) : parseAiModelPublicCapabilityCatalog(publicValue) + if (usePricing) endpointMap = (publicValue as { supported_endpoint?: unknown }).supported_endpoint + } + const metadata = new Map() + for (const entry of (value as { data: Array> }).data) { + const modelId = entry.id as string + const normalized = mergeAiModelCapabilityMetadata(parseAiModelCapabilityMetadata(entry, source.baseUrl + '/models', endpointMap), capabilities?.get(modelId) ?? null) + if (metadata.has(modelId) && JSON.stringify(metadata.get(modelId)) !== JSON.stringify(normalized)) throw new AiModelError('上游同名模型能力冲突,未保存本次同步', 502, 'catalog_invalid') + metadata.set(modelId, normalized) } if (Array.from(metadata.values()).some(evidence => JSON.stringify(evidence).includes(apiKey))) throw new AiModelError('上游能力目录包含敏感内容,已拒绝保存', 502, 'catalog_invalid') await aiModelTransaction(async db => {