trouteai 1.1.2 → 1.1.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/.build/next/BUILD_ID +1 -1
- package/.build/next/build-manifest.json +3 -3
- package/.build/next/fallback-build-manifest.json +3 -3
- package/.build/next/prerender-manifest.json +3 -3
- package/.build/next/server/app/(dashboard)/dashboard/activity/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/analytics/combo-health/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/analytics/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/analytics/utilization/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/api-manager/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/audit/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/auto-combo/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/cache/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/combos/[id]/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/combos/live/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/combos/playground/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/costs/budget/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/costs/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/costs/pricing/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/costs/quota-share/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/health/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/limits/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/logs/activity/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/logs/console/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/logs/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/logs/proxy/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/logs/timeline/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/media-providers/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/more/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/onboarding/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/provider-stats/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/quota/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/runtime/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/advanced/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/ai/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/appearance/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/cache/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/feature-flags/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/general/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/resilience/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/routing/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/security/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/settings/sidebar/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/system/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/system/proxy/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/(dashboard)/home/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/400/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/401/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/403/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/408/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/429/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/500/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/502/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/503/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/_global-error.html +1 -1
- package/.build/next/server/app/_global-error.rsc +1 -1
- package/.build/next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.build/next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.build/next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.build/next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/auth/callback/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/callback/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/connect/codex/[token]/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/forbidden/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/forgot-password/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/maintenance/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/offline/page_client-reference-manifest.js +1 -1
- package/.build/next/server/app/page_client-reference-manifest.js +1 -1
- package/.build/next/server/chunks/_02r_3f8xhg8a_._.js +4 -4
- package/.build/next/server/chunks/_07becj_u5_s86._.js +1 -1
- package/.build/next/server/chunks/_07ymisy5dfwkw._.js +19 -19
- package/.build/next/server/chunks/_085cu6zzvapwm._.js +1 -1
- package/.build/next/server/chunks/_0bjni2b0bk48x._.js +1 -1
- package/.build/next/server/chunks/_0ccwywk_11oi5._.js +4 -4
- package/.build/next/server/chunks/_0d3kqbu97v85m._.js +1 -1
- package/.build/next/server/chunks/_0lyzza9-jf0-p._.js +19 -19
- package/.build/next/server/chunks/_0miuo2l-inne9._.js +1 -1
- package/.build/next/server/chunks/_0ox6qf339bblb._.js +1 -1
- package/.build/next/server/chunks/_11g3_85xlffm_._.js +4 -4
- package/.build/next/server/chunks/_11hbt4c_vm6y3._.js +1 -1
- package/.build/next/server/chunks/_11hiw0cib9wo0._.js +1 -1
- package/.build/next/server/chunks/_16ueh-qq73qi8._.js +1 -1
- package/.build/next/server/chunks/_1a403tptlxihn._.js +1 -1
- package/.build/next/server/chunks/_1eqaw8kjn2rij._.js +19 -19
- package/.build/next/server/chunks/_1grc87rsv-ywz._.js +19 -19
- package/.build/next/server/chunks/_1po50cfv-3hj5._.js +1 -1
- package/.build/next/server/chunks/_1qcfk-jj0sgeo._.js +1 -1
- package/.build/next/server/chunks/_1r5622jp0txkb._.js +1 -1
- package/.build/next/server/chunks/_1sv8j92e_8eg7._.js +19 -19
- package/.build/next/server/chunks/_1wdvkgutsnz5f._.js +1 -1
- package/.build/next/server/chunks/_1weiljmnpxk97._.js +1 -1
- package/.build/next/server/chunks/_1y4_eli3wg893._.js +1 -1
- package/.build/next/server/chunks/_1z2m2jbpenszh._.js +1 -1
- package/.build/next/server/chunks/src_0jsr5vm5qt_kk._.js +1 -1
- package/.build/next/server/chunks/src_shared_constants_appConfig_ts_1rww0w9vzhopb._.js +1 -1
- package/.build/next/server/chunks/ssr/src_shared_constants_appConfig_ts_06ksyl9fe46j1._.js +1 -1
- package/.build/next/server/middleware-build-manifest.js +3 -3
- package/.build/next/server/pages/500.html +1 -1
- package/.build/next/server/preview-props.json +3 -3
- package/.build/next/server/server-reference-manifest.js +1 -1
- package/.build/next/server/server-reference-manifest.json +1 -1
- package/.build/next/static/chunks/{1h4_48cukszby.js → 3vmjmyyjjzrt7.js} +1 -1
- package/open-sse/executors/kiro.ts +122 -9
- package/open-sse/executors/kiroThinking.ts +26 -4
- package/open-sse/handlers/responseTranslator.ts +7 -2
- package/open-sse/services/combo/runtimeUnits.ts +11 -1
- package/open-sse/services/combo/validateQuality.ts +93 -2
- package/open-sse/services/combo.ts +28 -3
- package/open-sse/services/errorClassifier.ts +3 -1
- package/open-sse/translator/response/claude-to-openai.ts +2 -0
- package/open-sse/translator/response/openai-to-claude.ts +16 -1
- package/open-sse/utils/diagnostics.ts +4 -0
- package/open-sse/utils/reasoningPlaceholder.ts +3 -0
- package/open-sse/utils/stream.ts +16 -2
- package/open-sse/utils/streamReadiness.ts +1 -0
- package/package.json +1 -1
- package/src/app/api/v1/messages/route.ts +7 -1
- package/src/sse/handlers/chat.ts +14 -1
- package/src/sse/services/auth.ts +18 -1
- /package/.build/next/static/{umANHWG1zU3NUNPS9SOZN → tMQffjZE6QpGQdmaJrSAi}/_buildManifest.js +0 -0
- /package/.build/next/static/{umANHWG1zU3NUNPS9SOZN → tMQffjZE6QpGQdmaJrSAi}/_clientMiddlewareManifest.js +0 -0
- /package/.build/next/static/{umANHWG1zU3NUNPS9SOZN → tMQffjZE6QpGQdmaJrSAi}/_ssgManifest.js +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
module.exports=[487347,e=>{"use strict";var t=e.i(715372);t.B;let n=(0,t.w)("sdk-cli"),r=t.J,o=t.g,i=["claude-opus-5","claude-opus-5-5","claude-fable-5-1","claude-fable-5-2","claude-haiku-5-5"];e.s(["Q",0,r,"e",0,o,"r",0,n,"u",0,function(e){let t=String(e||"").trim().toLowerCase().replace(/-\d{8}$/,"");return i.some(e=>t===e||t.startsWith(`${e}-`))}])},80513,e=>{"use strict";e.s(["f",0,"EpwGCkYIChgCKkCzVUuRrg7CcglSUWEef4rH6o35g9UYS8ZPe0/VomQTBsFx6sttYNj5l8GqgW6ejuHyYqpFToxIbZl0bw17l5dJEgzCnqDO0Z8fRlMrNgsaDLS1cnCjC53KBqE0CCIwAADQdo1eO+7qPAmo8J4WR3JPmr92S97kmvr5K1iPMiOpkZNj8mEXW8uzBoOJs/9ZKoMFiqHJ3UObwaJDqFOW70E9oCwDoc6jesaWVAEdN5vWfKMpIkjFJjECdjIdkxyJNJ8Ib8yXVal3qwE7uThoPRqSZDdHB5mmwPEjWE/90cSYCbtX2YsJki1265CabBb8/QEkODXg4kgRrL+c8e8rRXz/dr1RswvaPuzEdGKHRNi9UooNUeOK4/ebx1KkP9YZttyohN9GWqlts36kOoW0Cfie/ABDgF9g534BPth/sstxDM6d79QlRmh6NxizyTF74DXJI34u0M4tTRchqE5pAq85SgdJaa+dix1yJPMji8m6nZkwJbscJb9rdc2MKyKWjz8QL2+rTSSuZ2F1k1qSsW0xNcI7qLcI12Vncfn/VqY6YOIZy/saZBR0ezXvN6g+UYbuIdyVg7AyIFZt3nbrO7/kmOEb2VKzygwklHGEIJHfFgMpH3JSrAzbZIowVHOF7VaJ+KXRFDCFin7hHTOiOsdg+1ij1mML9Z/x/9CP4b7OUcaQm1llDZPSHc6rZMNL3DdB+fW5YfmNgKU35S+7AMtA10nVILzDAk1UV4T2K9Do09JlI6rjOs9UuULlIN2Z0eE8YTlANR6uQcw7lMcdfqYE8tke4rDKc2dDiaS5vVe45VewICNpdXGN11yw8QqH7p27CR1HtN30e0tHXOR3bIwWk/Yb6O5fTaKG6Ri8e5ZCPvdD9HqepVi188nM0iTjJqL58F3ni04ECIhcbyaQWnuTes1Kw4CMwiZDLQkk8Hgz7HkUOf1btQTF/0nhD7ry0n0hAEg2PaDM3V6TjOjf4hEldRmeqERcQF1PfgKb6ZM12rlIIfUqKACczWJSzTV158+47HX36o0cgux6nFlv/DE+sEiRVxgB"])},325840,e=>{"use strict";e.s(["f",0,function(e,t){let n=e?.alternateFormats;if(!n?.length)return null;let r=t?.targetFormat;return"string"==typeof r&&r?n.find(e=>e.format===r)??null:null}])},312009,e=>{"use strict";let t=new Set(["agentrouter"]);e.s(["f",0,function(e){return"string"==typeof e&&t.has(e)}])},526707,e=>{"use strict";var t=e.i(666680),n=e.i(748823),r=e.i(858303),o=e.i(487347),i=e.i(878947),s=e.i(55245);let a=["claude-code-20250219","interleaved-thinking-2025-05-14","effort-2025-11-24"];function l(e={}){let t=[...a];return!0===e.redactThinking&&t.push("redact-thinking-2026-02-12"),t.join(",")}function u(e,t={}){if("disabled"===e.type)return e;let n=t.normalizedBody?._trouteaiCopilotReasoningSummary==="summarized",r=!0===t.summarizeThinking;return!n&&!r||Object.prototype.hasOwnProperty.call(e,"display")&&void 0!==e.display&&null!==e.display&&String(e.display).trim().length>0&&!n?e:{...e,display:"summarized"}}l(),e.i(786790),e.i(269903);var c=e.i(312009);let f=/^data:([^;]+);base64,(.+)$/;function p(e){if("image_url"===e.type)return y("string"==typeof e.image_url?e.image_url:g(e.image_url)?.url);if("image"===e.type&&!g(e.source)&&"string"==typeof e.image)return y(e.image);if("file"===e.type){let t=g(e.file),n=d(t?.file_data)||d(t?.data);if(!n)return null;let r=d(t?.filename),o=n.match(f);if(o){let e=o[1],t={type:"base64",media_type:e,data:o[2]};return"application/pdf"===e?{type:"document",source:t,...r?{title:r}:{}}:e.startsWith("image/")?{type:"image",source:t}:null}if(/^https?:\/\//i.test(n))return{type:"document",source:{type:"url",url:n},...r?{title:r}:{}}}return null}function y(e){let t=d(e);if(!t)return null;let n=t.match(f);return n?{type:"image",source:{type:"base64",media_type:n[1],data:n[2]}}:{type:"image",source:{type:"url",url:t}}}function g(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function d(e){return"string"!=typeof e?null:e.trim()||null}e.i(952685),e.i(967);let m="anthropic-compatible-cc-",h=r.J,_=[{type:"text",text:"You are a Claude agent, built on Anthropic's Claude Agent SDK."}],A=(0,n.R)(process.env);function k(e){return"string"==typeof e&&(0,i.supportsXHighEffort)("claude",e)}function b(e){let t=String(e||"").trim().replace(/\/$/,"");return t?t.split("?")[0].replace(/\/messages$/i,""):""}function x(e){let t=String(e||"").trim().replace(/\/$/,"");return t?t.split("?")[0].replace(/\/(?:v\d+\/)?messages$/i,""):""}function v(e,t){let n=String(e||"").replace(/\/$/,""),r=String(t||"").startsWith("/")?String(t):`/${String(t||"")}`,o=n.match(/(\/v\d+)$/i);return o&&r.toLowerCase().startsWith(`${o[1].toLowerCase()}/`)?`${n}${r.slice(o[1].length)}`:`${n}${r}`}function w({sourceBody:e,normalizedBody:n,claudeBody:r,model:o,stream:i=!1,cwd:s=process.cwd(),sessionId:a,preserveCacheControl:l=!1,preserveClaudeMessages:c=!1,summarizeThinking:f=!1}){var y,d,m,h,A;let k,b,x,v,j=n||{},R=r?c?(k=Array.isArray((y=r).messages)?y.messages:[],b={system:[...T(y.system),...I(k)],messages:k.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t}),tools:E(y.tools),thinking:M(L(y.thinking))||null},(x=M(L(y.metadata)))&&(b.metadata=x),(v=M(L(y.output_config)))&&(b.output_config=v),b):C(r,l):null,D=Array.isArray(j.messages)?j.messages:[],z=!R&&e?function(e,t){let n=Array.isArray(e.messages)?e.messages:[],r=n.some(e=>{let t=String(e?.role||"").toLowerCase();return"system"===t||"developer"===t}),o="string"==typeof e.system||Array.isArray(e.system)&&e.system.length>0;if(!o&&!r)return null;let i=n.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t});return C({...e,...o?{}:{system:I(n)},messages:i},t)}(e,l):null,B=R||z,W=B?c&&R?function(e,t){let n=Array.isArray(e)?e.map(e=>L(e)).filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t}):[];if(!t)for(let e of n)Array.isArray(e.content)&&U(e.content);return n}(B.messages,l):function(e,t){let n=Array.isArray(e)?e.map(e=>(function(e,t){let n=String(e?.role||"").toLowerCase(),r="user"===n?"user":"assistant"===n?"assistant":null;if(!r)return null;let o=O(e?.content).map(e=>{if(t)return e;let{cache_control:n,...r}=e;return r});return 0===o.length?null:{role:r,content:o}})(e,t)).filter(e=>!!e&&e.content.length>0):[],r=[],o=!1;for(let e of n){let t=e.content.some(e=>"tool_use"===e.type),n=e.content.some(e=>"tool_result"===e.type),i=r[r.length-1],s=t||n||o||i?.content?.some(e=>"tool_use"===e.type)||i?.content?.some(e=>"tool_result"===e.type);i&&i.role===e.role&&!s?i.content.push(...e.content):r.push({role:e.role,content:[...e.content]}),o="assistant"===e.role&&t}for(;r.length>0;){let e=r[r.length-1],t=e.content.some(e=>"tool_use"===e.type);if("assistant"!==e.role||t)break;r.pop()}if(!t)for(let e of r)U(e.content);if(0===r.length){let e=n.flatMap(e=>e.content).map(e=>$(e)).filter(Boolean).join("\n").trim();if(e)return[{role:"user",content:[{type:"text",text:e}]}]}return r}(B.messages,l):function(e){let t=e.map(e=>(function(e){let t=String(e?.role||"").toLowerCase(),n="user"===t?"user":"assistant"===t||"model"===t?"assistant":null;if(!n)return null;let r=$(e?.content),o=[...r?[{type:"text",text:r}]:[],..."user"===n?function(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){var n;let e=g((n=r,"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))));if(!e)continue;let o=p(e);if(o){t.push(o);continue}("image"===e.type||"document"===e.type)&&g(e.source)&&t.push(e)}return t}(e?.content):[]];return 0===o.length?null:{role:n,content:o}})(e)).filter(e=>!!e&&e.content.length>0),n=[];for(let e of t){let t=n[n.length-1];if(t&&t.role===e.role){t.content.push(...e.content);continue}n.push({role:e.role,content:[...e.content]})}for(;n.length>0&&"assistant"===n[n.length-1].role;)n.pop();if(0===n.length){let e=t.flatMap(e=>e.content).map(e=>N(e.text)).filter(Boolean).join("\n").trim();if(e)return[{role:"user",content:[{type:"text",text:e}]}]}return n}(D),K=function({messages:e,systemBlocks:t,preserveCacheControl:n}){var r;let o=(Array.isArray(t)&&t.length>0?t.map(e=>({...e})):I(e)).map(e=>{let t={...e};return n||delete t.cache_control,t});return(r=o,0===_.length||!(r.length<_.length)&&r.some((e,t)=>_.every((e,n)=>{let o=r[t+n];return!!o&&Object.entries(e).every(([e,t])=>o[e]===t)})))?o:[..._.map(e=>({...e})),...o]}({messages:c?[]:D,systemBlocks:B?.system,preserveCacheControl:l}),q=a||(0,t.randomUUID)(),P=S(e,n,o),X=function(e,t){for(let n of[e?.max_tokens,e?.max_completion_tokens,e?.max_output_tokens,t?.max_tokens,t?.max_completion_tokens,t?.max_output_tokens]){let e=Number(n);if(Number.isFinite(e)&&e>0)return Math.floor(e)}return 64e3}(e,n),F=R?.tools?(d=R.tools,m=l,Array.isArray(d)?d.map(e=>{let t={...e};return m||delete t.cache_control,t}):[]):(h=n,A=e,(Array.isArray(h?.tools)?h?.tools:Array.isArray(A?.tools)?A?.tools:[]).map(e=>(function(e){let t=M(e);if(!t)return null;let n="function"===t.type&&M(t.function)||t,r=N(n.name);if(!r)return null;let o=M(n.parameters)||M(n.input_schema)||{type:"object",properties:{},required:[]},i="object"!==o.type||M(o.properties)?o:{...o,properties:{}},s={name:r,description:N(n.description)||"",input_schema:i};return"boolean"==typeof n.defer_loading&&(s.defer_loading=n.defer_loading),s})(e)).filter(e=>!!e).map(e=>({...e}))),J=F.length>0?function(e){if(!e)return null;if("string"==typeof e)return"required"===e?{type:"any"}:null;let t=M(e);if(!t)return null;if("tool"===t.type){let e=N(t.name);return e?{type:"tool",name:e}:null}if("function"===t.type){let e=N(M(t.function)?.name)||N(t.name);return e?{type:"tool",name:e}:null}return"required"===t.type||"any"===t.type?{type:"any"}:null}(n?.tool_choice??e?.tool_choice):void 0,V=function({claudeBody:e,sourceBody:n,normalizedBody:r,cwd:o,sessionId:i}){let s=M(L(e?.metadata))||M(L(n?.metadata))||M(L(r?.metadata))||{};return N(s.user_id)||(s.user_id=JSON.stringify({device_id:(0,t.createHash)("sha256").update(String(o||"")).digest("hex"),account_uuid:"",session_id:i})),s}({claudeBody:r,sourceBody:e,normalizedBody:n,cwd:s,sessionId:q}),H=function({claudeBody:e,sourceBody:t,normalizedBody:n,summarizeThinking:r=!1}){let o=M(L(e?.thinking))||M(L(t?.thinking))||M(L(n?.thinking));return o?u(o,{normalizedBody:n,summarizeThinking:r}):u({type:"adaptive"},{normalizedBody:n,summarizeThinking:r})}({claudeBody:R??r,sourceBody:e,normalizedBody:n,summarizeThinking:f}),Z=function({claudeBody:e,sourceBody:t,normalizedBody:n,model:r,effort:o}){return{...M(L(e?.output_config))||M(L(t?.output_config))||M(L(n?.output_config))||{},effort:S(t,n,r)||o}}({claudeBody:r,sourceBody:e,normalizedBody:n,model:o,effort:P});return{model:o,messages:W,system:K,tools:F,metadata:V,max_tokens:X,thinking:H,output_config:Z,...J?{tool_choice:J}:{},...i?{stream:!0}:{}}}function S(e,t,n){let r=(D(e,["output_config","effort"])||D(e,["reasoning","effort"])||N(e?.reasoning_effort)||D(t,["output_config","effort"])||D(t,["reasoning","effort"])||N(t?.reasoning_effort)||"").toLowerCase();return r?"low"===r?"low":"medium"===r?"medium":"high"===r?"high":"none"===r||"disabled"===r?"low":"xhigh"===r?k(n)?"xhigh":"high":"max"===r?(0,i.supportsClaudeMaxEffort)(n)?"max":"high":k(n)?"xhigh":"high":k(n)?"xhigh":"high"}function C(e,t){var n;let r=(0,s.L)({system:T(e.system),messages:Array.isArray(n=e.messages)?n.map(e=>{var t;let n,r=M(e);return r?{...r,content:(n=O(t=r.content)).length>0?n:t}:null}).filter(e=>!!e):[],tools:E(e.tools),thinking:M(e.thinking)||null},m,!0);return M(r)}function T(e){if("string"==typeof e){let t=e.trim();return t?[{type:"text",text:t}]:[]}return Array.isArray(e)?e.map(e=>j(e)).filter(e=>!!e):[]}function E(e){return Array.isArray(e)?e.map(e=>M(L(e))).filter(e=>!!e):[]}function O(e){if("string"==typeof e){let t=e.trim();return t?[{type:"text",text:t}]:[]}if(!Array.isArray(e)){let t=j(e);return t?[t]:[]}return e.map(e=>j(e)).filter(e=>!!e)}function j(e){let t=M(L(e));if(!t)return null;if("text"===t.type||"string"!=typeof t.type&&"string"==typeof t.text){let e=N(t.text);return e?{...t,type:"text",text:e}:null}return p(t)??t}function I(e){return Array.isArray(e)?e.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"===t||"developer"===t}).map(e=>$(e?.content)).filter(Boolean).map(e=>({type:"text",text:e})):[]}function U(e){for(let t of e)delete t.cache_control}function L(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}function $(e){return"string"==typeof e?e.trim():Array.isArray(e)?e.map(e=>e&&"object"==typeof e&&("text"===e.type&&"string"==typeof e.text||"string"==typeof e.text)?e.text.trim():"").filter(Boolean).join("\n").trim():e&&"object"==typeof e&&"string"==typeof e.text?e.text.trim():""}function R(e,t){if(!e)return null;if("function"==typeof e.get)return e.get(t);let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r??null;return null}function N(e){return"string"!=typeof e?null:e.trim()||null}function M(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function D(e,t){let n=e;for(let e of t){if(!n||"object"!=typeof n||Array.isArray(n)||"__proto__"===e||"constructor"===e||"prototype"===e||!Object.prototype.hasOwnProperty.call(n,e))return null;n=Reflect.get(n,e)}return N(n)}e.s(["d",0,"/v1/messages?beta=true","q",0,"/models","K",0,"context-1m-2025-08-07","A",0,function(e,t){let n=Object.keys(e).find(e=>"anthropic-beta"===e.toLowerCase());if(!n){e["anthropic-beta"]=t;return}let r=String(e[n]||"").split(",").map(e=>e.trim()).filter(Boolean);r.includes(t)||(e[n]=[...r,t].join(","))},"o",0,function(e,t=!1,n,r={}){return{"Content-Type":"application/json",Accept:t?"text/event-stream":"application/json",Authorization:`Bearer ${e}`,"anthropic-version":h,"anthropic-beta":l({redactThinking:!0===r.redactThinking}),"anthropic-dangerous-direct-browser-access":"true","x-app":"cli","User-Agent":o.r,"X-Stainless-Retry-Count":"0","X-Stainless-Timeout":String(A),"X-Stainless-Lang":"js","X-Stainless-Package-Version":o.Q,"X-Stainless-OS":"MacOS","X-Stainless-Arch":"arm64","X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":o.e,"accept-encoding":"gzip, deflate, br, zstd",...n?{"X-Claude-Code-Session-Id":n}:{}}},"s",0,w,"g",0,function(e="claude-sonnet-4-6"){return w({sourceBody:{max_tokens:1},normalizedBody:{messages:[{role:"user",content:"ok"}],max_tokens:1},model:e,stream:!0,sessionId:(0,t.randomUUID)(),cwd:process.cwd(),now:new Date})},"P",0,function(e){return"string"==typeof e&&e.startsWith(m)||(0,c.f)(e)},"H",0,function(e,t){return v(b(e),t)},"Q",0,function(e,t){return v(x(e),t)},"Z",0,function(e){let n=R(e,"x-claude-code-session-id")||R(e,"x-session-id")||R(e,"x_session_id")||R(e,"x-trouteai-session")||null;return n&&n.trim()||(0,t.randomUUID)()},"r",0,b,"e",0,x],526707)},786790,e=>{"use strict";let t={subagents:"SubDispatch",session_status:"CheckStatus",bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep",task:"Task",webfetch:"WebFetch",websearch:"WebSearch",todowrite:"TodoWrite",todoread:"TodoRead",question:"Question",skill:"Skill",multiedit:"MultiEdit",notebook:"Notebook",lsp:"Lsp",apply_patch:"ApplyPatch"},n={};for(let[e,r]of Object.entries(t))n[r]=e;function r(e){let t=e._toolNameMap instanceof Map?e._toolNameMap:new Map;return Object.defineProperty(e,"_toolNameMap",{value:t,enumerable:!1,configurable:!0,writable:!0}),t}function o(e,t,n){r(e).set(t,n)}function i(e){let t=new Set;if(!Array.isArray(e))return t;for(let n of e)n&&c(n.type)&&"string"==typeof n.name&&t.add(n.name);return t}let s=new Set(Object.values(t)),a={read_file:"Read",write_file:"Write",search_files:"Grep",grep_search:"Grep",list_directory:"Glob",run_command:"Bash",terminal:"Bash",todo:"TodoWrite",todo_write:"TodoWrite",todo_read:"TodoRead",patch:"Edit",multi_edit:"MultiEdit"},l=/^[a-z][a-z0-9_]*_\d{8}$/,u=new Set(["web_search","web_search_preview"]);function c(e){return"string"==typeof e&&0!==e.length&&(l.test(e)||u.has(e))}e.s(["X",0,n,"i",0,function(e,n){if("true"===process.env.CLAUDE_DISABLE_TOOL_NAME_CLOAK)return new Map;let o=e=>!(!e||s.has(e)||e.startsWith("mcp__"))&&(/[a-z]/.test(e.charAt(0))||e.includes("_")||e.includes("-"))&&!(n?.skip&&n.skip(e)),l=e.tools,u=i(l),f=new Set;if(Array.isArray(l))for(let e of l)e&&"string"==typeof e.name&&f.add(e.name);let p=e._toolNameMap instanceof Map?e._toolNameMap:null;if(p)for(let e of p.keys())f.add(e);let y=p,g=new Map,d=n=>{let o=g.get(n);if(o)return o;let i=t[n]??a[n]??(n.split(/[_\s-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")||n),s=i,l=2;for(;s!==n&&f.has(s);)s=`${i}${l++}`;return f.delete(n),f.add(s),g.set(n,s),y||(y=r(e)),y.set(s,n),s};Array.isArray(l)&&(e.tools=l.map(e=>e&&c(e.type)?e:e&&"string"==typeof e.name&&o(e.name)?{...e,name:d(e.name)}:e));let m=e.messages;Array.isArray(m)&&(e.messages=m.map(e=>{let t=e?.content;if(!Array.isArray(t))return e;let n=!1,r=t.map(e=>e?.type==="tool_use"&&"string"==typeof e.name&&!u.has(e.name)&&o(e.name)?(n=!0,{...e,name:d(e.name)}):e);return n?{...e,content:r}:e}));let h=e.tool_choice;return h?.type==="tool"&&"string"==typeof h.name&&!u.has(h.name)&&o(h.name)&&(e.tool_choice={...h,name:d(h.name)}),y??new Map},"j",0,function(e){let r=!1,s=!1,a=i(e.tools),l=e.tools;if(Array.isArray(l))for(let i of l){if(!i||c(i.type))continue;let a=String(i.name||"");if(t[a]){let n=t[a];i.name=n,o(e,n,a),r=!0}else n[a]&&(s=!0)}let u=e.messages;if(Array.isArray(u))for(let i of u){let l=i.content;if(Array.isArray(l)){for(let i of l)if("tool_use"===i.type&&"string"==typeof i.name){if(a.has(i.name))continue;let l=t[i.name];if(l){let t=i.name;i.name=l,o(e,l,t),r=!0}else n[i.name]&&(s=!0)}}}let f=e.tool_choice;if(f?.type==="tool"&&"string"==typeof f.name&&!a.has(f.name)){let i=t[f.name];if(i){let t=f.name;f.name=i,o(e,i,t),r=!0}else n[f.name]&&(s=!0)}return r&&!s}],786790)},85713,e=>{"use strict";var t=e.i(889771),n=e.i(313613),r=e.i(325840),o=e.i(526707),i=e.i(421892),s=e.i(628740),a=e.i(312009);let l="https://api.openai.com/v1",u="https://api.anthropic.com/v1";function c(e){return"string"==typeof e&&e.startsWith("openai-compatible-")}function f(e){return"string"==typeof e&&e.startsWith("anthropic-compatible-")}function p(e){return"string"==typeof e&&e.startsWith("anthropic-compatible-cc-")||(0,a.f)(e)}function y(e,t=null){if(!c(e))return"chat";let n=t&&"object"==typeof t&&"string"==typeof t.apiType?t.apiType:null;return"responses"===n||"chat"===n||"embeddings"===n||"audio-transcriptions"===n||"audio-speech"===n||"images-generations"===n?n:e.includes("responses")?"responses":e.includes("embeddings")?"embeddings":e.includes("audio-transcriptions")?"audio-transcriptions":e.includes("audio-speech")?"audio-speech":e.includes("images-generations")?"images-generations":"chat"}function g(e,t=""){let n=String(t||"");return/\/responses(?=\/|$)/i.test(n)||/^responses(?=\/|$)/i.test(n)?"openai-responses":/\/messages(?=\/|$)/i.test(n)||/^messages(?=\/|$)/i.test(n)?"claude":/\/antigravity(?=\/|:|$)/i.test(n)||/^antigravity(?=\/|:|$)/i.test(n)?"antigravity":/\/(?:chat\/completions|completions)(?=\/|$)/i.test(n)||/^(?:chat\/completions|completions)(?=\/|$)/i.test(n)?e&&"object"==typeof e&&!Array.isArray(e)&&void 0!==e.input&&void 0===e.messages?"openai-responses":"openai":d(e)}function d(e){let t=Object.prototype.hasOwnProperty.call(e,"input")&&void 0!==e.input,n=void 0!==e.max_output_tokens||void 0!==e.previous_response_id||void 0!==e.reasoning;if(t||n)return"openai-responses";if(e.request?.contents&&"antigravity"===e.userAgent)return"antigravity";if(e.contents&&Array.isArray(e.contents))return"gemini";if(e.stream_options||e.response_format||void 0!==e.logprobs||void 0!==e.top_logprobs||void 0!==e.n||void 0!==e.presence_penalty||void 0!==e.frequency_penalty||e.logit_bias||e.user)return"openai";if(e.messages&&Array.isArray(e.messages)){let t=e.messages[0];if(t?.content&&Array.isArray(t.content)){let n=t.content[0];if(n?.type==="text"&&!e.model?.includes("/")){if(e.system||e.anthropic_version)return"claude";let n=t.content.some(e=>"image"===e.type&&e.source?.type==="base64"),r=t.content.some(e=>"image_url"===e.type&&e.image_url?.url);if(n)return"claude";if(r)return"openai";if(t.content.some(e=>"tool_use"===e.type||"tool_result"===e.type))return"claude"}}if(void 0!==e.system||e.anthropic_version||e.max_tokens&&!e.stream_options&&!e.response_format)return"claude"}return"openai"}function m(e,n=null){if(c(e)){let r=y(e,n);return{...t.L.openai,format:"responses"===r?"openai-responses":"openai",baseUrl:l}}return f(e)?{...t.L.anthropic,format:"claude",baseUrl:u}:t.L[e]||t.L.openai}e.s(["W",0,function(e,t,r=!0,l=null){let u=m(e),c=(0,n.k)(e),y={"Content-Type":"application/json",...u.headers};if(p(e)){let n=t.apiKey||t.accessToken||"",s=(0,i.U)(t?.providerSpecificData),l=(0,o.o)(n,r,t?.providerSpecificData?.ccSessionId,{redactThinking:!0===s.redactThinking});if((0,a.f)(e)){delete l.Authorization;let e=c?.authHeader||"bearer";"x-api-key"===e?n&&(l["x-api-key"]=n):"key"===e?n&&(l.Authorization=`Key ${n}`):l.Authorization=`Bearer ${n}`}return l}if(f(e))t.apiKey?y["x-api-key"]=t.apiKey:t.accessToken&&(y.Authorization=`Bearer ${t.accessToken}`),y["anthropic-version"]||(y["anthropic-version"]="2023-06-01");else if("github"===e){let e=t.copilotToken||t.accessToken;y.Authorization=`Bearer ${e}`,y["x-request-id"]=crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),r||(y.Accept="application/json")}else if("cline"===e)Object.assign(y,(0,s.k)(t.apiKey||t.accessToken));else if(c){let e=c.authHeader||"bearer";if("x-api-key"===e){let e=t.apiKey||t.accessToken;e&&(y["x-api-key"]=e)}else if("key"===e){let e=t.apiKey||t.accessToken;e&&(y.Authorization=`Key ${e}`)}else"x-goog-api-key"===e?t.apiKey?y["x-goog-api-key"]=t.apiKey:t.accessToken&&(y.Authorization=`Bearer ${t.accessToken}`):y.Authorization=`Bearer ${t.apiKey||t.accessToken}`}else y.Authorization=`Bearer ${t.apiKey||t.accessToken}`;return r&&(y.Accept="text/event-stream"),y},"o",0,function(e,t,r=!0,i={}){if((0,a.f)(e)){let t=(0,n.k)(e),r=m(e),s=i?.baseUrl||t?.baseUrl||r.baseUrl;return(0,o.Q)(s,o.d)}if(c(e)){var s;let t,n,r=i?.providerSpecificData||null,o=y(e,r);return s=i?.baseUrl||("string"==typeof r?.baseUrl?r.baseUrl:null)||l,t=s.replace(/\/$/,""),n="/chat/completions","responses"===o?n="/responses":"embeddings"===o?n="/embeddings":"audio-transcriptions"===o?n="/audio/transcriptions":"audio-speech"===o?n="/audio/speech":"images-generations"===o&&(n="/images/generations"),`${t}${n}`}if(f(e)){let t,n=i?.baseUrl||u;return p(e)?(0,o.Q)(n,o.d):(t=n.replace(/\/$/,""),`${t}/messages`)}let g=(0,n.k)(e),d=m(e);if(g){if(g.baseUrls){let e=i?.baseUrlIndex||0,n=g.baseUrls[e]||g.baseUrls[0];return g.urlBuilder?g.urlBuilder(n,t,r):n}if(g.urlBuilder){let e=g.baseUrl||d.baseUrl;if(e)return g.urlBuilder(e,t,r)}if(g.urlSuffix)return`${g.baseUrl}${g.urlSuffix}`}return d.baseUrl},"$",0,d,"i",0,g,"R",0,function(e,t){return g(e,new URL(t).pathname)},"h",0,y,"a",0,function(e,t=null){if(c(e))return"responses"===y(e,t)?"openai-responses":"openai";if(f(e))return"claude";let o=(0,n.k)(e);if(o){let e=(0,r.f)(o,t);return e?e.format:o.format||"openai"}return m(e).format||"openai"},"F",0,function(e){return!!(e.reasoning_effort||e.thinking?.type==="enabled")},"l",0,p,"G",0,function(e){return!function(e){let t=e.messages||e.contents;if(!t?.length)return!0;let n=t[t.length-1];return n?.role==="user"}(e)&&delete e.thinking,e}])},163686,e=>{"use strict";let t,n;var r=e.i(306860),o=e.i(139908);let i=new Set(["deepseek","opencode-go","siliconflow","nebius","deepinfra","sambanova","fireworks","together","kimi-coding","kimi-coding-apikey","xiaomi-mimo"]),s=[/deepseek-r1/i,/deepseek-reasoner/i,/deepseek-chat/i,/deepseek[-/]v4[-.](flash|pro)(-free)?/i,/zen\/deepseek-v4/i,/kimi[-/]k\d/i,/qwq/i,/qwen.*think/i,/glm.*think/i,/^mimo[-.]?v\d/i],a=/deepseek[-/]v4[-.](flash|pro)/i,l=new Map,u=0,c=0,f=0;function p(){let e=Date.now();for(let[t,n]of l)e>=n.expiresAt&&l.delete(t)}function y(e,t,n,o){if(!e||!o)return;o.length>1e4&&(o=o.slice(0,1e4));let i=Date.now();l.size>=200&&function(){let e=null,t=1/0;for(let[n,r]of l)r.createdAt<t&&(t=r.createdAt,e=n);e&&l.delete(e)}(),l.set(e,{reasoning:o,provider:t,model:n,expiresAt:i+72e5,createdAt:i});try{(0,r.R)(e,t,n,o,72e5)}catch{}}function g(){p();try{return(0,r.F)()}catch{return 0}}try{let e=g();e>0&&console.log(`[ReasoningCache] boot cleanup removed ${e} expired entries`)}catch(e){console.error("[ReasoningCache] boot cleanup failed:",e)}(0,o.P)("reasoning-cache-cleanup",()=>{try{let e=g();e>0&&console.log(`[ReasoningCache] periodic cleanup removed ${e} expired entries`)}catch(e){console.error("[ReasoningCache] periodic cleanup failed:",e)}},Number.isFinite(n=(t=process.env.TROUTEAI_REASONING_CACHE_CLEANUP_INTERVAL_MS)?Number(t):0/0)&&n>=6e4?n:18e5),e.s(["W",0,function(e,t,n,r){if(!e||"assistant"!==e.role)return 0;let o="string"==typeof e.reasoning_content&&e.reasoning_content.length>0?e.reasoning_content:"string"==typeof e.reasoning&&e.reasoning.length>0?e.reasoning:"";if(!o)return 0;let i=Array.isArray(e.tool_calls)?e.tool_calls.map(e=>"string"==typeof e.id?e.id:"").filter(e=>e.length>0):[];if(0===i.length){let e=r?.requestId?.trim(),i=r?.messageIndex;return e&&"number"==typeof i&&Number.isInteger(i)?(y(`request:${e}:message:${i}`,t,n,o),1):0}for(let e of i)e&&y(e,t,n,o);return i.length},"k",0,function(e){if(e)for(let[t,n]of l)n.provider===e&&l.delete(t);else l.clear();u=0,c=0,f=0;try{return(0,r.Y)(e)}catch{return 0}},"C",0,function(e){if(!e)return 0;let t=l.delete(e),n=0;try{n=(0,r.J)(e)}catch{}return n+(t&&0===n?1:0)},"N",0,function(e={}){try{return(0,r.a)(e)}catch{return[]}},"b",0,function(){p();let e={totalEntries:0,totalChars:0,byProvider:{},byModel:{},oldestEntry:null,newestEntry:null};try{e=(0,r.s)()}catch{}let t=u+c,n=t>0?(f/t*100).toFixed(1):"0.0";return{memoryEntries:l.size,dbEntries:e.totalEntries,totalEntries:e.totalEntries,totalChars:e.totalChars,hits:u,misses:c,replays:f,replayRate:`${n}%`,byProvider:e.byProvider,byModel:e.byModel,oldestEntry:e.oldestEntry,newestEntry:e.newestEntry}},"c",0,function(e){if(!e)return c++,null;let t=l.get(e);if(t){if(Date.now()<t.expiresAt)return u++,t.reasoning;l.delete(e)}let n=null;try{n=(0,r.t)(e)}catch{}if(n){u++;let t=n.reasoning;return t.length>1e4&&(t=t.slice(0,1e4)),l.set(e,{reasoning:t,provider:n.provider,model:n.model,expiresAt:Date.now()+72e5,createdAt:Date.now()}),t}return c++,null},"X",0,function(){f++},"f",0,function(e){let t=e.provider.trim().toLowerCase(),n=e.model.trim(),r="string"==typeof e.interleavedField?e.interleavedField.trim().toLowerCase():"";return"reasoning_content"===r||!("reasoning_details"===r||/deepseek-reasoner/i.test(n)||/deepseek-r1/i.test(n))&&(!!(!0===e.thinkingEnabled&&a.test(e.model))||!1!==e.allowLegacyFallback&&(!!i.has(t)||s.some(e=>e.test(n))))}])},55245,e=>{"use strict";var t=e.i(80513),n=e.i(163686),r=e.i(878947),o=e.i(286410);let i=new Set(["minimax","minimax-cn"]);function s(e){if(!Array.isArray(e)||0===e.length)return e;let t=[],n=new Set,r=e=>{for(let t of e)t?.type==="tool_use"&&"string"==typeof t.id&&n.add(t.id)};for(let o of e){if("assistant"!==o.role||!Array.isArray(o.content)){t.push(o);continue}let e=o.content.filter(e=>e?.type==="tool_result");if(0===e.length){t.push(o),r(o.content);continue}let i=e.filter(e=>"string"==typeof e?.tool_use_id&&n.has(e.tool_use_id)),s=o.content.filter(e=>e?.type!=="tool_result");if(i.length>0){let e=t[t.length-1];e&&"user"===e.role&&Array.isArray(e.content)?t[t.length-1]={...e,content:[...e.content,...i]}:t.push({role:"user",content:i})}s.length>0&&(t.push({...o,content:s}),r(s))}return t}function a(e){return Array.isArray(e?.content)?e.content:"string"==typeof e?.content&&e.content.trim()?(e.content=[{type:"text",text:e.content}],e.content):[]}function l(e,t){let n=a(e);if(0===n.length)return!1;let r=n.length-1;return n[r].cache_control=void 0!==t?{type:"ephemeral",ttl:t}:{type:"ephemeral"},!0}function u(e){if(!e||"object"!=typeof e)return!1;let n="redacted_thinking"===e.type?e.data:"thinking"===e.type?e.signature:void 0;return("thinking"===e.type||"redacted_thinking"===e.type)&&("string"!=typeof n||0===n.length||n===t.f)}e.s(["F",0,function(e,t){if(!t.thinking&&!t.reasoning_effort)return;let n=String(t.reasoning_effort??t.thinking?.effort??"on").toLowerCase(),r=t.thinking?.type==="disabled"||["off","none"].includes(n);if(e.thinking={type:r?"disabled":"enabled"},!r&&!["on","auto"].includes(n)){let t=e.output_config&&"object"==typeof e.output_config?e.output_config:{};e.output_config={...t,effort:n}}},"L",0,function(e,t=null,c=!1,f=null,p={}){t&&i.has(t)&&delete e.output_config,c&&!0===p.fallbackToHeuristicWhenNoMarkers&&!function(e){if(Array.isArray(e.system)){for(let t of e.system)if(t&&"object"==typeof t&&t.cache_control)return!0}if(Array.isArray(e.messages)){for(let t of e.messages)if(Array.isArray(t?.content)){for(let e of t.content)if(e&&"object"==typeof e&&e.cache_control)return!0}}if(Array.isArray(e.tools)){for(let t of e.tools)if(t&&"object"==typeof t&&t.cache_control)return!0}return!1}(e)&&(c=!1);let y="claude"===t||"anthropic"===t||t?.startsWith?.("anthropic-compatible-"),g="kimi-coding"===t||"kimi-coding-apikey"===t,d=!!t&&!!f&&"claude"===(0,r.getModelTargetFormat)(t,f),m=!g&&(y||d),h=e.system;if(h&&Array.isArray(h)&&!c&&(e.system=h.map((e,t)=>{let{cache_control:n,...r}=e;return t===h.length-1&&y?{...r,cache_control:{type:"ephemeral",ttl:"1h"}}:r})),e.messages&&Array.isArray(e.messages)){let r=e.messages.length,i=[];for(let t=0;t<r;t++){let n=e.messages[t];if(Array.isArray(n.content)&&!c)for(let e of n.content)delete e.cache_control;(t===r-1&&"assistant"===n.role||"string"==typeof n.content&&n.content.trim()||Array.isArray(n.content)&&n.content.some(e=>"text"===e.type&&e.text?.trim()||"tool_use"===e.type||"tool_result"===e.type||"image"===e.type||"document"===e.type))&&i.push(n)}for(let e of i)Array.isArray(e.content)&&(e.content=e.content.filter(e=>"tool_use"!==e.type||e.name&&e.name?.trim()),e.content=e.content.filter(e=>"tool_result"!==e.type||e.tool_use_id));e.tools&&Array.isArray(e.tools)&&"claude"!==t&&(e.tools=e.tools.filter(e=>!e.type||"function"===e.type).map(e=>{if(e.function)return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};let{type:t,...n}=e;return n})),e.tools&&Array.isArray(e.tools)&&(e.tools=e.tools.filter(e=>e.name&&e.name?.trim())),e.messages=i=function(e){if(e.length<=1)return e;for(let t of e)if("assistant"===t.role&&Array.isArray(t.content)&&t.content.some(e=>"tool_use"===e.type)){let e=[],n=!1;for(let r of t.content)"tool_use"===r.type?(n=!0,e.push(r)):"thinking"===r.type||"redacted_thinking"===r.type?e.push(r):n||e.push(r);t.content=e}let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.role===n.role){let t=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];e.content=[...t.filter(e=>"tool_result"===e.type),...r.filter(e=>"tool_result"===e.type),...t.filter(e=>"tool_result"!==e.type),...r.filter(e=>"tool_result"!==e.type)]}else{let e=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];t.push({role:n.role,content:[...e]})}}return t}(i=s(i));let u=i[i.length-1],f=u?.role==="user",p=e.thinking?.type==="enabled"&&f;if(!c&&y){let e=i.reduce((e,t,n)=>(t?.role==="user"&&e.push(n),e),[]),t=e.length>=2?e[e.length-2]:-1;t>=0&&l(i[t])}let d=-1;for(let e=i.length-1;e>=0;e--)if(i[e]?.role==="assistant"){d=e;break}let h=!1;for(let e=i.length-1;e>=0;e--){let t=i[e],r=a(t);if("assistant"===t.role&&r.length>0){!c&&y&&!h&&l(t)&&(h=!0);let i=e===d?r.filter(e=>"thinking"===e.type||"redacted_thinking"===e.type):[],s=i.length>0;if(i.every(e=>"redacted_thinking"===e.type?"string"==typeof e.data&&e.data.length>0:"string"==typeof e.signature&&e.signature.length>0),m)continue;let a=!1,u=!1,f=[];if(!m)for(let e of r)"tool_use"===e.type&&"string"==typeof e.id&&f.push(e.id);let _=0;for(let e of r){if("thinking"===e.type||"redacted_thinking"===e.type){if(g)"redacted_thinking"===e.type&&(e.type="thinking",e.thinking="string"==typeof e.thinking?e.thinking:""),delete e.data,delete e.signature;else{let t="string"==typeof e.thinking&&e.thinking.length>0?e.thinking:"";if(t&&s)e.type="thinking";else{if(!t){let e=f[_];if(e){let r=(0,n.c)(e);r&&(t=r,(0,n.X)())}}e.type="thinking",e.thinking=t||o.P}delete e.data,delete e.signature}u=!0,_++}"tool_use"===e.type&&(a=!0)}if(p&&!u&&a)if(g)r.unshift({type:"thinking",thinking:""});else{let e="",t=f[0];if(t){let r=(0,n.c)(t);r&&(e=r,(0,n.X)())}r.unshift({type:"thinking",thinking:e||o.P})}}}}if(m&&function(e){let t=e.messages;if(!Array.isArray(t))return;for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||"assistant"!==n.role||!Array.isArray(n.content)||!n.content.some(u))continue;let r=n.content.filter(e=>!u(e));r.length>0?n.content=r:t.splice(e,1)}if(e.thinking?.type!=="enabled"||t[t.length-1]?.role!=="user")return;let n=-1;for(let e=t.length-1;e>=0;e--)if(t[e]?.role==="assistant"){n=e;break}let r=Array.isArray(t[n]?.content)?t[n].content:[],o=r.some(e=>e?.type==="tool_use"),i=r.some(e=>e?.type==="thinking"||e?.type==="redacted_thinking");if(!o||i)return;delete e.thinking;let s=e.context_management;if(s&&Array.isArray(s.edits)){let t=s.edits.filter(e=>!String(e?.type||"").startsWith("clear_thinking"));t.length>0?e.context_management={...s,edits:t}:delete e.context_management}}(e),e.tools&&Array.isArray(e.tools)&&!c&&(e.tools=e.tools.map(e=>{let{cache_control:t,...n}=e;return n}),y)){for(let t=e.tools.length-1;t>=0;t--)if(!e.tools[t].defer_loading){e.tools[t].cache_control={type:"ephemeral",ttl:"1h"};break}}return e},"O",0,s])},286410,e=>{"use strict";let t="(prior reasoning summary unavailable)";e.s(["P",0,t,"p",0,function(e){return"string"==typeof e&&e.trim()===t},"L",0,function(e){let n=e.replaceAll(t,"");return""===n.trim()?"":n}])},628740,e=>{"use strict";var t=e.i(666680);let n=process.env.TROUTEAI_CLINE_CLIENT_VERSION?.trim()||"3.8.49";function r(e){if("string"!=typeof e)return;let t=e.trim();if(!(!t||t.length>256||/[\r\n\0]/.test(t)))return t}function o(e,t){let n=Object.keys(e??{}).find(e=>e.toLowerCase()===t);return n?r(e?.[n]):void 0}function i(e,s={}){let a=r(s.taskId)??o(e,"x-task-id")??(0,t.randomUUID)(),l=r(s.clientVersion)??n;for(let[t,o]of Object.entries({"HTTP-Referer":"https://cline.bot","X-Title":"Cline","User-Agent":`Cline/${l}`,"X-IS-MULTIROOT":!0===s.isMultiRoot?"true":"false","X-CLIENT-TYPE":r(s.clientType)??"trouteai","X-CLIENT-VERSION":l,"X-PLATFORM":r(s.platform)??process.platform??"unknown","X-PLATFORM-VERSION":r(s.platformVersion)??process.version??"unknown","X-CORE-VERSION":r(s.coreVersion)??n,"X-Task-ID":a})){for(let n of Object.keys(e))n!==t&&n.toLowerCase()===t.toLowerCase()&&delete e[n];e[t]=o}return e}function s(e,t={},n={}){let r,o=(r=function(e){if("string"!=typeof e)return"";let t=e.trim();return t?t.startsWith("workos:")?t:`workos:${t}`:""}(e))?`Bearer ${r}`:"",a=i({...t},n);return o&&(a.Authorization=o),a}e.s(["b",0,function(e,n,r,a,l){let u={taskId:o(a,"x-task-id")??(0,t.randomUUID)()};return Object.assign(e,l?function(e,t,n={}){if(e?.accessToken)return s(e.accessToken,{},n);let r=i({},n),o=t||e?.apiKey;return o&&(r.Authorization=`Bearer ${o}`),r}(n,r,u):s(r||n?.accessToken,{},u)),e},"w",0,i,"k",0,s])}];
|
|
1
|
+
module.exports=[487347,e=>{"use strict";var t=e.i(715372);t.B;let n=(0,t.w)("sdk-cli"),r=t.J,o=t.g,i=["claude-opus-5","claude-opus-5-5","claude-fable-5-1","claude-fable-5-2","claude-haiku-5-5"];e.s(["Q",0,r,"e",0,o,"r",0,n,"u",0,function(e){let t=String(e||"").trim().toLowerCase().replace(/-\d{8}$/,"");return i.some(e=>t===e||t.startsWith(`${e}-`))}])},80513,e=>{"use strict";e.s(["f",0,"EpwGCkYIChgCKkCzVUuRrg7CcglSUWEef4rH6o35g9UYS8ZPe0/VomQTBsFx6sttYNj5l8GqgW6ejuHyYqpFToxIbZl0bw17l5dJEgzCnqDO0Z8fRlMrNgsaDLS1cnCjC53KBqE0CCIwAADQdo1eO+7qPAmo8J4WR3JPmr92S97kmvr5K1iPMiOpkZNj8mEXW8uzBoOJs/9ZKoMFiqHJ3UObwaJDqFOW70E9oCwDoc6jesaWVAEdN5vWfKMpIkjFJjECdjIdkxyJNJ8Ib8yXVal3qwE7uThoPRqSZDdHB5mmwPEjWE/90cSYCbtX2YsJki1265CabBb8/QEkODXg4kgRrL+c8e8rRXz/dr1RswvaPuzEdGKHRNi9UooNUeOK4/ebx1KkP9YZttyohN9GWqlts36kOoW0Cfie/ABDgF9g534BPth/sstxDM6d79QlRmh6NxizyTF74DXJI34u0M4tTRchqE5pAq85SgdJaa+dix1yJPMji8m6nZkwJbscJb9rdc2MKyKWjz8QL2+rTSSuZ2F1k1qSsW0xNcI7qLcI12Vncfn/VqY6YOIZy/saZBR0ezXvN6g+UYbuIdyVg7AyIFZt3nbrO7/kmOEb2VKzygwklHGEIJHfFgMpH3JSrAzbZIowVHOF7VaJ+KXRFDCFin7hHTOiOsdg+1ij1mML9Z/x/9CP4b7OUcaQm1llDZPSHc6rZMNL3DdB+fW5YfmNgKU35S+7AMtA10nVILzDAk1UV4T2K9Do09JlI6rjOs9UuULlIN2Z0eE8YTlANR6uQcw7lMcdfqYE8tke4rDKc2dDiaS5vVe45VewICNpdXGN11yw8QqH7p27CR1HtN30e0tHXOR3bIwWk/Yb6O5fTaKG6Ri8e5ZCPvdD9HqepVi188nM0iTjJqL58F3ni04ECIhcbyaQWnuTes1Kw4CMwiZDLQkk8Hgz7HkUOf1btQTF/0nhD7ry0n0hAEg2PaDM3V6TjOjf4hEldRmeqERcQF1PfgKb6ZM12rlIIfUqKACczWJSzTV158+47HX36o0cgux6nFlv/DE+sEiRVxgB"])},325840,e=>{"use strict";e.s(["f",0,function(e,t){let n=e?.alternateFormats;if(!n?.length)return null;let r=t?.targetFormat;return"string"==typeof r&&r?n.find(e=>e.format===r)??null:null}])},312009,e=>{"use strict";let t=new Set(["agentrouter"]);e.s(["f",0,function(e){return"string"==typeof e&&t.has(e)}])},526707,e=>{"use strict";var t=e.i(666680),n=e.i(748823),r=e.i(858303),o=e.i(487347),i=e.i(878947),s=e.i(55245);let a=["claude-code-20250219","interleaved-thinking-2025-05-14","effort-2025-11-24"];function l(e={}){let t=[...a];return!0===e.redactThinking&&t.push("redact-thinking-2026-02-12"),t.join(",")}function u(e,t={}){if("disabled"===e.type)return e;let n=t.normalizedBody?._trouteaiCopilotReasoningSummary==="summarized",r=!0===t.summarizeThinking;return!n&&!r||Object.prototype.hasOwnProperty.call(e,"display")&&void 0!==e.display&&null!==e.display&&String(e.display).trim().length>0&&!n?e:{...e,display:"summarized"}}l(),e.i(786790),e.i(269903);var c=e.i(312009);let f=/^data:([^;]+);base64,(.+)$/;function p(e){if("image_url"===e.type)return y("string"==typeof e.image_url?e.image_url:g(e.image_url)?.url);if("image"===e.type&&!g(e.source)&&"string"==typeof e.image)return y(e.image);if("file"===e.type){let t=g(e.file),n=d(t?.file_data)||d(t?.data);if(!n)return null;let r=d(t?.filename),o=n.match(f);if(o){let e=o[1],t={type:"base64",media_type:e,data:o[2]};return"application/pdf"===e?{type:"document",source:t,...r?{title:r}:{}}:e.startsWith("image/")?{type:"image",source:t}:null}if(/^https?:\/\//i.test(n))return{type:"document",source:{type:"url",url:n},...r?{title:r}:{}}}return null}function y(e){let t=d(e);if(!t)return null;let n=t.match(f);return n?{type:"image",source:{type:"base64",media_type:n[1],data:n[2]}}:{type:"image",source:{type:"url",url:t}}}function g(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function d(e){return"string"!=typeof e?null:e.trim()||null}e.i(952685),e.i(967);let m="anthropic-compatible-cc-",h=r.J,_=[{type:"text",text:"You are a Claude agent, built on Anthropic's Claude Agent SDK."}],A=(0,n.R)(process.env);function k(e){return"string"==typeof e&&(0,i.supportsXHighEffort)("claude",e)}function b(e){let t=String(e||"").trim().replace(/\/$/,"");return t?t.split("?")[0].replace(/\/messages$/i,""):""}function x(e){let t=String(e||"").trim().replace(/\/$/,"");return t?t.split("?")[0].replace(/\/(?:v\d+\/)?messages$/i,""):""}function v(e,t){let n=String(e||"").replace(/\/$/,""),r=String(t||"").startsWith("/")?String(t):`/${String(t||"")}`,o=n.match(/(\/v\d+)$/i);return o&&r.toLowerCase().startsWith(`${o[1].toLowerCase()}/`)?`${n}${r.slice(o[1].length)}`:`${n}${r}`}function w({sourceBody:e,normalizedBody:n,claudeBody:r,model:o,stream:i=!1,cwd:s=process.cwd(),sessionId:a,preserveCacheControl:l=!1,preserveClaudeMessages:c=!1,summarizeThinking:f=!1}){var y,d,m,h,A;let k,b,x,v,j=n||{},R=r?c?(k=Array.isArray((y=r).messages)?y.messages:[],b={system:[...T(y.system),...I(k)],messages:k.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t}),tools:E(y.tools),thinking:M(L(y.thinking))||null},(x=M(L(y.metadata)))&&(b.metadata=x),(v=M(L(y.output_config)))&&(b.output_config=v),b):C(r,l):null,D=Array.isArray(j.messages)?j.messages:[],z=!R&&e?function(e,t){let n=Array.isArray(e.messages)?e.messages:[],r=n.some(e=>{let t=String(e?.role||"").toLowerCase();return"system"===t||"developer"===t}),o="string"==typeof e.system||Array.isArray(e.system)&&e.system.length>0;if(!o&&!r)return null;let i=n.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t});return C({...e,...o?{}:{system:I(n)},messages:i},t)}(e,l):null,B=R||z,W=B?c&&R?function(e,t){let n=Array.isArray(e)?e.map(e=>L(e)).filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t}):[];if(!t)for(let e of n)Array.isArray(e.content)&&U(e.content);return n}(B.messages,l):function(e,t){let n=Array.isArray(e)?e.map(e=>(function(e,t){let n=String(e?.role||"").toLowerCase(),r="user"===n?"user":"assistant"===n?"assistant":null;if(!r)return null;let o=O(e?.content).map(e=>{if(t)return e;let{cache_control:n,...r}=e;return r});return 0===o.length?null:{role:r,content:o}})(e,t)).filter(e=>!!e&&e.content.length>0):[],r=[],o=!1;for(let e of n){let t=e.content.some(e=>"tool_use"===e.type),n=e.content.some(e=>"tool_result"===e.type),i=r[r.length-1],s=t||n||o||i?.content?.some(e=>"tool_use"===e.type)||i?.content?.some(e=>"tool_result"===e.type);i&&i.role===e.role&&!s?i.content.push(...e.content):r.push({role:e.role,content:[...e.content]}),o="assistant"===e.role&&t}for(;r.length>0;){let e=r[r.length-1],t=e.content.some(e=>"tool_use"===e.type);if("assistant"!==e.role||t)break;r.pop()}if(!t)for(let e of r)U(e.content);if(0===r.length){let e=n.flatMap(e=>e.content).map(e=>$(e)).filter(Boolean).join("\n").trim();if(e)return[{role:"user",content:[{type:"text",text:e}]}]}return r}(B.messages,l):function(e){let t=e.map(e=>(function(e){let t=String(e?.role||"").toLowerCase(),n="user"===t?"user":"assistant"===t||"model"===t?"assistant":null;if(!n)return null;let r=$(e?.content),o=[...r?[{type:"text",text:r}]:[],..."user"===n?function(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){var n;let e=g((n=r,"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))));if(!e)continue;let o=p(e);if(o){t.push(o);continue}("image"===e.type||"document"===e.type)&&g(e.source)&&t.push(e)}return t}(e?.content):[]];return 0===o.length?null:{role:n,content:o}})(e)).filter(e=>!!e&&e.content.length>0),n=[];for(let e of t){let t=n[n.length-1];if(t&&t.role===e.role){t.content.push(...e.content);continue}n.push({role:e.role,content:[...e.content]})}for(;n.length>0&&"assistant"===n[n.length-1].role;)n.pop();if(0===n.length){let e=t.flatMap(e=>e.content).map(e=>N(e.text)).filter(Boolean).join("\n").trim();if(e)return[{role:"user",content:[{type:"text",text:e}]}]}return n}(D),K=function({messages:e,systemBlocks:t,preserveCacheControl:n}){var r;let o=(Array.isArray(t)&&t.length>0?t.map(e=>({...e})):I(e)).map(e=>{let t={...e};return n||delete t.cache_control,t});return(r=o,0===_.length||!(r.length<_.length)&&r.some((e,t)=>_.every((e,n)=>{let o=r[t+n];return!!o&&Object.entries(e).every(([e,t])=>o[e]===t)})))?o:[..._.map(e=>({...e})),...o]}({messages:c?[]:D,systemBlocks:B?.system,preserveCacheControl:l}),q=a||(0,t.randomUUID)(),P=S(e,n,o),X=function(e,t){for(let n of[e?.max_tokens,e?.max_completion_tokens,e?.max_output_tokens,t?.max_tokens,t?.max_completion_tokens,t?.max_output_tokens]){let e=Number(n);if(Number.isFinite(e)&&e>0)return Math.floor(e)}return 64e3}(e,n),F=R?.tools?(d=R.tools,m=l,Array.isArray(d)?d.map(e=>{let t={...e};return m||delete t.cache_control,t}):[]):(h=n,A=e,(Array.isArray(h?.tools)?h?.tools:Array.isArray(A?.tools)?A?.tools:[]).map(e=>(function(e){let t=M(e);if(!t)return null;let n="function"===t.type&&M(t.function)||t,r=N(n.name);if(!r)return null;let o=M(n.parameters)||M(n.input_schema)||{type:"object",properties:{},required:[]},i="object"!==o.type||M(o.properties)?o:{...o,properties:{}},s={name:r,description:N(n.description)||"",input_schema:i};return"boolean"==typeof n.defer_loading&&(s.defer_loading=n.defer_loading),s})(e)).filter(e=>!!e).map(e=>({...e}))),J=F.length>0?function(e){if(!e)return null;if("string"==typeof e)return"required"===e?{type:"any"}:null;let t=M(e);if(!t)return null;if("tool"===t.type){let e=N(t.name);return e?{type:"tool",name:e}:null}if("function"===t.type){let e=N(M(t.function)?.name)||N(t.name);return e?{type:"tool",name:e}:null}return"required"===t.type||"any"===t.type?{type:"any"}:null}(n?.tool_choice??e?.tool_choice):void 0,V=function({claudeBody:e,sourceBody:n,normalizedBody:r,cwd:o,sessionId:i}){let s=M(L(e?.metadata))||M(L(n?.metadata))||M(L(r?.metadata))||{};return N(s.user_id)||(s.user_id=JSON.stringify({device_id:(0,t.createHash)("sha256").update(String(o||"")).digest("hex"),account_uuid:"",session_id:i})),s}({claudeBody:r,sourceBody:e,normalizedBody:n,cwd:s,sessionId:q}),H=function({claudeBody:e,sourceBody:t,normalizedBody:n,summarizeThinking:r=!1}){let o=M(L(e?.thinking))||M(L(t?.thinking))||M(L(n?.thinking));return o?u(o,{normalizedBody:n,summarizeThinking:r}):u({type:"adaptive"},{normalizedBody:n,summarizeThinking:r})}({claudeBody:R??r,sourceBody:e,normalizedBody:n,summarizeThinking:f}),Z=function({claudeBody:e,sourceBody:t,normalizedBody:n,model:r,effort:o}){return{...M(L(e?.output_config))||M(L(t?.output_config))||M(L(n?.output_config))||{},effort:S(t,n,r)||o}}({claudeBody:r,sourceBody:e,normalizedBody:n,model:o,effort:P});return{model:o,messages:W,system:K,tools:F,metadata:V,max_tokens:X,thinking:H,output_config:Z,...J?{tool_choice:J}:{},...i?{stream:!0}:{}}}function S(e,t,n){let r=(D(e,["output_config","effort"])||D(e,["reasoning","effort"])||N(e?.reasoning_effort)||D(t,["output_config","effort"])||D(t,["reasoning","effort"])||N(t?.reasoning_effort)||"").toLowerCase();return r?"low"===r?"low":"medium"===r?"medium":"high"===r?"high":"none"===r||"disabled"===r?"low":"xhigh"===r?k(n)?"xhigh":"high":"max"===r?(0,i.supportsClaudeMaxEffort)(n)?"max":"high":k(n)?"xhigh":"high":k(n)?"xhigh":"high"}function C(e,t){var n;let r=(0,s.L)({system:T(e.system),messages:Array.isArray(n=e.messages)?n.map(e=>{var t;let n,r=M(e);return r?{...r,content:(n=O(t=r.content)).length>0?n:t}:null}).filter(e=>!!e):[],tools:E(e.tools),thinking:M(e.thinking)||null},m,!0);return M(r)}function T(e){if("string"==typeof e){let t=e.trim();return t?[{type:"text",text:t}]:[]}return Array.isArray(e)?e.map(e=>j(e)).filter(e=>!!e):[]}function E(e){return Array.isArray(e)?e.map(e=>M(L(e))).filter(e=>!!e):[]}function O(e){if("string"==typeof e){let t=e.trim();return t?[{type:"text",text:t}]:[]}if(!Array.isArray(e)){let t=j(e);return t?[t]:[]}return e.map(e=>j(e)).filter(e=>!!e)}function j(e){let t=M(L(e));if(!t)return null;if("text"===t.type||"string"!=typeof t.type&&"string"==typeof t.text){let e=N(t.text);return e?{...t,type:"text",text:e}:null}return p(t)??t}function I(e){return Array.isArray(e)?e.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"===t||"developer"===t}).map(e=>$(e?.content)).filter(Boolean).map(e=>({type:"text",text:e})):[]}function U(e){for(let t of e)delete t.cache_control}function L(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}function $(e){return"string"==typeof e?e.trim():Array.isArray(e)?e.map(e=>e&&"object"==typeof e&&("text"===e.type&&"string"==typeof e.text||"string"==typeof e.text)?e.text.trim():"").filter(Boolean).join("\n").trim():e&&"object"==typeof e&&"string"==typeof e.text?e.text.trim():""}function R(e,t){if(!e)return null;if("function"==typeof e.get)return e.get(t);let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r??null;return null}function N(e){return"string"!=typeof e?null:e.trim()||null}function M(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function D(e,t){let n=e;for(let e of t){if(!n||"object"!=typeof n||Array.isArray(n)||"__proto__"===e||"constructor"===e||"prototype"===e||!Object.prototype.hasOwnProperty.call(n,e))return null;n=Reflect.get(n,e)}return N(n)}e.s(["d",0,"/v1/messages?beta=true","q",0,"/models","K",0,"context-1m-2025-08-07","A",0,function(e,t){let n=Object.keys(e).find(e=>"anthropic-beta"===e.toLowerCase());if(!n){e["anthropic-beta"]=t;return}let r=String(e[n]||"").split(",").map(e=>e.trim()).filter(Boolean);r.includes(t)||(e[n]=[...r,t].join(","))},"o",0,function(e,t=!1,n,r={}){return{"Content-Type":"application/json",Accept:t?"text/event-stream":"application/json",Authorization:`Bearer ${e}`,"anthropic-version":h,"anthropic-beta":l({redactThinking:!0===r.redactThinking}),"anthropic-dangerous-direct-browser-access":"true","x-app":"cli","User-Agent":o.r,"X-Stainless-Retry-Count":"0","X-Stainless-Timeout":String(A),"X-Stainless-Lang":"js","X-Stainless-Package-Version":o.Q,"X-Stainless-OS":"MacOS","X-Stainless-Arch":"arm64","X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":o.e,"accept-encoding":"gzip, deflate, br, zstd",...n?{"X-Claude-Code-Session-Id":n}:{}}},"s",0,w,"g",0,function(e="claude-sonnet-4-6"){return w({sourceBody:{max_tokens:1},normalizedBody:{messages:[{role:"user",content:"ok"}],max_tokens:1},model:e,stream:!0,sessionId:(0,t.randomUUID)(),cwd:process.cwd(),now:new Date})},"P",0,function(e){return"string"==typeof e&&e.startsWith(m)||(0,c.f)(e)},"H",0,function(e,t){return v(b(e),t)},"Q",0,function(e,t){return v(x(e),t)},"Z",0,function(e){let n=R(e,"x-claude-code-session-id")||R(e,"x-session-id")||R(e,"x_session_id")||R(e,"x-trouteai-session")||null;return n&&n.trim()||(0,t.randomUUID)()},"r",0,b,"e",0,x],526707)},786790,e=>{"use strict";let t={subagents:"SubDispatch",session_status:"CheckStatus",bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep",task:"Task",webfetch:"WebFetch",websearch:"WebSearch",todowrite:"TodoWrite",todoread:"TodoRead",question:"Question",skill:"Skill",multiedit:"MultiEdit",notebook:"Notebook",lsp:"Lsp",apply_patch:"ApplyPatch"},n={};for(let[e,r]of Object.entries(t))n[r]=e;function r(e){let t=e._toolNameMap instanceof Map?e._toolNameMap:new Map;return Object.defineProperty(e,"_toolNameMap",{value:t,enumerable:!1,configurable:!0,writable:!0}),t}function o(e,t,n){r(e).set(t,n)}function i(e){let t=new Set;if(!Array.isArray(e))return t;for(let n of e)n&&c(n.type)&&"string"==typeof n.name&&t.add(n.name);return t}let s=new Set(Object.values(t)),a={read_file:"Read",write_file:"Write",search_files:"Grep",grep_search:"Grep",list_directory:"Glob",run_command:"Bash",terminal:"Bash",todo:"TodoWrite",todo_write:"TodoWrite",todo_read:"TodoRead",patch:"Edit",multi_edit:"MultiEdit"},l=/^[a-z][a-z0-9_]*_\d{8}$/,u=new Set(["web_search","web_search_preview"]);function c(e){return"string"==typeof e&&0!==e.length&&(l.test(e)||u.has(e))}e.s(["X",0,n,"i",0,function(e,n){if("true"===process.env.CLAUDE_DISABLE_TOOL_NAME_CLOAK)return new Map;let o=e=>!(!e||s.has(e)||e.startsWith("mcp__"))&&(/[a-z]/.test(e.charAt(0))||e.includes("_")||e.includes("-"))&&!(n?.skip&&n.skip(e)),l=e.tools,u=i(l),f=new Set;if(Array.isArray(l))for(let e of l)e&&"string"==typeof e.name&&f.add(e.name);let p=e._toolNameMap instanceof Map?e._toolNameMap:null;if(p)for(let e of p.keys())f.add(e);let y=p,g=new Map,d=n=>{let o=g.get(n);if(o)return o;let i=t[n]??a[n]??(n.split(/[_\s-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")||n),s=i,l=2;for(;s!==n&&f.has(s);)s=`${i}${l++}`;return f.delete(n),f.add(s),g.set(n,s),y||(y=r(e)),y.set(s,n),s};Array.isArray(l)&&(e.tools=l.map(e=>e&&c(e.type)?e:e&&"string"==typeof e.name&&o(e.name)?{...e,name:d(e.name)}:e));let m=e.messages;Array.isArray(m)&&(e.messages=m.map(e=>{let t=e?.content;if(!Array.isArray(t))return e;let n=!1,r=t.map(e=>e?.type==="tool_use"&&"string"==typeof e.name&&!u.has(e.name)&&o(e.name)?(n=!0,{...e,name:d(e.name)}):e);return n?{...e,content:r}:e}));let h=e.tool_choice;return h?.type==="tool"&&"string"==typeof h.name&&!u.has(h.name)&&o(h.name)&&(e.tool_choice={...h,name:d(h.name)}),y??new Map},"j",0,function(e){let r=!1,s=!1,a=i(e.tools),l=e.tools;if(Array.isArray(l))for(let i of l){if(!i||c(i.type))continue;let a=String(i.name||"");if(t[a]){let n=t[a];i.name=n,o(e,n,a),r=!0}else n[a]&&(s=!0)}let u=e.messages;if(Array.isArray(u))for(let i of u){let l=i.content;if(Array.isArray(l)){for(let i of l)if("tool_use"===i.type&&"string"==typeof i.name){if(a.has(i.name))continue;let l=t[i.name];if(l){let t=i.name;i.name=l,o(e,l,t),r=!0}else n[i.name]&&(s=!0)}}}let f=e.tool_choice;if(f?.type==="tool"&&"string"==typeof f.name&&!a.has(f.name)){let i=t[f.name];if(i){let t=f.name;f.name=i,o(e,i,t),r=!0}else n[f.name]&&(s=!0)}return r&&!s}],786790)},85713,e=>{"use strict";var t=e.i(889771),n=e.i(313613),r=e.i(325840),o=e.i(526707),i=e.i(421892),s=e.i(628740),a=e.i(312009);let l="https://api.openai.com/v1",u="https://api.anthropic.com/v1";function c(e){return"string"==typeof e&&e.startsWith("openai-compatible-")}function f(e){return"string"==typeof e&&e.startsWith("anthropic-compatible-")}function p(e){return"string"==typeof e&&e.startsWith("anthropic-compatible-cc-")||(0,a.f)(e)}function y(e,t=null){if(!c(e))return"chat";let n=t&&"object"==typeof t&&"string"==typeof t.apiType?t.apiType:null;return"responses"===n||"chat"===n||"embeddings"===n||"audio-transcriptions"===n||"audio-speech"===n||"images-generations"===n?n:e.includes("responses")?"responses":e.includes("embeddings")?"embeddings":e.includes("audio-transcriptions")?"audio-transcriptions":e.includes("audio-speech")?"audio-speech":e.includes("images-generations")?"images-generations":"chat"}function g(e,t=""){let n=String(t||"");return/\/responses(?=\/|$)/i.test(n)||/^responses(?=\/|$)/i.test(n)?"openai-responses":/\/messages(?=\/|$)/i.test(n)||/^messages(?=\/|$)/i.test(n)?"claude":/\/antigravity(?=\/|:|$)/i.test(n)||/^antigravity(?=\/|:|$)/i.test(n)?"antigravity":/\/(?:chat\/completions|completions)(?=\/|$)/i.test(n)||/^(?:chat\/completions|completions)(?=\/|$)/i.test(n)?e&&"object"==typeof e&&!Array.isArray(e)&&void 0!==e.input&&void 0===e.messages?"openai-responses":"openai":d(e)}function d(e){let t=Object.prototype.hasOwnProperty.call(e,"input")&&void 0!==e.input,n=void 0!==e.max_output_tokens||void 0!==e.previous_response_id||void 0!==e.reasoning;if(t||n)return"openai-responses";if(e.request?.contents&&"antigravity"===e.userAgent)return"antigravity";if(e.contents&&Array.isArray(e.contents))return"gemini";if(e.stream_options||e.response_format||void 0!==e.logprobs||void 0!==e.top_logprobs||void 0!==e.n||void 0!==e.presence_penalty||void 0!==e.frequency_penalty||e.logit_bias||e.user)return"openai";if(e.messages&&Array.isArray(e.messages)){let t=e.messages[0];if(t?.content&&Array.isArray(t.content)){let n=t.content[0];if(n?.type==="text"&&!e.model?.includes("/")){if(e.system||e.anthropic_version)return"claude";let n=t.content.some(e=>"image"===e.type&&e.source?.type==="base64"),r=t.content.some(e=>"image_url"===e.type&&e.image_url?.url);if(n)return"claude";if(r)return"openai";if(t.content.some(e=>"tool_use"===e.type||"tool_result"===e.type))return"claude"}}if(void 0!==e.system||e.anthropic_version||e.max_tokens&&!e.stream_options&&!e.response_format)return"claude"}return"openai"}function m(e,n=null){if(c(e)){let r=y(e,n);return{...t.L.openai,format:"responses"===r?"openai-responses":"openai",baseUrl:l}}return f(e)?{...t.L.anthropic,format:"claude",baseUrl:u}:t.L[e]||t.L.openai}e.s(["W",0,function(e,t,r=!0,l=null){let u=m(e),c=(0,n.k)(e),y={"Content-Type":"application/json",...u.headers};if(p(e)){let n=t.apiKey||t.accessToken||"",s=(0,i.U)(t?.providerSpecificData),l=(0,o.o)(n,r,t?.providerSpecificData?.ccSessionId,{redactThinking:!0===s.redactThinking});if((0,a.f)(e)){delete l.Authorization;let e=c?.authHeader||"bearer";"x-api-key"===e?n&&(l["x-api-key"]=n):"key"===e?n&&(l.Authorization=`Key ${n}`):l.Authorization=`Bearer ${n}`}return l}if(f(e))t.apiKey?y["x-api-key"]=t.apiKey:t.accessToken&&(y.Authorization=`Bearer ${t.accessToken}`),y["anthropic-version"]||(y["anthropic-version"]="2023-06-01");else if("github"===e){let e=t.copilotToken||t.accessToken;y.Authorization=`Bearer ${e}`,y["x-request-id"]=crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),r||(y.Accept="application/json")}else if("cline"===e)Object.assign(y,(0,s.k)(t.apiKey||t.accessToken));else if(c){let e=c.authHeader||"bearer";if("x-api-key"===e){let e=t.apiKey||t.accessToken;e&&(y["x-api-key"]=e)}else if("key"===e){let e=t.apiKey||t.accessToken;e&&(y.Authorization=`Key ${e}`)}else"x-goog-api-key"===e?t.apiKey?y["x-goog-api-key"]=t.apiKey:t.accessToken&&(y.Authorization=`Bearer ${t.accessToken}`):y.Authorization=`Bearer ${t.apiKey||t.accessToken}`}else y.Authorization=`Bearer ${t.apiKey||t.accessToken}`;return r&&(y.Accept="text/event-stream"),y},"o",0,function(e,t,r=!0,i={}){if((0,a.f)(e)){let t=(0,n.k)(e),r=m(e),s=i?.baseUrl||t?.baseUrl||r.baseUrl;return(0,o.Q)(s,o.d)}if(c(e)){var s;let t,n,r=i?.providerSpecificData||null,o=y(e,r);return s=i?.baseUrl||("string"==typeof r?.baseUrl?r.baseUrl:null)||l,t=s.replace(/\/$/,""),n="/chat/completions","responses"===o?n="/responses":"embeddings"===o?n="/embeddings":"audio-transcriptions"===o?n="/audio/transcriptions":"audio-speech"===o?n="/audio/speech":"images-generations"===o&&(n="/images/generations"),`${t}${n}`}if(f(e)){let t,n=i?.baseUrl||u;return p(e)?(0,o.Q)(n,o.d):(t=n.replace(/\/$/,""),`${t}/messages`)}let g=(0,n.k)(e),d=m(e);if(g){if(g.baseUrls){let e=i?.baseUrlIndex||0,n=g.baseUrls[e]||g.baseUrls[0];return g.urlBuilder?g.urlBuilder(n,t,r):n}if(g.urlBuilder){let e=g.baseUrl||d.baseUrl;if(e)return g.urlBuilder(e,t,r)}if(g.urlSuffix)return`${g.baseUrl}${g.urlSuffix}`}return d.baseUrl},"$",0,d,"i",0,g,"R",0,function(e,t){return g(e,new URL(t).pathname)},"h",0,y,"a",0,function(e,t=null){if(c(e))return"responses"===y(e,t)?"openai-responses":"openai";if(f(e))return"claude";let o=(0,n.k)(e);if(o){let e=(0,r.f)(o,t);return e?e.format:o.format||"openai"}return m(e).format||"openai"},"F",0,function(e){return!!(e.reasoning_effort||e.thinking?.type==="enabled")},"l",0,p,"G",0,function(e){return!function(e){let t=e.messages||e.contents;if(!t?.length)return!0;let n=t[t.length-1];return n?.role==="user"}(e)&&delete e.thinking,e}])},163686,e=>{"use strict";let t,n;var r=e.i(306860),o=e.i(139908);let i=new Set(["deepseek","opencode-go","siliconflow","nebius","deepinfra","sambanova","fireworks","together","kimi-coding","kimi-coding-apikey","xiaomi-mimo"]),s=[/deepseek-r1/i,/deepseek-reasoner/i,/deepseek-chat/i,/deepseek[-/]v4[-.](flash|pro)(-free)?/i,/zen\/deepseek-v4/i,/kimi[-/]k\d/i,/qwq/i,/qwen.*think/i,/glm.*think/i,/^mimo[-.]?v\d/i],a=/deepseek[-/]v4[-.](flash|pro)/i,l=new Map,u=0,c=0,f=0;function p(){let e=Date.now();for(let[t,n]of l)e>=n.expiresAt&&l.delete(t)}function y(e,t,n,o){if(!e||!o)return;o.length>1e4&&(o=o.slice(0,1e4));let i=Date.now();l.size>=200&&function(){let e=null,t=1/0;for(let[n,r]of l)r.createdAt<t&&(t=r.createdAt,e=n);e&&l.delete(e)}(),l.set(e,{reasoning:o,provider:t,model:n,expiresAt:i+72e5,createdAt:i});try{(0,r.R)(e,t,n,o,72e5)}catch{}}function g(){p();try{return(0,r.F)()}catch{return 0}}try{let e=g();e>0&&console.log(`[ReasoningCache] boot cleanup removed ${e} expired entries`)}catch(e){console.error("[ReasoningCache] boot cleanup failed:",e)}(0,o.P)("reasoning-cache-cleanup",()=>{try{let e=g();e>0&&console.log(`[ReasoningCache] periodic cleanup removed ${e} expired entries`)}catch(e){console.error("[ReasoningCache] periodic cleanup failed:",e)}},Number.isFinite(n=(t=process.env.TROUTEAI_REASONING_CACHE_CLEANUP_INTERVAL_MS)?Number(t):0/0)&&n>=6e4?n:18e5),e.s(["W",0,function(e,t,n,r){if(!e||"assistant"!==e.role)return 0;let o="string"==typeof e.reasoning_content&&e.reasoning_content.length>0?e.reasoning_content:"string"==typeof e.reasoning&&e.reasoning.length>0?e.reasoning:"";if(!o)return 0;let i=Array.isArray(e.tool_calls)?e.tool_calls.map(e=>"string"==typeof e.id?e.id:"").filter(e=>e.length>0):[];if(0===i.length){let e=r?.requestId?.trim(),i=r?.messageIndex;return e&&"number"==typeof i&&Number.isInteger(i)?(y(`request:${e}:message:${i}`,t,n,o),1):0}for(let e of i)e&&y(e,t,n,o);return i.length},"k",0,function(e){if(e)for(let[t,n]of l)n.provider===e&&l.delete(t);else l.clear();u=0,c=0,f=0;try{return(0,r.Y)(e)}catch{return 0}},"C",0,function(e){if(!e)return 0;let t=l.delete(e),n=0;try{n=(0,r.J)(e)}catch{}return n+(t&&0===n?1:0)},"N",0,function(e={}){try{return(0,r.a)(e)}catch{return[]}},"b",0,function(){p();let e={totalEntries:0,totalChars:0,byProvider:{},byModel:{},oldestEntry:null,newestEntry:null};try{e=(0,r.s)()}catch{}let t=u+c,n=t>0?(f/t*100).toFixed(1):"0.0";return{memoryEntries:l.size,dbEntries:e.totalEntries,totalEntries:e.totalEntries,totalChars:e.totalChars,hits:u,misses:c,replays:f,replayRate:`${n}%`,byProvider:e.byProvider,byModel:e.byModel,oldestEntry:e.oldestEntry,newestEntry:e.newestEntry}},"c",0,function(e){if(!e)return c++,null;let t=l.get(e);if(t){if(Date.now()<t.expiresAt)return u++,t.reasoning;l.delete(e)}let n=null;try{n=(0,r.t)(e)}catch{}if(n){u++;let t=n.reasoning;return t.length>1e4&&(t=t.slice(0,1e4)),l.set(e,{reasoning:t,provider:n.provider,model:n.model,expiresAt:Date.now()+72e5,createdAt:Date.now()}),t}return c++,null},"X",0,function(){f++},"f",0,function(e){let t=e.provider.trim().toLowerCase(),n=e.model.trim(),r="string"==typeof e.interleavedField?e.interleavedField.trim().toLowerCase():"";return"reasoning_content"===r||!("reasoning_details"===r||/deepseek-reasoner/i.test(n)||/deepseek-r1/i.test(n))&&(!!(!0===e.thinkingEnabled&&a.test(e.model))||!1!==e.allowLegacyFallback&&(!!i.has(t)||s.some(e=>e.test(n))))}])},55245,e=>{"use strict";var t=e.i(80513),n=e.i(163686),r=e.i(878947),o=e.i(286410);let i=new Set(["minimax","minimax-cn"]);function s(e){if(!Array.isArray(e)||0===e.length)return e;let t=[],n=new Set,r=e=>{for(let t of e)t?.type==="tool_use"&&"string"==typeof t.id&&n.add(t.id)};for(let o of e){if("assistant"!==o.role||!Array.isArray(o.content)){t.push(o);continue}let e=o.content.filter(e=>e?.type==="tool_result");if(0===e.length){t.push(o),r(o.content);continue}let i=e.filter(e=>"string"==typeof e?.tool_use_id&&n.has(e.tool_use_id)),s=o.content.filter(e=>e?.type!=="tool_result");if(i.length>0){let e=t[t.length-1];e&&"user"===e.role&&Array.isArray(e.content)?t[t.length-1]={...e,content:[...e.content,...i]}:t.push({role:"user",content:i})}s.length>0&&(t.push({...o,content:s}),r(s))}return t}function a(e){return Array.isArray(e?.content)?e.content:"string"==typeof e?.content&&e.content.trim()?(e.content=[{type:"text",text:e.content}],e.content):[]}function l(e,t){let n=a(e);if(0===n.length)return!1;let r=n.length-1;return n[r].cache_control=void 0!==t?{type:"ephemeral",ttl:t}:{type:"ephemeral"},!0}function u(e){if(!e||"object"!=typeof e)return!1;let n="redacted_thinking"===e.type?e.data:"thinking"===e.type?e.signature:void 0;return("thinking"===e.type||"redacted_thinking"===e.type)&&("string"!=typeof n||0===n.length||n===t.f)}e.s(["F",0,function(e,t){if(!t.thinking&&!t.reasoning_effort)return;let n=String(t.reasoning_effort??t.thinking?.effort??"on").toLowerCase(),r=t.thinking?.type==="disabled"||["off","none"].includes(n);if(e.thinking={type:r?"disabled":"enabled"},!r&&!["on","auto"].includes(n)){let t=e.output_config&&"object"==typeof e.output_config?e.output_config:{};e.output_config={...t,effort:n}}},"L",0,function(e,t=null,c=!1,f=null,p={}){t&&i.has(t)&&delete e.output_config,c&&!0===p.fallbackToHeuristicWhenNoMarkers&&!function(e){if(Array.isArray(e.system)){for(let t of e.system)if(t&&"object"==typeof t&&t.cache_control)return!0}if(Array.isArray(e.messages)){for(let t of e.messages)if(Array.isArray(t?.content)){for(let e of t.content)if(e&&"object"==typeof e&&e.cache_control)return!0}}if(Array.isArray(e.tools)){for(let t of e.tools)if(t&&"object"==typeof t&&t.cache_control)return!0}return!1}(e)&&(c=!1);let y="claude"===t||"anthropic"===t||t?.startsWith?.("anthropic-compatible-"),g="kimi-coding"===t||"kimi-coding-apikey"===t,d=!!t&&!!f&&"claude"===(0,r.getModelTargetFormat)(t,f),m=!g&&(y||d),h=e.system;if(h&&Array.isArray(h)&&!c&&(e.system=h.map((e,t)=>{let{cache_control:n,...r}=e;return t===h.length-1&&y?{...r,cache_control:{type:"ephemeral",ttl:"1h"}}:r})),e.messages&&Array.isArray(e.messages)){let r=e.messages.length,i=[];for(let t=0;t<r;t++){let n=e.messages[t];if(Array.isArray(n.content)&&!c)for(let e of n.content)delete e.cache_control;(t===r-1&&"assistant"===n.role||"string"==typeof n.content&&n.content.trim()||Array.isArray(n.content)&&n.content.some(e=>"text"===e.type&&e.text?.trim()||"tool_use"===e.type||"tool_result"===e.type||"image"===e.type||"document"===e.type))&&i.push(n)}for(let e of i)Array.isArray(e.content)&&(e.content=e.content.filter(e=>"tool_use"!==e.type||e.name&&e.name?.trim()),e.content=e.content.filter(e=>"tool_result"!==e.type||e.tool_use_id));e.tools&&Array.isArray(e.tools)&&"claude"!==t&&(e.tools=e.tools.filter(e=>!e.type||"function"===e.type).map(e=>{if(e.function)return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};let{type:t,...n}=e;return n})),e.tools&&Array.isArray(e.tools)&&(e.tools=e.tools.filter(e=>e.name&&e.name?.trim())),e.messages=i=function(e){if(e.length<=1)return e;for(let t of e)if("assistant"===t.role&&Array.isArray(t.content)&&t.content.some(e=>"tool_use"===e.type)){let e=[],n=!1;for(let r of t.content)"tool_use"===r.type?(n=!0,e.push(r)):"thinking"===r.type||"redacted_thinking"===r.type?e.push(r):n||e.push(r);t.content=e}let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.role===n.role){let t=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];e.content=[...t.filter(e=>"tool_result"===e.type),...r.filter(e=>"tool_result"===e.type),...t.filter(e=>"tool_result"!==e.type),...r.filter(e=>"tool_result"!==e.type)]}else{let e=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];t.push({role:n.role,content:[...e]})}}return t}(i=s(i));let u=i[i.length-1],f=u?.role==="user",p=e.thinking?.type==="enabled"&&f;if(!c&&y){let e=i.reduce((e,t,n)=>(t?.role==="user"&&e.push(n),e),[]),t=e.length>=2?e[e.length-2]:-1;t>=0&&l(i[t])}let d=-1;for(let e=i.length-1;e>=0;e--)if(i[e]?.role==="assistant"){d=e;break}let h=!1;for(let e=i.length-1;e>=0;e--){let t=i[e],r=a(t);if("assistant"===t.role&&r.length>0){!c&&y&&!h&&l(t)&&(h=!0);let i=e===d?r.filter(e=>"thinking"===e.type||"redacted_thinking"===e.type):[],s=i.length>0;if(i.every(e=>"redacted_thinking"===e.type?"string"==typeof e.data&&e.data.length>0:"string"==typeof e.signature&&e.signature.length>0),m)continue;let a=!1,u=!1,f=[];if(!m)for(let e of r)"tool_use"===e.type&&"string"==typeof e.id&&f.push(e.id);let _=0;for(let e of r){if("thinking"===e.type||"redacted_thinking"===e.type){if(g)"redacted_thinking"===e.type&&(e.type="thinking",e.thinking="string"==typeof e.thinking?e.thinking:""),delete e.data,delete e.signature;else{let t="string"==typeof e.thinking&&e.thinking.length>0?e.thinking:"";if(t&&s)e.type="thinking";else{if(!t){let e=f[_];if(e){let r=(0,n.c)(e);r&&(t=r,(0,n.X)())}}e.type="thinking",e.thinking=t||o.P}delete e.data,delete e.signature}u=!0,_++}"tool_use"===e.type&&(a=!0)}if(p&&!u&&a)if(g)r.unshift({type:"thinking",thinking:""});else{let e="",t=f[0];if(t){let r=(0,n.c)(t);r&&(e=r,(0,n.X)())}r.unshift({type:"thinking",thinking:e||o.P})}}}}if(m&&function(e){let t=e.messages;if(!Array.isArray(t))return;for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||"assistant"!==n.role||!Array.isArray(n.content)||!n.content.some(u))continue;let r=n.content.filter(e=>!u(e));r.length>0?n.content=r:t.splice(e,1)}if(e.thinking?.type!=="enabled"||t[t.length-1]?.role!=="user")return;let n=-1;for(let e=t.length-1;e>=0;e--)if(t[e]?.role==="assistant"){n=e;break}let r=Array.isArray(t[n]?.content)?t[n].content:[],o=r.some(e=>e?.type==="tool_use"),i=r.some(e=>e?.type==="thinking"||e?.type==="redacted_thinking");if(!o||i)return;delete e.thinking;let s=e.context_management;if(s&&Array.isArray(s.edits)){let t=s.edits.filter(e=>!String(e?.type||"").startsWith("clear_thinking"));t.length>0?e.context_management={...s,edits:t}:delete e.context_management}}(e),e.tools&&Array.isArray(e.tools)&&!c&&(e.tools=e.tools.map(e=>{let{cache_control:t,...n}=e;return n}),y)){for(let t=e.tools.length-1;t>=0;t--)if(!e.tools[t].defer_loading){e.tools[t].cache_control={type:"ephemeral",ttl:"1h"};break}}return e},"O",0,s])},286410,e=>{"use strict";let t="(prior reasoning summary unavailable)";e.s(["P",0,t,"p",0,function(e){return"string"==typeof e&&e.trim()===t},"L",0,function(e){if(!e.includes(t))return e;let n=e.replaceAll(t,"");return""===n.trim()?"":n}])},628740,e=>{"use strict";var t=e.i(666680);let n=process.env.TROUTEAI_CLINE_CLIENT_VERSION?.trim()||"3.8.49";function r(e){if("string"!=typeof e)return;let t=e.trim();if(!(!t||t.length>256||/[\r\n\0]/.test(t)))return t}function o(e,t){let n=Object.keys(e??{}).find(e=>e.toLowerCase()===t);return n?r(e?.[n]):void 0}function i(e,s={}){let a=r(s.taskId)??o(e,"x-task-id")??(0,t.randomUUID)(),l=r(s.clientVersion)??n;for(let[t,o]of Object.entries({"HTTP-Referer":"https://cline.bot","X-Title":"Cline","User-Agent":`Cline/${l}`,"X-IS-MULTIROOT":!0===s.isMultiRoot?"true":"false","X-CLIENT-TYPE":r(s.clientType)??"trouteai","X-CLIENT-VERSION":l,"X-PLATFORM":r(s.platform)??process.platform??"unknown","X-PLATFORM-VERSION":r(s.platformVersion)??process.version??"unknown","X-CORE-VERSION":r(s.coreVersion)??n,"X-Task-ID":a})){for(let n of Object.keys(e))n!==t&&n.toLowerCase()===t.toLowerCase()&&delete e[n];e[t]=o}return e}function s(e,t={},n={}){let r,o=(r=function(e){if("string"!=typeof e)return"";let t=e.trim();return t?t.startsWith("workos:")?t:`workos:${t}`:""}(e))?`Bearer ${r}`:"",a=i({...t},n);return o&&(a.Authorization=o),a}e.s(["b",0,function(e,n,r,a,l){let u={taskId:o(a,"x-task-id")??(0,t.randomUUID)()};return Object.assign(e,l?function(e,t,n={}){if(e?.accessToken)return s(e.accessToken,{},n);let r=i({},n),o=t||e?.apiKey;return o&&(r.Authorization=`Bearer ${o}`),r}(n,r,u):s(r||n?.accessToken,{},u)),e},"w",0,i,"k",0,s])}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=_085cu6zzvapwm._.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
module.exports=[744402,e=>{"use strict";var t=e.i(190134),n=e.i(95360),r=e.i(802275),o=e.i(139908);let i=new Map;function a(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return null}async function l(e,t){let n,o=i.get(e);if(o&&Date.now()-o.fetchedAt<6e4)return o.quota;let l="string"==typeof(n=t?.apiKey)&&n.trim().length>0?n.trim():null;if(!l)return null;try{await (0,r.f)();let t=await fetch("https://crof.ai/usage_api/",{method:"GET",headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(!t.ok)return(401===t.status||403===t.status)&&i.delete(e),null;let n=await t.json(),o=function(e){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};if(0===Object.keys(t).length)return null;let n=t.usable_requests,r=null==n?null:a(n),o=a(t.credits)??0,i=0;return i=null!==r?r>0?0:1:o>0?0:1,{used:0,total:r??0,percentUsed:i,resetAt:null,usableRequests:r,credits:o}}(n);if(!o)return null;return i.set(e,{quota:o,fetchedAt:Date.now()}),o}catch{return null}}(0,o.P)("crofUsageFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of i)e-n.fetchedAt>3e5&&i.delete(t)},3e5),e.s(["f",0,function(){(0,t.s)("crof",l),(0,n.I)("crof",l)}])},167389,e=>{"use strict";var t=e.i(931680);let n=null,r=t.P,o={enabled:!0,provider:"nvidia",model:"openai/gpt-oss-120b",triggerOn402:!0,triggerOnBudgetKeywords:!0,budgetKeywords:["insufficient funds","insufficient_funds","budget exceeded","budget_exceeded","quota exceeded","quota_exceeded","billing","payment required","out of credits","no credits","credit limit","spending limit","saldo insuficiente","limite de gastos","cota excedida"],skipForToolRequests:!0,maxOutputTokens:4096};e.s(["g",0,function(e){return!0===e.shouldFallback},"i",0,function(e,t,i,a=o){if(!a.enabled)return{shouldFallback:!1,reason:"emergency fallback disabled"};if(!function(){let e,t=Date.now();if(n&&n.expiresAt>t)return n.value;try{e=r("TROUTEAI_EMERGENCY_FALLBACK")}catch(n){let t;console.warn("[emergencyFallback] Feature flag resolution failed; falling back to raw env:",n instanceof Error?n.message:n),e="true"===(t=process.env.TROUTEAI_EMERGENCY_FALLBACK)||"1"===t}return n={value:e,expiresAt:t+500},e}())return{shouldFallback:!1,reason:"emergency fallback off (TROUTEAI_EMERGENCY_FALLBACK is not true)"};if(a.skipForToolRequests&&i)return{shouldFallback:!1,reason:"skipped: request has tools"};if(a.triggerOn402&&402===e)return{shouldFallback:!0,reason:`HTTP 402 → emergency fallback to ${a.provider}/${a.model}`,provider:a.provider,model:a.model,maxOutputTokens:a.maxOutputTokens};if(a.triggerOnBudgetKeywords&&t){let e=t.toLowerCase(),n=a.budgetKeywords.find(t=>e.includes(t.toLowerCase()));if(n)return{shouldFallback:!0,reason:`Budget error detected ('${n}') → emergency fallback to ${a.provider}/${a.model}`,provider:a.provider,model:a.model,maxOutputTokens:a.maxOutputTokens}}return{shouldFallback:!1,reason:"no budget error detected"}}])},238492,e=>e.a(async(t,n)=>{try{var r=e.i(919644),o=e.i(190134),i=e.i(139908),a=t([r]);[r]=a.then?(await a)():a;let s=new Map;function l(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return null}(0,i.P)("genericQuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of s)e-n.fetchedAt>3e5&&s.delete(t)},3e5);let u=async(e,t)=>{let n;if(!t)return null;let i="string"==typeof t.provider?t.provider:null;if(!i)return null;let a=`${i}::${e}`,u=s.get(a);if(u&&Date.now()-u.fetchedAt<6e4)return u.quota;try{n=await (0,r.c)(t)}catch{return null}let c=function(e){if(!e||"object"!=typeof e||"string"==typeof e.message&&(!e.quotas||"object"!=typeof e.quotas))return null;let t=e.quotas;if(!t||"object"!=typeof t||Array.isArray(t))return null;let n={},r=0,o=null;for(let[e,i]of Object.entries(t)){let t=function(e){if(!e||"object"!=typeof e||!0===e.unlimited||!1===e.fractionReported)return null;let t=l(e.remainingPercentage);if(null!==t)return(100-Math.max(0,Math.min(100,t)))/100;let n=l(e.used),r=l(e.total);return null!==n&&null!==r&&r>0?Math.max(0,Math.min(1,n/r)):null}(i);if(null===t)continue;let a=i&&"object"==typeof i&&"string"==typeof i.resetAt?i.resetAt:null;n[e]={percentUsed:t,resetAt:a},t>r&&(r=t,o=a)}return 0===Object.keys(n).length?null:{used:0,total:0,percentUsed:r,resetAt:o,windows:n,limitReached:r>=1-1e-9}}(n);return c?((0,o.L)(i,Object.keys(c.windows||{})),s.set(a,{quota:c,fetchedAt:Date.now()}),c):null};e.s(["f",0,function(){for(let e of r.J)(0,o.l)(e)||(0,o.s)(e,u)}]),n()}catch(e){n(e)}},!1),645035,e=>{"use strict";var t=e.i(190134),n=e.i(95360),r=e.i(802275),o=e.i(139908);let i=new Map;function a(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}async function l(e,t){let n,o=i.get(e);if(o&&Date.now()-o.fetchedAt<6e4)return o.quota;let{systemAccessToken:l,userId:s}={systemAccessToken:"string"==typeof(n=a(t?.providerSpecificData)).consoleApiKey&&n.consoleApiKey.trim().length>0?n.consoleApiKey:null,userId:"string"==typeof n.newApiUserId&&n.newApiUserId.trim().length>0?n.newApiUserId:null};if(!l||!s)return null;let u="https://agentrouter.org/api/user/self";try{await (0,r.f)();let t=await fetch(u,{method:"GET",headers:{Authorization:`Bearer ${l}`,"New-Api-User":s,"Content-Type":"application/json",Accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(401===t.status||403===t.status)return i.delete(e),null;if(!t.ok)return null;let n=await t.json(),o=function(e){let t=a(e),n=a(t.data),r="quota"in n?n.quota:t.quota;if(void 0===r)return null;let o=function(e,t=0){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return t}(r,-1);if(o<0)return null;let i=o<=0,l=+!!i;return{used:100*l,total:100,percentUsed:l,resetAt:null,rawQuota:o,dollarBalance:o/5e5,limitReached:i}}(n);if(!o)return null;return i.set(e,{quota:o,fetchedAt:Date.now()}),o}catch{return null}}(0,o.P)("agentrouterQuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of i)e-n.fetchedAt>3e5&&i.delete(t)},3e5);let s="https://api.v0.dev",u="credits",c="dailyOps",d=new Map;function f(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function p(e,t=0){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return t}function y(e){let t=f(e);if(!("remaining"in t)||!("limit"in t))return null;let n=p(t.remaining,-1),r=p(t.limit,-1);return n<0||r<=0?null:{percentUsed:Math.min(1,Math.max(0,r-n)/r),resetAt:function(e){if("string"==typeof e&&e.trim().length>0){let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toISOString()}return"number"==typeof e&&Number.isFinite(e)&&e>0?new Date(e).toISOString():null}(t.reset)}}async function m(e,t,n){try{await (0,r.f)();let o=await fetch(e,{method:"GET",headers:t,signal:AbortSignal.timeout(8e3)});if(401===o.status||403===o.status)return{window:null,billingType:null,invalidCredential:!0};if(!o.ok)return{window:null,billingType:null,invalidCredential:!1};let i=await o.json(),a=n(i);return{window:a.window,billingType:a.billingType,invalidCredential:!1}}catch{return{window:null,billingType:null,invalidCredential:!1}}}function g(e){return{billingType:null,window:y(e)}}function h(e){let t=f(e);return{billingType:"string"==typeof t.billingType?t.billingType:"unknown",window:y(t.data)}}async function b(e,t){let n=d.get(e);if(n&&Date.now()-n.fetchedAt<6e4)return n.quota;let r="string"==typeof t?.apiKey&&t.apiKey.trim().length>0?t.apiKey:null;if(!r)return null;let o={Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json"},i={},a="unknown",l=await m(`${s}/v1/user/billing`,o,h);l.window&&(i[u]=l.window,a=l.billingType??"unknown");let f=await m(`${s}/v1/rate-limits`,o,g);if(f.window&&(i[c]=f.window),l.invalidCredential||f.invalidCredential)return d.delete(e),null;let p=function(e,t){if(0===Object.keys(e).length)return null;let n=Math.max(0,...Object.values(e).map(e=>e.percentUsed)),r=Object.values(e).find(e=>e.percentUsed===n)??null;return{used:Math.round(100*n),total:100,percentUsed:n,resetAt:r?.resetAt??null,windows:e,billingType:t}}(i,a);return p?(d.set(e,{quota:p,fetchedAt:Date.now()}),p):null}(0,o.P)("v0QuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of d)e-n.fetchedAt>3e5&&d.delete(t)},3e5);let w="window5h",_="window7d";function A(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}let I=new Map;function k(e,t,n){return n-e.windowStart>=t?{count:0,windowStart:n}:e}function v(e,t,n){return{percentUsed:n>0?Math.min(1,e.count/n):0,resetAt:new Date(e.windowStart+t).toISOString()}}async function T(e){let t=I.get(e);if(!t)return null;let n=Date.now(),r=A("FREEMODEL_5H_REQUEST_LIMIT",500),o=A("FREEMODEL_7D_REQUEST_LIMIT",2e3),i=k(t.window5h,18e6,n),a=k(t.window7d,6048e5,n),l=v(i,18e6,r),s=v(a,6048e5,o),u=Math.max(l.percentUsed,s.percentUsed),c=u===l.percentUsed?l.resetAt:s.resetAt;return{used:Math.round(100*u),total:100,percentUsed:u,resetAt:c,windows:{[w]:l,[_]:s}}}function R(e,t=0){if(t<0||e.length-t<5)return null;let n=e[t];if(0!==n&&1!==n&&128!==n&&129!==n)return null;let r=t+5,o=e.readUInt32BE(t+1);return o>e.length-r?null:{flag:n,payloadStart:r,payloadLength:o}}function S(e,t){let n=0n,r=0n,o=t;for(;;){if(o>=e.length)return null;let t=e[o];if(n|=BigInt(127&t)<<r,o+=1,(128&t)==0)break;if((r+=7n)>70n)return null}return{value:Number(n),next:o}}function E(e,t,n,r){return t+n>e.length?null:{field:{wireType:r,bytes:e.subarray(t,t+n)},next:t+n}}function x(e){let t=new Map,n=0;for(;n<e.length;){let r=function(e,t){let n=S(e,t);if(!n)return null;let r=n.value>>>3,o=7&n.value;if(0===r)return null;if(0===o){let t=S(e,n.next);return t?{fieldNumber:r,field:{wireType:0,value:t.value},next:t.next}:null}if(2===o){let t=function(e,t){let n=S(e,t);if(!n)return null;let{value:r,next:o}=n;return r<0||o+r>e.length?null:{field:{wireType:2,bytes:e.subarray(o,o+r)},next:o+r}}(e,n.next);return t?{fieldNumber:r,field:t.field,next:t.next}:null}if(1===o){let t=E(e,n.next,8,1);return t?{fieldNumber:r,field:t.field,next:t.next}:null}if(5===o){let t=E(e,n.next,4,5);return t?{fieldNumber:r,field:t.field,next:t.next}:null}return null}(e,n);if(!r)return null;t.set(r.fieldNumber,r.field),n=r.next}return t}let $=Buffer.from([0,0,0,0,0]),C=new Map;async function O(e,t){var n,o,i;let a,l=C.get(e);if(l&&Date.now()-l.fetchedAt<6e4)return l.quota;let s="string"==typeof(a=(n=t?.credentials)&&"object"==typeof n&&!Array.isArray(n)?n:{}).accessToken&&a.accessToken.trim().length>0?a.accessToken:null;if(!s)return null;let u="https://grok.com/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig";try{let t;await (0,r.f)();let n=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/grpc-web+proto","X-Grpc-Web":"1"},body:$,signal:AbortSignal.timeout(8e3)});if(401===n.status||403===n.status)return C.delete(e),null;if(!n.ok)return null;let a=await n.arrayBuffer(),l=function(e){if(!e||0===e.length)return null;try{var t,n;let r=null!==R(e,0)?function(e){let t=0;for(;t<e.length;){let n=R(e,t);if(!n)break;let r=n.payloadStart+n.payloadLength;if((128&n.flag)==0)return e.subarray(n.payloadStart,r);t=r}return null}(e):e;if(!r)return null;let o=x(r);if(!o)return null;let i=(t=o.get(1))&&2===t.wireType?x(t.bytes):null;if(!i)return null;let a=(n=i.get(1))?5===n.wireType?n.bytes.readFloatLE(0):1===n.wireType?n.bytes.readDoubleLE(0):null:0;if(null===a||!Number.isFinite(a)||a<0)return null;return{percentUsed:Math.min(100,100*a),resetAt:function(e){if(!e||2!==e.wireType)return null;let t=x(e.bytes);if(!t)return null;let n=t.get(1),r=t.get(2),o=new Date(1e3*(n?.wireType===0?n.value:0)+Math.round((r?.wireType===0?r.value:0)/1e6));return Number.isNaN(o.getTime())?null:o.toISOString()}(i.get(5))}}catch{return null}}(Buffer.from(a));if(!l)return null;let c=(o=l.percentUsed,i=l.resetAt,t=Math.min(100,Math.max(0,o)),{used:Math.round(t),total:100,percentUsed:t/100,resetAt:i,limitReached:t>=100});return C.set(e,{quota:c,fetchedAt:Date.now()}),c}catch{return null}}(0,o.P)("grokCliQuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of C)e-n.fetchedAt>3e5&&C.delete(t)},3e5);var M=e.i(184498),L=e.i(808203);(0,t.s)("agentrouter",l),(0,n.I)("agentrouter",l),(0,t.s)("v0-vercel",b),(0,n.I)("v0-vercel",b),(0,t.L)("v0-vercel",[u,c]),(0,t.s)("freemodel-dev",T),(0,n.I)("freemodel-dev",T),(0,t.L)("freemodel-dev",[w,_]),(0,t.s)("grok-cli",O),(0,n.I)("grok-cli",O),(0,M.registerXaiOauthQuotaFetcher)(),(0,L.P)(),e.s([],645035)},324348,e=>{"use strict";function t(e){return"string"==typeof e?e:""}function n(e){if(!e||"object"!=typeof e)return!1;let n=e.tools;return!!Array.isArray(n)&&n.some(e=>!!e&&"object"==typeof e&&!e.function&&t(e.type).startsWith("web_search"))}e.s(["W",0,n,"s",0,function(e,r,o){let i={wasRouted:!1,model:e};if(!n(r))return i;let a=t(o?.webSearchRouteModel).trim();return a&&a!==e?{wasRouted:!0,model:a}:i}])},701554,e=>{"use strict";async function t(e,t,n,r){if(!e||!n||!n.comboAutoPromoteEnabled)return!1;let o="string"==typeof e.id?e.id:null;if(!o)return!1;let i=function(e,t){if(!Array.isArray(e)||0===e.length||"string"!=typeof t||0===t.length)return null;let n=e.findIndex(e=>(function(e){if("string"==typeof e)return e.trim().length>0?e:null;if(e&&"object"==typeof e){let t=e.model;if("string"==typeof t&&t.trim().length>0)return t}return null})(e)===t);return n<=0?null:[e[n],...e.filter((e,t)=>t!==n)]}(Array.isArray(e.models)?e.models:null,t);if(!i)return!1;let a="string"==typeof e.name?e.name:o;try{return await r.updateCombo(o,{models:i}),r.info?.("COMBO",`Model "${t}" succeeded — promoted to #1 in combo "${a}"`),!0}catch(e){return r.warn?.("COMBO",`Failed to promote model "${t}" in combo "${a}": ${e?.message||"unknown error"}`),!1}}e.s(["f",0,t])},444063,e=>{"use strict";e.s(["f",0,function(e){return Array.isArray(e)&&e.includes("policy:bypass-provider-quota")}])},913577,e=>e.a(async(t,n)=>{try{var r=e.i(719201),o=e.i(889771),i=e.i(529160),a=e.i(713553),l=e.i(122791),s=e.i(245272),u=e.i(403122),c=e.i(249157),d=t([i,a,s]);async function f(t,n,r){try{let{parseAutoPrefix:o}=await e.A(501885),a=o(t);if(!a.valid)return n.spec||c.warn("AUTO",`Invalid auto prefix format: ${t}`),n;let l=Object.prototype.hasOwnProperty.call(i.s,t)?n.variant:a.variant,s="auto"===t&&void 0===l?r.autoRoutingDefaultVariant:void 0,u=l??s;return c.info("AUTO",`Zero-config routing variant: ${u||"default"} (model=${t})`),{variant:u,spec:n.spec}}catch(e){return c.error("AUTO","Failed to load auto-prefix parser",{err:e}),n}}async function p(e){let t="auto"===e||e.startsWith("auto/"),n=function(e){let t="auto"===e||Object.prototype.hasOwnProperty.call(i.s,e);if(Object.prototype.hasOwnProperty.call(i.s,e))return{variant:i.s[e],recognizedBuiltInAuto:!0};if(!e.startsWith("auto/"))return{recognizedBuiltInAuto:t};let n=e.slice(5);if(i.G.has(n))return{recognizedBuiltInAuto:!0};let r=(0,a.E)(n);return r.valid?{recognizedBuiltInAuto:!0,spec:{category:r.category,tier:r.tier}}:(0,l.d)(n)?{recognizedBuiltInAuto:!0,spec:{family:n}}:{recognizedBuiltInAuto:t}}(e);if(!t)return{model:e,...n,isAutoRouting:t,response:null};let s=await (0,u.getCachedSettings)().catch(()=>({}));if(s?.autoRoutingEnabled===!1)return{model:e,...n,isAutoRouting:t,response:(0,r.errorResponse)(o.p.BAD_REQUEST,"Auto routing is disabled. Enable it in Settings > Routing.")};let c=await f(e,n,s);return{model:e,...n,...c,isAutoRouting:t,response:null}}async function y(t,n,i){if(!t.isAutoRouting||null!==n)return n;if(!t.recognizedBuiltInAuto)return(0,r.errorResponse)(o.p.BAD_REQUEST,`Model '${t.model}' is not a valid combo or provider. Unknown built-in auto combo.`);try{let{createVirtualAutoCombo:n}=await e.A(849824),r=await n(t.variant,t.spec,i,t.model);return r.name=t.model,r.id=t.model,c.info("AUTO",`Virtual auto-combo created: ${r.name} (${r.candidatePool?.length||0} candidates)`),r}catch(e){return c.error("AUTO","Failed to create virtual auto-combo",{err:e}),null}}[i,a,s]=d.then?(await d)():d,e.s(["Z",0,y,"g",0,p]),n()}catch(e){n(e)}},!1),10641,e=>e.a(async(t,n)=>{try{var r=e.i(877621),o=e.i(428489),i=e.i(594737),a=e.i(287726),l=e.i(574835),s=e.i(192408),u=e.i(821518),c=e.i(719201),d=e.i(779170),f=e.i(998905),p=e.i(496727),y=e.i(720902),m=e.i(573344),g=e.i(563682),h=e.i(984168),b=e.i(189281),w=e.i(359756),_=e.i(838679),A=e.i(298321),I=e.i(308401),k=e.i(7228),v=e.i(110963),T=e.i(889771),R=e.i(85713),S=e.i(613775),E=e.i(878947),x=e.i(249157),$=e.i(496973),C=e.i(656368),O=e.i(403098),M=e.i(151205),L=e.i(125852),N=e.i(701554),U=e.i(245272),D=e.i(130273),B=e.i(403122),F=e.i(186920),q=e.i(984340),j=e.i(421892),K=e.i(22775),P=e.i(123751),G=e.i(957921),Q=e.i(158756),H=e.i(990338),W=e.i(375152),z=e.i(74214),Y=e.i(913577),J=e.i(546747),V=e.i(638146),X=e.i(897135),Z=e.i(760391),ee=e.i(260222),et=e.i(25687),en=e.i(306976),er=e.i(454925),eo=e.i(577122),ei=e.i(478847),ea=e.i(444063),el=e.i(548351),es=e.i(852705),eu=e.i(324348),ec=e.i(154939),ed=e.i(95360),ef=e.i(167389),ep=e.i(646629),ey=e.i(396692),em=e.i(744402),eg=e.i(470019),eh=e.i(446518),eb=e.i(903141),ew=e.i(887165),e_=e.i(238492);e.i(645035);var eA=e.i(75106),eI=e.i(283439),ek=e.i(717263),ev=e.i(338258),eT=t([o,a,l,s,d,y,b,w,_,A,$,L,U,F,K,P,G,Q,z,Y,J,Z,et,ei,e_,eA,eI,ev]);[o,a,l,s,d,y,b,w,_,A,$,L,U,F,K,P,G,Q,z,Y,J,Z,et,ei,e_,eA,eI,ev]=eT.then?(await eT)():eT,(0,ep.registerCodexQuotaFetcher)(),(0,ey.registerBailianCodingPlanQuotaFetcher)(),(0,em.f)(),(0,eg.Q)(),(0,eh.T)(),(0,eb.o)(),(0,ew.F)(),(0,e_.f)();let eM=null,eL=0,eN=-1;async function eR(){let e=Date.now();return null!==eM&&e-eL<1e4&&eN===(0,B.getCombosCacheVersion)()?eM:(eL=e,eN=(0,B.getCombosCacheVersion)(),eM=(0,M.e)().catch(()=>[]))}function eS(e){if(!Array.isArray(e))return null;let t=e.filter(e=>"string"==typeof e&&e.trim().length>0);return t.length>0?t:null}function eE(e,t){let n=eS(e),r=eS(t);return n&&r?n.filter(e=>r.includes(e)):n||r||null}let eU={updateCombo:M.a,info:x.info,warn:x.warn};async function ex(e,t=null,n=null,r){let o=await e$(e,t,n,r),i="";try{i=new URL(e?.url).pathname}catch{i=""}let a=/\/messages\/?$/.test(i)?"claude":"openai",l=await (0,S.k)(function(e,t){if("claude"===t||!e||529!==e.status)return e;let n=new Headers(e.headers);return n.delete("content-length"),new Response(e.body,{status:T.p.SERVICE_UNAVAILABLE,headers:n})}(o,a),a),s=t?.body?.model??n?.model;return"string"==typeof s&&s.trim()?(0,_.B)(l,{requestedModel:s}):l}async function e$(t,n=null,u=null,w){let v,S=(0,C.s)(t?.headers,x.warn,c.errorResponse);if(S)return S;let $=w||(0,eo.s)(),O=new er.RequestTelemetry($),M=(0,ek.f)();if(M.shouldReject)return x.warn("BACKPRESSURE","Rejecting request: at connection limit"),M.response;try{O.startPhase("parse"),v=await (0,r.f)(t,u),O.endPhase()}catch{return x.warn("CHAT","Invalid JSON body"),(0,c.errorResponse)(T.p.BAD_REQUEST,"Invalid JSON body")}v=(0,o.I)(v);let U=(0,R.R)(v,t.url),D=v;if("messages"in D&&!Array.isArray(D.messages))return x.warn("CHAT","Rejecting request with non-array messages"),(0,c.errorResponse)(T.p.BAD_REQUEST,"messages: Expected array");if(Array.isArray(D.messages)&&0===D.messages.length)return x.warn("CHAT","Rejecting request with empty messages array"),(0,c.errorResponse)(T.p.BAD_REQUEST,"messages: at least one message is required");if(!("messages"in D)&&!("input"in D)&&"antigravity"!==U)return x.warn("CHAT","Rejecting request with missing messages"),(0,c.errorResponse)(T.p.BAD_REQUEST,"messages: Expected array, received undefined");let q=v.model;if(null!=q&&"string"!=typeof q)return x.warn("CHAT",`Rejecting non-string model (typeof=${typeof q})`),(0,c.errorResponse)(T.p.BAD_REQUEST,`model: Expected string, received ${Array.isArray(q)?"array":typeof q}`);{let e=v,t=(e,t)=>(0,c.errorResponse)(T.p.BAD_REQUEST,`${e}: ${t}`);if(void 0!==e.temperature){if("number"!=typeof e.temperature||Number.isNaN(e.temperature))return t("temperature","must be a number");if(e.temperature<0||e.temperature>2)return t("temperature","must be between 0 and 2")}if(void 0!==e.top_p){if("number"!=typeof e.top_p||Number.isNaN(e.top_p))return t("top_p","must be a number");if(e.top_p<0||e.top_p>1)return t("top_p","must be between 0 and 1")}if(void 0!==e.max_tokens&&("number"!=typeof e.max_tokens||!Number.isInteger(e.max_tokens)||e.max_tokens<1))return t("max_tokens","must be a positive integer");if(void 0!==e.n&&("number"!=typeof e.n||!Number.isInteger(e.n)||e.n<1))return t("n","must be a positive integer")}n||(n=(0,ev.X)(t,v));let j=new URL(t.url),K=(0,g._)(v,{claudeFormat:j.pathname.includes("/messages")});K.applied&&x.debug("NO_THINKING",`Resolved no-thinking alias → ${K.realModel}`);let Q=(0,i.F)(t,v),H=await (0,h.f)(Q);H.stripped&&(x.debug("CC_DISCOVERY",`Resolved cc discovery alias: ${Q} → ${H.model}`),Q=H.model);let V=(0,W.D)(Q,v);v=i.R.align(v,Q,x);let X=v.messages?.length||v.input?.length||0,Z=v.tools?.length||0,ee=v.reasoning_effort||v.reasoning?.effort||null;x.request("POST",`${j.pathname} | ${Q} | ${X} msgs${Z?` | ${Z} tools`:""}${ee?` | effort=${ee}`:""}`);let et=t.headers.get("Authorization"),ed=(0,a.t)(t);et&&ed?x.debug("AUTH","API key provided"):x.debug("AUTH","No API key provided (local mode)");let ef=await (0,el.N)(t,v);if(ef)return(0,er.recordTelemetry)(O),ef;let ep=t.headers?.get?.("x-internal-test")==="combo-health-check";if(!Q)return x.warn("CHAT","Missing model"),(0,c.errorResponse)(T.p.BAD_REQUEST,"Missing model");let ey=(0,m.O)(Q),em=!!ey&&(0,E.getModelsByProviderId)(ey.provider).some(e=>e.id===ey.model);if(ey&&!em)return x.warn("CHAT",`Rejecting image-generation model on chat endpoint: ${Q}`),(0,c.errorResponse)(T.p.BAD_REQUEST,`Model '${Q}' is an image-generation model and cannot be used on /v1/chat/completions. Use POST /v1/images/generations instead.`);let eg=(0,ec.extractExternalSessionId)(t.headers)||(0,ec.generateSessionId)(v),eh=(0,a.J)(v,t.headers)||eg,eb=t.headers.get("x-trouteai-connection")?.trim()||null;eg&&(0,ec.touchSession)(eg),O.startPhase("policy");let ew=await (0,ei.r)(t,Q);if(ew.rejection)return x.warn("POLICY",`API key policy rejected: ${Q} (key=${ew.apiKeyInfo?.id||"unknown"})`),ew.rejection;let e_=ew.apiKeyInfo,eA=(0,ea.f)(e_?.scopes);O.endPhase(),O.startPhase("validate");let eT=await P.Q.runPreCallHooks(v,{apiKeyInfo:e_,disabledGuardrails:(0,P.W)({apiKeyInfo:e_??null,body:v,headers:t.headers}),endpoint:new URL(t.url).pathname,headers:t.headers,log:x,method:t.method,model:Q,stream:v?.stream===!0});if(eT.blocked)return x.warn("GUARDRAIL","Request blocked during pre-call guardrails",{guardrail:eT.guardrail,message:eT.message}),(0,c.errorResponse)(T.p.BAD_REQUEST,eT.message||"Request rejected: suspicious content detected");let eS="string"==typeof v?.model&&v.model.length>0?v.model:Q;if(v=eT.payload,{body:v,modelStr:Q}=await i.R.reconcileGuardrailReroute({body:v,modelBeforeGuardrails:eS,modelStr:Q,apiKey:ed,apiKeyId:e_?.id,isModelAllowedForKey:L.isModelAllowedForKey,log:x}),O.endPhase(),e_?.id&&eg){let e="number"==typeof e_.maxSessions&&e_.maxSessions>0?e_.maxSessions:0;if(e>0&&!(0,ec.isSessionRegisteredForKey)(e_.id,eg)){let t=(0,ec.checkSessionLimit)(e_.id,e);if(t)return(0,G.t)((0,c.errorResponse)(T.p.RATE_LIMITED,t.message),eg);(0,ec.registerKeySession)(e_.id,eg)}}let eO=Q;if((0,es.getTaskRoutingConfig)().enabled){O.startPhase("task-route");let e=(0,es.applyTaskAwareRouting)(Q,v);e.wasRouted?(eO=e.model,v={...v,model:e.model},x.info("T05",`Task-Aware: detected="${e.taskType}" → model override: ${Q} → ${e.model}`)):"chat"!==e.taskType&&x.debug("T05",`Task-Aware: detected="${e.taskType}" (no override configured)`),e.taskType,e.wasRouted,O.endPhase()}if((0,eu.W)(v)){let e=await (0,B.getCachedSettings)().catch(()=>({})),t=(0,eu.s)(eO,v,e);t.wasRouted&&(x.info("WEBSEARCH-ROUTE",`web_search tool → model override: ${eO} → ${t.model}`),eO=t.model,v={...v,model:t.model})}if(U===p.f.CLAUDE&&(0,y.n)(v)&&"0"!==process.env.TROUTEAI_WEB_SEARCH_EMULATION&&await (0,y.X)(eO))return x.info("WEBSEARCH",`${eO} has no web search / fetch of its own; TRouteAI runs it`),(0,er.recordTelemetry)(O),(0,y.d)({request:t,body:{...v,model:eO},callModel:e=>ex(t,null,e,w),apiKeyId:e_?.id??null,log:x});let eM=null,eL={tags:[]},eN=await (0,z.i)({request:t,body:v,modelStr:eO,policy:ew,apiKeyInfo:e_,reasoningIntent:V});if(eN.response)return eN.response;v=eN.body,eO=eN.modelStr,eM=eN.reasoningDecision,eL=eN.requestRoutingTags;let eD=await (0,Y.g)(eO);if(eD.response)return eD.response;O.startPhase("resolve");let eB=await (0,s.Q)(eO);if(eM?.targetCombo&&(eB=eM.targetCombo),!eB&&eO.startsWith("auto/")){let e=eO.slice(5);for(let t of[`auto/best-${e}`,`auto/${e}`])if(eB=await (0,s.Q)(t)){x.info("ROUTING",`"${eO}" → combo "${t}" (auto fuzzy)`);break}}let eF=await (0,Y.Z)(eD,eB,e_?.id);if(eF instanceof Response)return eF;if(eB=eF){if(eM){let e=(0,z.d)(eB,eM);if(e instanceof Response)return e;eB=e}if(Array.isArray(eB.models)&&eB.models.some(f.l)){let e=eB.models.filter(e=>!(0,f.l)(e));if(0===e.length)return(0,c.errorResponse)(T.p.SERVICE_UNAVAILABLE,`All steps of combo '${eB.name}' are turned off. Turn one on in Dashboard > Combos.`);eB={...eB,models:e}}x.info("CHAT",`Combo "${Q}" [${eB.strategy||"priority"}] with ${eB.models.length} models`);let r=new Map,o=null,i=[],u=!0,p=new Map,y=(e,t)=>`${t?.executionKey||t?.connectionId||""}:${e}`,m=async(e,t)=>{if(ep)return!0;let n=await (0,s.M)(e),l=!t?.providerId||t.providerId===n.provider||e.startsWith(t.providerId+"/")?n.provider:t.providerId;if(!l)return!0;let c=n.model||e,d=`${l}\0${c}`;if(!p.has(d)){let e=!1;try{e=(0,F.J)(l,c)}catch{}p.set(d,e)}if(p.get(d))return!1;"string"==typeof t?.connectionId&&t.connectionId.trim().length;let f=eE(e_?.allowedConnections??null,t?.allowedConnectionIds??null);if(e_?.allowedQuotas&&e_.allowedQuotas.length>0){let e=await (0,eI.resolveQuotaKeyScope)(e_.allowedQuotas);f=(0,eI.constrainConnectionsToQuota)(f??[],e.connectionIds)}if(Array.isArray(f)&&0===f.length)return!1;let m=await (0,a.m)(l,null,f,c,{sessionKey:eh,...t?.allowRateLimitedConnection?{allowRateLimitedConnections:!0}:{},...t?.connectionId?{forcedConnectionId:t.connectionId}:{},...eA?{bypassQuotaPolicy:!0}:{}});if(!m||m.allRateLimited){let e,t,n;return m?.allRateLimited&&(e=Number(m?.cooldownStatus)||Number(m?.lastErrorCode)||429,i.push(e),429===e&&m?.cooldownReason!=="quota_exhausted"&&(u=!1),!(!Number.isFinite(n="string"==typeof(t=m?.retryAfter)||t instanceof Date?new Date(t).getTime():0/0)||n<=Date.now())&&(null===o||n<o)&&(o=n)),!1}return r.set(y(e,t),m),!0},[g,h]=await Promise.all([(0,B.getCachedSettings)().catch(()=>({})),eR()]),w=Array.isArray(h)?h.map(e=>Array.isArray(e?.models)&&e.models.some(f.l)?{...e,models:e.models.filter(e=>!(0,f.l)(e))}:e):h,R="context-relay"===eB.strategy?(0,k.N)(eB,g):null,S=(0,I.D)(t.headers),E="context-relay"===eB.strategy||eA||Object.keys(S).length>0?{..."context-relay"===eB.strategy?{sessionId:eg,config:R}:{},...eA?{bypassProviderQuotaPolicy:!0}:{},...S}:void 0;O.endPhase();let C=await b.f({body:v,combo:eB,handleSingleModel:(e,o,i)=>eC(e,o,n,t,eB.name,e_,O,{sessionId:eg,sessionAffinityKey:eh,forceLiveComboTest:ep,forcedConnectionId:i?.connectionId??null,allowedConnectionIds:i?.allowedConnectionIds??null,comboStepId:i?.stepId||null,comboExecutionKey:i?.executionKey||i?.stepId||null,skipUpstreamRetry:i?.failoverBeforeRetry??!1,allowRateLimitedConnection:i?.allowRateLimitedConnection===!0,preselectedCredentials:r.get(y(o,i)),cachedSettings:g,providerId:i?.providerId??null,correlationId:$,modelPinned:i?.modelPinned??!1,reasoningDecision:eM,reasoningIntent:V,reasoningRequestTags:eL.tags,modelAbortSignal:i?.modelAbortSignal??null},i?.effectiveComboStrategy??eB.strategy,!0).then(async e=>(e?.ok&&await (0,N.f)(eB,o,g,eU),e)),isModelAvailable:m,log:x,settings:g,allCombos:w,apiKeyAllowedConnections:e_?.allowedConnections??null,relayOptions:E,signal:t?.signal??null,correlationId:$,priority:(0,en.W)(t?.headers?.get?.("x-trouteai-priority")??null,e_?.defaultPriority)});if(!C.ok&&[502,503].includes(C.status)&&"string"==typeof g?.globalFallbackModel&&g.globalFallbackModel.trim()){let e=g.globalFallbackModel.trim();x.info("GLOBAL_FALLBACK",`Combo "${eB.name}" exhausted — attempting global fallback: ${e}`);try{let r=await (0,A.f)({fallback:"global",attempts:Array.isArray(eB.models)?eB.models.length:1},()=>eC(v,e,n,t,eB.name,e_,O,{sessionId:eg,sessionAffinityKey:eh,emergencyFallbackTried:!0,forceLiveComboTest:ep},eB.strategy,!0));if(r.ok)return x.info("GLOBAL_FALLBACK",`Global fallback ${e} succeeded`),(0,er.recordTelemetry)(O),(0,G.t)((0,_.B)(r,{fallback:"global",fallbackAttempts:Array.isArray(eB.models)?eB.models.length:1}),eg);x.warn("GLOBAL_FALLBACK",`Global fallback ${e} also failed (${r.status})`)}catch(e){x.warn("GLOBAL_FALLBACK",`Global fallback error: ${e?.message||"unknown"}`)}}if(!C.ok&&503===C.status&&null!==o&&o>Date.now()&&"ALL_ACCOUNTS_INACTIVE"===await C.clone().json().then(e=>e?.error?.code??null).catch(()=>null)){let e=new Date(o).toISOString(),t=(0,d.k)(i,T.p.RATE_LIMITED);C=t===T.p.RATE_LIMITED?(0,c.unavailableResponse)(T.p.RATE_LIMITED,`All accounts of combo '${eB.name}' have reached their usage limit; the next one is usable at ${e}`,e,(0,l.RG)(e),{usageLimit:u}):(0,c.unavailableResponse)(t,`Every model of combo '${eB.name}' is cooling down after upstream errors`,e,(0,l.RG)(e))}if((0,er.recordTelemetry)(O),!C.ok)try{let{recordRejectedRequestUsage:t,resolveRejectedComboProvider:r}=await e.A(353104);await t({status:C.status,model:v?.model||eO,requestedModel:v?.model||eO,provider:r(v?.model||eO,eB.name),endpoint:n?.endpoint,error:await (0,J.f)(C,eB.name),comboName:eB.name,apiKeyId:e_?.id??null,apiKeyName:e_?.name??null,correlationId:$,startTime:O?.startTime,requestBody:n?.body??null})}catch{}return(0,G.v)((0,G.t)(C,eg),$)}O.endPhase();let eq=null;if(!eB){let t=eO.split("/")[0];if(t)try{let{getComboByName:n}=await e.A(605589),r=await n(t);r?.id&&(eq=r.id)}catch{}}let ej=await eC(v,eO,n,t,null,e_,O,{sessionId:eg,sessionAffinityKey:eh,forceLiveComboTest:ep,forcedConnectionId:eb,correlationId:$,routingComboId:eq,reasoningDecision:eM,reasoningIntent:V,reasoningRequestTags:eL.tags},null,!1);return(0,er.recordTelemetry)(O),(0,G.v)((0,G.t)(ej,eg),$)}async function eC(...e){let t=await eO(...e);if(!t||t.ok)return t;let n="string"==typeof e[1]?e[1]:"",r=n.indexOf("/");return(0,_.B)(t,{model:r>0?n.slice(r+1):n,provider:r>0?n.slice(0,r):null})}async function eO(t,n,r=null,o=null,i=null,s=null,d=null,f={},p=null,y=!1){let m=await (0,G.X)(n,t,r?.endpoint,r?.headers);if(m.error)return m.error;if(m.combo){let e=m.combo;return x.info("ROUTING",`Safety-net combo redirect for "${n}" → combo="${e.name}"`),x.info("ROUTING",`Auto-combo redirect from handleSingleModelChat for "${n}"`),x.info("ROUTING",`Auto-combo redirect to combo flow for "${n}"`),(0,b.f)({body:t,combo:e,handleSingleModel:(t,i,a)=>eC(t,i,r,o,e.name??n,s,d,{sessionId:"",forceLiveComboTest:!1,forcedConnectionId:null,allowedConnectionIds:null,comboStepId:null,comboExecutionKey:null,skipUpstreamRetry:a?.failoverBeforeRetry??!1,allowRateLimitedConnection:a?.allowRateLimitedConnection===!0,providerId:a?.providerId??null,correlationId:f?.correlationId??null,modelAbortSignal:a?.modelAbortSignal??null},a?.effectiveComboStrategy??e.strategy??"priority",!1),isModelAvailable:async()=>!0,log:x,settings:{},allCombos:[],relayOptions:void 0,signal:o?.signal??null,correlationId:f?.correlationId??null})}let{provider:g,model:h,sourceFormat:I,targetFormat:k,extendedContext:S,apiFormat:C}=m,M=!f.providerId||f.providerId===g||n.startsWith(f.providerId+"/")?g:f.providerId,L=!0===f.forceLiveComboTest;if(!L){let e=!1;try{e=(0,F.J)(M,h)}catch{}if(e)return x.warn("CHAT",`Model ${M}/${h} is turned off`,{model:n}),(0,c.errorResponse)(T.p.NOT_FOUND,`Model '${M}/${h}' is turned off. Turn it on in Dashboard > Providers.`)}let N=(0,ea.f)(s?.scopes),U="string"==typeof f.forcedConnectionId&&f.forcedConnectionId.trim().length>0,K=eE(s?.allowedConnections??null,f.allowedConnectionIds??null);if(s?.allowedQuotas&&s.allowedQuotas.length>0){let e=await (0,eI.resolveQuotaKeyScope)(s.allowedQuotas);K=(0,eI.constrainConnectionsToQuota)(K??[],e.connectionIds)}let P=L?"combo live test":U?"fixed combo step connection":void 0,W=await (0,l.aP)(M),Y=await (0,G.J)(M,h,{ignoreCircuitBreaker:L||U,ignoreModelCooldown:L||U,providerProfile:W,...P?{bypassReason:P}:{}});if(Y){try{let{recordRejectedRequestUsage:o}=await e.A(353104);await o({status:Y.status,model:h,requestedModel:t?.model||n,provider:M,endpoint:r?.endpoint,error:`[${Y.status}] Pipeline gate rejected`,comboName:y?i:null,comboStepId:y?f?.comboStepId??null:null,comboExecutionKey:y?f?.comboExecutionKey??null:null,apiKeyId:s?.id??null,apiKeyName:s?.name??null,correlationId:f?.correlationId??null,startTime:d?.startTime})}catch{}return Y}let J=(0,Z.f)(M,W.useUpstream429BreakerHints),en=(0,ee.getCircuitBreaker)(M,{failureThreshold:W.failureThreshold,resetTimeout:W.resetTimeoutMs,isFailure:e=>!(0,ee.isLocalStreamLifecycleError)(e),onStateChange:(e,t,n)=>x.info("CIRCUIT",`${e}: ${t} → ${n}`),...J?{cooldownByKind:{rate_limit:6e4,quota_exhausted:36e5},classifyError:V.Z}:{}}),er=o?.headers?.get("user-agent")||"",eo=f.cachedSettings??await (0,B.getCachedSettings)().catch(()=>({})),ei=(0,eA.z)(eo),el=(0,eA.n)(ei,"claude-web"===M||y||L||!0===f.emergencyFallbackTried),es=o?.signal??null,eu=el.budgetMs;if(Array.isArray(K)&&0===K.length)return x.debug("AUTH",`${M}/${h} filtered out by connection-level routing constraints`),(0,c.errorResponse)(T.p.SERVICE_UNAVAILABLE,"No eligible connections matched the requested routing constraints");let ey=0,em=null,eg=null,eh=0;e:for(;;){let m=new Set,g=em,b=eg,B=f.preselectedCredentials;for(;;){let F=B&&0===m.size?B:await (0,a.m)(M,null,K,h,{sessionKey:f.sessionAffinityKey??f.sessionId??null,excludeConnectionIds:Array.from(m),...f.allowRateLimitedConnection?{allowRateLimitedConnections:!0}:{},...L?{allowSuppressedConnections:!0,bypassQuotaPolicy:!0}:{},...!L&&N?{bypassQuotaPolicy:!0}:{},...f.forcedConnectionId?{forcedConnectionId:f.forcedConnectionId}:{}});if(B=null,!F||"allRateLimited"in F||!F.connectionId){if(F?.allRateLimited){let e=(0,eA.Q)({retryAfter:F.retryAfter,settings:el,attempt:ey,budgetLeftMs:eu});if(e.shouldRetry){let t=Math.max(Math.ceil(e.waitMs/1e3),0);if(x.info("COOLDOWN_RETRY",`${M}/${h} all connections cooling down (${e.retryAfterHuman||`retry in ${t}s`}) — waiting ${t}s before retry ${ey+1}/${el.maxRetries}`),!await (0,eA.A)(e.waitMs,es))return x.info("COOLDOWN_RETRY",`${M}/${h} retry wait aborted by client disconnect`),(0,c.errorResponse)(499,"Request aborted");ey+=1,eu=Math.max(0,eu-e.waitMs),x.info("COOLDOWN_RETRY",`${M}/${h} cooldown elapsed — restarting request attempt ${ey}/${el.maxRetries}`);continue e}}let t=Number(b??F?.lastErrorCode);!L&&F?.allRateLimited&&Q.E.has(t)&&en._onFailure();let r=null;if(!F&&!i&&0===m.size&&!g)try{let{getProviderConnections:t}=await e.A(605589),o=await t({provider:M});if(0===o.length){let{listComboNames:t,noServeSentence:o}=await e.A(989075);r=o(n,await t())}}catch{r=null}let o=(0,G.P)(F,m.size>0?Array.from(m)[0]:null,M,h,g,b,r),a=m.size>0?Array.from(m)[m.size-1]:null;return(0,G.E)(o,a)}let P=F.connectionId.slice(0,8);x.info("AUTH",`Using ${M} account: ${P}...`);let Y=(0,u.v)(n,h,F.defaultModel,{anyBareName:(0,u.m)(eo)})??h,J=Y!==h?{...t,model:`${M}/${Y}`}:t;if(!f.reasoningDecision&&f.reasoningIntent){let e=await (0,z.L)({requestBody:J,provider:M,effectiveModel:Y,credentials:F,apiKeyInfo:s,reasoningIntent:f.reasoningIntent,reasoningDecision:f.reasoningDecision,requestRoutingTags:f.reasoningRequestTags});if(e.response)return e.response;J=e.body}let Z=null;if("context-relay"===p&&i&&f.sessionId&&t?._trouteaiSkipContextRelay!==!0){let e=(0,O.x)(f.sessionId,i);e&&e.fromAccount!==F.connectionId&&(J=(0,v.w)(J,e),Z=e,x.info("CONTEXT_RELAY",`Injecting handoff for session ${f.sessionId}: ${e.fromAccount.slice(0,8)} -> ${F.connectionId.slice(0,8)}`))}let ee=await (0,$.B)(M,F),ei=(0,j.c)(ee?.providerSpecificData??F?.providerSpecificData);if("codex"===M&&ei&&f.sessionId&&(J=(0,j.T)(J,f.sessionId)),"codex"===M&&ee?.accessToken&&F.connectionId){let e="string"==typeof ee?.providerSpecificData?.workspaceId&&ee.providerSpecificData.workspaceId.trim().length>0?ee.providerSpecificData.workspaceId:"string"==typeof F?.providerSpecificData?.workspaceId&&F.providerSpecificData.workspaceId.trim().length>0?F.providerSpecificData.workspaceId:void 0;(0,ep.registerCodexConnection)(F.connectionId,{accessToken:ee.accessToken,...e?{workspaceId:e}:{}})}f.sessionId&&t?._trouteaiInternalRequest!=="context-handoff"&&((0,ec.touchSession)(f.sessionId,F.connectionId),(0,ed.y)(f.sessionId,M,F.connectionId,ee));let ea=await (0,G.K)(F.connectionId,s?.id,M),eb={proxy:null},ew=Date.now();d&&d.startPhase("connect");let e_=(0,ev.j)(r,f.modelAbortSignal),{result:eI,tlsFingerprintUsed:ek}=await (0,G.O)({bypassCircuitBreaker:L||U,breaker:en,body:J,provider:M,model:Y,refreshedCredentials:ee,proxyInfo:ea,appliedProxySink:eb,log:x,clientRawRequest:e_,credentials:F,apiKeyInfo:s,userAgent:er,comboName:i,comboStrategy:p,isCombo:y,comboStepId:f.comboStepId??null,comboExecutionKey:f.comboExecutionKey??f.comboStepId??null,extendedContext:S,modelApiFormat:C,providerProfile:W,cachedSettings:f.cachedSettings,skipUpstreamRetry:f.skipUpstreamRetry??!1,correlationId:f?.correlationId??null,modelPinned:f?.modelPinned??!1,routingComboId:f?.routingComboId??null});d&&d.endPhase();let eT=Date.now()-ew,eR=E.PROVIDER_ID_TO_ALIAS[M]||M,eS=(0,E.getModelTargetFormat)(eR,h)||(0,R.a)(M,F.providerSpecificData)||k;if((0,G.D)({result:eI,proxyInfo:(0,G._)(ea,eb.proxy),proxyLatency:eT,provider:M,model:h,sourceFormat:I,targetFormat:eS,credentials:F,comboName:i,clientRawRequest:r,tlsFingerprintUsed:ek}),eI.success)return(0,l.m5)(M,F.connectionId,h),L||en._onSuccess(),Z&&f.sessionId&&i&&(0,O.v)(f.sessionId,i),d&&d.startPhase("finalize"),d&&d.endPhase(),eI.response;if((0,Q.L)(M,eI))return(0,G.E)(eI.response,F.connectionId);let eE="antigravity"===M&&("STREAM_READINESS_TIMEOUT"===eI.errorCode||"STREAM_EARLY_EOF"===eI.errorCode||"stream_timeout"===eI.errorType||"stream_early_eof"===eI.errorType);if(("stream_timeout"===eI.errorType||"stream_early_eof"===eI.errorType)&&!eE){if((0,G.N)(eI.errorCode,eh)&&!U){eh+=1,x.warn("STREAM",`${M}/${h} closed the stream early before useful content — retrying once (attempt ${eh})`);continue}return(0,G.E)(eI.response,F?.connectionId)}if(eE){let{shouldFallback:e,cooldownMs:t}=await (0,a.p)(F.connectionId,eI.status||T.p.BAD_GATEWAY,eI.error||eI.errorCode||"Antigravity stream ended before useful content",M,h,W,{isCombo:y});if(e&&!U){if(x.warn("AUTH",`Antigravity connection ${P}... produced no useful stream content, trying fallback connection`),Number.isFinite(t),f.sessionAffinityKey)try{let e=(0,D.getSessionAccountAffinity)(f.sessionAffinityKey,M);e?.connectionId===F.connectionId&&(0,D.deleteSessionAccountAffinity)(f.sessionAffinityKey,M)}catch{}m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}return(0,G.E)(eI.response,F?.connectionId)}if("antigravity"===M&&eI.status===T.p.GATEWAY_TIMEOUT&&("upstream_timeout"===eI.errorType||eI.errorCode===T.D)){let{shouldFallback:e,cooldownMs:t}=await (0,a.p)(F.connectionId,eI.status,eI.error||T.D,M,h,W,{isCombo:y});if(e&&!U){if(x.warn("AUTH",`Antigravity connection ${P}... timed out before response headers, trying fallback connection`),Number.isFinite(t),f.sessionAffinityKey)try{let e=(0,D.getSessionAccountAffinity)(f.sessionAffinityKey,M);e?.connectionId===F.connectionId&&(0,D.deleteSessionAccountAffinity)(f.sessionAffinityKey,M)}catch{}m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}return(0,G.E)(eI.response,F?.connectionId)}if("RATE_LIMIT_COOLDOWN"===eI.errorCode){if(U)return(0,G.E)(eI.response,F?.connectionId);m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}if("account_semaphore_capacity"===eI.errorType){if(U)return(0,G.E)(eI.response,F?.connectionId);x.warn("AUTH",`Account ${P}... at local concurrency cap, trying fallback account`),m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}if(!f.emergencyFallbackTried&&!i){let e=(0,ef.i)(Number(eI.status||0),String(eI.error||""),Array.isArray(t?.tools)&&t.tools.length>0);if((0,ef.g)(e)){let n=`${e.provider}/${e.model}`,a=`${M}/${h}`;if(n!==a){let l={...t,model:n},u=Math.min(Number(l.max_tokens??l.max_completion_tokens??e.maxOutputTokens)||e.maxOutputTokens,e.maxOutputTokens);l.max_tokens=u,l.max_completion_tokens=u,x.warn("EMERGENCY_FALLBACK",`${a} -> ${n} | reason=${e.reason}`);let c=await (0,A.f)({fallback:"emergency",attempts:1},()=>eC(l,n,r,o,i,s,d,{...f,emergencyFallbackTried:!0,forcedConnectionId:null,comboStepId:null,comboExecutionKey:null},null,!!i));if(c.ok)return(0,_.B)(c,{fallback:"emergency",fallbackAttempts:1});x.warn("EMERGENCY_FALLBACK",`Emergency fallback to ${n} failed with status ${c.status}. Resuming original provider account fallback.`)}}}let ex=!1,e$=String(eI.rawMessage??eI.error??""),eO=429===eI.status?(0,X.M)(e$.toLowerCase(),M)?"quota_exhausted":(0,V.Z)({status:eI.status,message:e$}):void 0;if(429===eI.status&&(0,l.P5)(e$)){let e=e$.match(/today's quota for model ([^,]+)/),t=e?e[1].trim():h,n=(0,q.f)(f.cachedSettings);if(n.enabled&&n.errorCodes.includes(eI.status)){let e=(0,l.nz)(M,F.connectionId,t,"quota_exhausted",eI.status,0,W,{maxCooldownMs:n.maxCooldownMs});x.info("MODEL_DAILY_QUOTA",JSON.stringify({connection:F.connectionId.slice(0,8),model:t,cooldownMs:e.cooldownMs,failureCount:e.failureCount}))}ex=!0}if(!ex){let e=F.providerSpecificData?.passthroughModels;429===eI.status&&(0,l.jE)(M,h,e,eO)&&(0,et.markAccountExhaustedFrom429)(F.connectionId,M)}let eM=(F.providerSpecificData?.extraApiKeys??[]).length>0||(0,H.V)(F.connectionId),eL=401===eI.status,{shouldFallback:eN,cooldownMs:eU}=(0,w.r)(eI,eL,eM,M)?{shouldFallback:!1,cooldownMs:0}:(0,w.Y)(eI.status,e$)?{shouldFallback:!0,cooldownMs:0}:await (0,a.p)(F.connectionId,eI.status,e$,M,h,W,{persistUnavailableState:!(y&&429===eI.status&&("rate_limit"===eO||"transient"===eO)),isCombo:y});if(eN){if(Number.isFinite(eU),x.warn("AUTH",Number.isFinite(eU)&&eU>0?`Account ${P}... unavailable (${eI.status}, cooldown ${Math.ceil(eU/1e3)}s), trying fallback`:`Account ${P}... failed (${eI.status}, no cooldown), trying fallback`),f.sessionAffinityKey)try{(0,D.evictSessionAccountAffinityForConnection)(f.sessionAffinityKey,M,F.connectionId)}catch{}m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}return(0,Q.x)(eI,y,L)&&en._onFailure(),(0,G.E)(eI.response,F?.connectionId)}}}e.s(["f",0,ex]),n()}catch(e){n(e)}},!1),338258,e=>e.a(async(t,n)=>{try{var r=e.i(268263),o=e.i(54092),i=t([r,o]);[r,o]=i.then?(await i)():i,e.s(["X",0,function(e,t){return{endpoint:new URL(e.url).pathname,body:(0,o.Z)(t),headers:Object.fromEntries(e.headers.entries()),signal:e.signal??null}},"j",0,function(e,t){return t?{...e,signal:e?.signal?(0,r.G)(e.signal,t):t}:e}]),n()}catch(e){n(e)}},!1),158756,e=>e.a(async(t,n)=>{try{var r=e.i(260222),o=e.i(546747),i=e.i(359756),a=t([o,i]);[o,i]=a.then?(await a)():a;let l=new Set([408,500,502,503,504]);e.s(["E",0,l,"L",0,function(e,t){return"antigravity"===e&&422===t.status&&"missing_project_id"===t.errorCode&&"oauth_missing_project_id"===t.errorType},"x",0,function(e,t,n){return!n&&!t&&!(0,i.D)({code:e.errorCode,type:e.errorType})&&!(0,r.isLocalStreamLifecycleError)(e.error)&&l.has(Number(e.status))}]),n()}catch(e){n(e)}},!1),546747,e=>e.a(async(t,n)=>{try{var r=e.i(359756),o=t([r]);async function i(e,t){let n=`[${e.status}] Combo "${t}" failed`;try{let t=await e.clone().json(),r=t?.error?.message;return"string"==typeof r&&r.trim()?`[${e.status}] ${r.trim()}`:n}catch{return n}}[r]=o.then?(await o)():o,e.s(["f",0,i]),n()}catch(e){n(e)}},!1),74214,e=>e.a(async(t,n)=>{try{var r=e.i(192408),o=e.i(719201),i=e.i(889771),a=e.i(478847),l=e.i(100435),s=e.i(249157),u=e.i(375152),c=t([r,a]);async function d(e){try{return await (0,u.t)(e)}catch(e){return s.error("REASONING_ROUTE","Failed to resolve reasoning routing policy",{error:e}),{error:(0,o.errorResponse)(i.p.BAD_REQUEST,"Reasoning routing policy could not be resolved")}}}async function f({request:e,body:t,modelStr:n,policy:c,apiKeyInfo:p,reasoningIntent:y}){let m=y||(0,u.D)(n,t),g=await (0,r.Q)(m.model),h=[];if(!g){let e=await (0,u.X)(m.model,r.M);m.model=e.normalized,h=e.aliases}let b=(0,l.O)(t),w=await d({sourceModel:m.model,sourceModelAliases:h,sourceEffort:m.sourceEffort,hasReasoningSignal:m.hasReasoningSignal,hasThinkingBudget:m.hasThinkingBudget,apiKeyId:p?.id??null,comboId:"string"==typeof g?.id?g.id:null,requestTags:b.tags});if(!w)return{body:t,modelStr:n,reasoningIntent:m,reasoningDecision:null,requestRoutingTags:b,response:null};if("error"in w)return{body:t,modelStr:n,reasoningIntent:m,reasoningDecision:null,requestRoutingTags:b,response:w.error};let _=await ("unsupported"===w.capability&&!w.targetCombo?{response:(0,o.errorResponse)(i.p.BAD_REQUEST,`Reasoning effort '${w.targetEffort}' is not supported by the configured target`)}:(0,a.V)(e,c.apiKey,p,w.targetModel).then(e=>{if(e)return s.warn("REASONING_ROUTE",`Rule ${w.rule.id} target rejected by API key policy`),{response:e};for(let e of(s.info("REASONING_ROUTE",`Rule ${w.rule.id}: ${w.sourceModel}/${w.sourceEffort} → ${w.targetModel}/${w.targetEffort||"inherit"}`),w.warnings))s.warn("REASONING_ROUTE",`Rule ${w.rule.id}: ${e}`);return{body:(0,u.G)(t,w),modelStr:w.targetModel,response:null}}));return _.response?{body:t,modelStr:n,reasoningIntent:m,reasoningDecision:w,requestRoutingTags:b,response:_.response}:{body:_.body,modelStr:_.modelStr,reasoningIntent:m,reasoningDecision:w,requestRoutingTags:b,response:null}}async function p({requestBody:e,provider:t,effectiveModel:n,credentials:r,apiKeyInfo:a,reasoningIntent:l,reasoningDecision:c,requestRoutingTags:d}){if(c||!l)return{body:e,response:null};let f=await (0,u.t)({sourceModel:l.model,sourceEffort:l.sourceEffort,hasReasoningSignal:l.hasReasoningSignal,hasThinkingBudget:l.hasThinkingBudget,apiKeyId:a?.id??null,connectionId:r.connectionId,requestTags:d??[],connectionOnly:!0,capabilityModel:`${t}/${n}`});return f?"unsupported"===f.capability?{body:e,response:(0,o.errorResponse)(i.p.BAD_REQUEST,`Reasoning effort '${f.targetEffort}' is not supported by the selected connection model`)}:(s.info("REASONING_ROUTE",`Connection rule ${f.rule.id} applied to ${r.connectionId}`),{body:(0,u.G)(e,f),response:null}):{body:e,response:null}}[r,a]=c.then?(await c)():c,e.s(["L",0,p,"i",0,f,"d",0,function(e,t){let n=(0,u.W)(e,t);return n.combo?(n.removed.length>0&&s.warn("REASONING_ROUTE",`Rule ${t.rule.id} skipped ${n.removed.length} incompatible combo target(s)`),n.combo):(0,o.errorResponse)(i.p.BAD_REQUEST,"Reasoning routing policy leaves no compatible combo target")}]),n()}catch(e){n(e)}},!1),877621,e=>{"use strict";async function t(e,n=null){return null!=n?n:await e.json()}e.s(["f",0,t])},594737,e=>{"use strict";async function t(e){let{body:t,modelBeforeGuardrails:n,apiKey:r,apiKeyId:o,isModelAllowedForKey:i,log:a}=e,{modelStr:l}=e;if(t?.model&&"string"==typeof t.model&&t.model!==n){let e=t.model;return await i(r,e)?(a.info("ROUTING",`Guardrail model reroute: ${n} → ${e}`),{body:t,modelStr:e}):(a.warn("POLICY",`Guardrail reroute to "${e}" rejected by API key policy (key=${o||"unknown"}); keeping original model "${l}"`),{body:{...t,model:l},modelStr:l})}return l&&"string"==typeof t?.model&&t.model!==l?{body:{...t,model:l},modelStr:l}:{body:t,modelStr:l}}e.s(["R",0,{align:function(e,t,n){let r,o=(r="string"==typeof e?.model?e.model:null,t&&"string"==typeof t&&0!==t.length&&r!==t?{body:{...e,model:t},aligned:!0,previousModel:r}:{body:e,aligned:!1,previousModel:r});return o.aligned&&n.info("ROUTING",`Aligned body.model to routing model: ${o.previousModel||"(none)"} → ${t}`),o.body},reconcileGuardrailReroute:t,reconcileModelOverride:function(e){let{body:t,overrideModel:n,logTag:r,log:o}=e,{modelStr:i}=e;return n&&n!==i?(o.info("ROUTING",`${r}: ${i} → ${n}`),i=n,"string"!=typeof t?.model||t.model!==i)?{body:{...t,model:i},modelStr:i}:{body:t,modelStr:i}:i&&"string"==typeof t?.model&&t.model!==i?{body:{...t,model:i},modelStr:i}:{body:t,modelStr:i}}},"F",0,function(e,t){return e.headers.get("x-route-model")?.trim()||t.model}])},720902,e=>e.a(async(t,n)=>{try{var r=e.i(666680),o=e.i(998905),i=e.i(186920),a=e.i(748648),l=e.i(780007),s=e.i(138324),u=e.i(939282),c=e.i(878947),d=e.i(892373),f=e.i(85713),p=e.i(373004),y=e.i(192408),m=t([i,a,l,s,d,y]);[i,a,l,s,d,y]=m.then?(await m)():m;let N=new Set(["kiro","openai"]);function g(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.type&&/^web_search_\d{8}$/.test(e.type)&&!e.function}function h(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.type&&/^web_fetch_\d{8}$/.test(e.type)&&!e.function}async function b(e){let t=await (0,y.M)(e).catch(()=>null),n=t?.provider;if(!n)return!1;try{return N.has(String((0,f.a)(n)))}catch{return!1}}async function w(e,t=0){if(!e||t>3)return!1;let n=await (0,y.Q)(e).catch(()=>null),r=Array.isArray(n?.models)?n.models:null;if(!r)return b(e);for(let e of r){if((0,o.l)(e))continue;if(e&&"object"==typeof e&&"combo-ref"===e.kind){if(await w(String(e.comboName||""),t+1))return!0;continue}let n=(0,o.I)(e);if(n&&await b(n))return!0}return!1}function _(e,t){let n=t.toLowerCase().replace(/^\*\./,"").replace(/^www\./,""),r=e.replace(/^www\./,"");return r===n||r.endsWith(`.${n}`)}function A(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e.trim()).map(e=>e.trim()):[]}async function I(e,t,n){let r=e=>{let n=function(e){try{return new URL(e).hostname.toLowerCase()}catch{return""}}(e);return!(!n||t.blocked.some(e=>_(n,e)))&&(!t.allowed.length||!!t.allowed.some(e=>_(n,e)))},o="";try{let{data:n}=await (0,l.f)({query:e,max_results:5,filters:{...t.allowed.length?{include_domains:t.allowed}:{},...t.blocked.length?{exclude_domains:t.blocked}:{}},apiKeyId:t.apiKeyId??null}),o=(n.results||[]).filter(e=>e?.url&&r(e.url)).map(e=>({title:e.title||e.url,url:e.url,snippet:e.snippet||"",pageAge:e.published_at?String(e.published_at):null,...e.content?.text?{pageText:String(e.content.text).slice(0,3e3)}:{}}));if(o.length)return{items:o,provider:n.provider}}catch(e){o=e instanceof Error?e.message:String(e)}let i=[e,...1===t.allowed.length?[`site:${t.allowed[0]}`]:[],...t.blocked.map(e=>`-site:${e}`)].join(" ").slice(0,400);try{return{items:(await (0,d.f)(i,8,1e4)).filter(e=>r(e.url)).slice(0,5).map(e=>({title:e.title||e.url,url:e.url,snippet:e.snippet||"",pageAge:null})),provider:"duckduckgo-free"}}catch(t){let e=t instanceof Error?t.message:String(t);throw n?.warn?.("WEBSEARCH",`search failed (${o?`${o.slice(0,120)}; `:""}free search: ${e.slice(0,120)})`),Error("web search unavailable")}}function k(e){let t=e.slice(0,786432),n=t.toLowerCase(),r=n.indexOf("<body");if(-1!==r){let e=n.indexOf(">",r),o=n.lastIndexOf("</body");t=t.slice(-1===e?r:e+1,o>r?o:void 0)}return(t=(t=(t=(t=function(e,t){let n=e.toLowerCase(),r=[...t.map(e=>({open:`<${e}`,close:`</${e}`,end:">"})),{open:"<!--",close:"-->",end:""}],o=r.map(()=>-2),i="",a=0;for(;a<e.length;){let t=-1,l=-1;for(let e=0;e<r.length;e++)-1!==o[e]&&o[e]<a&&(o[e]=n.indexOf(r[e].open,a)),-1!==o[e]&&(-1===t||o[e]<t)&&(t=o[e],l=e);if(-1===t){i+=e.slice(a);break}let s=r[l],u=n.charAt(t+s.open.length);if(s.end&&/[a-z0-9-]/.test(u)){i+=e.slice(a,t+1),a=t+1;continue}i+=`${e.slice(a,t)} `;let c=n.indexOf(s.close,t+s.open.length);if(-1===c)break;if(s.end){let t=n.indexOf(">",c);a=-1===t?e.length:t+1}else a=c+s.close.length}return i}(t,["script","style","noscript","svg","template","iframe","nav","footer","header","aside","form","head"])).replace(/<\/?(p|div|br|li|ul|ol|h[1-6]|tr|table|section|article|pre|blockquote)\b[^>]{0,500}>/gi,"\n")).replace(/<[^>]{0,2000}>/g," ")).replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/�*39;|'/gi,"'").replace(/&#(\d{1,6});/g,(e,t)=>{let n=Number(t);return n>0&&n<1114112?String.fromCodePoint(n):" "}).replace(/&/gi,"&")).split("\n").map(e=>e.replace(/[ \t\r\f\v]+/g," ").trim()).filter(e=>e.length>1).join("\n").replace(/\n{3,}/g,"\n\n")}async function v(e,t,n,r){let o=e;for(let e=0;e<5;e++){let e;if(t?.aborted)break;try{e=await (0,s.u)(o,{method:"GET",guard:"public-only",allowRedirect:!1,timeoutMs:6e3,retry:!1,headers:{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0 Safari/537.36",Accept:r}})}catch{break}if(e.status>=300&&e.status<400){let t=e.headers.get("location");if(await e.body?.cancel().catch(()=>{}),!t)return null;try{o=new URL(t,o).href}catch{return null}continue}let i=(e.headers.get("content-type")||"").toLowerCase();if(!e.ok)return await e.body?.cancel().catch(()=>{}),{status:e.status,contentType:i,bytes:Buffer.alloc(0),url:o};let a=e.body?.getReader();if(!a)return{status:e.status,contentType:i,bytes:Buffer.alloc(0),url:o};let l=[],u=0;for(;u<=n;){let{done:e,value:t}=await a.read().catch(()=>({done:!0,value:void 0}));if(e||!t)break;l.push(t),u+=t.length}return await a.cancel().catch(()=>{}),{status:e.status,contentType:i,bytes:Buffer.concat(l.map(e=>Buffer.from(e))),url:o}}return null}async function T(e,t){let n=await v(e,t,786432,"text/html,text/plain;q=0.9,*/*;q=0.5");if(!n||200!==n.status||!/text\/html|text\/plain|application\/xhtml/.test(n.contentType))return"";let r=n.bytes.subarray(0,786432).toString("utf8");return(n.contentType.includes("text/plain")?r:k(r)).slice(0,3e3)}async function R(e,t,n){let r,o=await v(e,n,0x2000000,"text/html,application/xhtml+xml,text/plain;q=0.9,application/pdf;q=0.9,*/*;q=0.5");if(!o)return{ok:!1,errorCode:"url_not_accessible"};if(429===o.status)return{ok:!1,errorCode:"too_many_requests"};if(200!==o.status)return{ok:!1,errorCode:"url_not_accessible"};let i=o.contentType;if(i.includes("application/pdf")||"%PDF-"===o.bytes.subarray(0,5).toString())return o.bytes.length>0x2000000?{ok:!1,errorCode:"content_too_large"}:{ok:!0,url:o.url,title:"",pdfBase64:o.bytes.toString("base64")};if(!(/text\/|application\/(xhtml\+xml|xml|json|javascript|x-javascript|rss\+xml|atom\+xml)/.test(i)||""===i))return{ok:!1,errorCode:"unsupported_content_type"};let a=o.bytes.subarray(0,4194304).toString("utf8"),l=/html|xml/.test(i)||/^\s*<(!doctype|html)/i.test(a.slice(0,200)),s=l?k(a.slice(0,4194304)):a;return s.length>t&&(s=`${s.slice(0,t)}
|
|
1
|
+
module.exports=[744402,e=>{"use strict";var t=e.i(190134),n=e.i(95360),r=e.i(802275),o=e.i(139908);let i=new Map;function a(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return null}async function l(e,t){let n,o=i.get(e);if(o&&Date.now()-o.fetchedAt<6e4)return o.quota;let l="string"==typeof(n=t?.apiKey)&&n.trim().length>0?n.trim():null;if(!l)return null;try{await (0,r.f)();let t=await fetch("https://crof.ai/usage_api/",{method:"GET",headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(!t.ok)return(401===t.status||403===t.status)&&i.delete(e),null;let n=await t.json(),o=function(e){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};if(0===Object.keys(t).length)return null;let n=t.usable_requests,r=null==n?null:a(n),o=a(t.credits)??0,i=0;return i=null!==r?r>0?0:1:o>0?0:1,{used:0,total:r??0,percentUsed:i,resetAt:null,usableRequests:r,credits:o}}(n);if(!o)return null;return i.set(e,{quota:o,fetchedAt:Date.now()}),o}catch{return null}}(0,o.P)("crofUsageFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of i)e-n.fetchedAt>3e5&&i.delete(t)},3e5),e.s(["f",0,function(){(0,t.s)("crof",l),(0,n.I)("crof",l)}])},167389,e=>{"use strict";var t=e.i(931680);let n=null,r=t.P,o={enabled:!0,provider:"nvidia",model:"openai/gpt-oss-120b",triggerOn402:!0,triggerOnBudgetKeywords:!0,budgetKeywords:["insufficient funds","insufficient_funds","budget exceeded","budget_exceeded","quota exceeded","quota_exceeded","billing","payment required","out of credits","no credits","credit limit","spending limit","saldo insuficiente","limite de gastos","cota excedida"],skipForToolRequests:!0,maxOutputTokens:4096};e.s(["g",0,function(e){return!0===e.shouldFallback},"i",0,function(e,t,i,a=o){if(!a.enabled)return{shouldFallback:!1,reason:"emergency fallback disabled"};if(!function(){let e,t=Date.now();if(n&&n.expiresAt>t)return n.value;try{e=r("TROUTEAI_EMERGENCY_FALLBACK")}catch(n){let t;console.warn("[emergencyFallback] Feature flag resolution failed; falling back to raw env:",n instanceof Error?n.message:n),e="true"===(t=process.env.TROUTEAI_EMERGENCY_FALLBACK)||"1"===t}return n={value:e,expiresAt:t+500},e}())return{shouldFallback:!1,reason:"emergency fallback off (TROUTEAI_EMERGENCY_FALLBACK is not true)"};if(a.skipForToolRequests&&i)return{shouldFallback:!1,reason:"skipped: request has tools"};if(a.triggerOn402&&402===e)return{shouldFallback:!0,reason:`HTTP 402 → emergency fallback to ${a.provider}/${a.model}`,provider:a.provider,model:a.model,maxOutputTokens:a.maxOutputTokens};if(a.triggerOnBudgetKeywords&&t){let e=t.toLowerCase(),n=a.budgetKeywords.find(t=>e.includes(t.toLowerCase()));if(n)return{shouldFallback:!0,reason:`Budget error detected ('${n}') → emergency fallback to ${a.provider}/${a.model}`,provider:a.provider,model:a.model,maxOutputTokens:a.maxOutputTokens}}return{shouldFallback:!1,reason:"no budget error detected"}}])},238492,e=>e.a(async(t,n)=>{try{var r=e.i(919644),o=e.i(190134),i=e.i(139908),a=t([r]);[r]=a.then?(await a)():a;let s=new Map;function l(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return null}(0,i.P)("genericQuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of s)e-n.fetchedAt>3e5&&s.delete(t)},3e5);let u=async(e,t)=>{let n;if(!t)return null;let i="string"==typeof t.provider?t.provider:null;if(!i)return null;let a=`${i}::${e}`,u=s.get(a);if(u&&Date.now()-u.fetchedAt<6e4)return u.quota;try{n=await (0,r.c)(t)}catch{return null}let c=function(e){if(!e||"object"!=typeof e||"string"==typeof e.message&&(!e.quotas||"object"!=typeof e.quotas))return null;let t=e.quotas;if(!t||"object"!=typeof t||Array.isArray(t))return null;let n={},r=0,o=null;for(let[e,i]of Object.entries(t)){let t=function(e){if(!e||"object"!=typeof e||!0===e.unlimited||!1===e.fractionReported)return null;let t=l(e.remainingPercentage);if(null!==t)return(100-Math.max(0,Math.min(100,t)))/100;let n=l(e.used),r=l(e.total);return null!==n&&null!==r&&r>0?Math.max(0,Math.min(1,n/r)):null}(i);if(null===t)continue;let a=i&&"object"==typeof i&&"string"==typeof i.resetAt?i.resetAt:null;n[e]={percentUsed:t,resetAt:a},t>r&&(r=t,o=a)}return 0===Object.keys(n).length?null:{used:0,total:0,percentUsed:r,resetAt:o,windows:n,limitReached:r>=1-1e-9}}(n);return c?((0,o.L)(i,Object.keys(c.windows||{})),s.set(a,{quota:c,fetchedAt:Date.now()}),c):null};e.s(["f",0,function(){for(let e of r.J)(0,o.l)(e)||(0,o.s)(e,u)}]),n()}catch(e){n(e)}},!1),645035,e=>{"use strict";var t=e.i(190134),n=e.i(95360),r=e.i(802275),o=e.i(139908);let i=new Map;function a(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}async function l(e,t){let n,o=i.get(e);if(o&&Date.now()-o.fetchedAt<6e4)return o.quota;let{systemAccessToken:l,userId:s}={systemAccessToken:"string"==typeof(n=a(t?.providerSpecificData)).consoleApiKey&&n.consoleApiKey.trim().length>0?n.consoleApiKey:null,userId:"string"==typeof n.newApiUserId&&n.newApiUserId.trim().length>0?n.newApiUserId:null};if(!l||!s)return null;let u="https://agentrouter.org/api/user/self";try{await (0,r.f)();let t=await fetch(u,{method:"GET",headers:{Authorization:`Bearer ${l}`,"New-Api-User":s,"Content-Type":"application/json",Accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(401===t.status||403===t.status)return i.delete(e),null;if(!t.ok)return null;let n=await t.json(),o=function(e){let t=a(e),n=a(t.data),r="quota"in n?n.quota:t.quota;if(void 0===r)return null;let o=function(e,t=0){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return t}(r,-1);if(o<0)return null;let i=o<=0,l=+!!i;return{used:100*l,total:100,percentUsed:l,resetAt:null,rawQuota:o,dollarBalance:o/5e5,limitReached:i}}(n);if(!o)return null;return i.set(e,{quota:o,fetchedAt:Date.now()}),o}catch{return null}}(0,o.P)("agentrouterQuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of i)e-n.fetchedAt>3e5&&i.delete(t)},3e5);let s="https://api.v0.dev",u="credits",c="dailyOps",d=new Map;function f(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function p(e,t=0){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=parseFloat(e);if(Number.isFinite(t))return t}return t}function y(e){let t=f(e);if(!("remaining"in t)||!("limit"in t))return null;let n=p(t.remaining,-1),r=p(t.limit,-1);return n<0||r<=0?null:{percentUsed:Math.min(1,Math.max(0,r-n)/r),resetAt:function(e){if("string"==typeof e&&e.trim().length>0){let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toISOString()}return"number"==typeof e&&Number.isFinite(e)&&e>0?new Date(e).toISOString():null}(t.reset)}}async function m(e,t,n){try{await (0,r.f)();let o=await fetch(e,{method:"GET",headers:t,signal:AbortSignal.timeout(8e3)});if(401===o.status||403===o.status)return{window:null,billingType:null,invalidCredential:!0};if(!o.ok)return{window:null,billingType:null,invalidCredential:!1};let i=await o.json(),a=n(i);return{window:a.window,billingType:a.billingType,invalidCredential:!1}}catch{return{window:null,billingType:null,invalidCredential:!1}}}function g(e){return{billingType:null,window:y(e)}}function h(e){let t=f(e);return{billingType:"string"==typeof t.billingType?t.billingType:"unknown",window:y(t.data)}}async function b(e,t){let n=d.get(e);if(n&&Date.now()-n.fetchedAt<6e4)return n.quota;let r="string"==typeof t?.apiKey&&t.apiKey.trim().length>0?t.apiKey:null;if(!r)return null;let o={Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json"},i={},a="unknown",l=await m(`${s}/v1/user/billing`,o,h);l.window&&(i[u]=l.window,a=l.billingType??"unknown");let f=await m(`${s}/v1/rate-limits`,o,g);if(f.window&&(i[c]=f.window),l.invalidCredential||f.invalidCredential)return d.delete(e),null;let p=function(e,t){if(0===Object.keys(e).length)return null;let n=Math.max(0,...Object.values(e).map(e=>e.percentUsed)),r=Object.values(e).find(e=>e.percentUsed===n)??null;return{used:Math.round(100*n),total:100,percentUsed:n,resetAt:r?.resetAt??null,windows:e,billingType:t}}(i,a);return p?(d.set(e,{quota:p,fetchedAt:Date.now()}),p):null}(0,o.P)("v0QuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of d)e-n.fetchedAt>3e5&&d.delete(t)},3e5);let w="window5h",_="window7d";function A(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}let I=new Map;function k(e,t,n){return n-e.windowStart>=t?{count:0,windowStart:n}:e}function v(e,t,n){return{percentUsed:n>0?Math.min(1,e.count/n):0,resetAt:new Date(e.windowStart+t).toISOString()}}async function T(e){let t=I.get(e);if(!t)return null;let n=Date.now(),r=A("FREEMODEL_5H_REQUEST_LIMIT",500),o=A("FREEMODEL_7D_REQUEST_LIMIT",2e3),i=k(t.window5h,18e6,n),a=k(t.window7d,6048e5,n),l=v(i,18e6,r),s=v(a,6048e5,o),u=Math.max(l.percentUsed,s.percentUsed),c=u===l.percentUsed?l.resetAt:s.resetAt;return{used:Math.round(100*u),total:100,percentUsed:u,resetAt:c,windows:{[w]:l,[_]:s}}}function R(e,t=0){if(t<0||e.length-t<5)return null;let n=e[t];if(0!==n&&1!==n&&128!==n&&129!==n)return null;let r=t+5,o=e.readUInt32BE(t+1);return o>e.length-r?null:{flag:n,payloadStart:r,payloadLength:o}}function S(e,t){let n=0n,r=0n,o=t;for(;;){if(o>=e.length)return null;let t=e[o];if(n|=BigInt(127&t)<<r,o+=1,(128&t)==0)break;if((r+=7n)>70n)return null}return{value:Number(n),next:o}}function E(e,t,n,r){return t+n>e.length?null:{field:{wireType:r,bytes:e.subarray(t,t+n)},next:t+n}}function x(e){let t=new Map,n=0;for(;n<e.length;){let r=function(e,t){let n=S(e,t);if(!n)return null;let r=n.value>>>3,o=7&n.value;if(0===r)return null;if(0===o){let t=S(e,n.next);return t?{fieldNumber:r,field:{wireType:0,value:t.value},next:t.next}:null}if(2===o){let t=function(e,t){let n=S(e,t);if(!n)return null;let{value:r,next:o}=n;return r<0||o+r>e.length?null:{field:{wireType:2,bytes:e.subarray(o,o+r)},next:o+r}}(e,n.next);return t?{fieldNumber:r,field:t.field,next:t.next}:null}if(1===o){let t=E(e,n.next,8,1);return t?{fieldNumber:r,field:t.field,next:t.next}:null}if(5===o){let t=E(e,n.next,4,5);return t?{fieldNumber:r,field:t.field,next:t.next}:null}return null}(e,n);if(!r)return null;t.set(r.fieldNumber,r.field),n=r.next}return t}let $=Buffer.from([0,0,0,0,0]),C=new Map;async function O(e,t){var n,o,i;let a,l=C.get(e);if(l&&Date.now()-l.fetchedAt<6e4)return l.quota;let s="string"==typeof(a=(n=t?.credentials)&&"object"==typeof n&&!Array.isArray(n)?n:{}).accessToken&&a.accessToken.trim().length>0?a.accessToken:null;if(!s)return null;let u="https://grok.com/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig";try{let t;await (0,r.f)();let n=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/grpc-web+proto","X-Grpc-Web":"1"},body:$,signal:AbortSignal.timeout(8e3)});if(401===n.status||403===n.status)return C.delete(e),null;if(!n.ok)return null;let a=await n.arrayBuffer(),l=function(e){if(!e||0===e.length)return null;try{var t,n;let r=null!==R(e,0)?function(e){let t=0;for(;t<e.length;){let n=R(e,t);if(!n)break;let r=n.payloadStart+n.payloadLength;if((128&n.flag)==0)return e.subarray(n.payloadStart,r);t=r}return null}(e):e;if(!r)return null;let o=x(r);if(!o)return null;let i=(t=o.get(1))&&2===t.wireType?x(t.bytes):null;if(!i)return null;let a=(n=i.get(1))?5===n.wireType?n.bytes.readFloatLE(0):1===n.wireType?n.bytes.readDoubleLE(0):null:0;if(null===a||!Number.isFinite(a)||a<0)return null;return{percentUsed:Math.min(100,100*a),resetAt:function(e){if(!e||2!==e.wireType)return null;let t=x(e.bytes);if(!t)return null;let n=t.get(1),r=t.get(2),o=new Date(1e3*(n?.wireType===0?n.value:0)+Math.round((r?.wireType===0?r.value:0)/1e6));return Number.isNaN(o.getTime())?null:o.toISOString()}(i.get(5))}}catch{return null}}(Buffer.from(a));if(!l)return null;let c=(o=l.percentUsed,i=l.resetAt,t=Math.min(100,Math.max(0,o)),{used:Math.round(t),total:100,percentUsed:t/100,resetAt:i,limitReached:t>=100});return C.set(e,{quota:c,fetchedAt:Date.now()}),c}catch{return null}}(0,o.P)("grokCliQuotaFetcher-sweep",()=>{let e=Date.now();for(let[t,n]of C)e-n.fetchedAt>3e5&&C.delete(t)},3e5);var M=e.i(184498),L=e.i(808203);(0,t.s)("agentrouter",l),(0,n.I)("agentrouter",l),(0,t.s)("v0-vercel",b),(0,n.I)("v0-vercel",b),(0,t.L)("v0-vercel",[u,c]),(0,t.s)("freemodel-dev",T),(0,n.I)("freemodel-dev",T),(0,t.L)("freemodel-dev",[w,_]),(0,t.s)("grok-cli",O),(0,n.I)("grok-cli",O),(0,M.registerXaiOauthQuotaFetcher)(),(0,L.P)(),e.s([],645035)},324348,e=>{"use strict";function t(e){return"string"==typeof e?e:""}function n(e){if(!e||"object"!=typeof e)return!1;let n=e.tools;return!!Array.isArray(n)&&n.some(e=>!!e&&"object"==typeof e&&!e.function&&t(e.type).startsWith("web_search"))}e.s(["W",0,n,"s",0,function(e,r,o){let i={wasRouted:!1,model:e};if(!n(r))return i;let a=t(o?.webSearchRouteModel).trim();return a&&a!==e?{wasRouted:!0,model:a}:i}])},701554,e=>{"use strict";async function t(e,t,n,r){if(!e||!n||!n.comboAutoPromoteEnabled)return!1;let o="string"==typeof e.id?e.id:null;if(!o)return!1;let i=function(e,t){if(!Array.isArray(e)||0===e.length||"string"!=typeof t||0===t.length)return null;let n=e.findIndex(e=>(function(e){if("string"==typeof e)return e.trim().length>0?e:null;if(e&&"object"==typeof e){let t=e.model;if("string"==typeof t&&t.trim().length>0)return t}return null})(e)===t);return n<=0?null:[e[n],...e.filter((e,t)=>t!==n)]}(Array.isArray(e.models)?e.models:null,t);if(!i)return!1;let a="string"==typeof e.name?e.name:o;try{return await r.updateCombo(o,{models:i}),r.info?.("COMBO",`Model "${t}" succeeded — promoted to #1 in combo "${a}"`),!0}catch(e){return r.warn?.("COMBO",`Failed to promote model "${t}" in combo "${a}": ${e?.message||"unknown error"}`),!1}}e.s(["f",0,t])},444063,e=>{"use strict";e.s(["f",0,function(e){return Array.isArray(e)&&e.includes("policy:bypass-provider-quota")}])},913577,e=>e.a(async(t,n)=>{try{var r=e.i(719201),o=e.i(889771),i=e.i(529160),a=e.i(713553),l=e.i(122791),s=e.i(245272),u=e.i(403122),c=e.i(249157),d=t([i,a,s]);async function f(t,n,r){try{let{parseAutoPrefix:o}=await e.A(501885),a=o(t);if(!a.valid)return n.spec||c.warn("AUTO",`Invalid auto prefix format: ${t}`),n;let l=Object.prototype.hasOwnProperty.call(i.s,t)?n.variant:a.variant,s="auto"===t&&void 0===l?r.autoRoutingDefaultVariant:void 0,u=l??s;return c.info("AUTO",`Zero-config routing variant: ${u||"default"} (model=${t})`),{variant:u,spec:n.spec}}catch(e){return c.error("AUTO","Failed to load auto-prefix parser",{err:e}),n}}async function p(e){let t="auto"===e||e.startsWith("auto/"),n=function(e){let t="auto"===e||Object.prototype.hasOwnProperty.call(i.s,e);if(Object.prototype.hasOwnProperty.call(i.s,e))return{variant:i.s[e],recognizedBuiltInAuto:!0};if(!e.startsWith("auto/"))return{recognizedBuiltInAuto:t};let n=e.slice(5);if(i.G.has(n))return{recognizedBuiltInAuto:!0};let r=(0,a.E)(n);return r.valid?{recognizedBuiltInAuto:!0,spec:{category:r.category,tier:r.tier}}:(0,l.d)(n)?{recognizedBuiltInAuto:!0,spec:{family:n}}:{recognizedBuiltInAuto:t}}(e);if(!t)return{model:e,...n,isAutoRouting:t,response:null};let s=await (0,u.getCachedSettings)().catch(()=>({}));if(s?.autoRoutingEnabled===!1)return{model:e,...n,isAutoRouting:t,response:(0,r.errorResponse)(o.p.BAD_REQUEST,"Auto routing is disabled. Enable it in Settings > Routing.")};let c=await f(e,n,s);return{model:e,...n,...c,isAutoRouting:t,response:null}}async function y(t,n,i){if(!t.isAutoRouting||null!==n)return n;if(!t.recognizedBuiltInAuto)return(0,r.errorResponse)(o.p.BAD_REQUEST,`Model '${t.model}' is not a valid combo or provider. Unknown built-in auto combo.`);try{let{createVirtualAutoCombo:n}=await e.A(849824),r=await n(t.variant,t.spec,i,t.model);return r.name=t.model,r.id=t.model,c.info("AUTO",`Virtual auto-combo created: ${r.name} (${r.candidatePool?.length||0} candidates)`),r}catch(e){return c.error("AUTO","Failed to create virtual auto-combo",{err:e}),null}}[i,a,s]=d.then?(await d)():d,e.s(["Z",0,y,"g",0,p]),n()}catch(e){n(e)}},!1),10641,e=>e.a(async(t,n)=>{try{var r=e.i(877621),o=e.i(428489),i=e.i(594737),a=e.i(287726),l=e.i(574835),s=e.i(192408),u=e.i(821518),c=e.i(719201),d=e.i(779170),f=e.i(998905),p=e.i(496727),y=e.i(720902),m=e.i(573344),g=e.i(563682),h=e.i(984168),b=e.i(189281),w=e.i(359756),_=e.i(838679),A=e.i(298321),I=e.i(308401),k=e.i(7228),v=e.i(110963),T=e.i(889771),R=e.i(85713),S=e.i(613775),E=e.i(878947),x=e.i(249157),$=e.i(496973),C=e.i(656368),O=e.i(403098),M=e.i(151205),L=e.i(125852),N=e.i(701554),U=e.i(245272),D=e.i(130273),B=e.i(403122),F=e.i(186920),q=e.i(984340),j=e.i(421892),K=e.i(22775),P=e.i(123751),G=e.i(957921),Q=e.i(158756),H=e.i(990338),W=e.i(375152),z=e.i(74214),Y=e.i(913577),J=e.i(546747),V=e.i(638146),X=e.i(897135),Z=e.i(760391),ee=e.i(260222),et=e.i(25687),en=e.i(306976),er=e.i(454925),eo=e.i(577122),ei=e.i(478847),ea=e.i(444063),el=e.i(548351),es=e.i(852705),eu=e.i(324348),ec=e.i(154939),ed=e.i(95360),ef=e.i(167389),ep=e.i(646629),ey=e.i(396692),em=e.i(744402),eg=e.i(470019),eh=e.i(446518),eb=e.i(903141),ew=e.i(887165),e_=e.i(238492);e.i(645035);var eA=e.i(75106),eI=e.i(283439),ek=e.i(717263),ev=e.i(338258),eT=t([o,a,l,s,d,y,b,w,_,A,$,L,U,F,K,P,G,Q,z,Y,J,Z,et,ei,e_,eA,eI,ev]);[o,a,l,s,d,y,b,w,_,A,$,L,U,F,K,P,G,Q,z,Y,J,Z,et,ei,e_,eA,eI,ev]=eT.then?(await eT)():eT,(0,ep.registerCodexQuotaFetcher)(),(0,ey.registerBailianCodingPlanQuotaFetcher)(),(0,em.f)(),(0,eg.Q)(),(0,eh.T)(),(0,eb.o)(),(0,ew.F)(),(0,e_.f)();let eM=null,eL=0,eN=-1;async function eR(){let e=Date.now();return null!==eM&&e-eL<1e4&&eN===(0,B.getCombosCacheVersion)()?eM:(eL=e,eN=(0,B.getCombosCacheVersion)(),eM=(0,M.e)().catch(()=>[]))}function eS(e){if(!Array.isArray(e))return null;let t=e.filter(e=>"string"==typeof e&&e.trim().length>0);return t.length>0?t:null}function eE(e,t){let n=eS(e),r=eS(t);return n&&r?n.filter(e=>r.includes(e)):n||r||null}let eU={updateCombo:M.a,info:x.info,warn:x.warn};async function ex(e,t=null,n=null,r){let o=await e$(e,t,n,r),i="";try{i=new URL(e?.url).pathname}catch{i=""}let a=/\/messages\/?$/.test(i)?"claude":"openai",l=await (0,S.k)(function(e,t){if("claude"===t||!e||529!==e.status)return e;let n=new Headers(e.headers);return n.delete("content-length"),new Response(e.body,{status:T.p.SERVICE_UNAVAILABLE,headers:n})}(o,a),a),s=t?.body?.model??n?.model;return"string"==typeof s&&s.trim()?(0,_.B)(l,{requestedModel:s}):l}async function e$(t,n=null,u=null,w){let v,S=(0,C.s)(t?.headers,x.warn,c.errorResponse);if(S)return S;let $=w||(0,eo.s)(),O=new er.RequestTelemetry($),M=(0,ek.f)();if(M.shouldReject)return x.warn("BACKPRESSURE","Rejecting request: at connection limit"),M.response;try{O.startPhase("parse"),v=await (0,r.f)(t,u),O.endPhase()}catch{return x.warn("CHAT","Invalid JSON body"),(0,c.errorResponse)(T.p.BAD_REQUEST,"Invalid JSON body")}v=(0,o.I)(v);let U=(0,R.R)(v,t.url),D=v;if("messages"in D&&!Array.isArray(D.messages))return x.warn("CHAT","Rejecting request with non-array messages"),(0,c.errorResponse)(T.p.BAD_REQUEST,"messages: Expected array");if(Array.isArray(D.messages)&&0===D.messages.length)return x.warn("CHAT","Rejecting request with empty messages array"),(0,c.errorResponse)(T.p.BAD_REQUEST,"messages: at least one message is required");if(!("messages"in D)&&!("input"in D)&&"antigravity"!==U)return x.warn("CHAT","Rejecting request with missing messages"),(0,c.errorResponse)(T.p.BAD_REQUEST,"messages: Expected array, received undefined");let q=v.model;if(null!=q&&"string"!=typeof q)return x.warn("CHAT",`Rejecting non-string model (typeof=${typeof q})`),(0,c.errorResponse)(T.p.BAD_REQUEST,`model: Expected string, received ${Array.isArray(q)?"array":typeof q}`);{let e=v,t=(e,t)=>(0,c.errorResponse)(T.p.BAD_REQUEST,`${e}: ${t}`);if(void 0!==e.temperature){if("number"!=typeof e.temperature||Number.isNaN(e.temperature))return t("temperature","must be a number");if(e.temperature<0||e.temperature>2)return t("temperature","must be between 0 and 2")}if(void 0!==e.top_p){if("number"!=typeof e.top_p||Number.isNaN(e.top_p))return t("top_p","must be a number");if(e.top_p<0||e.top_p>1)return t("top_p","must be between 0 and 1")}if(void 0!==e.max_tokens&&("number"!=typeof e.max_tokens||!Number.isInteger(e.max_tokens)||e.max_tokens<1))return t("max_tokens","must be a positive integer");if(void 0!==e.n&&("number"!=typeof e.n||!Number.isInteger(e.n)||e.n<1))return t("n","must be a positive integer")}n||(n=(0,ev.X)(t,v));let j=new URL(t.url),K=(0,g._)(v,{claudeFormat:j.pathname.includes("/messages")});K.applied&&x.debug("NO_THINKING",`Resolved no-thinking alias → ${K.realModel}`);let Q=(0,i.F)(t,v),H=await (0,h.f)(Q);H.stripped&&(x.debug("CC_DISCOVERY",`Resolved cc discovery alias: ${Q} → ${H.model}`),Q=H.model);let V=(0,W.D)(Q,v);v=i.R.align(v,Q,x);let X=v.messages?.length||v.input?.length||0,Z=v.tools?.length||0,ee=v.reasoning_effort||v.reasoning?.effort||null;x.request("POST",`${j.pathname} | ${Q} | ${X} msgs${Z?` | ${Z} tools`:""}${ee?` | effort=${ee}`:""}`);let et=t.headers.get("Authorization"),ed=(0,a.t)(t);et&&ed?x.debug("AUTH","API key provided"):x.debug("AUTH","No API key provided (local mode)");let ef=await (0,el.N)(t,v);if(ef)return(0,er.recordTelemetry)(O),ef;let ep=t.headers?.get?.("x-internal-test")==="combo-health-check";if(!Q)return x.warn("CHAT","Missing model"),(0,c.errorResponse)(T.p.BAD_REQUEST,"Missing model");let ey=(0,m.O)(Q),em=!!ey&&(0,E.getModelsByProviderId)(ey.provider).some(e=>e.id===ey.model);if(ey&&!em)return x.warn("CHAT",`Rejecting image-generation model on chat endpoint: ${Q}`),(0,c.errorResponse)(T.p.BAD_REQUEST,`Model '${Q}' is an image-generation model and cannot be used on /v1/chat/completions. Use POST /v1/images/generations instead.`);let eg=(0,ec.extractExternalSessionId)(t.headers)||(0,ec.generateSessionId)(v),eh=(0,a.J)(v,t.headers)||eg,eb=t.headers.get("x-trouteai-connection")?.trim()||null;eg&&(0,ec.touchSession)(eg),O.startPhase("policy");let ew=await (0,ei.r)(t,Q);if(ew.rejection)return x.warn("POLICY",`API key policy rejected: ${Q} (key=${ew.apiKeyInfo?.id||"unknown"})`),ew.rejection;let e_=ew.apiKeyInfo,eA=(0,ea.f)(e_?.scopes);O.endPhase(),O.startPhase("validate");let eT=await P.Q.runPreCallHooks(v,{apiKeyInfo:e_,disabledGuardrails:(0,P.W)({apiKeyInfo:e_??null,body:v,headers:t.headers}),endpoint:new URL(t.url).pathname,headers:t.headers,log:x,method:t.method,model:Q,stream:v?.stream===!0});if(eT.blocked)return x.warn("GUARDRAIL","Request blocked during pre-call guardrails",{guardrail:eT.guardrail,message:eT.message}),(0,c.errorResponse)(T.p.BAD_REQUEST,eT.message||"Request rejected: suspicious content detected");let eS="string"==typeof v?.model&&v.model.length>0?v.model:Q;if(v=eT.payload,{body:v,modelStr:Q}=await i.R.reconcileGuardrailReroute({body:v,modelBeforeGuardrails:eS,modelStr:Q,apiKey:ed,apiKeyId:e_?.id,isModelAllowedForKey:L.isModelAllowedForKey,log:x}),O.endPhase(),e_?.id&&eg){let e="number"==typeof e_.maxSessions&&e_.maxSessions>0?e_.maxSessions:0;if(e>0&&!(0,ec.isSessionRegisteredForKey)(e_.id,eg)){let t=(0,ec.checkSessionLimit)(e_.id,e);if(t)return(0,G.t)((0,c.errorResponse)(T.p.RATE_LIMITED,t.message),eg);(0,ec.registerKeySession)(e_.id,eg)}}let eO=Q;if((0,es.getTaskRoutingConfig)().enabled){O.startPhase("task-route");let e=(0,es.applyTaskAwareRouting)(Q,v);e.wasRouted?(eO=e.model,v={...v,model:e.model},x.info("T05",`Task-Aware: detected="${e.taskType}" → model override: ${Q} → ${e.model}`)):"chat"!==e.taskType&&x.debug("T05",`Task-Aware: detected="${e.taskType}" (no override configured)`),e.taskType,e.wasRouted,O.endPhase()}if((0,eu.W)(v)){let e=await (0,B.getCachedSettings)().catch(()=>({})),t=(0,eu.s)(eO,v,e);t.wasRouted&&(x.info("WEBSEARCH-ROUTE",`web_search tool → model override: ${eO} → ${t.model}`),eO=t.model,v={...v,model:t.model})}if(U===p.f.CLAUDE&&(0,y.n)(v)&&"0"!==process.env.TROUTEAI_WEB_SEARCH_EMULATION&&await (0,y.X)(eO))return x.info("WEBSEARCH",`${eO} has no web search / fetch of its own; TRouteAI runs it`),(0,er.recordTelemetry)(O),(0,y.d)({request:t,body:{...v,model:eO},callModel:e=>ex(t,null,e,w),apiKeyId:e_?.id??null,log:x});let eM=null,eL={tags:[]},eN=await (0,z.i)({request:t,body:v,modelStr:eO,policy:ew,apiKeyInfo:e_,reasoningIntent:V});if(eN.response)return eN.response;v=eN.body,eO=eN.modelStr,eM=eN.reasoningDecision,eL=eN.requestRoutingTags;let eD=await (0,Y.g)(eO);if(eD.response)return eD.response;O.startPhase("resolve");let eB=await (0,s.Q)(eO);if(eM?.targetCombo&&(eB=eM.targetCombo),!eB&&eO.startsWith("auto/")){let e=eO.slice(5);for(let t of[`auto/best-${e}`,`auto/${e}`])if(eB=await (0,s.Q)(t)){x.info("ROUTING",`"${eO}" → combo "${t}" (auto fuzzy)`);break}}let eF=await (0,Y.Z)(eD,eB,e_?.id);if(eF instanceof Response)return eF;if(eB=eF){if(eM){let e=(0,z.d)(eB,eM);if(e instanceof Response)return e;eB=e}if(Array.isArray(eB.models)&&eB.models.some(f.l)){let e=eB.models.filter(e=>!(0,f.l)(e));if(0===e.length)return(0,c.errorResponse)(T.p.SERVICE_UNAVAILABLE,`All steps of combo '${eB.name}' are turned off. Turn one on in Dashboard > Combos.`);eB={...eB,models:e}}x.info("CHAT",`Combo "${Q}" [${eB.strategy||"priority"}] with ${eB.models.length} models`);let r=new Map,o=null,i=[],u=!0,p=0,y=0,m=new Map,g=(e,t)=>`${t?.executionKey||t?.connectionId||""}:${e}`,h=async(e,t)=>{if(ep)return!0;let n=await (0,s.M)(e),l=!t?.providerId||t.providerId===n.provider||e.startsWith(t.providerId+"/")?n.provider:t.providerId;if(!l)return!0;let c=n.model||e,d=`${l}\0${c}`;if(!m.has(d)){let e=!1;try{e=(0,F.J)(l,c)}catch{}m.set(d,e)}if(m.get(d))return!1;"string"==typeof t?.connectionId&&t.connectionId.trim().length;let f=eE(e_?.allowedConnections??null,t?.allowedConnectionIds??null);if(e_?.allowedQuotas&&e_.allowedQuotas.length>0){let e=await (0,eI.resolveQuotaKeyScope)(e_.allowedQuotas);f=(0,eI.constrainConnectionsToQuota)(f??[],e.connectionIds)}if(Array.isArray(f)&&0===f.length)return!1;let p=await (0,a.m)(l,null,f,c,{sessionKey:eh,...t?.allowRateLimitedConnection?{allowRateLimitedConnections:!0}:{},...t?.connectionId?{forcedConnectionId:t.connectionId}:{},...eA?{bypassQuotaPolicy:!0}:{}});if(!p||p.allRateLimited){let e,t,n;return p?.allRateLimited&&(e=Number(p?.cooldownStatus)||Number(p?.lastErrorCode)||429,i.push(e),429===e&&p?.cooldownReason!=="quota_exhausted"&&(u=!1),!(!Number.isFinite(n="string"==typeof(t=p?.retryAfter)||t instanceof Date?new Date(t).getTime():0/0)||n<=Date.now())&&(null===o||n<o)&&(o=n)),!1}return r.set(g(e,t),p),!0},[w,R]=await Promise.all([(0,B.getCachedSettings)().catch(()=>({})),eR()]),S=Array.isArray(R)?R.map(e=>Array.isArray(e?.models)&&e.models.some(f.l)?{...e,models:e.models.filter(e=>!(0,f.l)(e))}:e):R,E="context-relay"===eB.strategy?(0,k.N)(eB,w):null,C=(0,I.D)(t.headers),M="context-relay"===eB.strategy||eA||Object.keys(C).length>0?{..."context-relay"===eB.strategy?{sessionId:eg,config:E}:{},...eA?{bypassProviderQuotaPolicy:!0}:{},...C}:void 0;O.endPhase();let L=await b.f({body:v,combo:eB,handleSingleModel:(e,o,i)=>eC(e,o,n,t,eB.name,e_,O,{sessionId:eg,sessionAffinityKey:eh,forceLiveComboTest:ep,forcedConnectionId:i?.connectionId??null,allowedConnectionIds:i?.allowedConnectionIds??null,comboStepId:i?.stepId||null,comboExecutionKey:i?.executionKey||i?.stepId||null,skipUpstreamRetry:i?.failoverBeforeRetry??!1,allowRateLimitedConnection:i?.allowRateLimitedConnection===!0,preselectedCredentials:r.get(g(o,i)),cachedSettings:w,providerId:i?.providerId??null,correlationId:$,modelPinned:i?.modelPinned??!1,reasoningDecision:eM,reasoningIntent:V,reasoningRequestTags:eL.tags,modelAbortSignal:i?.modelAbortSignal??null},i?.effectiveComboStrategy??eB.strategy,!0).then(async e=>{if(e?.status===401){let e=r.get(g(o,i));e?.allExpired&&"expired"===e.expiredStatus?p++:y++}return e?.ok&&await (0,N.f)(eB,o,w,eU),e}),isModelAvailable:h,log:x,settings:w,allCombos:S,apiKeyAllowedConnections:e_?.allowedConnections??null,relayOptions:M,signal:t?.signal??null,correlationId:$,priority:(0,en.W)(t?.headers?.get?.("x-trouteai-priority")??null,e_?.defaultPriority)}),U=401===L.status&&p>0&&0===y;if(!L.ok&&([502,503].includes(L.status)||U)&&"string"==typeof w?.globalFallbackModel&&w.globalFallbackModel.trim()){let e=w.globalFallbackModel.trim();x.info("GLOBAL_FALLBACK",`Combo "${eB.name}" exhausted — attempting global fallback: ${e}`);try{let r=await (0,A.f)({fallback:"global",attempts:Array.isArray(eB.models)?eB.models.length:1},()=>eC(v,e,n,t,eB.name,e_,O,{sessionId:eg,sessionAffinityKey:eh,emergencyFallbackTried:!0,forceLiveComboTest:ep},eB.strategy,!0));if(r.ok)return x.info("GLOBAL_FALLBACK",`Global fallback ${e} succeeded`),(0,er.recordTelemetry)(O),(0,G.t)((0,_.B)(r,{fallback:"global",fallbackAttempts:Array.isArray(eB.models)?eB.models.length:1}),eg);x.warn("GLOBAL_FALLBACK",`Global fallback ${e} also failed (${r.status})`)}catch(e){x.warn("GLOBAL_FALLBACK",`Global fallback error: ${e?.message||"unknown"}`)}}if(!L.ok&&503===L.status&&null!==o&&o>Date.now()&&"ALL_ACCOUNTS_INACTIVE"===await L.clone().json().then(e=>e?.error?.code??null).catch(()=>null)){let e=new Date(o).toISOString(),t=(0,d.k)(i,T.p.RATE_LIMITED);L=t===T.p.RATE_LIMITED?(0,c.unavailableResponse)(T.p.RATE_LIMITED,`All accounts of combo '${eB.name}' have reached their usage limit; the next one is usable at ${e}`,e,(0,l.RG)(e),{usageLimit:u}):(0,c.unavailableResponse)(t,`Every model of combo '${eB.name}' is cooling down after upstream errors`,e,(0,l.RG)(e))}if((0,er.recordTelemetry)(O),!L.ok)try{let{recordRejectedRequestUsage:t,resolveRejectedComboProvider:r}=await e.A(353104);await t({status:L.status,model:v?.model||eO,requestedModel:v?.model||eO,provider:r(v?.model||eO,eB.name),endpoint:n?.endpoint,error:await (0,J.f)(L,eB.name),comboName:eB.name,apiKeyId:e_?.id??null,apiKeyName:e_?.name??null,correlationId:$,startTime:O?.startTime,requestBody:n?.body??null})}catch{}return(0,G.v)((0,G.t)(L,eg),$)}O.endPhase();let eq=null;if(!eB){let t=eO.split("/")[0];if(t)try{let{getComboByName:n}=await e.A(605589),r=await n(t);r?.id&&(eq=r.id)}catch{}}let ej=await eC(v,eO,n,t,null,e_,O,{sessionId:eg,sessionAffinityKey:eh,forceLiveComboTest:ep,forcedConnectionId:eb,correlationId:$,routingComboId:eq,reasoningDecision:eM,reasoningIntent:V,reasoningRequestTags:eL.tags},null,!1);return(0,er.recordTelemetry)(O),(0,G.v)((0,G.t)(ej,eg),$)}async function eC(...e){let t=await eO(...e);if(!t||t.ok)return t;let n="string"==typeof e[1]?e[1]:"",r=n.indexOf("/");return(0,_.B)(t,{model:r>0?n.slice(r+1):n,provider:r>0?n.slice(0,r):null})}async function eO(t,n,r=null,o=null,i=null,s=null,d=null,f={},p=null,y=!1){let m=await (0,G.X)(n,t,r?.endpoint,r?.headers);if(m.error)return m.error;if(m.combo){let e=m.combo;return x.info("ROUTING",`Safety-net combo redirect for "${n}" → combo="${e.name}"`),x.info("ROUTING",`Auto-combo redirect from handleSingleModelChat for "${n}"`),x.info("ROUTING",`Auto-combo redirect to combo flow for "${n}"`),(0,b.f)({body:t,combo:e,handleSingleModel:(t,i,a)=>eC(t,i,r,o,e.name??n,s,d,{sessionId:"",forceLiveComboTest:!1,forcedConnectionId:null,allowedConnectionIds:null,comboStepId:null,comboExecutionKey:null,skipUpstreamRetry:a?.failoverBeforeRetry??!1,allowRateLimitedConnection:a?.allowRateLimitedConnection===!0,providerId:a?.providerId??null,correlationId:f?.correlationId??null,modelAbortSignal:a?.modelAbortSignal??null},a?.effectiveComboStrategy??e.strategy??"priority",!1),isModelAvailable:async()=>!0,log:x,settings:{},allCombos:[],relayOptions:void 0,signal:o?.signal??null,correlationId:f?.correlationId??null})}let{provider:g,model:h,sourceFormat:I,targetFormat:k,extendedContext:S,apiFormat:C}=m,M=!f.providerId||f.providerId===g||n.startsWith(f.providerId+"/")?g:f.providerId,L=!0===f.forceLiveComboTest;if(!L){let e=!1;try{e=(0,F.J)(M,h)}catch{}if(e)return x.warn("CHAT",`Model ${M}/${h} is turned off`,{model:n}),(0,c.errorResponse)(T.p.NOT_FOUND,`Model '${M}/${h}' is turned off. Turn it on in Dashboard > Providers.`)}let N=(0,ea.f)(s?.scopes),U="string"==typeof f.forcedConnectionId&&f.forcedConnectionId.trim().length>0,K=eE(s?.allowedConnections??null,f.allowedConnectionIds??null);if(s?.allowedQuotas&&s.allowedQuotas.length>0){let e=await (0,eI.resolveQuotaKeyScope)(s.allowedQuotas);K=(0,eI.constrainConnectionsToQuota)(K??[],e.connectionIds)}let P=L?"combo live test":U?"fixed combo step connection":void 0,W=await (0,l.aP)(M),Y=await (0,G.J)(M,h,{ignoreCircuitBreaker:L||U,ignoreModelCooldown:L||U,providerProfile:W,...P?{bypassReason:P}:{}});if(Y){try{let{recordRejectedRequestUsage:o}=await e.A(353104);await o({status:Y.status,model:h,requestedModel:t?.model||n,provider:M,endpoint:r?.endpoint,error:`[${Y.status}] Pipeline gate rejected`,comboName:y?i:null,comboStepId:y?f?.comboStepId??null:null,comboExecutionKey:y?f?.comboExecutionKey??null:null,apiKeyId:s?.id??null,apiKeyName:s?.name??null,correlationId:f?.correlationId??null,startTime:d?.startTime})}catch{}return Y}let J=(0,Z.f)(M,W.useUpstream429BreakerHints),en=(0,ee.getCircuitBreaker)(M,{failureThreshold:W.failureThreshold,resetTimeout:W.resetTimeoutMs,isFailure:e=>!(0,ee.isLocalStreamLifecycleError)(e),onStateChange:(e,t,n)=>x.info("CIRCUIT",`${e}: ${t} → ${n}`),...J?{cooldownByKind:{rate_limit:6e4,quota_exhausted:36e5},classifyError:V.Z}:{}}),er=o?.headers?.get("user-agent")||"",eo=f.cachedSettings??await (0,B.getCachedSettings)().catch(()=>({})),ei=(0,eA.z)(eo),el=(0,eA.n)(ei,"claude-web"===M||y||L||!0===f.emergencyFallbackTried),es=o?.signal??null,eu=el.budgetMs;if(Array.isArray(K)&&0===K.length)return x.debug("AUTH",`${M}/${h} filtered out by connection-level routing constraints`),(0,c.errorResponse)(T.p.SERVICE_UNAVAILABLE,"No eligible connections matched the requested routing constraints");let ey=0,em=null,eg=null,eh=0;e:for(;;){let m=new Set,g=em,b=eg,B=f.preselectedCredentials;for(;;){let F=B&&0===m.size?B:await (0,a.m)(M,null,K,h,{sessionKey:f.sessionAffinityKey??f.sessionId??null,excludeConnectionIds:Array.from(m),...f.allowRateLimitedConnection?{allowRateLimitedConnections:!0}:{},...L?{allowSuppressedConnections:!0,bypassQuotaPolicy:!0}:{},...!L&&N?{bypassQuotaPolicy:!0}:{},...f.forcedConnectionId?{forcedConnectionId:f.forcedConnectionId}:{}});if(B=null,!F||"allRateLimited"in F||!F.connectionId){if(F?.allRateLimited){let e=(0,eA.Q)({retryAfter:F.retryAfter,settings:el,attempt:ey,budgetLeftMs:eu});if(e.shouldRetry){let t=Math.max(Math.ceil(e.waitMs/1e3),0);if(x.info("COOLDOWN_RETRY",`${M}/${h} all connections cooling down (${e.retryAfterHuman||`retry in ${t}s`}) — waiting ${t}s before retry ${ey+1}/${el.maxRetries}`),!await (0,eA.A)(e.waitMs,es))return x.info("COOLDOWN_RETRY",`${M}/${h} retry wait aborted by client disconnect`),(0,c.errorResponse)(499,"Request aborted");ey+=1,eu=Math.max(0,eu-e.waitMs),x.info("COOLDOWN_RETRY",`${M}/${h} cooldown elapsed — restarting request attempt ${ey}/${el.maxRetries}`);continue e}}let t=Number(b??F?.lastErrorCode);!L&&F?.allRateLimited&&Q.E.has(t)&&en._onFailure();let r=null;if(!F&&!i&&0===m.size&&!g)try{let{getProviderConnections:t}=await e.A(605589),o=await t({provider:M});if(0===o.length){let{listComboNames:t,noServeSentence:o}=await e.A(989075);r=o(n,await t())}}catch{r=null}let o=(0,G.P)(F,m.size>0?Array.from(m)[0]:null,M,h,g,b,r),a=m.size>0?Array.from(m)[m.size-1]:null;return(0,G.E)(o,a)}let P=F.connectionId.slice(0,8);x.info("AUTH",`Using ${M} account: ${P}...`);let Y=(0,u.v)(n,h,F.defaultModel,{anyBareName:(0,u.m)(eo)})??h,J=Y!==h?{...t,model:`${M}/${Y}`}:t;if(!f.reasoningDecision&&f.reasoningIntent){let e=await (0,z.L)({requestBody:J,provider:M,effectiveModel:Y,credentials:F,apiKeyInfo:s,reasoningIntent:f.reasoningIntent,reasoningDecision:f.reasoningDecision,requestRoutingTags:f.reasoningRequestTags});if(e.response)return e.response;J=e.body}let Z=null;if("context-relay"===p&&i&&f.sessionId&&t?._trouteaiSkipContextRelay!==!0){let e=(0,O.x)(f.sessionId,i);e&&e.fromAccount!==F.connectionId&&(J=(0,v.w)(J,e),Z=e,x.info("CONTEXT_RELAY",`Injecting handoff for session ${f.sessionId}: ${e.fromAccount.slice(0,8)} -> ${F.connectionId.slice(0,8)}`))}let ee=await (0,$.B)(M,F),ei=(0,j.c)(ee?.providerSpecificData??F?.providerSpecificData);if("codex"===M&&ei&&f.sessionId&&(J=(0,j.T)(J,f.sessionId)),"codex"===M&&ee?.accessToken&&F.connectionId){let e="string"==typeof ee?.providerSpecificData?.workspaceId&&ee.providerSpecificData.workspaceId.trim().length>0?ee.providerSpecificData.workspaceId:"string"==typeof F?.providerSpecificData?.workspaceId&&F.providerSpecificData.workspaceId.trim().length>0?F.providerSpecificData.workspaceId:void 0;(0,ep.registerCodexConnection)(F.connectionId,{accessToken:ee.accessToken,...e?{workspaceId:e}:{}})}f.sessionId&&t?._trouteaiInternalRequest!=="context-handoff"&&((0,ec.touchSession)(f.sessionId,F.connectionId),(0,ed.y)(f.sessionId,M,F.connectionId,ee));let ea=await (0,G.K)(F.connectionId,s?.id,M),eb={proxy:null},ew=Date.now();d&&d.startPhase("connect");let e_=(0,ev.j)(r,f.modelAbortSignal),{result:eI,tlsFingerprintUsed:ek}=await (0,G.O)({bypassCircuitBreaker:L||U,breaker:en,body:J,provider:M,model:Y,refreshedCredentials:ee,proxyInfo:ea,appliedProxySink:eb,log:x,clientRawRequest:e_,credentials:F,apiKeyInfo:s,userAgent:er,comboName:i,comboStrategy:p,isCombo:y,comboStepId:f.comboStepId??null,comboExecutionKey:f.comboExecutionKey??f.comboStepId??null,extendedContext:S,modelApiFormat:C,providerProfile:W,cachedSettings:f.cachedSettings,skipUpstreamRetry:f.skipUpstreamRetry??!1,correlationId:f?.correlationId??null,modelPinned:f?.modelPinned??!1,routingComboId:f?.routingComboId??null});d&&d.endPhase();let eT=Date.now()-ew,eR=E.PROVIDER_ID_TO_ALIAS[M]||M,eS=(0,E.getModelTargetFormat)(eR,h)||(0,R.a)(M,F.providerSpecificData)||k;if((0,G.D)({result:eI,proxyInfo:(0,G._)(ea,eb.proxy),proxyLatency:eT,provider:M,model:h,sourceFormat:I,targetFormat:eS,credentials:F,comboName:i,clientRawRequest:r,tlsFingerprintUsed:ek}),eI.success)return(0,l.m5)(M,F.connectionId,h),L||en._onSuccess(),Z&&f.sessionId&&i&&(0,O.v)(f.sessionId,i),d&&d.startPhase("finalize"),d&&d.endPhase(),eI.response;if((0,Q.L)(M,eI))return(0,G.E)(eI.response,F.connectionId);let eE="antigravity"===M&&("STREAM_READINESS_TIMEOUT"===eI.errorCode||"STREAM_EARLY_EOF"===eI.errorCode||"stream_timeout"===eI.errorType||"stream_early_eof"===eI.errorType);if(("stream_timeout"===eI.errorType||"stream_early_eof"===eI.errorType)&&!eE){if((0,G.N)(eI.errorCode,eh)&&!U){eh+=1,x.warn("STREAM",`${M}/${h} closed the stream early before useful content — retrying once (attempt ${eh})`);continue}return(0,G.E)(eI.response,F?.connectionId)}if(eE){let{shouldFallback:e,cooldownMs:t}=await (0,a.p)(F.connectionId,eI.status||T.p.BAD_GATEWAY,eI.error||eI.errorCode||"Antigravity stream ended before useful content",M,h,W,{isCombo:y});if(e&&!U){if(x.warn("AUTH",`Antigravity connection ${P}... produced no useful stream content, trying fallback connection`),Number.isFinite(t),f.sessionAffinityKey)try{let e=(0,D.getSessionAccountAffinity)(f.sessionAffinityKey,M);e?.connectionId===F.connectionId&&(0,D.deleteSessionAccountAffinity)(f.sessionAffinityKey,M)}catch{}m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}return(0,G.E)(eI.response,F?.connectionId)}if("antigravity"===M&&eI.status===T.p.GATEWAY_TIMEOUT&&("upstream_timeout"===eI.errorType||eI.errorCode===T.D)){let{shouldFallback:e,cooldownMs:t}=await (0,a.p)(F.connectionId,eI.status,eI.error||T.D,M,h,W,{isCombo:y});if(e&&!U){if(x.warn("AUTH",`Antigravity connection ${P}... timed out before response headers, trying fallback connection`),Number.isFinite(t),f.sessionAffinityKey)try{let e=(0,D.getSessionAccountAffinity)(f.sessionAffinityKey,M);e?.connectionId===F.connectionId&&(0,D.deleteSessionAccountAffinity)(f.sessionAffinityKey,M)}catch{}m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}return(0,G.E)(eI.response,F?.connectionId)}if("RATE_LIMIT_COOLDOWN"===eI.errorCode){if(U)return(0,G.E)(eI.response,F?.connectionId);m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}if("account_semaphore_capacity"===eI.errorType){if(U)return(0,G.E)(eI.response,F?.connectionId);x.warn("AUTH",`Account ${P}... at local concurrency cap, trying fallback account`),m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}if(!f.emergencyFallbackTried&&!i){let e=(0,ef.i)(Number(eI.status||0),String(eI.error||""),Array.isArray(t?.tools)&&t.tools.length>0);if((0,ef.g)(e)){let n=`${e.provider}/${e.model}`,a=`${M}/${h}`;if(n!==a){let l={...t,model:n},u=Math.min(Number(l.max_tokens??l.max_completion_tokens??e.maxOutputTokens)||e.maxOutputTokens,e.maxOutputTokens);l.max_tokens=u,l.max_completion_tokens=u,x.warn("EMERGENCY_FALLBACK",`${a} -> ${n} | reason=${e.reason}`);let c=await (0,A.f)({fallback:"emergency",attempts:1},()=>eC(l,n,r,o,i,s,d,{...f,emergencyFallbackTried:!0,forcedConnectionId:null,comboStepId:null,comboExecutionKey:null},null,!!i));if(c.ok)return(0,_.B)(c,{fallback:"emergency",fallbackAttempts:1});x.warn("EMERGENCY_FALLBACK",`Emergency fallback to ${n} failed with status ${c.status}. Resuming original provider account fallback.`)}}}let ex=!1,e$=String(eI.rawMessage??eI.error??""),eO=429===eI.status?(0,X.M)(e$.toLowerCase(),M)?"quota_exhausted":(0,V.Z)({status:eI.status,message:e$}):void 0;if(429===eI.status&&(0,l.P5)(e$)){let e=e$.match(/today's quota for model ([^,]+)/),t=e?e[1].trim():h,n=(0,q.f)(f.cachedSettings);if(n.enabled&&n.errorCodes.includes(eI.status)){let e=(0,l.nz)(M,F.connectionId,t,"quota_exhausted",eI.status,0,W,{maxCooldownMs:n.maxCooldownMs});x.info("MODEL_DAILY_QUOTA",JSON.stringify({connection:F.connectionId.slice(0,8),model:t,cooldownMs:e.cooldownMs,failureCount:e.failureCount}))}ex=!0}if(!ex){let e=F.providerSpecificData?.passthroughModels;429===eI.status&&(0,l.jE)(M,h,e,eO)&&(0,et.markAccountExhaustedFrom429)(F.connectionId,M)}let eM=(F.providerSpecificData?.extraApiKeys??[]).length>0||(0,H.V)(F.connectionId),eL=401===eI.status,{shouldFallback:eN,cooldownMs:eU}=(0,w.r)(eI,eL,eM,M)?{shouldFallback:!1,cooldownMs:0}:(0,w.Y)(eI.status,e$)?{shouldFallback:!0,cooldownMs:0}:await (0,a.p)(F.connectionId,eI.status,e$,M,h,W,{persistUnavailableState:!(y&&429===eI.status&&("rate_limit"===eO||"transient"===eO)),isCombo:y,retryAfterMs:"number"==typeof eI.retryAfterMs?eI.retryAfterMs:null});if(eN){if(Number.isFinite(eU),x.warn("AUTH",Number.isFinite(eU)&&eU>0?`Account ${P}... unavailable (${eI.status}, cooldown ${Math.ceil(eU/1e3)}s), trying fallback`:`Account ${P}... failed (${eI.status}, no cooldown), trying fallback`),f.sessionAffinityKey)try{(0,D.evictSessionAccountAffinityForConnection)(f.sessionAffinityKey,M,F.connectionId)}catch{}m.add(F.connectionId),g=eI.error,b=eI.status,em=eI.error,eg=eI.status;continue}return(0,Q.x)(eI,y,L)&&en._onFailure(),(0,G.E)(eI.response,F?.connectionId)}}}e.s(["f",0,ex]),n()}catch(e){n(e)}},!1),338258,e=>e.a(async(t,n)=>{try{var r=e.i(268263),o=e.i(54092),i=t([r,o]);[r,o]=i.then?(await i)():i,e.s(["X",0,function(e,t){return{endpoint:new URL(e.url).pathname,body:(0,o.Z)(t),headers:Object.fromEntries(e.headers.entries()),signal:e.signal??null}},"j",0,function(e,t){return t?{...e,signal:e?.signal?(0,r.G)(e.signal,t):t}:e}]),n()}catch(e){n(e)}},!1),158756,e=>e.a(async(t,n)=>{try{var r=e.i(260222),o=e.i(546747),i=e.i(359756),a=t([o,i]);[o,i]=a.then?(await a)():a;let l=new Set([408,500,502,503,504]);e.s(["E",0,l,"L",0,function(e,t){return"antigravity"===e&&422===t.status&&"missing_project_id"===t.errorCode&&"oauth_missing_project_id"===t.errorType},"x",0,function(e,t,n){return!n&&!t&&!(0,i.D)({code:e.errorCode,type:e.errorType})&&!(0,r.isLocalStreamLifecycleError)(e.error)&&l.has(Number(e.status))}]),n()}catch(e){n(e)}},!1),546747,e=>e.a(async(t,n)=>{try{var r=e.i(359756),o=t([r]);async function i(e,t){let n=`[${e.status}] Combo "${t}" failed`;try{let t=await e.clone().json(),r=t?.error?.message;return"string"==typeof r&&r.trim()?`[${e.status}] ${r.trim()}`:n}catch{return n}}[r]=o.then?(await o)():o,e.s(["f",0,i]),n()}catch(e){n(e)}},!1),74214,e=>e.a(async(t,n)=>{try{var r=e.i(192408),o=e.i(719201),i=e.i(889771),a=e.i(478847),l=e.i(100435),s=e.i(249157),u=e.i(375152),c=t([r,a]);async function d(e){try{return await (0,u.t)(e)}catch(e){return s.error("REASONING_ROUTE","Failed to resolve reasoning routing policy",{error:e}),{error:(0,o.errorResponse)(i.p.BAD_REQUEST,"Reasoning routing policy could not be resolved")}}}async function f({request:e,body:t,modelStr:n,policy:c,apiKeyInfo:p,reasoningIntent:y}){let m=y||(0,u.D)(n,t),g=await (0,r.Q)(m.model),h=[];if(!g){let e=await (0,u.X)(m.model,r.M);m.model=e.normalized,h=e.aliases}let b=(0,l.O)(t),w=await d({sourceModel:m.model,sourceModelAliases:h,sourceEffort:m.sourceEffort,hasReasoningSignal:m.hasReasoningSignal,hasThinkingBudget:m.hasThinkingBudget,apiKeyId:p?.id??null,comboId:"string"==typeof g?.id?g.id:null,requestTags:b.tags});if(!w)return{body:t,modelStr:n,reasoningIntent:m,reasoningDecision:null,requestRoutingTags:b,response:null};if("error"in w)return{body:t,modelStr:n,reasoningIntent:m,reasoningDecision:null,requestRoutingTags:b,response:w.error};let _=await ("unsupported"===w.capability&&!w.targetCombo?{response:(0,o.errorResponse)(i.p.BAD_REQUEST,`Reasoning effort '${w.targetEffort}' is not supported by the configured target`)}:(0,a.V)(e,c.apiKey,p,w.targetModel).then(e=>{if(e)return s.warn("REASONING_ROUTE",`Rule ${w.rule.id} target rejected by API key policy`),{response:e};for(let e of(s.info("REASONING_ROUTE",`Rule ${w.rule.id}: ${w.sourceModel}/${w.sourceEffort} → ${w.targetModel}/${w.targetEffort||"inherit"}`),w.warnings))s.warn("REASONING_ROUTE",`Rule ${w.rule.id}: ${e}`);return{body:(0,u.G)(t,w),modelStr:w.targetModel,response:null}}));return _.response?{body:t,modelStr:n,reasoningIntent:m,reasoningDecision:w,requestRoutingTags:b,response:_.response}:{body:_.body,modelStr:_.modelStr,reasoningIntent:m,reasoningDecision:w,requestRoutingTags:b,response:null}}async function p({requestBody:e,provider:t,effectiveModel:n,credentials:r,apiKeyInfo:a,reasoningIntent:l,reasoningDecision:c,requestRoutingTags:d}){if(c||!l)return{body:e,response:null};let f=await (0,u.t)({sourceModel:l.model,sourceEffort:l.sourceEffort,hasReasoningSignal:l.hasReasoningSignal,hasThinkingBudget:l.hasThinkingBudget,apiKeyId:a?.id??null,connectionId:r.connectionId,requestTags:d??[],connectionOnly:!0,capabilityModel:`${t}/${n}`});return f?"unsupported"===f.capability?{body:e,response:(0,o.errorResponse)(i.p.BAD_REQUEST,`Reasoning effort '${f.targetEffort}' is not supported by the selected connection model`)}:(s.info("REASONING_ROUTE",`Connection rule ${f.rule.id} applied to ${r.connectionId}`),{body:(0,u.G)(e,f),response:null}):{body:e,response:null}}[r,a]=c.then?(await c)():c,e.s(["L",0,p,"i",0,f,"d",0,function(e,t){let n=(0,u.W)(e,t);return n.combo?(n.removed.length>0&&s.warn("REASONING_ROUTE",`Rule ${t.rule.id} skipped ${n.removed.length} incompatible combo target(s)`),n.combo):(0,o.errorResponse)(i.p.BAD_REQUEST,"Reasoning routing policy leaves no compatible combo target")}]),n()}catch(e){n(e)}},!1),877621,e=>{"use strict";async function t(e,n=null){return null!=n?n:await e.json()}e.s(["f",0,t])},594737,e=>{"use strict";async function t(e){let{body:t,modelBeforeGuardrails:n,apiKey:r,apiKeyId:o,isModelAllowedForKey:i,log:a}=e,{modelStr:l}=e;if(t?.model&&"string"==typeof t.model&&t.model!==n){let e=t.model;return await i(r,e)?(a.info("ROUTING",`Guardrail model reroute: ${n} → ${e}`),{body:t,modelStr:e}):(a.warn("POLICY",`Guardrail reroute to "${e}" rejected by API key policy (key=${o||"unknown"}); keeping original model "${l}"`),{body:{...t,model:l},modelStr:l})}return l&&"string"==typeof t?.model&&t.model!==l?{body:{...t,model:l},modelStr:l}:{body:t,modelStr:l}}e.s(["R",0,{align:function(e,t,n){let r,o=(r="string"==typeof e?.model?e.model:null,t&&"string"==typeof t&&0!==t.length&&r!==t?{body:{...e,model:t},aligned:!0,previousModel:r}:{body:e,aligned:!1,previousModel:r});return o.aligned&&n.info("ROUTING",`Aligned body.model to routing model: ${o.previousModel||"(none)"} → ${t}`),o.body},reconcileGuardrailReroute:t,reconcileModelOverride:function(e){let{body:t,overrideModel:n,logTag:r,log:o}=e,{modelStr:i}=e;return n&&n!==i?(o.info("ROUTING",`${r}: ${i} → ${n}`),i=n,"string"!=typeof t?.model||t.model!==i)?{body:{...t,model:i},modelStr:i}:{body:t,modelStr:i}:i&&"string"==typeof t?.model&&t.model!==i?{body:{...t,model:i},modelStr:i}:{body:t,modelStr:i}}},"F",0,function(e,t){return e.headers.get("x-route-model")?.trim()||t.model}])},720902,e=>e.a(async(t,n)=>{try{var r=e.i(666680),o=e.i(998905),i=e.i(186920),a=e.i(748648),l=e.i(780007),s=e.i(138324),u=e.i(939282),c=e.i(878947),d=e.i(892373),f=e.i(85713),p=e.i(373004),y=e.i(192408),m=t([i,a,l,s,d,y]);[i,a,l,s,d,y]=m.then?(await m)():m;let N=new Set(["kiro","openai"]);function g(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.type&&/^web_search_\d{8}$/.test(e.type)&&!e.function}function h(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.type&&/^web_fetch_\d{8}$/.test(e.type)&&!e.function}async function b(e){let t=await (0,y.M)(e).catch(()=>null),n=t?.provider;if(!n)return!1;try{return N.has(String((0,f.a)(n)))}catch{return!1}}async function w(e,t=0){if(!e||t>3)return!1;let n=await (0,y.Q)(e).catch(()=>null),r=Array.isArray(n?.models)?n.models:null;if(!r)return b(e);for(let e of r){if((0,o.l)(e))continue;if(e&&"object"==typeof e&&"combo-ref"===e.kind){if(await w(String(e.comboName||""),t+1))return!0;continue}let n=(0,o.I)(e);if(n&&await b(n))return!0}return!1}function _(e,t){let n=t.toLowerCase().replace(/^\*\./,"").replace(/^www\./,""),r=e.replace(/^www\./,"");return r===n||r.endsWith(`.${n}`)}function A(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e.trim()).map(e=>e.trim()):[]}async function I(e,t,n){let r=e=>{let n=function(e){try{return new URL(e).hostname.toLowerCase()}catch{return""}}(e);return!(!n||t.blocked.some(e=>_(n,e)))&&(!t.allowed.length||!!t.allowed.some(e=>_(n,e)))},o="";try{let{data:n}=await (0,l.f)({query:e,max_results:5,filters:{...t.allowed.length?{include_domains:t.allowed}:{},...t.blocked.length?{exclude_domains:t.blocked}:{}},apiKeyId:t.apiKeyId??null}),o=(n.results||[]).filter(e=>e?.url&&r(e.url)).map(e=>({title:e.title||e.url,url:e.url,snippet:e.snippet||"",pageAge:e.published_at?String(e.published_at):null,...e.content?.text?{pageText:String(e.content.text).slice(0,3e3)}:{}}));if(o.length)return{items:o,provider:n.provider}}catch(e){o=e instanceof Error?e.message:String(e)}let i=[e,...1===t.allowed.length?[`site:${t.allowed[0]}`]:[],...t.blocked.map(e=>`-site:${e}`)].join(" ").slice(0,400);try{return{items:(await (0,d.f)(i,8,1e4)).filter(e=>r(e.url)).slice(0,5).map(e=>({title:e.title||e.url,url:e.url,snippet:e.snippet||"",pageAge:null})),provider:"duckduckgo-free"}}catch(t){let e=t instanceof Error?t.message:String(t);throw n?.warn?.("WEBSEARCH",`search failed (${o?`${o.slice(0,120)}; `:""}free search: ${e.slice(0,120)})`),Error("web search unavailable")}}function k(e){let t=e.slice(0,786432),n=t.toLowerCase(),r=n.indexOf("<body");if(-1!==r){let e=n.indexOf(">",r),o=n.lastIndexOf("</body");t=t.slice(-1===e?r:e+1,o>r?o:void 0)}return(t=(t=(t=(t=function(e,t){let n=e.toLowerCase(),r=[...t.map(e=>({open:`<${e}`,close:`</${e}`,end:">"})),{open:"<!--",close:"-->",end:""}],o=r.map(()=>-2),i="",a=0;for(;a<e.length;){let t=-1,l=-1;for(let e=0;e<r.length;e++)-1!==o[e]&&o[e]<a&&(o[e]=n.indexOf(r[e].open,a)),-1!==o[e]&&(-1===t||o[e]<t)&&(t=o[e],l=e);if(-1===t){i+=e.slice(a);break}let s=r[l],u=n.charAt(t+s.open.length);if(s.end&&/[a-z0-9-]/.test(u)){i+=e.slice(a,t+1),a=t+1;continue}i+=`${e.slice(a,t)} `;let c=n.indexOf(s.close,t+s.open.length);if(-1===c)break;if(s.end){let t=n.indexOf(">",c);a=-1===t?e.length:t+1}else a=c+s.close.length}return i}(t,["script","style","noscript","svg","template","iframe","nav","footer","header","aside","form","head"])).replace(/<\/?(p|div|br|li|ul|ol|h[1-6]|tr|table|section|article|pre|blockquote)\b[^>]{0,500}>/gi,"\n")).replace(/<[^>]{0,2000}>/g," ")).replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/�*39;|'/gi,"'").replace(/&#(\d{1,6});/g,(e,t)=>{let n=Number(t);return n>0&&n<1114112?String.fromCodePoint(n):" "}).replace(/&/gi,"&")).split("\n").map(e=>e.replace(/[ \t\r\f\v]+/g," ").trim()).filter(e=>e.length>1).join("\n").replace(/\n{3,}/g,"\n\n")}async function v(e,t,n,r){let o=e;for(let e=0;e<5;e++){let e;if(t?.aborted)break;try{e=await (0,s.u)(o,{method:"GET",guard:"public-only",allowRedirect:!1,timeoutMs:6e3,retry:!1,headers:{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0 Safari/537.36",Accept:r}})}catch{break}if(e.status>=300&&e.status<400){let t=e.headers.get("location");if(await e.body?.cancel().catch(()=>{}),!t)return null;try{o=new URL(t,o).href}catch{return null}continue}let i=(e.headers.get("content-type")||"").toLowerCase();if(!e.ok)return await e.body?.cancel().catch(()=>{}),{status:e.status,contentType:i,bytes:Buffer.alloc(0),url:o};let a=e.body?.getReader();if(!a)return{status:e.status,contentType:i,bytes:Buffer.alloc(0),url:o};let l=[],u=0;for(;u<=n;){let{done:e,value:t}=await a.read().catch(()=>({done:!0,value:void 0}));if(e||!t)break;l.push(t),u+=t.length}return await a.cancel().catch(()=>{}),{status:e.status,contentType:i,bytes:Buffer.concat(l.map(e=>Buffer.from(e))),url:o}}return null}async function T(e,t){let n=await v(e,t,786432,"text/html,text/plain;q=0.9,*/*;q=0.5");if(!n||200!==n.status||!/text\/html|text\/plain|application\/xhtml/.test(n.contentType))return"";let r=n.bytes.subarray(0,786432).toString("utf8");return(n.contentType.includes("text/plain")?r:k(r)).slice(0,3e3)}async function R(e,t,n){let r,o=await v(e,n,0x2000000,"text/html,application/xhtml+xml,text/plain;q=0.9,application/pdf;q=0.9,*/*;q=0.5");if(!o)return{ok:!1,errorCode:"url_not_accessible"};if(429===o.status)return{ok:!1,errorCode:"too_many_requests"};if(200!==o.status)return{ok:!1,errorCode:"url_not_accessible"};let i=o.contentType;if(i.includes("application/pdf")||"%PDF-"===o.bytes.subarray(0,5).toString())return o.bytes.length>0x2000000?{ok:!1,errorCode:"content_too_large"}:{ok:!0,url:o.url,title:"",pdfBase64:o.bytes.toString("base64")};if(!(/text\/|application\/(xhtml\+xml|xml|json|javascript|x-javascript|rss\+xml|atom\+xml)/.test(i)||""===i))return{ok:!1,errorCode:"unsupported_content_type"};let a=o.bytes.subarray(0,4194304).toString("utf8"),l=/html|xml/.test(i)||/^\s*<(!doctype|html)/i.test(a.slice(0,200)),s=l?k(a.slice(0,4194304)):a;return s.length>t&&(s=`${s.slice(0,t)}
|
|
2
2
|
[... cut at the content limit]`),{ok:!0,url:o.url,title:l?(r=/<title[^>]{0,200}>([\s\S]{0,500}?)<\/title>/i.exec(a.slice(0,2e5)))?k(r[1]).replace(/\s+/g," ").trim().slice(0,300):"":"",text:s}}let U=/https?:\/\/[^\s"'<>`{}|\\^[\]]+/gi;function S(e){try{let t=new URL(e.replace(/[.,;:!?)]+$/,""));t.hash="";let n=t.href;return n.endsWith("/")&&"/"!==t.pathname&&(n=n.slice(0,-1)),"/"!==t.pathname||t.search||(n=`${t.protocol}//${t.host}`),n.toLowerCase()}catch{return""}}function E(e,t){for(let n of e.matchAll(U)){let e=S(n[0]);e&&t.add(e)}}function x(e){let t=e||{};return{type:"string"==typeof t.type?t.type:"all",tools:Array.isArray(t.tools)?t.tools.map(e=>String(e?.name||"")).filter(Boolean):[]}}function $(e,t){return"none"!==e.type&&("only"===e.type?e.tools.includes(t):"except"!==e.type||!e.tools.includes(t))}async function C(e,t,n,r){let{items:o,provider:i}=await I(e,t,r);return"0"!==process.env.TROUTEAI_WEB_SEARCH_READ_PAGES&&await Promise.all(o.slice(0,3).map(async e=>{e.pageText||(e.pageText=await T(e.url,n))})),r?.info?.("WEBSEARCH",`"${e.slice(0,80)}": ${o.length} results via ${i}, ${o.filter(e=>e.pageText).length} pages read`),o}function O(e){let t=/(?:opus|sonnet|haiku|fable)-(\d+)(?:[-.](\d))?(?:$|[^0-9])/.exec(e);return t?Number(t[1])+(t[2]?Number(t[2])/10:0):0}async function M(){let e=(process.env.TROUTEAI_WEB_SEARCH_FALLBACK_MODEL||"").trim();if(e)return"off"===e.toLowerCase()?null:e;for(let e of["claude","anthropic"]){if(!(await (0,a.W)({provider:e}).catch(()=>[])).some(e=>e?.isActive!==!1))continue;let t=await (0,i.c)(e).catch(()=>[])||[],n=[...new Set([...(0,c.getModelsByProviderId)(e).map(e=>e.id),...t.map(e=>String(e?.id||"")).filter(Boolean)])].filter(t=>{try{return!(0,i.J)(e,t)}catch{return!0}}),r=(e,t)=>O(t)-O(e),o=n.filter(e=>e.includes("sonnet")).sort(r)[0];if(o)return`${e}/${o}`}return null}let D=e=>`${e}${(0,r.randomBytes)(12).toString("base64url")}`;async function L(e){let{body:t,callModel:n,log:r}=e,o=e.request?.signal??null,i=e.search||((e,t)=>C(e,t,o,r)),a=e.nativeModel||M,l=e.fetch||((e,t)=>R(e,t,o)),s=Array.isArray(t.tools)?t.tools:[],c=s.find(g),d=s.find(h),f=s.filter(e=>!g(e)&&!h(e)),y=new Set(f.map(e=>String(e?.name||""))),m=y.has("web_search")?"trouteai_web_search":"web_search",b=y.has("web_fetch")?"trouteai_web_fetch":"web_fetch",w=e=>Math.min(10,Math.max(1,Number(e?.max_uses)>0?Number(e?.max_uses):5)),I=w(c),k=w(d),v=Number(d?.max_content_tokens)>0?Math.min(4e5,Math.ceil(3*Number(d?.max_content_tokens))):1e5,T=d?.citations?.enabled===!0,O={user:x(d?.url_sources?.user_input),client:x(d?.url_sources?.client_tool_results),server:x(d?.url_sources?.server_tool_results)},L={allowed:A(c?.allowed_domains),blocked:A(c?.blocked_domains),apiKeyId:e.apiKeyId},N={allowed:A(d?.allowed_domains),blocked:A(d?.blocked_domains)},U={name:m,description:"Search the web for current information. Returns the top results with title, URL, a summary and the text of the first pages. Use it when the answer needs recent or outside facts.",input_schema:{type:"object",properties:{query:{type:"string",description:"The search query"}},required:["query"]}},B={name:b,description:"Fetch the full content of a web page or PDF by its URL. Only URLs that appeared earlier in the conversation (written by the user, in a tool result, or in web search / fetch results) can be fetched.",input_schema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"}},required:["url"]}},F=t.tool_choice,q=F?.type==="tool"&&c&&F.name===c.name?m:F?.type==="tool"&&d&&F.name===d.name?b:F?.type!=="any"||0!==f.length||c&&d?"":c?m:b,j=F?.type==="any"||!!q,K=[...t.messages||[]],{allowed:P,user:G}=function(e,t){let n=new Set,r=new Set,o=new Map;for(let i of e){let e=i?.content;if(i?.role==="assistant"&&Array.isArray(e)){for(let r of e){if((r?.type==="tool_use"||r?.type==="server_tool_use")&&r.id&&o.set(String(r.id),String(r.name||"")),r?.type==="web_search_tool_result"&&$(t.server,"web_search"))for(let e of Array.isArray(r.content)?r.content:[])"string"==typeof e?.url&&E(e.url,n);if(r?.type==="web_fetch_tool_result"&&$(t.server,"web_fetch")){let e=r.content;"string"==typeof e?.url&&E(e.url,n);let t=e?.content?.source;t?.type==="text"&&"string"==typeof t.data&&E(t.data,n)}}continue}if(i?.role==="user"){if("string"==typeof e){E(e,r);continue}for(let i of Array.isArray(e)?e:[])if(i?.type==="text"&&"string"==typeof i.text&&E(i.text,r),i?.type==="tool_result"){let e=o.get(String(i.tool_use_id||""))||"";if(!$(t.client,e))continue;let r="string"==typeof i.content?[i.content]:[];for(let e of Array.isArray(i.content)?i.content:[])e?.type==="text"&&"string"==typeof e.text&&r.push(e.text);for(let e of r)E(e,n)}}}if("none"!==t.user.type)for(let e of r)n.add(e);return{allowed:n,user:r}}(K,O),Q=(e,n,r)=>{let o=[...c&&e?[U]:[],...d&&n?[B]:[]],i={...t,stream:!1,messages:K,tools:[...f,...o]};return 0===i.tools.length&&delete i.tools,j&&r&&q&&o.some(e=>e.name===q)?i.tool_choice={type:"tool",name:q}:t.tool_choice&&(j||0===o.length)&&(i.tools?.length?i.tool_choice=r&&F?.type==="any"?{type:"any"}:{type:"auto"}:delete i.tool_choice),i},H=e=>e?.type==="tool_use"&&(!!c&&e.name===m||!!d&&e.name===b),W=e=>{let t;if(!e)return"invalid_tool_input";if(e.length>250)return"url_too_long";try{t=new URL(e)}catch{return"invalid_tool_input"}if("http:"!==t.protocol&&"https:"!==t.protocol)return"invalid_tool_input";let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if("localhost"===n||(0,u.W)(n)||N.blocked.some(e=>_(n,e))||N.allowed.length&&!N.allowed.some(e=>_(n,e)))return"url_not_allowed";let r=S(e);return function(e){if(e.username||e.password)return!0;for(let t of e.searchParams.keys())if(/(^|[_-])(key|apikey|token|secret|password|passwd|pwd|auth|signature|sig)$/i.test(t))return!0;return!1}(t)&&!G.has(r)?"url_not_allowed":P.has(r)?"":"url_not_in_prior_context"},z=await n(Q(!0,!0,!0));if(!z.ok)return z;let Y=await z.json().catch(()=>null);if(!Y||!Array.isArray(Y.content))return new Response(JSON.stringify({type:"error",error:{type:"api_error",message:"The model answered in an unexpected format"}}),{status:502,headers:{"content-type":"application/json"}});let J=c?Y.content.filter(e=>e?.type==="tool_use"&&e.name===m):[],V=null;if(J.length>0){V=new Map;let e=String(J[0].input?.query||"").trim();try{V.set(String(J[0].id),await i(e,L))}catch(o){let e=await a().catch(()=>null);if(e){r?.warn?.("WEBSEARCH",`no web search reachable; sending this request to ${e}`);let o=await n({...t,model:e});if(o.ok)return o;await o.body?.cancel().catch(()=>{})}V.set(String(J[0].id),o)}}let X=!0===t.stream,Z={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},ee=0,et=0,en=()=>({...c?{web_search_requests:ee}:{},...d?{web_fetch_requests:et}:{}}),er=!1,eo=()=>er||!!o?.aborted,ei=async e=>{let t=[],r=n=>{t.push(n),e.block(n)};e.start(Y);let o=!0,a=!0;for(let t=0;t<12;t++){let t=Y;!function(e,t){let n=t||{},r=e=>"number"==typeof e&&Number.isFinite(e)?e:0;e.input_tokens+=r(n.input_tokens),e.output_tokens+=r(n.output_tokens),e.cache_creation_input_tokens+=r(n.cache_creation_input_tokens),e.cache_read_input_tokens+=r(n.cache_read_input_tokens)}(Z,t.usage);let s=t.content||[],u=s.filter(H),f=s.some(e=>e?.type==="tool_use"&&!H(e)),y=[];for(let e of s){if(!H(e)){r(e);continue}if(e.name===b&&d){let t=String(e.input?.url||"").trim(),n=D("srvtoolu_");r({type:"server_tool_use",id:n,name:String(d.name||"web_fetch"),input:{url:t}});let o="",i=null;if(et>=k?o="max_uses_exceeded":(et++,(o=W(t))||(i=await l(t,v).catch(()=>({ok:!1,errorCode:"unavailable"}))).ok||(o=i.errorCode)),i?.ok){let t=i.pdfBase64?{type:"document",source:{type:"base64",media_type:"application/pdf",data:i.pdfBase64}}:{type:"document",source:{type:"text",media_type:"text/plain",data:i.text||""},...i.title?{title:i.title}:{}};T&&(t.citations={enabled:!0}),r({type:"web_fetch_tool_result",tool_use_id:n,content:{type:"web_fetch_result",url:i.url,content:t,retrieved_at:new Date().toISOString()}}),y.push({type:"tool_result",tool_use_id:e.id,content:[{type:"text",text:`Fetched ${i.url}${i.title?` (${i.title})`:""}:`},t]}),P.add(S(i.url)),i.text&&$(O.server,"web_fetch")&&E(i.text,P)}else r({type:"web_fetch_tool_result",tool_use_id:n,content:{type:"web_fetch_tool_result_error",error_code:o}}),y.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:"url_not_in_prior_context"===o?"This URL cannot be fetched: only URLs that appeared earlier in the conversation (from the user, a tool result or a web search) can be. Search for it first or ask the user for it.":"max_uses_exceeded"===o?"The fetch limit for this request is reached. Answer now with what you have.":`The page could not be fetched (${o}).`});continue}let t=String(e.input?.query||"").trim(),n=D("srvtoolu_");r({type:"server_tool_use",id:n,name:String(c?.name||"web_search"),input:{query:t}});let o=null,a="";if(ee>=I)a="max_uses_exceeded";else if(t){ee++;let n=V?.get(String(e.id)),r=void 0!==n?n:await i(t,L).catch(e=>e);r instanceof Error?a="unavailable":o=r}else a="invalid_tool_input";if(o&&$(O.server,"web_search"))for(let e of o)P.add(S(e.url));r({type:"web_search_tool_result",tool_use_id:n,content:o?o.map(e=>({type:"web_search_result",title:e.title,url:e.url,encrypted_content:(0,p.W)(e),page_age:e.pageAge||null})):{type:"web_search_tool_result_error",error_code:a}}),y.push({type:"tool_result",tool_use_id:e.id,content:o?(0,p.m)(t,o):"max_uses_exceeded"===a?"The search limit for this request is reached. Answer now with what you have.":"The web search is not available right now. Answer from what you know and say that you could not search.",...o?{}:{is_error:!0}})}if(V=null,0===u.length||f||eo())return void e.finish({...t,usage:{...Z,server_tool_use:en()}});K.push({role:"assistant",content:s},{role:"user",content:y}),ee>=I&&(o=!1),et>=k&&(a=!1);let m=await n(Q(o,a,!1));if(!m.ok){let t=await m.text().catch(()=>""),n=`The model request failed (HTTP ${m.status})`;try{let e=JSON.parse(t);n=String(e?.error?.message||e?.message||n)}catch{}e.fail(n);return}if(!(Y=await m.json().catch(()=>null))||!Array.isArray(Y.content))return void e.fail("The model answered in an unexpected format")}e.finish({...Y,usage:{...Z,server_tool_use:en()}})};if(!X){let e=[],t={final:null,failure:""};if(await ei({start(){},block:t=>e.push(t),ping(){},finish:e=>{t.final=e},fail:e=>{t.failure=e}}),t.failure||!t.final)return new Response(JSON.stringify({type:"error",error:{type:"api_error",message:t.failure||"Web search failed"}}),{status:502,headers:{"content-type":"application/json"}});let n=t.final;return new Response(JSON.stringify({id:n.id,type:"message",role:"assistant",model:n.model,content:e,stop_reason:n.stop_reason??"end_turn",stop_sequence:n.stop_sequence??null,stop_details:n.stop_details??null,usage:n.usage}),{status:200,headers:{"content-type":"application/json"}})}let ea=new TextEncoder;return new Response(new ReadableStream({async start(e){let t=!1,n=(n,r)=>{if(!t)try{e.enqueue(ea.encode(`event: ${n}
|
|
3
3
|
data: ${JSON.stringify(r)}
|
|
4
4
|
|