PageSourceSearch

https://ylilike-test.hf.space/static/js/async/3243.41d1fad694.js

js ylilike-test.hf.space collected 2026-10-04 17:32:37 UTC 325,924 bytes, 1 lines download raw bytes

1"use strict";(self.rspackChunknewapi_web=self.rspackChunknewapi_web||[]).push([[3243],{10552(e,t,s){var a=s(89795);function l(e,t,s){return!!e&&(e.role===a.z7.SUPER_ADMIN||e.permissions?.admin_permissions?.[t]?.[s]===!0)}function n(e,t){let s=t.roles.find(e=>"admin"===e.key)?.grants??{},a={};for(let l of t.resources){let t={};for(let a of l.actions)t[a.action]=e?.[l.resource]?.[a.action]??s[l.resource]?.[a.action]??!1;a[l.resource]=t}return a}s.d(t,{_m:()=>l,v$:()=>n},{YG:{READ:"read",OPERATE:"operate",WRITE:"write",SENSITIVE_WRITE:"sensitive_write",SECRET_VIEW:"secret_view"},kB:{CHANNEL:"channel"},sJ:{resources:[],roles:[]}})},71463(e,t,s){let a="newapi_channel_conn";function l(e,t){return JSON.stringify({_type:a,key:e,url:t})}function n(e){if(!e||"string"!=typeof e)return null;try{let t=JSON.parse(e.trim());if("object"==typeof t&&null!==t&&t._type===a&&"string"==typeof t.key&&"string"==typeof t.url)return{key:t.key,url:t.url}}catch{}return null}s.d(t,{G1:()=>l,hd:()=>n})},27526(e,t,s){s.r(t),s.d(t,{component:()=>nC});var a=s(72361),l=s(53540),n=s(71114),r=s(76336),i=s(6702),o=s(47745),d=s(90879),c=s(47303),u=s(89795),m=s(52523),h=s(12257),p=s(96962),x=s(68413),g=s(20598),f=s(22990);function j(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return Array.from(new Set((e||[]).map(e=>String(e||"").trim()).filter(Boolean)))}function v(e){let t=null;if(e&&"object"==typeof e&&!Array.isArray(e))t=e;else if("string"==typeof e)try{t=JSON.parse(e)}catch{t=null}return t&&"object"==typeof t?{enabled:!0===t.upstream_model_update_check_enabled,pendingAddModels:j(t.upstream_model_update_last_detected_models||[]),pendingRemoveModels:j(t.upstream_model_update_last_removed_models||[])}:{enabled:!1,pendingAddModels:[],pendingRemoveModels:[]}}let y={skipBusinessError:!0,skipErrorHandler:!0};var b=s(19376),_=s(43459);let N={0:"Unknown",1:"OpenAI",2:"MjProxy",3:"Azure",4:"Ollama",5:"MjProxyPlus",7:"OhMyGPT",8:"Custom",14:"Anthropic",15:"Baidu",16:"Zhipu",17:"Ali",18:"Xunfei",19:"360",20:"OpenRouter",22:"FastGPT",23:"Tencent",24:"Gemini",25:"Moonshot",26:"Zhipu V4",27:"Perplexity",31:"LingYiWanWu",33:"AWS",34:"Cohere",35:"MiniMax",36:"SunoAPI",37:"Dify",38:"Jina",39:"Cloudflare",40:"SiliconFlow",41:"Vertex AI",42:"Mistral",43:"DeepSeek",44:"MokaAI",45:"VolcEngine",46:"Baidu V2",47:"Xinference",48:"xAI",49:"Coze",50:"Kling",51:"Jimeng",52:"Vidu",53:"Submodel",54:"DoubaoVideo",55:"Sora",56:"Replicate",57:"ChatGPT Subscription (Codex)",58:"Advanced Custom",59:"Sub2API",60:"New API"},w=[1,14,33,24,43,3,41,48,60,58,42,34,20,4,40,27,25,17,26,15,46,23,18,45,31,35,49,19,47,37,38,39,11,8,57,59,22,21,44,2,5,36,50,51,52,53,54,55,56],k=(()=>{let e=[],t=new Set;for(let s of w){let a=N[s];a&&(e.push({value:s,label:a}),t.add(s))}for(let[s,a]of Object.entries(N)){let l=Number(s);0===l||t.has(l)||e.push({value:l,label:a})}return e})(),C={0:"Unknown",1:"Enabled",2:"Disabled",3:"Auto Disabled"},A=[{value:"all",label:"All Status"},{value:"enabled",label:"Enabled"},{value:"disabled",label:"Disabled"}],S={0:{variant:"neutral",label:"Unknown"},1:{variant:"success",label:"Enabled"},2:{variant:"danger",label:"Disabled"},3:{variant:"warning",label:"Auto Disabled"}},R={1:{variant:"success",label:"Enabled"},2:{variant:"neutral",label:"Manual Disabled"},3:{variant:"danger",label:"Auto Disabled"}},I=[{value:"single",label:"Single Key"},{value:"batch",label:"Batch Add (one key per line)"},{value:"multi_to_single",label:"Multi-Key Mode (multiple keys, one channel)"}],M=[{value:"all",label:"All Status"},{value:"1",label:"Enabled"},{value:"2",label:"Manual Disabled"},{value:"3",label:"Auto Disabled"}],O="Invalid JSON format",T="Failed to create channel",z="Failed to update channel",E="Failed to delete channel",$="Failed to test channel",F={variant:"success",label:"Excellent"},B={variant:"success",label:"Good"},P={variant:"warning",label:"Fair"},D={variant:"danger",label:"Poor"},J={variant:"neutral",label:"Not tested"},q=new Set([1,4,14,17,20,23,24,25,26,27,31,34,35,40,42,43,47,48,57,58,59,60]),L={15:"Format: APIKey|SecretKey",18:"Format: APPID|APISecret|APIKey",22:"Format: APIKey-AppId, e.g., fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041",23:"Format: TokenHub API Key, or legacy AppId|SecretId|SecretKey",33:"Format: Ak|Sk|Region",50:"Format: AccessKey|SecretKey (or just ApiKey if upstream is New API)",51:"Format: Access Key ID|Secret Acce
1ss Key",57:"Paste Codex OAuth JSON credential (access_token / refresh_token / account_id)",59:"Enter API key for this channel",60:"Enter API key for this channel"},V={3:'For channels added after May 10, 2025, no need to remove "." from model names during deployment',8:"If connecting to upstream One API or New API relay projects, use OpenAI type instead unless you know what you are doing",37:"Dify channels only support chatflow and agent, and agent does not support images"},K={all:["channels"],lists:()=>[...K.all,"list"],list:e=>[...K.lists(),e],details:()=>[...K.all,"detail"],detail:e=>[...K.details(),e]};function W(e){let t=e?.channelName?.trim(),s=e?.testModel?.trim();return t&&s?b.Ay.t("Channel {{name}} model {{model}}",{name:t,model:s}):t?b.Ay.t("Channel {{name}}",{name:t}):s?b.Ay.t("Model {{model}}",{model:s}):b.Ay.t("Channel")}async function U(e,t,s){try{let a=await (0,h.BK)(e,1);a.success?(g.oR.success(b.Ay.t("Channel enabled successfully")),t?.invalidateQueries({queryKey:K.lists()}),s?.()):g.oR.error(a.message||b.Ay.t(z))}catch{g.oR.error(b.Ay.t(z))}}async function H(e,t,s){try{let a=await (0,h.BK)(e,2);a.success?(g.oR.success(b.Ay.t("Channel disabled successfully")),t?.invalidateQueries({queryKey:K.lists()}),s?.()):g.oR.error(a.message||b.Ay.t(z))}catch{g.oR.error(b.Ay.t(z))}}async function G(e,t,s,a){1===t?await H(e,s,a):await U(e,s,a)}async function Y(e,t,s){try{let a=await (0,h.D3)(e);a.success?(g.oR.success(b.Ay.t("Channel deleted successfully")),t?.invalidateQueries({queryKey:K.lists()}),s?.()):g.oR.error(a.message||b.Ay.t(E))}catch{g.oR.error(b.Ay.t(E))}}async function Z(e,t,s,a,l){try{let n=await (0,h.fy)(e,{[t]:s});if(n.success){let e=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase();g.oR.success(b.Ay.t("{{field}} updated to {{value}}",{field:e,value:s})),a?.invalidateQueries({queryKey:K.lists()}),l?.()}else g.oR.error(n.message||b.Ay.t(z))}catch{g.oR.error(b.Ay.t(z))}}async function Q(e,t,s,a,l){try{let n=await (0,h.vS)({tag:e,[t]:s});if(n.success){let n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase();g.oR.success(b.Ay.t("{{field}} updated to {{value}} for tag: {{tag}}",{field:n,value:s,tag:e})),a?.invalidateQueries({queryKey:K.lists()}),l?.()}else g.oR.error(n.message||b.Ay.t(z))}catch{g.oR.error(b.Ay.t(z))}}async function X(e,t,s){let a=t&&(t.testModel||t.endpointType||t.stream)?{...t.testModel?{model:t.testModel}:{},...t.endpointType?{endpoint_type:t.endpointType}:{},...t.stream?{stream:!0}:{}}:void 0;try{let l,n=await (0,h.S4)(e,a),r=(l=n.data?.response_time,"number"==typeof l&&Number.isFinite(l)?l:"number"==typeof n.time&&Number.isFinite(n.time)&&n.time>0?Math.round(1e3*n.time):void 0),i=function(e){if(void 0!==e)return e>=1e3?`${(e/1e3).toFixed(2)} s`:`${Math.max(1,Math.round(e))} ms`}(r),o=W(t);if(n.success)t?.silent||g.oR.success(b.Ay.t("{{target}} test succeeded",{target:o}),i?{description:b.Ay.t("Response time: {{duration}}",{duration:i})}:void 0),s?.(!0,r);else{let e=n.message||b.Ay.t($);t?.silent||g.oR.error(b.Ay.t("{{target}} test failed",{target:o}),{description:n.error_code?`${e} (${n.error_code})`:e}),s?.(!1,r,e,n.error_code)}}catch(l){let e=l?.response?.data?.message||b.Ay.t($),a=W(t);t?.silent||g.oR.error(b.Ay.t("{{target}} test failed",{target:a}),{description:e}),s?.(!1,void 0,e)}}async function ee(e,t,s,a){try{let l=await (0,h.Rx)(e,t);l.success?(g.oR.success(b.Ay.t("Channel copied successfully")),s?.invalidateQueries({queryKey:K.lists()}),a?.(l.data?.id??0)):g.oR.error(l.message||b.Ay.t("Failed to copy channel"))}catch{g.oR.error(b.Ay.t("Failed to copy channel"))}}async function et(e,t,s){try{let a=await (0,h.$3)(e);if(a.success&&void 0!==a.balance){let e=a.balance;g.oR.success(b.Ay.t("Balance updated: {{balance}}",{balance:(0,_.J5)(e,{digitsLarge:2,digitsSmall:4,abbreviate:!1})})),t?.invalidateQueries({queryKey:K.lists()}),s?.(e)}else g.oR.error(a.message||b.Ay.t("Failed to update balance"))}catch(e){g.oR.error(e instanceof Error?e.message:b.Ay.t("Failed to update balance"))}}async function es(e,t,s){if(0===e.length)return void g.oR.error(b.Ay.t("No channels selected"));try{let a=await (0,h.oR)({ids:e});a.success?(g.oR.success(b.Ay.t("{{count}} channel(s) deleted",{count:a.data||e.length}
1)),t?.invalidateQueries({queryKey:K.lists()}),s?.(a.data||e.length)):g.oR.error(a.message||b.Ay.t(E))}catch{g.oR.error(b.Ay.t(E))}}async function ea(e,t,s){if(0===e.length)return void g.oR.error(b.Ay.t("No channels selected"));try{let a=await (0,h.BF)(e,1),l=a.success&&a.data||0,n=e.length-l;l>0&&(g.oR.success(b.Ay.t("{{count}} channel(s) enabled",{count:l})),t?.invalidateQueries({queryKey:K.lists()}),s?.()),a.success?n>0&&g.oR.error(b.Ay.t("{{count}} channel(s) failed to enable",{count:n})):g.oR.error(a.message||b.Ay.t("Failed to enable channels"))}catch{g.oR.error(b.Ay.t("Failed to enable channels"))}}async function el(e,t,s){if(0===e.length)return void g.oR.error(b.Ay.t("No channels selected"));try{let a=await (0,h.BF)(e,2),l=a.success&&a.data||0,n=e.length-l;l>0&&(g.oR.success(b.Ay.t("{{count}} channel(s) disabled",{count:l})),t?.invalidateQueries({queryKey:K.lists()}),s?.()),a.success?n>0&&g.oR.error(b.Ay.t("{{count}} channel(s) failed to disable",{count:n})):g.oR.error(a.message||b.Ay.t("Failed to disable channels"))}catch{g.oR.error(b.Ay.t("Failed to disable channels"))}}async function en(e,t,s,a){if(0===e.length)return void g.oR.error(b.Ay.t("No channels selected"));try{let l=await (0,h.iC)({ids:e,tag:t});l.success?(g.oR.success(b.Ay.t("Tag set successfully")),s?.invalidateQueries({queryKey:K.lists()}),a?.()):g.oR.error(l.message||b.Ay.t("Failed to set tag"))}catch{g.oR.error(b.Ay.t("Failed to set tag"))}}async function er(e,t,s){try{let a=await (0,h.k)(e);a.success?(g.oR.success(b.Ay.t("Enabled all channels with tag: {{tag}}",{tag:e})),t?.invalidateQueries({queryKey:K.lists()}),s?.()):g.oR.error(a.message||b.Ay.t("Failed to enable tag channels"))}catch{g.oR.error(b.Ay.t("Failed to enable tag channels"))}}async function ei(e,t,s){try{let a=await (0,h.lK)(e);a.success?(g.oR.success(b.Ay.t("Disabled all channels with tag: {{tag}}",{tag:e})),t?.invalidateQueries({queryKey:K.lists()}),s?.()):g.oR.error(a.message||b.Ay.t("Failed to disable tag channels"))}catch{g.oR.error(b.Ay.t("Failed to disable tag channels"))}}async function eo(e,t){try{let s=await (0,h.KR)();s.success?(g.oR.success(b.Ay.t("{{count}} disabled channel(s) deleted",{count:s.data||0})),e?.invalidateQueries({queryKey:K.lists()}),t?.(s.data||0)):g.oR.error(s.message||b.Ay.t("Failed to delete disabled channels"))}catch{g.oR.error(b.Ay.t("Failed to delete disabled channels"))}}async function ed(e,t){try{let s=await (0,h.xn)();s.success&&s.data?(g.oR.success(b.Ay.t("Channel consistency repaired: {{success}} succeeded, {{fails}} failed",{success:s.data.success,fails:s.data.fails})),e?.invalidateQueries({queryKey:K.lists()}),t?.(s.data)):g.oR.error(s.message||b.Ay.t("Failed to repair channel consistency"))}catch{g.oR.error(b.Ay.t("Failed to repair channel consistency"))}}async function ec(e,t){try{let s=await (0,h.kV)();s.success?(g.oR.success(b.Ay.t("Testing all enabled channels started. Please refresh to see results.")),e?.invalidateQueries({queryKey:K.lists()}),t?.()):g.oR.error(s.message||b.Ay.t("Failed to start testing all channels"))}catch{g.oR.error(b.Ay.t("Failed to test all channels"))}}async function eu(e,t){try{let s=await (0,h.Vq)();s.success?(g.oR.success(b.Ay.t("Updating all channel balances. This may take a while. Please refresh to see results.")),e?.invalidateQueries({queryKey:K.lists()}),t?.()):g.oR.error(s.message||b.Ay.t("Failed to update all balances"))}catch{g.oR.error(b.Ay.t("Failed to update all balances"))}}let em={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e)},eh="/v1/models",ep="OpenAI Models",ex=[{value:"none",label:"Native forwarding",triggerLabel:"Native forwarding"},{value:"anthropic_messages_to_openai_chat_completions",label:"Anthropic Messages to OpenAI Chat",triggerLabel:"To OpenAI Chat"},{value:"openai_chat_completions_to_anthropic_messages",label:"OpenAI Chat to Anthropic Messages",triggerLabel:"To Anthropic Messages"},{value:"openai_chat_completions_to_openai_responses",label:"OpenAI Chat to OpenAI Responses",triggerLabel:"To OpenAI Responses"},{value:"openai_responses_to_openai_chat_completions",label:"OpenAI Responses to OpenAI Chat",triggerLabel:"To OpenAI Chat"},{value:"openai_responses_to_gemini_generate_content",label:"OpenAI Responses to Gemini Generate Content",triggerLabel:"To Gemini Generate Content"},{value:"gemini_generate_content_to_openai_chat_completions",label:"Gemini Generate Content to OpenAI Chat",triggerLabel:"To OpenAI Chat"},{value:"openai_chat_completions_to_gemini_generate_content",label:"OpenAI Chat to Gemini Generate Content",triggerLabel:"To Gemini Generate Content"}],eg=[{value:"default",label:"Default Bearer"},{value:"none",label:"No Auth"},{value:"header",label:"Header"},{value:"query",label:"Query"}],ef=[{value:"/v1/chat/completions",label:"OpenAI Chat"},{value:"/v1/responses",label:"OpenAI Responses"},{value:"/v1/responses/compact",label:"OpenAI Responses Compact"},{value:"/v1/alpha/search",label:"OpenAI Alpha Search"},{value:eh,label:ep},{value:"/v1/embeddings",label:"OpenAI Embeddings"},{value:"/v1/images/generations",label:"OpenAI Image Generations"},{value:"/v1/images/edits",label:"OpenAI Image Edits"},{value:"/v1/completions",label:"OpenAI Completions"}
1,{value:"/v1/audio/speech",label:"OpenAI Audio Speech"},{value:"/v1/audio/transcriptions",label:"OpenAI Audio Transcriptions"},{value:"/v1/audio/translations",label:"OpenAI Audio Translations"},{value:"/v1/rerank",label:"OpenAI Rerank"},{value:"/v1/realtime",label:"OpenAI Realtime"},{value:"/v1/messages",label:"Claude Messages"},{value:"/v1beta/models/{model}:generateContent",label:"Gemini Generate Content"},{value:"/v1beta/models/{model}:embedContent",label:"Gemini Embed Content"},{value:"/v1beta/models/{model}:batchEmbedContents",label:"Gemini Batch Embed Contents"}],ej={"/v1/chat/completions":"OpenAI Chat",[eh]:ep},ev="/v1/chat/completions",ey="/v1/messages",eb=()=>({type:"header",name:"Authorization",value:"Bearer {api_key}"}),e_=()=>({type:"header",name:"x-api-key",value:"{api_key}"}),eN=()=>({type:"query",name:"key",value:"{api_key}"}),ew=[{value:"official_openai_chat",label:"Official OpenAI Chat",config:{advanced_routes:[{incoming_path:"/v1/chat/completions",upstream_path:"/v1/chat/completions",converter:"none",auth:eb()}]}},{value:"official_openai_responses",label:"Official OpenAI Responses",config:{advanced_routes:[{incoming_path:"/v1/responses",upstream_path:"/v1/responses",converter:"none",auth:eb()}]}},{value:"official_openai_embeddings",label:"Official OpenAI Embeddings",config:{advanced_routes:[{incoming_path:"/v1/embeddings",upstream_path:"/v1/embeddings",converter:"none",auth:eb()}]}},{value:"official_openai_images",label:"Official OpenAI Images",config:{advanced_routes:[{incoming_path:"/v1/images/generations",upstream_path:"/v1/images/generations",converter:"none",auth:eb()},{incoming_path:"/v1/images/edits",upstream_path:"/v1/images/edits",converter:"none",auth:eb()}]}},{value:"official_claude_messages",label:"Official Claude Messages",config:{advanced_routes:[{incoming_path:"/v1/messages",upstream_path:"/v1/messages",converter:"none",auth:e_()}]}},{value:"official_gemini_native",label:"Official Gemini Native",config:{advanced_routes:[{incoming_path:"/v1beta/models/{model}:generateContent",upstream_path:"/v1beta/models/{model}:generateContent",converter:"none",auth:eN()},{incoming_path:"/v1beta/models/{model}:embedContent",upstream_path:"/v1beta/models/{model}:embedContent",converter:"none",auth:eN()},{incoming_path:"/v1beta/models/{model}:batchEmbedContents",upstream_path:"/v1beta/models/{model}:batchEmbedContents",converter:"none",auth:eN()}]}},{value:"official_gemini_from_openai_chat",label:"Official Gemini from OpenAI Chat",config:{advanced_routes:[{incoming_path:"/v1/chat/completions",upstream_path:"/v1beta/models/{model}:generateContent",converter:"openai_chat_completions_to_gemini_generate_content",auth:eN()}]}}];function ek(e){return JSON.parse(JSON.stringify((ew.find(t=>t.value===e)||ew[0]).config))}function eC(){return{incoming_path:ev,upstream_path:ev,converter:"none"}}function eA(){return{advanced_routes:[eC()]}}function eS(e,t){let s=t.trim()||eI(e);return"none"===e?{upstream_path:s,auth:eR(s)}:"anthropic_messages_to_openai_chat_completions"===e||"gemini_generate_content_to_openai_chat_completions"===e||"openai_responses_to_openai_chat_completions"===e?{upstream_path:ev,auth:eb()}:"openai_chat_completions_to_openai_responses"===e?{upstream_path:"/v1/responses",auth:eb()}:"openai_chat_completions_to_anthropic_messages"===e?{upstream_path:ey,auth:e_()}:"openai_chat_completions_to_gemini_generate_content"===e||"openai_responses_to_gemini_generate_content"===e?{upstream_path:"/v1beta/models/{model}:generateContent",auth:eN()}:{upstream_path:s||ev,auth:eR(s)}}function eR(e){return e===ey?e_():e.includes(":generateContent")||e.includes(":streamGenerateContent")||e.includes(":embedContent")||e.includes(":batchEmbedContents")?eN():eb()}function eI(e){return ef.filter(t=>eJ(t.value,e))[0]?.value||"/v1/chat/completions"}function eM(e){return ef.find(t=>t.value===e)?.label||e}function eO(e){if(!e?.trim())return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return null;return ez(t)}catch{return null}}function eT(e){return JSON.stringify(ez(e),null,2)}function ez(e){return{advanced_routes:Array.isArray(e.advanced_routes)?e.advanced_routes.map(eB):[]}}function eE(e){return[...new Set(e.split(",").map(e=>
1e.trim()).filter(Boolean))]}function e$(e){return e.startsWith("re:")?"regex":"exact"}function eF(e){if(!e)return{message:"Advanced custom configuration is required"};let t=ez(e).advanced_routes||[];if(0===t.length)return{message:"Advanced custom configuration requires at least one route"};let s=new Map,a=null;for(let e=0;e<t.length;e+=1){var l;let n=t[e],r=n.incoming_path?.trim()||"",i=eD(n),o=n.converter||"none",d=eP(n.models);if(!r)return{routeIndex:e,message:"Incoming path is required"};if(!r.startsWith("/"))return{routeIndex:e,message:"Incoming path must start with /"};if(r.includes("?"))return{routeIndex:e,message:"Incoming path must not include query"};if(r===eh){if(null!==a)return{routeIndex:e,message:"Only one OpenAI Models route is allowed"};if(a=e,d.length>0)return{routeIndex:e,message:"OpenAI Models route does not support client model rules"};if("none"!==o)return{routeIndex:e,message:"OpenAI Models route must use native forwarding"};if(i.includes("{model}"))return{routeIndex:e,message:"OpenAI Models upstream path must not contain {model}"}}let c=function(e,t,s,a){let l=a.get(t);if(l||(l={catchAllIndex:null,models:new Map},a.set(t,l)),0===s.length)return null!==l.catchAllIndex?{routeIndex:e,message:"Only one catch-all route is allowed for the same incoming path"}:(l.catchAllIndex=e,null);if(null!==l.catchAllIndex)return{routeIndex:e,message:"Catch-all route must be last for the same incoming path"};let n=new Set;for(let t of s){if("regex"===e$(t)&&""===t.slice(3))return{routeIndex:e,message:"Model regex cannot be empty"};if(n.has(t))return{routeIndex:e,message:"Duplicate model in route models"};if(n.add(t),l.models.has(t))return{routeIndex:e,message:"Route models must be unique for the same incoming path"};l.models.set(t,e)}return null}(e,r,d,s);if(c)return c;if(!i)return{routeIndex:e,message:"Upstream path is required"};if(!function(e){if(e.startsWith("/"))return!e.startsWith("//");try{let t=new URL(e);return!!t.host&&("http:"===t.protocol||"https:"===t.protocol)}catch{return!1}}(i))return{routeIndex:e,message:"Upstream path must be a full URL or a path starting with /"};if(!function(e){return ex.some(t=>t.value===e)}(o))return{routeIndex:e,message:"Converter is not registered"};if(!eJ(r,o))return{routeIndex:e,message:"Converter does not match incoming path"};let u=(l=n.auth)&&"none"!==l.type?"header"!==l.type&&"query"!==l.type?"Auth type is invalid":l.name?.trim()?l.value?.trim()?null:"Auth value is required":"Auth name is required":null;if(u)return{routeIndex:e,message:u}}return null}function eB(e){let t={incoming_path:e.incoming_path||"",upstream_path:eD(e),converter:e.converter||"none"},s=eP(e.models);return s.length>0&&(t.models=s),e.auth&&(t.auth={type:e.auth.type,name:e.auth.name||"",value:e.auth.value||""}),t}function eP(e){return Array.isArray(e)?e.map(e=>e.trim()).filter(Boolean):[]}function eD(e){return(e.upstream_path||"").trim()}function eJ(e,t){return"none"===t||"/v1/alpha/search"!==e&&("anthropic_messages_to_openai_chat_completions"===t?"/v1/messages"===e:"openai_chat_completions_to_anthropic_messages"===t||"openai_chat_completions_to_openai_responses"===t||"openai_chat_completions_to_gemini_generate_content"===t?"/v1/chat/completions"===e:"openai_responses_to_openai_chat_completions"===t||"openai_responses_to_gemini_generate_content"===t?"/v1/responses"===e:e.includes(":generateContent")||e.includes(":streamGenerateContent"))}let eq=new Set(["priority","weight","test_model","auto_ban","tag","remark","param_override","header_override","status_code_mapping","advanced_custom","force_format","thinking_to_content","pass_through_body_enabled","proxy","http_protocol","http2_connection_shards","system_prompt","system_prompt_override","allow_service_tier","disable_store","allow_safety_identifier","allow_include_obfuscation","allow_inference_geo","allow_speed","claude_beta_query","disable_task_polling_sleep","upstream_model_update_check_enabled","upstream_model_update_auto_sync_enabled","upstream_model_update_ignored_models"]);function eL(e){return Object.keys(e).some(e=>eq.has(e))}var eV=s(41128),eK=s(25732);let eW=new Set(["http:","https:","socks5:","socks5h:"]),eU="auto",eH="http1";function eG(e){return String(e||"").trim().toLowerCase()===eH?eH:eU}function eY(e){return null==e||Number.isNaN(e)||0===e||e<1?1:e>8?8:e}function eZ(e){if(e?.trim())return JSON.parse(e)}function eQ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eX(e){try{let t=eZ(e);return void 0===t||eQ(t)}catch{return!1}}function e0(e,t,s){e.addIssue({code:eV.eq.custom,path:[t],message:s})}let e1=eK.Ik({name:eK.Yj().min(1,"Channel name is required"),type:eK.ai().min(0,"Channel type is required"),base_url:eK.Yj().optional(),key:eK.Yj(),openai_organization:eK.Yj().optional(),models:eK.Yj().min(1,"Models are required"),group:eK.YO(eK.Yj()).min(1,"Group is required"),model_mapping:eK.Yj().optional().refine(function(e){try{let t=eZ(e);if(void 0===t)return!0;
1if(!eQ(t))return!1;return Object.values(t).every(e=>"string"==typeof e)}catch{return!1}},"Model mapping must be a JSON object with string values"),priority:eK.ai().optional(),weight:eK.ai().optional(),test_model:eK.Yj().optional(),auto_ban:eK.ai().optional(),status:eK.ai(),status_code_mapping:eK.Yj().optional().refine(function(e){try{let t=eZ(e);if(void 0===t)return!0;if(!eQ(t))return!1;return Object.entries(t).every(e=>{let[t,s]=e,a=Number(t),l=Number(s);return Number.isInteger(a)&&Number.isInteger(l)&&a>=100&&a<=599&&l>=100&&l<=599})}catch{return!1}},"Status code mapping must use valid HTTP status codes"),tag:eK.Yj().optional(),remark:eK.Yj().max(255,"Remark must be less than 255 characters").optional(),setting:eK.Yj().optional().refine(eX,O),param_override:eK.Yj().optional().refine(eX,O),header_override:eK.Yj().optional().refine(eX,O),settings:eK.Yj().optional().refine(eX,O),advanced_custom:eK.Yj().optional(),other:eK.Yj().optional(),multi_key_mode:eK.k5(["single","batch","multi_to_single"]).optional(),multi_key_type:eK.k5(["random","polling"]).optional(),batch_add_set_key_prefix_2_name:eK.zM().optional(),key_mode:eK.k5(["append","replace"]).optional(),force_format:eK.zM().optional(),thinking_to_content:eK.zM().optional(),proxy:eK.Yj().optional().refine(function(e){let t=e?.trim()||"";if(!t)return!0;let s=t.indexOf("://");if(s<=0)return!1;let a=t.slice(s+3),l=a.search(/[/?#]/);if(l>=0&&"/"!==a.slice(l))return!1;try{let e=new URL(t);return eW.has(e.protocol)&&!!e.hostname&&"0"!==e.port}catch{return!1}},"Proxy address must use HTTP, HTTPS, SOCKS5, or SOCKS5H and include a valid host"),http_protocol:eK.k5(["auto","http1"]).optional(),http2_connection_shards:eK.ai().int().optional(),pass_through_body_enabled:eK.zM().optional(),system_prompt:eK.Yj().optional(),system_prompt_override:eK.zM().optional(),is_enterprise_account:eK.zM().optional(),vertex_key_type:eK.k5(["json","api_key"]).optional(),aws_key_type:eK.k5(["ak_sk","api_key"]).optional(),azure_responses_version:eK.Yj().optional(),allow_service_tier:eK.zM().optional(),disable_store:eK.zM().optional(),allow_safety_identifier:eK.zM().optional(),allow_include_obfuscation:eK.zM().optional(),allow_inference_geo:eK.zM().optional(),allow_speed:eK.zM().optional(),claude_beta_query:eK.zM().optional(),disable_task_polling_sleep:eK.zM().optional(),upstream_model_update_check_enabled:eK.zM().optional(),upstream_model_update_auto_sync_enabled:eK.zM().optional(),upstream_model_update_ignored_models:eK.Yj().optional()}).superRefine((e,t)=>{if([3,8,36,45,60].includes(e.type)&&!e.base_url?.trim()&&e0(t,"base_url","Base URL is required for this channel type"),58===e.type){let s=eO(e.advanced_custom),a=eF(s);a&&e0(t,"advanced_custom",a.message),s&&(ez(s).advanced_routes||[]).some(e=>eD(e).startsWith("/"))&&!e.base_url?.trim()&&e0(t,"base_url","Base URL is required when an advanced route uses an upstream path"),!0!==e.upstream_model_update_check_enabled||!(!s||eF(s))&&(ez(s).advanced_routes||[]).some(e=>e.incoming_path?.trim()===eh)||e0(t,"upstream_model_update_check_enabled","OpenAI Models route is required to enable upstream model checks")}[3,18,21,39,41,49].includes(e.type)&&!e.other?.trim()&&e0(t,"other","This channel type requires additional configuration"),57===e.type&&(e.multi_key_mode&&"single"!==e.multi_key_mode&&e0(t,"multi_key_mode","Codex channels do not support batch creation"),e.key?.trim()&&!function(e){try{let t=eZ(e);if(void 0===t)return!0;return eQ(t)&&"string"==typeof t.access_token&&t.access_token.trim().length>0&&"string"==typeof t.account_id&&t.account_id.trim().length>0}catch{return!1}}(e.key)&&e0(t,"key","Codex credential must be a JSON object with access_token and account_id")),41===e.type&&"json"===e.vertex_key_type&&e.key?.trim()&&!function(e){try{let t=eZ(e);if(void 0===t)return!0;if(Array.isArray(t))return t.every(e=>eQ(e));return eQ(t)}catch{return!1}}(e.key)&&e0(t,"key","Vertex AI service account key must be valid JSON"),41===e.type&&"api_key"===e.vertex_key_type&&e.multi_key_mode&&"single"!==e.multi_key_mode&&e0(t,"multi_key_mode","Vertex AI API Key mode does not support batch creation");let s=eG(e.http_protocol),a=e.http2_connection_shards??1;(a<1||a>8)&&e0(t,"http2_connection_shards","HTTP/2 connection shards must be between 1 and 8"),s===eH&&a>1&&e0(t,"http2_connection_shards","HTTP/2 connection shards must be 1 when HTTP/1.1 is selected")}
1),e2={name:"",type:1,base_url:"",key:"",openai_organization:"",models:"",group:["default"],model_mapping:"",priority:0,weight:0,test_model:"",auto_ban:1,status:1,status_code_mapping:"",tag:"",remark:"",setting:"",param_override:"",header_override:"",settings:"{}",other:"",multi_key_mode:"single",multi_key_type:"random",batch_add_set_key_prefix_2_name:!1,key_mode:"append",force_format:!1,thinking_to_content:!1,proxy:"",http_protocol:eU,http2_connection_shards:1,pass_through_body_enabled:!1,system_prompt:"",system_prompt_override:!1,is_enterprise_account:!1,vertex_key_type:"json",aws_key_type:"ak_sk",azure_responses_version:"",allow_service_tier:!1,disable_store:!1,allow_safety_identifier:!1,allow_include_obfuscation:!1,allow_inference_geo:!1,allow_speed:!1,claude_beta_query:!1,disable_task_polling_sleep:!1,upstream_model_update_check_enabled:!1,upstream_model_update_auto_sync_enabled:!1,upstream_model_update_ignored_models:"",advanced_custom:""};function e4(e){let t={force_format:e.force_format||!1,thinking_to_content:e.thinking_to_content||!1,proxy:e.proxy?.trim()||"",pass_through_body_enabled:e.pass_through_body_enabled||!1,system_prompt:e.system_prompt||"",system_prompt_override:e.system_prompt_override||!1},s=eG(e.http_protocol),a=s===eH?1:eY(e.http2_connection_shards);return s===eH?t.http_protocol=eH:a>1&&(t.http2_connection_shards=a),JSON.stringify(t)}function e5(e){let t={};if(e.settings&&"{}"!==e.settings)try{t=JSON.parse(e.settings)}catch(e){console.error("Failed to parse existing settings:",e)}if(41===e.type?t.vertex_key_type=e.vertex_key_type||"json":"vertex_key_type"in t&&delete t.vertex_key_type,3===e.type&&e.azure_responses_version?t.azure_responses_version=e.azure_responses_version:"azure_responses_version"in t&&delete t.azure_responses_version,20===e.type?t.openrouter_enterprise=!0===e.is_enterprise_account:"openrouter_enterprise"in t&&delete t.openrouter_enterprise,33===e.type?t.aws_key_type=e.aws_key_type||"ak_sk":"aws_key_type"in t&&delete t.aws_key_type,1===e.type||14===e.type||57===e.type?t.allow_service_tier=!0===e.allow_service_tier:"allow_service_tier"in t&&delete t.allow_service_tier,1===e.type||57===e.type?(t.disable_store=!0===e.disable_store,t.allow_safety_identifier=!0===e.allow_safety_identifier,t.allow_include_obfuscation=!0===e.allow_include_obfuscation,t.allow_inference_geo=!0===e.allow_inference_geo):("disable_store"in t&&delete t.disable_store,"allow_safety_identifier"in t&&delete t.allow_safety_identifier,"allow_include_obfuscation"in t&&delete t.allow_include_obfuscation,14!==e.type&&"allow_inference_geo"in t&&delete t.allow_inference_geo),14===e.type?(t.allow_inference_geo=!0===e.allow_inference_geo,t.allow_speed=!0===e.allow_speed,t.claude_beta_query=!0===e.claude_beta_query):("allow_speed"in t&&delete t.allow_speed,"claude_beta_query"in t&&delete t.claude_beta_query),t.disable_task_polling_sleep=!0===e.disable_task_polling_sleep,q.has(e.type)&&(t.upstream_model_update_check_enabled=!0===e.upstream_model_update_check_enabled,t.upstream_model_update_auto_sync_enabled=!0===t.upstream_model_update_check_enabled&&!0===e.upstream_model_update_auto_sync_enabled,t.upstream_model_update_ignored_models=[...new Set(String(e.upstream_model_update_ignored_models||"").split(",").map(e=>e.trim()).filter(Boolean))],Array.isArray(t.upstream_model_update_last_detected_models)&&!0===t.upstream_model_update_check_enabled||(t.upstream_model_update_last_detected_models=[]),"number"!=typeof t.upstream_model_update_last_check_time&&(t.upstream_model_update_last_check_time=0)),58===e.type){let s=eO(e.advanced_custom);s&&(t.advanced_custom=s)}else"advanced_custom"in t&&delete t.advanced_custom;return JSON.stringify(t)}function e3(e){return String(e||"").trim().replace(/\/+$/,"")}N["1"],N["3"],N["14"],N["24"],N["41"],N["43"],N["20"],N["56"],N["58"],N["59"],N["60"];var e6=s(33271);function e8(e){return N[e]||"Unknown"}function e7(e){return({1:"OpenAI",6:"OpenAI",7:"OpenAI",8:"OpenAI",58:"NewAPI",59:"Sub2API",60:"NewAPI",3:"Azure",14:"Claude",24:"Gemini",11:"Google",41:"Gemini",33:"Aws",39:"Cloudflare",15:"Baidu",46:"Baidu",16:"Zhipu",26:"Zhipu",17:"Qwen",18:"Spark",23:"Hunyuan",19:"Ai360",25:"Moonshot",31:"Yi",35:"Minimax",45:"Volcengine",4:"Ollama",27:"Perplexity",34:"Cohere",42:"Mistral",43:"DeepSeek",48:"XAI",49:"Coze",40:"SiliconCloud",44:"OpenAI",20:"OpenRouter",2:"Midjourney",5:"Midjourney",50:"Kling",51:"Jimeng",52:"Vidu",36:"Suno",5
15:"OpenAI",54:"Doubao",56:"Replicate",37:"Dify",38:"Jina",22:"FastGPT",47:"Xinference",53:"OpenAI",10:"OpenAI",21:"OpenAI",12:"OpenAI",13:"OpenAI",9:"OpenAI"})[e]||"OpenAI"}function e9(e){return e.channel_info?.is_multi_key||!1}function te(e){return e?e.split(",").map(e=>e.trim()).filter(e=>e.length>0).sort((e,t)=>"default"===e?-1:"default"===t?1:e.localeCompare(t)):[]}function tt(e,t){return 0===e?t?t("Not tested"):"Not tested":e<1e3?t?t("{{value}}ms",{value:e}):`${e}ms`:t?t("{{value}}s",{value:(e/1e3).toFixed(2)}):`${(e/1e3).toFixed(2)}s`}function ts(e){return Array.isArray(e.children)}function ta(e){return ts(e)?`tag:${e.tag||""}`:`channel:${e.id}`}function tl(e){return e?e.split(",").map(e=>e.trim()).filter(Boolean):[]}function tn(e){return Array.from(new Set(e)).join(",")}function tr(e){return"string"==typeof e?e.trim():""}let ti=[{name:"Perplexity",keywords:["perplexity","sonar-"]},{name:"NVIDIA",keywords:["nvidia/","nvidia.","nemotron"]},{name:"OpenAI",keywords:["openai/","openai.","gpt-","chatgpt-","codex-","dall-e-","whisper-","tts-","omni-moderation-","text-moderation-","text-embedding-ada-","text-embedding-3-","text-ada-","text-babbage-","text-curie-","davinci-","babbage-","computer-use-preview","sora"],pattern:/(?:^|[/.:])o(?:1|3|4)(?=$|[-.:])/},{name:"Anthropic",keywords:["anthropic","claude"]},{name:"Gemini",keywords:["gemini","gemma","learnlm","imagen","veo","nano-banana","palm-"],pattern:/(?:^|[/.:])aqa$/},{name:"xAI",keywords:["x-ai/","xai/","xai-","grok"]},{name:"DeepSeek",keywords:["deepseek"]},{name:"Qwen",keywords:["qwen","qwq-","qvq-","tongyi","gte-"],pattern:/(?:^|[/.:])(?:text-embedding-v\d+|gui-plus|z-image)(?:$|[-_.:])/},{name:"Wan",pattern:/(?:^|[/.:])wan(?:x?\d|[-_])/}
1,{name:"Moonshot",keywords:["moonshot","kimi-"]},{name:"MiniMax",keywords:["minimax","abab","hailuo"],pattern:/^(?:t2v|i2v|s2v)-01(?:-|$)/},{name:"Doubao",keywords:["doubao","volcengine","seedance","seedream","seed-1-"]},{name:"Zhipu",keywords:["zhipu","zai-org","thudm","chatglm","cogview","cogvideo"],pattern:/(?:^|[/._-])glm(?=$|[-._])/},{name:"Baidu",keywords:["baidu","wenxin","ernie"]},{name:"Yi",keywords:["01-ai/"],pattern:/(?:^|[/.:])yi(?=$|[-_])/},{name:"iFlytek",keywords:["iflytek","sparkdesk"]},{name:"Tencent",keywords:["tencent","hunyuan"],pattern:/(?:^|[/.:])hy\d*(?=$|[-_.:])/},{name:"Baichuan",keywords:["baichuan"]},{name:"InternLM",keywords:["internlm"]},{name:"StepFun",keywords:["stepfun","step-"]},{name:"MiMo",keywords:["xiaomi","mimo-"]},{name:"Mistral",keywords:["mistral","mixtral","codestral","ministral","pixtral","magistral"]},{name:"Meta",keywords:["meta-llama","llama-","llama2","llama3"]},{name:"Cohere",keywords:["cohere","command-","c4ai-aya","aya-"],pattern:/(?:^|[/.:])command$/},{name:"Jina",keywords:["jinaai","jina-"]},{name:"BAAI",keywords:["baai/","bge-"]},{name:"Black Forest Labs",keywords:["black-forest-labs","flux."]},{name:"Microsoft",keywords:["microsoft/"],pattern:/(?:^|[/.:])phi(?=$|[-._])/},{name:"Amazon",keywords:["amazon/","amazon.","nova-","titan-"]},{name:"AI21 Labs",keywords:["ai21","jamba"]},{name:"Stability AI",keywords:["stabilityai","stable-diffusion","stable-image","sdxl-"]},{name:"Nous Research",keywords:["nousresearch","hermes-"]},{name:"360 AI",keywords:["360gpt","360zhinao"]},{name:"Midjourney",keywords:["midjourney","mj_","mj-","swap_face"]},{name:"Kling",keywords:["kling"]},{name:"Vidu",keywords:["vidu"]},{name:"Suno",keywords:["suno"]},{name:"Jimeng",keywords:["jimeng"]}];function to(e){let t={};for(let s of e){let e=function(e){let t=e.trim().toLowerCase();for(let e of ti)if(e.keywords?.some(e=>t.includes(e))||e.pattern?.test(t))return e.name;return"Other"}(s);t[e]??=[],t[e].push(s)}return t}let td=(0,x.createContext)(void 0);function tc(e){let{children:t}=e,[s,l]=(0,x.useState)(null),[n,r]=(0,x.useState)(null),[o,d]=(0,x.useState)(null),[c,u]=(0,x.useState)(()=>"true"===localStorage.getItem("enable-tag-mode")),[m,h]=(0,x.useState)(()=>"true"===localStorage.getItem("channels-id-sort")),[v,b]=(0,x.useState)(!1),[_,N]=(0,x.useState)(!0),w=(0,p.jE)(),k=function(e){let{t}=(0,i.Bd)(),[s,a]=(0,x.useState)(!1),[l,n]=(0,x.useState)(null),[r,o]=(0,x.useState)([]),[d,c]=(0,x.useState)([]),[u,m]=(0,x.useState)("add"),[h,p]=(0,x.useState)(!1),[v,b]=(0,x.useState)(!1),[_,N]=(0,x.useState)(!1),w=(0,x.useRef)(!1),k=(0,x.useRef)(!1),C=(0,x.useRef)(!1),A=(0,x.useRef)(!1),S=(0,x.useCallback)(function(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"add",i=j(s),d=j(l);e?.id&&(0!==i.length||0!==d.length)?(n(e),o(i),c(d),m(r),a(!0)):g.oR.info(t("No processable upstream model updates for this channel"))},[t]),R=(0,x.useCallback)(()=>{a(!1),n(null),o([]),c([]),m("add")},[]),I=(0,x.useCallback)(async function(){let{addModels:s=[],removeModels:a=[]}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!w.current){if(!l?.id)return void R();w.current=!0,p(!0);try{let n=j(s),i=new Set(n),o=r.filter(e=>!i.has(e)),{success:d,message:c,data:u}=(await f.FH.post("/api/channel/upstream_updates/apply",{id:l.id,add_models:n,ignore_models:o,remove_models:j(a)},y)).data||{};if(!d)return void g.oR.error(c||t("Operation failed"));g.oR.success(t("Upstream model updates applied: {{added}} added, {{removed}} removed, {{ignored}} ignored this time, {{totalIgnored}} total ignored models",{added:u?.added_models?.length||0,removed:u?.removed_models?.length||0,ignored:j(o).length,totalIgnored:function(e){let t=null;if(e&&"object"==typeof e)t=e;else if("string"==typeof e)try{t=JSON.parse(e)}catch{t=null}return t?j(t.upstream_model_update_ignored_models||[]).length:0}(u?.settings)})),R(),await e()}catch(e){g.oR.error(e?.response?.data?.message||e?.message||t("Operation failed"))}finally{w.current=!1,p(!1)}}},[l,r,R,e,t]),M=(0,x.useCallback)(async()=>
1{if(!A.current){A.current=!0,N(!0);try{let{success:s,message:a,data:l}=(await f.FH.post("/api/channel/upstream_updates/apply_all",{},y)).data||{};if(!s)return void g.oR.error(a||t("Batch processing failed"));g.oR.success(t("Batch upstream model updates applied: {{channels}} channels, {{added}} added, {{removed}} removed, {{fails}} failed",{channels:l?.processed_channels||0,added:l?.added_models||0,removed:l?.removed_models||0,fails:(l?.failed_channel_ids||[]).length})),await e()}catch(e){g.oR.error(e?.response?.data?.message||e?.message||t("Batch processing failed"))}finally{A.current=!1,N(!1)}}},[e,t]),O=(0,x.useCallback)(async s=>{if(!k.current&&s?.id){k.current=!0;try{let{success:a,message:l,data:n}=(await f.FH.post("/api/channel/upstream_updates/detect",{id:s.id},y)).data||{};if(!a)return void g.oR.error(l||t("Detection failed"));g.oR.success(t("Detection complete: {{add}} to add, {{remove}} to remove",{add:n?.add_models?.length||0,remove:n?.remove_models?.length||0})),await e()}catch(e){g.oR.error(e?.response?.data?.message||e?.message||t("Detection failed"))}finally{k.current=!1}}},[e,t]),T=(0,x.useCallback)(async()=>{if(!C.current){C.current=!0,b(!0);try{let{success:s,message:a}=(await f.FH.post("/api/channel/upstream_updates/detect_all",{},y)).data||{};if(!s)return void g.oR.error(a||t("Batch detection failed"));g.oR.success(t("Upstream model detection task started. Track progress in System Info, then refresh to review staged updates.")),await e()}catch(e){g.oR.error(e?.response?.data?.message||e?.message||t("Batch detection failed"))}finally{C.current=!1,b(!1)}}},[e,t]);return(0,x.useMemo)(()=>({showModal:s,channel:l,addModels:r,removeModels:d,preferredTab:u,applyLoading:h,detectAllLoading:v,applyAllLoading:_,openModal:S,closeModal:R,applyUpdates:I,applyAllUpdates:M,detectChannelUpdates:O,detectAllUpdates:T}),[s,l,r,d,u,h,v,_,S,R,I,M,O,T])}((0,x.useCallback)(async()=>{await w.invalidateQueries({queryKey:K.all})},[w])),C=(0,x.useMemo)(()=>({open:s,setOpen:l,currentRow:n,setCurrentRow:r,currentTag:o,setCurrentTag:d,enableTagMode:c,setEnableTagMode:u,idSort:m,setIdSort:h,batchMode:v,setBatchMode:b,sensitiveVisible:_,setSensitiveVisible:N,upstream:k}),[s,n,o,c,m,v,_,k]);return(0,a.jsx)(td.Provider,{value:C,children:t})}function tu(){let e=(0,x.useContext)(td);if(!e)throw Error("useChannels must be used within ChannelsProvider");return e}var tm=s(64730),th=s(55724),tp=s(54622),tx=s(60641),tg=s(72868),tf=s(39649),tj=s(67834),tv=s(99893),ty=s(23921),tb=s(96855),t_=s(87159),tN=s(37116),tw=s(73280),tk=s(42817),tC=s(43284),tA=s(68974),tS=s(6242),tR=s(12393),tI=s(47497),tM=s(15161),tO=s(97785),tT=s(29625),tz=s(84935),tE=s(56275);function t$(e){if("string"!=typeof e||""===e.trim())return"-";let t=(0,tz.A)(e);return t.isValid()?(0,e6.Sz)(t.toDate()):e}function tF(e,t){let s=Number(e);if(!Number.isFinite(s)||s<=0)return"-";let a=Math.floor(s),l=Math.floor(a/3600),n=Math.floor(a%3600/60),r=a%60;return l>0?`${l}${t("h")} ${n}${t("m")}`:n>0?`${n}${t("m")} ${r}${t("s")}`:`${r}${t("s")}`}function tB(e){return null==e?"":String(e).trim().toLowerCase()}function tP(e){if("string"!=typeof e||""===e.trim())return 1/0;let t=(0,tz.A)(e);return t.isValid()?t.valueOf():1/0}function tD(e){return String(e||"").trim().toLowerCase()}function tJ(e){let t=e?.rate_limit??{},s=t?.primary_window??null,a=t?.secondary_window??null,l=[s,a].filter(Boolean),n=tB(e?.plan_type??t?.plan_type),r=null,i=null;for(let e of l){let t=function(e){let t=Number(e?.limit_window_seconds);return!Number.isFinite(t)||t<=0?null:t>=86400?"weekly":"fiveHour"}(e);if("fiveHour"===t&&!r){r=e;continue}"weekly"!==t||i||(i=e)}return"free"===n?(i||(i=s??a??null),{fiveHourWindow:null,weeklyWindow:i}):r||i?(r||(r=l.find(e=>e!==i)??null),i||(i=l.find(e=>e!==r)??null),{fiveHourWindow:r,weeklyWindow:i}):{fiveHourWindow:s,weeklyWindow:a}}let tq={enterprise:{label:"Enterprise",variant:"success"},team:{label:"Team",variant:"info"},pro:{label:"Pro",variant:"blue"},plus:{label:"Plus",variant:"purple"},free:{label:"Free",variant:"warning"}},tL={available:{label:"Available",variant:"success"},redeemed:{label:"Redeemed",variant:"neutral"},expired:{label:"Expired",variant:"warning"}};function tV(e,t){return e&&0!==Object.keys(e).length?e.allowed&&!e.limit_reached?(0,a.jsx)(tk.Wh,{label:t("Available"),variant:"success",copyable:!1}):(0,a.jsx)(tk.Wh,{label:t("Limited"),variant:"danger",copyable:!1}):(0,a.jsx)(tk.Wh,{label:t("Pending"),variant:"neutral",copyable:!1})}let tK={success:"text-success",warning:"text-warning",danger:"text-destructive",info:"text-info",neutral:"text-muted-foreground",purple:"text-chart-4",amber:"text-warning",blue:"text-chart-1",cyan:"text-chart-2",green:"text-success",grey:"text-muted-foreground",indigo:"text-chart-1","light-blue":"text-info","light-green":"text-emerald-500 dark:text-emerald-300",lime:"text-chart-3",orange:"text-warning",pink:"text-chart-5",red:"text-destructive",teal:"text-chart-2",violet:"text-chart-4",yellow:"text-warning"};function tW(e){var t;let s,l,n,r,{t:o}=(0,i.Bd)(),d=!!e.window&&"object"==typeof e.window&&Object.keys(e.window).length>0,{percent:c,variant:u}=(t=e.window,l=Number.isFinite(s=Number(t?.used_percent))?Math.max(0,Math.min(100,s)):0,n="info",l>=95?n="danger":l>=80&&(n="warning"),{percent:l,variant:n});return(0,a.jsxs)(tA.Zp,{size:"sm",className:"gap-0 py-0",children:[(0,a.jsx)(tA.aR,{className:"p-3 pb-2",children:(0,a.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)(tA.ZB,{className:"text-sm font-semibold",children:e.title}),(0,a.jsxs)(tA.BT,{className:"mt-1 text-xs",children:[o("Window:")," ",d?tF(e.window?.limit_window_seconds,o):"-"]})]}),(0,a.jsxs)("div",{className:"shrink-0 text-right",children:[(0,a.jsx)("div",{className:(0,tE.cn)("text-xl leading-none font-semibold tabular-nums",tK[u??"neutral"]),children:d?`${c}%`:"-"}),(0,a.jsx)("div",{className:"text-muted-foreground mt-1 text-[11px]",children:o("Used")})]})]})}),(0,a.jsxs)(tA.Wu,{className:"p-3 pt-0",children:[d?(0,a.jsx)(tI.ke,{value:c,"aria-label":`${e.title} usage: ${c}%`,className:"mt-1"}):(0,a.jsx)("div",{className:"text-muted-foreground mt-1 text-sm",children:"-"}),(0,a.jsxs)("div",{className:"mt-3 grid grid-cols-1 gap-2 text-xs sm:grid-cols-2",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-[11px]",children:o("Reset at:")}),(0,a.jsx)("div",{className:"break-all tabular-nums",children:d&&Number.isFinite(r=Number(e.window?.reset_at))&&r>0?(0,e6.fk)(r):"-"})]}),(0,a.jsxs)("div",{className:"min-w-0 sm:text-right",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-[11px]",children:o("Resets in:")}),(0,a.jsx)("div",{className:"tabular-nums",children:d?tF(e.window?.reset_after_seconds,o):"-"})]})]})]})]})}function tU(e){let{t}=(0,i.Bd)();return(0,a.jsxs)("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:[(0,a.jsx)(tW,{title:t("5-Hour Window"),window:e.fiveHourWindow}),(0,a.jsx)(tW,{title:t("Weekly Window"),window:e.weeklyWindow})]})}function tH(e){return(0,a.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("div",{className:"text-sm font-semibold",children:e.title}),e.description?(0,a.jsx)("div",{className:"text-muted-foreground mt-1 text-xs leading-5",children:e.description}):null]}),e.children?(0,a.jsx)("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:e.children}):null]})}function tG(e){let{t}=(0,i.Bd)(),{fiveHourWindow:s,weeklyWindow:l}=tJ(e.source),n=tV(e.source?.rate_limit,t);return(0,a.jsxs)("section",{className:"bg-muted/40 flex flex-col gap-3 rounded-xl p-3",children:[(0,a.jsx)(tH,{title:e.title,de
1scription:e.description,children:n}),e.meteredFeature?(0,a.jsxs)("div",{className:"bg-background ring-border/60 inline-flex max-w-full flex-wrap items-center gap-x-2 gap-y-1 rounded-lg px-2 py-1 text-xs ring-1",children:[(0,a.jsx)("span",{className:"text-muted-foreground text-[11px]",children:"metered_feature"}),(0,a.jsx)("span",{className:"min-w-0 font-mono break-all",children:e.meteredFeature})]}):null,(0,a.jsx)(tU,{fiveHourWindow:s,weeklyWindow:l})]})}function tY(e){let{t}=(0,i.Bd)(),{copyToClipboard:s,copiedText:l}=(0,tT.C)({notify:!1}),n=e.value?.trim()||"",r=l===n;return(0,a.jsxs)("div",{className:(0,tE.cn)("bg-background ring-border/60 min-w-0 rounded-lg p-3 ring-1",e.className),children:[(0,a.jsx)("div",{className:"text-muted-foreground text-[11px] font-medium",children:e.label}),(0,a.jsxs)("div",{className:"mt-1 flex min-w-0 items-start justify-between gap-2",children:[(0,a.jsx)("span",{className:(0,tE.cn)("min-w-0 flex-1 text-xs leading-5 break-all",e.mono&&"font-mono tabular-nums"),children:n||"-"}),!1!==e.copyable&&n?(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Copy"),onClick:()=>s(n),children:r?(0,a.jsx)(tj.A,{className:"text-success"}):(0,a.jsx)(tv.A,{})}):null]})]})}function tZ(e){return(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-[11px] font-medium",children:e.label}),(0,a.jsx)("div",{className:(0,tE.cn)("mt-1 text-xs leading-5 tabular-nums",e.emphasis?"font-semibold":"text-foreground"),children:e.value})]})}function tQ(e){var t;let{t:s}=(0,i.Bd)(),l=(t=e.credit.status,tL[tD(t)]??{label:String(t||"")||s("Unknown"),variant:"neutral"}),n=e.credit.title?.trim()||`${s("Reset Credit")} ${e.index+1}`,r=function(e,t){if("string"!=typeof e||""===e.trim())return"-";let s=(0,tz.A)(e);if(!s.isValid())return"-";let a=s.diff((0,tz.A)(),"second");if(a<=0)return t("Expired");let l=Math.floor(a/86400),n=a%86400;if(l>0){let e=Math.floor(n/3600);return`${l} ${t("days")} ${e}${t("h")}`}return tF(a,t)}(e.credit.expires_at,s),o="available"===tD(e.credit.status);return(0,a.jsxs)("div",{className:"bg-background rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsx)("div",{className:"min-w-0 text-sm font-medium break-words",children:n}),(0,a.jsx)(tk.Wh,{label:s(l.label),variant:l.variant,copyable:!1})]}),e.credit.description?(0,a.jsx)("div",{className:"text-muted-foreground mt-1 text-xs leading-5",children:e.credit.description}):null,e.credit.id?(0,a.jsx)("div",{className:"text-muted-foreground mt-1 font-mono text-[11px] break-all",children:e.credit.id}):null]}),(0,a.jsxs)("div",{className:"shrink-0 text-right",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-[11px] font-medium",children:s("Expires in")}),(0,a.jsx)("div",{className:(0,tE.cn)("mt-1 text-sm font-semibold tabular-nums",o?"text-success":"text-muted-foreground"),children:r})]})]}),(0,a.jsxs)("div",{className:"mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3",children:[(0,a.jsx)(tZ,{label:s("Granted at"),value:t$(e.credit.granted_at)}),(0,a.jsx)(tZ,{label:s("Expires at"),value:t$(e.credit.expires_at)}),(0,a.jsx)(tZ,{label:s("Redeemed at"),value:t$(e.credit.redeemed_at),emphasis:!!e.credit.redeemed_at})]})]})}function tX(e){let t,{t:s}=(0,i.Bd)(),l=(0,x.useMemo)(()=>[...e.payload?.credits??[]].sort((e,t)=>{let s="available"===tD(e.status);if(s!==("available"===tD(t.status)))return s?-1:1;let a=tP(e.expires_at)-tP(t.expires_at);if(0!==a)return a;let l=tP(e.granted_at)-tP(t.granted_at);return 0!==l?l:String(e.id||"").localeCompare(String(t.id||""))}),[e.payload?.credits]),n=e.payload?.available_count,r=Number.isFinite(Number(n))?String(n):e.usageAvailableCount,o=Number.isFinite(Number(e.payload?.total_earned_count))?String(e.payload?.total_earned_count):"-",d=Number(r)>0;return t=e.errorMessage?(0,a.jsx)("div",{className:"border-destructive/40 bg-destructive/10 text-destructive rounded-lg border px-3 py-2 text-sm",children:e.errorMessage}):e.isLoading?(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(tO.E,{className:"h-24 w-full"}),(0,a.jsx)(tO.E,{className:"h-24 w-full"})]}):l.length>0?(0,a.jsx)("div",{className:"flex flex-col gap-2",children:l.map((e,t)=>(0,a.jsx)(tQ,{credit:e,index:t},e.id??e.expires_at??e.granted_at??e.title??e.reset_type??""))}):(0,a.jsx)(tR.Sv,{className:"min-h-32 border",children:(0,a.jsxs)(tR.FT,{children:[(0,a.jsx)(tR.cz,{children:s("No reset credits")}),(0,a.jsx)(tR.Ou,{children:s("Upstream did not return reset credit details.")})]})}),(0,a.jsxs)("div",{className:"flex flex-col gap-3 p-3",children:[(0,a.jsxs)("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[(0,a.jsx)(tY,{label:s("Available reset credits"),value:r,mono:!0,copyable:!1}),(0,a.jsx)(tY,{label:s("Total earned"),value:o,mono:!0,copyable:!1}),(0,a.jsx)(tY,{label:"HTTP",value:String(e.response?.upstream_status??"-"),mono:!0,copyable:!1})]}),(0,a.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-xs leading-5",children:s("Available credits are ordered by soonest expiration.")}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:e.onRefresh,disabled:e.isLoading,children:[(0,a.jsx)(tp.A,{"data-icon":"inl
1ine-start"}),s("Refresh details")]})]}),(0,a.jsxs)("div",{className:"bg-muted/30 flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("div",{className:"text-sm font-semibold",children:s("Reset usage window")}),(0,a.jsx)("div",{className:"text-muted-foreground mt-1 text-xs leading-5",children:s("Use one available reset credit to refresh the current Codex usage windows.")})]}),(0,a.jsxs)(tg.$,{type:"button",variant:d?"destructive":"outline",size:"sm",onClick:e.onRequestReset,disabled:!d||e.isLoading||e.isResetting,className:"shrink-0",children:[(0,a.jsx)(ty.A,{"data-icon":"inline-start"}),s(e.isResetting?"Resetting...":"Apply reset")]})]}),d?null:(0,a.jsxs)(tC.Fc,{children:[(0,a.jsx)(tb.A,{}),(0,a.jsx)(tC.XL,{children:s("No reset credits available")}),(0,a.jsx)(tC.TN,{children:s("The reset request stays disabled until a credit is available.")})]}),e.resetSuccessMessage?(0,a.jsxs)(tC.Fc,{className:"border-success/40 bg-success/10 text-success",children:[(0,a.jsx)(tj.A,{}),(0,a.jsx)(tC.XL,{children:s("Reset completed")}),(0,a.jsx)(tC.TN,{children:e.resetSuccessMessage})]}):null,e.resetErrorMessage?(0,a.jsxs)(tC.Fc,{variant:"destructive",children:[(0,a.jsx)(tb.A,{}),(0,a.jsx)(tC.XL,{children:s("Reset failed")}),(0,a.jsx)(tC.TN,{children:e.resetErrorMessage})]}):null,t]})}function t0(e){var t,s;let{open:l,onOpenChange:n,channelName:r,channelId:o,channelDisplayName:d,channelDisplayId:c,response:u,onRefresh:m,isRefreshing:p}=e,{t:g}=(0,i.Bd)(),{copiedText:f,copyToClipboard:j}=(0,tT.C)({notify:!1}),[v,y]=(0,x.useState)(!1),[b,_]=(0,x.useState)(!1),[N,w]=(0,x.useState)(null),[k,C]=(0,x.useState)(!1),[A,S]=(0,x.useState)(""),[R,I]=(0,x.useState)(!1),[M,O]=(0,x.useState)(!1),[T,z]=(0,x.useState)(""),[E,$]=(0,x.useState)(""),F=(0,x.useMemo)(()=>{let e=u?.data;return e&&"object"==typeof e?e:null},[u?.data]),B=(0,x.useMemo)(()=>{let e=N?.data;return e&&"object"==typeof e?e:null},[N?.data]),P=F?.rate_limit,D=(t=F?.plan_type??P?.plan_type,tq[tB(t)]??{label:String(t||"")||g("Unknown"),variant:"neutral"}),J=(F?.additional_rate_limits??[]).filter(e=>e&&Object.keys(e).length>0),q=B?.available_count??F?.rate_limit_reset_credits?.available_count,L=Number.isFinite(Number(q))?String(q):"-",V=Number(q)>0,K="";null!=c?K=` (#${c})`:o&&(K=` (#${o})`);let W=`${d??r??"-"}${K}`,{fiveHourWindow:U,weeklyWindow:H}=tJ(F),G=u?.success===!1?u?.message?.trim()||g("Failed to fetch usage"):"",Y=(0,x.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!o)return void S(g("Channel ID is required"));if(!k&&(e||!N)){C(!0),S("");try{let e=await (0,h.Dh)(o);if(!e.success)throw Error(e.message||g("Failed to fetch reset credit details"));w(e)}catch(e){S(e instanceof Error?e.message:g("Failed to fetch reset credit details"))}finally{C(!1)}}},[o,k,N,g]),Z=e=>{e||(y(!1),_(!1),w(null),S(""),C(!1),I(!1),O(!1),z(""),$("")),n(e)},Q=async()=>{if(o&&!M&&V){O(!0),z(""),$("");try{let e=await (0,h.AK)(o);if(!e.success)throw Error(e.message||g("Failed to reset usage"));let t=e.data,s=Number(t?.windows_reset);$(Number.isFinite(s)?`${g("Reset completed. Latest usage has been refreshed.")} ${g("Affected windows:")} ${s}`:g("Reset completed. Latest usage has been refreshed.")),I(!1),await Promise.resolve(m?.()),await Y(!0)}catch(e){z(e instanceof Error?e.message:g("Failed to reset usage"))}finally{O(!1)}}},X=(0,x.useMemo)(()=>{if(!u)return"";try{return JSON.stringify({success:u.success,message:u.message,upstream_status:u.upstream_status,data:u.data},null,2)}catch{return String(u?.data??"")}},[u]);return(0,a.jsxs)(tx.l,{open:l,onOpenChange:Z,title:g("Codex Account & Usage"),contentClassName:"sm:max-w-[900px]",titleClassName:"flex items-center gap-2",contentHeight:"auto",bodyClassName:"flex flex-col gap-4",footer:(0,a.jsx)(tg.$,{type:"button",variant:"outline",onClick:()=>Z(!1),children:g("Close")}),children:[(0,a.jsxs)("div",{className:"flex flex-col gap-4",children:[G&&(0,a.jsx)("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-800 dark:bg-red-950/30 dark:text-red-400",children:G}),(0,a.jsxs)(tA.Zp,{size:"sm",className:"bg-muted/30 gap-0 py-0",children:[(0,a.jsxs)(tA.aR,{className:"p-4 pb-2",children:[(0,a.jsx)(tA.ZB,{className:"text-muted-foreground text-xs font-medium",children:g("Codex Account Status")}),m?(0,a.jsx)(tA.X9,{children:(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:m,disabled:!!p,children:[(0,a.jsx)(tp.A,{"data-icon":"inl
1ine-start"}),g("Refresh")]})}):null]}),(0,a.jsxs)(tA.Wu,{className:"p-4 pt-0",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsx)(tk.Wh,{label:D.label,variant:D.variant,copyable:!1}),tV(P,g),(0,a.jsx)(tk.Wh,{label:`HTTP ${u?.upstream_status??"-"}`,variant:"neutral",copyable:!1}),(0,a.jsx)(tk.Wh,{label:(s=g("Reset count:"),s.endsWith(":")?`${s}${L}`:`${s} ${L}`),variant:Number(q)>0?"blue":"neutral",copyable:!1}),F?.credits?.overage_limit_reached?(0,a.jsx)(tk.Wh,{label:g("Overage limited"),variant:"danger",copyable:!1}):null,F?.spend_control?.reached?(0,a.jsx)(tk.Wh,{label:g("Spend limited"),variant:"danger",copyable:!1}):null]}),(0,a.jsxs)("div",{className:"mt-4 grid grid-cols-1 gap-3 md:grid-cols-2",children:[(0,a.jsx)(tY,{label:g("Email"),value:F?.email,copyable:!0}),(0,a.jsx)(tY,{label:g("Channel"),value:W,copyable:!1}),(0,a.jsx)(tY,{label:"User ID",value:F?.user_id,mono:!0,className:"md:col-span-2"})]})]})]}),(0,a.jsxs)(tS.Nt,{open:b,onOpenChange:e=>{_(e),e&&Y(!1)},className:"rounded-lg border",children:[(0,a.jsxs)(tS.R6,{render:(0,a.jsx)("button",{type:"button",className:"hover:bg-muted/40 flex w-full items-start justify-between gap-3 p-3 text-left transition-colors","aria-expanded":b}),children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsx)("div",{className:"text-sm font-semibold",children:g("Reset Credits")}),(0,a.jsx)(tk.Wh,{label:`${g("Available")} ${L}`,variant:Number(q)>0?"blue":"neutral",copyable:!1})]}),(0,a.jsx)("div",{className:"text-muted-foreground mt-1 text-xs leading-5",children:g("View issued reset credits, grant dates, and expiration.")})]}),b?(0,a.jsx)(t_.A,{className:"text-muted-foreground mt-0.5 shrink-0"}):(0,a.jsx)(tN.A,{className:"text-muted-foreground mt-0.5 shrink-0"})]}),(0,a.jsx)(tS.Ke,{className:"border-t",children:(0,a.jsx)(tX,{payload:B,response:N,usageAvailableCount:L,isLoading:k,isResetting:M,errorMessage:A,resetErrorMessage:T,resetSuccessMessage:E,onRefresh:()=>void Y(!0),onRequestReset:()=>{z(""),$(""),I(!0)}})})]}),(0,a.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,a.jsx)(tH,{title:g("Base Limits"),description:g("Base rate limit windows for this account."),children:tV(P,g)}),(0,a.jsx)(tU,{fiveHourWindow:U,weeklyWindow:H})]}),J.length>0?(0,a.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,a.jsx)(tH,{title:g("Additional Limits"),description:g("Per-feature metered windows split by model or capability.")}),(0,a.jsx)("div",{className:"flex flex-col gap-3",children:J.map(e=>{let t=e.limit_name||e.metered_feature||g("Additional Limit");return(0,a.jsx)(tG,{title:t,description:g("Additional metered capability"),source:e,meteredFeature:e.metered_feature},`${t}-${e.metered_feature??""}-${e.plan_type??""}`)})})]}):null,(0,a.jsxs)(tS.Nt,{open:v,onOpenChange:y,className:"rounded-lg border",children:[(0,a.jsxs)(tS.R6,{render:(0,a.jsx)("button",{type:"button",className:"hover:bg-muted/40 flex w-full items-center justify-between gap-2 p-3 transition-colors","aria-expanded":v}),children:[(0,a.jsx)("div",{className:"text-sm font-medium",children:g("Raw JSON")}),v?(0,a.jsx)(t_.A,{className:"text-muted-foreground h-4 w-4"}):(0,a.jsx)(tN.A,{className:"text-muted-foreground h-4 w-4"})]}),(0,a.jsx)(tS.Ke,{children:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"flex justify-end border-t px-3 py-2",children:(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>j(X),disabled:!X,children:[f===X?(0,a.jsx)(tj.A,{"data-icon":"inline-start",className:"text-success"}):(0,a.jsx)(tv.A,{"data-icon":"inline-start"}),g("Copy")]})}),(0,a.jsx)(tM.F,{className:"max-h-[50vh]",children:(0,a.jsx)("pre",{className:"bg-muted/30 m-0 p-3 text-xs break-words whitespace-pre-wrap",children:X||"-"})})]})})]})]}),(0,a.jsx)(tw.T,{open:R,onOpenChange:I,title:g("Confirm usage reset"),desc:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)("p",{children:g("Use one available reset credit for this channel. The reset request is sent only after confirmation.")}),(0,a.jsxs)("div",{className:"bg-muted/50 rounded-lg border px-3 py-2 text-xs",children:[(0,a.jsx)("div",{className:"font-medium",children:W}),(0,a.jsxs)("div",{className:"text-muted-foreground mt-1",children:[g("Available reset credits"),": ",L]})]}),(0,a.jsx)("p",{className:"text-destructive",children:g("Used reset credits cannot be restored.")})]}),destructive:!0,disabled:!V,isLoading:M,cancelBtnText:g("Cancel"),confirmText:M?g("Resetting..."):g("Apply reset"),handleConfirm:Q})]})}function t1(e){var t;let s,{open:l,onOpenChange:n}=e,{t:r}=(0,i.Bd)(),{currentRow:o,setCurrentRow:d}=tu(),c=(0,p.jE)(),[u,m]=(0,x.useState)(!1),[f,j]=(0,x.useState)(null),[v,y]=(0,x.useState)(null),[b,N]=(0,x.useState)(null),w=o?.type===57,k=async()=>
1{if(o){m(!0);try{let e=await (0,h.Tl)(o.id);if(!e.success)throw Error(e.message||r("Failed to fetch usage"));N(e)}catch(e){g.oR.error(e instanceof Error?e.message:r("Failed to fetch usage"))}finally{m(!1)}}};if((0,x.useEffect)(()=>{!w||l&&k()},[l,w]),!o)return null;let C=async()=>{m(!0);try{let e=await (0,h.$3)(o.id);if(e.success&&void 0!==e.balance){let t=e.balance,s=Math.floor(Date.now()/1e3);j(t),y(s),g.oR.success(r("Balance updated successfully")),d({...o,balance:t,balance_updated_time:s}),await c.invalidateQueries({queryKey:K.lists()})}else g.oR.error(e.message||r("Failed to query balance"))}catch(e){g.oR.error(e instanceof Error?e.message:r("Failed to query balance"))}finally{m(!1)}},A=()=>{j(null),y(null),N(null),n(!1)};if(w)return(0,a.jsx)(t0,{open:l,onOpenChange:e=>{e||A()},channelName:o.name,channelId:o.id,response:b,onRefresh:k,isRefreshing:u});return(0,a.jsx)(tx.l,{open:l,onOpenChange:A,title:r("Query Balance"),description:(0,a.jsxs)(a.Fragment,{children:[r("Update balance for:"),(0,a.jsx)("strong",{children:o.name})]}),contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsx)(tg.$,{variant:"outline",onClick:A,disabled:u,children:r("Close")}),children:(0,a.jsxs)("div",{className:"space-y-4 py-4",children:[(0,a.jsxs)("div",{className:"bg-muted/50 rounded-lg border p-4",children:[(0,a.jsxs)("div",{className:"text-muted-foreground mb-2 flex items-center gap-2 text-sm",children:[(0,a.jsx)(tf.f,{tone:"success",size:"xs",children:(0,a.jsx)(tm.A,{})}),(0,a.jsx)("span",{children:r("Current Balance")})]}),(0,a.jsx)("div",{className:"text-2xl font-bold",children:(s=null!==f?f:o.balance,(0,_.J5)(s,{digitsLarge:2,digitsSmall:4,abbreviate:!1}))}),(0,a.jsxs)("div",{className:"text-muted-foreground mt-2 text-xs",children:[r("Last updated:")," ",(t=v??o.balance_updated_time)?(0,e6.fk)(t):"Never"]})]}),(0,a.jsxs)(tg.$,{className:"w-full",onClick:C,disabled:u,children:[u&&(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}),!u&&(0,a.jsx)(tp.A,{className:"mr-2 h-4 w-4"}),u?r("Querying..."):r("Update Balance")]})]})})}var t2=s(98307),t4=s(85949),t5=s(14653),t3=s(26197),t6=s(86094),t8=s(55045),t7=s(47029),t9=s(82655),se=s(1738),st=s(11728),ss=s(88288),sa=s(74559),sl=s(87212),sn=s(38009);function sr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();if("number"==typeof e&&Number.isFinite(e))return{responseTime:e,testTime:Math.floor(t/1e3)}}let si=[{value:"auto",label:"Auto detect (default)"},{value:"openai",label:"OpenAI (/v1/chat/completions)"},{value:"openai-response",label:"OpenAI Responses (/v1/responses)"},{value:"openai-response-compact",label:"OpenAI Response Compaction (/v1/responses/compact)"},{value:"anthropic",label:"Anthropic (/v1/messages)"},{value:"gemini",label:"Gemini (/v1beta/models/{model}:generateContent)"},{value:"jina-rerank",label:"Jina Rerank (/v1/rerank)"},{value:"image-generation",label:"Image Generation (/v1/images/generations)"},{value:"embeddings",label:"Embeddings (/v1/embeddings)"}],so=new Set(["embeddings","image-generation","jina-rerank","openai-response-compact"]);function sd(e){return e.replaceAll(/\s+/g," ").trim()}function sc(e){let{open:t,onOpenChange:s}=e,{currentRow:l}=tu();return l?(0,a.jsx)(su,{open:t,onOpenChange:s,currentRow:l},l.id):null}function su(e){let{open:t,onOpenChange:s,currentRow:l}=e,{t:n}=(0,i.Bd)(),r=(0,p.jE)(),o=l.id,d=(0,x.useRef)(!1),u=(0,x.useRef)(null),[m,f]=(0,x.useState)("auto"),[j,v]=(0,x.useState)(!1),[y,b]=(0,x.useState)(""),[_,N]=(0,x.useState)({}),[w,k]=(0,x.useState)({}),[C,A]=(0,x.useState)(()=>new Set),[S,R]=(0,x.useState)(!1),[I,M]=(0,x.useState)(!1),[O,T]=(0,x.useState)(null),[z,E]=(0,x.useState)(()=>new Set),[$,F]=(0,x.useState)(!1),[B,P]=(0,x.useState)(!1),[D,J]=(0,x.useState)(null),[q,L]=(0,x.useState)({pageIndex:0,pageSize:30}),V=(0,x.useMemo)(()=>si.map(e=>({value:e.value,label:n(e.label)})),[n]),W=(0,x.useCallback)(()=>{null!==u.current&&(g.oR.dismiss(u.current),u.current=null)},[]);(0,x.useEffect)(()=>{if(!O)return void W();let e=I?n("Stopping batch test..."):n("Batch testing models..."),t=n("{{completed}}/{{total}} completed",{completed:O.completed,total:O.total}),s=n("{{success}} succeeded, {{failed}} failed",{success:O.success,failed:O.failed});u.current=g.oR.loading(e,{id:u.current??void 0,description:`${t} \xb7 ${s}`})},[O,W,I,n]),(0,x.useEffect)(()=>W,[W]);let U=(0,x.useCallback)(()=>{d.current=!0,f("auto"),v(!1),b(""),N({}),k({}),A(()=>new Set),R(!1),M(!1),T(null),E(()=>new Set),F(!1),P(!1),J(null),L({pageIndex:0,pageSize:30})},[]),H=so.has(m),G=!H&&j,Y=(0,x.useCallback)(e=>{null!==e&&(f(e),so.has(e)&&v(!1))},[]),Z=(0,x.useCallback)(e=>{b(e.target.value),L(e=>0===e.pageIndex?e:{...e,pageIndex:0})},[]),Q=l.models,ee=l.test_model?.trim(),et=(0,x.useMemo)(()=>Q?Q.split(",").map(e=>
1e.trim()).filter(Boolean):[],[Q]),es=(0,x.useMemo)(()=>et.filter(e=>!z.has(e)),[et,z]),ea=(0,x.useMemo)(()=>es.filter(e=>_[e]?.status==="success"),[es,_]),el=(0,x.useMemo)(()=>es.filter(e=>_[e]?.status==="error"),[es,_]),en=(0,x.useMemo)(()=>{if(!y)return es;let e=y.toLowerCase();return es.filter(t=>t.toLowerCase().includes(e))},[es,y]),er=(0,x.useMemo)(()=>en.map(e=>({model:e})),[en]),ei=(0,x.useCallback)((e,t)=>{A(s=>{let a=new Set(s);return t?a.add(e):a.delete(e),a})},[]),eo=(0,x.useCallback)((e,t)=>{J(t=>t?.model===e?null:t),N(s=>({...s,[e]:t}))},[]),ed=(0,x.useCallback)(e=>{e&&r.setQueriesData({queryKey:K.lists()},t=>{let s=t?.data;if(!t||!s?.items.length)return t;let a=!1,l=s.items.map(t=>t.id!==o?t:(a=!0,{...t,response_time:e.responseTime,test_time:e.testTime}));return a?{...t,data:{...s,items:l}}:t})},[o,r]),ec=(0,x.useCallback)(e=>{ed(e),r.invalidateQueries({queryKey:K.lists()}).then(()=>ed(e)).catch(()=>void 0)},[r,ed]),eu=(0,x.useCallback)(async function(e){let t,s=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(l){ei(e,!0),eo(e,{status:"testing"});try{await X(l.id,{channelName:l.name,testModel:e,endpointType:"auto"===m?void 0:m,stream:G||void 0,silent:s},(s,a,l,n)=>{let r=Date.now();t={status:s?"success":"error",responseTime:a,completedAt:r,error:l,errorCode:n},eo(e,t)})}catch(s){eo(e,t={status:"error",completedAt:Date.now(),error:s instanceof Error?s.message:n("Test failed")})}finally{ei(e,!1),a&&ec(sr(t?.responseTime,t?.completedAt))}return t}},[l,m,G,ei,ec,n,eo]),em=(0,x.useCallback)(()=>{S&&!I&&(d.current=!0,M(!0))},[I,S]),eh=(0,x.useCallback)(async e=>{let t,s=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(!s.length)return;d.current=!1,R(!0),M(!1),T({total:s.length,completed:0,success:0,failed:0});let a=[],l=0,r=0,i=0;try{let e,o=e=>({status:"error",completedAt:Date.now(),error:e instanceof Error?e.message:n("Test failed")}),c=e=>{a.push(e),l+=1,"success"===e.status&&(r+=1),i=l-r,T({total:s.length,completed:l,success:r,failed:i})};for(let e=0;e<s.length&&!d.current;e+=5){let t=s.slice(e,e+5).map(async e=>{try{let t=await eu(e,!0,!1),s=t??o();return t||eo(e,s),c(s),s}catch(s){let t=o(s);return eo(e,t),c(t),t}});if(await Promise.allSettled(t),d.current||e+5>=s.length)break;await new Promise(e=>window.setTimeout(e,100))}e=a.reduce((e,t)=>{let s=t.completedAt??0,a=sr(t.responseTime,s);return a&&(!e||s>=e.completedAt)?{patch:a,completedAt:s}:e},void 0),t=e?.patch;let u=d.current&&l<s.length;W(),u?g.oR.info(n("Batch test stopped: {{completed}}/{{total}} completed, {{success}} succeeded, {{failed}} failed",{completed:l,total:s.length,success:r,failed:i})):i>0?g.oR.error(n("Batch test completed: {{success}} succeeded, {{failed}} failed",{success:r,failed:i})):g.oR.success(n("Batch test completed: {{count}} succeeded",{count:r}))}finally{d.current=!1,R(!1),M(!1),T(null),k({}),ec(t)}},[W,ec,n,eu,eo]),ep=(0,x.useCallback)(()=>{k(()=>{let e={};for(let t of ea)e[t]=!0;return e})},[ea]),ex=(0,x.useCallback)(async()=>{let e=es.filter(e=>_[e]?.status==="error");
1if(!e.length)return void F(!1);let t=new Set(e),s=es.filter(e=>!t.has(e));P(!0);try{let t=await (0,h.fy)(l.id,{models:s.join(",")});t.success?(E(t=>{let s=new Set(t);for(let t of e)s.add(t);return s}),N(t=>{let s={...t};for(let t of e)delete s[t];return s}),k(t=>{let s={...t};for(let t of e)delete s[t];return s}),g.oR.success(n("Deleted {{count}} failed models",{count:e.length})),ec(),F(!1)):g.oR.error(t.message||n("Failed to delete failed models"))}catch(e){g.oR.error(e instanceof Error?e.message:n("Failed to delete failed models"))}finally{P(!1)}},[l.id,es,ec,n,_]),eg=(0,x.useCallback)(()=>{U(),s(!1)},[s,U]),ef=(0,x.useCallback)(e=>{e||eg()},[eg]),ej=C.size>0||S,ev=y.trim().length>0?n("Test {{count}} matching models",{count:en.length}):n("Test all {{count}} models",{count:en.length}),ey=(0,x.useMemo)(()=>[{id:"select",header:e=>{let{table:t}=e;return(0,a.jsx)(t9.S,{checked:t.getIsAllRowsSelected(),indeterminate:t.getIsSomeRowsSelected()&&!t.getIsAllRowsSelected(),onCheckedChange:e=>t.toggleAllRowsSelected(!!e),"aria-label":n("Select all models")})},cell:e=>{let{row:t}=e;return(0,a.jsx)(t9.S,{checked:t.getIsSelected(),onCheckedChange:e=>t.toggleSelected(!!e),"aria-label":n("Select model {{model}}",{model:t.original.model})})},enableSorting:!1,enableHiding:!1,size:40},{accessorKey:"model",header:n("Model"),cell:e=>{let{row:t}=e,s=t.original.model,l=ee===s;return(0,a.jsxs)("div",{className:"flex w-max items-center gap-2 whitespace-nowrap",children:[(0,a.jsx)("span",{className:"font-medium whitespace-nowrap",title:s,children:s}),l&&(0,a.jsx)(tk.Wh,{label:n("Default"),variant:"info",size:"sm",copyable:!1})]})}},{id:"status",header:n("Status"),cell:e=>{let{row:t}=e,s=_[t.original.model];return(0,a.jsx)(sm,{result:s})},enableSorting:!1,size:112},{id:"result",header:n("Result"),cell:e=>{let{row:t}=e,s=t.original.model,l=_[s];return(0,a.jsx)(sh,{result:l,model:s,onOpenDetails:J})},enableSorting:!1,size:320},{id:"actions",header:n("Actions"),cell:e=>{let{row:t}=e,s=t.original.model,l=C.has(s);return(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"ghost",size:"icon-sm",onClick:()=>eu(s),disabled:l||S,"aria-label":n("Test Connection")}),children:l?(0,a.jsx)(th.A,{className:"size-4 animate-spin"}):(0,a.jsx)(t2.A,{className:"size-4"})}),(0,a.jsx)(c.ZI,{children:n("Test Connection")})]})},enableSorting:!1}],[ee,S,n,_,C,eu]),{table:eb}=(0,t8.uI)({data:er,columns:ey,rowSelection:w,pagination:q,enableRowSelection:!0,getRowId:e=>e.model,onRowSelectionChange:k,onPaginationChange:L,withFilteredRowModel:!1,withSortedRowModel:!1,withFacetedRowModel:!1});return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tx.l,{open:t,onOpenChange:ef,title:(0,a.jsxs)("span",{className:"inline-flex max-w-full min-w-0 items-center gap-1.5",children:[(0,a.jsxs)("span",{className:"shrink-0",children:[n("Test Channel Connection"),":"]}),(0,a.jsx)("span",{className:"min-w-0 truncate",children:l.name})]}),contentClassName:"max-h-[90vh] overflow-hidden sm:max-w-4xl",contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsx)(tg.$,{variant:"outline",onClick:eg,children:n("Close")}),children:(0,a.jsxs)("div",{className:"max-h-[78vh] space-y-4 overflow-y-auto py-4 pr-1",children:[(0,a.jsxs)("div",{className:"grid gap-4 md:grid-cols-2",children:[(0,a.jsxs)("div",{className:"grid gap-2",children:[(0,a.jsx)(st.J,{htmlFor:"endpoint-type",children:n("Endpoint Type")}),(0,a.jsxs)(ss.l6,{items:V,value:m,onValueChange:Y,children:[(0,a.jsx)(ss.bq,{id:"endpoint-type",className:"w-full min-w-0",children:(0,a.jsx)(ss.yv,{className:"min-w-0 truncate",placeholder:n("Auto detect (default)")})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,className:"w-[460px] max-w-[calc(100vw-2rem)]",children:(0,a.jsx)(ss.s3,{children:V.map(e=>(0,a.jsx)(ss.eb,{value:e.value,className:"items-start py-2 [&_[data-slot=select-item-text]]:min-w-0 [&_[data-slot=select-item-text]]:shrink [&_[data-slot=select-item-text]]:whitespace-normal",children:(0,a.jsx)("span",{className:"min-w-0 leading-snug break-words whitespace-normal",children:e.label})},e.value))})})]}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:n("Override the endpoint used for testing. Leave empty to auto detect.")})]}),(0,a.jsxs)("div",{className:"grid gap-2",children:[(0,a.jsx)(st.J,{htmlFor:"stream-toggle",children:n("Stream Mode")}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(sl.d,{id:"stream-toggle",checked:G,onCheckedChange:v,disabled:H}),(0,a.jsx)("span",{className:"text-sm",children:G?n("Enabled"):n("Disabled")})]}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:n("Enable streaming mode for the test request.")})]})]}),(0,a.jsxs)("div",{className:'space-y-3 max-sm:has-[div[role="toolbar"]]:pb-16',children:[(0,a.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,a.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,a.jsx)("p",{className:"text-sm font-medium",children:n("Channel models")}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:n("Select models to run batch tests.")}),(0,a.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:S?(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:em,disabled:I,children:I?n("Stopping..."):n("Stop testing")}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{size:"sm",onClick:()=>eh(en),disabled:ej||0===en.length,children:ev}),ea.length>0&&(0,a.jsxs)(tg.$,{variant:"outline",size:"sm",onClick:ep,children:[(0,a.jsx)(t4.A,{"data-icon":"inl
1ine-start"}),n("Select successful models ({{count}})",{count:ea.length})]}),el.length>0&&(0,a.jsxs)(tg.$,{variant:"outline",size:"sm",onClick:()=>F(!0),children:[(0,a.jsx)(t5.A,{"data-icon":"inline-start"}),n("Delete failed models ({{count}})",{count:el.length})]})]})})]}),(0,a.jsx)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:(0,a.jsx)(se.p,{placeholder:n("Filter models..."),value:y,onChange:Z,className:"sm:w-64"})})]}),(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsx)(t8.Oz,{table:eb,containerClassName:"rounded-md",containerProps:{role:"region","aria-label":n("Channel models")},tableContainerClassName:"max-h-90 overflow-auto **:data-[slot=table-container]:overflow-visible",tableClassName:"w-max min-w-full table-auto",pinnedColumns:[{columnId:"actions",side:"right",cellClassName:"bg-popover"}],colgroup:(0,a.jsxs)("colgroup",{children:[(0,a.jsx)("col",{className:"w-10 min-w-10"}),(0,a.jsx)("col",{className:"w-auto"}),(0,a.jsx)("col",{className:"w-28"}),(0,a.jsx)("col",{className:"w-80"}),(0,a.jsx)("col",{className:"w-px"})]}),getColumnClassName:e=>(function(e){switch(e){case"select":return"w-10 min-w-10";case"model":return"w-auto min-w-48 whitespace-nowrap";case"status":return"w-28 min-w-28 whitespace-nowrap";case"result":return"w-80 min-w-80 max-w-80 whitespace-normal";case"actions":return"bg-popover w-px whitespace-nowrap";default:return}})(e),emptyContent:es.length?n("No models matched your search."):n("This channel has no configured models."),emptyCellClassName:"text-muted-foreground h-16 text-center text-sm"}),(0,a.jsx)(t8.Tw,{table:eb})]}),(0,a.jsx)(sg,{table:eb})]})]})}),(0,a.jsx)(tw.T,{open:$,onOpenChange:F,title:n("Delete failed models"),desc:n("This removes {{count}} failed models from this channel. This action cannot be undone.",{count:el.length}),destructive:!0,isLoading:B,confirmText:n("Delete"),handleConfirm:ex}),(0,a.jsx)(sx,{details:D,onOpenChange:e=>{e||J(null)}})]})}function sm(e){let{result:t}=e,{t:s}=(0,i.Bd)();return t&&"idle"!==t.status?"testing"===t.status?(0,a.jsxs)(tk.Wh,{variant:"info",copyable:!1,children:[(0,a.jsx)(th.A,{className:"size-3.5 shrink-0 animate-spin"}),(0,a.jsx)("span",{className:"min-w-0 truncate leading-normal",children:s("Testing...")})]}):"success"===t.status?(0,a.jsx)(tk.Wh,{label:s("Success"),variant:"success",copyable:!1}):(0,a.jsx)(tk.Wh,{label:s("Failed"),variant:"danger",copyable:!1}):(0,a.jsx)(tk.Wh,{label:s("Not tested"),variant:"neutral",copyable:!1})}function sh(e){let{result:t,model:s,onOpenDetails:l}=e,{t:n}=(0,i.Bd)();return t&&"idle"!==t.status?"testing"===t.status?(0,a.jsxs)("div",{className:"text-muted-foreground flex min-w-0 items-center gap-2 text-sm",children:[(0,a.jsx)(th.A,{className:"size-4 shrink-0 animate-spin"}),(0,a.jsx)("span",{className:"truncate",children:n("Testing...")})]}):"success"===t.status?"number"==typeof t.responseTime?(0,a.jsx)("span",{className:"text-muted-foreground text-sm",children:tt(t.responseTime,n)}):(0,a.jsx)("span",{className:"text-muted-foreground text-sm",children:"-"}):(0,a.jsx)(sp,{result:t,model:s,onOpenDetails:l}):(0,a.jsx)("span",{className:"text-muted-foreground text-sm",children:"-"})}function sp(e){let{result:t,model:s,onOpenDetails:l}=e,{t:n}=(0,i.Bd)(),r=t.error?.trim(),o="model_price_error"===t.errorCode,d=n("Model price is not configured. Please complete model pricing in settings."),{summary:c,details:u}=function(e){var t;let{errorText:s,fallbackSummary:a,isModelPriceError:l,modelPriceSummary:n}=e,r=s?.trim();if(!r)return{summary:a};if(l)return{summary:n,details:r===n?void 0:r};let i=(t=sd(r.split(/\r?\n/).map(e=>e.trim()).find(Boolean)??r)).length<=96?t:`${t.slice(0,96).trimEnd()}...`;return{summary:i,details:i===sd(r)?void 0:r}}({errorText:r,fallbackSummary:n("Test failed"),isModelPriceError:o,modelPriceSummary:d});return(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs whitespace-normal",children:[(0,a.jsx)("p",{className:"text-muted-foreground line-clamp-2 min-w-0 flex-1 leading-snug wrap-break-word",children:c}),(0,a.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-1.5",children:[o&&(0,a.jsxs)(tg.$,{variant:"outline",size:"sm",className:"h-7 w-fit px-2 text-xs",onClick:()=>window.open("/system-settings/billing/model-pricing","_blank"),children:[(0,a.jsx)(t3.A,{className:"mr-1 h-3 w-3 shrink-0"}),n("Go to Settings")]}),u&&(0,a.jsxs)(tg.$,{variant:"ghost",size:"sm",className:"h-7 w-fit px-2 text-xs","aria-haspopup":"dialog",onClick:()=>l({model:s,summary:c,details:u}),children:[(0,a.jsx)(t6.A,{className:"mr-1 h-3 w-3 shrink-0"}),n("Details")]})]})]})}function sx(e){let{details:t,onOpenChange:s}=e,{t:l}=(0,i.Bd)(),n=(0,sn.a)(),{copiedText:r,copyToClipboard:o}=(0,tT.C)({notify:!1});return(0,a.jsx)(sa.cj,{open:!!t,onOpenChange:s,children:(0,a.jsx)(sa.h,{side:n?"bottom":"right",className:n?(0,t7.jW)("h-auto max-h-[85dvh] rounded-t-xl"):(0,t7.jW)("sm:max-w-lg"),children:t&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(sa.Fm,{className:(0,t7.Dt)("sm:px-5"),children:[(0,a.jsx)(sa.qp,{className:"pr-10",children:l("Details")}),(0,a.jsx)(sa.Qs,{className:"pr-10 wrap-break-word",children:t.model})]}),(0,a.jsxs)("div",{className:(0,t7.e)("gap-4 sm:px-5"),children:[(0,a.jsxs)("section",{className:"space-y-1",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-xs font-medium",children:l("Model")}),(0,a.jsx)("p",{className:"text-sm font-medium break-all",children:t.model})]}),(0,a.jsxs)("section",{className:"space-y-1",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-xs font-medium",children:l("Failed")}),(0,a.jsx)("p",{className:"text-muted-foreground text-sm leading-relaxed wrap-break-word",children:t.summary})]}),(0,a.jsxs)("section",{className:"space-y-2",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-xs font-medium",children:l("Details")}),(0,a.jsx)("pre",{className:"bg-muted/30 text-muted-foreground m-0 max-w-full rounded-md border p-3 text-xs leading-relaxed wrap-break-word whitespace-pre-wrap",children:t.details})]})]}),(0,a.jsx)(sa.XW,{className:(0,t7.Jx)("sm:px-5"),children:(0,a.jsxs)(tg.$,{variant:"outline",className:"w-full sm:w-auto",onClick:()=>o(t.details),children:[r===t.details?(0,a.jsx)(tj.A,{className:"mr-2 h-4 w-4 text-green-600"}):(0,a.jsx)(tv.A,{className:"mr-2 h-4 w-4"}),l("Copy")]})})]})})})}function sg(e){let{table:t}=e,{t:s}=(0,i.Bd)(),{copyToClipboard:l}=(0,tT.C)(),n=t.getFilteredSelectedRowModel().rows.map(e=>e.original.model),r=(0,x.useCallback)(()=>{0!==n.length&&l(n.join(","))},[l,n]);return(0,a.jsx)(t8.Of,{table:t,entityName:"model",children:(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)(tg.$,{size:"sm",onClick:r,disabled:0===n.length}
1),children:[(0,a.jsx)(tv.A,{"data-icon":"inline-start"}),s("Copy selected models")]}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:s("Copy selected models separated by commas (e.g. a,b)")})})]})})}function sf(e){let{open:t,onOpenChange:s}=e,{t:l}=(0,i.Bd)(),{currentRow:n}=tu(),r=(0,p.jE)(),[o,d]=(0,x.useState)("_copy"),[c,u]=(0,x.useState)(!0),[m,h]=(0,x.useState)(!1);if(!n)return null;let g=async()=>{h(!0),await ee(n.id,{suffix:o,reset_balance:c},r,()=>{s(!1),d("_copy"),u(!0)}),h(!1)};return(0,a.jsx)(tx.l,{open:t,onOpenChange:s,title:l("Copy Channel"),description:(0,a.jsxs)(a.Fragment,{children:[l("Create a copy of:"),(0,a.jsx)("strong",{children:n.name})]}),contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:()=>s(!1),disabled:m,children:l("Cancel")}),(0,a.jsxs)(tg.$,{onClick:g,disabled:m,children:[m&&(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}),l(m?"Copying...":"Copy Channel")]})]}),children:(0,a.jsxs)("div",{className:"space-y-4 py-4",children:[(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(st.J,{htmlFor:"suffix",children:l("Name Suffix")}),(0,a.jsx)(se.p,{id:"suffix",placeholder:l("_copy"),value:o,onChange:e=>d(e.target.value),disabled:m}),(0,a.jsxs)("p",{className:"text-muted-foreground text-xs",children:[l("New name will be:")," ",n.name,o]})]}),(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(t9.S,{id:"reset-balance",checked:c,onCheckedChange:e=>u(!!e),disabled:m}),(0,a.jsx)(st.J,{htmlFor:"reset-balance",className:"text-sm font-normal",children:l("Reset balance and used quota")})]})]})})}var sj=s(98622),sv=s(91460),sy=s(38939);function sb(e){let{open:t,onOpenChange:s}=e,{t:n}=(0,i.Bd)(),{currentTag:r}=tu(),o=(0,p.jE)(),[d,c]=(0,x.useState)(""),[u,m]=(0,x.useState)([]),[f,j]=(0,x.useState)(""),[v,y]=(0,x.useState)(""),[b,_]=(0,x.useState)([]),[N,w]=(0,x.useState)(!1),{data:k,isLoading:C}=(0,l.I)({queryKey:["tag-models",r],queryFn:()=>r?(0,h.$M)(r):null,enabled:t&&!!r}),{data:A}=(0,l.I)({queryKey:["all-models"],queryFn:h.i2,enabled:t}),{data:S}=(0,l.I)({queryKey:["groups"],queryFn:h.f,enabled:t}),R=A?.data?.map(e=>e.id).filter(Boolean)||[],I=S?.data||[];(0,x.useEffect)(()=>{t&&r&&(c(r),y(""),_([]),j(""),k?.data?m(k.data.split(",").filter(Boolean)):m([]))},[t,r,k]);let M=()=>{if(!f.trim())return;let e=f.split(",").map(e=>e.trim()).filter(Boolean).filter(e=>!u.includes(e));e.length>0?(m([...u,...e]),g.oR.success(n("Added {{count}} model(s)",{count:e.length})),j("")):g.oR.info(n("No new models to add"))},O=async()=>{if(r&&(()=>{if(v.trim())try{JSON.parse(v)}catch{return g.oR.error(n("Model mapping must be valid JSON")),!1}return!0})()){if(!(d!==r||v.trim()||u.length>0||b.length>0))return void g.oR.warning(n("No changes to save"));w(!0);try{let e={tag:r};d&&d!==r&&(e.new_tag=d||null),v.trim()&&(e.model_mapping=v),u.length>0&&(e.models=u.join(",")),b.length>0&&(e.groups=b.join(","));let t=await (0,h.vS)(e);t.success?(g.oR.success(n("Tag updated successfully")),o.invalidateQueries({queryKey:K.lists()}),s(!1)):g.oR.error(t.message||n("Failed to update tag"))}catch(e){g.oR.error(e instanceof Error?e.message:n("Failed to update tag"))}finally{w(!1)}}},T=()=>{s(!1)};return r?(0,a.jsx)(tx.l,{open:t,onOpenChange:T,title:(0,a.jsxs)(a.Fragment,{children:[n("Edit Tag:"),r]}),description:n("Batch edit all channels with this tag. Leave fields empty to keep current values."),contentClassName:"max-h-[90vh] max-w-2xl",contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:T,children:n("Cancel")}),(0,a.jsxs)(tg.$,{onClick:O,disabled:N,children:[N&&(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}),n("Save Changes")]})]}),children:(0,a.jsx)(tM.F,{className:"max-h-[60vh] pr-4",children:(0,a.jsxs)("div",{className:"space-y-6",children:[(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)(st.J,{htmlFor:"new-tag",children:[n("Tag Name"),(0,a.jsx)("span",{className:"text-muted-foreground ml-2 text-xs",children:n("(Leave empty to dissolve tag)")})]}),(0,a.jsx)(se.p,{id:"new-tag",value:d,onChange:e=>c(e.target.value),placeholder:n("Enter new tag name or leave empty")})]}),(0,a.jsx)(sy.w,{}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)(st.J,{children:[n("Models"),(0,a.jsx)("span",{className:"text-muted-foreground ml-2 text-xs",children:n("(Override all channels' models)")})]}),C?(0,a.jsxs)("div",{className:"flex items-center gap-2 py-4",children:[(0,a.jsx)(th.A,{className:"h-4 w-4 animate-spin"}),(0,a.jsx)("span",{className:"text-muted-foreground text-sm",children:n("Loading current models...")})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("div",{className:"flex min-h-[60
1px] flex-wrap gap-2 rounded-md border p-3",children:u.length>0?u.map(e=>(0,a.jsxs)(tk.Wh,{variant:"neutral",className:"cursor-pointer transition-opacity hover:opacity-70",copyable:!1,onClick:()=>{m(u.filter(t=>t!==e))},children:[e," ×"]},e)):(0,a.jsx)("span",{className:"text-muted-foreground text-sm",children:n("No models selected")})}),(0,a.jsx)("div",{className:"flex gap-2",children:(0,a.jsxs)(ss.l6,{items:[...R.map(e=>({value:e,label:e}))],onValueChange:e=>{null!==e&&(u.includes(e)||m([...u,e]))},children:[(0,a.jsx)(ss.bq,{className:"flex-1",children:(0,a.jsx)(ss.yv,{placeholder:n("Add from available models...")})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:(0,a.jsx)(tM.F,{className:"h-60",children:R.map(e=>(0,a.jsx)(ss.eb,{value:e,children:e},e))})})})]})}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(se.p,{placeholder:n("Custom model (comma-separated)"),value:f,onChange:e=>j(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),M())}}),(0,a.jsx)(tg.$,{type:"button",variant:"secondary",onClick:M,children:n("Add")})]})]})]}),(0,a.jsx)(sy.w,{}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)(st.J,{htmlFor:"model-mapping",children:[n("Model Mapping (JSON)"),(0,a.jsx)("span",{className:"text-muted-foreground ml-2 text-xs",children:n("(Optional: redirect model names)")})]}),(0,a.jsx)(sv.B,{id:"model-mapping",value:v,onChange:y,placeholder:'{\n  "gpt-3.5-turbo": "gpt-3.5-turbo-0125"\n}',heightClassName:"h-40 min-h-40 max-h-40"}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>y(JSON.stringify({"gpt-3.5-turbo":"gpt-3.5-turbo-0125"},null,2)),children:n("Example")}),(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>y(JSON.stringify({},null,2)),children:n("Clear Mapping")}),(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>y(""),children:n("No Change")})]})]}),(0,a.jsx)(sy.w,{}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)(st.J,{children:[n("Groups"),(0,a.jsx)("span",{className:"text-muted-foreground ml-2 text-xs",children:n("(Override all channels' groups)")})]}),(0,a.jsx)("div",{className:"flex min-h-[60px] flex-wrap gap-2 rounded-md border p-3",children:I.map(e=>(0,a.jsx)(sj.d,{group:e,className:`cursor-pointer rounded-sm transition-opacity hover:opacity-70 ${b.includes(e)?"bg-muted/70 px-1":""}`,onClick:()=>{_(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}},e))})]})]})})}):null}var s_=s(38766),sN=s(56920);function sw(e){return[...new Set(e.map(e=>tr(e)).filter(Boolean))]}function sk(e){let t,{open:s,onOpenChange:l,onModelsSelected:n,redirectModels:r=[],redirectSourceModels:o=[],customFetcher:d,existingModelsOverride:u,channelName:m}=e,{t:f}=(0,i.Bd)(),{currentRow:j}=tu(),v=d?null:j,y=(0,p.jE)(),[b,_]=(0,x.useState)(!1),[N,w]=(0,x.useState)(!1),[k,C]=(0,x.useState)([]),[A,S]=(0,x.useState)([]),[R,I]=(0,x.useState)(""),M=(0,x.useMemo)(()=>u??tl(v?.models||""),[u,v?.models]),{classificationSet:O,redirectOnlySet:T}=(0,x.useMemo)(()=>{let e,t,s,a;return e=new Set(M.map(e=>tr(e)).filter(Boolean)),s=new Set([...e,...t=new Set(r.map(e=>tr(e)).filter(Boolean))]),a=new Set(Array.from(t).filter(t=>!e.has(t))),{normalizedCurrentModels:e,normalizedRedirectModels:t,classificationSet:s,redirectOnlySet:a}},[M,r]),z=(0,x.useMemo)(()=>new Set(sw(k)),[k]),E=(0,x.useMemo)(()=>new Set(sw(o)),[o]),$=(0,x.useMemo)(()=>{let e=R.toLowerCase().trim();return sw(A).filter(t=>!(z.has(t)||E.has(t))&&(!e||t.toLowerCase().includes(e)))},[z,E,R,A]);(0,x.useEffect)(()=>{s&&(v||d)&&F()},[s,v?.id,d]);let F=async()=>{if(v||d){_(!0);try{if(d){let e=await d();C(e),S(M),g.oR.success(f("Fetched {{count}} models",{count:e.length}))}else if(v){let e=await (0,h.Mp)(v.id);if(e.success){let t=Array.isArray(e.data)?e.data:[];C(t),S(M),g.oR.success(f("Fetched {{count}} models",{count:t.length}))}else g.oR.error(e.message||f("Failed to fetch models")),C([])}}catch(e){g.oR.error(e instanceof Error?e.message:f("Failed to fetch models")),C([])}finally{_(!1)}}},B=async()=>
1{if(n){n(A),g.oR.success(f("Models filled to form")),l(!1);return}if(v){w(!0);try{let e=A.join(","),t=await (0,h.fy)(v.id,{models:e});t.success?(g.oR.success(f("Models updated successfully")),y.invalidateQueries({queryKey:K.lists()}),l(!1)):g.oR.error(t.message||f("Failed to update models"))}catch(e){g.oR.error(e instanceof Error?e.message:f("Failed to update models"))}finally{w(!1)}}},P=()=>{C([]),S([]),I(""),l(!1)},D=(0,x.useMemo)(()=>R?k.filter(e=>e.toLowerCase().includes(R.toLowerCase())):k,[k,R]),{newModels:J,existingFilteredModels:q,newModelsByCategory:L,existingModelsByCategory:V}=(0,x.useMemo)(()=>{let e=[],t=[];for(let s of D)O.has(tr(s))?t.push(s):e.push(s);return{newModels:e,existingFilteredModels:t,newModelsByCategory:to(e),existingModelsByCategory:to(t)}},[O,D]),W=e=>Object.entries(e).sort((e,t)=>{let[s]=e,[a]=t;return"Other"===s?1:"Other"===a?-1:s.localeCompare(a,void 0,{sensitivity:"base"})}),U=(e,t)=>{let s=t.every(e=>A.includes(e));return(0,a.jsxs)(tS.Nt,{defaultOpen:!0,children:[(0,a.jsxs)(tS.R6,{className:"hover:bg-muted/50 flex w-full items-center justify-between rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(tN.A,{className:"h-4 w-4"}),(0,a.jsxs)("span",{className:"font-medium",children:[e," (",t.length,")"]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)("span",{className:"text-muted-foreground text-sm",children:[t.filter(e=>A.includes(e)).length," ","/ ",t.length," selected"]}),(0,a.jsx)(t9.S,{checked:s,onCheckedChange:e=>{var s;return s=!!e,void S(e=>{if(!s)return e.filter(e=>!t.includes(e));{let s=[...e];return t.forEach(e=>{s.includes(e)||s.push(e)}),s}})},onClick:e=>e.stopPropagation()})]})]}),(0,a.jsx)(tS.Ke,{className:"px-4 py-2",children:(0,a.jsx)("div",{className:"grid grid-cols-2 gap-2",children:t.map(e=>(0,a.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,a.jsx)(t9.S,{id:e,checked:A.includes(e),onCheckedChange:()=>{S(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}}),(0,a.jsxs)(st.J,{htmlFor:e,className:"flex cursor-pointer items-center gap-1.5 text-sm font-normal",children:[(0,a.jsx)("span",{children:e}),T.has(tr(e))&&(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(t6.A,{className:"h-3.5 w-3.5 text-amber-500"})}),(0,a.jsx)(c.ZI,{children:f("From model redirect, not yet added to models list")})]})]})]},e))})})]},e)},H=!!(v||d)&&!b&&(k.length>0||$.length>0),G=f("Fetch available models from upstream");v?G=(0,a.jsxs)(a.Fragment,{children:[f("Channel:")," ",(0,a.jsx)("strong",{children:v.name})]}):m&&(G=(0,a.jsxs)(a.Fragment,{children:[f("Channel:")," ",(0,a.jsx)("strong",{children:m})]}));let Y="existing";return J.length>0?Y="new":$.length>0&&(Y="removed"),t=v||d?b?(0,a.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,a.jsx)(th.A,{className:"text-muted-foreground h-8 w-8 animate-spin"})}):0===k.length&&0===$.length?(0,a.jsxs)("div",{className:"text-muted-foreground py-8 text-center",children:[(0,a.jsx)("p",{children:f("No models fetched yet.")}),(0,a.jsx)(tg.$,{className:"mt-4",onClick:F,disabled:b,children:f("Fetch Models")})]}):(0,a.jsxs)("div",{className:"space-y-4",children:[(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)(s_.A,{className:"text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2"}),(0,a.jsx)(se.p,{placeholder:f("Search models..."),value:R,onChange:e=>I(e.target.value),className:"pl-9"})]}),(0,a.jsxs)(sN.tU,{defaultValue:Y,children:[(0,a.jsxs)(sN.j7,{className:`grid w-full ${$.length>0?"grid-cols-3":"grid-cols-2"}`,children:[(0,a.jsx)(sN.Xi,{value:"new",disabled:0===J.length,children:f("New Models ({{count}})",{count:J.length})}),(0,a.jsx)(sN.Xi,{value:"existing",disabled:0===q.length,children:f("Existing Models ({{count}})",{count:q.length})}),$.length>0&&(0,a.jsx)(sN.Xi,{value:"removed",children:f("Removed Models ({{count}})",{count:$.length})})]}),(0,a.jsx)(sN.av,{value:"new",className:"max-h-96 space-y-2 overflow-y-auto",children:W(L).map(e=>{let[t,s]=e;return U(t,s)})}),(0,a.jsx)(sN.av,{value:"existing",className:"max-h-96 space-y-2 overflow-y-auto",children:W(V).map(e=>{let[t,s]=e;return U(t,s)})}),$.length>0&&(0,a.jsxs)(sN.av,{value:"removed",className:"max-h-96 space-y-2 overflow-y-auto",children:[(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:f("These models are still in your selection but were not returned by the upstream listing. Entries that are only model_mapping source aliases are omitted. Toggle to adjust before saving.")}),U(f("Removed"),$)]})]},`${v?.id??"custom"}-${k.length}-${$.length}`),(0,a.jsx)("div",{className:"bg-muted/50 rounded-lg border p-3 text-sm",children:f("{{n}} model(s) selected",{n:A.length})})]}):(0,a.jsx)("div",{className:"text-muted-foreground py-8 text-center",children:f("No channel selected")}),(0,a.jsx)(tx.l,{open:s,onOpenChange:P,title:f("Fetch Models"),description:G,contentClassName:"max-w-3xl",contentHeight:"auto",bodyClassName:"space-y-4",footer:H?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:P,disabled:N,children:f("Cancel")}),(0,a.jsxs)(tg.$,{onClick:B,disabled:N,children:[N&&(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}),N?f("Saving..."):f("Save Models")]})]}):null,children:t})}var sC=s(36001),sA=s(6201),sS=s(10552);function sR(e){let{label:t,count:s,total:l}=e,{t:n}=(0,i.Bd)();return(0,a.jsxs)("div",{className:"rounded-md border p-3",children:[(0,a.jsx)("div",{className:"text-muted-foreground mb-1 text-xs font-medium",children:t}),(0,a.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,a.jsx)("span",{className:"text-foreground text-2xl font-semibold",children:s}),(0,a.jsxs)("span",{className:"text-muted-foreground text-sm",children:[n("of")," ",l]})]})]})}function sI(e){let{keyIndex:t,status:s,canDelete:l,onAction:n}=e,{t:r}=(0,i.Bd)();return(0,a.jsxs)("div",{className:"flex justify-end gap-2",children:[1===s?(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:()=>n({type:"disable",keyIndex:t}),children:r("Disable")}):(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:()=>n({type:"enable",keyIndex:t}),children:r("Enable")}),(0,a.jsx)(tg.$,{variant:"destructive",size:"sm",onClick:()=>
1{l&&n({type:"delete",keyIndex:t})},disabled:!l,title:l?void 0:r("No permission to perform this action"),children:r("Delete")})]})}function sM(e){let{open:t,onOpenChange:s}=e,{t:l}=(0,i.Bd)(),{currentRow:n}=tu(),r=(0,p.jE)(),o=(0,m.n)(e=>e.auth.user),d=(0,sS._m)(o,sS.kB.CHANNEL,sS.YG.SENSITIVE_WRITE),[c,u]=(0,x.useState)(!1),[f,j]=(0,x.useState)([]),[v,y]=(0,x.useState)(1),[b,_]=(0,x.useState)(10),[N,w]=(0,x.useState)(0),[k,C]=(0,x.useState)(0),[A,S]=(0,x.useState)(0),[I,O]=(0,x.useState)(0),[T,z]=(0,x.useState)(0),[E,$]=(0,x.useState)(null),[F,B]=(0,x.useState)(null),[P,D]=(0,x.useState)(!1);(0,x.useEffect)(()=>{t&&n&&(y(1),$(null),J(1,b,null))},[t,n?.id]);let J=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:v,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:E;if(n){u(!0);try{let a=await (0,h.bV)(n.id,e,t,null===s?void 0:s);a.success&&a.data?(j(a.data.keys||[]),w(a.data.total||0),y(a.data.page||1),_(a.data.page_size||10),C(a.data.total_pages||0),S(a.data.enabled_count||0),O(a.data.manual_disabled_count||0),z(a.data.auto_disabled_count||0)):g.oR.error(a.message||l("Failed to load key status"))}catch(e){g.oR.error(e instanceof Error?e.message:l("Failed to load key status"))}finally{u(!1)}}},q=e=>{y(e),J(e,b)},L=async()=>{if(F&&n){if(!d&&("delete"===F.type||"delete-disabled"===F.type))return void B(null);D(!0);try{let e,{type:t,keyIndex:s}=F;"enable"===t&&void 0!==s?e=await (0,h.C9)(n.id,s):"disable"===t&&void 0!==s?e=await (0,h.zi)(n.id,s):"delete"===t&&void 0!==s?e=await (0,h.SN)(n.id,s):"enable-all"===t?e=await (0,h.e1)(n.id):"disable-all"===t?e=await (0,h.bc)(n.id):"delete-disabled"===t&&(e=await (0,h.xF)(n.id)),e?.success?(g.oR.success(e.message||l("Operation successful")),r.invalidateQueries({queryKey:K.lists()}),t.includes("all")||"delete-disabled"===t?(y(1),J(1,b)):J(v,b)):g.oR.error(e?.message||l("Operation failed"))}catch(e){g.oR.error(e instanceof Error?e.message:l("Operation failed"))}finally{D(!1),B(null)}}};return n?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tx.l,{open:t,onOpenChange:s,title:(0,a.jsxs)(a.Fragment,{children:[l("Multi-Key Management"),(0,a.jsx)(tk.Wh,{label:n.name,variant:"neutral",copyable:!1}),n.channel_info?.multi_key_mode&&(0,a.jsx)(tk.Wh,{label:"random"===n.channel_info.multi_key_mode?l("Random"):l("Polling"),variant:"neutral",copyable:!1})]}),description:l("Manage multi-key status and configuration for this channel"),contentClassName:"flex max-h-[90vh] max-w-5xl flex-col",titleClassName:"flex items-center gap-2",contentHeight:"min(72vh, 720px)",bodyClassName:"space-y-4",children:(0,a.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col space-y-4 overflow-hidden",children:[(0,a.jsxs)("div",{className:"grid shrink-0 grid-cols-3 gap-3",children:[(0,a.jsx)(sR,{label:l("Enabled"),count:A,total:N}),(0,a.jsx)(sR,{label:l("Manual Disabled"),count:I,total:N}),(0,a.jsx)(sR,{label:l("Auto Disabled"),count:T,total:N})]}),(0,a.jsx)(sy.w,{className:"shrink-0"}),(0,a.jsxs)("div",{className:"flex shrink-0 items-center justify-between",children:[(0,a.jsxs)(ss.l6,{items:[...M.map(e=>({value:e.value,label:l(e.label)}))],value:null===E?"all":E.toString(),onValueChange:e=>{let t;return null!==e&&void($(t="all"===e?null:parseInt(e)),y(1),J(1,b,t))},children:[(0,a.jsx)(ss.bq,{className:"w-40",children:(0,a.jsx)(ss.yv,{placeholder:l("All Status")})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:M.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:l(e.label)},e.value))})})]}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:()=>J(),disabled:c,children:(0,a.jsx)(tp.A,{className:"h-4 w-4"})}),I+T>0&&(0,a.jsxs)(tg.$,{variant:"default",size:"sm",onClick:()=>B({type:"enable-all"}),children:[(0,a.jsx)(sC.A,{className:"mr-2 h-4 w-4"}),l("Enable All")]}),A>0&&(0,a.jsxs)(tg.$,{variant:"destructive",size:"sm",onClick:()=>B({type:"disable-all"}),children:[(0,a.jsx)(sA.A,{className:"mr-2 h-4 w-4"}),l("Disable All")]}),T>0&&(0,a.jsxs)(tg.$,{variant:"destructive",size:"sm",onClick:()=>{d&&B({type:"delete-disabled"})},disabled:!d,title:d?void 0:l("No permission to perform this action"),children:[(0,a.jsx)(t5.A,{className:"mr-2 h-4 w-4"}),l("Delete Auto-Disabled")]})]})]}
1),!d&&(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:l("No permission to perform this action")}),(0,a.jsx)("div",{className:"min-h-0 flex-1 overflow-auto rounded-md border",children:c?(0,a.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,a.jsx)(th.A,{className:"text-muted-foreground h-8 w-8 animate-spin"})}):0===f.length?(0,a.jsx)("div",{className:"text-muted-foreground py-12 text-center",children:l("No keys found")}):(0,a.jsx)(t8.hm,{className:"rounded-none border-0",tableClassName:"min-w-[800px]",data:f,getRowKey:e=>e.index,columns:[{id:"index",header:l("Index"),className:"w-20",cellClassName:"font-mono text-sm",cell:e=>`#${e.index+1}`},{id:"status",header:l("Status"),className:"w-32",cell:e=>{let t;return t=R[e.status]||{variant:"neutral",label:"Unknown"},(0,a.jsx)(tk.Wh,{label:l(t.label),variant:t.variant,showDot:!0,copyable:!1})}},{id:"reason",header:l("Disabled Reason"),className:"min-w-[200px]",cellClassName:"max-w-xs truncate text-sm",cell:e=>e.reason||"-"},{id:"disabled-time",header:l("Disabled Time"),className:"w-44",cellClassName:"text-muted-foreground text-sm",cell:e=>(e=>{if(!e)return"-";if(!e||0===e)return"N/A";try{return(0,e6.fk)(e)}catch{return"Invalid date"}})(e.disabled_time)},{id:"actions",header:l("Actions"),className:"text-right",cell:e=>(0,a.jsx)(sI,{keyIndex:e.index,status:e.status,canDelete:d,onAction:B})}]})}),k>1&&(0,a.jsxs)("div",{className:"flex shrink-0 items-center justify-between",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-sm",children:l("Page {{current}} of {{total}}",{current:v,total:k})}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:()=>q(v-1),disabled:1===v||c,children:l("Previous")}),(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:()=>q(v+1),disabled:v>=k||c,children:l("Next")})]})]})]})}),(0,a.jsx)(tw.T,{open:null!==F,onOpenChange:e=>!e&&B(null),title:l("Confirm Action"),desc:l(function(e){if(!e)return"";switch(e.type){case"delete":return"Are you sure you want to delete this key? This action cannot be undone.";case"enable":return"Enable this key?";case"disable":return"Disable this key?";case"enable-all":return"Are you sure you want to enable all keys?";case"disable-all":return"Are you sure you want to disable all enabled keys?";case"delete-disabled":return"Are you sure you want to delete all auto-disabled keys? This action cannot be undone.";default:return""}}(F)),destructive:!!F&&("delete"===F.type||"delete-disabled"===F.type||"disable-all"===F.type),isLoading:P,handleConfirm:L})]}):null}var sO=s(33834),sT=s(92379);function sz(e){return"object"==typeof e&&null!==e}function sE(e){return"string"==typeof e?e:void 0}function s$(e){return"number"==typeof e?e:void 0}function sF(e){if(!e)return"";let t="string"==typeof e.base_url?e.base_url.trim():"";if(t)return t;let s="string"==typeof e?.ollama_base_url?String(e.ollama_base_url).trim():"";if(s)return s;let a=function(e){if(!e)return null;if("object"==typeof e)return e;if("string"==typeof e)try{return JSON.parse(e)}catch{}return null}(e.other_info);if(sz(a)){let e=sE(a.base_url)?.trim();if(e)return e;let t=sE(a.public_url)?.trim();if(t)return t;let s=sE(a.api_url)?.trim();if(s)return s}return""}function sB(e){return Array.isArray(e)?e.map(e=>{if(!e)return null;if("string"==typeof e)return{id:e,owned_by:"ollama"};if(sz(e)){let t=sE(e.id)||sE(e.ID)||sE(e.name)||sE(e.model)||sE(e.Model);if(!t)return null;let s=e.metadata??e.Metadata,a={...e,id:t,owned_by:sE(e.owned_by)||sE(e.ownedBy)||"ollama"},l=s$(e.size);if("number"!=typeof l||a.size||(a.size=l),sz(s)){let e=s$(s.size);"number"!=typeof e||a.size||(a.size=e);let t=sE(s.digest);!a.digest&&t&&(a.digest=t);let l=sE(s.modified_at);!a.modified_at&&l&&(a.modified_at=l),s.details&&!a.details&&(a.details=s.details)}return a}return null}).filter(Boolean):[]}function sP(e){let{open:t,onOpenChange:s}=e,{t:l}=(0,i.Bd)(),n=(0,p.jE)(),{currentRow:r}=tu(),o=r?.type===4,d=r?.id,[c,u]=(0,x.useState)(!1),[m,j]=(0,x.useState)([]),[v,y]=(0,x.useState)([]),[b,_]=(0,x.useState)(""),[N,w]=(0,x.useState)(""),[k,C]=(0,x.useState)(!1),[A,S]=(0,x.useState)(null),R=(0,x.useRef)(null),[I,M]=(0,x.useState)(!1),[O,T]=(0,x.useState)(null),[z,E]=(0,x.useState)(!1),$=(0,x.useMemo)(()=>
1{if(!b.trim())return m;let e=b.trim().toLowerCase();return m.filter(t=>t.id.toLowerCase().includes(e))},[m,b]),F=(0,x.useMemo)(()=>tl(r?.models??""),[r?.models]);(0,x.useEffect)(()=>{if(!t){j([]),y([]),_(""),w(""),C(!1),S(null),R.current?.abort(),R.current=null;return}t&&o&&d&&B()},[t,o,d]);let B=(0,x.useCallback)(async()=>{if(d){u(!0);try{let e=[],t="",s=sF(r??null);if(o&&s)try{let a=await (0,h.ZC)({base_url:s,type:4,key:"string"==typeof r?.key?r.key:""});a?.success?e=sB(a.data):a?.message&&(t=String(a.message))}catch(e){t=e instanceof Error?e.message:""}if(!e.length){let s=await (0,h.Mp)(Number(d));s?.success?(e=sB(s.data),t=""):t=String(s?.message||"")}!e.length&&t&&g.oR.error(t||l("Failed to fetch models")),j(e),y(t=>{if(!t.length)return e.map(e=>e.id);let s=t.filter(t=>e.some(e=>e.id===t));return s.length?s:e.map(e=>e.id)})}catch(t){let e=t instanceof Error?t.message:void 0;g.oR.error(e||l("Failed to fetch models")),j([])}finally{u(!1)}}},[d,r,o,l]),P=async e=>{if(!r)return;if(!v.length)return void g.oR.info(l("No models selected"));let t="replace"===e?[...new Set(v)]:[...new Set([...F,...v])];try{let s=await (0,h.fy)(r.id,{models:t.join(",")});s.success?(g.oR.success("replace"===e?l("Models updated successfully"):l("Models appended successfully")),n.invalidateQueries({queryKey:K.lists()})):g.oR.error(s.message||l("Failed to update models"))}catch(e){g.oR.error(e instanceof Error?e.message:l("Failed to update models"))}},D=async()=>{if(!d)return;if(!N.trim())return void g.oR.error(l("Please enter model name"));if(!sF(r))return void g.oR.error(l("Please set Ollama API Base URL first"));R.current?.abort();let e=new AbortController;R.current=e,C(!0),S({status:"starting",completed:0,total:0});try{let t=await (0,f.DU)(),s=await fetch("/api/channel/ollama/pull/stream",{method:"POST",credentials:"include",headers:{...t,Accept:"text/event-stream"},body:JSON.stringify({channel_id:d,model_name:N.trim()}),signal:e.signal});if(!s.ok||!s.body)throw Error(`HTTP ${s.status}: ${s.statusText}`);let a=s.body.getReader(),l=new TextDecoder,r="";for(;;){let{done:e,value:t}=await a.read();if(e)break;let s=(r+=l.decode(t,{stream:!0})).split("\n");for(let e of(r=s.pop()||"",s)){if(!e.startsWith("data: "))continue;let t=e.slice(6);if(t){if("[DONE]"===t){C(!1),S(null),R.current=null;return}try{let e=JSON.parse(t);if(e?.status)S(e);else if(e?.error){g.oR.error(String(e.error)),C(!1),S(null),R.current=null;return}else if(e?.message){g.oR.success(String(e.message)),w(""),C(!1),S(null),R.current=null,await B(),n.invalidateQueries({queryKey:K.lists()});return}}catch{}}}}C(!1),S(null),R.current=null,await B(),n.invalidateQueries({queryKey:K.lists()})}catch(e){if(!("object"==typeof e&&null!==e&&"name"in e&&"AbortError"===e.name)){let t=e instanceof Error?e.message:"";g.oR.error(l("Model pull failed: {{msg}}",{msg:t}))}C(!1),S(null),R.current=null}},J=async e=>{if(d)try{E(!0);let t=await (0,h.No)({channel_id:Number(d),model_name:e});t?.success?(g.oR.success(l("Model deleted")),await B(),n.invalidateQueries({queryKey:K.lists()}),M(!1),T(null)):g.oR.error(t?.message||l("Failed to delete model"))}catch(t){let e=t instanceof Error?t.message:void 0;g.oR.error(e||l("Failed to delete model"))}finally{E(!1)}},q=()=>{R.current?.abort(),R.current=null,s(!1)};return t?(0,a.jsxs)(tx.l,{open:t,onOpenChange:q,title:l("Ollama Models"),description:(0,a.jsxs)(a.Fragment,{children:[l("Manage local models for:")," ",(0,a.jsx)("strong",{children:r?.name})]}),contentClassName:"sm:max-w-3xl",contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsx)(tg.$,{variant:"outline",onClick:q,children:l("Close")}),children:[o?(0,a.jsxs)("div",{className:"space-y-4 py-2 pr-1",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[(0,a.jsxs)("div",{className:"flex-1 space-y-2",children:[(0,a.jsx)(st.J,{htmlFor:"ollama-pull",children:l("Pull model")}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsx)(se.p,{id:"ollama-pull",placeholder:l("e.g. llama3.1:8b"),value:N,onChange:e=>w(e.target.value),disabled:!d||k}),(0,a.jsx)(tg.$,{onClick:()=>void D(),disabled:!d||k,children:k?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}),l("Pulling...")]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(sO.A,{className:"mr-2 h-4 w-4"}),l("Pull")]})})]}),A&&(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)("div",{className:"text-muted-foreground text-xs",children:[l("Status:")," ",String(A.status||"-")]}),(0,a.jsx)(tI.ke,{value:"number"==typeof A.completed&&"number"==typeof A.total&&A.total>0?Math.min(100,Math.round(A.completed/A.total*100)):0})]})]}),(0,a.jsx)("div",{className:"flex gap-2",children:(0,a.jsxs)(tg.$,{variant:"outline",onClick:()=>void B(),disabled:!d||c,children:[c?(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}):(0,a.jsx)(tp.A,{className:"mr-2 h-4 w-4"}),l("Refresh")]})})]}),(0,a.jsx)(sy.w,{}),(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-sm font-medium",children:l("Local models")}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:l("Select models and apply to channel models list.")})]}),(0,a.jsxs)("div",{className:"relative sm:w-72",children:[(0,a.jsx)(s_.A,{className:"text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2"}),(0,a.jsx)(se.p,{placeholder:l("Search models..."),value:b,onChange:e=>_(e.target.value),className:"pl-9"})]})]}),(0,a.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:()=>{y(e=>{let t=new Set(e);
1return $.forEach(e=>t.add(e.id)),[...t]})},children:l("Select all (filtered)")}),(0,a.jsx)(tg.$,{variant:"outline",size:"sm",onClick:()=>y([]),children:l("Clear selection")}),(0,a.jsx)(tg.$,{size:"sm",onClick:()=>void P("append"),disabled:!v.length,children:l("Append to channel")}),(0,a.jsx)(tg.$,{variant:"secondary",size:"sm",onClick:()=>void P("replace"),disabled:!v.length,children:l("Replace channel models")})]}),(0,a.jsx)("div",{className:"overflow-hidden rounded-md border",children:(0,a.jsx)("div",{className:"max-h-[420px] overflow-y-auto",children:0===$.length?(0,a.jsx)("div",{className:"text-muted-foreground p-6 text-center text-sm",children:l("No models found.")}):(0,a.jsx)("div",{className:"divide-y",children:$.map(e=>{let t=v.includes(e.id);return(0,a.jsxs)("div",{className:"flex items-center justify-between gap-3 p-3",children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-start gap-3",children:[(0,a.jsx)(t9.S,{checked:t,onCheckedChange:t=>{var s,a;return s=e.id,a=!!t,void y(e=>a?e.includes(s)?e:[...e,s]:e.filter(e=>e!==s))},"aria-label":`Select model ${e.id}`}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("div",{className:"truncate font-mono text-sm",children:e.id}),(0,a.jsxs)("div",{className:"text-muted-foreground flex flex-wrap gap-x-3 gap-y-1 text-xs",children:[(0,a.jsxs)("span",{children:[l("Size:")," ",function(e){if("number"!=typeof e||Number.isNaN(e))return"-";if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let s=t/1024;if(s<1024)return`${s.toFixed(1)} MB`;let a=s/1024;return`${a.toFixed(2)} GB`}(e.size)]}),e.digest&&(0,a.jsxs)("span",{className:"truncate",children:[l("Digest:")," ",String(e.digest)]})]})]})]}),(0,a.jsx)(tg.$,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{T(e.id),M(!0)},disabled:!d,children:(0,a.jsx)(t5.A,{className:"h-4 w-4"})})]},e.id)})})})})]})]}):(0,a.jsx)("div",{className:"text-muted-foreground py-8 text-center",children:l("This channel is not an Ollama channel.")}),(0,a.jsx)(sT.Lt,{open:I,onOpenChange:e=>{M(e),e||T(null)},children:(0,a.jsxs)(sT.EO,{children:[(0,a.jsxs)(sT.wd,{children:[(0,a.jsx)(sT.r7,{children:l("Confirm delete")}),(0,a.jsx)(sT.$v,{children:l('Delete model "{{name}}"? This cannot be undone.',{name:O||""})})]}),(0,a.jsxs)(sT.ck,{children:[(0,a.jsx)(sT.Zr,{disabled:z,children:l("Cancel")}),(0,a.jsxs)(sT.Rx,{variant:"destructive",disabled:z||!O,onClick:()=>{O&&J(O)},children:[z?(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}):null,l("Delete")]})]})]})})]}):null}var sD=s(52671),sJ=s(18353),sq=s(70954),sL=s(12798),sV=s(3501),sK=s(66002);let sW='{ "duplicate_source_models": ';function sU(e){let t=new Set,s=new Set;for(let a of e){let e=a.from.trim();e&&(t.has(e)?s.add(e):t.add(e))}return Array.from(s)}function sH(e){let{t}=(0,i.Bd)(),s=(0,x.useId)(),l=(0,x.useId)(),[n,r]=(0,x.useState)("visual"),[o,d]=(0,x.useState)([]),[c,u]=(0,x.useState)(e.value),[m,h]=(0,x.useState)(null),p=(0,x.useRef)(0),g=(0,x.useMemo)(()=>sU(o),[o]),f=()=>(p.current+=1,`mapping-${p.current}`),j=e=>{try{if(!e.trim())return d([]),h(null),!0;let s=JSON.parse(e);if(!s||"object"!=typeof s||Array.isArray(s))return h(t("Model mapping must be a valid JSON object")),!1;let a=Object.entries(s);if(a.find(e=>{let[,t]=e;return"string"!=typeof t}))return h(t("Model mapping values must be strings")),!1;return d(e=>{let t=[...e];return a.map((s,a)=>{let[l,n]=s,r=String(n),i=t.findIndex(t=>t.from===l||t.from===l&&t.to===r||e[a]?.id===t.id);if(i>=0){let[e]=t.splice(i,1);return{id:e.id,from:l,to:r}}return{id:f(),from:l,to:r}})}),h(null),!0}catch(e){return h(t("Model mapping must be valid JSON format")),!1}};(0,x.useEffect)(()=>{u(e.value),j(e.value)},[e.value]);let v=e=>{if(0===e.length)return"";let t={};return e.forEach(e=>{e.from.trim()&&(t[e.from.trim()]=e.to.trim())}),JSON.stringify(t,null,2)},y=s=>{if(d(s),sU(s).length>0){h(t("Duplicate source model mappings are not allowed")),u(sW),e.onChange(sW);return}let a=v(s);h(null),u(a),e.onChange(a)},b=(e,t,s)=>{y(o.map(a=>a.id===e?{...a,[t]:s}:a))};return(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)(sN.tU,{value:n,onValueChange:t=>{if("visual"===t||"json"===t){if("json"===t){if(0===sU(o).length){let t=v(o);u(t),e.onChange(t)}
1r("json");return}j(c),r("visual")}},className:"space-y-2",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,a.jsxs)(sN.j7,{children:[(0,a.jsxs)(sN.Xi,{value:"visual",children:[(0,a.jsx)(sL.A,{className:"h-4 w-4","aria-hidden":"true"}),t("Visual")]}),(0,a.jsxs)(sN.Xi,{value:"json",children:[(0,a.jsx)(sV.A,{className:"h-4 w-4","aria-hidden":"true"}),t("JSON")]})]}),(0,a.jsx)(tg.$,{type:"button",variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{let t=JSON.stringify({"gpt-3.5-turbo":"gpt-3.5-turbo-0125"},null,2);u(t),e.onChange(t),j(t)},disabled:e.disabled,children:t("Fill Template")})]}),m&&(0,a.jsx)(tC.Fc,{variant:"destructive",children:(0,a.jsx)(tC.TN,{children:m})}),g.length>0&&(0,a.jsx)(tC.Fc,{children:(0,a.jsx)(tC.TN,{children:t("Duplicate source model(s): {{models}}",{models:g.join(", ")})})}),(0,a.jsxs)(sN.av,{value:"visual",className:"space-y-2",children:[o.length>0?(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsxs)("div",{className:"grid grid-cols-[1fr_1fr_auto] gap-2 text-sm font-medium",children:[(0,a.jsx)("div",{children:t("Original Model")}),(0,a.jsx)("div",{children:t("Replacement Model")}),(0,a.jsx)("div",{className:"w-10"})]}),o.map(n=>(0,a.jsxs)("div",{className:"grid grid-cols-[1fr_1fr_auto] gap-2",children:[(0,a.jsx)(se.p,{value:n.from,onChange:e=>b(n.id,"from",e.target.value),placeholder:"gpt-3.5-turbo",disabled:e.disabled,list:s}),(0,a.jsx)(se.p,{value:n.to,onChange:e=>b(n.id,"to",e.target.value),placeholder:"gpt-3.5-turbo-0125",disabled:e.disabled,list:l}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"icon",onClick:()=>{var e;return e=n.id,void y(o.filter(t=>t.id!==e))},disabled:e.disabled,className:"h-10 w-10","aria-label":t("Delete mapping"),children:(0,a.jsx)(t5.A,{className:"h-4 w-4","aria-hidden":"true"})})]},n.id))]}):(0,a.jsx)("div",{className:"text-muted-foreground flex h-24 items-center justify-center rounded-md border border-dashed text-sm",children:t('No model mappings configured. Click "Add Mapping" to get started.')}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{y([...o,{id:f(),from:"",to:""}])},disabled:e.disabled,className:"w-full",children:[(0,a.jsx)(sK.A,{className:"mr-2 h-4 w-4"}),t("Add Mapping")]})]}),(0,a.jsx)(sN.av,{value:"json",children:(0,a.jsx)(sv.B,{value:c,onChange:t=>{u(t),e.onChange(t),j(t)},placeholder:t('{"original-model": "replacement-model"}'),disabled:e.disabled,className:m?"border-destructive":void 0,"aria-invalid":!!m,ariaLabel:t("Model Mapping")})})]}),e.sourceModelOptions&&e.sourceModelOptions.length>0&&(0,a.jsx)("datalist",{id:s,children:e.sourceModelOptions.map(e=>(0,a.jsx)("option",{value:e},e))}),e.targetModelOptions&&e.targetModelOptions.length>0&&(0,a.jsx)("datalist",{id:l,children:e.targetModelOptions.map(e=>(0,a.jsx)("option",{value:e},e))})]})}function sG(e){let{open:t,onOpenChange:s}=e,{t:n}=(0,i.Bd)(),{currentTag:r}=tu(),o=(0,p.jE)(),[d,c]=(0,x.useState)(!1),[u,m]=(0,x.useState)(!1),[f,j]=(0,x.useState)(""),[v,y]=(0,x.useState)(""),[b,_]=(0,x.useState)(""),[N,w]=(0,x.useState)([]),{data:k,isLoading:C}=(0,l.I)({queryKey:["groups"],queryFn:h.f}),A=(0,x.useMemo)(()=>k?.data?Array.from(new Set([...k.data,...N])).map(e=>({value:e,label:e})):[],[k,N]);(0,x.useEffect)(()=>{t&&r&&S()},[t,r]);let S=async()=>{if(r){c(!0);try{let e=await (0,h.$M)(r);e.success&&e.data&&y(e.data);let t=await (0,h.i2)();t.success&&t.data,j(r)}catch(e){g.oR.error(e instanceof Error?e.message:n("Failed to load tag data"))}finally{c(!1)}}},R=async()=>{if(r){if(b.trim())try{JSON.parse(b)}catch(e){g.oR.error(n("Model mapping must be valid JSON"));return}m(!0);try{let e={tag:r};if(f!==r&&(e.new_tag=f||void 0),v.trim()&&(e.models=v),b.trim()&&(e.model_mapping=b),N.length>0&&(e.groups=N.join(",")),1===Object.keys(e).length)return void g.oR.warning(n("No changes made"));let t=await (0,h.vS)(e);t.success?(g.oR.success(n("Tag updated successfully")),o.invalidateQueries({queryKey:K.lists()}),I()):g.oR.error(t.message||n("Failed to update tag"))}catch(e){g.oR.error(e instanceof Error?e.message:n("Failed to update tag"))}finally{m(!1)}}},I=()=>{j(""),y(""),_(""),w([]),s(!1)};return r?(0,a.jsx)(tx.l,{open:t,onOpenChange:I,title:n("Batch Edit by Tag"),description:(0,a.jsxs)(a.Fragment,{children:[n("Edit all channels with tag:"),(0,a.jsx)("strong",{children:r})]}),contentClassName:"max-w-2xl",contentHeight:"auto",bodyClassName:"space-y-4",footer:d?null:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:I,disabled:u,children:n("Cancel")}),(0,a.jsxs)(tg.$,{onClick:R,disabled:u,children:[u?(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}):null,u?n("Saving..."):n("Save Changes")]})]}),children:d?(0,a.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,a.jsx)(th.A,{className:"text-muted-foreground h-8 w-8 animate-spin"})}):(0,a.jsx)(a.Fragment,{children:(0,a.jsxs)("div",{className:"space-y-4 py-4",children:[(0,a.jsxs)(t
1C.Fc,{children:[(0,a.jsx)(sD.A,{className:"h-4 w-4"}),(0,a.jsx)(tC.TN,{children:n("All edits are overwrite operations. Leave fields empty to keep current values unchanged.")})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(st.J,{htmlFor:"new-tag",children:n("Tag Name")}),(0,a.jsx)(se.p,{id:"new-tag",placeholder:n("Enter new tag name (leave empty to disband tag)"),value:f,onChange:e=>j(e.target.value),disabled:u}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:n("Leave empty to disband the tag")})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(st.J,{htmlFor:"models",children:n("Models")}),(0,a.jsx)(sq.T,{id:"models",placeholder:n("Comma-separated model names (leave empty to keep current)"),value:v,onChange:e=>y(e.target.value),disabled:u,rows:3}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:n("Current models for the longest channel in this tag. May not include all models from all channels.")})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(st.J,{htmlFor:"model-mapping",children:n("Model Mapping")}),(0,a.jsx)(sH,{value:b,onChange:_,disabled:u})]}),(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(st.J,{htmlFor:"groups",children:n("Groups")}),C?(0,a.jsx)(tO.E,{className:"h-10 w-full"}):(0,a.jsx)(sJ.K,{options:A,selected:N,onChange:w,placeholder:n("Select groups (leave empty to keep current)")}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:n("User groups that can access channels with this tag")})]})]})})}):null}function sY(e){let{t}=(0,i.Bd)(),[s,l]=(0,x.useState)(e.preferredTab),[n,r]=(0,x.useState)(""),[o,d]=(0,x.useState)(""),[c,u]=(0,x.useState)(()=>new Set(e.addModels)),[m,h]=(0,x.useState)(()=>new Set(e.removeModels)),[p,g]=(0,x.useState)(!1),f=(0,x.useMemo)(()=>e.addModels.filter(e=>e.toLowerCase().includes(n.toLowerCase())),[e.addModels,n]),j=(0,x.useMemo)(()=>e.removeModels.filter(e=>e.toLowerCase().includes(o.toLowerCase())),[e.removeModels,o]),v=(e,t,s)=>{let a=new Set(t);a.has(e)?a.delete(e):a.add(e),s(a)},y=(e,t,s)=>{let a=e.every(e=>t.has(e)),l=new Set(t);a?e.forEach(e=>l.delete(e)):e.forEach(e=>l.add(e)),s(l)};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(tx.l,{open:e.open,onOpenChange:t=>!t&&e.onCancel(),title:t("Upstream Model Updates"),contentClassName:"sm:max-w-lg",contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:e.onCancel,children:t("Cancel")}),(0,a.jsx)(tg.$,{onClick:()=>{let t=e.addModels.length>0,s=e.removeModels.length>0,a=Array.from(c),l=Array.from(m),n=a.length>0,r=l.length>0;t&&s&&n!==r?g(!0):e.onConfirm({addModels:a,removeModels:l})},disabled:e.confirmLoading||0===e.addModels.length&&0===e.removeModels.length,children:t("Confirm")})]}),children:[(0,a.jsx)("p",{className:"text-muted-foreground text-sm",children:t('Select models to process. Unselected "add" models will be ignored.')}),(0,a.jsxs)(sN.tU,{value:s,onValueChange:e=>l(e),children:[(0,a.jsxs)(sN.j7,{className:"grid w-full grid-cols-2",children:[(0,a.jsxs)(sN.Xi,{value:"add",className:"gap-1",children:[t("Add Models"),(0,a.jsxs)(tk.Wh,{variant:"neutral",className:"ml-1",copyable:!1,children:[c.size,"/",e.addModels.length]})]}),(0,a.jsxs)(sN.Xi,{value:"remove",className:"gap-1",children:[t("Remove Models"),(0,a.jsxs)(tk.Wh,{variant:"neutral",className:"ml-1",copyable:!1,children:[m.size,"/",e.removeModels.length]})]})]}),(0,a.jsxs)(sN.av,{value:"add",className:"space-y-3",children:[(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)(s_.A,{className:"text-muted-foreground absolute top-2.5 left-2.5 h-4 w-4"}),(0,a.jsx)(se.p,{placeholder:t("Search models..."),className:"pl-8",value:n,onChange:e=>r(e.target.value)})]}),f.length>0&&(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(t9.S,{checked:f.every(e=>c.has(e)),onCheckedChange:()=>y(f,c,u)}),(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:t("Select All Visible")})]}),(0,a.jsx)(tM.F,{className:"h-[280px] rounded-md border p-2",children:f.length>0?(0,a.jsx)("div",{className:"space-y-1",children:f.map(e=>(0,a.jsxs)("label",{className:"hover:bg-accent flex cursor-pointer items-center gap-2 rounded px-2 py-1.5",children:[(0,a.jsx)(t9.S,{checked:c.has(e),onCheckedChange:()=>v(e,c,u)}),(0,a.jsx)("span",{className:"truncate text-sm",children:e})]},e))}):(0,a.jsx)("p",{className:"text-muted-foreground py-8 text-center text-sm",children:t(0===e.addModels.length?"No models to add":"No matching results")})})]}),(0,a.jsxs)(sN.av,{value:"remove",className:"space-y-3",children:[(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)(s_.A,{className:"text-muted-foreground absolute top-2.5 left-2.5 h-4 w-4"}),(0,a.jsx)(se.p,{placeholder:t("Search models..."),className:"pl-8",value:o,onChange:e=>d(e.target.value)})]}),j.length>0&&(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(t9.S,{checked:j.every(e=>m.has(e)),onCheckedChange:()=>y(j,m,h)}),(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:t("Select All Visible")})]}),(0,a.jsx)(tM.F,{className:"h-[280px] rounded-md border p-2",children:j.length>0?(0,a.jsx)("div",{className:"space-y-1",children:j.map(e=>(0,a.jsxs)("label",{className:"hover:bg-accent flex cursor-pointer items-center gap-2 rounded px-2 py-1.5",children:[(0,a.jsx)(t9.S,{checked:m.has(e),onCheckedChange:()=>v(e,m,h)}),(0,a.jsx)("span",{className:"truncate text-sm",children:e})]},e))}):(0,a.jsx)("p",{className:"text-muted-foreground py-8 text-center text-sm",children:t(0===e.removeModels.length?"No models to remove":"No matching results")})})]})]})]}),(0,a.jsx)(tw.T,{open:p,onOpenChange:g,title:t("Partial Submission"),desc:t("There are both add and remove models pending, but you only selected one type. Confirm submitting only the selected items?"),handleConfirm:()=>{g(!1),e.onConfirm({addModels:Array.from(c),removeModels:Array.from(m)}
1)}})]})}var sZ=s(48367),sQ=s(95227),sX=s(92702),s0=s(47296),s1=s(80781),s2=s(96262),s4=s(35285),s5=s(92429),s3=s(13236),s6=s(40315),s8=s(45202),s7=s(5623),s9=s(84e3),ae=s(30544),at=s(98721),as=s(86832),aa=s(24877),al=s(49641),an=s(36710),ar=s(71654),ai=s(71463),ao=s(95327),ad=s(55667);let ac=["type","key","base_url","openai_organization","param_override","header_override","setting","settings","other"];function au(e){return"object"==typeof e&&null!==e}let am=new Set([504,524]);function ah(e){let t=e.trim();return/^[1-5]\d{2}$/.test(t)?Number.parseInt(t,10):null}function ap(e){if("number"==typeof e&&Number.isInteger(e))return e>=100&&e<=599?e:null;if("string"==typeof e){let t=e.trim();if(!/^[1-5]\d{2}$/.test(t))return null;let s=Number.parseInt(t,10);return s>=100&&s<=599?s:null}return null}function ax(e){let t;if(!e?.trim())return[];try{t=JSON.parse(e)}catch{return[]}if(!t||"object"!=typeof t||Array.isArray(t))return[];let s=[];for(let[e,a]of Object.entries(t)){let t=ah(e),l=ap(a);null!==t&&null!==l&&am.has(t)&&t!==l&&s.push(`${t} -> ${l}`)}return[...new Set(s)].sort()}var ag=s(94369),af=s(43641),aj=s(45666),av=s(13415),ay=s(74501);let ab="w-[360px] max-w-[calc(100vw-2rem)]",a_="items-start py-2 [&_[data-slot=select-item-text]]:min-w-0 [&_[data-slot=select-item-text]]:shrink [&_[data-slot=select-item-text]]:whitespace-normal",aN="lg:grid-cols-[6rem_minmax(0,1fr)_minmax(0,1.25fr)_minmax(0,1fr)_minmax(0,0.85fr)_7rem]",aw="Use a path to append it to the channel Base URL, or enter a full URL to override the Base URL for this route.",ak=[];function aC(e,t){return e.find(e=>e.value===t)?.label||t}function aA(e){return(e.incoming_path||"").trim()}function aS(e){return!e.models||0===e.models.length}function aR(e){let{open:t,value:s,onOpenChange:l,onSave:n}=e,{t:r}=(0,i.Bd)(),o=(0,x.useRef)(0),[d,c]=(0,x.useState)(()=>eO(s)||eA()),[u,m]=(0,x.useState)(()=>(ez(eO(s)||eA()).advanced_routes||[]).map((e,t)=>`advanced-custom-route-initial-${t}`)),[h,p]=(0,x.useState)("visual"),[f,j]=(0,x.useState)(()=>eT(eO(s)||eA())),[v,y]=(0,x.useState)(""),[b,_]=(0,x.useState)(ew["0"]?.value||""),N=(0,x.useMemo)(()=>aC(ew,b),[b]),w=(0,x.useMemo)(()=>ez(d),[d]),k=w.advanced_routes||ak,C=(0,x.useMemo)(()=>k.map((e,t)=>({route:e,index:t,routeKey:u.at(t)||e.incoming_path||e.upstream_path||e.converter||"advanced-custom-route"})),[u,k]),A=(0,x.useMemo)(()=>(function(e){let t=[],s=new Map;for(let a of e){let e=aA(a.route),l=s.get(e);l||(l={incomingPath:e,routeRows:[]},s.set(e,l),t.push(l)),l.routeRows.push(a)}return t})(C),[C]),S=(0,x.useMemo)(()=>new Set(A.map(e=>e.incomingPath)),[A]),R=(0,x.useMemo)(()=>ef.filter(e=>!S.has(e.value)),[S]),I=(0,x.useMemo)(()=>eF(w),[w]),M=I?.message==="Catch-all route must be last for the same incoming path",O=()=>(o.current+=1,`advanced-custom-route-${o.current}`),T=e=>Array.from({length:e},()=>O()),z=(e,t)=>{c(s=>{let a=ez(s),l=[...a.advanced_routes||[]];return l[e]={...l[e],...t},{...a,advanced_routes:l}})},E=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:C.map(e=>e.routeKey);c(t=>({...ez(t),advanced_routes:e})),m(t)},$=e=>{c(t=>{let s=ez(t);return{...s,advanced_routes:(s.advanced_routes||[]).filter((t,s)=>s!==e)}}),m(t=>t.filter((t,s)=>s!==e))},F=e=>{let t=aA(k[e]),s=-1;for(let e=k.length-1;e>=0;e-=1)if(aA(k[e])===t){s=e;break}if(s<0||e===s)return;let a=[...k],l=C.map(e=>e.routeKey),[n]=a.splice(e,1),[r]=l.splice(e,1);a.splice(s,0,n),l.splice(s,0,r),E(a,l)},B=()=>{let e=eO(f);if(!e)return y(r("Invalid JSON")),null;let t=eF(e);return t?(y(r(t.message)),null):(y(""),e)},P=e=>{let t=ek(b),s=t;if("append"===e){let e="json"===h?B():w;if(!e)return;let a=ez(e),l=ez(t);s={advanced_routes:[...a.advanced_routes||[],...l.advanced_routes||[]]}}let a=ez(s);c(a),m(T(a.advanced_routes?.length||0)),j(eT(a)),y("")};return(0,a.jsxs)(tx.l,{open:t,onOpenChange:l,title:r("Advanced Custom Routes"),description:r("Advanced Custom"),contentClassName:"flex max-h-[90vh] flex-col gap-0 p-0 sm:max-w-5xl",headerClassName:"border-b px-6 py-4",footerClassName:"border-t px-6 py-4",contentHeight:"70vh",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{type:"button",variant:"outline",onClick:()=>l(!1),children:r("Cancel")}),(0,a.jsxs)(tg.$,{type:"button",onClick:()=>
1{if("json"===h){let e=B();return e?(n(eT(e)),void l(!1)):void g.oR.error(r("Please fix JSON errors before saving"))}I?g.oR.error(r(I.message)):(n(eT(w)),l(!1))},children:[(0,a.jsx)(tj.A,{"data-icon":"inline-start"}),r("Save changes")]})]}),children:[(0,a.jsx)("div",{className:"bg-muted/30 border-b px-4 py-3",children:(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsx)("span",{className:"text-muted-foreground text-xs font-medium",children:r("Mode")}),(0,a.jsx)(tg.$,{type:"button",variant:"visual"===h?"default":"outline",size:"sm",onClick:()=>{let e=B();if(!e)return;let t=ez(e);c(t),m(T(t.advanced_routes?.length||0)),p("visual")},children:r("Visual")}),(0,a.jsx)(tg.$,{type:"button",variant:"json"===h?"default":"outline",size:"sm",onClick:()=>{j(eT(w)),y(""),p("json")},children:r("JSON Text")}),(0,a.jsx)("div",{className:"bg-border mx-1 h-5 w-px"}),(0,a.jsx)("span",{className:"text-muted-foreground text-xs font-medium",children:r("Template")}),(0,a.jsxs)(ss.l6,{value:b,onValueChange:e=>_(e||ew["0"]?.value||""),children:[(0,a.jsx)(ss.bq,{className:"h-8 max-w-full min-w-[260px] flex-1 sm:w-[320px]",children:(0,a.jsx)(ss.yv,{className:"min-w-0 truncate",children:r(N)})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,className:ab,children:(0,a.jsx)(ss.s3,{children:ew.map(e=>(0,a.jsx)(ss.eb,{value:e.value,className:a_,children:(0,a.jsx)("span",{className:"min-w-0 leading-snug break-words whitespace-normal",children:r(e.label)})},e.value))})})]}),(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>P("fill"),children:r("Fill Template")}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>P("append"),children:r("Append Template")})]})}),"visual"===h?(0,a.jsxs)("div",{className:"flex flex-col gap-4 p-4 lg:gap-3",children:[(0,a.jsx)("div",{className:"flex justify-end border-y py-4 lg:py-2",children:(0,a.jsxs)(ss.l6,{items:R,value:null,onValueChange:e=>{"string"==typeof e&&(!e||S.has(e)||(c(t=>{let s=ez(t);return{...s,advanced_routes:[...s.advanced_routes||[],{...eC(),incoming_path:e,upstream_path:e}]}}),m(e=>[...e,O()])))},children:[(0,a.jsxs)(ss.bq,{size:"sm",disabled:0===R.length,children:[(0,a.jsx)(sK.A,{"data-icon":"inline-start"}),(0,a.jsx)(ss.yv,{placeholder:r("Add route")})]}),(0,a.jsx)(ss.gC,{align:"end",alignItemWithTrigger:!1,className:ab,children:(0,a.jsx)(ss.s3,{children:R.map(e=>(0,a.jsx)(ss.eb,{value:e.value,className:a_,children:(0,a.jsxs)("div",{className:"flex min-w-0 flex-col gap-1 leading-snug whitespace-normal",children:[(0,a.jsx)("span",{children:e.label}),(0,a.jsx)("span",{className:"text-muted-foreground font-mono text-xs break-all",children:e.value})]})},e.value))})})]})}),I?(0,a.jsx)(tC.Fc,{variant:"destructive",children:(0,a.jsxs)(tC.TN,{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("span",{children:[void 0!==I.routeIndex?`${r("Route")} ${I.routeIndex+1}: `:"",r(I.message)]}),M?(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{let e=new Map;for(let t of C){let s=aA(t.route);e.set(s,[...e.get(s)||[],t])}let t=new Map;for(let[s,a]of e)t.set(s,[...a.filter(e=>!aS(e.route)),...a.filter(e=>aS(e.route))]);let s=C.map(e=>{let s=aA(e.route),a=t.get(s);return a?.shift()||e});E(s.map(e=>e.route),s.map(e=>e.routeKey))},children:r("Fix order")}):null]})}):null,(0,a.jsx)("p",{className:"text-muted-foreground bg-muted/30 hidden rounded-md border px-3 py-2 text-xs leading-relaxed lg:block",children:r(aw)}),(0,a.jsx)("div",{className:"flex flex-col gap-4",children:A.map(e=>(0,a.jsx)(aI,{group:e,usedIncomingPaths:S,validationError:I,onAddRoute:()=>{let t;return t=e.incomingPath||"/v1/chat/completions",void(c(e=>{let s=ez(e);return{...s,advanced_routes:[...s.advanced_routes||[],{...eC(),incoming_path:t,upstream_path:t}]}}),m(e=>[...e,O()]))},onIncomingPathChange:t=>{let s,a;return s=t||"/v1/chat/completions",a=new Set(e.routeRows.map(e=>e.index)),void E(k.map((e,t)=>{if(!a.has(t))return e;if(s===eh)return{...e,incoming_path:s,upstream_path:eh,converter:"none",models:[]};
1let l=e.converter||"none";return{...e,incoming_path:s,converter:eJ(s,l)?l:"none"}}))},onMoveRoute:(e,t)=>{let s,a,l,n;return s=aA(k[e]),l=(a=k.map((e,t)=>({route:e,routeIndex:t})).filter(e=>{let{route:t}=e;return aA(t)===s}).map(e=>{let{routeIndex:t}=e;return t})).indexOf(e),void(void 0!==(n=a.at(l+t))&&((e,t)=>{if(e===t)return;let s=[...k],a=C.map(e=>e.routeKey),l=s[e];s[e]=s[t],s[t]=l;let n=a[e];a[e]=a[t],a[t]=n,E(s,a)})(e,n))},onMoveRouteToEnd:F,onRemoveRoute:$,onRouteChange:z},e.incomingPath||"advanced-custom-empty-path"))})]}):(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsx)("div",{className:"mb-2 flex items-center gap-2",children:(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:r("Advanced text editing")})}),(0,a.jsx)(sv.B,{value:f,onChange:e=>{j(e),v&&y("")},placeholder:eT(ek(b)),heightClassName:"h-[420px] min-h-[420px] max-h-[420px]","aria-invalid":!!v,ariaLabel:r("Advanced text editing")}),(0,a.jsx)("p",{className:"text-muted-foreground mt-2 text-xs",children:r("Edit JSON text directly. Format will be validated on save.")}),v?(0,a.jsx)("p",{className:"text-destructive mt-1 text-xs",children:v}):null]})]})}function aI(e){let{group:t,usedIncomingPaths:s,validationError:l,onAddRoute:n,onIncomingPathChange:r,onMoveRoute:o,onMoveRouteToEnd:c,onRemoveRoute:u,onRouteChange:m}=e,{t:h}=(0,i.Bd)(),p=t.incomingPath||"/v1/chat/completions",x=p===eh,g=eM(p),f=t.routeRows.find(e=>aS(e.route)),j=f?t.routeRows.findIndex(e=>e.index===f.index):-1,v=void 0!==f,y=!v||j===t.routeRows.length-1,b=l?.routeIndex!==void 0&&t.routeRows.some(e=>e.index===l.routeIndex);return(0,a.jsxs)("section",{className:(0,tE.cn)("border-border overflow-hidden rounded-md border",b&&"border-destructive/60"),children:[(0,a.jsxs)("div",{className:"bg-muted/20 flex flex-col gap-3 p-3 lg:flex-row lg:items-center lg:justify-between",children:[(0,a.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsx)("span",{className:"text-sm font-medium",children:h("Route group")}),(0,a.jsxs)(d.E,{variant:"secondary",children:[t.routeRows.length," ",h("Routes")]}),x?(0,a.jsx)(d.E,{variant:"outline",children:ep}):(0,a.jsx)(d.E,{variant:v?"outline":"secondary",children:h(v?"Fallback route":"Model-scoped only")}),x||y?null:(0,a.jsx)(d.E,{variant:"destructive",children:h("Fallback must be last")})]}),(0,a.jsxs)(ss.l6,{items:ef,value:p,onValueChange:r,children:[(0,a.jsx)(ss.bq,{className:"h-9 max-w-full lg:max-w-[420px]",children:(0,a.jsx)(ss.yv,{className:"min-w-0 truncate",children:g})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,className:ab,children:(0,a.jsx)(ss.s3,{children:ef.map(e=>(0,a.jsx)(ss.eb,{value:e.value,disabled:e.value!==p&&s.has(e.value)||e.value===eh&&t.routeRows.length>1,className:a_,children:(0,a.jsxs)("div",{className:"flex min-w-0 flex-col gap-1 leading-snug whitespace-normal",children:[(0,a.jsx)("span",{children:e.label}),(0,a.jsx)("span",{className:"text-muted-foreground font-mono text-xs break-all",children:e.value})]})},e.value))})})]})]}),x?null:(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:n,children:[(0,a.jsx)(sK.A,{"data-icon":"inline-start"}),h("Add split")]})]}),(0,a.jsxs)("div",{className:"border-t px-3 py-2",children:[(0,a.jsx)("p",{className:"text-muted-foreground text-xs leading-relaxed",children:h(x?"This route discovers upstream OpenAI models and cannot be split or matched by client model rules.":"Routes with the same incoming path are split by client model rules. Unmatched requests use the final fallback.")}),b&&l?(0,a.jsxs)("p",{className:"text-destructive mt-1 text-xs",children:[void 0!==l.routeIndex?`${h("Route")} ${l.routeIndex+1}: `:"",h(l.message)]}):null]}),(0,a.jsxs)("div",{className:(0,tE.cn)("text-muted-foreground hidden items-center gap-2 border-t bg-muted/10 px-3 py-2 text-xs font-medium lg:grid",aN),children:[(0,a.jsx)("span",{children:h("Route")}),(0,a.jsxs)("span",{className:"inline-flex items-center gap-1",children:[h("Client model"),(0,a.jsx)(aO,{})]}),(0,a.jsx)("span",{children:h("Upstream path")}),(0,a.jsx)("span",{children:h("Converter")}),(0,a.jsx)("span",{children:h("Auth")}),(0,a.jsx)("span",{className:"text-right",children:h("Actions")})]}),(0,a.jsx)("div",{className:"divide-y",children:t.routeRows.map((e,s)=>{let n=s<t.routeRows.length-1,r=aS(e.route)&&n,i=l?.routeIndex===e.index?l.message:void 0;return(0,a.jsx)(aM,{route:e.route,index:e.index,errorMessage:i,canMoveUp:s>0,canMoveDown:n,catchAllOutOfOrder:r,onChange:t=>m(e.index,t),onMoveDown:()=>o(e.index,1),onMoveUp:()=>o(e.index,-1),onMoveCatchAllToEnd:()=>c(e.index),onRemove:()=>u(e.index)},e.routeKey)})})]})}function aM(e){let{route:t,index:s,errorMessage:l,canMoveUp:n,canMoveDown:r,catchAllOutOfOrder:o,onChange:u,onMoveUp:m,onMoveDown:h,onMoveCatchAllToEnd:p,onRemove:g}=e,{t:f}
1=(0,i.Bd)(),j=t.converter||"none",v=t.auth?.type||"default",y=t.incoming_path||eI(j),b=y===eh,_=(0,x.useMemo)(()=>{let e;return e=y.trim(),ex.filter(t=>"none"===t.value||eJ(e,t.value))},[y]),N=aC(ex,j),w=ex.find(e=>e.value===j)?.triggerLabel||N,k=aC(eg,v),C="none"===j,A=C?s9.A:ag.A,S=t.models?.join(", ")||"",R=eE(S),I=!b&&0===R.length,M=(e,s)=>{let a=t.auth;a&&"none"!==a.type&&u({auth:{type:a.type,name:a.name||"",value:a.value||"",[e]:s}})};return(0,a.jsxs)("div",{className:(0,tE.cn)("flex flex-col gap-4 px-4 py-4 lg:gap-2 lg:px-3 lg:py-3",l&&"bg-destructive/5"),children:[(0,a.jsxs)("div",{className:(0,tE.cn)("grid gap-4 md:grid-cols-2 lg:items-center lg:gap-2",aN),children:[(0,a.jsxs)("div",{className:"flex min-w-0 items-start justify-between gap-3 md:col-span-2 lg:col-span-1",children:[(0,a.jsx)("div",{className:"min-w-0 space-y-2 lg:space-y-1",children:(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsxs)("div",{className:"text-sm font-medium",children:[f("Route")," ",s+1]}),b?(0,a.jsx)(d.E,{variant:"outline",children:ep}):null,!b&&I?(0,a.jsx)(d.E,{variant:"outline",children:f("Fallback")}):null,(0,a.jsx)(c.Bc,{delay:100,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)("span",{className:(0,tE.cn)("border-border inline-flex size-7 shrink-0 items-center justify-center rounded-md border",C?"bg-secondary text-secondary-foreground":"bg-muted text-foreground")}),children:[(0,a.jsx)(A,{className:"size-3.5","aria-hidden":"true"}),(0,a.jsx)("span",{className:"sr-only",children:f(N)})]}),(0,a.jsx)(c.ZI,{side:"top",children:f(N)})]})})]})}),(0,a.jsxs)("div",{className:"flex shrink-0 items-center gap-1 lg:hidden",children:[(0,a.jsx)(aT,{label:f("Move route up"),icon:af.A,disabled:!n,onClick:m}),(0,a.jsx)(aT,{label:f("Move route down"),icon:aj.A,disabled:!r,onClick:h}),o?(0,a.jsx)(aT,{label:f("Move fallback to end"),icon:av.A,onClick:p}):null,(0,a.jsx)(aT,{label:f("Delete"),icon:t5.A,onClick:g})]})]}),(0,a.jsx)(az,{label:(0,a.jsxs)("span",{className:"inline-flex items-center gap-1",children:[f("Client model"),(0,a.jsx)(aO,{})]}),className:"lg:gap-1",labelClassName:"lg:sr-only",children:b&&0===R.length?(0,a.jsx)("div",{className:"flex h-9 items-center",children:(0,a.jsx)(d.E,{variant:"outline",children:ep})}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(se.p,{value:S,onChange:e=>{var t;u({models:""===(t=e.target.value)?[]:t.split(",")})},onBlur:e=>{u({models:eE(e.target.value)})},placeholder:I?f("Leave empty for fallback"):f("e.g. gpt-4o, gemini-2.5-flash"),"aria-invalid":!!l}),(0,a.jsx)("div",{className:"flex flex-wrap gap-1",children:I?(0,a.jsx)(d.E,{variant:"outline",children:f("Fallback")}):R.map(e=>{let t=e$(e),s="regex"===t&&e.slice(3)||e;return(0,a.jsxs)(d.E,{variant:"regex"===t?"outline":"secondary",className:"max-w-full gap-1.5 font-mono",children:[(0,a.jsx)("span",{className:"font-sans text-[10px] font-semibold tracking-normal uppercase",children:f("regex"===t?"Regex":"Exact")}),(0,a.jsx)("span",{className:"truncate",children:s})]},e)})})]})}),(0,a.jsxs)(az,{label:f("Upstream path"),className:"lg:gap-1",labelClassName:"lg:sr-only",children:[(0,a.jsx)(se.p,{value:t.upstream_path||"",onChange:e=>u({upstream_path:e.target.value}),placeholder:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eI(e);return eS(e,t).upstream_path}(j,y)}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs leading-relaxed lg:hidden",children:f(aw)})]}),(0,a.jsx)(az,{label:f("Converter"),className:"lg:gap-1",labelClassName:"lg:sr-only",children:(0,a.jsxs)(ss.l6,{value:j,disabled:b&&"none"===j,onValueChange:e=>{var t;let s,a;return t=e,eJ(s=y,t)||(s=eI(t)),a=eS(t,s),void u({converter:t,incoming_path:s,upstream_path:a.upstream_path,auth:a.auth})},children:[(0,a.jsx)(ss.bq,{className:"w-full max-w-full lg:h-8",children:(0,a.jsx)(ss.yv,{className:"min-w-0 truncate",children:f(w)})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,className:ab,children:(0,a.jsx)(ss.s3,{children:_.map(e=>(0,a.jsx)(ss.eb,{value:e.value,className:a_,children:(0,a.jsx)("span",{className:"min-w-0 leading-snug break-words whitespace-normal",children:f(e.label)})},e.value))})})]})}),(0,a.jsx)(az,{label:f("Auth"),className:"lg:gap-1",labelClassName:"lg:sr-only",children:(0,a.jsxs)(ss.l6,{value:v,onValueChange:e=>{u({auth:function(e,t){if("default"!==e)return"none"===e?{type:"none"}:"header"===e?{type:"header",name:t?.name||"Authorization",value:t?.value||"Bearer {api_key}"}:{type:"query",name:t?.name||"api_key",value:t?.value||"{api_key}"}}(e,t.auth)})},children:[(0,a.jsx)(ss.bq,{className:"w-full max-w-full lg:h-8",children:(0,a.jsx)(ss.yv,{className:"min-w-0 truncate",children:f(k)})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:eg.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:f(e.label)},e.value))})})]})}),(0,a.jsxs)("div",{className:"hidden items-center justify-end gap-1 lg:flex",children:[(0,a.jsx)(aT,{label:f("Move route up"),icon:af.A,disabled:!n,onClick:m}),(0,a.jsx)(aT,{label:f("Move route down"),icon:aj.A,disabled:!r,onClick:h}),o?(0,a.jsx)(aT,{label:f("Move fallback to end"),icon:av.A,onClick:p}):null,(0,a.jsx)(aT,{label:f("Delete"),icon:t5.A,onClick:g})]})]}),l?(0,a.jsx)("p",{className:"text-destructive text-xs",children:f(l)}):null,"header"===v||"query"===v?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(sy.w,{className:"lg:hidden"}),(0,a.jsxs)("div",{className:(0,tE.cn)("grid gap-4 md:grid-cols-2 lg:items-end lg:gap-2 lg:border-t lg:pt-2",aN),children:[(0,a.jsx)("span",{className:"hidden lg:block","aria-hidden":"true"}),(0,a.jsx)(az,{label:f("Auth name"),className:"lg:gap-1",labelClassName:"lg:text-xs",children:(0,a.jsx)(se.p,{value:t.auth?.name||"",onChange:e=>M("name",e.target.value),placeholder:"header"===v?"Authorization":"api_key"})}),(0,a.jsx)(az,{label:f("Auth value"),className:"lg:gap-1",labelClassName:"lg:text-xs",children:(0,a.jsx)(se.p,{value:t.auth?.value||"",onChange:e=>M("value",e.target.value),placeholder:"header"===v?"Bearer {api_key}":"{api_key}"})}),(0,a.jsx)("span",{className:"hidden lg:block","aria-hidden":"true"}),(0,a.jsx)("span",{className:"hidden lg:block","aria-hidden":"true"}),(0,a.jsx)("span",{className:"hidden lg:block","aria-hidden":"true"})]})]}):null]})}function aO(){let{t:e}=(0,i.Bd)();return(0,a.jsxs)(ay.AM,{children:[(0,a.jsx)(ay.Wv,{render:(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-foreground size-6","aria-label":e("Client model matching help")}),children:(0,a.jsx)(t6.A,{className:"size-3.5","aria-hidden":"true"})}),(0,a.jsxs)(ay.hl,{align:"start",side:"bottom",sideOffset:8,className:"w-[min(22rem,calc(100vw-2rem))] gap-3 p-3",children:[(0,a.jsxs)(ay.DI,{className:"gap-1",children:[(0,a.jsx)(ay.eO,{children:e("Client model matching")}),(0,a.jsx)(ay.ui,{className:"text-xs leading-relaxed",children:e("Rules match the original model value from the client request body.")})]}),(0,a.jsxs)("div",{className:"text-muted-foreground space-y-2 text-xs leading-relaxed",children:[(0,a.jsx)("p",{children:e("Use exact model names such as gpt-4o, or regex rules prefixed with re: such as re:^gemini-.")}),(0,a.jsx)("p",{children:e("Separate multiple rules with English commas. For regex patterns that need commas, switch to JSON Text.")}),(0,a.jsx)("p",{children:e("Leave the final split empty as the fallback for models not matched above.")})]})]})]})}function aT(e){let{label:t,icon:s,disabled:l,onClick:n}=e;return(0,a.jsx)(c.Bc,{delay:100,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"icon",disabled:l,onClick:n}
1),children:[(0,a.jsx)(s,{"data-icon":"inline-start","aria-hidden":"true"}),(0,a.jsx)("span",{className:"sr-only",children:t})]}),(0,a.jsx)(c.ZI,{side:"top",children:t})]})})}function az(e){let{label:t,className:s,labelClassName:l,children:n}=e;return(0,a.jsxs)("div",{className:(0,tE.cn)("flex min-w-0 flex-col gap-2",s),children:[(0,a.jsx)("span",{className:(0,tE.cn)("text-sm font-medium",l),children:t}),n]})}function aE(e){let{open:t,missingModels:s,onConfirm:l,onOpenChange:n}=e,{t:r}=(0,i.Bd)();return(0,a.jsx)(sT.Lt,{open:t,onOpenChange:e=>{e||l("cancel"),n?.(e)},children:(0,a.jsxs)(sT.EO,{children:[(0,a.jsxs)(sT.wd,{children:[(0,a.jsx)(sT.r7,{children:r("Models not in list, may fail to invoke")}),(0,a.jsxs)(sT.$v,{render:(0,a.jsx)("div",{className:"space-y-3 text-sm"}),children:[(0,a.jsx)("div",{children:r('The following models in the model redirect have not been added to the "Models" list and may fail during invocation due to missing available models:')}),(0,a.jsx)("div",{className:"rounded-md bg-red-50 p-2 font-mono text-xs break-all text-red-600 dark:bg-red-950/50 dark:text-red-400",children:s.join(", ")}),(0,a.jsx)("div",{children:r('You can manually add them in "Custom Model Names", click "Fill" and then submit, or use the operations below to handle automatically.')})]})]}),(0,a.jsxs)(sT.ck,{className:"flex-col gap-2 sm:flex-row",children:[(0,a.jsx)(sT.Zr,{onClick:()=>l("cancel"),children:r("Go back and edit")}),(0,a.jsx)(tg.$,{variant:"secondary",onClick:()=>l("submit"),children:r("Submit directly")}),(0,a.jsx)(sT.Rx,{onClick:()=>l("add"),children:r("Add and submit")})]})]})})}var a$=s(90685);let aF=[{label:"Set Field",value:"set"},{label:"Delete Field",value:"delete"},{label:"Append to End",value:"append"},{label:"Prepend to Start",value:"prepend"},{label:"Copy Field",value:"copy"},{label:"Move Field",value:"move"},{label:"String Replace",value:"replace"},{label:"Regex Replace",value:"regex_replace"},{label:"Trim Prefix",value:"trim_prefix"},{label:"Trim Suffix",value:"trim_suffix"},{label:"Ensure Prefix",value:"ensure_prefix"},{label:"Ensure Suffix",value:"ensure_suffix"},{label:"Trim Space",value:"trim_space"},{label:"To Lowercase",value:"to_lower"},{label:"To Uppercase",value:"to_upper"},{label:"Return Custom Error",value:"return_error"},{label:"Prune Object Items",value:"prune_objects"},{label:"Pass Through Headers",value:"pass_headers"},{label:"Sync Fields",value:"sync_fields"},{label:"Set Request Header",value:"set_header"},{label:"Delete Request Header",value:"delete_header"},{label:"Copy Request Header",value:"copy_header"},{label:"Move Request Header",value:"move_header"}],aB=new Set(aF.map(e=>e.value)),aP=aF.reduce((e,t)=>(e[t.value]=t.label,e),{}),aD=[{label:"Exact Match",value:"full"},{label:"Prefix",value:"prefix"},{label:"Suffix",value:"suffix"},{label:"Contains",value:"contains"},{label:"Greater Than",value:"gt"},{label:"Greater Than or Equal",value:"gte"},{label:"Less Than",value:"lt"},{label:"Less Than or Equal",value:"lte"}],aJ=new Set(aD.map(e=>e.value)),aq={delete:{path:!0},set:{path:!0,value:!0,keepOrigin:!0},append:{path:!0,value:!0,keepOrigin:!0},prepend:{path:!0,value:!0,keepOrigin:!0},copy:{from:!0,to:!0},move:{from:!0,to:!0},replace:{path:!0,from:!0,to:!1},regex_replace:{path:!0,from:!0,to:!1},trim_prefix:{path:!0,value:!0},trim_suffix:{path:!0,value:!0},ensure_prefix:{path:!0,value:!0},ensure_suffix:{path:!0,value:!0},trim_space:{path:!0},to_lower:{path:!0},to_upper:{path:!0},return_error:{value:!0},prune_objects:{pathOptional:!0,value:!0},pass_headers:{value:!0,keepOrigin:!0},sync_fields:{from:!0,to:!0},set_header:{path:!0,value:!0,keepOrigin:!0},delete_header:{path:!0},copy_header:{from:!0,to:!0,keepOrigin:!0,pathAlias:!0},move_header:{from:!0,to:!0,keepOrigin:!0,pathAlias:!0}},aL=new Set(["trim_prefix","trim_suffix","ensure_prefix","ensure_suffix","set_header","return_error","prune_objects","pass_headers"]),aV=new Set(["copy","move","replace","regex_replace","copy_header","move_header","sync_fields"]),aK=new Set(["copy","move","copy_header","move_header","sync_fields"]),aW={set:"Write value to the target field",delete:"Remove the target field",append:"Append value to array / string / object end",prepend:"Prepend value to array / string / object start",copy:"Copy source field to target field",move:"Move source field to target field",replace:"Do string replacement in the target field",regex_replace:"Do regex replacement in the target field",trim_prefix:"Remove string prefix",trim_suffix:"Remove string suffix",ensure_prefix:"Ensure the string has a specified prefix",ensure_suffix:"Ensure the string has a specified suffix",trim_space:"Trim leading/trailing whitespace",to_lower:"Convert string to lowercase",to_upper:"Convert string to uppercase",return_error:"Return a custom error immediately",prune_objects:"Prune object items by conditions",pass_headers:"Pass specified request headers to upstream",sync_fields:"Auto-fill when one field exists and another is missing",set_header:"Set runtime request header: override entire value, or manipulate comma-separated tokens",delete_header:"Delete a runtime request header",copy_header:"Copy a request header",move_header:"Move a request header"},aU=[{label:"Request Body Field",value:"json"},{label:"Request Header Field",value:"header"}],aH={temperature:0,max_tokens:1e3},aG={operations:[{description:"Set default temperature for openai/* models.",path:"temperature",mode:"set",value:.7,conditions:[{path:"model",mode:"prefix",value:"openai/"}],logic:"AND"}]},aY={operations_default:{label:"New Format Template",kind:"operations",payload:aG},legacy_default:{label:"Legacy Format Template",kind:"legacy",payload:aH},pass_headers_auth:{label:"Header Passthrough (X-Request-Id)",kind:"operations",payload:{operations:[{description:"Pass through X-Request-Id header to upstream.",mode:"pass_headers",value:["X-Request-Id"],keep_origin:!0}]}},gemini_image_4k:{label:"Gemini Image 4K",kind:"operations",payload:{operations:[{description:"Set imageSize to 4K when model contains gemini/image and ends with 4k.",mode:"set",path:"generationConfig.imageConfig.imageSize",value:"4K",conditions:[{path:"original_model",mode:"contains",value:"gemini"},{path:"original_model",mode:"contains",value:"image"},{path:"original_model",mode:"suffix",value:"4k"}],logic:"AND"}]}},claude_cli_headers_passthrough:{label:"Claude CLI Header Passthrough",kind:"operations",payload:{operations:[{mode:"pass_headers",value:["X-Stainless-Arch","X-Stainless-Lang","X-Stainless-Os","X-Stainless-Package-Version","X-Stainless-Retry-Count","X-Stainless-Runtime","X-Stainless-Runtime-Version","X-Stainless-Timeout","User-Agent","X-App","Anthropic-Beta","Anthropic-Dangerous-Direct-Browser-Access","Anthropic-Version"],keep_origin:!0}]}},codex_cli_headers_passthrough:{label:"Codex CLI Header Passthrough",kind:"operations",payload:{operations:[{mode:"pass_headers",value:["Originator","Session_id","Thread_id","Session-Id","Thread-Id","X-Client-Request-Id","User-Agent","X-Codex-Beta-Features","X-Codex-Turn-State","X-Codex-Turn-Metadata","X-Codex-Window-Id","X-Codex-Parent-Thread-Id","X-OpenAI-Subagent","X-OpenAI-Memgen-Request","X-ResponsesAPI-Include-Timing-Metrics","X-OpenAI-Internal-Codex-Responses-Lite"],keep_origin:!0}]}},aws_bedrock_anthropic_beta_override:{label:"AWS Bedrock Claude Compat",kind:"operations",payload:{operations:[{description:"Normalize anthropic-beta header tokens for Bedrock compatibility.",mode:"set_header",path:"anthropic-beta",value:{"advanced-tool-use-2025-11-20":"tool-search-tool-2025-10-19",bash_20241022:null,bas
1h_20250124:null,"code-execution-2025-08-25":null,"compact-2026-01-12":"compact-2026-01-12","computer-use-2025-01-24":"computer-use-2025-01-24","computer-use-2025-11-24":"computer-use-2025-11-24","context-1m-2025-08-07":"context-1m-2025-08-07","context-management-2025-06-27":"context-management-2025-06-27","effort-2025-11-24":null,"fast-mode-2026-02-01":null,"files-api-2025-04-14":null,"fine-grained-tool-streaming-2025-05-14":null,"interleaved-thinking-2025-05-14":"interleaved-thinking-2025-05-14","mcp-client-2025-11-20":null,"mcp-client-2025-04-04":null,"mcp-servers-2025-12-04":null,"output-128k-2025-02-19":null,"structured-output-2024-03-01":null,"prompt-caching-scope-2026-01-05":null,"skills-2025-10-02":null,"structured-outputs-2025-11-13":null,text_editor_20241022:null,text_editor_20250124:null,"token-efficient-tools-2025-02-19":null,"tool-search-tool-2025-10-19":"tool-search-tool-2025-10-19","web-fetch-2025-09-10":null,"web-search-2025-03-05":null,"oauth-2025-04-20":null}},{description:"Remove all tools[*].custom.input_examples before upstream relay.",mode:"delete",path:"tools.*.custom.input_examples"}]}}},aZ=0,aQ=()=>`po_${Date.now()}_${aZ++}`,aX=e=>{if(void 0===e)return"";if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}},a0=e=>{let t=String(e??"").trim();if(""===t)return"";try{return JSON.parse(t)}catch{return t}},a1=e=>{try{return JSON.parse(e),!0}catch{return!1}},a2=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:aQ(),path:"string"==typeof e.path?e.path:"",mode:aJ.has(e.mode)?e.mode:"full",value_text:aX(e.value),invert:!0===e.invert,pass_missing_key:!0===e.pass_missing_key}},a4=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:aQ(),description:"string"==typeof e.description?e.description:"",path:"str
1ing"==typeof e.path?e.path:"",mode:aB.has(e.mode)?e.mode:"set",value_text:aX(e.value),keep_origin:!0===e.keep_origin,from:"string"==typeof e.from?e.from:"",to:"string"==typeof e.to?e.to:"",logic:"AND"===String(e.logic||"OR").toUpperCase()?"AND":"OR",conditions:Array.isArray(e.conditions)?e.conditions.map(a2):[]}},a5=()=>a4({mode:"set"}),a3=function(e,t,s){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"before";if(!t||!s||t===s)return e;let l=e.findIndex(e=>e.id===t);if(l<0)return e;let n=[...e],[r]=n.splice(l,1),i=n.findIndex(e=>e.id===s);return i<0?e:("after"===a&&(i+=1),n.splice(i,0,r),n)},a6=e=>{let t=e.conditions.some(e=>e.path.trim()||e.value_text.trim()||"full"!==e.mode||e.invert||e.pass_missing_key);return"set"===e.mode&&!e.path.trim()&&!e.from.trim()&&!e.to.trim()&&""===e.value_text.trim()&&!e.keep_origin&&!t},a8=(e,t)=>{let s=e.mode||"set",a=aP[s]||s;if("sync_fields"===s){let s=e.from.trim(),l=e.to.trim();return`${t+1}. ${a} \xb7 ${s||l||"-"}`}let l=e.path.trim(),n=e.from.trim(),r=e.to.trim();return`${t+1}. ${a} \xb7 ${l||n||r||"-"}`},a7=e=>e.includes("header")?"bg-cyan-500/15 text-cyan-700 dark:text-cyan-300 border-cyan-500/20":e.includes("replace")||e.includes("trim")?"bg-violet-500/15 text-violet-700 dark:text-violet-300 border-violet-500/20":e.includes("copy")||e.includes("move")?"bg-blue-500/15 text-blue-700 dark:text-blue-300 border-blue-500/20":e.includes("error")||e.includes("prune")?"bg-red-500/15 text-red-700 dark:text-red-300 border-red-500/20":e.includes("sync")?"bg-green-500/15 text-green-700 dark:text-green-300 border-green-500/20":"bg-muted text-muted-foreground",a9=e=>{let t=String(e??"").trim();if(!t)return{type:"json",key:""};let s=t.indexOf(":");if(s<0)return{type:"json",key:t};let a=t.slice(0,s).trim().toLowerCase(),l=t.slice(s+1).trim();return"header"===a?{type:"header",key:l}:{type:"json",key:l}},le=(e,t)=>{let s=String(t??"").trim();return s?`${"header"===e?"header":"json"}:${s}`:""},lt=e=>{let t={message:"",statusCode:400,code:"",type:"",skipRetry:!0,simpleMode:!0},s=String(e??"").trim();if(!s)return t;try{let e=JSON.parse(s);if(e&&"object"==typeof e&&!Array.isArray(e)){let s=void 0!==e.status_code?e.status_code:e.status,a=Number(s);return{...t,message:String(e.message||e.msg||"").trim(),statusCode:Number.isInteger(a)&&a>=100&&a<=599?a:400,code:String(e.code||"").trim(),type:String(e.type||"").trim(),skipRetry:!1!==e.skip_retry,simpleMode:!1}}}catch{}return{...t,message:s,simpleMode:!0}},ls=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:aQ(),path:"string"==typeof e.path?e.path:"",mode:aJ.has(e.mode)?e.mode:"full",value_text:aX(e.value),invert:!0===e.invert,pass_missing_key:!0===e.pass_missing_key}},la=e=>{let t={simpleMode:!0,typeText:"",logic:"AND",recursive:!0,rules:[]},s=String(e??"").trim();if(!s)return t;try{let e=JSON.parse(s);if("string"==typeof e)return{...t,typeText:e.trim()};if(e&&"object"==typeof e&&!Array.isArray(e)){let s=[];if(e.where&&"object"==typeof e.where&&!Array.isArray(e.where))for(let[t,a]of Object.entries(e.where))s.push(ls({path:t,mode:"full",value:a}));if(Array.isArray(e.conditions))for(let t of e.conditions)t&&"object"==typeof t&&s.push(ls(t));else if(e.conditions&&"object"==typeof e.conditions&&!Array.isArray(e.conditions))for(let[t,a]of Object.entries(e.conditions))s.push(ls({path:t,mode:"full",value:a}));let a=void 0===e.type?"":String(e.type).trim(),l="OR"===String(e.logic||"AND").toUpperCase()?"OR":"AND",n=!1!==e.recursive,r=void 0!==e.logic||void 0!==e.recursive||void 0!==e.where||void 0!==e.conditions;return{...t,simpleMode:!r,typeText:a,logic:l,recursive:n,rules:s}}return{...t,typeText:String(e??"").trim()}}catch{return{...t,typeText:s}}},ll=e=>{if(Array.isArray(e))return e.map(e=>String(e??"").trim()).filter(Boolean);if(e&&"object"==typeof e){if(Array.isArray(e.headers))return e.headers.map(e=>String(e??"").trim()).filter(Boolean);if(void 0!==e.header){let t=String(e.header??"").trim();return t?[t]:[]}return[]}return"string"==typeof e?e.split(",").map(e=>e.trim()).filter(Boolean):[]},ln=e=>{let t=e.path.trim();if(!t)return null;let s={path:t,mode:e.mode||"full",value:a0(e.value_text)};return e.invert&&(s.invert=!0),e.pass_missing_key&&(s.pass_missing_key=!0),s},lr=(e,t,s)=>{let a=e.filter(e=>!a6(e));if(0===a.length)return"";if(t.validate){let e=((e,t)=>{for(let s=0;s<e.length;s++){let a=e[s],l=a.mode||"set",n=aq[l]||aq.set,r=s+1,i=a.path.trim(),o=a.from.trim(),d=a.to.trim();if(n.path&&!i)return t("Rule {{line}} is missing target path",{line:r});if(aV.has(l)&&!o&&!(n.pathAlias&&i))return t("Rule {{line}} is missing source field",{line:r});if(aK.has(l)&&!d&&!(n.pathAlias&&i))return t("Rule {{line}} is missing target field",{line:r});if(aL.has(l)&&""===a.value_text.trim())return t("Rule {{line}} is missing value",{line:r});if("return_error"===l){let e=a.value_text.trim();if(!e)return t("Rule {{line}} is missing value",{line:r});try{let s=JSON.parse(e);if(s&&"object"==typeof s&&!Array.isArray(s)&&!String(s.message||"").trim())return t("Rule {{line}} return_error requires a message field",{line:r})}catch{}}if("prune_objects"===l&&!a.value_text.trim())return t("Rule {{line}} prune_objects is missing conditions",{line:r});if("pass_headers"===l){let e=a.value_text.trim();if(!e)return t("Rule {{line}} pass_headers is missing header names",{line:r});if(0===ll(a0(e)).length)return t("Rule {{line}}
1 pass_headers format is invalid",{line:r})}}return""})(a,s);if(e)throw Error(e)}return JSON.stringify({operations:a.map(e=>{let t=e.mode||"set",s=aq[t]||aq.set,a=String(e.description||"").trim(),l=e.path.trim(),n=e.from.trim(),r=e.to.trim(),i={mode:t};a&&(i.description=a),s.path&&(i.path=l),s.pathOptional&&l&&(i.path=l),s.value&&(i.value=a0(e.value_text)),s.keepOrigin&&e.keep_origin&&(i.keep_origin=!0),s.from&&(i.from=n),!s.to&&e.to.trim()&&(i.to=r),s.to&&(i.to=r),s.pathAlias&&(!i.from&&l&&(i.from=l),!i.to&&l&&(i.to=l));let o=e.conditions.map(ln).filter(Boolean);return o.length>0&&(i.conditions=o,i.logic="AND"===e.logic?"AND":"OR"),i})},null,2)};function li(e){let{t}=(0,i.Bd)(),[s,l]=(0,x.useState)("visual"),[n,r]=(0,x.useState)("operations"),[o,c]=(0,x.useState)(""),[u,m]=(0,x.useState)([a5()]),[h,p]=(0,x.useState)(""),[f,j]=(0,x.useState)(""),[v,y]=(0,x.useState)(""),[b,_]=(0,x.useState)(""),[N,w]=(0,x.useState)({}),[k,C]=(0,x.useState)(""),[A,S]=(0,x.useState)(""),[R,I]=(0,x.useState)("before"),[M,O]=(0,x.useState)("operations_default");(0,x.useEffect)(()=>{if(!e.open)return;let t=(e=>{let t="string"==typeof e?e:"",s=t.trim();if(!s)return{editMode:"visual",visualMode:"operations",legacyValue:"",operations:[a5()],jsonText:"",jsonError:""};if(!a1(s))return{editMode:"json",visualMode:"operations",legacyValue:"",operations:[a5()],jsonText:t,jsonError:"Invalid JSON format"};let a=JSON.parse(s),l=JSON.stringify(a,null,2);return a&&"object"==typeof a&&!Array.isArray(a)&&Array.isArray(a.operations)?{editMode:"visual",visualMode:"operations",legacyValue:"",operations:a.operations.length>0?a.operations.map(a4):[a5()],jsonText:l,jsonError:""}:a&&"object"==typeof a&&!Array.isArray(a)?{editMode:"visual",visualMode:"legacy",legacyValue:l,operations:[a5()],jsonText:l,jsonError:""}:{editMode:"json",visualMode:"operations",legacyValue:"",operations:[a5()],jsonText:l,jsonError:""}})(e.value);l(t.editMode),r(t.visualMode),c(t.legacyValue),m(t.operations),p(t.jsonText),j(t.jsonError),y(""),_(t.operations[0]?.id||""),w({}),C(""),S(""),I("before"),"legacy"===t.visualMode?O("legacy_default"):O("operations_default")},[e.open,e.value]),(0,x.useEffect)(()=>{0===u.length?_(""):u.some(e=>e.id===b)||_(u[0].id)},[u,b]);let T=(0,x.useMemo)(()=>Object.entries(aY).map(e=>{let[t,s]=e;return{value:t,label:s.label}}),[]),z=(0,x.useMemo)(()=>u.filter(e=>!a6(e)).length,[u]),E=(0,x.useMemo)(()=>{let e=v.trim().toLowerCase();return e?u.filter(t=>[t.description,t.mode,t.path,t.from,t.to,t.value_text].filter(Boolean).join(" ").toLowerCase().includes(e)):u},[v,u]),$=(0,x.useMemo)(()=>u.find(e=>e.id===b),[u,b]),F=(0,x.useMemo)(()=>u.findIndex(e=>e.id===b),[u,b]),B=(0,x.useMemo)(()=>$&&"return_error"===$.mode?lt($.value_text):null,[$]),P=(0,x.useMemo)(()=>$&&"prune_objects"===$.mode?la($.value_text):null,[$]),D=(0,x.useMemo)(()=>{let e={};for(let t of u){let s=t.mode||"set";e[s]=(e[s]||0)+1}return Object.entries(e).sort((e,t)=>t[1]-e[1]).slice(0,4)},[u]),J=(0,x.useCallback)((e,t)=>{m(s=>s.map(s=>s.id===e?{...s,...t}:s))},[]),q=(0,x.useCallback)(()=>{let e=a5();m(t=>[...t,e]),_(e.id)},[]),L=(0,x.useCallback)(e=>{let t="";m(s=>{let a=s.findIndex(t=>t.id===e);if(a<0)return s;let l=s[a],n=a4({description:l.description,path:l.path,mode:l.mode,value:a0(l.value_text),keep_origin:l.keep_origin,from:l.from,to:l.to,logic:l.logic,conditions:l.conditions.map(e=>({path:e.path,mode:e.mode,value:a0(e.value_text),invert:e.invert,pass_missing_key:e.pass_missing_key}))});t=n.id;let r=[...s];return r.splice(a+1,0,n),r}),t&&_(t)},[]),V=(0,x.useCallback)(e=>{m(t=>t.length<=1?[a5()]:t.filter(t=>t.id!==e))},[]),K=(0,x.useCallback)(e=>{let t=a2({});m(s=>s.map(s=>s.id===e?{...s,conditions:[...s.conditions,t]}:s)),w(e=>({...e,[t.id]:!0}))},[]),W=(0,x.useCallback)((e,t,s)=>{m(a=>a.map(a=>a.id===e?{...a,conditions:a.conditions.map(e=>e.id===t?{...e,...s}:e)}:a))},[]),U=(0,x.useCallback)((e,t)=>{m(s=>s.map(s=>s.id===e?{...s,conditions:s.conditions.filter(e=>e.id!==t)}:s))},[]),H=(0,x.useCallback)((e,t)=>{m(s=>s.map(s=>{if(s.id!==e)return s;let a={...lt(s.value_text),...t};return{...s,value_text:(e=>{let t=String(e.message||"").trim();if(e.simpleMode)return t;let s=Number(e.statusCode),a={message:t,status_code:Number.isInteger(s)&&s>=100&&s<=599?s:400},l=String(e.code||"").trim(),n=String(e.type||"").trim();
1return l&&(a.code=l),n&&(a.type=n),!1===e.skipRetry&&(a.skip_retry=!1),JSON.stringify(a)})(a)}}))},[]),G=(0,x.useCallback)((e,t)=>{m(s=>s.map(s=>{if(s.id!==e)return s;let a=la(s.value_text),l="function"==typeof t?t(a):{...a,...t};return{...s,value_text:(e=>{let t=String(e.typeText||"").trim();if(e.simpleMode)return t;let s={};t&&(s.type=t),"OR"===String(e.logic||"AND").toUpperCase()&&(s.logic="OR"),!1===e.recursive&&(s.recursive=!1);let a=(e.rules||[]).filter(e=>String(e.path||"").trim()).map(e=>{let t={path:String(e.path||"").trim(),mode:aJ.has(e.mode)?e.mode:"full"},s=String(e.value_text||"").trim();return""!==s&&(t.value=a0(s)),e.invert&&(t.invert=!0),e.pass_missing_key&&(t.pass_missing_key=!0),t});return(a.length>0&&(s.conditions=a),s.type||s.conditions)?JSON.stringify(s):JSON.stringify({logic:"AND"})})(l)}}))},[]),Y=(0,x.useCallback)(e=>{G(e,e=>({...e,simpleMode:!1,rules:[...e.rules,ls({})]}))},[G]),Z=(0,x.useCallback)((e,t,s)=>{G(e,e=>({...e,rules:e.rules.map(e=>e.id===t?{...e,...s}:e)}))},[G]),Q=(0,x.useCallback)((e,t)=>{G(e,e=>({...e,rules:e.rules.filter(e=>e.id!==t)}))},[G]),X=(0,x.useCallback)(()=>{C(""),S(""),I("before")},[]),ee=(0,x.useCallback)((e,t)=>{C(t),_(t),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",t)},[]),et=(0,x.useCallback)((e,t)=>{if(e.preventDefault(),!k||k===t)return;let s=e.currentTarget.getBoundingClientRect(),a=e.clientY-s.top>s.height/2?"after":"before";S(t),I(a),e.dataTransfer.dropEffect="move"},[k]),es=(0,x.useCallback)((e,t)=>{e.preventDefault();let s=k||e.dataTransfer.getData("text/plain"),a=A===t?R:"before";s&&t&&s!==t&&(m(e=>a3(e,s,t,a)),_(s)),X()},[k,A,R,X]),ea=(0,x.useCallback)(()=>{if("legacy"===n){let e=o.trim();if(!e)return"";if(!a1(e))throw Error(t("Parameter override must be valid JSON format"));let s=JSON.parse(e);if(!s||"object"!=typeof s||Array.isArray(s))throw Error(t("Legacy format must be a JSON object"));return JSON.stringify(s,null,2)}return lr(u,{validate:!0},t)},[o,u,t,n]),el=(0,x.useCallback)(()=>{if("json"!==s){try{p(ea()),j("")}catch(e){g.oR.error(e.message),"legacy"===n?p(o):p(lr(u,{validate:!1},t)),j(e.message||t("Parameter configuration error"))}l("json")}},[ea,s,o,u,t,n]),en=(0,x.useCallback)(()=>{if("visual"===s)return;let e=h.trim();if(!e){let e=a5();r("operations"),m([e]),_(e.id),c(""),j(""),l("visual");return}if(!a1(e))return void g.oR.error(t("Parameter override must be valid JSON format"));let a=JSON.parse(e);if(a&&"object"==typeof a&&!Array.isArray(a)&&Array.isArray(a.operations)){let e=a.operations.length>0?a.operations.map(a4):[a5()];r("operations"),m(e),_(e[0]?.id||""),c(""),j(""),l("visual"),O("operations_default");return}if(a&&"object"==typeof a&&!Array.isArray(a)){let e=a5();r("legacy"),c(JSON.stringify(a,null,2)),m([e]),_(e.id),j(""),l("visual"),O("legacy_default");return}g.oR.error(t("Parameter override must be a valid JSON object"))},[s,h,t]),er=(0,x.useCallback)(e=>{let s=aY[M]||aY.operations_default,a=s.payload;if("legacy"===s.kind){if("append"===e&&"legacy"===n){let e=o.trim(),s={};if(e){if(!a1(e))return void g.oR.error(t("Current legacy JSON is invali
1d, cannot append"));s=JSON.parse(e)}let n=JSON.stringify({...a||{},...s},null,2);r("legacy"),c(n),m([a5()]),p(n),j(""),l("visual")}else{let e=JSON.stringify(a,null,2);r("legacy"),c(e),m([a5()]),p(e),j(""),l("visual")}return}let i=a.operations||[];if("append"===e){let e=i.map(a4),t=[..."operations"===n?u.filter(e=>!a6(e)):[],...e];r("operations"),m(t.length>0?t:e),_(t[0]?.id||e[0]?.id||""),c(""),j(""),l("visual"),p("")}else{let e=i.map(a4),t=e.length>0?e:[a5()];r("operations"),m(t),_(t[0]?.id||""),p(JSON.stringify({operations:i},null,2)),j(""),l("visual")}},[o,u,M,n,t]),ei=(0,x.useCallback)(()=>{let e=a5();r("operations"),c(""),m([e]),_(e.id),p(""),j(""),O("operations_default"),l("visual")},[]),eo=(0,x.useCallback)(e=>{p(e);let s=e.trim();s?j(a1(s)?"":t("JSON format error")):j("")},[t]),ed=(0,x.useMemo)(()=>{if("visual"!==s)return"";try{return ea(),""}catch(e){return e?.message||t("Parameter configuration error")}},[ea,s,t]),ec=(0,x.useCallback)(()=>{try{let a="";if("json"===s){let e=h.trim();if(e){if(!a1(e))throw Error(t("Parameter override must be valid JSON format"));a=JSON.stringify(JSON.parse(e),null,2)}}else a=ea();e.onSave(a),e.onOpenChange(!1)}catch(e){g.oR.error(e.message)}},[ea,s,h,e,t]),eu=(0,x.useCallback)(()=>{if(!$)return;let e={};for(let t of $.conditions)e[t.id]=!0;w(t=>({...t,...e}))},[$]),em=(0,x.useCallback)(()=>{if(!$)return;let e={};for(let t of $.conditions)e[t.id]=!1;w(t=>({...t,...e}))},[$]);return(0,a.jsxs)(tx.l,{open:e.open,onOpenChange:e.onOpenChange,title:t("Parameter Override"),description:t("Create request parameter override rules with a visual editor or raw JSON."),contentClassName:"flex max-h-[90vh] flex-col gap-0 p-0 sm:max-w-5xl",headerClassName:"border-b px-6 py-4",footerClassName:"border-t px-6 py-4",contentHeight:"min(72vh, 720px)",bodyClassName:"space-y-4",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{type:"button",variant:"outline",onClick:()=>e.onOpenChange(!1),children:t("Cancel")}),(0,a.jsx)(tg.$,{type:"button",onClick:ec,children:t("Save")})]}),children:[(0,a.jsx)("div",{className:"bg-muted/30 border-b px-4 py-3",children:(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsx)("span",{className:"text-muted-foreground text-xs font-medium",children:t("Mode")}),(0,a.jsx)(tg.$,{type:"button",variant:"visual"===s?"default":"outline",size:"sm",onClick:en,children:t("Visual")}),(0,a.jsx)(tg.$,{type:"button",variant:"json"===s?"default":"outline",size:"sm",onClick:el,children:t("JSON Text")}),(0,a.jsx)("div",{className:"bg-border mx-1 h-5 w-px"}),(0,a.jsx)("span",{className:"text-muted-foreground text-xs font-medium",children:t("Template")}),(0,a.jsxs)(ss.l6,{items:[...T.map(e=>({value:e.value,label:t(e.label)}))],value:M,onValueChange:e=>O(e||"operations_default"),children:[(0,a.jsx)(ss.bq,{className:"h-8 w-[220px]",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:T.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:t(e.label)},e.value))})})]}),(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>er("fill"),children:t("Fill Template")}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>er("append"),children:t("Append Template")}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:ei,children:t("Reset")})]})}),(0,a.jsx)("div",{className:"min-h-0 flex-1 overflow-hidden",children:"visual"===s?"legacy"===n?(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsx)("p",{className:"text-muted-foreground mb-2 text-sm",children:t("Legacy Format (JSON Object)")}),(0,a.jsx)(sv.B,{value:o,onChange:c,placeholder:JSON.stringify(aH,null,2),heightClassName:"h-72 min-h-72 max-h-72",ariaLabel:t("Legacy Format (JSON Object)")}),(0,a.jsx)("p",{className:"text-muted-foreground mt-2 text-xs",children:t("Edit JSON object directly. Suitable for simple parameter overrides.")})]}):(0,a.jsxs)("div",{className:"flex h-full",children:[(0,a.jsxs)("div",{className:"flex w-[280px] flex-shrink-0 flex-col border-r",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between border-b px-3 py-2",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("span",{className:"text-sm font-medium",children:t("Rules")}),(0,a.jsxs)(d.E,{variant:"secondary",children:[z,"/",u.length]})]}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:q,children:(0,a.jsx)(sK.A,{className:"h-4 w-4"})})]}),D.length>0&&(0,a.jsx)("div",{className:"flex flex-wrap gap-1 border-b px-3 py-2",children:D.map(e=>{let[s,l]=e;return(0,a.jsxs)("span",{className:(0,tE.cn)("inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium",a7(s)),children:[t(aP[s]||s)," · ",l]},`mode_stat_${s}`)})}),(0,a.jsx)("div",{className:"px-3 py-2",children:(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)(s_.A,{className:"text-muted-foreground absolute top-2.5 left-2.5 h-3.5 w-3.5"}
1),(0,a.jsx)(se.p,{value:v,onChange:e=>y(e.target.value),placeholder:t("Search rules..."),className:"h-8 pl-8 text-xs"})]})}),(0,a.jsx)(tM.F,{className:"flex-1",children:(0,a.jsx)("div",{className:"flex flex-col gap-1 px-3 pb-3",children:0===E.length?(0,a.jsx)("p",{className:"text-muted-foreground py-4 text-center text-xs",children:t("No matching rules")}):E.map(e=>{let s=u.findIndex(t=>t.id===e.id),l=e.id===b,n=e.id===k,r=e.id===A&&""!==k&&k!==e.id;return(0,a.jsx)("div",{role:"button",tabIndex:0,draggable:u.length>1,onClick:()=>_(e.id),onDragStart:t=>ee(t,e.id),onDragOver:t=>et(t,e.id),onDrop:t=>es(t,e.id),onDragEnd:X,onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),_(e.id))},className:(0,tE.cn)("cursor-pointer rounded-lg border p-2.5 transition-colors",l?"border-primary bg-primary/5":"hover:bg-muted/50",n&&"opacity-50",r&&"before"===R&&"border-t-primary border-t-2",r&&"after"===R&&"border-b-primary border-b-2"),children:(0,a.jsxs)("div",{className:"flex items-start gap-2",children:[(0,a.jsx)(a$.A,{className:(0,tE.cn)("text-muted-foreground mt-0.5 h-3.5 w-3.5 flex-shrink-0",u.length>1?"cursor-grab":"cursor-default")}),(0,a.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-1",children:[(0,a.jsxs)("span",{className:"text-xs font-semibold",children:["#",s+1]}),(0,a.jsx)(d.E,{variant:"outline",className:"text-[10px]",children:e.conditions.length})]}),(0,a.jsx)("p",{className:"text-muted-foreground mt-0.5 line-clamp-1 text-[11px]",children:a8(e,s)}),e.description.trim()&&(0,a.jsx)("p",{className:"text-muted-foreground mt-0.5 line-clamp-2 text-[10px]",children:e.description}),(0,a.jsx)("span",{className:(0,tE.cn)("mt-1 inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium",a7(e.mode||"set")),children:t(aP[e.mode||"set"]||e.mode||"set")})]})]})},e.id)})})})]}),(0,a.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col overflow-y-auto",children:[$?(0,a.jsx)(lo,{operation:$,operationIndex:F,operations:u,returnErrorDraft:B,pruneObjectsDraft:P,expandedConditions:N,setExpandedConditions:w,updateOperation:J,duplicateOperation:L,removeOperation:V,addCondition:K,updateCondition:W,removeCondition:U,updateReturnErrorDraft:H,updatePruneObjectsDraft:G,addPruneRule:Y,updatePruneRule:Z,removePruneRule:Q,expandAllConditions:eu,collapseAllConditions:em}):(0,a.jsx)("div",{className:"flex flex-1 items-center justify-center",children:(0,a.jsx)("p",{className:"text-muted-foreground text-sm",children:t("Select a rule to edit.")})}),ed&&(0,a.jsx)("div",{className:"border-t px-4 py-2",children:(0,a.jsx)("p",{className:"text-destructive text-xs",children:ed})})]})]}):(0,a.jsxs)("div",{className:"p-4",children:[(0,a.jsx)("div",{className:"mb-2 flex items-center gap-2",children:(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:t("Advanced text editing")})}),(0,a.jsx)(sv.B,{value:h,onChange:eo,placeholder:JSON.stringify(aG,null,2),heightClassName:"h-[420px] min-h-[420px] max-h-[420px]","aria-invalid":!!f,ariaLabel:t("Advanced text editing")}),(0,a.jsx)("p",{className:"text-muted-foreground mt-2 text-xs",children:t("Edit JSON text directly. Format will be validated on save.")}),f&&(0,a.jsx)("p",{className:"text-destructive mt-1 text-xs",children:f})]})})]})}function lo(e){let{t}=(0,i.Bd)(),s=e.operation,l=s.mode||"set",n=aq[l]||aq.set,r=s.conditions,o="sync_fields"===l?a9(s.from):null,c="sync_fields"===l?a9(s.to):null;return(0,a.jsx)(tM.F,{className:"flex-1",children:(0,a.jsxs)("div",{className:"space-y-4 p-4",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)(d.E,{variant:"outline",children:["#",e.operationIndex+1]}),(0,a.jsx)("span",{className:"text-muted-foreground line-clamp-1 text-xs",children:a8(s,e.operationIndex)})]}),(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>e.duplicateOperation(s.id),children:[(0,a.jsx)(tv.A,{className:"mr-1 h-3.5 w-3.5"}),t("Duplicate")]}),(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>e.removeOperation(s.id),children:[(0,a.jsx)(t5.A,{className:"mr-1 h-3.5 w-3.5"}),t("Delete")]})]})]}),(0,a.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Operation Type")}),(0,a.jsxs)(ss.l6,{items:[...aF.map(e=>({value:e.value,label:t(e.label)}))],value:l,onValueChange:t=>null!==t&&e.updateOperation(s.id,{mode:t}),children:[(0,a.jsx)(ss.bq,{className:"h-9",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:aF.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:t(e.label)},e.value))})})]})]}),(n.path||n.pathOptional)&&(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("set_header"===l||"delete_header"===l?"Header Name":"prune_objects"===l?"Target Path (optional)":"Target Field Path")}),(0,a.jsx)(se.p,{value:s.path,onChange:t=>e.updateOperation(s.id,{path:t.target.value}),placeholder:"set_header"===l?"Authorization":"delete_header"===l?"X-Debug-Mode":"prune_objects"===l?"messages":"temperature",className:"h-9"})]})]}),aW[l]&&(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:t(aW[l])}),(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Rule Description (optional)")}),(0,a.jsxs)("span",{className:"text-muted-foreground text-[10px]",children:[s.description.length,"/180"]})]}),(0,a.jsx)(se.p,{value:s.description,onChange:t=>e.updateOperation(s.id,{description:t.target.value}),placeholder:t("e.g. Clean tool parameters to avoid upstream validation errors"),maxLength:180,className:"h-9"})]}),n.value&&("return_error"===l&&e.returnErrorDraft?(0,a.jsx)(lc,{operationId:s.id,draft:e.returnErrorDraft,updateDraft:e.updateReturnErrorDraft}):"prune_objects"===l&&e.pruneObjectsDraft?(0,a.jsx)(lu,{operationId:s.id,draft:e.pruneObjectsDraft,updateDraft:e.updatePruneObjectsDraft,addRule:e.addPruneRule,updateRule:e.updatePruneRule,removeRule:e.removePruneRule}):(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("set_header"===l?"Header Value (supports string or JSON mapping)":"pass_headers"===l?"Pass-through Headers (comma-separated or JSON array)":"trim_prefix"===l||"trim_suffix"===l||"ensure_prefix"===l||"ensure_suffix"===l?"Prefix/Suffix Text":"prune_objects"===l?"Prune Rule (string or JSON object)":"Value (supports JSON or plain text)")}),s.value_text.trim().startsWith("{")&&(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground h-auto px-1.5 py-0.5 text-xs",onClick:()=>{try{let t=JSON.parse(s.value_text);e.updateOperation(s.id,{value_text:JSON.stringify(t,null,2)})}catch(e){}},children:t("Format")})]}),(0,a.jsx)(sq.T,{value:s.value_text,onChange:t=>e.updateOperation(s.id,{value_text:t.target.value}),placeholder:"set_header"===l?"Bearer sk-xxx":"pass_headers"===l?"Authorization, X-Request-Id":"trim_prefix"===l||"trim_suffix"===l||"ensure_prefix"===l||"ensure_suffix"===l?"openai/":"prune_objects"===l?'{"type":"redacted_thinking"}':"0.7",rows:3,className:"max-h-[200px] resize-y overflow-y-auto font-mono text-xs"})]})),n.keepOrigin&&(0,a.jsxs)("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[(0,a.jsx)("p",{className:"text-sm font-medium",children:t("Keep original value (skip if target exists)")}),(0,a.jsx)(sl.d,{checked:s.keep_origin,onCheckedChange:t=>e.updateOperation(s.id,{keep_origin:t})})]}
1),"sync_fields"===l&&o&&c?(0,a.jsx)(lm,{operationId:s.id,syncFromTarget:o,syncToTarget:c,updateOperation:e.updateOperation}):(n.from||void 0!==n.to)&&"sync_fields"!==l?(0,a.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(n.from||!1===n.to)&&(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("replace"===l?"Match Text":"regex_replace"===l?"Regex Pattern":"copy_header"===l||"move_header"===l?"Source Header":"Source Field")}),(0,a.jsx)(se.p,{value:s.from,onChange:t=>e.updateOperation(s.id,{from:t.target.value}),placeholder:"replace"===l?"openai/":"regex_replace"===l?"^gpt-":"copy_header"===l||"move_header"===l?"Authorization":"model",className:"h-9"})]}),(n.to||!1===n.to)&&(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("replace"===l||"regex_replace"===l?"Replace With":"copy_header"===l||"move_header"===l?"Target Header":"Target Field")}),(0,a.jsx)(se.p,{value:s.to,onChange:t=>e.updateOperation(s.id,{to:t.target.value}),placeholder:"replace"===l?"(leave empty to delete)":"regex_replace"===l?"openai/gpt-":"copy_header"===l||"move_header"===l?"X-Upstream-Auth":"original_model",className:"h-9"})]})]}):null,(0,a.jsxs)("div",{className:"rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"mb-2 flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)("span",{className:"text-sm font-medium",children:t("Conditions")}),(0,a.jsxs)(ss.l6,{items:[{value:"OR",label:t("Match Any (OR)")},{value:"AND",label:t("Match All (AND)")}],value:s.logic||"OR",onValueChange:t=>null!==t&&e.updateOperation(s.id,{logic:t}),children:[(0,a.jsx)(ss.bq,{className:"h-7 w-[120px] text-xs",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"OR",children:t("Match Any (OR)")}),(0,a.jsx)(ss.eb,{value:"AND",children:t("Match All (AND)")})]})})]})]}),(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[r.length>0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:e.expandAllConditions,children:[(0,a.jsx)(tN.A,{className:"mr-1 h-3 w-3"}),t("Expand All")]}),(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:e.collapseAllConditions,children:[(0,a.jsx)(t_.A,{className:"mr-1 h-3 w-3"}),t("Collapse All")]})]}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>e.addCondition(s.id),children:[(0,a.jsx)(sK.A,{className:"mr-1 h-3 w-3"}),t("Add Condition")]})]})]}),0===r.length?(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:t("When no conditions are set, the operation always executes.")}):(0,a.jsx)("div",{className:"space-y-2",children:r.map((t,l)=>(0,a.jsx)(ld,{condition:t,conditionIndex:l,operationId:s.id,expanded:e.expandedConditions[t.id]??!1,onExpandedChange:s=>e.setExpandedConditions(e=>({...e,[t.id]:s})),updateCondition:e.updateCondition,removeCondition:e.removeCondition},t.id))})]})]})})}function ld(e){let{t}=(0,i.Bd)(),s=e.condition;return(0,a.jsx)(tS.Nt,{open:e.expanded,onOpenChange:e.onExpandedChange,children:(0,a.jsxs)("div",{className:"rounded-md border",children:[(0,a.jsxs)(tS.R6,{className:"hover:bg-muted/50 flex w-full items-center justify-between px-3 py-2",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)(d.E,{variant:"outline",className:"text-[10px]",children:["C",e.conditionIndex+1]}),(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:s.path||t("Path not set")})]}),e.expanded?(0,a.jsx)(t_.A,{className:"text-muted-foreground h-3.5 w-3.5"}):(0,a.jsx)(tN.A,{className:"text-muted-foreground h-3.5 w-3.5"})]}),(0,a.jsx)(tS.Ke,{children:(0,a.jsxs)("div",{className:"space-y-3 border-t px-3 py-3",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between",children:[(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:t("Condition Settings")}),(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive h-7 text-xs",onClick:()=>e.removeCondition(e.operationId,s.id),children:[(0,a.jsx)(t5.A,{className:"mr-1 h-3 w-3"}),t("Delete Condition")]})]}),(0,a.jsxs)("div",{className:"grid gap-2 sm:grid-cols-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Field Path")}),(0,a.jsx)(se.p,{value:s.path,onChange:t=>e.updateCondition(e.operationId,s.id,{path:t.target.value}),placeholder:"model",className:"h-8 text-xs"})]}),(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Match Mode")}),(0,a.jsxs)(ss.l6,{items:[...aD.map(e=>({value:e.value,label:t(e.label)}))],value:s.mode,onValueChange:t=>null!==t&&e.updateCondition(e.operationId,s.id,{mode:t}),children:[(0,a.jsx)(ss.bq,{className:"h-8 text-xs",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:aD.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:t(e.label)},e.value))})})]})]}),(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Match Value")}),(0,a.jsx)(se.p,{value:s.value_text,onChange:t=>e.updateCondition(e.operationId,s.id,{value_text:t.target.value}),placeholder:"gpt",className:"h-8 text-xs"})]})]}),(0,a.jsxs)("div",{className:"flex flex-wrap gap-4",children:[(0,a.jsxs)("label",{className:"flex items-center gap-2 text-xs",children:[(0,a.jsx)(sl.d,{checked:s.invert,onCheckedChange:t=>e.updateCondition(e.operationId,s.id,{invert:t})}),t("Invert match")]}),(0,a.jsxs)("label",{className:"flex items-center gap-2 text-xs",children:[(0,a.jsx)(sl.d,{checked:s.pass_missing_key,onCheckedChange:t=>e.updateCondition(e.operationId,s.id,{pass_missing_key:t})}),t("Pass when key is missing")]})]})]})})]})})}function lc(e){let{t}=(0,i.Bd)(),s=e.draft;return(0,a.jsxs)("div",{className:"rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"mb-2 flex items-center justify-between",children:[(0,a.jsx)("span",{className:"text-sm font-medium",children:t("Custom Error Response")}),(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:t("Mode")}),(0,a.jsx)(tg.$,{type:"button",variant:s.simpleMode?"default":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>e.updateDraft(e.operationId,{simpleMode:!0}),children:t("Simple")}),(0,a.jsx)(tg.$,{type:"button",variant:s.simpleMode?"outline":"default",size:"sm",className:"h-7 text-xs",onClick:()=>e.updateDraft(e.operationId,{simpleMode:!1}),children:t("Advanced")})]})]}),(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Error Message (required)")}),(0,a.jsx)(sq.T,{value:s.message,onChange:t=>e.updateDraft(e.operationId,{message:t.target.value}),placeholder:t("e.g. This request does not meet access policy"),rows:2,className:"text-xs"})]}),s.simpleMode?(0,a.jsx)("p",{className:"text-muted-foreground mt-2 text-xs",children:t("Simple mode only returns message; status code and error type use system defaults.")}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Status Code")}),(0,a.jsx)(se.p,{value:String(s.statusCode??""),onChange:t=>e.updateDraft(e.operationId,{statusCode:parseInt(t.target.value,10)||400}),placeholder:"400",className:"h-8 text-xs"})]}),(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Error Code (optional)")}),(0,a.jsx)(se.p,{value:s.code,onChange:t=>e.updateDraft(e.operationId,{code:t.target.value}),placeholder:"forced_bad_request",className:"h-8 text-xs"})]}),(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Error Type (optional)")}
1),(0,a.jsx)(se.p,{value:s.type,onChange:t=>e.updateDraft(e.operationId,{type:t.target.value}),placeholder:"invalid_request_error",className:"h-8 text-xs"})]})]}),(0,a.jsxs)("div",{className:"mt-2 flex items-center gap-2",children:[(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:t("Retry Suggestion")}),(0,a.jsx)(tg.$,{type:"button",variant:s.skipRetry?"default":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>e.updateDraft(e.operationId,{skipRetry:!0}),children:t("Stop Retry")}),(0,a.jsx)(tg.$,{type:"button",variant:s.skipRetry?"outline":"default",size:"sm",className:"h-7 text-xs",onClick:()=>e.updateDraft(e.operationId,{skipRetry:!1}),children:t("Allow Retry")})]}),(0,a.jsx)("div",{className:"mt-2 flex flex-wrap gap-1",children:[{label:"Bad Request",statusCode:400,code:"invalid_request",type:"invalid_request_error"},{label:"Unauthorized",statusCode:401,code:"unauthorized",type:"authentication_error"},{label:"Rate Limited",statusCode:429,code:"rate_limited",type:"rate_limit_error"}].map(s=>(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",className:"h-6 text-[10px]",onClick:()=>e.updateDraft(e.operationId,{statusCode:s.statusCode,code:s.code,type:s.type}),children:t(s.label)},s.code))})]})]})}function lu(e){let{t}=(0,i.Bd)(),s=e.draft;return(0,a.jsxs)("div",{className:"rounded-lg border p-3",children:[(0,a.jsxs)("div",{className:"mb-2 flex items-center justify-between",children:[(0,a.jsx)("span",{className:"text-sm font-medium",children:t("Object Prune Rules")}),(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:t("Mode")}),(0,a.jsx)(tg.$,{type:"button",variant:s.simpleMode?"default":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>e.updateDraft(e.operationId,{simpleMode:!0}),children:t("Simple")}),(0,a.jsx)(tg.$,{type:"button",variant:s.simpleMode?"outline":"default",size:"sm",className:"h-7 text-xs",onClick:()=>e.updateDraft(e.operationId,{simpleMode:!1}),children:t("Advanced")})]})]}),(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Type (common)")}),(0,a.jsx)(se.p,{value:s.typeText,onChange:t=>e.updateDraft(e.operationId,{typeText:t.target.value}),placeholder:"redacted_thinking",className:"h-8 text-xs"})]}),s.simpleMode?(0,a.jsx)("p",{className:"text-muted-foreground mt-2 text-xs",children:t("Simple mode: prune objects by type, e.g. redacted_thinking.")}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Logic")}),(0,a.jsxs)(ss.l6,{items:[{value:"AND",label:t("All Must Match (AND)")},{value:"OR",label:t("Any Match (OR)")}],value:s.logic,onValueChange:t=>e.updateDraft(e.operationId,{logic:t||"AND"}),children:[(0,a.jsx)(ss.bq,{className:"h-8 text-xs",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"AND",children:t("All Must Match (AND)")}),(0,a.jsx)(ss.eb,{value:"OR",children:t("Any Match (OR)")})]})})]})]}),(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Recursion Strategy")}),(0,a.jsxs)("div",{className:"flex gap-1",children:[(0,a.jsx)(tg.$,{type:"button",variant:s.recursive?"default":"outline",size:"sm",className:"h-8 text-xs",onClick:()=>e.updateDraft(e.operationId,{recursive:!0}),children:t("Recursive")}),(0,a.jsx)(tg.$,{type:"button",variant:s.recursive?"outline":"default",size:"sm",className:"h-8 text-xs",onClick:()=>e.updateDraft(e.operationId,{recursive:!1}),children:t("Current Level Only")})]})]})]}),(0,a.jsxs)("div",{className:"bg-muted/30 mt-3 rounded-md border p-2",children:[(0,a.jsxs)("div",{className:"mb-2 flex items-center justify-between",children:[(0,a.jsx)("span",{className:"text-xs font-medium",children:t("Additional Conditions")}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>e.addRule(e.operationId),children:[(0,a.jsx)(sK.A,{className:"mr-1 h-3 w-3"}),t("Add Condition")]})]}),0===s.rules.length?(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:t("Without additional conditions, only the type above is used for pruning.")}):(0,a.jsx)("div",{className:"space-y-2",children:s.rules.map((s,l)=>(0,a.jsxs)("div",{className:"bg-background rounded-md border p-2",children:[(0,a.jsxs)("div",{className:"mb-1 flex items-center justify-between",children:[(0,a.jsxs)(d.E,{variant:"outline",className:"text-[10px]",children:["R",l+1]}),(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive h-6 text-[10px]",onClick:()=>e.removeRule(e.operationId,s.id),children:[(0,a.jsx)(t5.A,{className:"mr-1 h-3 w-3"}),t("Delete")]})]}),(0,a.jsxs)("div",{className:"grid gap-2 sm:grid-cols-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Field Path")}),(0,a.jsx)(se.p,{value:s.path,onChange:t=>e.updateRule(e.operationId,s.id,{path:t.target.value}),placeholder:"type",className:"h-7 text-xs"})]}),(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Match Mode")}),(0,a.jsxs)(ss.l6,{items:[...aD.map(e=>({value:e.value,label:t(e.label)}))],value:s.mode,onValueChange:t=>null!==t&&e.updateRule(e.operationId,s.id,{mode:t}),children:[(0,a.jsx)(ss.bq,{className:"h-7 text-xs",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:aD.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:t(e.label)},e.value))})})]})]}),(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Match Value (optional)")}),(0,a.jsx)(se.p,{value:s.value_text,onChange:t=>e.updateRule(e.operationId,s.id,{value_text:t.target.value}),placeholder:"redacted_thinking",className:"h-7 text-xs"})]})]}),(0,a.jsxs)("div",{className:"mt-1.5 flex flex-wrap gap-3",children:[(0,a.jsxs)("label",{className:"flex items-center gap-1.5 text-[10px]",children:[(0,a.jsx)(sl.d,{checked:s.invert,onCheckedChange:t=>e.updateRule(e.operationId,s.id,{invert:t})}),t("Invert match")]}),(0,a.jsxs)("label",{className:"flex items-center gap-1.5 text-[10px]",children:[(0,a.jsx)(sl.d,{checked:s.pass_missing_key,onCheckedChange:t=>e.updateRule(e.operationId,s.id,{pass_missing_key:t})}),t("Pass when key is missing")]})]})]},s.id))})]})]})]})}function lm(e){let{t}=(0,i.Bd)();return(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsx)("label",{className:"text-xs font-medium",children:t("Sync Endpoints")}),(0,a.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Source Endpoint")}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsxs)(ss.l6,{items:[...aU.map(e=>({value:e.value,label:t(e.label)}))],value:e.syncFromTarget.type||"json",onValueChange:t=>null!==t&&e.updateOperation(e.operationId,{from:le(t,e.syncFromTarget.key)}),children:[(0,a.jsx)(ss.bq,{className:"h-8 w-[110px] text-xs",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:aU.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:t(e.label)},e.value))})})]}),(0,a.jsx)(se.p,{value:e.syncFromTarget.key,onChange:t=>e.updateOperation(e.operationId,{from:le(e.syncFromTarget.type,t.target.value)}),placeholder:"session_id",className:"h-8 text-xs"})]})]}),(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsx)("label",{className:"text-[10px] font-medium",children:t("Target Endpoint")}),(0,a.jsxs)("div",{className:"flex gap-2",children:[(0,a.jsxs)(ss.l6,{items:[...aU.map(e=>({value:e.value,label:t(e.label)}))],value:e.syncToTarget.type||"json",onValueChange:t=>null!==t&&e.updateOperation(e.operationId,{to:le(t,e.syncToTarget.key)}),children:[(0,a.jsx)(ss.bq,{className:"h-8 w-[110px] text-xs",children:(0,a.jsx)(ss.yv,{})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:aU.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:t(e.label)},e.value))})})]}),(0,a.jsx)(se.p,{value:e.syncToTarget.key,onChange:t=>e.updateOperation(e.operationId,{to:le(e.syncToTarget.type,t.target.value)}),placeholder:"prompt_cache_key",className:"h-8 text-xs"})]})]})]}),(0,a.jsx)("div",{className:"flex flex-wrap gap-1",children:[{label:"header:session_id -> json:prompt_cache_key",from:"header:session_id",to:"json:prompt_cache_key"},{label:"json:prompt_cache_key -> header:session_id",from:"json:prompt_cache_key",to:"header:session_id"}].map(t=>(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",className:"h-6 text-[10px]",onClick:()=>e.updateOperation(e.operationId,{from:t.from,to:t.to}),children:t.label},t.label))})]})}let lh=(0,x.lazy)(()=>Promise.resolve().then(s.bind(s,26403)).then(e=>({default:e.Markdown}))),lp=["High-risk status code retry risk check 1","High-risk status code retry risk check 2","High-risk status code retry risk check 3","High-risk status code retry risk check 4"];function lx(e){let{open:t,onOpenChange:s,detailItems:l,onConfirm:n}=e,{t:r}=(0,i.Bd)(),[o,d]=(0,x.useState)(new Set),[c,u]=(0,x.useState)(""),m=r("High-risk status code retry confirmation text"),h=o.size===lp.length,p=c.trim()===m.trim(),g=h&&p;return(0,a.jsx)(tx.l,{open:t,onOpenChange:s,title:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tb.A,{className:"h-5 w-5"}),r("High-risk operation confirmation")]}),contentClassName:"sm:max-w-3xl",titleClassName:"text-destructive flex items-center gap-2",contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:()=>{d(new Set),u(""),s(!1)},children:r("Cancel")}),(0,a.jsx)(tg.$,{variant:"destructive",disabled:!g,onClick:()=>{g&&(d(new Set),u(""),n())},children:r("I confirm enabling high-risk retry")})]}),children:(0,a.jsxs)("div",{className:"space-y-4",children:[t?(0,a.jsx)("div",{className:"border-warning/40 bg-warning/5 rounded-lg border p-3 sm:p-4",children:(0,a.jsx)(x.Suspense,{fallback:(0,a.jsx)("div",{"aria-hidden":"true",className:"bg-warning/10 h-32 animate-pulse rounded-md"}),children:(0,a.jsx)(lh,{className:"[&_h3]:text-warning text-sm [&_h3]:text-base",children:r("High-risk status code retry risk disclaimer")})})}):null,l.length>0&&(0,a.jsxs)("div",{className:"border-destructive/30 bg-destructive/5 rounded-lg border p-3",children:[(0,a.jsx)("p",{className:"mb-2 text-sm font-medium",children:r("Detected high-risk status code redirect rules")}),(0,a.jsx)("ul",{className:"list-inside list-disc text-sm",children:l.map(e=>(0,a.jsx)("li",{className:"font-mono text-xs",children:e},e))})]}),(0,a.jsx)("div",{className:"space-y-2",children:lp.map((e,t)=>(0,a.jsxs)("div",{className:"flex items-start gap-2",children:[(0,a.jsx)(t9.S,{id:`risk-check-${t}`,checked:o.has(t),onCheckedChange:()=>{d(e=>{let s=new Set(e);return s.has(t)?s.delete(t):s.add(t),s})}}),(0,a.jsx)(st.J,{htmlFor:`risk-check-${t}`,className:"text-sm leading-tight",children:r(e)})]},e))}),(0,a.jsxs)("div",{className:"space-y-1.5",children:[(0,a.jsxs)(st.J,{className:"text-sm",children:[r("Action confirmation"),":"," ",(0,a.jsx)("code",{className:"bg-muted rounded px-1 text-xs",children:m})]}),(0,a.jsx)(se.p,{value:c,onChange:e=>u(e.target.value),placeholder:r("High-risk status code retry input placeholder")}),c&&!p&&(0,a.jsx)("p",{className:"text-destructive text-xs",children:r("High-risk status code retry input mismatch")})]})]})})}function lg(e){let{t}=(0,i.Bd)();return(0,a.jsxs)(tS.Nt,{open:e.open,onOpenChange:e.onOpenChange,children:[(0,a.jsxs)(tS.R6,{render:(0,a.jsx)("button",{type:"button",className:"hover:bg-muted/40 border-border/60 flex w-full items-center justify-between rounded-lg border px-3 py-3 text-left transition-colors","aria-expanded":e.open}),children:[(0,a.jsxs)("div",{className:"flex items-start gap-3",children:[(0,a.jsx)("span",{className:"bg-muted text-muted-foreground flex size-8 shrink-0 items-center justify-center rounded-md",children:(0,a.jsx)(t3.A,{className:"h-4 w-4","aria-hidden":"true"})}),(0,a.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,a.jsx)("div",{className:"text-[13px] font-semibold",children:t("Advanced Settings")}),(0,a.jsx)("div",{className:"text-muted-foreground text-xs",children:e.summary??t("Request overrides, routing behavior, and upstream model automation")})]})]}),(0,a.jsx)(tN.A,{className:(0,tE.cn)("text-muted-foreground h-4 w-4 shrink-0 transition-transform",e.open&&"rotate-180"),"aria-hidden":"true"})]}),(0,a.jsx)(tS.Ke,{className:"mt-5 flex flex-col gap-5",children:e.children})]})}function lf(e){let{t}=(0,i.Bd)();return(0,a.jsxs)(t7.y5,{children:[(0,a.jsx)(t7.JP,{title:t("Credentials"),description:t("Authentication"),icon:(0,a.jsx)(s0.A,{className:"h-4 w-4","aria-hidden":"true"}),iconTone:"success"}),e.children]})}function lj(e){let{t}=(0,i.Bd)();return(0,a.jsxs)("div",{className:"border-border/60 flex flex-col gap-3 border-t pt-4",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(s0.A,{className:"text-muted-foreground h-3.5 w-3.5","aria-hidden":"true"}),(0,a.jsx)("h4",{className:"text-muted-foreground text-xs font-medium tracking-wide uppercase",children:t("Authentication")})]}),e.children]})}function lv(e){let{t}=(0,i.Bd)();return(0,a.jsxs)(t7.y5,{children:[(0,a.jsx)(t7.JP,{title:t("Basic Information"),description:t("Name, provider type, and availability."),icon:(0,a.jsx)(sQ.A,{className:"h-4 w-4","aria-hidden":"true"}),iconTone:"info"}),e.children]})}function ly(){let{t:e}=(0,i.Bd)();return(0,a.jsxs)("div",{className:"border-border/60 flex flex-col gap-4 roun
1ded-lg border p-4","aria-live":"polite",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-sm font-medium",children:e("Loading channel details")}),(0,a.jsx)("p",{className:"text-muted-foreground mt-1 text-xs",children:e("Please wait before editing to avoid overwriting saved values.")})]}),(0,a.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,a.jsx)(tO.E,{className:"h-10 w-full"}),(0,a.jsx)(tO.E,{className:"h-10 w-full"})]}),(0,a.jsx)(tO.E,{className:"h-24 w-full"}),(0,a.jsx)(tO.E,{className:"h-32 w-full"})]})}function lb(e){let{t}=(0,i.Bd)();return(0,a.jsxs)(t7.y5,{children:[(0,a.jsx)(t7.JP,{title:t("Models & Groups"),description:t("Published models, groups, and model remapping rules."),icon:(0,a.jsx)(s1.A,{className:"h-4 w-4","aria-hidden":"true"}),iconTone:"chart-4"}),e.children]})}let l_=()=>({invalidJson:!1,entries:[],missingSourceModels:[],exposedTargetModels:[]}),lN=e=>e.map(e=>`"${e}"`).join(", "),lw=[{source:"client-model",target:"upstream-model"}],lk="channel-advanced-settings-expanded",lC="channel-section-identity",lA="channel-section-credentials",lS="channel-section-models",lR="channel-section-advanced",lI=[lC,lA,lS,lR],lM={routingStrategy:"channel-section-advanced-routing-strategy",internalNotes:"channel-section-advanced-internal-notes",overrideRules:"channel-section-advanced-override-rules",extraSettings:"channel-section-advanced-extra-settings",fieldPassthrough:"channel-section-advanced-field-passthrough",upstreamModelDetection:"channel-section-advanced-upstream-model-detection"},lO=Object.values(lM),lT=["type","base_url","key","openai_organization","other","key_mode","param_override","header_override","settings","setting","advanced_custom","is_enterprise_account","vertex_key_type","aws_key_type","azure_responses_version","force_format","thinking_to_content","proxy","http_protocol","http2_connection_shards","pass_through_body_enabled","system_prompt","system_prompt_override","allow_service_tier","disable_store","allow_safety_identifier","allow_include_obfuscation","allow_inference_geo","allow_speed","claude_beta_query","disable_task_polling_sleep","upstream_model_update_check_enabled","upstream_model_update_auto_sync_enabled","upstream_model_update_ignored_models"];function lz(e){if("string"!=typeof e)return!1;let t=e.trim();if(!t||"null"===t)return!1;try{let e=JSON.parse(t);if(null===e)return!1;if(Array.isArray(e))return e.length>0;if("object"==typeof e)return Object.keys(e).length>0}catch{}return!0}function lE(e){return(0,a.jsxs)("div",{className:"flex items-center gap-3",children:[e.icon&&(0,a.jsx)(tf.f,{tone:e.iconTone,size:"md",children:e.icon}),(0,a.jsx)("h3",{className:"text-sm font-semibold tracking-tight",children:e.title})]})}function l$(e){return(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[e.icon&&(0,a.jsx)(tf.f,{tone:e.iconTone,size:"xs",children:e.icon}),(0,a.jsx)("h4",{className:"text-muted-foreground text-xs font-medium tracking-wide uppercase",children:e.title})]})}function lF(e,t){return(0,tE.cn)(e,"border-border/60 rounded-lg border p-3 transition-colors",t&&"border-primary/35 ring-primary/20 ring-1")}function lB(e){return k.some(t=>t.value===e.type)?(0,a.jsx)("span",{className:(0,tE.cn)("inline-flex shrink-0",e.className),children:(0,ao.Y)(`${e7(e.type)}.Color`,e.size??16)}):(0,a.jsx)(sQ.A,{className:(0,tE.cn)("text-muted-foreground shrink-0",e.className),style:{width:e.size??16,height:e.size??16},"aria-hidden":"true"})}function lP(e,t){return e?"error":t?"complete":"idle"}function lD(e,t){return t("error"===e?"Error":"complete"===e||"configured"===e?"Ready":"Incomplete")}function lJ(e){return(0,a.jsx)("aside",{className:"hidden self-start lg:sticky lg:top-4 lg:z-20 lg:block",children:(0,a.jsxs)("div",{className:"flex max-h-[calc(100dvh-12rem)] flex-col gap-3 overflow-y-auto overscroll-contain pr-1",children:[(0,a.jsx)("div",{className:"border-border/60 bg-muted/20 rounded-lg border p-3",children:(0,a.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,a.jsx)("span",{className:"bg-background flex size-8 shrink-0 items-center justify-center rounded-md border",children:e.providerLogo}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("p",{className:"truncate text-sm font-medium",children:e.providerLabel}),(0,a.jsxs)("p",{className:"text-muted-foreground truncate text-xs",children:[e.statusLabel," · ",e.progressLabel]})]})]})}),(0,a.jsx)("nav",{className:"border-border/60 bg-background rounded-lg border p-1","aria-label":e.navigationLabel,children:e.items.map(t=>{var s;let l="error"===t.status,n="complete"===t.status||"configured"===t.status,r=!!t.configured,i=e.activeItemId===t.id,o=e.expandedItemId===t.id;return(0,a.jsxs)("div",{children:[(0,a.jsxs)("button",{type:"button",className:(0,tE.cn)("hover:bg-muted/60 flex w-full items-start gap-2 rounded-md px-2 py-2 text-left transition-colors",i&&"bg-muted/70",r&&!l&&"text-primary",l&&"text-destructive hover:bg-destructive/10"),onClick:()=>e.onNavigate(t.id),"aria-current":i?"true":void 0,children:[(0,a.jsx)("span",{className:(0,tE.cn)("bg-muted text-muted-foreground mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-md",r&&!l&&"bg-primary/10 text-primary",l&&"bg-destructive/10 text-destructive",n&&!l&&"text-primary"),children:t.icon}),(0,a.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,a.jsx)("span",{className:"block truncate text-sm font-medium",children:t.title}),t.description&&(0,a.jsx)("span",{className:"text-muted-foreground block truncate text-xs",children:t.description})]}),(0,a.jsx)("span",{className:(0,tE.cn)("text-muted-foreground mt-1 shrink-0",l&&"text-destructive",n&&!l&&"text-primary",r&&!l&&"pt-1.5"),"aria-label":t.statusLabel,children:!r||l||n?"error"===(s=t.status)?(0,a.jsx)(sD.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):"complete"===s||"configured"===s?(0,a.jsx)(t4.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}):(0,a.jsx)(sX.A,{className:"h-3.5 w-3.5","aria-hidden":"true"}
1):(0,a.jsx)("span",{className:"bg-success block size-2 rounded-full","aria-hidden":"true"})})]}),t.children&&o&&(0,a.jsx)("div",{className:"border-border/60 ml-5 flex flex-col gap-0.5 border-l py-1 pl-3",children:t.children.map(t=>(0,a.jsxs)("button",{type:"button",className:(0,tE.cn)("text-muted-foreground hover:bg-muted/50 hover:text-foreground flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-xs transition-colors",t.configured&&"text-primary"),onClick:()=>e.onNavigate(t.id),children:[(0,a.jsx)("span",{className:"min-w-0 flex-1 truncate",children:t.title}),t.configured&&(0,a.jsx)("span",{className:"bg-success size-1.5 shrink-0 rounded-full","aria-hidden":"true"})]},t.id))})]},t.id)})})]})})}function lq(e){let t,{open:s,onOpenChange:n,currentRow:r}=e,{t:o}=(0,i.Bd)(),f=(0,p.jE)(),{setOpen:j}=tu(),v=(0,m.n)(e=>e.auth.user),y=(0,sS._m)(v,sS.kB.CHANNEL,sS.YG.SENSITIVE_WRITE),b=v?.role===u.z7.SUPER_ADMIN,[_,N]=(0,x.useState)(!1),[w,A]=(0,x.useState)(null),[S,R]=(0,x.useState)(!1),[M,O]=(0,x.useState)(!1),E=(0,x.useRef)([]),$=(0,x.useRef)(""),F=(0,x.useRef)(""),[B,P]=(0,x.useState)(!1),[D,J]=(0,x.useState)([]),W=(0,x.useRef)(null),[U,H]=(0,x.useState)(!1),[G,Y]=(0,x.useState)([]),Z=(0,x.useRef)(null),Q=(0,x.useRef)(null),X=(0,x.useRef)(!1),[ee,et]=(0,x.useState)(lC),[es,ea]=(0,x.useState)(),[el,en]=(0,x.useState)(!1),[er,ei]=(0,x.useState)(!1),[eo,ed]=(0,x.useState)(!1),[ec,eu]=(0,x.useState)(null),em=!!r,eh=r?.id??null,ep=em&&!y,{data:ex,isLoading:eg}=(0,l.I)({queryKey:K.detail(eh||0),queryFn:()=>(0,h.c)(eh||0),enabled:em&&!!eh}),{data:ef,isLoading:ev}=(0,l.I)({queryKey:["groups"],queryFn:h.f}),{data:ey}=(0,l.I)({queryKey:["channel_models"],queryFn:h.i2}),{data:eb}=(0,l.I)({queryKey:["prefill_groups","model"],queryFn:()=>(0,h.xI)("model")}),{copyToClipboard:e_}=(0,tT.C)(),{open:eN,methods:ew,state:ek,executeVerification:eC,withVerification:eA,cancel:eS,setCode:eR,switchMethod:eI}=(0,ar.Yu)();(0,x.useEffect)(()=>{s?eh&&A(null):(A(null),R(!1))},[s,eh]);let eE=em&&ex?.data?.channel_info?.is_multi_key===!0,e$=(0,as.mN)({resolver:(0,sZ.u)(e1),defaultValues:e2}),eB=e$.watch("multi_key_mode"),eP=e$.watch("multi_key_type"),eD=e$.watch("key_mode"),eJ=e$.watch("group"),eq=e$.watch("type"),eV=e$.watch("status"),eK=e$.watch("base_url"),eW=e$.watch("key"),eZ=e$.watch("other"),eQ=e$.watch("models"),eX=e$.watch("name"),e0=e$.watch("model_mapping"),e6=e$.watch("aws_key_type"),e8=e$.watch("vertex_key_type"),e7=e$.watch("upstream_model_update_check_enabled"),e9=e$.watch("settings"),te=e$.watch("advanced_custom"),tt=e$.watch("priority"),ts=e$.watch("weight"),ta=e$.w
1atch("test_model"),ti=e$.watch("auto_ban"),to=e$.watch("tag"),td=e$.watch("remark"),tc=e$.watch("status_code_mapping"),tm=e$.watch("param_override"),tx=e$.watch("header_override"),tj=e$.watch("force_format"),ty=e$.watch("thinking_to_content"),tb=e$.watch("pass_through_body_enabled"),t_=e$.watch("disable_task_polling_sleep"),tN=e$.watch("proxy"),tw=e$.watch("http_protocol"),tk=e$.watch("http2_connection_shards"),tA=e$.watch("system_prompt"),tS=e$.watch("system_prompt_override"),tR=e$.watch("allow_service_tier"),tI=e$.watch("disable_store"),tM=e$.watch("allow_safety_identifier"),tz=e$.watch("allow_include_obfuscation"),tE=e$.watch("allow_inference_geo"),t$=e$.watch("allow_speed"),tF=e$.watch("claude_beta_query"),tB=e$.watch("upstream_model_update_auto_sync_enabled"),tP=e$.watch("upstream_model_update_ignored_models"),tD=!em||58===eq&&y,{unlocked:tJ,handleClick:tq,reset:tL}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.disabled??!1,s=e.requiredClicks??3,a=e.onUnlock,l=(0,x.useRef)(0),[n,r]=(0,x.useState)(!1),i=(0,x.useCallback)(()=>{l.current=0,r(!1)},[]),o=(0,x.useCallback)(()=>{if(t||n)return;let e=l.current+1;l.current=e,e>=s&&(l.current=0,r(!0),a?.())},[t,a,s,n]);return{unlocked:n,handleClick:o,reset:i}}({requiredClicks:10,disabled:45!==eq||ep,onUnlock:()=>{g.oR.info(o("Doubao custom API address editing unlocked"))}});(0,x.useEffect)(()=>{s||tL()},[s,tL]);let tV=(0,x.useCallback)(e=>{e$.setValue("key",e.key,{shouldDirty:!0,shouldValidate:!0}),e$.setValue("base_url",e.url,{shouldDirty:!0,shouldValidate:!0}),eu(null),g.oR.success(o("Connection info filled in"))},[e$,o]),tK=(0,x.useCallback)(async()=>{if("u"<typeof navigator||!navigator.clipboard?.readText)return void g.oR.error(o("Unable to read clipboard"));try{let e=await navigator.clipboard.readText(),t=(0,ai.hd)(e);if(t)return void tV(t);g.oR.info(o("No connection info found in clipboard"))}catch{g.oR.error(o("Unable to read clipboard"))}},[tV,o]);(0,x.useEffect)(()=>{if(!s||em)return void eu(null);if("u"<typeof navigator||!navigator.clipboard?.readText)return;let e=!1;return navigator.clipboard.readText().then(t=>{e||eu((0,ai.hd)(t))}).catch(()=>{}),()=>{e=!0}},[em,s]);let tW="batch"===eB||"multi_to_single"===eB,tU=em&&eg,tH=57!==eq&&(41!==eq||"api_key"!==e8),tG=(0,x.useMemo)(()=>tH?I:I.filter(e=>"single"===e.value),[tH]),tY=(0,x.useMemo)(()=>(function(e){let t=eO(e);if(!t)return{routeCount:0,valid:!1,routeTypeLabels:[]};let s=ez(t),a=s.advanced_routes||[],l=[],n=new Set;for(let e of a){let t=function(e){let t=e.incoming_path?.trim()||"";return t?ej[t]||eM(t):null}(e);!t||n.has(t)||(l.push(t),n.add(t))}return{routeCount:a.length,valid:null===eF(s),routeTypeLabels:l}})(te),[te]),tZ=tY.routeTypeLabels.slice(0,3),tQ=tY.routeTypeLabels.length-tZ.length,tX=tQ>0?tY.routeTypeLabels.join(", "):void 0,t0=(0,x.useMemo)(()=>ey?.data?.map(e=>e.id).filter(Boolean)||[],[ey]),t1=(0,x.useMemo)(()=>t0.length?1===eq?t0.filter(e=>e.startsWith("gpt-")||e.startsWith("text-")):t0:[],[t0,eq]),t2=(0,x.useMemo)(()=>eb?.data||[],[eb]),t4=(0,x.useMemo)(()=>ef?.data?[...new Set([...ef.data,...eJ||[]])].map(e=>({value:e,label:e})):[],[ef,eJ]),t6=(0,x.useMemo)(()=>tl(eQ),[eQ]),t8=(0,x.useMemo)(()=>k.find(e=>e.value===eq)?.label||`#${eq}`,[eq]),t9=(0,x.useMemo)(()=>{let e=k.map(e=>({value:String(e.value),label:o(e.label),icon:(0,a.jsx)(lB,{type:e.value,size:16})}));return e.some(e=>Number(e.value)===eq)||e.push({value:String(eq),label:`#${eq}`,icon:(0,a.jsx)(lB,{type:eq,size:16})}),e},[eq,o]),st=e$.formState.errors,sn=!!(st.name||st.type||st.status||st.openai_organization),sr=!!(st.key||st.base_url||st.other||st.multi_key_mode||st.multi_key_type||st.key_mode||st.vertex_key_type||st.aws_key_type||st.azure_responses_version),si=!!(st.models||st.group||st.model_mapping),so=eL(st)||!!st.advanced_custom,sd=[3,8,36,45].includes(eq),sc=[3,18,21,39,41,49].includes(eq),su=!!(eX?.trim()&&eq>0),sm=!!((em||eW?.trim())&&(!sd||eK?.trim())&&(!sc||eZ?.trim())),sh=!!(t6.length>0&&eJ?.length),sp=[su,sm,sh].filter(Boolean).length,sx=C[eV]||"Unknown",sg=`${sp}/3`,sf=lP(sn,su),sj=lP(sr,sm),sb=lP(si,sh),s_=so?o("Error"):void 0,sN=!!(tt||ts||ta?.trim()||(ti??1)!==1),sw=!!(to?.trim()||td?.trim()),sC=!!(lz(tc)||lz(tm)||lz(tx)),sA=!!(tj||ty||tb||t_||t
1N?.trim()||tA?.trim()||tS||tw&&"auto"!==tw||null!=tk&&tk>1),sR=!1;1===eq||57===eq?sR=!!(tR||tI||tM||tz||tE):14===eq&&(sR=!!(tR||tE||t$||tF));let sI=!!(e7||tB||tP?.trim()),sM=!!(sN||sw||sC||sA||sR||sI),sO=[{id:lM.routingStrategy,title:o("Routing Strategy"),configured:sN},{id:lM.internalNotes,title:o("Internal Notes"),configured:sw},{id:lM.overrideRules,title:o("Override Rules"),configured:sC},{id:lM.extraSettings,title:o("Channel Extra Settings"),configured:sA}];(1===eq||14===eq||57===eq)&&sO.push({id:lM.fieldPassthrough,title:o("Field passthrough controls"),configured:sR}),q.has(eq)&&sO.push({id:lM.upstreamModelDetection,title:o("Upstream Model Detection Settings"),configured:sI});let sT=[{id:lC,title:o("Basic Information"),description:lD(sf,o),statusLabel:lD(sf,o),status:sf,icon:(0,a.jsx)(sQ.A,{className:"h-4 w-4","aria-hidden":"true"})},{id:lA,title:o("Credentials"),description:lD(sj,o),statusLabel:lD(sj,o),status:sj,icon:(0,a.jsx)(s0.A,{className:"h-4 w-4","aria-hidden":"true"})},{id:lS,title:o("Models & Groups"),description:lD(sb,o),statusLabel:lD(sb,o),status:sb,icon:(0,a.jsx)(s1.A,{className:"h-4 w-4","aria-hidden":"true"})},{id:lR,title:o("Advanced Settings"),description:s_,statusLabel:s_??o("Advanced Settings"),status:so?"error":"idle",icon:(0,a.jsx)(t3.A,{className:"h-4 w-4","aria-hidden":"true"}),configured:sM,children:sO}],sz=(0,x.useMemo)(()=>(function(e){if("string"!=typeof e)return[];let t=e.trim();if(!t)return[];try{let e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return[];let s=Object.values(e).map(e=>"string"==typeof e?e.trim():void 0).filter(e=>!!e);return Array.from(new Set(s))}catch{return[]}})(e0||""),[e0]),sE=(0,x.useMemo)(()=>(function(e){if("string"!=typeof e)return[];let t=e.trim();if(!t)return[];try{let e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return[];let s=Object.keys(e).map(e=>e.trim()).filter(Boolean);return Array.from(new Set(s))}catch{return[]}})(e0||""),[e0]),s$=(0,x.useMemo)(()=>[...new Set([...t0,...t6])].map(e=>({value:e,label:e})),[t0,t6]),sF=(0,x.useMemo)(()=>{if(!e0?.trim())return l_();try{let e=JSON.parse(e0);if(!e||"object"!=typeof e||Array.isArray(e))return{...l_(),invalidJson:!0};let t=Object.entries(e).reduce((e,t)=>{let[s,a]=t,l=String(s).trim(),n=String(a??"").trim();return l&&n&&e.push({source:l,target:n}),e},[]),s=[...new Set(t.filter(e=>!!e.source&&!t6.includes(e.source)).map(e=>e.source))],a=[...new Set(t.filter(e=>!!e.target&&t6.includes(e.target)).map(e=>e.target))];return{invalidJson:!1,entries:t,missingSourceModels:s,exposedTargetModels:a}}catch{return{...l_(),invalidJson:!0}}},[e0,t6]),sB=sF.entries.length>0?sF.entries.slice(0,3):lw,sP=sF.entries.length>3?sF.entries.length-3:0,sD=(0,x.useMemo)(()=>{let e=function(e){if(!e?.trim())return{};try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}(e9),t=Array.isArray(e.upstream_model_update_last_detected_models)?e.upstream_model_update_last_detected_models.map(e=>String(e||"").trim()).filter(Boolean):[];return{lastCheckTime:e.upstream_model_update_last_check_time,detectedModels:[...new Set(t)]}},[e9]),sL=sD.detectedModels.slice(0,8),sW=sD.detectedModels.length-sL.length;(0,x.useEffect)(()=>{if(em&&ex?.data){let e=function(e){var t;let s={force_format:!1,thinking_to_content:!1,proxy:"",http_protocol:eU,http2_connection_shards:1,pass_through_body_enabled:!1,system_prompt:"",system_prompt_override:!1};if(e.setting)try{let t=JSON.parse(e.setting),a=eG(t.http_protocol),l=eY(t.http2_connection_shards);s={force_format:t.force_format||!1,thinking_to_content:t.thinking_to_content||!1,proxy:t.proxy||"",http_protocol:a,http2_connection_shards:a===eH?1:l,pass_through_body_enabled:t.pass_through_body_enabled||!1,system_prompt:t.system_prompt||"",system_prompt_override:t.system_prompt_override||!1}}catch(e){console.error("Failed to parse channel setting:",e)}let a="json",l="",n=!1,r="ak_sk",i=!1,o=!1,d=!1,c=!1,u=!1,m=!1,h=!1,p=!1,x=!1,g=!1,f="",j="";if(e.settings)try{let t=JSON.parse(e.settings);a=t.vertex_key_type||"json",l=t.azure_responses_version||"",n=!0===t.openrouter_enterprise,r=t.aws_key_type||"ak_sk",i=!0===t.allow_service_tier,o=!0===t.disable_store,d=!0===t.allow_safety_identifier,c=!0===t.allow_include_obfuscation,u=!0===t.allow_inference_geo,m=!0===t.allow_speed,h=!0===t.claude_beta_query,p=!0===t.disable_task_polling_sleep,x=!0===t.upstream_model_update_check_enabled,g=!0===t.upstream_model_update_auto_
1sync_enabled,f=Array.isArray(t.upstream_model_update_ignored_models)?t.upstream_model_update_ignored_models.join(","):"",t.advanced_custom&&(j=eT(t.advanced_custom))}catch(e){console.error("Failed to parse channel settings:",e)}return{name:e.name||"",type:e.type,base_url:e.base_url||"",key:"",openai_organization:e.openai_organization||"",models:e.models||"",group:(t=e.group||"default",t.split(",").map(e=>e.trim()).filter(e=>e.length>0)),model_mapping:e.model_mapping||"",priority:e.priority||0,weight:e.weight||0,test_model:e.test_model||"",auto_ban:e.auto_ban??1,status:e.status,status_code_mapping:e.status_code_mapping||"",tag:e.tag||"",remark:e.remark||"",setting:e.setting||"",param_override:e.param_override||"",header_override:e.header_override||"",settings:e.settings||"{}",other:e.other||"",multi_key_mode:"single",multi_key_type:e.channel_info.multi_key_mode||"random",batch_add_set_key_prefix_2_name:!1,key_mode:"append",...s,is_enterprise_account:n,vertex_key_type:a,azure_responses_version:l,aws_key_type:r,allow_service_tier:i,disable_store:o,allow_include_obfuscation:c,allow_inference_geo:u,allow_speed:m,claude_beta_query:h,disable_task_polling_sleep:p,allow_safety_identifier:d,upstream_model_update_check_enabled:x,upstream_model_update_auto_sync_enabled:g,upstream_model_update_ignored_models:f,advanced_custom:j}}(ex.data);e$.reset(e),en(!("u"<typeof window)&&"true"===window.localStorage.getItem(lk)||!!(lz(e.param_override)||lz(e.header_override)||e.advanced_custom?.trim()||lz(e.status_code_mapping)||e.tag?.trim()||e.remark?.trim()||e.priority||e.weight||e.proxy?.trim()||e.system_prompt?.trim()||e.force_format||e.thinking_to_content||e.pass_through_body_enabled||e.system_prompt_override||e.http_protocol&&"auto"!==e.http_protocol||null!=e.http2_connection_shards&&e.http2_connection_shards>1||e.claude_beta_query||e.upstream_model_update_check_enabled||e.upstream_model_update_auto_sync_enabled||e.upstream_model_update_ignored_models?.trim())),E.current=tl(ex.data.models||""),$.current=ex.data.model_mapping||"",F.current=ex.data.status_code_mapping||""}else em||(e$.reset(e2),en(!1),E.current=[],$.current="",F.current="")},[em,ex,e$]),(0,x.useEffect)(()=>{if(!em){if(45===eq){let e=e$.getValues("base_url");e&&""!==e||e$.setValue("base_url","https://ark.cn-beijing.volces.com")}if(18===eq){let e=e$.getValues("other");e&&""!==e||e$.setValue("other","v2.1")}}},[eq,em,e$]),(0,x.useEffect)(()=>{45===eq&&"doubao-coding-plan"===eK&&e$.setValue("base_url","https://ark.cn-beijing.volces.com",{shouldDirty:!1,shouldValidate:!0})},[eK,eq,e$]),(0,x.useEffect)(()=>{em||tH||eB&&"single"!==eB&&e$.setValue("multi_key_mode","single",{shouldDirty:!0,shouldValidate:!0})},[e$,em,eB,tH]),(0,x.useEffect)(()=>{if(!eK||!eK.endsWith("/v1"))return;let e=setTimeout(()=>{g.oR.warning(o("Warning: Base URL should not end with /v1. New API will handle it automatically. This may cause request failures."),{duration:5e3})},500);return()=>clearTimeout(e)},[eK]);let sU=()=>{let e=e$.getValues("key");if(!e||""===e.trim())return void g.oR.info(o("Please enter keys first"));let t=function(e){if(!e||""===e.trim())return{deduplicatedText:"",beforeCount:0,afterCount:0,removedCount:0};let t=e.split("\n"),s=t.length,a=new Set,l=[];t.forEach(e=>{let t=e.trim();t&&!a.has(t)&&(a.add(t),l.push(t))});let n=l.length;return{deduplicatedText:l.join("\n"),beforeCount:s,afterCount:n,removedCount:s-n}}(e);0===t.removedCount?g.oR.info(o("No duplicate keys found")):(e$.setValue("key",t.deduplicatedText),g.oR.success(o("Removed {{removed}} duplicate key(s). Before: {{before}}, After: {{after}}",{removed:t.removedCount,before:t.beforeCount,after:t.afterCount})))},sG=(0,x.useCallback)(async e=>{if(!eh)throw Error("Channel is not selected");R(!0);try{let t=await (0,h.BQ)(eh,e);if(!t.success)throw Error(t.message||o("Failed to fetch channel key"));let s=t.data?.key??"";return A(s),g.oR.success(o("Channel key unlocked")),t}finally{R(!1)}},[eh,o]),sY=(0,x.useCallback)(async()=>{if(eh)try{await eA(sG,{scope:"channel.key.read",preferredMethod:"passkey",title:o("Verify to view channel key"),description:o("Use Passkey or 2FA to confirm your identity before revealing this channel key.")})}catch(e){e instanceof Error&&g.oR.error(e.message)}},[eh,eA,sG,o]),sX=(0,x.useCallback)(async()=>
1{if(eh){O(!0);try{let e=await (0,h.uJ)(eh);if(!e.success)throw Error(e.message||o("Failed to refresh credential"));g.oR.success(o("Credential refreshed")),f.invalidateQueries({queryKey:K.detail(eh)})}catch(e){g.oR.error(e instanceof Error?e.message:o("Refresh failed"))}finally{O(!1)}}},[eh,f,o]),ao=(0,x.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],s=t?tn([...t6,...e]):tn(e);return e$.setValue("models",s),e.length},[t6,e$]),am=(0,x.useCallback)(async()=>{let e=e$.getValues("type");if(!q.has(e))return void g.oR.error(o("This channel type does not support fetching models"));if(!em&&!y)return void g.oR.error(o("You don't have necessary permission"));if(!em&&58!==e){let e=e$.getValues("key");if(!e?.trim())return void g.oR.error(o("Please enter API key first"))}N(!0)},[em,y,e$,o]),ag=(0,x.useCallback)(async()=>{if(!y)throw Error(o("You don't have necessary permission"));let e=e$.getValues("type"),t=em&&58===e;if(t&&null===eh)throw Error(o("No channel selected"));let s=await (0,h.ZC)({type:e,key:em?void 0:e$.getValues("key"),channel_id:t&&eh||void 0,base_url:e$.getValues("base_url")||"",advanced_custom:e$.getValues("advanced_custom"),header_override:e$.getValues("header_override"),proxy:e$.getValues("proxy")});if(s.success&&s.data)return s.data;throw Error(s.message||o("No models fetched from upstream"))},[y,eh,e$,em,o]),af=(0,x.useCallback)(()=>{t1.length?(ao(t1),g.oR.success(o("Filled {{count}} related model(s)",{count:t1.length}))):g.oR.info(o("No related models available for this channel type"))},[t1,ao,o]),aj=(0,x.useCallback)(()=>{t0.length?(ao(t0),g.oR.success(o("Filled {{count}} model(s)",{count:t0.length}))):g.oR.info(o("No models available"))},[t0,ao,o]),av=(0,x.useCallback)(()=>{e$.setValue("models",""),g.oR.success(o("Cleared all models"))},[e$,o]),ay=(0,x.useCallback)(async()=>{let e=e$.getValues("models");e?.trim()?await e_(e):g.oR.info(o("No models to copy"))},[e$,e_,o]),ab=(0,x.useCallback)(e=>{try{let t=Array.isArray(e.items)?e.items:JSON.parse(e.items);if(!Array.isArray(t))throw Error("Invalid items format");let s=ao(t,!0);g.oR.success(o('Added {{count}} models from "{{name}}"',{count:s,name:e.name}))}catch{g.oR.error(o("Failed to parse group items"))}},[ao,o]),a_=(0,x.useCallback)(e=>{e$.setValue("models",e.join(","))},[e$]),aN=(0,x.useCallback)(()=>{f.invalidateQueries({queryKey:K.lists()}),eh&&f.invalidateQueries({queryKey:K.detail(eh)}),n(!1),j(null)},[eh,f,n,j]),aw=(0,x.useCallback)(e=>new Promise(t=>{Y(e),H(!0),Z.current=t}),[]),ak=(0,x.useCallback)(e=>{H(!1),Z.current&&(Z.current(e),Z.current=null)},[]),aC=(0,x.useCallback)(e=>new Promise(t=>{W.current=t,J(e),P(!0)}),[]),aA=(0,x.useCallback)(e=>{P(!1),J([]),W.current&&(W.current(e),W.current=null)},[]);(0,x.useEffect)(()=>()=>{W.current&&(W.current(!1),W.current=null)},[]);let aS=function(e){let{t}=(0,i.Bd)(),s=(0,m.n)(e=>e.auth.user),a=(0,sS._m)(s,sS.kB.CHANNEL,sS.YG.SENSITIVE_WRITE);return(0,ad.n)({mutationFn:async s=>{let l,n;if(e.isEditing&&e.currentRow){let l,n=(l={id:e.currentRow.id,name:s.name,type:s.type,base_url:e3(s.base_url)||null,openai_organization:s.openai_organization||null,models:s.models,group:s.group.join(","),model_mapping:s.model_mapping||null,priority:s.priority??0,weight:s.weight??0,test_model:s.test_model||null,auto_ban:s.auto_ban??1,status_code_mapping:s.status_code_mapping||null,tag:s.tag||null,remark:s.remark||"",setting:e4(s),param_override:s.param_override||null,header_override:s.header_override||null,settings:e5(s),other:s.other||""},s.key&&s.key.trim()&&(l.key=s.key),Object.keys(l).forEach(e=>{""===l[e]&&(l[e]=null)}),l.base_url=e3(s.base_url)||"",l.openai_organization=s.openai_organization||"",l.test_model=s.test_model||"",l.tag=s.tag||"",l.remark=s.remark||"",l.model_mapping=s.model_mapping||"",l.status_code_mapping=s.status_code_mapping||"",l.param_override=s.param_override||"",l.header_override=s.header_override||"",l);if(s.key?.trim()||delete n.key,!a)for(let e of ac)delete n[e];let r=a&&e.isMultiKeyChannel&&s.key?.trim()&&s.key_mode?{...n,key_mode:s.key_mode}:n,i=await (0,h.fy)(e.currentRow.id,r);if(!i.success)throw Error(i.message||t(z));return"Channel updated successfully"}let r=(l=s.multi_key_mode||"single",Object.keys(n={name:s.name,type:s.type,base_url:e3(s.base_url)||null,key:s.key,open
1ai_organization:s.openai_organization||null,models:s.models,group:s.group.join(","),model_mapping:s.model_mapping||null,priority:s.priority||null,weight:s.weight||null,test_model:s.test_model||null,auto_ban:s.auto_ban??1,status:s.status,status_code_mapping:s.status_code_mapping||null,tag:s.tag||null,remark:s.remark||"",setting:e4(s),param_override:s.param_override||null,header_override:s.header_override||null,settings:e5(s),other:s.other||""}).forEach(e=>{""===n[e]&&(n[e]=null)}),{mode:l,multi_key_mode:"multi_to_single"===l?s.multi_key_type:void 0,batch_add_set_key_prefix_2_name:"batch"===l?s.batch_add_set_key_prefix_2_name:void 0,channel:n}),i=await (0,h.oP)(r);if(!i.success)throw Error(i.message||t(T));return"Channel created successfully"},onSuccess:s=>{g.oR.success(t(s)),e.onSuccess()},onError:e=>{g.oR.error(function(e){if(e instanceof Error&&"string"==typeof e.message)return e.message;if(!au(e))return;let t=e.response;if(au(t)){let e=t.data;if(au(e)){let t=e.message;if("string"==typeof t)return t}}let s=e.message;if("string"==typeof s)return s}(e)||t(T))}})}({currentRow:r,isEditing:em,isMultiKeyChannel:eE,onSuccess:aN}),aI=aS.isPending,aM=(0,x.useCallback)(async e=>{if(!em&&!e.key?.trim())return void e$.setError("key",{type:"manual",message:"API key is required"});if(ep){let e=e$.formState.dirtyFields;if(lT.some(t=>!!e[t]))return void g.oR.error(o("You do not have permission to edit sensitive channel settings."))}if(e.status_code_mapping?.trim()){let t=function(e){let t;if(!e?.trim())return[];try{t=JSON.parse(e)}catch{return[]}if(!t||"object"!=typeof t||Array.isArray(t))return[];let s=[];for(let[e,a]of Object.entries(t)){let t=ah(e),l=ap(a);(null===t||null===l)&&s.push(`${e} → ${a}`)}return s}(e.status_code_mapping);if(t.length>0)return void g.oR.error(o("Invalid status code mapping entries: {{entries}}",{entries:t.join(", ")}));let s=function(e,t){let s=ax(t);if(0===s.length)return[];let a=new Set(ax(e));return s.filter(e=>!a.has(e))}
1(F.current,e.status_code_mapping);if(s.length>0&&!await aC(s))return}let t="string"==typeof e.model_mapping&&""!==e.model_mapping.trim(),s=e.model_mapping||"";if(t){let e=function(e){if(!e||""===e.trim())return{valid:!0};try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return{valid:!1,error:"Model mapping must be a valid JSON object"};if(Object.values(t).some(e=>"string"!=typeof e))return{valid:!1,error:"Model mapping values must be strings"};return{valid:!0}}catch{return{valid:!1,error:"Model mapping must be valid JSON format"}}}(s);if(!e.valid)return void g.oR.error(o(e.error||"Invalid model mapping"))}let a=tl(e.models||"");if(t){let t=function(e,t){let s;if(!e||""===e.trim())return[];try{if(!(s=JSON.parse(e))||"object"!=typeof s||Array.isArray(s))return[]}catch{return[]}let a=new Set(t.map(e=>tr(e)));return Array.from(new Set(Object.keys(s).map(e=>tr(e)).filter(e=>e&&!a.has(e))))}(s,a);if(t.length>0&&function(e,t,s,a){if(0===s.length&&!a||e.length!==s.length)return!0;for(let t=0;t<e.length;t++)if(e[t]!==s[t])return!0;return(t||"").trim()!==(a||"").trim()}(a,e.model_mapping||"",E.current,$.current)){let s=await aw(t);if("cancel"===s)return;"add"===s&&(e.models=tn([...new Set([...a,...t])]),e$.setValue("models",e.models))}}await aS.mutateAsync(e)},[em,ep,e$,aw,aC,aS,o]),aO=(0,x.useCallback)(e=>{e||(X.current=!1,ea(void 0)),en(e),"u">typeof window&&window.localStorage.setItem(lk,String(e))},[]),aT=(0,x.useCallback)(e=>{let t=e===lR||lO.includes(e);t?(X.current=!0,aO(!0),et(lR),ea(lR)):(X.current=!1,et(e),ea(void 0));let s=()=>{document.querySelector(`#${e}`)?.scrollIntoView({behavior:"smooth",block:"start"})};t&&!el?window.requestAnimationFrame(s):s()},[el,aO]),az=(0,x.useCallback)(()=>{let e=Q.current;if(!e)return;let t=e.getBoundingClientRect().top+80,s=lC;for(let e of lI){let a=document.querySelector(`#${e}`);if(a)if(a.getBoundingClientRect().top<=t)s=e;else break}et(e=>e===s?e:s),s===lR?(X.current=!1,ea(lR),el||aO(!0)):X.current||ea(void 0)},[el,aO]);(0,x.useEffect)(()=>{if(!s||tU)return;let e=Q.current;if(e)return az(),e.addEventListener("scroll",az,{passive:!0}),window.addEventListener("resize",az),()=>{e.removeEventListener("scroll",az),window.removeEventListener("resize",az)}},[tU,s,az]);let a$=(0,x.useCallback)(e=>{eL(e)&&aO(!0),g.oR.error(o("Please fix the highlighted fields before saving"))},[aO,o]),aF=(0,x.useCallback)(e=>{n(e),e||(e$.reset(e2),X.current=!1,et(lC),ea(void 0),en(!1),eu(null))},[n,e$]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(sa.cj,{open:s,onOpenChange:aF,children:(0,a.jsxs)(sa.h,{className:(0,t7.jW)("sm:max-w-5xl"),children:[(0,a.jsx)(sa.Fm,{className:(0,t7.Dt)(),children:(0,a.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsxs)(sa.qp,{className:"flex items-center gap-3",children:[(0,a.jsx)(tf.f,{tone:"info",size:"title",children:(0,a.jsx)(lB,{type:eq,size:22})}),(0,a.jsxs)("span",{children:[em?o("Edit Channel"):o("Create Channel"),(0,a.jsx)("span",{className:"text-muted-foreground ml-2 text-sm font-normal",children:o(t8)})]})]}),(0,a.jsx)(sa.Qs,{className:"mt-1",children:em?o("Update channel configuration and click save when you're done."):o("Add a new channel by providing the necessary information.")})]}),!em&&(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",className:"shrink-0",onClick:tK,children:[(0,a.jsx)(s2.A,{className:"size-4"}),(0,a.jsx)("span",{children:o("Paste Connection Info")})]})]})}),ep&&(0,a.jsx)(tC.Fc,{className:"border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-50",children:(0,a.jsxs)(tC.TN,{children:[o("Sensitive channel settings are read-only for your account.")," ",o("You can still edit non-sensitive operations fields such as models, groups, priority, and weight.")]})}),!em&&ec&&(0,a.jsx)(tC.Fc,{children:(0,a.jsxs)(tC.TN,{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsx)("span",{children:o("Connection info detected in clipboard")}),(0,a.jsxs)("span",{className:"flex shrink-0 gap-2",children:[(0,a.jsx)(tg.$,{type:"button",size:"sm",onClick:()=>tV(ec),children:o("Fill in")}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>eu(null),children:o("Ignore")})]})]})}),(0,a.jsx)(an.lV,{...e$,children:(0,a.jsx)("form",{id:"channel-form",ref:Q,onSubmit:e$.handleSubmit(aM,a$),className:(0,t7.e)("gap-
15"),children:tU?(0,a.jsx)(ly,{}):(0,a.jsxs)("div",{className:"grid gap-5 lg:grid-cols-[13rem_minmax(0,1fr)] lg:items-start",children:[(0,a.jsx)(lJ,{providerLogo:(0,a.jsx)(lB,{type:eq,size:18}),providerLabel:o(t8),statusLabel:o(sx),progressLabel:sg,navigationLabel:o("Channels"),items:sT,activeItemId:ee,expandedItemId:es,onNavigate:aT}),(0,a.jsxs)("div",{className:"flex min-w-0 flex-col gap-5",children:[(0,a.jsx)("div",{id:lC,className:"scroll-mt-4",children:(0,a.jsxs)(lv,{children:[(0,a.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,a.jsx)("fieldset",{disabled:ep,className:"min-w-0 disabled:opacity-60",children:(0,a.jsx)(an.zB,{control:e$.control,name:"type",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Type *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsxs)("div",{className:"relative",children:[(0,a.jsx)("span",{className:"pointer-events-none absolute top-1/2 left-3 z-10 flex -translate-y-1/2",children:(0,a.jsx)(lB,{type:Number(t.value),size:18})}),(0,a.jsx)(al.G3,{options:t9,value:String(t.value),onValueChange:e=>{let s=Number(e);Number.isInteger(s)&&s>0&&t.onChange(s)},placeholder:o("Select channel type"),searchPlaceholder:o("Search channel type..."),emptyText:o("No channel type found."),className:"pl-10",allowCustomValue:!0,openOnFocus:!1})]})}),ep&&(0,a.jsx)(an.Rr,{children:o("No permission to perform this action")}),(0,a.jsx)(an.C5,{})]})}})}),(0,a.jsx)(an.zB,{control:e$.control,name:"name",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Name *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., OpenAI GPT-4 Production"),...t})}),(0,a.jsx)(an.C5,{})]})}})]}),!em&&(0,a.jsx)(an.zB,{control:e$.control,name:"status",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:(0,t7.fE)(),children:[(0,a.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,a.jsx)(an.lR,{children:o("Enabled")}),(0,a.jsx)(an.Rr,{className:"text-xs",children:o("Enable or disable this channel")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:1===t.value,onCheckedChange:e=>t.onChange(e?1:2)})})]})}}),1===eq&&(0,a.jsx)("fieldset",{disabled:ep,className:"disabled:opacity-60",children:(0,a.jsx)(an.zB,{control:e$.control,name:"openai_organization",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("OpenAI Organization")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("org-..."),...t})}),(0,a.jsx)(an.Rr,{children:ep?o("No permission to perform this action"):o("OpenAI Organization ID (optional)")}),(0,a.jsx)(an.C5,{})]})}})})]})}),(0,a.jsx)("div",{id:lA,className:"scroll-mt-4",children:(0,a.jsxs)(lf,{children:[V[eq]&&(0,a.jsx)(tC.Fc,{children:(0,a.jsx)(tC.TN,{children:o(V[eq])})}),ep&&(0,a.jsx)(tC.Fc,{className:"border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-50",children:(0,a.jsx)(tC.TN,{children:o("No permission to perform this action")})}),(0,a.jsx)("div",{className:"border-border/60 bg-muted/10 rounded-lg border p-4",children:(0,a.jsxs)("fieldset",{disabled:ep,className:"space-y-4 disabled:opacity-60",children:[3===eq&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(an.zB,{control:e$.control,name:"base_url",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("AZURE_OPENAI_ENDPOINT *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., https://docs-test-001.openai.azure.com"),...t})}),(0,a.jsx)(an.Rr,{children:o("Your Azure OpenAI endpoint URL")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"other",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Default API Version *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., 2025-04-01-preview"),...t})}),(0,a.jsx)(an.Rr,{children:o("Default API version for this channel")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"azure_responses_version",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Responses API Version")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., preview"),...t})}),(0,a.jsx)(an.Rr,{children:o("Default Responses API version, if empty, will use the API version above")}),(0,a.jsx)(an.C5,{})]})}})]}),8===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"base_url",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsxs)(an.lR,{children:[o("Full Base URL (supports")," ","{",o("model"),"}"," ",o("variable) *")]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., https://api.openai.com/v1/c
1hat/completions"),...t})}),(0,a.jsxs)(an.Rr,{children:[o("Enter the complete URL, supports")," ","{",o("model"),"}"," ",o("variable")]}),(0,a.jsx)(an.C5,{})]})}}),18===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"other",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Model Version *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., v2.1"),...t})}),(0,a.jsx)(an.Rr,{children:o("Spark model version, e.g., v2.1 (version number in API URL)")}),(0,a.jsx)(an.C5,{})]})}}),20===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"is_enterprise_account",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Enterprise Account")}),(0,a.jsx)(an.Rr,{children:o("Enable if this is an OpenRouter enterprise account with special response format")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),33===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"aws_key_type",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("AWS Key Format")}),(0,a.jsxs)(ss.l6,{items:[{value:"ak_sk",label:o("AccessKey / SecretAccessKey")},{value:"api_key",label:o("API Key")}],onValueChange:t.onChange,value:t.value,children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{children:(0,a.jsx)(ss.yv,{placeholder:o("Select key format")})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"ak_sk",children:o("AccessKey / SecretAccessKey")}),(0,a.jsx)(ss.eb,{value:"api_key",children:o("API Key")})]})})]}),(0,a.jsx)(an.Rr,{children:"api_key"===t.value?o("API Key mode: use APIKey|Region"):o("AK/SK mode: use AccessKey|SecretAccessKey|Region")}),(0,a.jsx)(an.C5,{})]})}}),21===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"other",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Knowledge Base ID *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., 123456"),...t})}),(0,a.jsx)(an.Rr,{children:o("Enter the knowledge base ID")}),(0,a.jsx)(an.C5,{})]})}}),22===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"base_url",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Private Deployment URL")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., https://fastgpt.run/api/openapi"),...t})}),(0,a.jsx)(an.Rr,{children:o("For private deployments, format: https://fastgpt.run/api/openapi")}),(0,a.jsx)(an.C5,{})]})}}),36===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"base_url",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("API Base URL (Important: Not Chat API) *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., https://api.example.com (path before /suno)"),...t})}),(0,a.jsx)(an.Rr,{children:o("Enter the path before /suno, usually just the domain")}),(0,a.jsx)(an.C5,{})]})}}),39===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"other",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Account ID *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., d6b5da8hk1awo8nap34ube6gh"),...t})}),(0,a.jsx)(an.Rr,{children:o("Your Cloudflare Account ID")}),(0,a.jsx)(an.C5,{})]})}}),40===eq&&(0,a.jsx)(tC.Fc,{children:(0,a.jsxs)(tC.TN,{children:[o("Referral link:")," ",(0,a.jsx)("a",{href:"https://cloud.siliconflow.cn/i/hij0YNTZ",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:o("https://cloud.siliconflow.cn/i/hij0YNTZ")})]})}),41===eq&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(an.zB,{control:e$.control,name:"vertex_key_type",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Vertex AI Key Format")}),(0,a.jsxs)(ss.l6,{items:[{value:"json",label:o("JSON")},{value:"api_key",label:o("API Key")}],onValueChange:t.onChange,value:t.value,children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{children:(0,a.jsx)(ss.yv,{})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"json",children:o("JSON")}),(0,a.jsx)(ss.eb,{value:"api_key",children:o("API Key")})]})})]}),(0,a.jsx)(an.Rr,{children:"json"===t.value?o("JSON format supports service account JSON files"):o("API Key mode (does not support batch creation)")}),(0,a.jsx)(an.C5,{})]})}}),"json"===e8&&(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Service account JSON file(s)")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{type:"file",accept:".json,application/json",multiple:tW,onChange:async e=>{let t=e.target.files,s=t?[...t]:[];if(e.target.value="",0===s.length)return void g.oR.info(o("Please upload key file(s)"));let a=[];for(let e of s)try{let t=await e.text();a.push(JSON.parse(t))}catch{g.oR.error(o("Failed to parse JSON file: {{name}}",{name:e.name}));return}if(0===a.length)return void g.oR.info(o("Please upload key file(s)"));let l=tW?JSON.stringify(a):JSON.stringify(a[0]);e$.setValue("key",l,{shouldDirty:!0,shouldValidate:!0}),g.oR.success(o("Parsed {{count}} service account file(s)",{count:a.length}))}})}),(0,a.jsx)(an.Rr,{children:tW?o("Upload multiple JSON files in batch modes"):o("Upload a single service account JSON file")}),(0,a.jsx)(an.C5,{})]}),(0,a.jsx)(an.zB,{control:e$.control,name:"other",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Deployment Region *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sq.T,{placeholder:o("e.g., us-central1 or JSON format for model-specific regions"),rows:3,...t})}),(0,a.jsxs)(an.Rr,{children:[o("Enter deployment region or JSON mapping:")," ","{",o('"default": "us-central1", "claude-3-5-sonnet-20240620": "europe-west1"'),"}"]}),(0,a.jsx)(an.C5,{})]})}})]}),45===eq&&!tJ&&(0,a.jsx)(an.zB,{control:e$.control,name:"base_url",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{className:"cursor-pointer select-none",onClick:tq,children:o("API Base URL *")}),(0,a.jsxs)(ss.l6,{items:[{value:"https://ark.cn-beijing.volces.com",label:o("https://ark.cn-beijing.volces.com")},{value:"https://ark.ap-southeast.bytepluses.com",label:o("https://ark.ap-southeast.bytepluses.com")}],onValueChange:t.onChange,value:"doubao-coding-plan"===t.value?"https://ark.cn-beijing.volces.com":t.value||"https://ark.cn-beijing.volces.com",children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{children:(0,a.jsx)(ss.yv,{})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"https://ark.cn-beijing.volces.com",children:o("https://ark.cn-beijing.volces.com")}),(0,a.jsx)(ss.eb,{value:"https://ark.ap-southeast.bytepluses.com",children:o("https://ark.ap-southeast.bytepluses.com")})]})})]}),(0,a.jsx)(an.Rr,{children:o("Select the API endpoint region")}),(0,a.jsx)(an.C5,{})]})}}),45===eq&&tJ&&(0,a.jsx)(an.zB,{control:e$.control,name:"base_url",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("API Base URL *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., https://ark.cn-beijing.volces.com"),...t})}),(0,a.jsx)(an.Rr,{children:o("Enter custom API endpoint URL")}),(0,a.jsx)(an.C5,{})]})}}),49===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"other",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Agent ID *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., 7342866812345"),...t})}),(0,a.jsx)(an.Rr,{children:o("Enter the Coze agent ID")}),(0,a.jsx)(an.C5,{})]})}}),![3,8,22,36,45].includes(eq)&&(0,a.jsx)(an.zB,{control:e$.control,name:"base_url",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Base URL")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("Leave empty to use default"),...t})}),(0,a.jsx)(an.Rr,{children:o("Custom API base URL. For official channels, New API has built-in addresses. Only fill this for third-party proxy sites or special endpoints. Do not add /v1 or trailing slash.")}),(0,a.jsx)(an.C5,{})]})}}),58===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"advanced_custom",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"space-y-3 border-y py-4",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,a.jsxs)("div",{className:"space-y-2",children:[(0,a.jsx)(an.lR,{children:o("Advanced Custom Routes")}),(0,a.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,a.jsxs)(d.E,{variant:"secondary",children:[o("Routes"),":"," ",tY.routeCount]}),tZ.map(e=>(0,a.jsx)(d.E,{variant:"outline",className:"max-w-[12rem]",title:e,children:(0,a.jsx)("span",{className:"truncate",children:e})},e)),tQ>0&&(0,a.jsxs)(d.E,{variant:"outline",title:tX,children:["+",tQ]}),!tY.valid&&(0,a.jsx)(d.E,{variant:"destructive",children:o("Incomplete")}
1)]})]}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>ed(!0),children:[(0,a.jsx)(s4.A,{className:"mr-2 h-4 w-4"}),o("Configure routes")]})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)("input",{type:"hidden",...t})}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsxs)(lj,{children:[!em&&(0,a.jsx)(an.zB,{control:e$.control,name:"multi_key_mode",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsx)(an.lR,{className:"text-muted-foreground text-xs font-medium",children:o("Add Mode")}),(0,a.jsxs)(ss.l6,{items:tG.map(e=>({value:e.value,label:o(e.label)})),onValueChange:t.onChange,value:t.value,children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{size:"sm",className:"w-full sm:w-56",children:(0,a.jsx)(ss.yv,{})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:tG.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:o(e.label)},e.value))})})]}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"key",render:e=>{let{field:t}=e,s=o(L[eq]||"Enter API key for this channel");em?s=o("Leave empty to keep existing key"):33===eq&&"api_key"===e6&&tW?s=o("Enter API Key, one per line, format: APIKey|Region"):33===eq&&"api_key"===e6?s=o("Enter API Key, format: APIKey|Region"):33===eq&&tW?s=o("Enter key, one per line, format: AccessKey|SecretAccessKey|Region"):33===eq?s=o("Enter key, format: AccessKey|SecretAccessKey|Region"):tW&&(s=o("Enter one key per line for batch creation"));let l=o("API key from the provider");if(em){let e=o("Append mode: New keys will be added to the end of the existing key list");"replace"===eD&&(e=o("Replace mode: Will completely replace all existing keys")),l=(0,a.jsxs)(a.Fragment,{children:[o("Enter new key to update, or leave empty to keep current key"),eE&&(0,a.jsx)("span",{className:"text-warning mt-1 block",children:e})]})}else tW&&(l=o("Enter one API key per line for batch creation"));return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("API Key *")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sq.T,{placeholder:s,rows:tW?8:4,...t})}),(0,a.jsx)(an.Rr,{children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)("span",{children:l}),tW&&(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:sU,className:"w-fit",children:[(0,a.jsx)(t5.A,{className:"mr-2 h-4 w-4"}),o("Remove Duplicates")]})]})}),em&&b&&(0,a.jsxs)("div",{className:"border-border/60 mt-4 flex flex-col gap-3 border-y border-dashed py-4",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-sm font-medium",children:o("Current key")}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:o("Verification required to reveal the saved key.")})]}),(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:sY,disabled:S||ek.loading,children:[S||ek.loading?(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}):(0,a.jsx)(s5.A,{className:"mr-2 h-4 w-4"}),o("Reveal key")]}),(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:async()=>{w&&await e_(w)},disabled:!w,children:[(0,a.jsx)(tv.A,{className:"mr-2 h-4 w-4"}),o("Copy")]})]})]}),(0,a.jsx)(se.p,{readOnly:!0,value:w??"",placeholder:o("Hidden — verify to reveal"),className:"font-mono"})]}),(0,a.jsx)(an.C5,{})]})}}),57===eq&&(0,a.jsxs)("div",{className:"border-border/60 flex flex-col gap-3 border-y py-4",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsx)("div",{className:"text-muted-foreground text-xs",children:o("Codex channels use an OAuth JSON credential as the key.")}),(0,a.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:em&&eh&&(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:sX,disabled:ep||M,children:[M?(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}):(0,a.jsx)(tp.A,{className:"mr-2 h-4 w-4"}),M?o("Refreshing..."):o("Refresh credential")]})})]}),(0,a.jsx)(tC.Fc,{className:"border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-50",children:(0,a.jsx)(tC.TN,{children:o("Disclaimer: Personal use only. Do not distribute or share any credentials. This channel has prerequisites and requires prior setup; use it only if you understand the flow and risks, and comply with OpenAI's terms and policies. Credentials and configuration are for Codex CLI integration only, and are not intended for any other client, platform, or channel.")})})]}),em&&eE&&(0,a.jsx)(an.zB,{control:e$.control,name:"key_mode",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Key Update Mode")}),(0,a.jsxs)(ss.l6,{items:[{value:"append",label:o("Append to existing keys")},{value:"replace",label:o("Replace all existing keys")}],onValueChange:t.onChange,value:t.value,children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{children:(0,a.jsx)(ss.yv,{})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"append",children:o("Append to existing keys")}),(0,a.jsx)(ss.eb,{value:"replace",children:o("Replace all existing keys")})]})})]}),(0,a.jsx)(an.Rr,{children:"replace"===t.value?o("Replace mode: Will completely replace all existing keys"):o("Append mode: New keys will be added to the end of the existing key list")}),(0,a.jsx)(an.C5,{})]})}}),!em&&"multi_to_single"===eB&&(0,a.jsx)(an.zB,{control:e$.control,name:"multi_key_type",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Multi-Key Strategy")}),(0,a.jsxs)(ss.l6,{items:[{value:"random",label:o("Random")},{value:"polling",label:o("Polling")}],onValueChange:t.onChange,value:t.value,children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{children:(0,a.jsx)(ss.yv,{})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"random",children:o("Random")}),(0,a.jsx)(ss.eb,{value:"polling",children:o("Polling")})]})})]}),(0,a.jsx)(an.Rr,{children:"polling"===eP?(0,a.jsx)("span",{className:"text-warning",children:o("Polling mode requires Redis and memory cache, otherwise performance will be significantly degraded")}):o("Randomly select a key from the pool for each request")}),(0,a.jsx)(an.C5,{})]})}})]})]})})]})}),(0,a.jsx)("div",{id:lS,className:"scroll-mt-4",children:(0,a.jsx)(lb,{children:(0,a.jsxs)("div",{className:"space-y-5",children:[(0,a.jsxs)("div",{className:"border-border/60 bg-muted/10 rounded-lg border p-4",children:[(0,a.jsx)(an.zB,{control:e$.control,name:"models",render:()=>(0,a.jsxs)(an.eI,{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(an.lR,{children:o("Models *")}),(0,a.jsx)(an.Rr,{children:o("List of models supported by this channel. Use comma to separate multiple models.")})]}),(0,a.jsx)(d.E,{variant:"outline",className:"w-fit",children:o("Selected {{count}}",{count:t6.length})})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sJ.K,{options:s$,selected:t6,onChange:a_,placeholder:o("Select models or add custom ones"),allowCreate:!0,createLabel:'Add custom model "{{value}}"',maxVisibleChips:8,copyChipOnClick:!0})}),sF.exposedTargetModels.length>0&&(0,a.jsx)(tC.Fc,{className:"border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-50",children:(0,a.jsxs)(t
1C.TN,{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("span",{children:[o("The mapped upstream model(s)")," ",lN(sF.exposedTargetModels)," ",o("are also listed here. Remove them from Models to keep the `/v1/models` response user-friendly and hide vendor-specific names.")]}),(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{let e=new Set(sF.exposedTargetModels);ao(t6.filter(t=>!e.has(t)))},children:o("Remove mapped targets")})]})}),(0,a.jsx)(an.C5,{})]})}),(0,a.jsx)(sy.w,{className:"my-4"}),(0,a.jsxs)("div",{className:"space-y-3",children:[(0,a.jsxs)("div",{children:[(0,a.jsx)("p",{className:"text-sm font-medium",children:o("Quick actions")}),(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:o("Use presets or upstream discovery to populate the model list faster.")})]}),(0,a.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:af,disabled:!t1.length,children:[(0,a.jsx)(s3.A,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),o("Fill Related Models")]}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:aj,disabled:!t0.length,children:[(0,a.jsx)(sK.A,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),o("Fill All Models")]}),q.has(eq)&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:am,disabled:!em&&!y,children:[(0,a.jsx)(s6.A,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),o("Fetch from Upstream")]}),!em&&!y&&(0,a.jsx)("span",{className:"text-muted-foreground basis-full text-xs",children:o("No permission to perform this action")})]}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:ay,disabled:0===t6.length,children:[(0,a.jsx)(tv.A,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),o("Copy All")]}),(0,a.jsxs)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:av,disabled:0===t6.length,children:[(0,a.jsx)(s8.A,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),o("Clear All")]})]}),t2.length>0&&(0,a.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,a.jsxs)("span",{className:"text-muted-foreground text-xs",children:[o("Preset groups"),":"]}),t2.map(e=>(0,a.jsx)(tg.$,{type:"button",variant:"secondary",size:"sm",onClick:()=>ab(e),children:e.name},e.id))]})]})]}),(0,a.jsx)("div",{className:"border-border/60 rounded-lg border p-4",children:(0,a.jsx)(an.zB,{control:e$.control,name:"model_mapping",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"space-y-3",children:[(0,a.jsx)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(an.lR,{className:"mb-0",children:o("Model Mapping")}),(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"icon-sm",className:"text-muted-foreground hover:text-foreground size-auto p-0","aria-label":o("How model mapping works")}),children:(0,a.jsx)(s7.A,{className:"h-4 w-4","aria-hidden":"true"})}),(0,a.jsxs)(c.ZI,{side:"top",align:"start",className:"max-w-xs space-y-2 text-left",children:[(0,a.jsx)("p",{className:"text-xs font-semibold tracking-wide uppercase",children:o("Request flow")}),(0,a.jsxs)("div",{className:"space-y-1 font-mono text-xs",children:[sB.map(e=>(0,a.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.jsx)("span",{children:e.source}),(0,a.jsx)(s9.A,{className:"h-3.5 w-3.5 opacity-70","aria-hidden":"true"}),(0,a.jsx)("span",{children:e.target})]},`${e.source}-${e.target}`)),sP>0&&(0,a.jsxs)("div",{className:"text-[11px] opacity-70",children:["+",sP," ",o("more mapping"),sP>1?"s":""]})]}),(0,a.jsx)("p",{className:"text-[11px] leading-relaxed opacity-80",children:o("Users call the model on the left. The platform forwards the request to the upstream model on the right.")})]})]})]}),(0,a.jsx)(an.Rr,{children:o("Map request model names to actual provider model names (JSON format)")})]})}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sH,{value:t.value||"",onChange:t.onChange,disabled:aI,sourceModelOptions:t6,targetModelOptions:s$.map(e=>e.value)})}),sF.invalidJson&&(0,a.jsx)(tC.Fc,{variant:"destructive",children:(0,a.jsxs)(t
1C.TN,{children:[o("Model Mapping must be a JSON object like")," ",(0,a.jsx)("code",{className:"font-mono",children:'{"gpt-4":"Azure-GPT4"}'}),o(". Please fix the JSON before saving.")]})}),sF.missingSourceModels.length>0&&(0,a.jsx)(tC.Fc,{className:"border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-50",children:(0,a.jsxs)(tC.TN,{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,a.jsxs)("span",{children:[o("Add")," ",lN(sF.missingSourceModels)," ",o("to the Models list so users can use them before the mapping sends traffic upstream.")]}),(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{ao([...t6,...sF.missingSourceModels])},children:o("Add missing models")})]})}),(0,a.jsx)(an.C5,{})]})}})}),(0,a.jsx)("div",{className:"border-border/60 rounded-lg border p-4",children:(0,a.jsx)(an.zB,{control:e$.control,name:"group",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(an.lR,{children:o("Groups *")}),(0,a.jsx)(an.Rr,{children:o("User groups that can access this channel. ")})]}),(0,a.jsx)(an.MJ,{children:ev?(0,a.jsx)(tO.E,{className:"h-10 w-full"}):(0,a.jsx)(sJ.K,{options:t4,selected:t.value,onChange:t.onChange,placeholder:o("Please Select user groups that can access this channel.")})}),(0,a.jsx)(an.C5,{})]})}})})]})})}),(0,a.jsx)("div",{id:lR,className:"scroll-mt-4",children:(0,a.jsxs)(lg,{open:el,onOpenChange:aO,summary:s_,children:[(0,a.jsxs)("div",{className:(0,t7.nP)(),children:[(0,a.jsx)(lE,{title:o("Routing & Overrides"),icon:(0,a.jsx)(s4.A,{className:"h-4 w-4"}),iconTone:"info"}),(0,a.jsxs)("div",{id:lM.routingStrategy,className:lF("flex scroll-mt-4 flex-col gap-4",sN),children:[(0,a.jsx)(l$,{title:o("Routing Strategy"),icon:(0,a.jsx)(s4.A,{className:"h-3.5 w-3.5"}),iconTone:"info"}),(0,a.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,a.jsx)(an.zB,{control:e$.control,name:"priority",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Priority")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{type:"number",placeholder:"0",...t,onChange:e=>t.onChange(Number(e.target.value))})}),(0,a.jsx)(an.Rr,{children:o("Higher priority channels are selected first")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"weight",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Weight")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{type:"number",placeholder:"0",...t,onChange:e=>t.onChange(Number(e.target.value))})}),(0,a.jsx)(an.Rr,{children:o("Used for load balancing. Higher weight = more requests")}),(0,a.jsx)(an.C5,{})]})}})]}),(0,a.jsx)(an.zB,{control:e$.control,name:"test_model",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Test Model")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("Model to use for testing"),...t})}),(0,a.jsx)(an.Rr,{children:o("Model to use when testing channel connectivity")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"auto_ban",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Auto Ban")}),(0,a.jsx)(an.Rr,{children:o("Automatically disable channel on repeated failures")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:1===t.value,onCheckedChange:e=>t.onChange(+!!e)})})]})}})]}),(0,a.jsxs)("div",{id:lM.internalNotes,className:lF("flex scroll-mt-4 flex-col gap-4 border-t pt-4",sw),children:[(0,a.jsx)(l$,{title:o("Internal Notes"),icon:(0,a.jsx)(s3.A,{className:"h-3.5 w-3.5"}),iconTone:"chart-3"}),(0,a.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,a.jsx)(an.zB,{control:e$.control,name:"tag",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Tag")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("Optional tag for grouping channels"),...t})}),(0,a.jsx)(an.Rr,{children:o("Group channels by tag for batch operations")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"remark",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Remark")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sq.T,{placeholder:o("Optional notes about this channel"),rows:2,...t})}),(0,a.jsx)(an.Rr,{children:o("Internal notes (not shown to users)")}),(0,a.jsx)(an.C5,{})]})}})]})]}),(0,a.jsxs)("div",{id:lM.overrideRules,className:lF("flex scroll-mt-4 flex-col gap-4 border-t pt-4",sC),children:[(0,a.jsx)(l$,{title:o("Override Rules"),icon:(0,a.jsx)(sV.A,{className:"h-3.5 w-3.5"}),iconTone:"chart-4"}),(0,a.jsx)(an.zB,{control:e$.control,name:"status_code_mapping",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"space-y-3",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(an.lR,{children:o("Status Code Mapping")}),(0,a.jsx)(an.Rr,{children:o("Map upstream status codes to different c
1odes")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(aa.i,{value:t.value||"",onChange:t.onChange,disabled:aI,keyPlaceholder:"400",valuePlaceholder:"500",keyLabel:"Original Code",valueLabel:"Mapped Code",emptyMessage:o("No status code mappings configured."),template:{400:"500",429:"503"},valueType:"string"})}),(0,a.jsx)(an.C5,{})]})}}),ep&&(0,a.jsx)("p",{className:"text-muted-foreground text-xs",children:o("No permission to perform this action")}),(0,a.jsxs)("fieldset",{disabled:ep,className:"space-y-4 disabled:opacity-60",children:[(0,a.jsx)(an.zB,{control:e$.control,name:"param_override",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"space-y-3 border-t pt-4",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(an.lR,{children:o("Parameter Override")}),(0,a.jsx)(an.Rr,{children:o("Override request parameters. Cannot override stream parameter.")})]}),(0,a.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>ei(!0),children:[(0,a.jsx)(ae.A,{className:"mr-2 h-4 w-4"}),o("Visual edit")]}),(0,a.jsxs)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>{t.onChange(JSON.stringify({operations:[{path:"temperature",mode:"set",value:.7,conditions:[{path:"model",mode:"prefix",value:"gpt"}],logic:"AND"}]},null,2))},children:[(0,a.jsx)(sV.A,{className:"mr-2 h-4 w-4"}),o("New Format Template")]}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>t.onChange(""),children:o("Clear")})]})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sv.B,{value:t.value||"",onChange:t.onChange,name:t.name,onBlur:t.onBlur,textareaRef:t.ref,disabled:ep||aI,placeholder:o("Override request parameters. Cannot override stream parameter.")})}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"header_override",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"space-y-3 border-t pt-4",children:[(0,a.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[(0,a.jsxs)("div",{className:"space-y-1",children:[(0,a.jsx)(an.lR,{children:o("Request Header Override")}),(0,a.jsx)(an.Rr,{children:o("Override request headers")})]}),(0,a.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>t.onChange(JSON.stringify({"*":!0,"re:^X-Trace-.*$":!0,"X-Foo":"{client_header:X-Foo}",Authorization:"Bearer {api_key}"},null,2)),children:o("Fill Template")}),(0,a.jsx)(tg.$,{type:"button",variant:"outline",size:"sm",onClick:()=>t.onChange(JSON.stringify({"*":!0},null,2)),children:o("Passthrough Template")}),(0,a.jsx)(tg.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>t.onChange(""),children:o("Clear")})]})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sv.B,{value:t.value||"",onChange:t.onChange,name:t.name,onBlur:t.onBlur,textareaRef:t.ref,disabled:ep||aI,placeholder:o("Enter JSON to override request headers"),heightClassName:"h-40 min-h-40 max-h-40"})}),(0,a.jsxs)(an.Rr,{className:"text-xs",children:[o("Supported variables"),":"," ",(0,a.jsx)("code",{className:"bg-muted rounded px-1 py-0.5",children:"{api_key}"})," ","— ",o("Channel key"),","," ",(0,a.jsx)("code",{className:"bg-muted rounded px-1 py-0.5",children:"{client_header:NAME}"})," ","— ",o("Client header value")]}),(0,a.jsx)(an.C5,{})]})}})]})]})]}),(0,a.jsxs)("div",{id:lM.extraSettings,className:(0,t7.nP)(lF("scroll-mt-4",sA)),children:[(0,a.jsx)(lE,{title:o("Channel Extra Settings"),icon:(0,a.jsx)(t3.A,{className:"h-4 w-4"}),iconTone:"chart-3"}),ep&&(0,a.jsx)(tC.Fc,{className:"border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-50",children:(0,a.jsx)(tC.TN,{children:o("No permission to perform this action")})}),(0,a.jsxs)("fieldset",{disabled:ep,className:"space-y-4 disabled:opacity-60",children:[(0,a.jsxs)("div",{className:"divide-border space-y-0 divide-y border-y",children:[1===eq&&(0,a.jsx)(an.zB,{control:e$.control,name:"force_format",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Force Format")}),(0,a.jsx)(an.Rr,{children:o("Force format response to OpenAI standard (OpenAI channel only)")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"thinking_to_content",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Thinking to Content")}),(0,a.jsx)(an.Rr,{children:o("Convert reasoning_content to <think> tag in content")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"pass_through_body_enabled",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Pass Through Body")}),(0,a.jsx)(an.Rr,{children:o("Pass request body directly to upstream")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"disable_task_polling_sleep",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Skip async task polling delay")}),(0,a.jsx)(an.Rr,{children:o("Do not wait one second between polling async tasks for this channel")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}})]}),(0,a.jsx)(an.zB,{control:e$.control,name:"proxy",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Proxy Address")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("socks5://user:pass@host:port"),...t})}),(0,a.jsx)(an.Rr,{children:o("Network proxy for this channel (supports HTTP, HTTPS, SOCKS5, and SOCKS5H)")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"http_protocol",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("HTTP Protocol")}),(0,a.jsxs)(ss.l6,{items:[{value:"auto",label:o("Auto")},{value:"http1",label:o("HTTP/1.1")}],value:t.value||"auto",onValueChange:e=>{let s="http1"===e?"http1":"auto";t.onChange(s),"http1"===s&&e$.setValue("http2_connection_shards",1,{shouldDirty:!0,shouldValidate:!0})},children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{children:(0,a.jsx)(ss.yv,{})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsxs)(ss.s3,{children:[(0,a.jsx)(ss.eb,{value:"auto",children:o("Auto")}),(0,a.jsx)(ss.eb,{value:"http1",children:o("HTTP/1.1")})]})})]}),(0,a.jsx)(an.Rr,{children:o("Auto negotiates HTTP/2 when available. HTTP/1.1 forces multiple keep-alive connections under concurrency.")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"http2_connection_shards",render:e=>{let{field:t}=e,s="http1"===tw,l=Array.from({length:8},(e,t)=>{let s=String(t+1);return{value:s,label:s}});return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("HTTP/2 Connection Shards")}),(0,a.jsxs)(ss.l6,{items:l,value:String(t.value||1),disabled:s,onValueChange:e=>
1{t.onChange(Number(e))},children:[(0,a.jsx)(an.MJ,{children:(0,a.jsx)(ss.bq,{disabled:s,children:(0,a.jsx)(ss.yv,{})})}),(0,a.jsx)(ss.gC,{alignItemWithTrigger:!1,children:(0,a.jsx)(ss.s3,{children:l.map(e=>(0,a.jsx)(ss.eb,{value:e.value,children:e.label},e.value))})})]}),(0,a.jsx)(an.Rr,{children:s?o("HTTP/2 connection shards are unavailable when HTTP/1.1 is selected."):o("Spread HTTP/2 traffic across multiple reusable connections to the same upstream origin (1-8).")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"system_prompt",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("System Prompt")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sq.T,{placeholder:o("Enter system prompt (user prompt takes priority)"),rows:3,...t})}),(0,a.jsx)(an.Rr,{children:o("Default system prompt for this channel")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"system_prompt_override",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("System Prompt Concatenation")}),(0,a.jsx)(an.Rr,{children:o("Concatenate channel system prompt with user&apos;s prompt")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}})]})]}),(1===eq||14===eq||57===eq)&&(0,a.jsxs)("div",{id:lM.fieldPassthrough,className:(0,t7.nP)(lF("scroll-mt-4",sR)),children:[(0,a.jsx)(lE,{title:o("Field passthrough controls"),icon:(0,a.jsx)(at.A,{className:"h-4 w-4"}),iconTone:"chart-4"}),(0,a.jsx)("fieldset",{disabled:ep,className:"disabled:opacity-60",children:(0,a.jsxs)("div",{className:"divide-border space-y-0 divide-y border-y",children:[(0,a.jsx)(an.zB,{control:e$.control,name:"allow_service_tier",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Allow service_tier passthrough")}),(0,a.jsx)(an.Rr,{children:o("Pass through the service_tier field")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(1===eq||57===eq)&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(an.zB,{control:e$.control,name:"disable_store",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Disable store passthrough")}),(0,a.jsx)(an.Rr,{children:o("When enabled, the store field will be blocked")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"allow_safety_identifier",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Allow safety_identifier passthrough")}),(0,a.jsx)(an.Rr,{children:o("Pass through the safety_identifier field")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"allow_include_obfuscation",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Allow include usage obfuscation passthrough")}),(0,a.jsx)(an.Rr,{children:o("Pass through the include field for usage obfuscation")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"allow_inference_geo",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Allow inference geography passthrough")}),(0,a.jsx)(an.Rr,{children:o("Pass through the inference_geo field for geographic routing")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}})]}),14===eq&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(an.zB,{control:e$.control,name:"allow_inference_geo",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Allow inference_geo passthrough")}),(0,a.jsx)(an.Rr,{children:o("Pass through the inference_geo field for Claude data residency region control")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"allow_speed",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Allow speed passthrough")}),(0,a.jsx)(an.Rr,{children:o("Pass through the speed field for Claude inference speed mode control")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"claude_beta_query",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{className:"text-sm",children:o("Allow Claude beta query passthrough")}),(0,a.jsx)(an.Rr,{children:o("Pass through the anthropic-beta header for beta features")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}})]})]})})]}),q.has(eq)&&(0,a.jsxs)("div",{id:lM.upstreamModelDetection,className:(0,t7.nP)(lF("scroll-mt-4",sI)),children:[(0,a.jsx)(lE,{title:o("Upstream Model Detection Settings"),icon:(0,a.jsx)(tp.A,{className:"h-4 w-4"}),iconTone:"info"}),(0,a.jsxs)("fieldset",{disabled:ep,className:"space-y-4 disabled:opacity-60",children:[(0,a.jsxs)("div",{className:"divide-border space-y-0 divide-y border-y",children:[(0,a.jsx)(an.zB,{control:e$.control,name:"upstream_model_update_check_enabled",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Upstream Model Update Check")}
1),(0,a.jsx)(an.Rr,{children:o("Periodically check for upstream model changes")}),(0,a.jsx)(an.C5,{})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,onCheckedChange:t.onChange})})]})}}),(0,a.jsx)(an.zB,{control:e$.control,name:"upstream_model_update_auto_sync_enabled",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{className:"flex items-center justify-between px-4 py-3",children:[(0,a.jsxs)("div",{className:"space-y-0.5",children:[(0,a.jsx)(an.lR,{children:o("Auto Sync Upstream Models")}),(0,a.jsx)(an.Rr,{children:o("Automatically sync model list when upstream changes are detected")})]}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(sl.d,{checked:t.value,disabled:!e7,onCheckedChange:t.onChange})})]})}})]}),(0,a.jsx)(an.zB,{control:e$.control,name:"upstream_model_update_ignored_models",render:e=>{let{field:t}=e;return(0,a.jsxs)(an.eI,{children:[(0,a.jsx)(an.lR,{children:o("Ignored upstream models")}),(0,a.jsx)(an.MJ,{children:(0,a.jsx)(se.p,{placeholder:o("e.g., gpt-4.1-nano,regex:^claude-.*$,regex:^sora-.*$"),...t})}),(0,a.jsx)(an.Rr,{children:o("Comma-separated exact model names. Prefix with regex: to ignore by regular expression.")}),(0,a.jsx)(an.C5,{})]})}}),(0,a.jsxs)("div",{className:"text-muted-foreground space-y-2 border-t pt-3 text-xs",children:[(0,a.jsxs)("div",{children:[(0,a.jsxs)("span",{className:"text-foreground font-medium",children:[o("Last check time"),":"]})," ",!Number.isFinite(t=Number(sD.lastCheckTime))||t<=0?"-":new Date(1e3*t).toLocaleString()]}),(0,a.jsxs)("div",{children:[(0,a.jsxs)("span",{className:"text-foreground font-medium",children:[o("Last detected addable models"),":"]})," ",0===sD.detectedModels.length?o("None"):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{className:"break-all",children:sL.join(", ")}),sW>0&&(0,a.jsx)("span",{className:"ml-1",children:o("({{total}} total, {{omit}} omitted)",{total:sD.detectedModels.length,omit:sW})})]})]})]})]})]})]})})]})]})})}),(0,a.jsxs)(sa.XW,{className:(0,t7.Jx)(),children:[(0,a.jsx)(sa.kN,{render:(0,a.jsx)(tg.$,{variant:"outline",disabled:aI}),children:o("Cancel")}),(0,a.jsxs)(tg.$,{form:"channel-form",type:"submit",disabled:aI,children:[aI&&(0,a.jsx)(th.A,{className:"mr-2 h-4 w-4 animate-spin"}),em?o("Update Channel"):o("Save changes")]})]})]})}),er&&!ep&&(0,a.jsx)(li,{open:er,value:e$.watch("param_override")||"",onOpenChange:ei,onSave:e=>{e$.setValue("param_override",e,{shouldDirty:!0,shouldValidate:!0})}}),eo&&!ep&&(0,a.jsx)(aR,{open:eo,value:e$.watch("advanced_custom")||"",onOpenChange:ed,onSave:e=>{e$.setValue("advanced_custom",e,{shouldDirty:!0,shouldValidate:!0})}}),(0,a.jsx)(sk,{open:_,onOpenChange:N,onModelsSelected:e=>{e$.setValue("models",tn(e))},redirectModels:sz,redirectSourceModels:sE,customFetcher:tD?ag:void 0,channelName:tD?eX?.trim():void 0,existingModelsOverride:tD?tl(e$.getValues("models")||""):void 0}),(0,a.jsx)(ar.x9,{open:eN,onOpenChange:e=>{e||eS()},methods:ew,state:ek,onVerify:async(e,t)=>{await eC(e,t)},onCancel:eS,onCodeChange:eR,onMethodChange:eI}),(0,a.jsx)(aE,{open:U,missingModels:G,onConfirm:ak,onOpenChange:H}),(0,a.jsx)(lx,{open:B,onOpenChange:e=>{e||aA(!1)},detailItems:D,onConfirm:()=>aA(!0)})]})}function lL(){let{open:e,setOpen:t,currentRow:s,upstream:l}=tu();return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(lq,{open:"create-channel"===e||"update-channel"===e,onOpenChange:e=>!e&&t(null),currentRow:"update-channel"===e?s:null}),(0,a.jsx)(sc,{open:"test-channel"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(t1,{open:"balance-query"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(sk,{open:"fetch-models"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(sP,{open:"ollama-models"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(sf,{open:"copy-channel"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(sM,{open:"multi-key-manage"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(sG,{open:"tag-batch-edit"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(sb,{open:"edit-tag"===e,onOpenChange:e=>!e&&t(null)}),(0,a.jsx)(sY,{open:l.showModal,addModels:l.addModels,removeModels:l.removeModels,preferredTab:l.preferredTab,confirmLoading:l.applyLoading,onConfirm:l.applyUpdates,onCancel:l.closeModal})]})}var lV=s(88664),lK=s(16129),lW=s(59213),lU=s(50947),lH=s(38409),lG=s(77409),lY=s(84368);function lZ(){let{t:e}=(0,i.Bd)(),{setOpen:t,setCurrentRow:s,enableTagMode:l,setEnableTagMode:n,idSort:o,setIdSort:d,batchMode:u,setBatchMode:h,upstream:g}
1=tu(),f=(0,p.jE)(),[j,v]=(0,x.useState)(!1),[y,b]=(0,x.useState)(!1),[_,N]=(0,x.useState)(!1),w=(0,m.n)(e=>e.auth.user),k=(0,sS._m)(w,sS.kB.CHANNEL,sS.YG.SENSITIVE_WRITE),C=e=>{localStorage.setItem("enable-tag-mode",String(e)),n(e)},A=e=>{localStorage.setItem("channels-id-sort",String(e)),d(e)},S=e=>{h(e)};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsxs)("div",{className:"hidden items-center gap-2 rounded-md border px-3 py-1.5 sm:flex",children:[(0,a.jsx)(lV.A,{className:"text-muted-foreground h-4 w-4"}),(0,a.jsx)(st.J,{htmlFor:"channel-batch-mode",className:"cursor-pointer text-sm",children:e("Batch Operations")}),(0,a.jsx)(sl.d,{id:"channel-batch-mode",checked:u,onCheckedChange:S})]}),(0,a.jsxs)("div",{className:"hidden items-center gap-2 rounded-md border px-3 py-1.5 sm:flex",children:[(0,a.jsx)(lK.A,{className:"text-muted-foreground h-4 w-4"}),(0,a.jsx)(st.J,{htmlFor:"tag-mode",className:"cursor-pointer text-sm",children:e("Tag Mode")}),(0,a.jsx)(sl.d,{id:"tag-mode",checked:l,onCheckedChange:C})]}),(0,a.jsxs)("div",{className:"hidden items-center gap-2 rounded-md border px-3 py-1.5 sm:flex",children:[(0,a.jsx)(lW.A,{className:"text-muted-foreground h-4 w-4"}),(0,a.jsx)(st.J,{htmlFor:"id-sort",className:"cursor-pointer text-sm",children:e("Sort by ID")}),(0,a.jsx)(sl.d,{id:"id-sort",checked:o,onCheckedChange:A})]}),(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)("span",{className:"inline-flex"}),children:(0,a.jsxs)(tg.$,{onClick:()=>{k&&(s(null),t("create-channel"))},size:"sm",disabled:!k,children:[(0,a.jsx)(sK.A,{className:"h-4 w-4"}),(0,a.jsx)("span",{className:"max-sm:hidden",children:e("Create Channel")}),(0,a.jsx)("span",{className:"sm:hidden",children:e("Create")})]})}),!k&&(0,a.jsx)(c.ZI,{children:e("No permission to perform this action")})]}),(0,a.jsxs)(lY.rI,{children:[(0,a.jsx)(lY.ty,{render:(0,a.jsx)(tg.$,{variant:"outline",size:"sm"}),children:(0,a.jsx)(lU.A,{className:"h-4 w-4"})}),(0,a.jsxs)(lY.SQ,{align:"end",className:"w-56",children:[(0,a.jsxs)(lY.hO,{className:"sm:hidden",checked:u,onCheckedChange:S,children:[(0,a.jsx)(lV.A,{className:"mr-2 h-4 w-4"}),e("Batch Operations")]}),(0,a.jsxs)(lY.hO,{className:"sm:hidden",checked:l,onCheckedChange:C,children:[(0,a.jsx)(lK.A,{className:"mr-2 h-4 w-4"}),e("Tag Mode")]}),(0,a.jsxs)(lY.hO,{className:"sm:hidden",checked:o,onCheckedChange:A,children:[(0,a.jsx)(lW.A,{className:"mr-2 h-4 w-4"}),e("Sort by ID")]}),(0,a.jsx)(lY.mB,{className:"sm:hidden"}),(0,a.jsxs)(lY._2,{onClick:()=>{ec(f)},children:[e("Test All Channels"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(lH.A,{className:"h-4 w-4"})})]}),(0,a.jsxs)(lY._2,{onClick:()=>{eu(f)},children:[e("Update All Balances"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(tm.A,{className:"h-4 w-4"})})]}),(0,a.jsx)(lY.mB,{}),(0,a.jsxs)(lY._2,{onClick:()=>g.detectAllUpdates(),disabled:g.detectAllLoading,children:[e("Detect All Upstream Updates"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(tp.A,{className:"h-4 w-4"})})]}),(0,a.jsxs)(lY._2,{onClick:()=>g.applyAllUpdates(),disabled:g.applyAllLoading,children:[e("Apply All Upstream Updates"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(lG.A,{className:"h-4 w-4"})})]}),(0,a.jsx)(lY.mB,{}),(0,a.jsxs)(lY._2,{onSelect:e=>{e.preventDefault(),b(!0)},children:[e("Repair Channel Consistency"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(r.A,{className:"h-4 w-4"})})]}),(0,a.jsx)(lY.mB,{}),(0,a.jsxs)(lY._2,{onSelect:e=>{e.preventDefault(),k&&v(!0)},disabled:!k,className:"text-destructive focus:text-destructive",children:[e("Delete All Disabled"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(t5.A,{className:"h-4 w-4"})})]})]})]})]}),(0,a.jsx)(tw.T,{open:j,onOpenChange:v,title:e("Delete All Disabled Channels?"),desc:e("This will permanently delete all manually and automatically disabled channels. This action cannot be undone."),destructive:!0,handleConfirm:()=>{k&&(eo(f,e=>{}),v(!1))}}),(0,a.jsx)(tw.T,{open:y,onOpenChange:b,title:e("Repair channel consistency?"),desc:e("This will rebuild the channel routing index from every channel configuration, including supported models, groups, priorities, and weights. Routing may be briefly incomplete while the rebuild is running. Continue?"),confirmText:e("Repair"),isLoading:_,handleConfirm:async()=>{N(!0);try{await ed(f,e=>{}),b(!1)}finally{N(!1)}}})]})}var lQ=s(2718),lX=s(5333),l0=s(7579),l1=s(8803),l2=s(55581);let l4=(0,x.createContext)("table"),l5="••••",l3=(0,x.memo)(function(e){let{row:t,isSelected:s}=e,{t:l}=(0,i.Bd)(),{sensitiveVisible:n}=tu(),r=ts(t.original),o=t.getAllCells(),d=e=>
1{let t=o.find(t=>t.column.id===e);return t&&t.column.columnDef.cell?(0,l2.Kv)(t.column.columnDef.cell,t.getContext()):null},c={balance:l("Used / Remaining"),response_time:l("Response"),test_time:l("Last Tested")},u=te(t.original.group??""),m=d("select"),h=d("type"),p=d("name"),x=d("status"),g=d("actions"),f=d("priority"),j=d("weight"),v=d("balance"),y=d("response_time"),b=d("test_time"),_="text-muted-foreground text-[11px] font-medium select-none",N=r||1!==t.original.status&&2!==t.original.status;return(0,a.jsx)(l4.Provider,{value:"card",children:(0,a.jsxs)("div",{"data-state":s?"selected":void 0,className:"flex flex-col gap-3",children:[(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,a.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[!r&&m&&(0,a.jsx)("span",{className:"shrink-0",children:m}),(0,a.jsx)("div",{className:"min-w-0 overflow-hidden",children:h})]}),(0,a.jsxs)("div",{className:"flex shrink-0 items-center gap-1.5",children:[N&&x,g]})]}),(0,a.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,a.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-3 overflow-hidden",children:[(0,a.jsxs)("div",{className:"min-w-0 text-sm",children:[!r&&(0,a.jsxs)("div",{className:_,children:["#",n?t.original.id:l5]}),p]}),(0,a.jsxs)("div",{className:"min-w-0",children:[(0,a.jsx)("div",{className:(0,tE.cn)("mb-1",_),children:c.balance}),(0,a.jsx)("div",{className:"min-w-0 overflow-hidden text-sm",children:v??(0,a.jsx)("span",{className:"text-muted-foreground",children:"-"})})]})]}),(0,a.jsxs)("div",{className:"grid shrink-0 grid-cols-[auto_auto] items-center gap-x-3 gap-y-1",children:[(0,a.jsx)("span",{className:_,children:l("Priority")}),(0,a.jsx)("span",{className:_,children:l("Weight")}),(0,a.jsx)("div",{className:"flex justify-start",children:f}),(0,a.jsx)("div",{className:"flex justify-start",children:j}),(0,a.jsx)("span",{className:(0,tE.cn)("mt-2",_),children:c.response_time}),(0,a.jsx)("span",{className:(0,tE.cn)("mt-2",_),children:c.test_time}),(0,a.jsx)("div",{className:"overflow-hidden text-sm",children:y??(0,a.jsx)("span",{className:"text-muted-foreground",children:"-"})}),(0,a.jsx)("div",{className:"overflow-hidden text-sm",children:b??(0,a.jsx)("span",{className:"text-muted-foreground",children:"-"})})]})]}),(0,a.jsx)("div",{className:"min-w-0",children:u.length>0?(0,a.jsx)("div",{className:"-ml-1.5 flex flex-wrap gap-1",children:u.map(e=>(0,a.jsx)(sj.d,{group:e,label:n?void 0:l5,size:"sm"},e))}):(0,a.jsx)("span",{className:"text-muted-foreground text-sm",children:"-"})})]})})});var l6=s(63162),l8=s(30970),l7=s(74764),l9=s(28079),ne=s(81532);function nt(e){let{text:t,className:s,maxWidth:l="max-w-[200px]",side:n="top"}=e;return(0,a.jsx)(ne.T,{className:(0,tE.cn)(l,s),side:n,children:t})}var ns=s(52048),na=s(65277),nl=s(23804),nn=s(41167);function nr(e){let{row:t}=e,{t:s}=(0,i.Bd)(),l=(0,x.useContext)(l4),n=t.original,{setOpen:r,setCurrentRow:o,upstream:d}=tu(),u=(0,p.jE)(),h=(0,m.n)(e=>e.auth.user),[g,f]=(0,x.useState)(!1),[j,y]=(0,x.useState)(!1),[b,_]=(0,x.useState)(!1),N=1===n.status,w=e9(n),k=(0,sS._m)(h,sS.kB.CHANNEL,sS.YG.SENSITIVE_WRITE),C=()=>{o(n),r("update-channel")},A=()=>{o(n),r("test-channel")},S=async e=>{e.stopPropagation(),y(!0);try{await X(n.id,{channelName:n.name},()=>{u.invalidateQueries({queryKey:K.lists()})})}finally{y(!1)}},R=async e=>{e?.stopPropagation(),_(!0);try{await G(n.id,n.status,u)}finally{_(!1)}},I=(0,a.jsx)(sC.A,{className:"size-4"});return b?I=(0,a.jsx)(th.A,{className:"size-4 animate-spin"}):N&&(I=(0,a.jsx)(sA.A,{className:"size-4"})),(0,a.jsxs)("div",{className:"-ml-1.5 flex items-center gap-1",children:["card"!==l&&(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"ghost",size:"icon-sm",onClick:e=>{e.stopPropagation(),C()},"aria-label":s("Edit")}),children:(0,a.jsx)(na.A,{className:"size-4"})}),(0,a.jsx)(c.ZI,{children:s("Edit")})]}),(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"ghost",size:"icon-sm",onClick:S,disabled:j,"aria-label":s("Test Connection")}),children:j?(0,a.jsx)(th.A,{className:"size-4 animate-spin"}):(0,a.jsx)(t2.A,{className:"size-4"})}),(0,a.jsx)(c.ZI,{children:s("Test Connection")})]}),"card"===l&&(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"ghost",size:"icon-sm",onClick:e=>{e.stopPropagation(),A()},"aria-label":s("Test Channel Connection")}),children:(0,a.jsx)(nl.A,{className:"size-4"})}),(0,a.jsx)(c.ZI,{children:s("Test Channel Connection")})]}),(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"ghost",size:"icon-sm",onClick:R,disabled:b,"aria-label":s(N?"Disable":"Enable"),className:N?"text-destructive hover:text-destructive":"text-success hover:text-success"}),children:I}),(0,a.jsx)(c.ZI,{children:s(N?"Disable":"Enable")})]}),(0,a.jsxs)(lY.rI,{children:[(0,a.jsxs)(lY.ty,{render:(0,a.jsx)(tg.$,{variant:"ghost",className:"data-popup-open:bg-muted flex h-8 w-8 p-0"}),children:[(0,a.jsx)(lU.A,{className:"h-4 w-4"}),(0,a.jsx)("span",{className:"sr-only",children:s("Open menu")})]}),(0,a.jsxs)(lY.SQ,{align:"end",className:"w-48",children:["card"===l&&(0,a.jsxs)(lY._2,{onClick:C,children:[s("Edit"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(na.A,{size:16})})]}),(0,a.jsxs)(lY._2,{onClick:A,children:[s("Test Connection"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(nl.A,{size:16})})]}),(0,a.jsxs)(lY._2,{onClick:()=>{o(n),r("balance-query")},children:[s("Query Balance"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(tm.A,{size:16})})]}),(0,a.jsxs)(lY._2,{onClick:()=>{o(n),r("fetch-models")},children:[s("Fetch Models"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(sO.A,{size:16})})]}),q.has(n.type)&&(0,a.jsxs)(lY._2,{onClick:()=>{let e=v(n.settings);e.pendingAddModels.length>0||e.pendingRemoveModels.length>0?d.openModal(n,e.pendingAddModels,e.pendingRemoveModels,e.pendingAddModels.length>0?"add":"remove"):d.detectChannelUpdates(n)},children:[s("Upstream Updates"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(tp.A,{size:16})})]}),4===n.type&&(0,a.jsxs)(lY._2,{onClick:()=>{o(n),r("ollama-models")},children:[s("Manage Ollama Models"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(s1.A,{size:16})})]}),(0,a.jsx)(lY.mB,{}),(0,a.jsxs)(lY._2,{disabled:!k,onClick:k?()=>{o(n),r("copy-channel")}:void 0,children:[s("Copy Channel"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(tv.A,{size:16})})]}),!k&&(0,a.jsx)(lY._2,{disabled:!0,className:"text-xs normal-case",children:s("No permission to perform this action")}),w&&(0,a.jsxs)(lY._2,{onClick:()=>{o(n),r("multi-key-manage")},children:[s("Manage Keys"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(nn.A,{size:16})})]}),(0,a.jsx)(lY.mB,{}),(0,a.jsxs)(lY._2,{disabled:!k,onSelect:e=>{e.preventDefault(),k&&f(!0)},className:"text-destructive focus:text-destructive",children:[s("Delete"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(t5.A,{size:16})})]})]})]}),(0,a.jsx)(tw.T,{open:g,onOpenChange:f,title:s("Delete Channel"),desc:s('Are you sure you want to delete channel "{{name}}"? This action cannot be undone.',{name:n.name}),confirmText:s("Delete"),destructive:!0,handleConfirm:()=>{k&&(Y(n.id,u),f(!1))}})]})}var ni=s(5825),no=s(43494);
1function nd(e){let{row:t}=e,{t:s}=(0,i.Bd)(),l=t.original.tag,{setOpen:n,setCurrentTag:r}=tu(),o=(0,p.jE)();return l?(0,a.jsxs)("div",{className:"-ml-1.5 flex items-center gap-1",children:[(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"ghost",size:"icon-sm",onClick:()=>{r(l),n("edit-tag")},"aria-label":s("Edit Tag")}),children:(0,a.jsx)(ni.A,{})}),(0,a.jsx)(c.ZI,{children:s("Edit Tag")})]}),(0,a.jsxs)(no.C,{ariaLabel:s("Open menu"),children:[(0,a.jsxs)(lY._2,{onClick:()=>{r(l),n("tag-batch-edit")},children:[s("Batch Edit"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(na.A,{size:16})})]}),(0,a.jsx)(lY.mB,{}),(0,a.jsxs)(lY._2,{onClick:()=>{er(l,o)},children:[s("Enable All"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(sC.A,{size:16})})]}),(0,a.jsxs)(lY._2,{onClick:()=>{ei(l,o)},children:[s("Disable All"),(0,a.jsx)(lY.V0,{children:(0,a.jsx)(sA.A,{size:16})})]})]})]}):null}var nc=s(31562);function nu(e){let{value:t,onChange:s,onCommit:l,min:n=0,max:r,step:i=1,disabled:o=!1,className:d,label:c}=e,[u,m]=(0,x.useState)(String(t??0)),[h,p]=(0,x.useState)(!1),g=(0,x.useRef)(null);(0,x.useEffect)(()=>{h||m(String(t??0))},[t,h]);let f=e=>{let t=e;return void 0!==n&&(t=Math.max(n,t)),void 0!==r&&(t=Math.min(r,t)),t},j=void 0!==n&&Number(u)<=n,v=void 0!==r&&Number(u)>=r;return(0,a.jsxs)("div",{className:(0,tE.cn)("inline-flex items-center",d),children:[c&&(0,a.jsx)(st.J,{className:"text-muted-foreground mr-1.5 text-xs",children:c}),(0,a.jsxs)("div",{onBlur:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||l?.()},className:(0,tE.cn)("group/spinner border-input inline-flex h-7 items-center gap-0 rounded-md border transition-colors",!o&&"hover:bg-muted/60",h&&"bg-muted/60 ring-primary/30 ring-1"),children:[(0,a.jsx)("button",{type:"button",tabIndex:-1,"aria-label":"Decrement",onClick:e=>{if(e.stopPropagation(),o)return;let t=f((Number(u)||0)-i);m(String(t)),s(t)},disabled:o||j,className:(0,tE.cn)("text-muted-foreground/0 group-hover/spinner:text-muted-foreground flex h-7 w-6 shrink-0 items-center justify-center rounded-l-md transition-colors",!o&&!j&&"group-hover/spinner:hover:text-foreground group-hover/spinner:hover:bg-muted",(o||j)&&"group-hover/spinner:opacity-30"),children:(0,a.jsx)(nc.A,{className:"size-3"})}),h?(0,a.jsx)("input",{ref:g,type:"text",value:u,onChange:e=>{let t=e.target.value;""===t||"-"===t?m(t):/^-?\d+$/.test(t)&&m(t)},onBlur:()=>{p(!1);let e=Number(u);if(Number.isNaN(e)||""===u||"-"===u)return void m(String(t??0));let a=f(e);m(String(a)),a!==(t??0)&&s(a)},onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),g.current?.blur()):"Escape"===e.key&&(p(!1),m(String(t??0)))},className:"h-7 w-10 bg-transparent text-center font-mono text-sm outline-none",autoFocus:!0}):(0,a.jsx)("button",{type:"button",onClick:()=>{o||(p(!0),requestAnimationFrame(()=>g.current?.select()))},disabled:o,title:u,className:(0,tE.cn)("h-7 min-w-8 max-w-16 cursor-text truncate px-1 text-center font-mono text-sm tabular-nums",o&&"cursor-default opacity-50"),children:u}),(0,a.jsx)("button",{type:"button",tabIndex:-1,"aria-label":"Increment",onClick:e=>{if(e.stopPropagation(),o)return;let t=f((Number(u)||0)+i);m(String(t)),s(t)},disabled:o||v,className:(0,tE.cn)("text-muted-foreground/0 group-hover/spinner:text-muted-foreground flex h-7 w-6 shrink-0 items-center justify-center rounded-r-md transition-colors",!o&&!v&&"group-hover/spinner:hover:text-foreground group-hover/spinner:hover:bg-muted",(o||v)&&"group-hover/spinner:opacity-30"),children:(0,a.jsx)(sK.A,{className:"size-3"})})]})]})}function nm(e){let{channel:t}=e,{upstream:s,setCurrentRow:l}=tu();if(!q.has(t.type))return null;let n=v(t.settings);if(!n.enabled)return null;let r=n.pendingAddModels.length,i=n.pendingRemoveModels.length;return 0===r&&0===i?null:(0,a.jsxs)("div",{className:"flex items-center gap-0.5",children:[r>0&&(0,a.jsx)(tk.Wh,{label:`+${r}`,variant:"success",size:"sm",copyable:!1,className:"cursor-pointer",onClick:e=>{e.stopPropagation(),l(t),s.openModal(t,n.pendingAddModels,n.pendingRemoveModels,"add")}}),i>0&&(0,a.jsx)(tk.Wh,{label:`-${i}`,variant:"danger",size:"sm",copyable:!1,className:"cursor-pointer",onClick:e=>{e.stopPropagation(),l(t),s.openModal(t,n.pendingAddModels,n.pendingRemoveModels,"remove")}})]})}function nh(e){let{channel:t}=e;return ts(t)?(0,a.jsx)(np,{channel:t}):(0,a.jsx)(nx,{channelId:t.id,value:t.priority,field:"priority",min:-999})}function np(e){let{channel:t}=e,{t:s}=(0,i.Bd)(),l=(0,p.jE)(),n=t.priority,[r,o]=(0,x.useState)(!1),[d,c]=(0,x.useState)(null),u=t.tag||"",m=t.children?.length||0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(nu,{value:n??0,onChange:e=>{c(e),o(!0)},min:-999}),(0,a.jsx)(tw.T,{open:r,onOpenChange:o,title:s("Confirm Batch Update"),desc:s('This will update the priority to {{value}} for all {{count}} channel(s) with tag "{{tag}}". Continue?',{value:d,count:m,tag:u}),confirmText:s("Update"),handleConfirm:()=>{null!==d&&Q(u,"priority",d,l),o(!1)}})]})}function nx(e){let{channelId:t,value:s,field:l,min:n}=e,r=(0,p.jE)(),i=(0,x.useMemo)(()=>(function(e){let t,s,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:em,l=()=>{void 0!==t&&(a.clearTimeout(t),t=void 0)},n=()=>
1{if(l(),void 0===s)return;let t=s;s=void 0,e(t)};return{schedule(e){l(),s=e,t=a.setTimeout(n,800)},flush:n}})(e=>{Z(t,l,e,r)}),[t,l,r]);return(0,x.useEffect)(()=>()=>i.flush(),[i]),(0,a.jsx)(nu,{value:s??0,onChange:i.schedule,onCommit:i.flush,min:n})}function ng(e){let{channel:t}=e;return ts(t)?(0,a.jsx)(nf,{channel:t}):(0,a.jsx)(nx,{channelId:t.id,value:t.weight,field:"weight",min:0})}function nf(e){let{channel:t}=e,{t:s}=(0,i.Bd)(),l=(0,p.jE)(),n=t.weight,[r,o]=(0,x.useState)(!1),[d,c]=(0,x.useState)(null),u=t.tag||"",m=t.children?.length||0;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(nu,{value:n??0,onChange:e=>{c(e),o(!0)},min:0}),(0,a.jsx)(tw.T,{open:r,onOpenChange:o,title:s("Confirm Batch Update"),desc:s('This will update the weight to {{value}} for all {{count}} channel(s) with tag "{{tag}}". Continue?',{value:d,count:m,tag:u}),confirmText:s("Update"),handleConfirm:()=>{null!==d&&Q(u,"weight",d,l),o(!1)}})]})}let nj="••••";function nv(e){let{channel:t}=e,{t:s,i18n:l}=(0,i.Bd)(),n=(0,p.jE)(),r=(0,x.useContext)(l4),{sensitiveVisible:o}=tu(),d=ts(t),u=t.balance||0,m=t.used_quota||0,[f,j]=(0,x.useState)(!1),[v,y]=(0,x.useState)(!1),[b,N]=(0,x.useState)(null),w="Tokens"===(0,_.yz)()?" Tokens":"",k=e=>w&&"-"!==e?`${e}${w}`:e,C=(0,ns.Tl)(l.resolvedLanguage||l.language),A=k((0,_.rP)(m,{digitsLarge:2,digitsSmall:4,abbreviate:!0,showSymbol:"card"!==r})),S=k((0,_.J5)(u,{digitsLarge:2,digitsSmall:4,abbreviate:!1,showSymbol:"card"!==r})),R=A.length>8?k((0,_.rP)(m,{compact:!0,locale:C,showSymbol:"card"!==r})):A,I=S.length>8?k((0,_.J5)(u,{compact:!0,locale:C,showSymbol:"card"!==r})):S,M=`${s("Used:")} ${A}`,O=`${s("Remaining:")} ${S}`,T=`${s("Used:")} ${nj}`,z=`${s("Remaining:")} ${nj}`;if(d)return(0,a.jsx)(c.Bc,{children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tk.Wh,{label:o?`${s("Used:")} ${R}`:T,variant:"neutral",size:"sm",copyable:!1,showDot:!1,className:"-ml-1.5 cursor-help"})}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:o?M:T})})]})});let E=0===u?"neutral":u<1?"danger":u<10?"warning":"success",$=async()=>{if(!f){if(j(!0),57===t.type){try{let e=await (0,h.Tl)(t.id);if(!e.success)throw Error(e.message||s("Failed to fetch usage"));N(e),y(!0)}catch(e){g.oR.error(e instanceof Error?e.message:s("Failed to fetch usage"))}finally{j(!1)}return}await et(t.id,n),j(!1)}},F=o?I:nj;o&&f?F=s("Updating..."):o&&57===t.type&&(F=s("Account Info"));let B=O;o?57===t.type&&(B=s("Click to view Codex usage")):B=z;let P=E;return 57===t.type?P="info":f&&(P="neutral"),(0,a.jsxs)(c.Bc,{children:[(0,a.jsxs)("div",{className:"-ml-1.5 flex items-center gap-1",children:[(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tk.Wh,{label:o?R:nj,variant:"neutral",size:"sm",copyable:!1,showDot:!1,className:"cursor-help"})}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:o?M:T})})]}),(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tk.Wh,{label:F,variant:P,size:"sm",copyable:!1,showDot:!1,className:"cursor-pointer",onClick:$})}),(0,a.jsxs)(c.ZI,{children:[(0,a.jsx)("p",{children:B}),57!==t.type&&(0,a.jsx)("p",{children:s("Click to update balance")})]})]})]}),(0,a.jsx)(t0,{open:v,onOpenChange:y,channelName:t.name,channelId:t.id,channelDisplayName:o?void 0:nj,channelDisplayId:o?void 0:nj,response:b,onRefresh:async()=>{if(!f){j(!0);try{let e=await (0,h.Tl)(t.id);if(!e.success)throw Error(e.message||s("Failed to fetch usage"));N(e)}catch(e){g.oR.error(e instanceof Error?e.message:s("Failed to fetch usage"))}finally{j(!1)}}},isRefreshing:f})]})}var ny=s(48986);function nb(e){let{table:t}=e,{t:s}=(0,i.Bd)(),l=(0,p.jE)(),[n,r]=(0,x.useState)(!1),[o,d]=(0,x.useState)(!1),[u,h]=(0,x.useState)(""),g=(0,m.n)(e=>e.auth.user),f=(0,sS._m)(g,sS.kB.CHANNEL,sS.YG.SENSITIVE_WRITE),j=t.getFilteredSelectedRowModel().rows.reduce((e,t)=>{let s=t.original.id;return"number"==typeof s&&e.push(s),e},[]),v=()=>{t.resetRowSelection()};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(t8.Of,{table:t,entityName:"channel",children:[(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"outline",size:"icon",onClick:()=>{ea(j,l,v)},className:"size-8","aria-label":s("Enable selected channels"),title:s("Enable selected channels")}),children:[(0,a.jsx)(sC.A,{}),(0,a.jsx)("span",{className:"sr-only",children:s("Enable selected channels")})]}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:s("Enable selected channels")})})]}),(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"outline",size:"icon",onClick:()=>{el(j,l,v)},className:"size-8","aria-label":s("Disable selected channels"),title:s("Disable selected channels")}),children:[(0,a.jsx)(sA.A,{}),(0,a.jsx)("span",{className:"sr-only",children:s("Disable selected channels")})]}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:s("Disable selected channels")})})]}),(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"outline",size:"icon",onClick:()=>r(!0),className:"size-8","aria-label":s("Set tag for selected channels"),title:s("Set tag for selected channels")}),children:[(0,a.jsx)(ny.A,{}),(0,a.jsx)("span",{className:"sr-only",children:s("Set tag for selected channels")})]}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:s("Set tag for selected channels")})})]}),(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"destructive",size:"icon",onClick:()=>{f&&d(!0)},"aria-disabled":!f,className:(0,tE.cn)("size-8",!f&&"cursor-not-allowed opacity-50"),"aria-label":s("Delete selected channels"),title:s(f?"Delete selected channels":"No permission to perform this action")}),children:[(0,a.jsx)(t5.A,{}),(0,a.jsx)("span",{className:"sr-only",children:s("Delete selected channels")})]}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:s(f?"Delete selected channels":"No permission to perform this action")})})]})]}),(0,a.jsx)(tx.l,{open:n,onOpenChange:r,title:s("Set Tag"),description:(0,a.jsxs)(a.Fragment,{children:[s("Set a tag for"),j.length," ",s("selected channel(s). Leave empty to remove tag.")]}
1),contentHeight:"auto",bodyClassName:"space-y-4",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:()=>{r(!1),h("")},children:s("Cancel")}),(0,a.jsx)(tg.$,{onClick:()=>{en(j,u||null,l,()=>{r(!1),h(""),v()})},children:s("Set Tag")})]}),children:(0,a.jsx)("div",{className:"grid gap-4 py-4",children:(0,a.jsxs)("div",{className:"grid gap-2",children:[(0,a.jsx)(st.J,{htmlFor:"tag",children:s("Tag")}),(0,a.jsx)(se.p,{id:"tag",placeholder:s("Enter tag name (optional)"),value:u,onChange:e=>h(e.target.value)})]})})}),(0,a.jsx)(tx.l,{open:o,onOpenChange:d,title:s("Delete Channels?"),description:(0,a.jsxs)(a.Fragment,{children:[s("Are you sure you want to delete"),j.length," ",s("channel(s)? This action cannot be undone.")]}),contentHeight:"auto",footer:(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(tg.$,{variant:"outline",onClick:()=>d(!1),children:s("Cancel")}),(0,a.jsx)(tg.$,{variant:"destructive",onClick:()=>{f&&es(j,l,()=>{d(!1),v()})},disabled:!f,children:s("Delete")})]}),children:" "})]})}let n_=(0,lQ.GY)("/_authenticated/channels/"),nN="channel-status-filter",nw=new Set(["id","name","priority","balance","response_time","test_time"]);function nk(){let{t:e}=(0,i.Bd)(),{enableTagMode:t,idSort:s,batchMode:n,sensitiveVisible:r,setSensitiveVisible:o}=tu(),d=(0,l0.Ub)("(max-width: 640px)"),[u,m]=(0,x.useState)([]),{globalFilter:p,onGlobalFilterChange:g,columnFilters:f,onColumnFiltersChange:j,pagination:v,onPaginationChange:y,ensurePageInRange:b}=(0,l1.c)({search:n_.useSearch(),navigate:n_.useNavigate(),pagination:{defaultPage:1,defaultPageSize:d?10:20},globalFilter:{enabled:!0,key:"filter"}
1,columnFilters:[{columnId:"status",searchKey:"status",type:"array",deserialize:e=>{if(void 0!==e)return e;let t=localStorage.getItem(nN);return"enabled"===t||"disabled"===t?[t]:[]}},{columnId:"type",searchKey:"type",type:"array"},{columnId:"group",searchKey:"group",type:"array"},{columnId:"model",searchKey:"model",type:"string"}]}),_=f.find(e=>"status"===e.id)?.value||[],N=(0,x.useMemo)(()=>f.find(e=>"type"===e.id)?.value||[],[f]),w=f.find(e=>"group"===e.id)?.value||[],{value:k,inputValue:C,onChange:R,onCompositionStart:I,onCompositionEnd:M,resetInput:O}=(0,t8.bz)({columnFilters:f,columnId:"model",onColumnFiltersChange:j}),T=!!(p?.trim()||k.trim()),z=(0,x.useMemo)(()=>{let e=u[0];return e&&nw.has(e.id)?{sort_by:e.id,sort_order:e.desc?"desc":"asc"}:{}},[u]),{data:E}=(0,l.I)({queryKey:["groups"],queryFn:h.f}),$=(0,x.useMemo)(()=>(E?.data||[]).map(e=>({label:e,value:e})),[E]),{data:q,isLoading:L,isFetching:V}=(0,l.I)({queryKey:K.list({keyword:p,model:k,group:w.length>0&&!w.includes("all")?w[0]:void 0,status:_.length>0&&!_.includes("all")?_[0]:void 0,type:N.length>0&&!N.includes("all")?Number(N[0]):void 0,tag_mode:t,id_sort:s,...z,p:v.pageIndex+1,page_size:v.pageSize}),queryFn:async()=>T?(0,h.jl)({keyword:p,model:k,group:w.length>0&&!w.includes("all")?w[0]:void 0,status:_.length>0&&!_.includes("all")?_[0]:void 0,type:N.length>0&&!N.includes("all")?Number(N[0]):void 0,tag_mode:t,id_sort:s,...z,p:v.pageIndex+1,page_size:v.pageSize}):(0,h.Jp)({group:w.length>0&&!w.includes("all")?w[0]:void 0,status:_.length>0&&!_.includes("all")?_[0]:void 0,type:N.length>0&&!N.includes("all")?Number(N[0]):void 0,tag_mode:t,id_sort:s,...z,p:v.pageIndex+1,page_size:v.pageSize}),placeholderData:e=>e}),W=(0,x.useMemo)(()=>{let e=q?.data?.items||[];return t&&e.length>0?function(e){let t=new Map,s=[];for(let a of e){let e=a.tag||"";if(!t.has(e)){let l={...a,key:e,id:e,tag:e,name:e,type:0,status:void 0,group:"",used_quota:0,response_time:0,priority:-1,weight:-1,balance:0,test_time:0,created_time:0,balance_updated_time:0,models:"",children:[]};t.set(e,l),s.push(l)}let l=t.get(e);if(!l)continue;l.children.push(a);let n=l.children.length;if(l.used_quota+=a.used_quota,l.response_time=(l.response_time*(n-1)+a.response_time)/n,-1===l.priority?l.priority=a.priority:l.priority!==a.priority&&(l.priority=null),-1===l.weight?l.weight=a.weight:l.weight!==a.weight&&(l.weight=null),""===l.group)l.group=a.group;else{let e=new Set(l.group.split(",").filter(Boolean));a.group.split(",").filter(Boolean).forEach(t=>{e.has(t)||(l.group+=`,${t}`)})}1===a.status?l.status=1:void 0===l.status&&(l.status=a.status)}return s}(e):e},[q,t]),U=q?.data?.total||0,H=q?.data?.type_counts,G=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{t,i18n:s}=(0,i.Bd)(),{sensitiveVisible:l}=tu(),n=e.enableSelection??!0,r=(0,ns.Tl)(s.resolvedLanguage||s.language);return(0,x.useMemo)(()=>[...n?[{id:"select",header:e=>{let{table:s}=e;return(0,a.jsx)(t9.S,{checked:s.getIsAllPageRowsSelected(),indeterminate:s.getIsSomePageRowsSelected(),onCheckedChange:e=>s.toggleAllPageRowsSelected(!!e),"aria-label":t("Select all")})},cell:e=>{let{row:s}=e;return ts(s.original)?null:(0,a.jsx)(t9.S,{checked:s.getIsSelected(),onCheckedChange:e=>s.toggleSelected(!!e),"aria-label":t("Select row")})},enableSorting:!1,enableHiding:!1,enableResizing:!1,size:40}]:[],{accessorKey:"id",header:t("ID"),meta:{mobileHidden:!0},cell:e=>{let{row:t}=e,s=t.getValue("id");return(0,a.jsx)(l9.C,{value:l?s:nj})},size:80},{accessorKey:"name",header:t("Name"),meta:{mobileTitle:!0},cell:e=>{let{row:s}=e,n=ts(s.original),r=s.getValue("name"),i=s.original;if(n){let e=s.original.tag||r,t=s.original.children?.length||0;return(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(tg.$,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:s.getToggleExpandedHandler(),children:s.getIsExpanded()?(0,a.jsx)(tN.A,{className:"h-4 w-4"}):(0,a.jsx)(l6.A,{className:"h-4 w-4"})}),(0,a.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,a.jsxs)("span",{className:"font-semibold",children:["Tag:",e]}),(0,a.jsx)(tk.Wh,{label:`${t} channels`,variant:"blue",size:"sm",copyable:!1})]})]})}let o=!0===function(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}(i.setting).pass_through_body_enabled,d=!!i.param_override?.trim();return(0,a.jsx)("div",{className:"flex max-w-full min-w-0 items-center gap-2",children:(0,a.jsxs)("div",{className:"flex max-w-full min-w-0 flex-col gap-1",children:[(0,a.jsxs)("div",{className:"flex max-w-full min-w-0 items-center gap-1.5",children:[(0,a.jsx)(nt,{text:l?r:nj,className:"font-medium",maxWidth:"max-w-full"}),o&&(0,a.jsx)(c.Bc,{delay:100,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tb.A,{className:"h-3.5 w-3.5 flex-shrink-0 text-amber-500"})}),(0,a.jsx)(c.ZI,{side:"top",children:t("Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.")})]})}),d&&(0,a.jsx)(c.Bc,{delay:100,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(at.A,{className:"text-info h-3.5 w-3.5 flex-shrink-0"})}),(0,a.jsx)(c.ZI,{side:"top",children:t("Override request parameters")})]})}),(0,a.jsx)(nm,{channel:i})]}),i.remark&&(0,a.jsx)(c.Bc,{delay:200,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)("span",{className:"text-muted-foreground text-xs"}),children:(0,tE.EJ)(i.remark,40)}),(0,a.jsx)(c.ZI,{side:"bottom",className:"max-w-xs",children:i.remark})]})})]})})},size:260,minSize:200},{accessorKey:"type",header:t("Type"),cell:e=>{let{row:s}=e;if(ts(s.original))return(0,a.jsx)(tk.Wh,{label:t("Tag Aggregate"),variant:"blue",size:"sm",copyable:!1,className:"-ml-1.5"});let l=s.getValue("type"),n=t(e8(l)),r=e7(l),i=s.original,o=e9(i),d=i.channel_info?.multi_key_mode??"random",u="random"===d?ag.A:l8.A,m="random"===d?t("Multi-key: Random rotation"):t("Multi-key: Polling rotation"),h=function(e){if(!e)return null;try{let t=JSON.parse(e);if(t&&"object"==typeof t)return t}catch{}return null}(i.other_info),p=h?.source==="ionet",x="string"==typeof h?.deployment_id?h?.deployment_id:void 0;return(0,a.jsxs)("div",{className:"flex max-w-full min-w-0 items-center gap-2 overflow-hidden",children:[o&&(0,a.jsx)(c.Bc,{delay:100,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)("span",{className:"border-border bg-muted text-primary inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md border"}),children:(0,a.jsx)(u,{className:"h-3 w-3"})}),(0,a.jsx)(c.ZI,{side:"top",children:m})]})}),(0,a.jsx)(c.Bc,{delay:300,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)("div",{className:"max-w-full min-w-0 overflow-hidden"}),children:(0,a.jsx)(l7.d,{iconKey:`${r}.Color`,iconSize:18,label:n,colorText:!1,copyable:!1,showDot:!1,className:"max-w-full min-w-0 overflow-hidden"})}),(0,a.jsx)(c.ZI,{side:"top",children:n})]})}),p&&(0,a.jsx)(c.Bc,{delay:100,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)("span",{className:"flex cursor-pointer items-center gap-1.5 text-xs font-medium",onClick:e=>{if(e.stopPropagation(),!x)return;let t=`/models/deployments?dFilter=${encodeURIComponent(String(x))}`;window.open(t,"_blank","noopener")}}),children:(0,a.jsx)(tk.Wh,{label:"IO.NET",variant:"purple",size:"sm",copyable:!1,className:"cursor-pointer"})}),(0,a.jsx)(c.ZI,{side:"top",children:(0,a.jsxs)("div",{className:"max-w-xs space-y-1",children:[(0,a.jsx)("div",{className:"text-xs",children:t("From IO.NET deployment")}),x&&(0,a.jsxs)("div",{className:"text-muted-foreground font-mono text-xs",children:[t("Deployment ID"),": ",x]}),(0,a.jsx)("div",{className:"text-muted-foreground text-xs",children:t("Click to open deployment")})]})})]})})]})},filterFn:(e,t,s)=>!!(!s||0===s.length||s.includes("all"))||s.includes(String(e.getValue(t))),size:220,enableSorting:!1},{accessorKey:"status",header:t("Status"),meta:{mobileBadge:!0},cell:e=>{let{row:s}=e,l=ts(s.original),n=s.getValue("status"),r=s.original;if(l){let e=s.original.children?.length||0;return 1===n?(0,a.jsx)(tk.Wh,{label:`Active (${e})`,variant:"success",size:"sm",copyable:!1,className:"-ml-1.5"}):(0,a.jsx)(tk.Wh,{label:`Inactive (${e})`,variant:"neutral",size:"sm",copyable:!1,className:"-ml-1.5"})}let i=S[n]||S["0"],o=e9(r),d=r.channel_info?.multi_key_size??0,u=Math.max(0,d-(r.channel_info?.multi_key_status_list?Object.keys(r.channel_info.multi_key_status_list).length:0)),m=o&&d>0?`${t(i.label)} (${u}/${d}
1)`:t(i.label);if(3===n){let e="",s="";try{let t=r.other_info?JSON.parse(r.other_info):null;t&&(e=t.status_reason||"",s=t.status_time?(0,e6.fk)(t.status_time):"")}catch{}if(e||s)return(0,a.jsx)(c.Bc,{delay:100,children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)("span",{}),children:(0,a.jsx)(tk.Wh,{label:m,variant:i.variant,size:"sm",copyable:!1})}),(0,a.jsx)(c.ZI,{side:"top",className:"max-w-xs",children:(0,a.jsxs)("div",{className:"space-y-1 text-xs",children:[e&&(0,a.jsxs)("div",{children:[t("Reason:")," ",e]}),s&&(0,a.jsxs)("div",{children:[t("Time:")," ",s]})]})})]})})}return(0,a.jsx)(tk.Wh,{label:m,variant:i.variant,size:"sm",copyable:!1})},filterFn:(e,t,s)=>{if(!s||0===s.length||s.includes("all"))return!0;let a=e.getValue(t);return s.includes("enabled")?1===a:!!s.includes("disabled")&&1!==a},size:120,enableSorting:!1},{accessorKey:"models",header:t("Models"),meta:{mobileHidden:!0},cell:e=>{var t;let{row:s}=e,l=(t=s.getValue("models"))?t.split(",").map(e=>e.trim()).filter(e=>e.length>0):[];return(0,a.jsx)(t8.Yt,{items:l.map(e=>(0,a.jsx)(tk.Wh,{label:e,autoColor:e,size:"sm",className:"font-mono"},e))})},size:200,enableSorting:!1},{accessorKey:"group",header:t("Groups"),meta:{mobileHidden:!0},cell:e=>{let{row:t}=e,s=te(t.getValue("group"));return(0,a.jsx)(t8.Yt,{items:s.map(e=>(0,a.jsx)(sj.d,{group:e,label:l?void 0:nj,size:"sm"},e))})},filterFn:(e,t,s)=>!!(!s||0===s.length||s.includes("all"))||te(e.getValue(t)).some(e=>s.includes(e)),size:150,enableSorting:!1},{accessorKey:"tag",header:t("Tag"),meta:{mobileHidden:!0},cell:e=>{let{row:t}=e,s=t.getValue("tag");return s?(0,a.jsx)(tk.Wh,{label:s,autoColor:s,size:"sm",className:"-ml-1.5"}):(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:"-"})},size:120,enableSorting:!1},{accessorKey:"priority",header:t("Priority"),meta:{mobileHidden:!0},cell:e=>{let{row:t}=e;return(0,a.jsx)(nh,{channel:t.original})},size:100},{accessorKey:"weight",header:t("Weight"),meta:{mobileHidden:!0},cell:e=>{let{row:t}=e;return(0,a.jsx)(ng,{channel:t.original})},size:90,enableSorting:!1},{accessorKey:"balance",header:t("Used / Remaining"),cell:e=>{let{row:t}=e;return(0,a.jsx)(nv,{channel:t.original})},size:180},{accessorKey:"response_time",header:t("Response"),meta:{mobileHidden:!0},cell:e=>{let{row:s}=e,l=s.getValue("response_time"),n=0===l?J:l<=500?F:l<=1e3?B:l<=2e3?P:D;return(0,a.jsx)(tk.Wh,{label:tt(l,t),variant:n.variant,size:"sm",copyable:!1,className:"-ml-1.5"})},size:110},{accessorKey:"test_time",header:t("Last Tested"),meta:{mobileHidden:!0},cell:e=>{let{row:t}=e,s=t.getValue("test_time");if(!s||0===s)return(0,a.jsx)("span",{className:"text-muted-foreground text-xs",children:"-"});let l=function(e,t){if(!e||0===e)return"Never";try{let s,a,l=e-Date.now()/1e3,n=Math.abs(l),r=new Intl.RelativeTimeFormat(t,{numeric:"always",style:"narrow"}),i=86400,o=30*i,d=365*i;n<60?(s=Math.round(l),a="second"):n<3600?(s=Math.round(l/60),a="minute"):n<i?(s=Math.round(l/3600),a="hour"):n<o?(s=Math.round(l/i),a="day"):n<d?(s=Math.round(l/o),a="month"):(s=Math.round(l/d),a="year");let c=r.format(s,a),u=Array.isArray(t)?t[0]:t,m=u?.toString();if(m?.startsWith("zh"))return c.replaceAll(/(\d)([\u4e00-\u9fff])/g,"$1 $2");return c}catch{return"Unknown"}}(s,r),n=(0,e6.fk)(s);return(0,a.jsx)(c.Bc,{children:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tk.Wh,{label:l,variant:"neutral",size:"sm",copyable:!1,className:"-ml-1.5 cursor-pointer"})}),(0,a.jsx)(c.ZI,{side:"top",children:(0,a.jsx)("p",{className:"font-mono text-sm",children:n})})]})})},size:120,enableSorting:!1},{id:"actions",header:()=>t("Actions"),cell:e=>{let{row:t}=e;return ts(t.original)?(0,a.jsx)(nd,{row:t}):(0,a.jsx)(nr,{row:t})},enableSorting:!1,enableHiding:!1,meta:{pinned:"right"}}],[n,t,r,l])}({enableSelection:n}),{table:Y}=(0,t8.uI)({data:W,columns:G,totalCount:U,sorting:u,initialColumnVisibility:{models:!1,tag:!1},columnVisibilityStorageKey:"channels:column-visibility",columnSizingStorageKey:!d&&"channels:column-sizing",columnFilters:f,pagination:v,globalFilter:p,enableRowSelection:!!n&&(e=>!ts(e.original)),onSortingChange:e=>{m(t=>{let s="function"==typeof e?e(t):e;return v.pageIndex>0&&y({...v,pageIndex:0}),s})},onColumnFiltersChange:e=>{j(t=>{let s="function"==typeof e?e(t):e,a=s.find(e=>"status"===e.id)?.value;return localStorage.setItem(nN,a?.[0]??"all"),s})},onPaginationChange:y,onGlobalFilterChange:g,getRowId:ta,getSubRows:e=>e.children,manualPagination:!0,manualSorting:!0,manualFiltering:!0,withExpandedRowModel:!0,enableColumnResizing:!d,ensurePageInRange:b});(0,x.useEffect)(()=>{n||Y.resetRowSelection()},[n,Y]);let Z=(0,x.useMemo)(()=>{let t=H||{},s=Object.entries(t).map(e=>{let[t,s]=e;return{type:Number(t),count:Number(s)||0}}).filter(e=>e.type>0&&e.count>0).sort((t,s)=>{let a=e(e8(t.type)),l=e(e8(s.type));return a.localeCompare(l)}),a=N.find(e=>"all"!==e);if(a){let e=Number(a),l=s.some(t=>t.type===e);e>0&&!l&&s.push({type:e,count:Number(t[a])||0})}return[{label:"All Types",value:"all",count:Object.values(t).reduce((e,t)=>
1e+(Number(t)||0),0)},...s.map(e=>{let t=e7(e.type);return{label:e8(e.type),value:String(e.type),count:e.count,iconNode:(0,ao.Y)(`${t}.Color`,16)}})]},[e,H,N]),Q=[{label:e("All Groups"),value:"all"},...$.map(e=>({...e,label:r?e.label:"••••"}))];return(0,a.jsx)(t8.cx,{table:Y,columns:G,isLoading:L,isFetching:V,emptyTitle:e("No Channels Found"),emptyDescription:e("No channels available. Create your first channel to get started."),skeletonKeyPrefix:"channel-skeleton",enableCardView:!0,viewModeStorageKey:"channels:view-mode",renderCard:(e,t)=>{let{isSelected:s}=t;return(0,a.jsx)(l3,{row:e,isSelected:s})},cardGridClassName:"grid grid-cols-1 gap-3 sm:gap-4 lg:grid-cols-3",applyHeaderSize:!0,toolbarProps:{searchPlaceholder:e("Filter by name, ID, or key..."),searchDebounceMs:500,onReset:()=>{O()},additionalSearch:(0,a.jsx)(se.p,{placeholder:e("Filter by model..."),value:C,onChange:R,onCompositionStart:I,onCompositionEnd:M,className:"w-full sm:w-[150px] lg:w-[180px]"}),filters:[{columnId:"status",title:e("Status"),options:[...A],singleSelect:!0},{columnId:"type",title:e("Type"),options:Z,singleSelect:!0},{columnId:"group",title:e("Group"),options:Q,singleSelect:!0}],preActions:(0,a.jsxs)(c.m_,{children:[(0,a.jsx)(c.k$,{render:(0,a.jsx)(tg.$,{variant:"ghost",size:"icon",onClick:()=>o(!r),"aria-label":r?e("Hide"):e("Show"),className:"text-muted-foreground hover:text-foreground size-8"}),children:r?(0,a.jsx)(s5.A,{}):(0,a.jsx)(lX.A,{})}),(0,a.jsx)(c.ZI,{children:r?e("Hide"):e("Show")})]})},getRowClassName:(e,t)=>{var s;let{isMobile:a}=t;if(!ts(s=e.original)&&1!==s.status)return a?t8.Z0:t8.JM},bulkActions:n?(0,a.jsx)(nb,{table:Y}):null})}let nC=function(){let{t:e}=(0,i.Bd)(),t=(0,m.n)(e=>e.auth.user?.role===u.z7.SUPER_ADMIN),s=(0,l.I)({queryKey:["channel-ops"],queryFn:h.mP,retry:!1,staleTime:3e5}),p=s.data?.data?.retry_times,x="number"==typeof p?`${e("Max Retries")}: ${p}`:null,g=null;return x&&(g=t?(0,a.jsxs)(c.m_,{children:[(0,a.jsxs)(c.k$,{render:(0,a.jsx)(d.E,{variant:"outline",className:"shrink-0 cursor-pointer","aria-label":e("Retry Settings"),render:(0,a.jsx)(n.N_,{to:"/system-settings/models/$section",params:{section:"routing-reliability"}})}),children:[(0,a.jsx)("span",{children:x}),(0,a.jsx)(r.A,{"data-icon":"inline-end"})]}),(0,a.jsx)(c.ZI,{children:(0,a.jsx)("p",{children:e("Retry Settings")})})]}):(0,a.jsx)(d.E,{variant:"outline",className:"shrink-0",children:x})),(0,a.jsxs)(tc,{children:[(0,a.jsxs)(o.Ni,{fixedContent:!0,children:[(0,a.jsx)(o.Ni.Title,{children:(0,a.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,a.jsx)("span",{className:"truncate",children:e("Channels")}),g]})}),(0,a.jsx)(o.Ni.Actions,{children:(0,a.jsx)(lZ,{})}),(0,a.jsx)(o.Ni.Content,{children:(0,a.jsx)(nk,{})})]}),(0,a.jsx)(lL,{})]})}}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.