omniroute 2.9.3 → 2.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/.next/BUILD_ID +1 -1
- package/app/.next/build-manifest.json +2 -2
- package/app/.next/prerender-manifest.json +3 -3
- package/app/.next/server/app/(dashboard)/dashboard/a2a/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/agents/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/analytics/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/api-manager/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/audit-log/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/auto-combo/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/cli-tools/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/costs/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/health/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/limits/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/logs/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/mcp/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/media/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/onboarding/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/profile/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/search-tools/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/settings/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/translator/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/400/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/401/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/403/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/408/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/429/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/500/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/502/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/503/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/_global-error.html +2 -2
- package/app/.next/server/app/_global-error.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/app/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/callback/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/docs/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/forbidden/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/forgot-password/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/landing/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/maintenance/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/offline/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/privacy/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/status/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/terms/page_client-reference-manifest.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__17482fc3._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__80e3bfc3._.js +2 -2
- package/app/.next/server/chunks/[root-of-the-server]__84e445b2._.js +2 -2
- package/app/.next/server/chunks/[root-of-the-server]__8c8abde4._.js +2 -2
- package/app/.next/server/chunks/[root-of-the-server]__98560fc3._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__beb64bf2._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__ce90c972._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__d4563e10._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__e27a89bd._.js +1 -1
- package/app/.next/server/chunks/_05c48915._.js +1 -1
- package/app/.next/server/chunks/_2115d8de._.js +1 -1
- package/app/.next/server/chunks/_3ac953eb._.js +1 -1
- package/app/.next/server/chunks/_4b8fd853._.js +1 -1
- package/app/.next/server/chunks/_68683848._.js +1 -1
- package/app/.next/server/chunks/_ee9b677b._.js +1 -1
- package/app/.next/server/chunks/open-sse_services_826884e1._.js +1 -3
- package/app/.next/server/chunks/open-sse_translator_index_ts_f5fd0821._.js +1 -1
- package/app/.next/server/chunks/ssr/[root-of-the-server]__9affb65e._.js +1 -1
- package/app/.next/server/chunks/ssr/[root-of-the-server]__a6942102._.js +1 -1
- package/app/.next/server/pages/500.html +2 -2
- package/app/.next/server/server-reference-manifest.js +1 -1
- package/app/.next/server/server-reference-manifest.json +1 -1
- package/app/.next/static/chunks/{410b615517204cbf.js → c8b74e25aecb09d5.js} +1 -1
- package/app/CHANGELOG.md +21 -0
- package/app/docs/openapi.yaml +1 -1
- package/app/open-sse/services/combo.ts +1 -1
- package/app/open-sse/translator/helpers/responsesApiHelper.ts +2 -1
- package/app/open-sse/translator/request/openai-responses.ts +2 -1
- package/app/package-lock.json +2 -2
- package/app/package.json +1 -1
- package/app/src/app/api/usage/[connectionId]/route.ts +37 -3
- package/package.json +1 -1
- /package/app/.next/static/{-EoiH1iUSM-hNTu_x_xls → z314c1HLTWx1ZCjOHV3gC}/_buildManifest.js +0 -0
- /package/app/.next/static/{-EoiH1iUSM-hNTu_x_xls → z314c1HLTWx1ZCjOHV3gC}/_clientMiddlewareManifest.json +0 -0
- /package/app/.next/static/{-EoiH1iUSM-hNTu_x_xls → z314c1HLTWx1ZCjOHV3gC}/_ssgManifest.js +0 -0
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
module.exports=[821518,e=>{"use strict";var t=e.i(878947);let r={};for(let[e,o]of Object.entries(t.PROVIDER_ID_TO_ALIAS))r[o]&&console.log(`[MODEL] Warning: alias "${o}" maps to both "${r[o]}" and "${e}". Using "${e}".`),r[o]=e;let o={github:{"claude-4.5-opus":"claude-opus-4-5-20251101","claude-opus-4.5":"claude-opus-4-5-20251101","gemini-3-pro":"gemini-3-pro-preview","gemini-3-flash":"gemini-3-flash-preview","raptor-mini":"oswe-vscode-prime"},gemini:{"gemini-3.1-pro-preview":"gemini-3.1-pro","gemini-3-1-pro":"gemini-3.1-pro"},"gemini-cli":{"gemini-3.1-pro-preview":"gemini-3.1-pro","gemini-3-1-pro":"gemini-3.1-pro"},nvidia:{"gpt-oss-120b":"openai/gpt-oss-120b","nvidia/gpt-oss-120b":"openai/gpt-oss-120b"},antigravity:{}},n=new Map;for(let[e,o]of Object.entries(t.PROVIDER_MODELS)){let t=r[e]||e;for(let e of o||[]){let r=e?.id;if(!r)continue;let o=n.get(r)||[];o.includes(t)||(o.push(t),n.set(r,o))}}function i(e){return r[e]||e}function a(e,t){if(!t||"string"!=typeof t)return t;let r=o[i(e)];return r?.[t]||t}function s(e){if(!e)return{provider:null,model:null,isAlias:!1,providerAlias:null,extendedContext:!1};if(/\.\.[\/\\]/.test(e)||/[\x00-\x1f]/.test(e))return console.log(`[MODEL] Warning: rejected malformed model string: "${e.substring(0,50)}"`),{provider:null,model:null,isAlias:!1,providerAlias:null,extendedContext:!1};let t=!1,r=e;if(r.endsWith("[1m]")&&(t=!0,r=r.slice(0,-4)),r.includes("/")){let e=r.indexOf("/"),o=r.slice(0,e),n=r.slice(e+1);return{provider:i(o),model:n,isAlias:!1,providerAlias:o,extendedContext:t}}return{provider:null,model:r,isAlias:!0,providerAlias:null,extendedContext:t}}async function l(e,r){let o=s(e),{extendedContext:l}=o;if(!o.isAlias){let e=a(o.provider,o.model);return{provider:o.provider,model:e,extendedContext:l}}let c="function"==typeof r?await r():r,u=function(e,t){if(!t)return null;let r=t[e];if(!r)return null;if("string"==typeof r&&r.includes("/")){let e=r.indexOf("/");return{provider:i(r.slice(0,e)),model:r.slice(e+1)}}return"object"==typeof r&&r.provider&&r.model?{provider:i(r.provider),model:r.model}:null}(o.model,c);if(u){let e=a(u.provider,u.model);return{provider:u.provider,model:e,extendedContext:l}}if(c&&"object"==typeof c){let e=Object.entries(c).map(([e,t])=>({pattern:e,target:t})),t=function(e,t){if(!e||!t||!Array.isArray(t))return null;let r=[];for(let o of t){let t=o.pattern||o.alias||o.from,n=o.target||o.model||o.to;t&&n&&function(e,t){if(!e||!t)return!1;if("*"===t||t===e)return!0;let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return RegExp(`^${r}$`,"i").test(e)}(e,t)&&r.push({pattern:t,target:n,specificity:function(e){if(!e)return 0;let t=0;for(let r of e.split(/[/*?]/))r.length>0&&(t+=10*r.length);let r=(e.match(/\*/g)||[]).length,o=(e.match(/\?/g)||[]).length;return t-=50*r,t-=5*o,t+=e.length}(t),...o})}return 0===r.length?null:(r.sort((e,t)=>t.specificity-e.specificity),r[0])}(o.model,e);if(t){let e=t.target;if(e.includes("/")){let r=e.indexOf("/"),o=e.slice(0,r),n=e.slice(r+1),s=i(o),c=a(s,n);return{provider:s,model:c,extendedContext:l,wildcardPattern:t.pattern}}}}let d=o.model,m=n.get(d)||[];if(m.includes("openai"))return{provider:"openai",model:d,extendedContext:l};let p=m.filter(e=>"openai"!==e);if(1===p.length){let e=p[0],t=a(e,d);return{provider:e,model:t,extendedContext:l}}if(p.length>1){let e=p.map(e=>t.PROVIDER_ID_TO_ALIAS[e]||e),r=e.slice(0,2).map(e=>`${e}/${d}`),o=`Ambiguous model '${d}'. Use provider/model prefix (ex: ${r.join(" or ")}).`;return console.warn(`[MODEL] ${o} Candidates: ${e.join(", ")}`),{provider:null,model:d,errorType:"ambiguous_model",errorMessage:o,candidateProviders:p,candidateAliases:e}}return/^claude-/i.test(d)?{provider:"antigravity",model:d,extendedContext:l}:/^gemini-/i.test(d)||/^gemma-/i.test(d)?{provider:"gemini",model:d,extendedContext:l}:{provider:"openai",model:d,extendedContext:l}}e.s(["getModelInfoCore",()=>l,"parseModel",()=>s],821518)},928041,e=>{"use strict";var t=e.i(441637),r=e.i(719201),o=e.i(178578);let n={strategy:"priority",maxRetries:1,retryDelayMs:2e3,timeoutMs:12e4,concurrencyPerModel:3,queueTimeoutMs:3e4,healthCheckEnabled:!0,healthCheckTimeoutMs:3e3,maxComboDepth:3,trackMetrics:!0};function i(e,t,r){let o=t?.comboDefaults||{},i=r&&t?.providerOverrides?.[r]||{},a=e?.config||{},s=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>null!=e));return{...n,...s(o),...s(i),...s(a)}}let a=new Map;function s(e,t=3){a.has(e)||a.set(e,{running:0,max:t,queue:[],rateLimitedUntil:null});let r=a.get(e);return r.max=t,r}function l(e){return!!e.rateLimitedUntil&&(!(Date.now()>=e.rateLimitedUntil)||(e.rateLimitedUntil=null,!1))}function c(e){let t=a.get(e);if(t)for(;t.queue.length>0&&t.running<t.max&&!l(t);){let r=t.queue.shift();clearTimeout(r.timer),t.running++,r.resolve(u(e))}}function u(e){let t=!1;return()=>{if(t)return;t=!0;let r=a.get(e);r&&r.running>0&&(r.running--,c(e))}}var d=e.i(260222),m=e.i(73114),p=e.i(821518);let f=/<omniModel>([^<]+)<\/omniModel>/,g=["function","class","import","def","SELECT","async","await","const","let","var","return","```","algorithm","compile","debug","refactor","typescript","python","javascript","code","implement","write a","create a component","endpoint","repository","deploy","install","script","api","database","query","schema","interface","generic","enum","module","package","dependency","função","classe","importar","definir","consulta","assíncrono","aguardar","constante","variável","retornar","algoritmo","compilar","depurar","refatorar","código","implementar","criar um","componente","como fazer","repositório","configurar","instalar","banco de dados","escrever uma função","criar uma classe","función","clase","importar","definir","consulta","asíncrono","esperar","constante","variable","retornar","algoritmo","compilar","depurar","refactorizar","código","implementar","函数","类","导入","定义","查询","异步","等待","常量","变量","返回","算法","编译","调试","代码","関数","クラス","インポート","非同期","定数","変数","コード","アルゴリズム","функция","класс","импорт","запрос","асинхронный","константа","переменная","алгоритм","код","funktion","klasse","importieren","abfrage","asynchron","konstante","variable","algorithmus","code","함수","클래스","가져오기","정의","쿼리","비동기","대기","상수","변수","반환","코드","دالة","فئة","استيراد","استعلام","غير متزامن","ثابت","متغير","كود","خوارزمية"],h=["prove","theorem","derive","step by step","chain of thought","formally","mathematical","proof","logically","analyze","reasoning","deduce","infer","hypothesis","convergence","provar","teorema","derivar","passo a passo","cadeia de pensamento","formalmente","matemático","prova","logicamente","analisar","raciocínio","deduzir","inferir","hipótese","demonstrar","cálculo","equação diferencial","integral","otimização","demostrar","teorema","derivar","paso a paso","formalmente","matemático","lógicamente","证明","定理","推导","逐步","思维链","数学","逻辑","分析","証明","定理","導出","論理的","分析","доказать","теорема","шаг за шагом","математически","логически","beweisen","theorem","schritt für schritt","mathematisch","logisch","증명","정리","단계별","수학적","논리적","إثبات","نظرية","خطوة بخطوة","رياضي","منطقياً"],y=["what is","define","translate","hello","yes or no","summarize","list","tell me","who is","o que é","definir","traduzir","olá","oi","sim ou não","resumir","listar","me diga","quem é","quando foi","onde fica","explique brevemente","de forma simples","qué es","definir","traducir","hola","resumir","listar","什么是","定义","翻译","你好","总结","列出","что такое","определить","перевести","привет","резюмировать","was ist","definieren","übersetzen","hallo","zusammenfassen","이란","정의","번역","안녕","요약","ما هو","تعريف","ترجمة","مرحبا","ملخص"],b={enabled:!0,simpleMaxWords:60},w={quota:.2,health:.25,costInv:.2,latencyInv:.15,taskFit:.1,stability:.05,tierPriority:.05};function v(e,t,r=w,o=()=>.5){return e.map(n=>{var i,a;let s,l,c,u=(s=Math.max(...e.map(e=>e.costPer1MTokens),.001),l=Math.max(...e.map(e=>e.p95LatencyMs),1),c=Math.max(...e.map(e=>e.latencyStdDev),.001),{quota:Math.min(1,n.quotaRemaining/100),health:"CLOSED"===n.circuitBreakerState?1:.5*("HALF_OPEN"===n.circuitBreakerState),costInv:1-n.costPer1MTokens/s,latencyInv:1-n.p95LatencyMs/l,taskFit:o(n.model,t),stability:1-n.latencyStdDev/c,tierPriority:(i=n.accountTier,a=n.quotaResetIntervalSecs,Math.min(1,.8*(({ultra:1,pro:.67,standard:.33,free:0})[i?.toLowerCase()??""]??.33)+.2*(null!=a&&a>0?Math.max(0,1-a/2592e3):0)))});return{provider:n.provider,model:n.model,score:r.quota*u.quota+r.health*u.health+r.costInv*u.costInv+r.latencyInv*u.latencyInv+r.taskFit*u.taskFit+r.stability*u.stability+r.tierPriority*u.tierPriority,factors:u}}).sort((e,t)=>t.score-e.score)}let M={coding:{"claude-sonnet":.95,"claude-opus":.92,"claude-haiku":.78,"gpt-4o":.9,"gpt-4o-mini":.8,"gpt-4-turbo":.88,o1:.93,o3:.95,"o4-mini":.88,codex:.98,"gemini-pro":.85,"gemini-flash":.8,"gemini-2.5-pro":.92,"gemini-2.5-flash":.82,"deepseek-coder":.9,"deepseek-v3":.85,"deepseek-r1":.88,"deepseek-chat":.84,"deepseek-v3.2":.86,qwen:.78,llama:.72,mistral:.75,mixtral:.77,"grok-4-fast":.8,"grok-4":.82,"grok-3":.8,"kimi-k2":.82,"glm-5":.78,"minimax-m2.5":.75,"minimax-m2":.72},review:{"claude-sonnet":.92,"claude-opus":.95,"claude-haiku":.7,"gpt-4o":.88,"gpt-4o-mini":.72,o1:.9,o3:.92,"gemini-pro":.9,"gemini-2.5-pro":.93,"gemini-flash":.75,"deepseek-r1":.85,"deepseek-v3":.8},planning:{"claude-opus":.95,"claude-sonnet":.9,"gpt-4o":.88,o1:.92,o3:.95,"gemini-2.5-pro":.93,"gemini-pro":.88,"deepseek-r1":.85},analysis:{"claude-opus":.95,"claude-sonnet":.92,"gemini-2.5-pro":.95,"gemini-pro":.88,"gemini-3.1-pro":.95,"gpt-4o":.85,o1:.9,o3:.93,"deepseek-r1":.88,"deepseek-chat":.8,"kimi-k2":.82,"glm-5":.78,"minimax-m2.5":.76},debugging:{"claude-sonnet":.93,"claude-opus":.9,"gpt-4o":.88,o1:.85,"deepseek-coder":.9,"deepseek-v3":.82,"gemini-flash":.78,codex:.92},documentation:{"claude-sonnet":.9,"claude-opus":.88,"gpt-4o":.92,"gpt-4o-mini":.85,"gemini-pro":.88,"gemini-flash":.82,"deepseek-v3":.78},default:{"claude-sonnet":.85,"claude-opus":.85,"gpt-4o":.85,"gemini-pro":.8,"gemini-3.1-pro":.85,"deepseek-v3":.75,"deepseek-chat":.74,"gemini-flash":.72,"grok-4-fast":.72,"grok-4":.74,"grok-3":.73,"kimi-k2":.76,"glm-5":.7,"minimax-m2.5":.7}},k=[{pattern:"coder",taskType:"coding",boost:.15},{pattern:"code",taskType:"coding",boost:.1},{pattern:"fast",taskType:"coding",boost:.05},{pattern:"thinking",taskType:"planning",boost:.1},{pattern:"thinking",taskType:"analysis",boost:.1}];function x(e,t){let r=e.toLowerCase(),o=t.toLowerCase();for(let[e,t]of Object.entries(M[o]||M.default))if(r.includes(e))return t;let n=.5;for(let e of k)r.includes(e.pattern)&&o===e.taskType&&(n+=e.boost);return Math.min(1,n)}let $={"ship-fast":{quota:.15,health:.3,costInv:.05,latencyInv:.35,taskFit:.1,stability:0,tierPriority:.05},"cost-saver":{quota:.15,health:.2,costInv:.4,latencyInv:.05,taskFit:.1,stability:.05,tierPriority:.05},"quality-first":{quota:.1,health:.2,costInv:.05,latencyInv:.05,taskFit:.4,stability:.15,tierPriority:.05},"offline-friendly":{quota:.4,health:.3,costInv:.1,latencyInv:.05,taskFit:0,stability:.1,tierPriority:.05}};class O{exclusions=new Map;incidentMode=!1;isExcluded(e){let t=this.exclusions.get(e);return!(!t||Date.now()-t.excludedAt>t.cooldownMs)}evaluate(e,t,r){let o=this.exclusions.get(e);if(o&&t>=.3&&Date.now()-o.excludedAt>o.cooldownMs)return this.exclusions.delete(e),{excluded:!1,reason:`Re-admitted: score ${t.toFixed(2)} >= 0.3`};if(this.isExcluded(e))return"HALF_OPEN"===r&&o?(o.probeCount++,{excluded:!1,isProbe:!0,reason:`Probe request #${o.probeCount}`}):{excluded:!0,reason:o?.reason||"Excluded"};if(t<.2){let r=o?Math.min(2*o.cooldownMs,18e5):3e5;return this.exclusions.set(e,{provider:e,excludedAt:Date.now(),cooldownMs:r,reason:`Score ${t.toFixed(2)} < 0.2`,probeCount:0}),{excluded:!0,reason:`Excluded: score ${t.toFixed(2)} below threshold`}}return"OPEN"===r?(this.exclusions.set(e,{provider:e,excludedAt:Date.now(),cooldownMs:3e5,reason:"Circuit breaker OPEN",probeCount:0}),{excluded:!0,reason:"Circuit breaker OPEN"}):{excluded:!1}}recordProbeResult(e,t){let r=this.exclusions.get(e);r&&(t&&r.probeCount>=3?this.exclusions.delete(e):t||(r.cooldownMs=Math.min(2*r.cooldownMs,18e5),r.excludedAt=Date.now(),r.probeCount=0))}updateIncidentMode(e){let t=e.length;if(0===t)return this.incidentMode=!1,!1;let r=e.filter(e=>"OPEN"===e).length;return this.incidentMode=r/t>.5,this.incidentMode}isInIncidentMode(){return this.incidentMode}getExclusions(){return[...this.exclusions.values()]}getStatus(){let e=Date.now();return{exclusionCount:this.exclusions.size,incidentMode:this.incidentMode,exclusions:[...this.exclusions.values()].map(t=>({provider:t.provider,reason:t.reason,remainingMs:Math.max(0,t.cooldownMs-(e-t.excludedAt))}))}}}let C=null,R=new Map,A=new class{name="rules";description="6-factor weighted scoring: quota, health, cost, latency, taskFit, stability";select(e,t){let r=e.filter(e=>"OPEN"!==e.circuitBreakerState),o=v(r.length>0?r:e,t.taskType,void 0,x),n=o[0];if(!n)throw Error("[RulesStrategy] No candidates to score");return{provider:n.provider,model:n.model,strategy:this.name,reason:`RulesStrategy: score=${n.score.toFixed(3)} (quota=${n.factors.quota.toFixed(2)}, health=${n.factors.health.toFixed(2)}, cost=${n.factors.costInv.toFixed(2)}, taskFit=${n.factors.taskFit.toFixed(2)})`,candidatesConsidered:o.length,finalScore:n.score}}},S=new class{name="cost";description="Always selects cheapest available provider (by costPer1MTokens)";select(e,t){let r=e.filter(e=>"OPEN"!==e.circuitBreakerState),o=r.length>0?r:e,n=[...o].sort((e,t)=>e.costPer1MTokens-t.costPer1MTokens)[0];if(!n)throw Error("[CostStrategy] No candidates available");return{provider:n.provider,model:n.model,strategy:this.name,reason:`CostStrategy: cheapest at $${n.costPer1MTokens.toFixed(3)}/1M tokens`,candidatesConsidered:o.length,finalScore:0===n.costPer1MTokens?1:1/n.costPer1MTokens}}},E=new class{name="latency";description="Prioritizes lowest p95 latency with reliability weighting";select(e,t){let r=e.filter(e=>"OPEN"!==e.circuitBreakerState),o=r.length>0?r:e,n=[...o].sort((e,t)=>{let r=1e3*e.errorRate,o=1e3*t.errorRate;return e.p95LatencyMs+r-(t.p95LatencyMs+o)})[0];if(!n)throw Error("[LatencyStrategy] No candidates available");let i=n.p95LatencyMs>0?Math.max(.001,1e4/n.p95LatencyMs):1,a=Math.max(0,1-n.errorRate);return{provider:n.provider,model:n.model,strategy:this.name,reason:`LatencyStrategy: p95=${n.p95LatencyMs}ms, errorRate=${(100*n.errorRate).toFixed(2)}%`,candidatesConsidered:o.length,finalScore:.7*i+.3*a}}};R.set("rules",A),R.set("cost",S),R.set("eco",S),R.set("latency",E),R.set("fast",E);var P=e.i(878947);let B=["gpt-oss-120b","deepseek-reasoner","glm-4.7","glm4.7"],T=[429,502,503,504],N={"grok-4-fast-non-reasoning":1143,"grok-4-1-fast-non-reasoning":1244,"gemini-2.5-flash":1238,"kimi-k2.5":1646,"gpt-4o-mini":2764,"claude-sonnet-4.6":4e3,"claude-opus-4.6":6e3,"deepseek-chat":2e3},q=new Map;function D(e){return"string"==typeof e?{model:e,weight:0}:{model:e.model,weight:e.weight||0}}function L(e,t,r=new Set,o=0){if(o>3)return e.models.map(e=>D(e).model);if(r.has(e.name))return[];r.add(e.name);let n=Array.isArray(t)?t:t?.combos||[],i=[];for(let t of e.models||[]){let e=D(t).model,a=n.find(t=>t.name===e);if(a){let e=L(a,n,new Set(r),o+1);i.push(...e)}else i.push(e)}return i}function I(e){let t=e.map(e=>D(e)),r=t.reduce((e,t)=>e+t.weight,0);if(r<=0)return t[Math.floor(Math.random()*t.length)].model;let o=Math.random()*r;for(let e of t)if((o-=e.weight)<=0)return e.model;return t[t.length-1].model}function F(e,t){let r=e.map(e=>D(e));return[r.find(e=>e.model===t),...r.filter(e=>e.model!==t).sort((e,t)=>t.weight-e.weight)].filter(Boolean).map(e=>e.model)}async function _(t){try{let{getPricingForModel:r}=await e.A(605589),o=await Promise.all(t.map(async e=>{let t=(0,p.parseModel)(e),o=t.provider||t.providerAlias||"unknown",n=t.model||e;try{let t=await r(o,n);return{modelStr:e,cost:t?.input??1/0}}catch{return{modelStr:e,cost:1/0}}}));return o.sort((e,t)=>e.cost-t.cost),o.map(e=>e.modelStr)}catch{return t}}function j(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?e.trim():"").filter(Boolean):"string"==typeof e?e.split(",").map(e=>e.trim()).filter(Boolean):[]}function z(e){return N[String(e||"").toLowerCase()]??1500}async function K(t,r){let n=(0,o.getComboMetrics)(r),{getPricingForModel:i}=await e.A(605589),a={};try{let{getModelLatencyStats:t}=await e.A(537776);a=await t({windowHours:24,minSamples:3,maxRows:1e4})}catch{}return await Promise.all(t.map(async e=>{let t=(0,p.parseModel)(e),r=t.provider||t.providerAlias||"unknown",o=t.model||e,s=a[`${r}/${o}`]||null,l=Number(s?.totalRequests),c=Number.isFinite(l)&&l>=10,u=1;try{let e=await i(r,o),t=Number(e?.input);Number.isFinite(t)&&t>=0&&(u=t)}catch{}let m=n?.byModel?.[e]||null,f=Number(m?.avgLatencyMs),g=Number(m?.successRate),h=Number(s?.p95LatencyMs),y=Number(s?.latencyStdDev),b=Number(s?.successRate),w=c?Number.isFinite(h)&&h>0?h:z(o):Number.isFinite(f)&&f>0?f:z(o),v=c?Number.isFinite(b)&&b>=0&&b<=1?1-b:.05:Number.isFinite(g)&&g>=0&&g<=100?1-g/100:.05,M=c&&Number.isFinite(y)&&y>0?Math.max(10,y):Math.max(10,.1*w),k=(0,d.getCircuitBreaker)(`combo:${e}`)?.getStatus?.()?.state;return{provider:r,model:o,quotaRemaining:100,quotaTotal:100,circuitBreakerState:"OPEN"===k||"HALF_OPEN"===k?k:"CLOSED",costPer1MTokens:u,p95LatencyMs:w,latencyStdDev:M,errorRate:v,accountTier:"standard",quotaResetIntervalSecs:86400}}))}async function U({body:e,combo:a,handleSingleModel:s,isModelAvailable:l,log:c,settings:u,allCombos:M}){let k,S=a.strategy||"priority",E=a.models||[],{body:N,pinnedModel:q}=function(e,t,r){var o;if(!t)return{body:e,pinnedModel:null};let n=Array.isArray(e.messages)?[...e.messages]:[],i=null;t.context_cache_protection&&(i=function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("assistant"===r.role&&"string"==typeof r.content){let e=f.exec(r.content);if(e)return e[1]}}return null}(n)),t.system_message&&t.system_message.trim()&&(o=n,n=[{role:"system",content:t.system_message},...o.filter(e=>"system"!==e.role)]);let a=function(e,t){let r;if(!e||!t)return e;try{r=new RegExp(t)}catch{return console.warn(`[ComboAgent] Invalid tool_filter_regex: "${t}"`),e}return e.filter(e=>{let t=e.function?.name??e.name??"";return r.test(String(t))})}(e.tools,t.tool_filter_regex);return n=n.map(e=>"string"==typeof e.content&&f.test(e.content)?{...e,content:e.content.replace(f,"").trimEnd()}:e),{body:{...e,messages:n,...a!==e.tools&&{tools:a}},pinnedModel:i}}(e,a,0);e=N,q&&c.info("COMBO",`[#401] Context caching: pinned model=${q}`);let z=a.context_cache_protection?async(e,t)=>{let r=await s(e,t);if(!r.ok)return r;if(!e.stream){try{let e=await r.clone().json(),o=Array.isArray(e?.messages)?e.messages:[];if(o.length>0){let n=function(e,t){let r=e.map(e=>"assistant"===e.role&&"string"==typeof e.content?{...e,content:e.content.replace(f,"").trimEnd()}:e),o=r.map(e=>e.role).lastIndexOf("assistant");if(-1===o)return[...r,{role:"assistant",content:`
|
|
2
2
|
<omniModel>${t}</omniModel>`}];let n=r[o];if("string"!=typeof n.content)return r;let i=[...r];return i[o]={...n,content:`${n.content}
|
|
3
|
-
<omniModel>${t}</omniModel>`},i}(o,t);return new Response(JSON.stringify({...e,messages:n}),{status:r.status,headers:r.headers})}}catch{}return r}if(!r.body)return r;let o=`
|
|
4
|
-
<omniModel>${t}</omniModel>
|
|
5
|
-
`,n=new TextEncoder,i=new TextDecoder,a=!1,l=new TransformStream({transform(e,t){if(a)return void t.enqueue(e);let r=i.decode(e,{stream:!0});if(r.match(/"content":"([^"]+)/)){let e=r.replace(/"content":"([^"]+)/,`"content":"${o.replace(/"/g,'\\"')}$1`);a=!0,t.enqueue(n.encode(e));return}t.enqueue(e)},flush(e){if(!a){let t=`data: ${JSON.stringify({choices:[{delta:{content:o},index:0,finish_reason:null}]})}
|
|
3
|
+
<omniModel>${t}</omniModel>`},i}(o,t);return new Response(JSON.stringify({...e,messages:n}),{status:r.status,headers:r.headers})}}catch{}return r}if(!r.body)return r;let o=`\\n<omniModel>${t}</omniModel>\\n`,n=new TextEncoder,i=new TextDecoder,a=!1,l=new TransformStream({transform(e,t){if(a)return void t.enqueue(e);let r=i.decode(e,{stream:!0});if(r.match(/"content":"([^"]+)/)){let e=r.replace(/"content":"([^"]+)/,`"content":"${o.replace(/"/g,'\\"')}$1`);a=!0,t.enqueue(n.encode(e));return}t.enqueue(e)},flush(e){if(!a){let t=`data: ${JSON.stringify({choices:[{delta:{content:o},index:0,finish_reason:null}]})}
|
|
6
4
|
|
|
7
5
|
`;e.enqueue(n.encode(t))}}});return new Response(r.body.pipeThrough(l),{status:r.status,headers:r.headers})}:s;if("round-robin"===S)return W({body:e,combo:a,handleSingleModel:z,isModelAvailable:l,log:c,settings:u,allCombos:M});let U=u?i(a,u):{...n,...a.config||{}},H=U.maxRetries??1,J=U.retryDelayMs??2e3;if(M){let e=L(a,M);if("weighted"===S){let e=I(E);k=(k=F(E,e)).flatMap(e=>{let t=(Array.isArray(M)?M:M?.combos||[]).find(t=>t.name===e);return t?L(t,M):[e]}),c.info("COMBO",`Weighted selection with nested resolution: ${k.length} total models`)}else k=e,c.info("COMBO",`${S} with nested resolution: ${k.length} total models`)}else if("weighted"===S){let e=I(E);k=F(E,e),c.info("COMBO",`Weighted selection: ${e} (from ${E.length} models)`)}else k=E.map(e=>D(e).model);if("auto"===S){let t,r=Array.isArray(e?.tools)&&e.tools.length>0,n=[...k];if(r){let e=n.filter(e=>(function(e){let t=(0,p.parseModel)(e),r=t.provider||t.providerAlias||"",o=t.model||e;if(r){let e=function(e,t){let r=P.PROVIDER_ID_TO_ALIAS[e]||e,o=P.PROVIDER_MODELS[r];if(!Array.isArray(o))return null;let n=o.find(e=>e?.id===t);return n&&"boolean"==typeof n.toolCalling?n.toolCalling:null}(r,o);if(null!==e)return e}let n=String(e||"").toLowerCase();return!!n&&!B.some(e=>!!(n===e||n.endsWith(`/${e}`))||n.includes(e))})(e));e.length>0?n=e:c.warn("COMBO","Auto strategy: all candidates filtered by tool-calling policy, falling back to full pool")}let i=function(e){if(!e||"object"!=typeof e)return"";let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e&&"object"==typeof e&&"user"===e.role):null;if(t){var r;return"string"==typeof(r=t.content)?r:Array.isArray(r)?r.map(e=>e&&"object"==typeof e&&"string"==typeof e.text?e.text:"").join("\n"):""}if("string"==typeof e.input)return e.input;if(Array.isArray(e.input)){let t=e.input.map(e=>e&&"object"==typeof e?"string"==typeof e.content?e.content:"string"==typeof e.text?e.text:"":"").filter(Boolean).join("\n");if(t)return t}return"string"==typeof e.prompt?e.prompt:""}(e),s="string"==typeof a?.system_message?a.system_message:void 0,l=function(e,t,r){if(!t.enabled)return"medium";let o=`${r??""} ${e}`.toLowerCase(),n=e.trim().split(/\s+/).length,i=t.simpleMaxWords??60,a=[...g,...t.extraCodeKeywords??[]],s=[...h,...t.extraReasoningKeywords??[]],l=[...y,...t.extraSimpleKeywords??[]];for(let e of a)if(o.includes(e.toLowerCase()))return"code";for(let e of s)if(o.includes(e.toLowerCase()))return"reasoning";if(n<i){for(let e of l)if(o.includes(e.toLowerCase()))return"simple"}return"medium"}(i,(t=a?.autoConfig?.intentConfig||a?.config?.auto?.intentConfig||a?.config?.intentConfig||{},{...b,...t,..."boolean"==typeof u?.intentDetectionEnabled?{enabled:u.intentDetectionEnabled}:{},...Number.isFinite(Number(u?.intentSimpleMaxWords))?{simpleMaxWords:Number(u.intentSimpleMaxWords)}:{},...j(u?.intentExtraCodeKeywords).length>0?{extraCodeKeywords:j(u.intentExtraCodeKeywords)}:{},...j(u?.intentExtraReasoningKeywords).length>0?{extraReasoningKeywords:j(u.intentExtraReasoningKeywords)}:{},...j(u?.intentExtraSimpleKeywords).length>0?{extraSimpleKeywords:j(u.intentExtraSimpleKeywords)}:{}}),s);(0,o.recordComboIntent)(a.name,l);let d=function(e){switch(e){case"code":return"coding";case"reasoning":return"analysis";default:return"default"}}(l),m=a?.autoConfig||a?.config?.auto||a?.config||{},f="string"==typeof m.routingStrategy?m.routingStrategy:"string"==typeof m.strategyName?m.strategyName:"rules",M=Array.isArray(m.candidatePool)?m.candidatePool:[...new Set(n.map(e=>{let t=(0,p.parseModel)(e);return t.provider||t.providerAlias||"unknown"}))],S=m.weights&&"object"==typeof m.weights?m.weights:w,E=Number.isFinite(Number(m.explorationRate))?Number(m.explorationRate):.05,T=Number.isFinite(Number(m.budgetCap))?Number(m.budgetCap):void 0,N="string"==typeof m.modePack?m.modePack:void 0,q=await K(n,a.name);if(q.length>0){let e=null,t=null,o="";if("rules"!==f)try{let n=function(e,t,r="rules"){let o;return(!(o=R.get(r))?(console.warn(`[RouterStrategy] Strategy '${r}' not found, falling back to 'rules'`),A):o).select(e,t)}(q,{taskType:d,requestHasTools:r},f);e=n.provider,t=n.model,o=n.reason}catch(e){c.warn("COMBO",`Auto strategy '${f}' failed (${e?.message||"unknown"}), falling back to rules`)}if(!e||!t){let r=function(e,t,r="default",o){let n,i=(C||(C=new O),C),a=e.weights;if(e.modePack){let t=$[e.modePack];t&&(a=t)}.01>Math.abs(Object.values(a).reduce((e,t)=>e+t,0)-1)||(a=w);let s=[],l=t.filter(t=>(!(e.candidatePool.length>0)||!!e.candidatePool.includes(t.provider))&&(!i.evaluate(t.provider,.5,t.circuitBreakerState).excluded||(s.push(t.provider),!1)));0===l.length&&(l.push(...t),s.length=0);let c=v(l,r,a,x),u=c.filter(e=>!i.evaluate(e.provider,e.score,"CLOSED").excluded||(s.push(e.provider),!1)),d=u.length>0?u:c,m=Math.random()<(i.isInIncidentMode()?0:e.explorationRate)&&d.length>1;if(m){let e=Math.floor(Math.random()*d.length);n=d[e]}else n=d[0];if(e.budgetCap){let r=t.find(e=>e.provider===n.provider);if(r&&r.costPer1MTokens/1e6*1e3>e.budgetCap){let e=d.map(e=>({...e,cost:t.find(t=>t.provider===e.provider)?.costPer1MTokens||0})).sort((e,t)=>e.cost-t.cost)[0];e&&(n=e)}}return{provider:n.provider,model:n.model,score:n.score,isExploration:m,factors:n.factors,excluded:s}}({id:a.id||a.name,name:a.name,type:"auto",candidatePool:M,weights:S,modePack:N,budgetCap:T,explorationRate:E},q,d);e=r.provider,t=r.model,o=`score=${r.score.toFixed(3)}${r.isExploration?" (exploration)":""}`}let i=new Map;for(let e of n){let t=(0,p.parseModel)(e),r=t.provider||t.providerAlias||"unknown",o=t.model||e;i.set(`${r}/${o}`,e)}let s=v(q,d,S).map(e=>i.get(`${e.provider}/${e.model}`)||`${e.provider}/${e.model}`).filter(Boolean),u=i.get(`${e}/${t}`)||`${e}/${t}`;k=[...new Set([u,...s,...n])],c.info("COMBO",`Auto selection: ${u} | intent=${l} task=${d} | strategy=${f} | ${o}`)}else c.warn("COMBO","Auto strategy has no candidates, keeping default ordering")}else if("strict-random"===S){let e=await (0,m.getNextFromDeck)(`combo:${a.name}`,k),t=k.filter(t=>t!==e);k=[e,...t],c.info("COMBO",`Strict-random deck: ${e} selected (${k.length} models)`)}else"random"===S?(k=(0,m.fisherYatesShuffle)([...k]),c.info("COMBO",`Random shuffle: ${k.length} models`)):"least-used"===S?(k=function(e,t){let r=(0,o.getComboMetrics)(t);if(!r||!r.byModel)return e;let n=e.map(e=>({modelStr:e,requests:r.byModel[e]?.requests??0}));return n.sort((e,t)=>e.requests-t.requests),n.map(e=>e.modelStr)}(k,a.name),c.info("COMBO",`Least-used ordering: ${k[0]} has fewest requests`)):"cost-optimized"===S&&(k=await _(k),c.info("COMBO",`Cost-optimized ordering: cheapest first (${k[0]})`));let V=null,G=null,Y=null,Q=Date.now(),X=0;for(let r=0;r<k.length;r++){let n=k[r],i=(0,p.parseModel)(n),s=i.provider||i.providerAlias||"unknown",u=(0,t.getProviderProfile)(s),m=`combo:${n}`,f=(0,d.getCircuitBreaker)(m,{failureThreshold:u.circuitBreakerThreshold,resetTimeout:u.circuitBreakerReset});if(!f.canExecute()){c.info("COMBO",`Skipping ${n}: circuit breaker OPEN for ${s}`),r>0&&X++;continue}if(l&&!await l(n)){c.info("COMBO",`Skipping ${n} (all accounts in cooldown)`),r>0&&X++;continue}for(let i=0;i<=H;i++){i>0&&(c.info("COMBO",`Retrying ${n} in ${J}ms (attempt ${i+1}/${H+1})`),await new Promise(e=>setTimeout(e,J))),c.info("COMBO",`Trying model ${r+1}/${k.length}: ${n}${i>0?` (retry ${i})`:""}`);let l=await z(e,n);if(l.ok){let e=Date.now()-Q;return c.info("COMBO",`Model ${n} succeeded (${e}ms, ${X} fallbacks)`),(0,o.recordComboRequest)(a.name,n,{success:!0,latencyMs:e,fallbackCount:X,strategy:S}),l}let u=l.statusText||"",d=null;try{let e=l.clone();try{let t=await e.json();u=t?.error?.message||t?.error||t?.message||u,d=t?.retryAfter||null}catch{try{let e=await l.text();e&&(u=e.substring(0,500))}catch{}}}catch{}if(d&&(!G||new Date(d)<new Date(G))&&(G=d),"string"!=typeof u)try{u=JSON.stringify(u)}catch{u=String(u)}let{shouldFallback:m,cooldownMs:p}=(0,t.checkFallbackError)(l.status,u,0,null,s);if(T.includes(l.status)&&f._onFailure(),!m)return c.warn("COMBO",`Model ${n} failed (no fallback)`,{status:l.status}),l;let g=[408,429,500,502,503,504].includes(l.status);if(!(i<H)||!g){V=u||String(l.status),Y||(Y=l.status),r>0&&X++,c.warn("COMBO",`Model ${n} failed, trying next`,{status:l.status});break}}}let Z=k.every(e=>!(0,d.getCircuitBreaker)(`combo:${e}`).canExecute()),ee=Date.now()-Q;if((0,o.recordComboRequest)(a.name,null,{success:!1,latencyMs:ee,fallbackCount:X,strategy:S}),Z)return c.warn("COMBO","All models have circuit breaker OPEN — aborting"),(0,r.unavailableResponse)(503,"All providers temporarily unavailable (circuit breakers open)");let et=Y||406,er=V||"All combo models unavailable";if(G){let e=(0,t.formatRetryAfter)(G);return c.warn("COMBO",`All models failed | ${er} (${e})`),(0,r.unavailableResponse)(et,er,G,e)}return c.warn("COMBO",`All models failed | ${er}`),new Response(JSON.stringify({error:{message:er}}),{status:et,headers:{"Content-Type":"application/json"}})}async function W({body:e,combo:a,handleSingleModel:m,isModelAvailable:f,log:g,settings:h,allCombos:y}){let b,w=a.models||[],v=h?i(a,h):{...n,...a.config||{}},M=v.concurrencyPerModel??3,k=v.queueTimeoutMs??3e4,x=v.maxRetries??1,$=v.retryDelayMs??2e3,O=(b=y?L(a,y):w.map(e=>D(e).model)).length;if(0===O)return(0,r.unavailableResponse)(406,"Round-robin combo has no models");let C=q.get(a.name)||0;q.set(a.name,C+1);let R=C%O,A=Date.now(),S=null,E=null,P=null,B=0;for(let r=0;r<O;r++){let n,i=b[(R+r)%O],h=(0,p.parseModel)(i),y=h.provider||h.providerAlias||"unknown",w=(0,t.getProviderProfile)(y),v=`combo:${i}`,N=(0,d.getCircuitBreaker)(v,{failureThreshold:w.circuitBreakerThreshold,resetTimeout:w.circuitBreakerReset});if(!N.canExecute()){g.info("COMBO-RR",`Skipping ${i}: circuit breaker OPEN for ${y}`),r>0&&B++;continue}if(f&&!await f(i)){g.info("COMBO-RR",`Skipping ${i} (all accounts in cooldown)`),r>0&&B++;continue}try{n=await function(e,{maxConcurrency:t=3,timeoutMs:r=3e4}={}){let o=s(e,t);return o.running<o.max&&!l(o)?(o.running++,Promise.resolve(u(e))):new Promise((t,n)=>{let i=setTimeout(()=>{let t=o.queue.findIndex(e=>e.timer===i);-1!==t&&o.queue.splice(t,1);let a=Error(`Semaphore timeout after ${r}ms for ${e}`);a.code="SEMAPHORE_TIMEOUT",n(a)},r);o.queue.push({resolve:t,reject:n,timer:i})})}(i,{maxConcurrency:M,timeoutMs:k})}catch(e){if("SEMAPHORE_TIMEOUT"===e.code){g.warn("COMBO-RR",`Semaphore timeout for ${i}, trying next model`),r>0&&B++;continue}throw e}try{for(let n=0;n<=x;n++){n>0&&(g.info("COMBO-RR",`Retrying ${i} in ${$}ms (attempt ${n+1}/${x+1})`),await new Promise(e=>setTimeout(e,$))),g.info("COMBO-RR",`[RR #${C}] → ${i}${r>0?` (fallback +${r})`:""}${n>0?` (retry ${n})`:""}`);let l=await m(e,i);if(l.ok){let e=Date.now()-A;return g.info("COMBO-RR",`${i} succeeded (${e}ms, ${B} fallbacks)`),(0,o.recordComboRequest)(a.name,i,{success:!0,latencyMs:e,fallbackCount:B,strategy:"round-robin"}),l}let u=l.statusText||"",d=null;try{let e=l.clone();try{let t=await e.json();u=t?.error?.message||t?.error||t?.message||u,d=t?.retryAfter||null}catch{try{let e=await l.text();e&&(u=e.substring(0,500))}catch{}}}catch{}if(d&&(!P||new Date(d)<new Date(P))&&(P=d),"string"!=typeof u)try{u=JSON.stringify(u)}catch{u=String(u)}let{shouldFallback:p,cooldownMs:f}=(0,t.checkFallbackError)(l.status,u,0,null,y);if(T.includes(l.status)&&f>0&&(!function(e,t){let r=s(e);r.rateLimitedUntil=Date.now()+t,setTimeout(()=>{r.rateLimitedUntil&&Date.now()>=r.rateLimitedUntil&&(r.rateLimitedUntil=null,c(e))},t+50)}(i,f),N._onFailure(),g.warn("COMBO-RR",`${i} error ${l.status}, cooldown ${f}ms (breaker: ${N.getStatus().failureCount}/${w.circuitBreakerThreshold})`)),!p)return g.warn("COMBO-RR",`${i} failed (no fallback)`,{status:l.status}),l;let h=[408,429,500,502,503,504].includes(l.status);if(!(n<x)||!h){S=u||String(l.status),E||(E=l.status),r>0&&B++,g.warn("COMBO-RR",`${i} failed, trying next model`,{status:l.status});break}}}finally{n()}}let N=Date.now()-A;if((0,o.recordComboRequest)(a.name,null,{success:!1,latencyMs:N,fallbackCount:B,strategy:"round-robin"}),b.every(e=>!(0,d.getCircuitBreaker)(`combo:${e}`).canExecute()))return g.warn("COMBO-RR","All models have circuit breaker OPEN — aborting"),(0,r.unavailableResponse)(503,"All providers temporarily unavailable (circuit breakers open)");let I=E||406,F=S||"All round-robin combo models unavailable";if(P){let e=(0,t.formatRetryAfter)(P);return g.warn("COMBO-RR",`All models failed | ${F} (${e})`),(0,r.unavailableResponse)(I,F,P,e)}return g.warn("COMBO-RR",`All models failed | ${F}`),new Response(JSON.stringify({error:{message:F}}),{status:I,headers:{"Content-Type":"application/json"}})}e.s(["handleComboChat",()=>U,"validateComboDAG",()=>function e(t,r,o=new Set,n=0){if(n>3)throw Error(`Max combo nesting depth (3) exceeded at "${t}"`);if(o.has(t))throw Error(`Circular combo reference detected: ${t}`);o.add(t);let i=Array.isArray(r)?r:r?.combos||[],a=i.find(e=>e.name===t);if(a&&a.models)for(let t of a.models){let r=D(t).model;i.find(e=>e.name===r)&&e(r,i,new Set(o),n+1)}}],928041)}];
|
|
8
6
|
|
|
@@ -2,7 +2,7 @@ module.exports=[352812,e=>{"use strict";var t=e.i(496727);let n="abcdefghijklmno
|
|
|
2
2
|
\`\`\`json
|
|
3
3
|
${t}
|
|
4
4
|
\`\`\`
|
|
5
|
-
Respond ONLY with the JSON object, no other text.`)}else"json_object"===e.type&&a.push("You must respond with valid JSON. Respond ONLY with a JSON object, no other text.")}return t.thinking&&(l.thinking={type:t.thinking.type||"enabled",...t.thinking.budget_tokens&&{budget_tokens:t.thinking.budget_tokens},...t.thinking.max_tokens&&{max_tokens:t.thinking.max_tokens}}),r.size>0&&(l._toolNameMap=r),l}function x(e){return"string"==typeof e?e:Array.isArray(e)?e.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):""}function A(e,t,n){let o={model:e,messages:[],stream:n};if(t.generationConfig){let e=t.generationConfig;e.maxOutputTokens&&(o.max_tokens=_({max_tokens:e.maxOutputTokens,tools:t.tools})),void 0!==e.temperature&&(o.temperature=e.temperature),void 0!==e.topP&&(o.top_p=e.topP)}if(t.systemInstruction){var s;let e="string"==typeof(s=t.systemInstruction)?s:s.parts&&Array.isArray(s.parts)?s.parts.map(e=>e.text||"").join(""):"";e&&o.messages.push({role:"system",content:e})}if(t.contents&&Array.isArray(t.contents))for(let e of t.contents){let t=function(e){let t="user"===e.role?"user":"assistant";if(!e.parts||!Array.isArray(e.parts))return null;let n=[],o=[];for(let t of e.parts)if(void 0!==t.text&&n.push({type:"text",text:t.text}),t.inlineData&&n.push({type:"image_url",image_url:{url:`data:${t.inlineData.mimeType};base64,${t.inlineData.data}`}}),t.functionCall&&o.push({id:`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:t.functionCall.name,arguments:JSON.stringify(t.functionCall.args||{})}}),t.functionResponse)return{role:"tool",tool_call_id:t.functionResponse.id||t.functionResponse.name,content:JSON.stringify(t.functionResponse.response?.result||t.functionResponse.response||{})};if(o.length>0){let e={role:"assistant"};return n.length>0&&(e.content=1===n.length?n[0].text:n),e.tool_calls=o,e}return n.length>0?{role:t,content:1===n.length&&"text"===n[0].type?n[0].text:n}:null}(e);t&&o.messages.push(t)}if(t.tools&&Array.isArray(t.tools)){for(let e of(o.tools=[],t.tools))if(e.functionDeclarations)for(let t of e.functionDeclarations)o.tools.push({type:"function",function:{name:t.name,description:t.description||"",parameters:t.parameters||{type:"object",properties:{}}}})}return o}f(t.FORMATS.OPENAI,t.FORMATS.CLAUDE,h,null),f(t.FORMATS.GEMINI,t.FORMATS.OPENAI,A,null),f(t.FORMATS.GEMINI_CLI,t.FORMATS.OPENAI,A,null);let k=["minLength","maxLength","exclusiveMinimum","exclusiveMaximum","pattern","minItems","maxItems","format","default","examples","$schema","$defs","definitions","const","$ref","additionalProperties","propertyNames","patternProperties","anyOf","oneOf","allOf","not","dependencies","dependentSchemas","dependentRequired","title","if","then","else","contentMediaType","contentEncoding","optional","cornerRadius","fillColor","fontFamily","fontSize","fontWeight","gap","padding","strokeColor","strokeThickness","textColor"],I=[{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"OFF"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"OFF"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"OFF"},{category:"HARM_CATEGORY_HARASSMENT",threshold:"OFF"},{category:"HARM_CATEGORY_CIVIC_INTEGRITY",threshold:"OFF"}];function O(e){return"string"==typeof e?e:Array.isArray(e)?e.filter(e=>"text"===e.type).map(e=>e.text).join(""):""}function S(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return null}}function b(){return`-${Math.floor(9e18*Math.random())}`}function T(e){let t=0,n=-1;for(let o=0;o<e.length;o++){let s=e[o],r=0,i=s.type;"object"===i||s.properties?r=3:"array"===i||s.items?r=2:i&&"null"!==i&&(r=1),r>n&&(n=r,t=o)}return t}function C(e){return e&&"object"==typeof e&&(!function e(t){if(t&&"object"==typeof t)for(let n of(void 0===t.const||t.enum||(t.enum=[t.const],delete t.const),Object.values(t)))n&&"object"==typeof n&&e(n)}(e),!function e(t){if(t&&"object"==typeof t)for(let n of(t.enum&&Array.isArray(t.enum)&&(t.enum=t.enum.map(e=>String(e))),Object.values(t)))n&&"object"==typeof n&&e(n)}(e),!function e(t){if(t&&"object"==typeof t){if(t.allOf&&Array.isArray(t.allOf)){let e={};for(let n of t.allOf)if(n.properties&&(e.properties||(e.properties={}),Object.assign(e.properties,n.properties)),n.required&&Array.isArray(n.required))for(let t of(e.required||(e.required=[]),n.required))e.required.includes(t)||e.required.push(t);delete t.allOf,e.properties&&(t.properties={...t.properties,...e.properties}),e.required&&(t.required=[...t.required||[],...e.required])}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t){if(t&&"object"==typeof t){if(t.anyOf&&Array.isArray(t.anyOf)&&t.anyOf.length>0){let e=t.anyOf.filter(e=>e&&"null"!==e.type);if(e.length>0){let n=T(e),o=e[n];delete t.anyOf,Object.assign(t,o)}}if(t.oneOf&&Array.isArray(t.oneOf)&&t.oneOf.length>0){let e=t.oneOf.filter(e=>e&&"null"!==e.type);if(e.length>0){let n=T(e),o=e[n];delete t.oneOf,Object.assign(t,o)}}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t){if(t&&"object"==typeof t){if(t.type&&Array.isArray(t.type)){let e=t.type.filter(e=>"null"!==e);t.type=e.length>0?e[0]:"string"}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t,n){if(t&&"object"==typeof t)if(Array.isArray(t))for(let o of t)e(o,n);else{for(let e of n)e in t&&delete t[e];for(let o of Object.values(t))o&&"object"==typeof o&&e(o,n)}}(e,k),!function e(t){if(t&&"object"==typeof t){if(t.required&&Array.isArray(t.required)&&t.properties){let e=t.required.filter(e=>Object.prototype.hasOwnProperty.call(t.properties,e));0===e.length?delete t.required:t.required=e}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t){if(t&&"object"==typeof t)for(let n of("object"!==t.type||t.properties&&0!==Object.keys(t.properties).length||(t.properties={reason:{type:"string",description:"Brief explanation of why you are calling this tool"}},t.required=["reason"]),Object.values(t)))n&&"object"==typeof n&&e(n)}(e)),e}function M(){return crypto.randomUUID()}function R(e,t,n){let o={model:e,contents:[],generationConfig:{},safetySettings:I};void 0!==t.temperature&&(o.generationConfig.temperature=t.temperature),void 0!==t.top_p&&(o.generationConfig.topP=t.top_p),void 0!==t.top_k&&(o.generationConfig.topK=t.top_k),void 0!==t.max_tokens&&(o.generationConfig.maxOutputTokens=t.max_tokens);let s={};if(t.messages&&Array.isArray(t.messages)){for(let e of t.messages)if("assistant"===e.role&&e.tool_calls)for(let t of e.tool_calls)"function"===t.type&&t.id&&t.function?.name&&(s[t.id]=t.function.name)}let r={};if(t.messages&&Array.isArray(t.messages))for(let e of t.messages)"tool"===e.role&&e.tool_call_id&&(r[e.tool_call_id]=e.content);if(t.messages&&Array.isArray(t.messages))for(let e=0;e<t.messages.length;e++){let n=t.messages[e],i=n.role,a=n.content;if("system"===i&&t.messages.length>1)o.systemInstruction={role:"user",parts:[{text:"string"==typeof a?a:O(a)}]};else if("user"===i||"system"===i&&1===t.messages.length){let e=function(e){let t=[];if("string"==typeof e)t.push({text:e});else if(Array.isArray(e)){for(let n of e)if("text"===n.type)t.push({text:n.text});else if("image_url"===n.type&&n.image_url?.url?.startsWith("data:")){let e=n.image_url.url,o=e.indexOf(",");if(-1!==o){let n=e.substring(5,o),s=e.substring(o+1),r=n.split(";")[0];t.push({inlineData:{mime_type:r,data:s}})}}}return t}(a);e.length>0&&o.contents.push({role:"user",parts:e})}else if("assistant"===i){let e=[];if(n.reasoning_content&&(e.push({thought:!0,text:n.reasoning_content}),e.push({thoughtSignature:l,text:""})),a){let t="string"==typeof a?a:O(a);t&&e.push({text:t})}if(n.tool_calls&&Array.isArray(n.tool_calls)){let t=[];for(let o of n.tool_calls){if("function"!==o.type)continue;let n=S(o.function?.arguments||"{}");e.push({thoughtSignature:l,functionCall:{id:o.id,name:o.function.name,args:n}}),t.push(o.id)}if(e.length>0&&o.contents.push({role:"model",parts:e}),t.some(e=>r[e])){let e=[];for(let n of t){if(!r[n])continue;let t=s[n];if(!t){let e=n.split("-");t=e.length>2?e.slice(0,-2).join("-"):n}let o=r[n],i=S(o);null===i?i={result:o}:"object"!=typeof i&&(i={result:i}),e.push({functionResponse:{id:n,name:t,response:{result:i}}})}e.length>0&&o.contents.push({role:"user",parts:e})}}else e.length>0&&o.contents.push({role:"model",parts:e})}}if(t.tools&&Array.isArray(t.tools)&&t.tools.length>0){let e=[];for(let n of t.tools)if(n.name&&n.input_schema)e.push({name:n.name,description:n.description||"",parameters:C(n.input_schema||{type:"object",properties:{}})});else if("function"===n.type&&n.function){let t=n.function;e.push({name:t.name,description:t.description||"",parameters:C(t.parameters||{type:"object",properties:{}})})}e.length>0&&(o.tools=[{functionDeclarations:e}])}if(t.response_format)if("json_schema"===t.response_format.type&&t.response_format.json_schema){o.generationConfig.responseMimeType="application/json";let e=t.response_format.json_schema.schema||t.response_format.json_schema;e&&"object"==typeof e&&(o.generationConfig.responseSchema=C(e))}else"json_object"===t.response_format.type?o.generationConfig.responseMimeType="application/json":"text"===t.response_format.type&&(o.generationConfig.responseMimeType="text/plain");return o}function j(e,t,n){let o=R(e,t,n);if(e.toLowerCase().includes("claude"),t.reasoning_effort){let e={low:1024,medium:8192,high:32768}[t.reasoning_effort]||8192;o.generationConfig.thinkingConfig={thinkingBudget:e,include_thoughts:!0}}if(t.thinking?.type==="enabled"&&t.thinking.budget_tokens&&(o.generationConfig.thinkingConfig={thinkingBudget:t.thinking.budget_tokens,include_thoughts:!0}),o.tools?.[0]?.functionDeclarations){for(let e of o.tools[0].functionDeclarations)if(e.parameters){let t=C(e.parameters);e.parameters=t}}return o}function E(e,t,n=null,o=!1){let s=n?.projectId;s||(console.warn(`[OmniRoute] ${o?"Antigravity":"GeminiCLI"} account is missing projectId. Attempting request with empty project — reconnect OAuth to resolve.`),s="");let r={project:s,model:e.includes("/")?e.split("/").pop():e,userAgent:o?"antigravity":"gemini-cli",requestId:o?`agent-${M()}`:`agent-${crypto.randomUUID()}`,request:{sessionId:b(),contents:t.contents,systemInstruction:t.systemInstruction,generationConfig:t.generationConfig,tools:t.tools}};if(o){r.requestType="agent";let e={text:g.ANTIGRAVITY_DEFAULT_SYSTEM};r.request.systemInstruction?.parts?r.request.systemInstruction.parts.unshift(e):r.request.systemInstruction={role:"user",parts:[e]},t.tools?.length>0&&(r.request.toolConfig={functionCallingConfig:{mode:"VALIDATED"}})}else r.request.safetySettings=t.safetySettings;return r}f(t.FORMATS.OPENAI,t.FORMATS.GEMINI,function(e,t,n){return R(e,t,n)},null),f(t.FORMATS.OPENAI,t.FORMATS.GEMINI_CLI,(e,t,n,o)=>E(e,j(e,t,n),o),null),f(t.FORMATS.OPENAI,t.FORMATS.ANTIGRAVITY,function(e,t,n,o=null){if(e.toLowerCase().includes("claude")){let s,r=((s=h(e,t,n)).system&&Array.isArray(s.system)&&(s.system=s.system.filter(e=>!e.text||!e.text.includes("You are Claude Code")),0===s.system.length&&delete s.system),s.tools&&Array.isArray(s.tools)&&(s.tools=s.tools.map(e=>e.name&&e.name.startsWith(y)?{...e,name:e.name.slice(y.length)}:e)),s.messages&&Array.isArray(s.messages)&&(s.messages=s.messages.map(e=>{if(!e.content||!Array.isArray(e.content))return e;let t=e.content.map(e=>{let t="string"==typeof e.type?e.type:"",n="string"==typeof e.name?e.name:"";return"tool_use"===t&&n&&n.startsWith(y)?{...e,name:n.slice(y.length)}:e});return{...e,content:t}})),s);return function(e,t,n=null){let o=n?.projectId;o||(console.warn(`[OmniRoute] Antigravity/Claude account is missing projectId. Attempting request with empty project — reconnect OAuth to resolve.`),o="");let s={project:o,model:e.includes("/")?e.split("/").pop():e,userAgent:"antigravity",requestId:`agent-${M()}`,requestType:"agent",request:{sessionId:b(),contents:[],generationConfig:{temperature:t.temperature||1,maxOutputTokens:t.max_tokens||4096}}};if(t.messages&&Array.isArray(t.messages))for(let e of t.messages){let t=[];if(Array.isArray(e.content)){for(let n of e.content)if("text"===n.type)t.push({text:n.text});else if("tool_use"===n.type)t.push({functionCall:{id:n.id,name:n.name,args:n.input||{}}});else if("tool_result"===n.type){let e=n.content;Array.isArray(e)&&(e=e.map(e=>"text"===e.type?e.text:JSON.stringify(e)).join("\n")),t.push({functionResponse:{id:n.tool_use_id,name:"unknown",response:{result:S(e)||e}}})}}else"string"==typeof e.content&&t.push({text:e.content});t.length>0&&s.request.contents.push({role:"assistant"===e.role?"model":"user",parts:t})}if(t.tools&&Array.isArray(t.tools)){let e=[];for(let n of t.tools)if(n.name&&n.input_schema){let t=C(n.input_schema);e.push({name:n.name,description:n.description||"",parameters:t})}e.length>0&&(s.request.tools=[{functionDeclarations:e}],s.request.toolConfig={functionCallingConfig:{mode:"VALIDATED"}})}let r=[{text:g.ANTIGRAVITY_DEFAULT_SYSTEM}];if(t.system)if(Array.isArray(t.system))for(let e of t.system)e.text&&r.push({text:e.text});else"string"==typeof t.system&&r.push({text:t.system});return s.request.systemInstruction={role:"user",parts:r},s}(e,r,o)}let s=j(e,t,n);return E(e,s,o,!0)},null),f(t.FORMATS.ANTIGRAVITY,t.FORMATS.OPENAI,function(e,t,n){let o=t.request||t,s={model:e,messages:[],stream:n};if(o.generationConfig){let e=o.generationConfig;if(e.maxOutputTokens&&(s.max_tokens=_({max_tokens:e.maxOutputTokens,tools:o.tools})),void 0!==e.temperature&&(s.temperature=e.temperature),void 0!==e.topP&&(s.top_p=e.topP),void 0!==e.topK&&(s.top_k=e.topK),e.thinkingConfig){let t=e.thinkingConfig.thinkingBudget||0;t>0&&(t<=2048?s.reasoning_effort="low":t<=16384?s.reasoning_effort="medium":s.reasoning_effort="high")}}if(o.systemInstruction){var r;let e="string"==typeof(r=o.systemInstruction)?r:r.parts&&Array.isArray(r.parts)?r.parts.map(e=>e.text||"").join(""):"";e&&s.messages.push({role:"system",content:e})}if(o.contents&&Array.isArray(o.contents))for(let e of o.contents){let t=function(e){let t="model"===e.role?"assistant":"user"===e.role?"user":e.role;if(!e.parts||!Array.isArray(e.parts))return null;let n=[],o=[],s=[],r="";for(let t of e.parts){if(!0===t.thought&&t.text){r+=t.text;continue}if(t.thoughtSignature&&void 0!==t.text){n.push({type:"text",text:t.text});continue}void 0!==t.text&&n.push({type:"text",text:t.text}),t.inlineData&&n.push({type:"image_url",image_url:{url:`data:${t.inlineData.mimeType};base64,${t.inlineData.data}`}}),t.functionCall&&o.push({id:t.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:t.functionCall.name,arguments:JSON.stringify(t.functionCall.args||{})}}),t.functionResponse&&s.push({role:"tool",tool_call_id:t.functionResponse.id||t.functionResponse.name,content:JSON.stringify(t.functionResponse.response?.result||t.functionResponse.response||{})})}if(s.length>0)return s;if(o.length>0){let e={role:"assistant"};return n.length>0&&(e.content=1===n.length&&"text"===n[0].type?n[0].text:n),r&&(e.reasoning_content=r),e.tool_calls=o,e}if(n.length>0||r){let e={role:t};return n.length>0&&(e.content=1===n.length&&"text"===n[0].type?n[0].text:n),r&&(e.reasoning_content=r),e}return null}(e);t&&(Array.isArray(t)?s.messages.push(...t):s.messages.push(t))}if(o.tools&&Array.isArray(o.tools)){for(let e of(s.tools=[],o.tools))if(e.functionDeclarations)for(let t of e.functionDeclarations)s.tools.push({type:"function",function:{name:t.name,description:t.description||"",parameters:function e(t){if(!t||"object"!=typeof t)return t;let n=Array.isArray(t)?[...t]:{...t};if("string"==typeof n.type&&(n.type=n.type.toLowerCase()),n.properties){let t={};for(let[o,s]of Object.entries(n.properties))t[o]=e(s);n.properties=t}return n.items&&(n.items=e(n.items)),n}(t.parameters)||{type:"object",properties:{}}}})}return s},null);let N=["file_search","code_interpreter","web_search_preview"];function F(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function D(e){return Array.isArray(e)?e:[]}function v(e,t=""){return"string"==typeof e?e:t}function w(e){let t=Error(e);return t.statusCode=400,t.errorType="unsupported_feature",t}f(t.FORMATS.OPENAI_RESPONSES,t.FORMATS.OPENAI,function(e,t,n,o){let s=F(t);if(void 0===s.input)return t;let r=D(s.tools);if(r.length>0)for(let e of r){let t=F(e);if(N.includes(v(t.type)))throw w(`Unsupported Responses API feature: ${v(t.type)} tool type is not supported by omniroute`)}if(s.background)throw w("Unsupported Responses API feature: background mode is not supported by omniroute");let i={...s},l=[];i.messages=l,"string"==typeof s.instructions&&s.instructions.length>0&&l.push({role:"system",content:s.instructions});let a=null,u=[];for(let e of D(s.input)){let t=F(e),n=v(t.type)||(t.role?"message":"");if("message"===n){if(a&&(l.push(a),a=null),u.length>0){for(let e of u)l.push(e);u=[]}let e=Array.isArray(t.content)?t.content.map(e=>{let t=F(e);return"input_text"===t.type||"output_text"===t.type?{type:"text",text:v(t.text)}:e}):t.content;l.push({role:v(t.role),content:e});continue}if("function_call"===n){let e=v(t.name).trim();if(!e)continue;a||(a={role:"assistant",content:null,tool_calls:[]});let n=Array.isArray(a.tool_calls)?a.tool_calls:[];n.push({id:v(t.call_id),type:"function",function:{name:e,arguments:t.arguments}}),a.tool_calls=n;continue}if("function_call_output"===n){if(a&&(l.push(a),a=null),u.length>0){for(let e of u)l.push(e);u=[]}l.push({role:"tool",tool_call_id:v(t.call_id),content:"string"==typeof t.output?t.output:JSON.stringify(t.output)});continue}if("reasoning"===n)continue}if(a&&l.push(a),u.length>0)for(let e of u)l.push(e);Array.isArray(s.tools)&&(i.tools=s.tools.map(e=>{let t=F(e);return t.function?e:{type:"function",function:{name:v(t.name),description:v(t.description),parameters:t.parameters,strict:t.strict}}}));let c=new Set;for(let e of l){let t=F(e);if(Array.isArray(t.tool_calls))for(let e of t.tool_calls)e.id&&c.add(String(e.id))}return i.messages=l.filter(e=>{let t=F(e);return"tool"!==t.role||!t.tool_call_id||c.has(String(t.tool_call_id))}),delete i.input,delete i.instructions,delete i.include,delete i.prompt_cache_key,delete i.store,delete i.reasoning,i},null),f(t.FORMATS.OPENAI,t.FORMATS.OPENAI_RESPONSES,function(e,t,n,s){let r=F(t),i={model:e,input:[],stream:!0,store:!1},l=i.input,a=!1;for(let e of D(r.messages)){let t=F(e),n=v(t.role);if("system"===n){a||(i.instructions="string"==typeof t.content?t.content:"",a=!0);continue}if("user"===n){let e="string"==typeof t.content?[{type:"input_text",text:t.content}]:Array.isArray(t.content)?t.content.map(e=>{let t=F(e);if("text"===t.type)return{type:"input_text",text:v(t.text)};if("image_url"===t.type){let e=t.image_url;return{type:"input_image",image_url:"string"==typeof e?e:e?.url||""}}return e}):[{type:"input_text",text:""}];l.push({type:"message",role:"user",content:e})}if("assistant"===n){let e=[];if("string"==typeof t.content&&t.content)e.push({type:"output_text",text:t.content});else if(Array.isArray(t.content))for(let n of t.content){let t=F(n);if("text"===t.type&&t.text)e.push({type:"output_text",text:v(t.text)});else{if("thinking"===t.type||"redacted_thinking"===t.type)continue;e.push(n)}}if(e.length>0&&l.push({type:"message",role:"assistant",content:e}),Array.isArray(t.tool_calls))for(let e of t.tool_calls){let t=F(e),n=F(t.function),s=v(n.name).trim();s&&l.push({type:"function_call",call_id:v(t.id).trim()||o(),name:s,arguments:v(n.arguments,"{}")})}}"tool"===n&&l.push({type:"function_call_output",call_id:v(t.tool_call_id),output:t.content})}let u=new Set(l.filter(e=>"function_call"===e.type&&e.call_id).map(e=>e.call_id));return i.input=l.filter(e=>"function_call_output"!==e.type||!e.call_id||u.has(e.call_id)),a||(i.instructions=""),Array.isArray(r.tools)&&(i.tools=r.tools.map(e=>{let t=F(e);if("function"===t.type){let e=F(t.function);return{type:"function",name:v(e.name),description:v(e.description),parameters:e.parameters,strict:e.strict}}return e})),void 0!==r.service_tier&&(i.service_tier=r.service_tier),void 0!==r.temperature&&(i.temperature=r.temperature),void 0!==r.max_tokens&&(i.max_tokens=r.max_tokens),void 0!==r.top_p&&(i.top_p=r.top_p),i},null);var P=e.i(689960);function B(e){return"string"==typeof e?e.split("\n")[0]:""}function q(e){return"string"==typeof e?e:Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join(""):""}function $(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function U(e,t,n){let o=(n||"").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,"");return`<tool_result>
|
|
5
|
+
Respond ONLY with the JSON object, no other text.`)}else"json_object"===e.type&&a.push("You must respond with valid JSON. Respond ONLY with a JSON object, no other text.")}return t.thinking&&(l.thinking={type:t.thinking.type||"enabled",...t.thinking.budget_tokens&&{budget_tokens:t.thinking.budget_tokens},...t.thinking.max_tokens&&{max_tokens:t.thinking.max_tokens}}),r.size>0&&(l._toolNameMap=r),l}function x(e){return"string"==typeof e?e:Array.isArray(e)?e.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):""}function A(e,t,n){let o={model:e,messages:[],stream:n};if(t.generationConfig){let e=t.generationConfig;e.maxOutputTokens&&(o.max_tokens=_({max_tokens:e.maxOutputTokens,tools:t.tools})),void 0!==e.temperature&&(o.temperature=e.temperature),void 0!==e.topP&&(o.top_p=e.topP)}if(t.systemInstruction){var s;let e="string"==typeof(s=t.systemInstruction)?s:s.parts&&Array.isArray(s.parts)?s.parts.map(e=>e.text||"").join(""):"";e&&o.messages.push({role:"system",content:e})}if(t.contents&&Array.isArray(t.contents))for(let e of t.contents){let t=function(e){let t="user"===e.role?"user":"assistant";if(!e.parts||!Array.isArray(e.parts))return null;let n=[],o=[];for(let t of e.parts)if(void 0!==t.text&&n.push({type:"text",text:t.text}),t.inlineData&&n.push({type:"image_url",image_url:{url:`data:${t.inlineData.mimeType};base64,${t.inlineData.data}`}}),t.functionCall&&o.push({id:`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:t.functionCall.name,arguments:JSON.stringify(t.functionCall.args||{})}}),t.functionResponse)return{role:"tool",tool_call_id:t.functionResponse.id||t.functionResponse.name,content:JSON.stringify(t.functionResponse.response?.result||t.functionResponse.response||{})};if(o.length>0){let e={role:"assistant"};return n.length>0&&(e.content=1===n.length?n[0].text:n),e.tool_calls=o,e}return n.length>0?{role:t,content:1===n.length&&"text"===n[0].type?n[0].text:n}:null}(e);t&&o.messages.push(t)}if(t.tools&&Array.isArray(t.tools)){for(let e of(o.tools=[],t.tools))if(e.functionDeclarations)for(let t of e.functionDeclarations)o.tools.push({type:"function",function:{name:t.name,description:t.description||"",parameters:t.parameters||{type:"object",properties:{}}}})}return o}f(t.FORMATS.OPENAI,t.FORMATS.CLAUDE,h,null),f(t.FORMATS.GEMINI,t.FORMATS.OPENAI,A,null),f(t.FORMATS.GEMINI_CLI,t.FORMATS.OPENAI,A,null);let k=["minLength","maxLength","exclusiveMinimum","exclusiveMaximum","pattern","minItems","maxItems","format","default","examples","$schema","$defs","definitions","const","$ref","additionalProperties","propertyNames","patternProperties","anyOf","oneOf","allOf","not","dependencies","dependentSchemas","dependentRequired","title","if","then","else","contentMediaType","contentEncoding","optional","cornerRadius","fillColor","fontFamily","fontSize","fontWeight","gap","padding","strokeColor","strokeThickness","textColor"],I=[{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"OFF"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"OFF"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"OFF"},{category:"HARM_CATEGORY_HARASSMENT",threshold:"OFF"},{category:"HARM_CATEGORY_CIVIC_INTEGRITY",threshold:"OFF"}];function O(e){return"string"==typeof e?e:Array.isArray(e)?e.filter(e=>"text"===e.type).map(e=>e.text).join(""):""}function S(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return null}}function b(){return`-${Math.floor(9e18*Math.random())}`}function T(e){let t=0,n=-1;for(let o=0;o<e.length;o++){let s=e[o],r=0,i=s.type;"object"===i||s.properties?r=3:"array"===i||s.items?r=2:i&&"null"!==i&&(r=1),r>n&&(n=r,t=o)}return t}function C(e){return e&&"object"==typeof e&&(!function e(t){if(t&&"object"==typeof t)for(let n of(void 0===t.const||t.enum||(t.enum=[t.const],delete t.const),Object.values(t)))n&&"object"==typeof n&&e(n)}(e),!function e(t){if(t&&"object"==typeof t)for(let n of(t.enum&&Array.isArray(t.enum)&&(t.enum=t.enum.map(e=>String(e))),Object.values(t)))n&&"object"==typeof n&&e(n)}(e),!function e(t){if(t&&"object"==typeof t){if(t.allOf&&Array.isArray(t.allOf)){let e={};for(let n of t.allOf)if(n.properties&&(e.properties||(e.properties={}),Object.assign(e.properties,n.properties)),n.required&&Array.isArray(n.required))for(let t of(e.required||(e.required=[]),n.required))e.required.includes(t)||e.required.push(t);delete t.allOf,e.properties&&(t.properties={...t.properties,...e.properties}),e.required&&(t.required=[...t.required||[],...e.required])}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t){if(t&&"object"==typeof t){if(t.anyOf&&Array.isArray(t.anyOf)&&t.anyOf.length>0){let e=t.anyOf.filter(e=>e&&"null"!==e.type);if(e.length>0){let n=T(e),o=e[n];delete t.anyOf,Object.assign(t,o)}}if(t.oneOf&&Array.isArray(t.oneOf)&&t.oneOf.length>0){let e=t.oneOf.filter(e=>e&&"null"!==e.type);if(e.length>0){let n=T(e),o=e[n];delete t.oneOf,Object.assign(t,o)}}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t){if(t&&"object"==typeof t){if(t.type&&Array.isArray(t.type)){let e=t.type.filter(e=>"null"!==e);t.type=e.length>0?e[0]:"string"}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t,n){if(t&&"object"==typeof t)if(Array.isArray(t))for(let o of t)e(o,n);else{for(let e of n)e in t&&delete t[e];for(let o of Object.values(t))o&&"object"==typeof o&&e(o,n)}}(e,k),!function e(t){if(t&&"object"==typeof t){if(t.required&&Array.isArray(t.required)&&t.properties){let e=t.required.filter(e=>Object.prototype.hasOwnProperty.call(t.properties,e));0===e.length?delete t.required:t.required=e}for(let n of Object.values(t))n&&"object"==typeof n&&e(n)}}(e),!function e(t){if(t&&"object"==typeof t)for(let n of("object"!==t.type||t.properties&&0!==Object.keys(t.properties).length||(t.properties={reason:{type:"string",description:"Brief explanation of why you are calling this tool"}},t.required=["reason"]),Object.values(t)))n&&"object"==typeof n&&e(n)}(e)),e}function M(){return crypto.randomUUID()}function R(e,t,n){let o={model:e,contents:[],generationConfig:{},safetySettings:I};void 0!==t.temperature&&(o.generationConfig.temperature=t.temperature),void 0!==t.top_p&&(o.generationConfig.topP=t.top_p),void 0!==t.top_k&&(o.generationConfig.topK=t.top_k),void 0!==t.max_tokens&&(o.generationConfig.maxOutputTokens=t.max_tokens);let s={};if(t.messages&&Array.isArray(t.messages)){for(let e of t.messages)if("assistant"===e.role&&e.tool_calls)for(let t of e.tool_calls)"function"===t.type&&t.id&&t.function?.name&&(s[t.id]=t.function.name)}let r={};if(t.messages&&Array.isArray(t.messages))for(let e of t.messages)"tool"===e.role&&e.tool_call_id&&(r[e.tool_call_id]=e.content);if(t.messages&&Array.isArray(t.messages))for(let e=0;e<t.messages.length;e++){let n=t.messages[e],i=n.role,a=n.content;if("system"===i&&t.messages.length>1)o.systemInstruction={role:"user",parts:[{text:"string"==typeof a?a:O(a)}]};else if("user"===i||"system"===i&&1===t.messages.length){let e=function(e){let t=[];if("string"==typeof e)t.push({text:e});else if(Array.isArray(e)){for(let n of e)if("text"===n.type)t.push({text:n.text});else if("image_url"===n.type&&n.image_url?.url?.startsWith("data:")){let e=n.image_url.url,o=e.indexOf(",");if(-1!==o){let n=e.substring(5,o),s=e.substring(o+1),r=n.split(";")[0];t.push({inlineData:{mime_type:r,data:s}})}}}return t}(a);e.length>0&&o.contents.push({role:"user",parts:e})}else if("assistant"===i){let e=[];if(n.reasoning_content&&(e.push({thought:!0,text:n.reasoning_content}),e.push({thoughtSignature:l,text:""})),a){let t="string"==typeof a?a:O(a);t&&e.push({text:t})}if(n.tool_calls&&Array.isArray(n.tool_calls)){let t=[];for(let o of n.tool_calls){if("function"!==o.type)continue;let n=S(o.function?.arguments||"{}");e.push({thoughtSignature:l,functionCall:{id:o.id,name:o.function.name,args:n}}),t.push(o.id)}if(e.length>0&&o.contents.push({role:"model",parts:e}),t.some(e=>r[e])){let e=[];for(let n of t){if(!r[n])continue;let t=s[n];if(!t){let e=n.split("-");t=e.length>2?e.slice(0,-2).join("-"):n}let o=r[n],i=S(o);null===i?i={result:o}:"object"!=typeof i&&(i={result:i}),e.push({functionResponse:{id:n,name:t,response:{result:i}}})}e.length>0&&o.contents.push({role:"user",parts:e})}}else e.length>0&&o.contents.push({role:"model",parts:e})}}if(t.tools&&Array.isArray(t.tools)&&t.tools.length>0){let e=[];for(let n of t.tools)if(n.name&&n.input_schema)e.push({name:n.name,description:n.description||"",parameters:C(n.input_schema||{type:"object",properties:{}})});else if("function"===n.type&&n.function){let t=n.function;e.push({name:t.name,description:t.description||"",parameters:C(t.parameters||{type:"object",properties:{}})})}e.length>0&&(o.tools=[{functionDeclarations:e}])}if(t.response_format)if("json_schema"===t.response_format.type&&t.response_format.json_schema){o.generationConfig.responseMimeType="application/json";let e=t.response_format.json_schema.schema||t.response_format.json_schema;e&&"object"==typeof e&&(o.generationConfig.responseSchema=C(e))}else"json_object"===t.response_format.type?o.generationConfig.responseMimeType="application/json":"text"===t.response_format.type&&(o.generationConfig.responseMimeType="text/plain");return o}function j(e,t,n){let o=R(e,t,n);if(e.toLowerCase().includes("claude"),t.reasoning_effort){let e={low:1024,medium:8192,high:32768}[t.reasoning_effort]||8192;o.generationConfig.thinkingConfig={thinkingBudget:e,include_thoughts:!0}}if(t.thinking?.type==="enabled"&&t.thinking.budget_tokens&&(o.generationConfig.thinkingConfig={thinkingBudget:t.thinking.budget_tokens,include_thoughts:!0}),o.tools?.[0]?.functionDeclarations){for(let e of o.tools[0].functionDeclarations)if(e.parameters){let t=C(e.parameters);e.parameters=t}}return o}function E(e,t,n=null,o=!1){let s=n?.projectId;s||(console.warn(`[OmniRoute] ${o?"Antigravity":"GeminiCLI"} account is missing projectId. Attempting request with empty project — reconnect OAuth to resolve.`),s="");let r={project:s,model:e.includes("/")?e.split("/").pop():e,userAgent:o?"antigravity":"gemini-cli",requestId:o?`agent-${M()}`:`agent-${crypto.randomUUID()}`,request:{sessionId:b(),contents:t.contents,systemInstruction:t.systemInstruction,generationConfig:t.generationConfig,tools:t.tools}};if(o){r.requestType="agent";let e={text:g.ANTIGRAVITY_DEFAULT_SYSTEM};r.request.systemInstruction?.parts?r.request.systemInstruction.parts.unshift(e):r.request.systemInstruction={role:"user",parts:[e]},t.tools?.length>0&&(r.request.toolConfig={functionCallingConfig:{mode:"VALIDATED"}})}else r.request.safetySettings=t.safetySettings;return r}f(t.FORMATS.OPENAI,t.FORMATS.GEMINI,function(e,t,n){return R(e,t,n)},null),f(t.FORMATS.OPENAI,t.FORMATS.GEMINI_CLI,(e,t,n,o)=>E(e,j(e,t,n),o),null),f(t.FORMATS.OPENAI,t.FORMATS.ANTIGRAVITY,function(e,t,n,o=null){if(e.toLowerCase().includes("claude")){let s,r=((s=h(e,t,n)).system&&Array.isArray(s.system)&&(s.system=s.system.filter(e=>!e.text||!e.text.includes("You are Claude Code")),0===s.system.length&&delete s.system),s.tools&&Array.isArray(s.tools)&&(s.tools=s.tools.map(e=>e.name&&e.name.startsWith(y)?{...e,name:e.name.slice(y.length)}:e)),s.messages&&Array.isArray(s.messages)&&(s.messages=s.messages.map(e=>{if(!e.content||!Array.isArray(e.content))return e;let t=e.content.map(e=>{let t="string"==typeof e.type?e.type:"",n="string"==typeof e.name?e.name:"";return"tool_use"===t&&n&&n.startsWith(y)?{...e,name:n.slice(y.length)}:e});return{...e,content:t}})),s);return function(e,t,n=null){let o=n?.projectId;o||(console.warn(`[OmniRoute] Antigravity/Claude account is missing projectId. Attempting request with empty project — reconnect OAuth to resolve.`),o="");let s={project:o,model:e.includes("/")?e.split("/").pop():e,userAgent:"antigravity",requestId:`agent-${M()}`,requestType:"agent",request:{sessionId:b(),contents:[],generationConfig:{temperature:t.temperature||1,maxOutputTokens:t.max_tokens||4096}}};if(t.messages&&Array.isArray(t.messages))for(let e of t.messages){let t=[];if(Array.isArray(e.content)){for(let n of e.content)if("text"===n.type)t.push({text:n.text});else if("tool_use"===n.type)t.push({functionCall:{id:n.id,name:n.name,args:n.input||{}}});else if("tool_result"===n.type){let e=n.content;Array.isArray(e)&&(e=e.map(e=>"text"===e.type?e.text:JSON.stringify(e)).join("\n")),t.push({functionResponse:{id:n.tool_use_id,name:"unknown",response:{result:S(e)||e}}})}}else"string"==typeof e.content&&t.push({text:e.content});t.length>0&&s.request.contents.push({role:"assistant"===e.role?"model":"user",parts:t})}if(t.tools&&Array.isArray(t.tools)){let e=[];for(let n of t.tools)if(n.name&&n.input_schema){let t=C(n.input_schema);e.push({name:n.name,description:n.description||"",parameters:t})}e.length>0&&(s.request.tools=[{functionDeclarations:e}],s.request.toolConfig={functionCallingConfig:{mode:"VALIDATED"}})}let r=[{text:g.ANTIGRAVITY_DEFAULT_SYSTEM}];if(t.system)if(Array.isArray(t.system))for(let e of t.system)e.text&&r.push({text:e.text});else"string"==typeof t.system&&r.push({text:t.system});return s.request.systemInstruction={role:"user",parts:r},s}(e,r,o)}let s=j(e,t,n);return E(e,s,o,!0)},null),f(t.FORMATS.ANTIGRAVITY,t.FORMATS.OPENAI,function(e,t,n){let o=t.request||t,s={model:e,messages:[],stream:n};if(o.generationConfig){let e=o.generationConfig;if(e.maxOutputTokens&&(s.max_tokens=_({max_tokens:e.maxOutputTokens,tools:o.tools})),void 0!==e.temperature&&(s.temperature=e.temperature),void 0!==e.topP&&(s.top_p=e.topP),void 0!==e.topK&&(s.top_k=e.topK),e.thinkingConfig){let t=e.thinkingConfig.thinkingBudget||0;t>0&&(t<=2048?s.reasoning_effort="low":t<=16384?s.reasoning_effort="medium":s.reasoning_effort="high")}}if(o.systemInstruction){var r;let e="string"==typeof(r=o.systemInstruction)?r:r.parts&&Array.isArray(r.parts)?r.parts.map(e=>e.text||"").join(""):"";e&&s.messages.push({role:"system",content:e})}if(o.contents&&Array.isArray(o.contents))for(let e of o.contents){let t=function(e){let t="model"===e.role?"assistant":"user"===e.role?"user":e.role;if(!e.parts||!Array.isArray(e.parts))return null;let n=[],o=[],s=[],r="";for(let t of e.parts){if(!0===t.thought&&t.text){r+=t.text;continue}if(t.thoughtSignature&&void 0!==t.text){n.push({type:"text",text:t.text});continue}void 0!==t.text&&n.push({type:"text",text:t.text}),t.inlineData&&n.push({type:"image_url",image_url:{url:`data:${t.inlineData.mimeType};base64,${t.inlineData.data}`}}),t.functionCall&&o.push({id:t.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:t.functionCall.name,arguments:JSON.stringify(t.functionCall.args||{})}}),t.functionResponse&&s.push({role:"tool",tool_call_id:t.functionResponse.id||t.functionResponse.name,content:JSON.stringify(t.functionResponse.response?.result||t.functionResponse.response||{})})}if(s.length>0)return s;if(o.length>0){let e={role:"assistant"};return n.length>0&&(e.content=1===n.length&&"text"===n[0].type?n[0].text:n),r&&(e.reasoning_content=r),e.tool_calls=o,e}if(n.length>0||r){let e={role:t};return n.length>0&&(e.content=1===n.length&&"text"===n[0].type?n[0].text:n),r&&(e.reasoning_content=r),e}return null}(e);t&&(Array.isArray(t)?s.messages.push(...t):s.messages.push(t))}if(o.tools&&Array.isArray(o.tools)){for(let e of(s.tools=[],o.tools))if(e.functionDeclarations)for(let t of e.functionDeclarations)s.tools.push({type:"function",function:{name:t.name,description:t.description||"",parameters:function e(t){if(!t||"object"!=typeof t)return t;let n=Array.isArray(t)?[...t]:{...t};if("string"==typeof n.type&&(n.type=n.type.toLowerCase()),n.properties){let t={};for(let[o,s]of Object.entries(n.properties))t[o]=e(s);n.properties=t}return n.items&&(n.items=e(n.items)),n}(t.parameters)||{type:"object",properties:{}}}})}return s},null);let N=["file_search","code_interpreter","web_search_preview"];function F(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function D(e){return Array.isArray(e)?e:[]}function v(e,t=""){return"string"==typeof e?e:t}function w(e){let t=Error(e);return t.statusCode=400,t.errorType="unsupported_feature",t}f(t.FORMATS.OPENAI_RESPONSES,t.FORMATS.OPENAI,function(e,t,n,o){let s=F(t);if(void 0===s.input)return t;let r=D(s.tools);if(r.length>0)for(let e of r){let t=F(e);if(N.includes(v(t.type)))throw w(`Unsupported Responses API feature: ${v(t.type)} tool type is not supported by omniroute`)}if(s.background)throw w("Unsupported Responses API feature: background mode is not supported by omniroute");let i={...s},l=[];i.messages=l,"string"==typeof s.instructions&&s.instructions.length>0&&l.push({role:"system",content:s.instructions});let a=null,u=[];for(let e of D(s.input)){let t=F(e),n=v(t.type)||(t.role?"message":"");if("message"===n){if(a&&(l.push(a),a=null),u.length>0){for(let e of u)l.push(e);u=[]}let e=Array.isArray(t.content)?t.content.map(e=>{let t=F(e);return"input_text"===t.type||"output_text"===t.type?{type:"text",text:v(t.text)}:e}):t.content;l.push({role:v(t.role),content:e});continue}if("function_call"===n){let e=v(t.name).trim();if(!e)continue;a||(a={role:"assistant",content:null,tool_calls:[]});let n=Array.isArray(a.tool_calls)?a.tool_calls:[];n.push({id:v(t.call_id),type:"function",function:{name:e,arguments:t.arguments}}),a.tool_calls=n;continue}if("function_call_output"===n){if(a&&(l.push(a),a=null),u.length>0){for(let e of u)l.push(e);u=[]}l.push({role:"tool",tool_call_id:v(t.call_id),content:"string"==typeof t.output?t.output:JSON.stringify(t.output)});continue}if("reasoning"===n)continue}if(a&&l.push(a),u.length>0)for(let e of u)l.push(e);Array.isArray(s.tools)&&(i.tools=s.tools.map(e=>{let t=F(e);return t.function?e:{type:"function",function:{name:v(t.name),description:v(t.description),parameters:t.parameters,strict:t.strict}}}));let c=new Set;for(let e of l){let t=F(e);if(Array.isArray(t.tool_calls))for(let e of t.tool_calls)e.id&&c.add(String(e.id))}return i.messages=l.filter(e=>{let t=F(e);return"tool"!==t.role||!t.tool_call_id||c.has(String(t.tool_call_id))}),delete i.input,delete i.instructions,delete i.include,delete i.store,delete i.reasoning,i},null),f(t.FORMATS.OPENAI,t.FORMATS.OPENAI_RESPONSES,function(e,t,n,s){let r=F(t),i={model:e,input:[],stream:!0,store:!1},l=i.input,a=!1;for(let e of D(r.messages)){let t=F(e),n=v(t.role);if("system"===n){a||(i.instructions="string"==typeof t.content?t.content:"",a=!0);continue}if("user"===n){let e="string"==typeof t.content?[{type:"input_text",text:t.content}]:Array.isArray(t.content)?t.content.map(e=>{let t=F(e);if("text"===t.type)return{type:"input_text",text:v(t.text)};if("image_url"===t.type){let e=t.image_url;return{type:"input_image",image_url:"string"==typeof e?e:e?.url||""}}return e}):[{type:"input_text",text:""}];l.push({type:"message",role:"user",content:e})}if("assistant"===n){let e=[];if("string"==typeof t.content&&t.content)e.push({type:"output_text",text:t.content});else if(Array.isArray(t.content))for(let n of t.content){let t=F(n);if("text"===t.type&&t.text)e.push({type:"output_text",text:v(t.text)});else{if("thinking"===t.type||"redacted_thinking"===t.type)continue;e.push(n)}}if(e.length>0&&l.push({type:"message",role:"assistant",content:e}),Array.isArray(t.tool_calls))for(let e of t.tool_calls){let t=F(e),n=F(t.function),s=v(n.name).trim();s&&l.push({type:"function_call",call_id:v(t.id).trim()||o(),name:s,arguments:v(n.arguments,"{}")})}}"tool"===n&&l.push({type:"function_call_output",call_id:v(t.tool_call_id),output:t.content})}let u=new Set(l.filter(e=>"function_call"===e.type&&e.call_id).map(e=>e.call_id));return i.input=l.filter(e=>"function_call_output"!==e.type||!e.call_id||u.has(e.call_id)),a||(i.instructions=""),Array.isArray(r.tools)&&(i.tools=r.tools.map(e=>{let t=F(e);if("function"===t.type){let e=F(t.function);return{type:"function",name:v(e.name),description:v(e.description),parameters:e.parameters,strict:e.strict}}return e})),void 0!==r.service_tier&&(i.service_tier=r.service_tier),void 0!==r.temperature&&(i.temperature=r.temperature),void 0!==r.max_tokens&&(i.max_tokens=r.max_tokens),void 0!==r.top_p&&(i.top_p=r.top_p),i},null);var P=e.i(689960);function B(e){return"string"==typeof e?e.split("\n")[0]:""}function q(e){return"string"==typeof e?e:Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join(""):""}function $(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function U(e,t,n){let o=(n||"").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,"");return`<tool_result>
|
|
6
6
|
<tool_name>${$(e||"tool")}</tool_name>
|
|
7
7
|
<tool_call_id>${$(t||"")}</tool_call_id>
|
|
8
8
|
<result>${$(o)}</result>
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
module.exports=[918622,(a,b,c)=>{b.exports=a.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),342602,(a,b,c)=>{"use strict";b.exports=a.r(918622)},187924,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].ReactJsxRuntime},572131,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].React},804730,a=>{a.v({name:"omniroute",version:"2.9.
|
|
1
|
+
module.exports=[918622,(a,b,c)=>{b.exports=a.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),342602,(a,b,c)=>{"use strict";b.exports=a.r(918622)},187924,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].ReactJsxRuntime},572131,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].React},804730,a=>{a.v({name:"omniroute",version:"2.9.4",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},588788,a=>{"use strict";var b=a.i(32886),c=a.i(187924);function d({locale:a,...d}){if(!a)throw Error(void 0);return(0,c.jsx)(b.IntlProvider,{locale:a,...d})}a.s(["default",()=>d])}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=%5Broot-of-the-server%5D__9affb65e._.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
module.exports=[193695,(a,b,c)=>{b.exports=a.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),804730,a=>{a.v({name:"omniroute",version:"2.9.
|
|
1
|
+
module.exports=[193695,(a,b,c)=>{b.exports=a.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),804730,a=>{a.v({name:"omniroute",version:"2.9.4",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},569264,a=>{a.n(a.i(354832))},650645,a=>{a.n(a.i(827572))},923576,a=>{a.n(a.i(104858))},825210,a=>{a.n(a.i(402747))},517537,a=>{a.n(a.i(903363))},13718,a=>{a.n(a.i(685523))},118198,a=>{a.n(a.i(545518))},296736,(a,b,c)=>{"use strict";function d(a){if("function"!=typeof WeakMap)return null;var b=new WeakMap,c=new WeakMap;return(d=function(a){return a?c:b})(a)}c._=function(a,b){if(!b&&a&&a.__esModule)return a;if(null===a||"object"!=typeof a&&"function"!=typeof a)return{default:a};var c=d(b);if(c&&c.has(a))return c.get(a);var e={__proto__:null},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in a)if("default"!==g&&Object.prototype.hasOwnProperty.call(a,g)){var h=f?Object.getOwnPropertyDescriptor(a,g):null;h&&(h.get||h.set)?Object.defineProperty(e,g,h):e[g]=a[g]}return e.default=a,c&&c.set(a,e),e}},500790,(a,b,c)=>{let{createClientModuleProxy:d}=a.r(211857);a.n(d("[project]/node_modules/next/dist/client/app-dir/link.js <module evaluation>"))},784707,(a,b,c)=>{let{createClientModuleProxy:d}=a.r(211857);a.n(d("[project]/node_modules/next/dist/client/app-dir/link.js"))},297647,a=>{"use strict";a.i(500790);var b=a.i(784707);a.n(b)},395936,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d={default:function(){return i},useLinkStatus:function(){return h.useLinkStatus}};for(var e in d)Object.defineProperty(c,e,{enumerable:!0,get:d[e]});let f=a.r(296736),g=a.r(907997),h=f._(a.r(297647));function i(a){let b=a.legacyBehavior,c="string"==typeof a.children||"number"==typeof a.children||"string"==typeof a.children?.type,d=a.children?.type?.$$typeof===Symbol.for("react.client.reference");return!b||c||d||(a.children?.type?.$$typeof===Symbol.for("react.lazy")?console.error("Using a Lazy Component as a direct child of `<Link legacyBehavior>` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's `<a>` tag."):console.error("Using a Server Component as a direct child of `<Link legacyBehavior>` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's `<a>` tag.")),(0,g.jsx)(h.default,{...a})}("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},330878,a=>{"use strict";var b=a.i(800717),c=a.i(118845),d=a.i(40953),e=(0,b.cache)(function(a,b){return function({_cache:a=(0,c.b)(),_formatters:b=(0,c.c)(a),getMessageFallback:e=d.d,messages:f,namespace:g,onError:h=d.b,...i}){return function({messages:a,namespace:b,...c},e){return a=a["!"],b=(0,d.r)(b,"!"),(0,d.a)({...c,messages:a,namespace:b})}({...i,onError:h,cache:a,formatters:b,getMessageFallback:e,messages:{"!":f},namespace:g?`!.${g}`:"!"},0)}({...a,namespace:b})});a.s(["default",()=>e],330878)},442979,a=>{"use strict";var b=a.i(330878),c=a.i(767228),d=a.i(800717)["use".trim()];function e(...[a]){let f=function(a){var b=(0,c.default)();try{return d(b)}catch(b){throw b instanceof TypeError&&b.message.includes("Cannot read properties of null (reading 'use')")?Error(`\`${a}\` is not callable within an async component. Please refer to https://next-intl.dev/docs/environments/server-client-components#async-components`,{cause:b}):b}}("useTranslations");return(0,b.default)(f,a)}a.s(["useTranslations",()=>e],442979)}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=%5Broot-of-the-server%5D__a6942102._.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
<!DOCTYPE html><!--
|
|
2
|
-
@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding-right:23px;font-size:24px;font-weight:500;vertical-align:top">500</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:28px">Internal Server Error.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/e22b90cf374c3818.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[339756,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"default\"]\n3:I[837457,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"default\"]\n4:I[897367,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n7:I[897367,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"ViewportBoundary\"]\n9:I[897367,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"MetadataBoundary\"]\nb:I[168027,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"default\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"b\":\"
|
|
1
|
+
<!DOCTYPE html><!--z314c1HLTWx1ZCjOHV3gC--><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/e22b90cf374c3818.js"/><script src="/_next/static/chunks/3dd6d23a48e5d078.js" async=""></script><script src="/_next/static/chunks/726579f2940c2a2f.js" async=""></script><script src="/_next/static/chunks/b133d1854532ff8c.js" async=""></script><script src="/_next/static/chunks/c88fcc5f8b21ff92.js" async=""></script><script src="/_next/static/chunks/turbopack-858efc89e955ca00.js" async=""></script><script src="/_next/static/chunks/d96012bcfc98706a.js" async=""></script><script src="/_next/static/chunks/16ea27c3b926bc31.js" async=""></script><meta name="next-size-adjust" content=""/><title>500: Internal Server Error.</title><script src="/_next/static/chunks/a6dad97d9634a72d.js" noModule=""></script></head><body><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div style="line-height:48px"><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}
|
|
2
|
+
@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding-right:23px;font-size:24px;font-weight:500;vertical-align:top">500</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:28px">Internal Server Error.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/e22b90cf374c3818.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[339756,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"default\"]\n3:I[837457,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"default\"]\n4:I[897367,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n7:I[897367,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"ViewportBoundary\"]\n9:I[897367,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"MetadataBoundary\"]\nb:I[168027,[\"/_next/static/chunks/d96012bcfc98706a.js\",\"/_next/static/chunks/16ea27c3b926bc31.js\"],\"default\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"b\":\"z314c1HLTWx1ZCjOHV3gC\",\"c\":[\"\",\"_global-error\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]}],[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"html\",null,{\"id\":\"__next_error__\",\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"title\",null,{\"children\":\"500: Internal Server Error.\"}]}],[\"$\",\"body\",null,{\"children\":[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"style\":{\"lineHeight\":\"48px\"},\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}\\n@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"paddingRight\":23,\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\"},\"children\":\"500\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"28px\"},\"children\":\"Internal Server Error.\"}]}]]}]}]}]]}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/d96012bcfc98706a.js\",\"async\":true,\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-1\",{\"src\":\"/_next/static/chunks/16ea27c3b926bc31.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,false]},null,false,false],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$L7\",null,{\"children\":\"$L8\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$L9\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$La\"}]}]}],[\"$\",\"meta\",null,{\"name\":\"next-size-adjust\",\"content\":\"\"}]]}],false]],\"m\":\"$undefined\",\"G\":[\"$b\",\"$undefined\"],\"S\":true}\n"])</script><script>self.__next_f.push([1,"8:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\na:[]\n"])</script></body></html>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
self.__RSC_SERVER_MANIFEST="{\n \"node\": {},\n \"edge\": {},\n \"encryptionKey\": \"
|
|
1
|
+
self.__RSC_SERVER_MANIFEST="{\n \"node\": {},\n \"edge\": {},\n \"encryptionKey\": \"Ke8iAyrZSThzFyuZKHJpI2soSiE2FIoRsSzwi54XB1o=\"\n}"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,804730,t=>{t.v({name:"omniroute",version:"2.9.
|
|
1
|
+
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,804730,t=>{t.v({name:"omniroute",version:"2.9.4",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},175696,t=>{"use strict";var e=t.i(861745),s=t.i(843476);function n({locale:t,...n}){if(!t)throw Error(void 0);return(0,s.jsx)(e.IntlProvider,{locale:t,...n})}t.s(["default",()=>n])}]);
|
package/app/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,27 @@
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [2.9.4] — 2026-03-21
|
|
8
|
+
|
|
9
|
+
> Sprint: Bug fixes — preserve Codex prompt cache key, fix tagContent JSON escaping, sync expired token status to DB.
|
|
10
|
+
|
|
11
|
+
### 🐛 Bug Fixes
|
|
12
|
+
|
|
13
|
+
- **fix(translator)**: Preserve `prompt_cache_key` in Responses API → Chat Completions translation (#517)
|
|
14
|
+
— The field is a cache-affinity signal used by Codex; stripping it was preventing prompt cache hits.
|
|
15
|
+
Fixed in `openai-responses.ts` and `responsesApiHelper.ts`.
|
|
16
|
+
|
|
17
|
+
- **fix(combo)**: Escape `\n` in `tagContent` so injected JSON string is valid (#515)
|
|
18
|
+
— Template literal newlines (U+000A) are not allowed unescaped inside JSON string values.
|
|
19
|
+
Replaced with `\\n` literal sequences in `open-sse/services/combo.ts`.
|
|
20
|
+
|
|
21
|
+
- **fix(usage)**: Sync expired token status back to DB on live auth failure (#491)
|
|
22
|
+
— When the Limits & Quotas live check returns 401/403, the connection `testStatus` is now updated
|
|
23
|
+
to `"expired"` in the database so the Providers page reflects the same degraded state.
|
|
24
|
+
Fixed in `src/app/api/usage/[connectionId]/route.ts`.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
7
28
|
## [2.9.3] — 2026-03-21
|
|
8
29
|
|
|
9
30
|
> Sprint: Add 5 new free AI providers — LongCat, Pollinations, Cloudflare AI, Scaleway, AI/ML API.
|
package/app/docs/openapi.yaml
CHANGED
|
@@ -472,7 +472,7 @@ export async function handleComboChat({
|
|
|
472
472
|
// SDKs close the connection on finish_reason, so anything sent after
|
|
473
473
|
// that marker is silently dropped.
|
|
474
474
|
if (!res.body) return res;
|
|
475
|
-
const tagContent =
|
|
475
|
+
const tagContent = `\\n<omniModel>${modelStr}</omniModel>\\n`;
|
|
476
476
|
const encoder = new TextEncoder();
|
|
477
477
|
const decoder = new TextDecoder();
|
|
478
478
|
let tagInjected = false;
|
|
@@ -93,10 +93,11 @@ export function convertResponsesApiFormat(body) {
|
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
// Cleanup Responses API specific fields
|
|
96
|
+
// Note: prompt_cache_key is intentionally preserved — it is used by Codex and other
|
|
97
|
+
// providers as a cache-affinity signal. Stripping it breaks prompt caching (#517).
|
|
96
98
|
delete result.input;
|
|
97
99
|
delete result.instructions;
|
|
98
100
|
delete result.include;
|
|
99
|
-
delete result.prompt_cache_key;
|
|
100
101
|
delete result.store;
|
|
101
102
|
delete result.reasoning;
|
|
102
103
|
|
|
@@ -227,10 +227,11 @@ export function openaiResponsesToOpenAIRequest(
|
|
|
227
227
|
});
|
|
228
228
|
|
|
229
229
|
// Cleanup Responses API specific fields
|
|
230
|
+
// Note: prompt_cache_key is intentionally preserved — it is used by Codex and other
|
|
231
|
+
// providers as a cache-affinity signal. Stripping it breaks prompt caching (#517).
|
|
230
232
|
delete result.input;
|
|
231
233
|
delete result.instructions;
|
|
232
234
|
delete result.include;
|
|
233
|
-
delete result.prompt_cache_key;
|
|
234
235
|
delete result.store;
|
|
235
236
|
delete result.reasoning;
|
|
236
237
|
|
package/app/package-lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omniroute",
|
|
3
|
-
"version": "2.9.
|
|
3
|
+
"version": "2.9.4",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "omniroute",
|
|
9
|
-
"version": "2.9.
|
|
9
|
+
"version": "2.9.4",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"workspaces": [
|
package/app/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omniroute",
|
|
3
|
-
"version": "2.9.
|
|
3
|
+
"version": "2.9.4",
|
|
4
4
|
"description": "Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
getProviderConnectionById,
|
|
3
|
+
updateProviderConnection,
|
|
4
|
+
resolveProxyForConnection,
|
|
5
|
+
} from "@/lib/localDb";
|
|
2
6
|
import { getMachineId } from "@/shared/utils/machine";
|
|
3
7
|
import { getUsageForProvider } from "@omniroute/open-sse/services/usage.ts";
|
|
4
8
|
import { getExecutor } from "@omniroute/open-sse/executors/index.ts";
|
|
@@ -109,7 +113,10 @@ async function refreshAndUpdateCredentials(connection: any) {
|
|
|
109
113
|
/**
|
|
110
114
|
* GET /api/usage/[connectionId] - Get usage data for a specific connection
|
|
111
115
|
*/
|
|
112
|
-
export async function GET(
|
|
116
|
+
export async function GET(
|
|
117
|
+
request: Request,
|
|
118
|
+
{ params }: { params: Promise<{ connectionId: string }> }
|
|
119
|
+
) {
|
|
113
120
|
try {
|
|
114
121
|
const { connectionId } = await params;
|
|
115
122
|
|
|
@@ -155,7 +162,34 @@ export async function GET(request: Request, { params }: { params: Promise<{ conn
|
|
|
155
162
|
|
|
156
163
|
// Populate quota cache for quota-aware account selection
|
|
157
164
|
if (isRecord(usage?.quotas)) {
|
|
158
|
-
setQuotaCache(
|
|
165
|
+
setQuotaCache(
|
|
166
|
+
connectionId,
|
|
167
|
+
connection.provider as string,
|
|
168
|
+
usage.quotas as Record<string, unknown>
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// (#491) If the live usage check returned an auth error, sync the expired status
|
|
173
|
+
// back to the DB so the Providers page reflects the same degraded state as
|
|
174
|
+
// Limits & Quotas (which performs the live check).
|
|
175
|
+
const errorMessage = typeof usage?.message === "string" ? usage.message.toLowerCase() : "";
|
|
176
|
+
const isAuthError =
|
|
177
|
+
errorMessage.includes("token expired") ||
|
|
178
|
+
errorMessage.includes("access denied") ||
|
|
179
|
+
errorMessage.includes("re-authenticate") ||
|
|
180
|
+
errorMessage.includes("unauthorized");
|
|
181
|
+
|
|
182
|
+
if (isAuthError && connection.testStatus !== "expired") {
|
|
183
|
+
try {
|
|
184
|
+
await updateProviderConnection(connection.id as string, {
|
|
185
|
+
testStatus: "expired",
|
|
186
|
+
lastErrorType: "token_expired",
|
|
187
|
+
lastErrorAt: new Date().toISOString(),
|
|
188
|
+
});
|
|
189
|
+
} catch (dbErr) {
|
|
190
|
+
// Non-critical: log but don't block the response
|
|
191
|
+
console.error("[Usage API] Failed to sync expired status to DB:", dbErr);
|
|
192
|
+
}
|
|
159
193
|
}
|
|
160
194
|
|
|
161
195
|
return Response.json(usage);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omniroute",
|
|
3
|
-
"version": "2.9.
|
|
3
|
+
"version": "2.9.4",
|
|
4
4
|
"description": "Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
File without changes
|
|
File without changes
|
|
File without changes
|