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=[538038,e=>e.a(async(t,n)=>{try{var r=e.i(58501),i=e.i(998158),o=e.i(846280),l=t([r]);[r]=l.then?(await l)():l;let c=new Set(["max_tokens","tool_use"]),d=new Set(["length","tool_calls","content_filter"]),f={RATE_LIMITED:"rate_limited",UNAUTHORIZED:"unauthorized",ACCOUNT_DEACTIVATED:"account_deactivated",FORBIDDEN:"forbidden",SERVER_ERROR:"server_error",QUOTA_EXHAUSTED:"quota_exhausted",PROJECT_ROUTE_ERROR:"project_route_error",CONTEXT_OVERFLOW:"context_overflow",OAUTH_INVALID_TOKEN:"oauth_invalid_token",EMPTY_CONTENT:"empty_content",MODEL_NOT_FOUND:"model_not_found"},p=RegExp("context overflow|prompt too large|context window|maximum context|exceeds context|input too long|token limit|too many tokens|context length|exceed.*context|messages exceed","i"),g=/\bmodel\b[^\n]{0,80}\bis not supported\b/i;function a(e){return g.test(String(e||"").toLowerCase())}function s(e){if("string"==typeof e)return e;if(null!==e&&"object"==typeof e)try{return JSON.stringify(e)}catch{}return""}let m=[/\bfiles?\b[^\n]{0,160}\b(?:not found|does not exist)\b/i,/\b(?:not found|does not exist)\b[^\n]{0,160}\bfiles?\b/i,/\b(?:input[_ -]?file|file[_ -]?id|item|response|vector[_ -]?store|upload)\b[^\n]{0,160}\b(?:not found|does not exist)\b/i,/\b(?:not found|does not exist)\b[^\n]{0,160}\b(?:input[_ -]?file|file[_ -]?id|item|response|vector[_ -]?store|upload)\b/i,/\bfile-[a-z0-9_-]+\b[^\n]{0,160}\b(?:not found|does not exist)\b/i];function u(e){let t=s(e);return m.some(e=>e.test(t))}let h=/\bversion of [^\n]{1,60}\bis no longer supported\b/i,y=/\bbearer token included in the request is invalid\b|(?:^|\]:\s*|"message"\s*:\s*")Invalid token\b/i;e.s(["u",0,p,"R",0,f,"k",0,function(e,t,n){let l=s(t),c=(0,r.X)(l),d=(0,i.M)(l.toLowerCase()),g=(0,r.H)(l),m=(0,r.P)(l),w=!n||"oauth"===(0,o.Z)(n);if((c||d)&&[400,402,403].includes(e)||(c||d)&&429===e&&w)return f.QUOTA_EXHAUSTED;if(429===e)return w&&(0,r.N)(l)?f.QUOTA_EXHAUSTED:f.RATE_LIMITED;if(404===e)return u(t)?null:f.MODEL_NOT_FOUND;if(401===e)return m?f.OAUTH_INVALID_TOKEN:a(l)?f.MODEL_NOT_FOUND:g?f.ACCOUNT_DEACTIVATED:f.UNAUTHORIZED;if(402===e)return f.QUOTA_EXHAUSTED;if(403===e&&g)return f.ACCOUNT_DEACTIVATED;if(403===e){let e;if("kiro"===(e=(n||"").toLowerCase())||"amazon-q"===e){if(h.test(String(l||"")))return null;if(y.test(String(l||"")))return f.UNAUTHORIZED}let t=(n||"").toLowerCase(),r="antigravity"===t||"gemini-cli"===t||t.includes("cloudcode")||t.includes("cloud-code");return l.includes("has not been used in project")||l.includes("SERVICE_DISABLED")||l.includes("accessNotConfigured")||l.includes("PERMISSION_DENIED")||/\bit is disabled\b/i.test(l)||r?f.PROJECT_ROUTE_ERROR:n&&"apikey"===(0,o.Z)(n)||n&&(0,o.k)(n)?.authType==="none"?null:f.FORBIDDEN}if(e>=500)return f.SERVER_ERROR;if(400===e){if(p.test(String(l||"")))return f.CONTEXT_OVERFLOW;if(a(l))return f.MODEL_NOT_FOUND}return null},"c",0,a,"D",0,function(e){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e.choices)){let t=e.choices[0];if(!t)return!0;let n=t.message,r=t.delta,i=n?.content??r?.content,o=n?.reasoning_content??r?.reasoning_content,l=Array.isArray(n?.tool_calls)&&n.tool_calls.length>0||Array.isArray(r?.tool_calls)&&r.tool_calls.length>0,a="string"==typeof t.finish_reason?t.finish_reason:"";return!d.has(a)&&(null==i||""===i)&&(null==o||""===o)&&!l}if(Array.isArray(e.content)){if(e.content.length>0)return!1;let t="string"==typeof e.stop_reason?e.stop_reason:"";return!c.has(t)}if("string"==typeof e.text)return""===e.text.trim();if("content"in e){let t=e.content;return null==t||""===t}return!1},"n",0,u]),n()}catch(e){n(e)}},!1),507651,e=>e.a(async(t,n)=>{try{var r=e.i(309559),i=e.i(933990),o=t([r]);[r]=o.then?(await o)():o;let a=Object.values(i.f);function l(e){let t=e instanceof Set?Array.from(e):e;return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[])}e.s(["H",0,function(e,...t){let n=l(e);return a.some(e=>t.some(t=>t===e.id||t===e.alias)&&(n.has(e.id)||"string"==typeof e.alias&&n.has(e.alias)))},"I",0,function(...e){return a.some(t=>e.some(e=>e===t.id||e===t.alias))},"$",0,function(e,t){let n=a.find(t=>t.id===e);return"string"==typeof n?.alias&&n.alias!==e&&t===e},"q",0,function(e,t){let n=l(t),i=(0,r.Q)(e);return n.has(e)||"string"==typeof i?.alias&&n.has(i.alias)},"Q",0,l]),n()}catch(e){n(e)}},!1),756346,e=>{"use strict";var t=e.i(666680);e.s(["R",0,function(){let e=(0,t.randomBytes)(6),n=0;for(let t=0;t<e.length;t++)n=256*n+e[t];return n/0x1000000000000},"$",0,function(e){if(!Number.isFinite(e)||e<=1)return 0;let n=Math.floor(e);return(0,t.randomInt)(n)}])},39197,e=>{"use strict";var t=e.i(756346);let n=new Map,r=new Map;function i(e){let n=[...e];for(let e=n.length-1;e>0;e--){let r=(0,t.$)(e+1),i=n[e];n[e]=n[r],n[r]=i}return n}async function o(e,o){let l;if(0===o.length)return"";if(1===o.length)return o[0];let a=r.get(e)??Promise.resolve();r.set(e,new Promise(e=>{l=e}));try{await a;let r=[...o].sort().join(","),l=n.get(e);if(l&&l.idsKey===r&&l.index<l.order.length){let t=l.order[l.index];return n.set(e,{...l,index:l.index+1}),t}let s=l&&l.idsKey===r&&l.order.length>0?l.order[l.order.length-1]:void 0,u=i(o);if(void 0!==s&&u[0]===s&&u.length>1){let e=1+(0,t.$)(u.length-1),n=u[0];u[0]=u[e],u[e]=n}return n.set(e,{order:u,index:1,idsKey:r}),u[0]}finally{l?.()}}e.s(["k",0,i,"w",0,o,"B",0,function(e,r){if(0===r.length)return"";if(1===r.length)return r[0];let o=[...r].sort().join(","),l=n.get(e);if(l&&l.idsKey===o&&l.index<l.order.length){let t=l.order[l.index];return n.set(e,{...l,index:l.index+1}),t}let a=l&&l.idsKey===o&&l.order.length>0?l.order[l.order.length-1]:void 0,s=i(r);if(void 0!==a&&s[0]===a&&s.length>1){let e=1+(0,t.$)(s.length-1),n=s[0];s[0]=s[e],s[e]=n}return n.set(e,{order:s,index:1,idsKey:o}),s[0]}])},259298,e=>e.a(async(t,n)=>{try{e.s(["h",()=>ep,"N",()=>eg,"M",()=>J,"t",()=>em,"J",()=>F,"o",()=>ec,"m",()=>ed,"K",()=>eu,"Q",()=>eh,"p",()=>ef,"g",()=>N,"q",()=>Z]);var r=e.i(254799),i=e.i(350793),o=e.i(13572),l=e.i(687267),a=e.i(648830),s=e.i(950412),u=e.i(635824),c=e.i(435005),d=e.i(872704),f=e.i(402016),p=e.i(58501),g=e.i(846280),m=e.i(394043),h=e.i(670055),y=e.i(836184),w=e.i(858279),A=e.i(264590),b=e.i(900930),$=e.i(538038),U=e.i(468250),S=e.i(309559),T=e.i(933990),v=e.i(611704),x=e.i(987227),E=e.i(114843),C=e.i(367333),D=e.i(186071),k=e.i(348704),_=e.i(457308),M=e.i(131707),I=e.i(39197),R=t([i,o,a,s,c,p,$,S,E,C,_]);[i,o,a,s,c,p,$,S,E,C,_]=R.then?(await R)():R;let ey=new Set(["not_found","not_found_local"]);function O(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function L(e,t=0){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim().length>0){let n=Number(e);return Number.isFinite(n)?n:t}return t}function H(e,t){return"boolean"==typeof e?e:t}function N(e,t){if(!e)return null;if("function"==typeof e.get){let n=e.get(t)||e.get(t.toLowerCase());return"string"==typeof n&&n.trim().length>0?n.trim():null}let n=e[t]||e[t.toLowerCase()]||e[t.toUpperCase()];return Array.isArray(n)?"string"==typeof n[0]&&n[0].trim().length>0?n[0].trim():null:"string"==typeof n&&n.trim().length>0?n.trim():null}function P(e,t){if("string"!=typeof e||0===e.trim().length)return null;let n=e.trim();return n.length<=180&&/^[A-Za-z0-9._:-]+$/.test(n)?`${t}:${n}`:`${t}:sha256:${(0,r.createHash)("sha256").update(n).digest("hex")}`}function q(e){if("string"==typeof e)return e;if(Array.isArray(e)){let t=e.map(e=>{if("string"==typeof e)return e;let t=O(e);return"string"==typeof t.text?t.text:"string"==typeof t.content?t.content:null}).filter(Boolean);return t.length>0?t.join("\n"):JSON.stringify(e)}return e&&"object"==typeof e?JSON.stringify(e):null}function F(e,t){let n=P(N(t,"x-codex-session-id")??N(t,"x-session-id")??N(t,"x-trouteai-session"),"header");if(n)return n;let i=O(e),o=O(i.metadata),l=P(o.session_id,"metadata")??P(o.sessionId,"metadata")??P(i.conversation_id,"conversation")??P(i.session_id,"session")??P(i.prompt_cache_key,"prompt-cache");if(l)return l;let a=function(e){let t=O(e);if(void 0!==t.input){if("string"==typeof t.input)return t.input;if(Array.isArray(t.input))for(let e of t.input){let t=q(O(e).content??e);if(t&&t.trim().length>0)return t}let e=q(t.input);if(e&&e.trim().length>0)return e}if(Array.isArray(t.messages)){let e=t.messages.find(e=>"user"===O(e).role)??t.messages[0],n=q(O(e).content??e);if(n&&n.trim().length>0)return n}return null}(e);return a&&0!==a.trim().length?`input:sha256:${(0,r.createHash)("sha256").update(a.slice(0,4096)).digest("hex")}`:null}function j(e,t=c.DEFAULT_QUOTA_THRESHOLD_PERCENT){return Math.min(100,Math.max(1,L(e,t)))}function Q(e){if("string"!=typeof e)return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function K(e){return[...new Set(e)]}function B(e){if("string"!=typeof e)return null;let t=e.trim().toLowerCase();return"session (5h)"===t||"5h"===t||"five_hour"===t?"session":"weekly (7d)"===t||"7d"===t||"seven_day"===t?"weekly":(0,U.Q)(t)}function W(e,t){if(!t)return null;let n=(0,U.A)(t),r=O(e.codexScopeRateLimitedUntil)[n];return"string"==typeof r&&r.trim().length>0?r:null}function V(e,t){let n=W(e.providerSpecificData,t);return!!n&&new Date(n).getTime()>Date.now()}function z(e){return(e||"").trim().toLowerCase()}function X(e){let t=z(e.testStatus);return"credits_exhausted"===t||"banned"===t||"expired"===t}function Z(e,t){let n=O(t.limitPolicy),r=(Array.isArray(n.windows)?n.windows:[]).map(Q).filter(Boolean);if("codex"===e){var i;let e,o,l,a=(i=r,o={use5h:H((e=O(t.codexLimitPolicy)).use5h,!0),useWeekly:H(e.useWeekly,!0)},l=(l=[...i.map(B).filter(Boolean)]).filter(e=>"session"===e?o.use5h:"weekly"!==e||o.useWeekly),o.use5h&&l.push("session"),o.useWeekly&&l.push("weekly"),K(l));return{enabled:H(n.enabled,a.length>0),thresholdPercent:j(n.thresholdPercent),windows:a}}return{enabled:H(n.enabled,!1),thresholdPercent:j(n.thresholdPercent),windows:r}}function J(e,t,n=null){let r=Z(e,t.providerSpecificData);if(!r.enabled||0===r.windows.length)return{blocked:!1,reasons:[],resetAt:null};let i=[],o=[];for(let l of r.windows){let a="codex"===e?(0,U.n)(l,n):l,s=(0,c.getQuotaWindowStatus)(t.id,a,r.thresholdPercent);s?.reachedThreshold&&(i.push(`${a} usage ${Math.round(s.usedPercentage)}%`),o.push(s.resetAt))}return{blocked:i.length>0,reasons:i,resetAt:G(o)}}function Y(e){if(!e)return null;let t=(0,p.Z)(e);return!Number.isFinite(t)||t<=Date.now()?null:t}function G(e){return e.map(e=>({raw:e,ms:Y(e)})).filter(e=>null!==e.ms).sort((e,t)=>e.ms-t.ms)[0]?.raw||null}function ee(e,t){Number.isFinite(t)&&e.push(Math.max(0,Math.min(100,t)))}function et(e,t,n=null,r){let i,o,l,a,s,u;if(t.id&&r?.has(t.id)){let e=r.get(t.id);i=e.blocked,o=e.exhausted}else i=J(e,t,n).blocked,o=(0,c.isQuotaExhaustedForRequest)(t.id,e,n);let d=function(e,t,n=null){let r=Z(e,t.providerSpecificData),i=function(e,t,n,r){let i=[],o=new Set;for(let l of n.windows){let a=Q("codex"===e?(0,U.n)(l,r):l);if(!a||o.has(a))continue;o.add(a);let s=(0,c.getQuotaWindowStatus)(t.id,a,n.thresholdPercent);s&&ee(i,s.remainingPercentage)}return i}(e,t,r,n),o=i.length>0?i:function(e,t,n){let r=(0,c.getQuotaCache)(t.id),i=r?.quotas||{},o="codex"===e?(0,U.O)(n):void 0,l=[];for(let[e,t]of Object.entries(i)){var a;(!o||o(e))&&(!t||function(e){if(!e)return!1;let t=new Date(e).getTime();return Number.isFinite(t)&&t<=Date.now()}("string"==typeof(a=t.resetAt)&&a.trim().length>0?a:null)||ee(l,L(t.remainingPercentage,0/0)))}return l}(e,t,n);return o.length>0?Math.min(...o):null}(e,t,n),f=0;return null!==d?(f+=Math.round((100-d)/8),d<=10?f+=10:d<=25&&(f+=4)):i||o||(f+=4),{score:200*!!o+80*!!i+(l=z(t.lastErrorType),a=z(t.lastErrorSource),s=L(t.errorCode,0),u=0,t.lastError&&(u+=6),"rate_limited"===l||"quota_exhausted"===l||"quota"===l||429===s?u+=24:401===s||403===s||"oauth"===a?u+=18:s>=500&&(u+=10),u)+Math.min(40,8*(t.backoffLevel||0))+f+Math.min(12,2*(t.consecutiveUseCount||0))+function(e){if(!e.lastUsedAt)return 0;let t=Date.now()-new Date(e.lastUsedAt).getTime();return Number.isFinite(t)?t<15e3?3:t<6e4?2:+(t<3e5):0}(t)+Math.min(6,Math.max(0,t.priority||0)-1),quotaHeadroomPercent:d}}function en(e,t,n,r=null,i){let o=et(e,t,r,i),l=et(e,n,r,i);if(o.score!==l.score)return o.score-l.score;let a=o.quotaHeadroomPercent??-1,s=l.quotaHeadroomPercent??-1;return a!==s?s-a:(t.priority||999)!==(n.priority||999)?(t.priority||999)-(n.priority||999):t.id.localeCompare(n.id)}let ew="noauth";async function er(e){try{let t=(0,k.f)(e),n={};for(let e of t){let t=await (0,a.W)({provider:e});for(let e of(Array.isArray(t)?t:[]).map(u.j))!function(e,t){let n=t.providerSpecificData;n&&"object"==typeof n&&(Array.isArray(n.fingerprints)&&!Array.isArray(e.fingerprints)&&(e.fingerprints=n.fingerprints),Array.isArray(n.accountProxies)&&!Array.isArray(e.accountProxies)&&(e.accountProxies=n.accountProxies))}(n,e)}return Array.isArray(n.accountProxies)&&(n.accountProxies=await (0,D.f)(n.accountProxies)),n}catch{return{}}}async function ei(e,t){let n,r,i;return(n=(0,S.Q)(e),r=T.f[e],i=v.a[e],n?.anonymousFallback!==!0&&r?.noAuth!==!0&&i?.noAuth!==!0||t.has(ew))?null:function(e={}){return{apiKey:null,accessToken:null,refreshToken:null,expiresAt:null,projectId:null,defaultModel:null,copilotToken:null,providerSpecificData:e,connectionId:ew,testStatus:"active",lastError:null,lastErrorType:null,lastErrorSource:null,errorCode:null,rateLimitedUntil:null,maxConcurrent:null}}(await er(e))}function eo(e,t){let n=new Set;if("string"==typeof e&&e.trim().length>0&&n.add(e.trim()),Array.isArray(t))for(let e of t)"string"==typeof e&&e.trim().length>0&&n.add(e.trim());return n}function el(e,t=6){let n=Array.from(e).filter(e=>"string"==typeof e&&e.length>0).slice(0,t).map(e=>`${e.slice(0,8)}...`);return n.length>0?n.join(","):"none"}function ea(e,t){let n=G(t.map(e=>e.resetAt??null))||new Date(Date.now()+3e5).toISOString(),r=t.map(e=>{let t=Number.isFinite(e.quotaPercent)?`${Math.round(100*e.quotaPercent)}%`:"quota exhausted";return`${e.id.slice(0,8)}(${t})`}).join("; ");return M.info("AUTH",`${e} | quota preflight filtered account(s): ${r}`),{allRateLimited:!0,retryAfter:n,retryAfterHuman:(0,p.s)(n),lastError:`All ${e} accounts blocked by quota preflight`,lastErrorCode:429,cooldownReason:"quota_exhausted"}}async function es(e,t,n,r){let i=new Date(Y(n.resetAt??null??null)??Date.now()+3e5).toISOString(),o=Number.isFinite(n.quotaPercent)?`${Math.round(100*n.quotaPercent)}%`:"exhausted",l=r?` for ${r}`:"";return await (0,a.s)(t,{rateLimitedUntil:i,testStatus:"unavailable",lastError:`Quota preflight blocked${l}: ${o}`,lastErrorType:"quota_exhausted",lastErrorSource:"quota_preflight",errorCode:429,lastErrorAt:new Date().toISOString()}),i}let eA=new Map,eb=new Map,e$=[["nvidia","nvidia_nim"],["kimi-coding","kimi-coding-apikey"]];async function eu(e){let t=(0,S.I)(e),n=(0,S.u)(t),r=e$.find(t=>t.includes(e));if(r)return r[0]===e?r:[r[1],r[0]];let i=new Set([e,t,n].filter(Boolean));if((0,S.Q)(t))return Array.from(i);try{let r=await (0,l.getCachedProviderNodes)();for(let o of Array.isArray(r)?r:[]){let r=O(o),l="string"==typeof r.prefix?r.prefix.trim():"",a="string"==typeof r.id?r.id.trim():"";l&&a&&(l===e||l===t||l===n)&&i.add(a)}}catch{}return Array.from(i)}let eU=new Map;async function ec(e,t=null,n=null,i=null,o={}){var s,f,g,m;let h,y,w,A=(s=[(0,S.I)(e)||e,o.forcedConnectionId?`forced:${o.forcedConnectionId}`:"pool"].join(":"),y=eA.get(s)??Promise.resolve(),w=new Promise(e=>{h=e}),eA.set(s,w),{wait:y,release:()=>{h?.(),eA.get(s)===w&&eA.delete(s)}});try{let s;await A.wait;let h=(0,S.I)(e);if([T.f,v.a].some(e=>e[h]?.noAuth)){if(await (0,C.f)(h))return null;let e=eo(t,o.excludeConnectionIds);return await ei(h,e)}let y=!0===o.allowSuppressedConnections,w=y||!0===o.allowRateLimitedConnections,$=!0===o.bypassQuotaPolicy,U="string"==typeof o.forcedConnectionId&&o.forcedConnectionId.trim().length>0?o.forcedConnectionId.trim():null,D=eo(t,o.excludeConnectionIds),k=await (0,l.getCachedSettings)(),_=(0,E.W)(e,o,k),R=await eu(e),O=(await Promise.all(R.map(e=>(0,l.getCachedRawProviderConnections)({provider:e,isActive:!0})))).filter(Array.isArray).flat(),H=(Array.isArray(O)?O:[]).map(u.o).filter(e=>e.id.length>0);n&&n.length>0&&(H=H.filter(e=>n.includes(e.id))),(U=(0,E.H)({forcedConnectionId:U,options:o,sessionAffinityTtlMs:_,connections:H,provider:e,requestedModel:i,excludedConnectionIds:D,isTerminalConnectionStatus:X,isCodexScopeUnavailable:V,isQuotaPolicyBlocked:t=>J(e,t,i).blocked})??U)&&(H=H.filter(e=>e.id===U));let N=H.length,P=O.length,q=U?P-H.length:0,F=n&&n.length>0?Math.max(0,P-H.length-q):0,j=U?`${U.slice(0,8)}...`:"none";if(M.debug("AUTH",`${e} | active=${N}, excluded=${D.size} (${el(D)}), forcedId=${j}, blocked_forced=${q}, blocked_allowed=${F}`),"antigravity"===e&&(U||n?.length)){let t=[];U&&t.push(`forcedConnectionId kept ${H.length}`),n?.length&&t.push(`allowedConnections=${n.length}`),M.info("AUTH",`${e} selection constrained: ${t.join(", ")}`)}if(0===H.length){let t=(await Promise.all(R.map(e=>(0,a.W)({provider:e})))).filter(Array.isArray).flat().map(u.j).filter(e=>e.id.length>0);if(n&&n.length>0&&(t=t.filter(e=>n.includes(e.id))),U&&(t=t.filter(e=>e.id===U)),M.debug("AUTH",`${e} | all connections (incl inactive): ${t.length}`),t.length>0){let n=(0,p.d)(t);if(n)return M.warn("AUTH",`${e} | all ${t.length} accounts rate limited (${(0,p.s)(n)})`),{allRateLimited:!0,retryAfter:n,retryAfterHuman:(0,p.s)(n)};M.warn("AUTH",`${e} | ${t.length} accounts found but none active`),t.forEach(e=>{M.debug("AUTH",` → ${e.id?.slice(0,8)} | isActive=${e.isActive} | rateLimitedUntil=${e.rateLimitedUntil||"none"} | testStatus=${e.testStatus}`)});let r=t.filter(X);if(r.length===t.length){let e=await ei(h,D);if(e)return e;let t=new Map;for(let e of r){let n=z(e.testStatus)||"expired";t.set(n,(t.get(n)||0)+1)}let n=[...t.entries()].sort((e,t)=>t[1]-e[1])[0]?.[0]||"expired";return{allExpired:!0,expiredCount:r.length,expiredStatus:n}}}let r=await ei(h,D);if(r)return r;return(o.quietMissing?M.debug:M.warn)("AUTH",`No credentials for ${e}`),null}for(let e of H)!(e.backoffLevel>0)||X(e)||(0,p.v)(e.rateLimitedUntil)||(e.backoffLevel=0,(0,a.g)(e.id).catch(()=>{}));let Q=0,K=0,B=new Map,Z=H.filter(t=>{if(D.has(t.id))return B.set(t.id,"excluded"),!1;if(i&&(0,x.p)(i,t.providerSpecificData))return B.set(t.id,"modelExcluded"),!1;if(!y){if(!w&&(0,p.v)(t.rateLimitedUntil))return B.set(t.id,"rateLimited"),!1;if(X(t))return B.set(t.id,"terminalStatus"),!1;if("codex"===e&&V(t,i))return B.set(t.id,"codexScopeLimited"),!1;if(i&&(0,p.t)(e,t.id,i))return B.set(t.id,"modelLocked"),"antigravity"===e&&"family"===(0,d.t)(e,i)?K+=1:Q+=1,!1}return B.set(t.id,"available"),!0});if(M.debug("AUTH",`${e} | available: ${Z.length}/${H.length}`),"antigravity"===e&&M.info("AUTH",`${e} selection candidates model=${i||"none"}: active=${N}, excluded=${D.size}, modelLocked=${Q}, familyLocked=${K}, eligible=${Z.length}`),H.forEach(t=>{let n=B.get(t.id),r="excluded"===n,o="rateLimited"===n;if(r||o)M.debug("AUTH",` → ${t.id?.slice(0,8)} | ${r?"excluded":""} ${o?`rateLimited until ${t.rateLimitedUntil}`:""}${y&&o?" (retained for combo live test)":""}`);else if("modelExcluded"===n)M.debug("AUTH",` → ${t.id?.slice(0,8)} | excluded by per-account model rule for ${i}`);else if("terminalStatus"===n)M.debug("AUTH",y?` → ${t.id?.slice(0,8)} | retained terminal status=${t.testStatus} for combo live test`:` → ${t.id?.slice(0,8)} | skipped terminal status=${t.testStatus}`);else if("codexScopeLimited"===n){let e=W(t.providerSpecificData,i);M.debug("AUTH",y?` → ${t.id?.slice(0,8)} | retained codex scope-limited account until ${e} for combo live test`:` → ${t.id?.slice(0,8)} | codex scope-limited until ${e}`)}else if("modelLocked"===n){let n=(0,p.E)(e,t.id,i);M.debug("AUTH",y?` → ${t.id?.slice(0,8)} | retained model lockout for ${i} (${n?.remainingMs||0}ms remaining) for combo live test`:` → ${t.id?.slice(0,8)} | model-locked for ${i} (${n?.remainingMs||0}ms remaining)`)}}),0===Z.length){let t=H.map(t=>{var n;let r=Y(t.rateLimitedUntil),o="codex"===e?Y(W(t.providerSpecificData,i)):null,l=i?(0,p.E)(e,t.id,i):null,a=l&&l.remainingMs>0&&"string"==typeof(n=l.reason)&&n.length>0&&!ey.has(n)?Date.now()+l.remainingMs:null;return{connection:t,connectionCooldownMs:r,codexScopeCooldownMs:o,retryableModelCooldownMs:a,modelLockoutReason:null!==a&&"string"==typeof l?.reason?l.reason:null,modelLockoutStatus:null!==a&&"number"==typeof l?.status?l.status:null}}),n=t.flatMap(e=>{let t=[];return null!==e.connectionCooldownMs&&t.push({ms:e.connectionCooldownMs,connection:e.connection}),null!==e.codexScopeCooldownMs&&t.push({ms:e.codexScopeCooldownMs,connection:e.connection}),null!==e.retryableModelCooldownMs&&t.push({ms:e.retryableModelCooldownMs,connection:e.connection,lockoutReason:e.modelLockoutReason,lockoutStatus:e.modelLockoutStatus}),t}).sort((e,t)=>e.ms-t.ms),r=!!i&&t.length>0&&t.every(e=>(null!==e.codexScopeCooldownMs||null!==e.retryableModelCooldownMs)&&null===e.connectionCooldownMs),o=n[0],l=o?.ms&&Number.isFinite(o.ms)?new Date(o.ms).toISOString():null;if(l){let t,n,a,s,u,c=o?.connection,d=U?`account ${f=U,t=O.find(e=>e?.id===f),(n=[t?.name,t?.displayName].find(e=>"string"==typeof e&&e.trim().length>0))?n.trim():`${f.slice(0,8)}...`}`:`all ${H.length} active accounts`,h=r?`cooling down for model ${i}`:"rate limited",y=c?.errorCode!=null?` | last error ${g=c.errorCode,a=Number(g),Number.isFinite(a)?String(Math.trunc(a)):String(g)}: ${String(c.lastError??"").slice(0,50)}`:"";return m=`${e}|${d}|${h}|${c?.errorCode??""}`,s=Date.now(),u=eU.get(m),(void 0===u||!(s-u<5e3))&&(eU.size>500&&eU.clear(),eU.set(m,s),1)&&M.warn("AUTH",`${e} | ${d} ${h} (${(0,p.s)(l)})${y}`),{allRateLimited:!0,retryAfter:l,retryAfterHuman:(0,p.s)(l),lastError:c?.lastError||null,lastErrorCode:r?429:c?.errorCode||null,cooldownStatus:r?(0,p.W)(o?.lockoutReason??null,o?.lockoutStatus??c?.errorCode):null,cooldownReason:o?.lockoutReason??("string"==typeof c?.lastErrorType?c.lastErrorType:null),cooldownScope:r?"model":"connection",cooldownModel:r?i:null,connectionsCount:H.length}}let a=await ei(h,D);if(a)return a;return M.warn("AUTH",`${e} | all ${H.length} accounts unavailable`),null}let ee=Z,et=[],er=new Map;if($?Z.length>0&&M.debug("AUTH",`${e} | bypassing cached quota policy for this request`):ee=Z.filter(t=>{let n=J(e,t,i);return er.set(t.id,{blocked:n.blocked,exhausted:!1}),!n.blocked||(et.push({id:t.id,reasons:n.reasons,resetAt:n.resetAt}),!1)}),et.length>0&&M.info("AUTH",`${e} | quota policy filtered ${et.length} account(s): ${et.map(e=>`${e.id.slice(0,8)}(${e.reasons.join(", ")})`).join("; ")}`),0===ee.length&&Z.length>0){let t=G(et.map(e=>e.resetAt)),n=Y(t),r=n?new Date(n).toISOString():new Date(Date.now()+3e5).toISOString();return{allRateLimited:!0,retryAfter:r,retryAfterHuman:(0,p.s)(r),lastError:`All ${e} accounts reached configured quota threshold`,lastErrorCode:429,cooldownReason:"quota_exhausted"}}let ea=[],es=[];for(let t of ee){let n=(0,c.isQuotaExhaustedForRequest)(t.id,e,i),r=er.get(t.id);r&&(r.exhausted=n),n?es.push(t):ea.push(t)}if(es.length>0&&M.info("AUTH",`${e} | quota-aware: ${ea.length} with quota, skipping ${es.length} exhausted`),0===ea.length&&es.length>0){let t=G(es.map(e=>{let t=(0,c.getQuotaCache)(e.id);return t?.nextResetAt||null})),n=Y(t),r=n?new Date(n).toISOString():new Date(Date.now()+3e5).toISOString();return{allRateLimited:!0,retryAfter:r,retryAfterHuman:(0,p.s)(r),lastError:`All ${e} accounts have exhausted their quota`,lastErrorCode:429,cooldownReason:"quota_exhausted"}}let ec=(k.providerStrategies||{})[h]||{},ed=ec.fallbackStrategy||k.fallbackStrategy||"fill-first",ef=await (0,E.C)(e,o.sessionKey,ea,_);if(ef?s=ef:o.sessionKey&&Number(_)>0&&M.debug("AUTH",`session_key=${(0,E.w)(o.sessionKey)} has no available affinity target`),s);else if("round-robin"===ed){let n=L(ec.stickyRoundRobinLimit??k.stickyRoundRobinLimit,3);if(null!==t||D.size>0){for(let t of(s=[...ea].sort((e,t)=>{let n=e.backoffLevel||0,r=t.backoffLevel||0;return n!==r?n-r:e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime():1:-1:(e.priority||999)-(t.priority||999)})[0],M.info("AUTH",`${e} round-robin: FALLBACK MODE - excluded_count=${D.size} excluded=${el(D)} picked_lru=${s.id?.slice(0,8)}...`),await (0,a.w)(s.id,1),O))if(t.id===s.id){t.lastUsedAt=new Date().toISOString(),t.consecutiveUseCount=1;break}}else{let t=[...ea].sort((e,t)=>e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(t.lastUsedAt).getTime()-new Date(e.lastUsedAt).getTime():-1:1:(e.priority||999)-(t.priority||999))[0],r=t?.consecutiveUseCount||0;if(t&&t.lastUsedAt&&r<n){s=t,M.debug("AUTH",`${e} round-robin: staying with ${t.id?.slice(0,8)}... (count=${r}/${n})`);let i=(s.consecutiveUseCount||0)+1;for(let e of(await (0,a.w)(s.id,i),O))if(e.id===s.id){e.lastUsedAt=new Date().toISOString(),e.consecutiveUseCount=i;break}}else for(let t of(s=[...ea].sort((e,t)=>{let n=e.backoffLevel||0,r=t.backoffLevel||0;return n!==r?n-r:e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime():1:-1:(e.priority||999)-(t.priority||999)})[0],M.debug("AUTH",`${e} round-robin: switching to LRU ${s.id?.slice(0,8)}... (current count=${r} >= limit=${n} or no lastUsedAt)`),await (0,a.w)(s.id,1),O))if(t.id===s.id){t.lastUsedAt=new Date().toISOString(),t.consecutiveUseCount=1;break}}}else if("p2c"===ed){let t=(ea.length,ea);if(t.length<=2)s=[...t].sort((t,n)=>en(e,t,n,i,er))[0];else{let n=parseInt((0,r.randomUUID)().replace(/-/g,"").substring(0,8),16)%t.length,o=parseInt((0,r.randomUUID)().replace(/-/g,"").substring(0,8),16)%(t.length-1);o>=n&&o++;let l=t[n],a=t[o];s=0>=en(e,l,a,i,er)?l:a}}else if("random"===ed){let e=parseInt((0,r.randomUUID)().replace(/-/g,"").substring(0,8),16)%ea.length;s=ea[e]}else if("least-used"===ed)s=[...ea].sort((e,t)=>e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime():1:-1:(e.priority||999)-(t.priority||999))[0];else if("cost-optimized"===ed)s=[...ea].sort((e,t)=>(e.priority||999)-(t.priority||999))[0];else if("strict-random"===ed){let t=ea.map(e=>e.id),n=(0,I.B)(`conn:${e}`,t);s=ea.find(e=>e.id===n)||ea[0]}else s=ea[0];"antigravity"===e&&s&&M.info("AUTH",`${e} selected account=${s.id?.slice(0,8)}... eligible=${ea.length} excluded=${D.size}`);let ep=s.providerSpecificData?.apiKeyHealth;return ep&&(0,b.v)(s.id,ep),{apiKey:s.apiKey,accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.tokenExpiresAt||s.expiresAt||null,projectId:s.projectId,defaultModel:s.defaultModel||null,copilotToken:"string"==typeof s.providerSpecificData.copilotToken?s.providerSpecificData.copilotToken:null,providerSpecificData:s.providerSpecificData,id:s.id,provider:s.provider,email:s.email,connectionId:s.id,testStatus:s.testStatus,lastError:s.lastError,lastErrorType:s.lastErrorType,lastErrorSource:s.lastErrorSource,errorCode:s.errorCode,rateLimitedUntil:s.rateLimitedUntil,maxConcurrent:s.maxConcurrent,quotaWindowThresholds:s.quotaWindowThresholds??null}}finally{A.release()}}async function ed(e,t=null,n=null,r=null,i={}){if(!0===i.bypassQuotaPolicy||"antigravity"===e&&"always"===(0,f.e)())return ec(e,t,n,r,{...i,bypassQuotaPolicy:!0});let o=[],a=eo(t,i.excludeConnectionIds),{defaultThresholdPercent:s,warnThresholdPercent:u,providerWindowDefaults:c}=(0,w.resolveResilienceSettings)(await (0,l.getCachedSettings)()).quotaPreflight,d=c[e]||{},p=Object.keys(d).length>0,g=s>2;for(;;){let t=await ec(e,null,n,r,{...i,excludeConnectionIds:Array.from(a)});if(!t){if(o.length>0)return ea(e,o);return null}if("allRateLimited"in t&&t.allRateLimited||"allExpired"in t&&t.allExpired){if("allRateLimited"in t&&t.allRateLimited&&o.length>0)return ea(e,o);return t}let l=t.connectionId;if(!l)return t;let c=t.quotaWindowThresholds||{};if(t.providerSpecificData?.quotaPreflightEnabled===!1)return t;let f=Object.keys(c).length>0,m=(0,y.X)(t);if(!f&&!p&&!m&&!g)return t;let h=t=>{if(null!==t)for(let n of"codex"===e?K([t,(0,U.Q)(t)].filter(Boolean)):[t]){let e=c[n];if("number"==typeof e)return e;let t=d[n];if("number"==typeof t)return t}return s},w="codex"===e||"openrouter"===e,A=r&&w?{...t,requestedModel:r}:t,b=await (0,y.d)(e,l,A,{resolveMinRemainingPercent:h,resolveWarnRemainingPercent:()=>u});if(b.proceed)return t;let $=await es(e,l,b,r);o.push({id:l,quotaPercent:b.quotaPercent,resetAt:$}),a.add(l),M.info("AUTH",`${e} | preflight blocked ${l.slice(0,8)}${Number.isFinite(b.quotaPercent)?` at ${Math.round(100*b.quotaPercent)}%`:""} until ${$}`)}}async function ef(e,t,n,r=null,i=null,o=null,s={}){let f,y=eb.get(e)||Promise.resolve();eb.set(e,new Promise(e=>{f=e}));try{let f;await y;let w=(0,_.f)(t,n,e,M);if(w)return w;let b=await (0,a.W)({provider:r}),T=(Array.isArray(b)?b:[]).map(u.j).filter(e=>e.id.length>0).find(t=>t.id===e),x=T?.backoffLevel||0;if(T&&X(T))return M.info("AUTH",`${e.slice(0,8)} terminal status=${T.testStatus}, skipping cooldown overwrite`),{shouldFallback:!0,cooldownMs:0};let E=T?.providerSpecificData?.disableCooling===!0;if(429===t&&T&&!E){let t=(0,c.getQuotaBlockedUntil)(e,i),n=Y(t);if(t&&n){let t=!!(0,c.getQuotaBlockedUntil)(e,null),o=n-Date.now();r&&i&&(0,p.l)(r,e,i,"quota_exhausted",o);let l=T.rateLimitedUntil?(0,p.Z)(T.rateLimitedUntil):0/0;return t&&!(Number.isFinite(l)&&l>=n)&&await (0,a.s)(e,{rateLimitedUntil:new Date(n).toISOString(),testStatus:"unavailable",lastError:"Usage limit reached",lastErrorType:"quota_exhausted",lastErrorAt:new Date().toISOString(),errorCode:429}),M.info("AUTH",`${e.slice(0,8)} usage limit reached${t?"":` for ${i}`} — skipped until ${new Date(n).toISOString()} (${(0,p.s)(new Date(n).toISOString())})`),{shouldFallback:!0,cooldownMs:o}}}let C=T?.rateLimitedUntil?(0,p.Z)(T.rateLimitedUntil):0/0;if(Number.isFinite(C)&&C>Date.now())return M.info("AUTH",`${e.slice(0,8)} already marked unavailable (until ${T?.rateLimitedUntil}), skipping duplicate mark`),{shouldFallback:!0,cooldownMs:C-Date.now()};if("codex"===r&&i){let t=W(T?.providerSpecificData||{},i);if(t&&new Date(t).getTime()>Date.now())return M.info("AUTH",`${e.slice(0,8)} already scope-limited for ${(0,U.A)(i)} (until ${t}), skipping duplicate mark`),{shouldFallback:!0,cooldownMs:new Date(t).getTime()-Date.now()}}let D=o||(r?await (0,p.j)(r):null),k=(0,A.f)(await (0,l.getCachedSettings)()),I=(0,p.u)(t,n,x,i,r,null,D),R=T?.providerSpecificData||{},L=R.passthroughModels,H=!0===R.disableCooling,N=(0,p.O)(r,i,L),P={maxCooldownMs:D?.maxCooldownMs};if(N&&r&&"codex"!==r&&i&&(404===t||429===t||t>=500)){let n=404===t?"not_found":429===t&&I.reason===m.m.QUOTA_EXHAUSTED?"quota_exhausted":429===t?"rate_limited":"server_error";if(500===t)return(0,a.s)(e,{lastErrorType:n,lastError:`Model ${i} ${n}`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),M.info("AUTH",`Server error for ${r}:${i} — ${t} ${n} (no model lockout, connection stays active for sibling models)`),{shouldFallback:!0,cooldownMs:0};let o=(0,d.t)(r,i),l="antigravity"===r&&"family"===o&&429===t?3e4:null,s=(0,p.o)(r,e,i,n,t,404===t?D?.baseCooldownMs??h.b.notFoundLocal:l??I.baseCooldownMs??D?.baseCooldownMs??0,D,{...P,exactCooldownMs:!0===I.usedUpstreamRetryHint?I.cooldownMs:I.quotaResetHintMs??null,maxCooldownMs:k.maxCooldownMs,exactCooldownIsUpstreamReset:!0===I.usedUpstreamRetryHint||"number"==typeof I.quotaResetHintMs});return(0,a.s)(e,{lastErrorType:n,lastError:`Model ${i} ${n}`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),M.info("AUTH",`Model-only lockout for ${r}:${i} — ${t} ${n} ${Math.ceil(s.cooldownMs/1e3)}s (failureCount=${s.failureCount}, connection stays active)`),{shouldFallback:!0,cooldownMs:s.cooldownMs}}let{shouldFallback:q,cooldownMs:F,newBackoffLevel:j,reason:Q}=I;if(!q)return{shouldFallback:!1,cooldownMs:0};let K=(0,$.k)(t,n,r);if(r&&"grok-web"===(0,S.I)(r)&&403===t&&i){let n=(0,p.o)(r,e,i,"forbidden",t,D?.baseCooldownMs??h.b.serviceUnavailable,D,{maxCooldownMs:k.maxCooldownMs});return(0,a.s)(e,{lastErrorType:"forbidden",lastError:`Mode ${i} forbidden for this Grok account`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),M.info("AUTH",`Mode-only lockout for ${r}:${i} — 403 forbidden ${Math.ceil(n.cooldownMs/1e3)}s (connection stays active)`),{shouldFallback:!0,cooldownMs:n.cooldownMs}}let B=function(e,t,n=null,r=null){return t.creditsExhausted||402===e?"credits_exhausted":n===$.R.PROJECT_ROUTE_ERROR||n===$.R.OAUTH_INVALID_TOKEN?null:t.permanent||n===$.R.FORBIDDEN?"banned":n!==$.R.ACCOUNT_DEACTIVATED&&n!==$.R.UNAUTHORIZED&&401!==e||n!==$.R.ACCOUNT_DEACTIVATED&&null!=r&&(0,S.I)(r)in v.a?null:"expired"}(t,I,K,r),V=K===$.R.QUOTA_EXHAUSTED||Q===m.m.QUOTA_EXHAUSTED?(f=(0,c.getQuotaCache)(e),f?.quotas?G(Object.values(f.quotas).map(e=>e.resetAt)):null):null,z=Y(V),Z=B?0:z?z-Date.now():F;if(N&&403===t&&r&&i&&!B){let n=(0,p.o)(r,e,i,"forbidden",t,I.baseCooldownMs??D?.baseCooldownMs??h.b.serviceUnavailable,D,{...P,exactCooldownMs:!0===I.usedUpstreamRetryHint?I.cooldownMs:null,maxCooldownMs:k.maxCooldownMs});return(0,a.s)(e,{lastErrorType:"forbidden",lastError:`Model ${i} forbidden (per-model access/subscription)`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),M.info("AUTH",`Model-only lockout for ${r}:${i} — 403 forbidden ${Math.ceil(n.cooldownMs/1e3)}s (per-model quota provider, connection stays active)`),{shouldFallback:!0,cooldownMs:n.cooldownMs}}let J=T?.providerSpecificData?.baseUrl;if((0,g.B)(J)&&404===t&&r&&i){let n=(0,p.o)(r,e,i,"not_found",t,404===t?D?.baseCooldownMs??h.b.notFoundLocal:h.b.notFoundLocal,D,{maxCooldownMs:k.maxCooldownMs});return(0,a.s)(e,{lastErrorType:"not_found",lastError:`Model ${i} not_found`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),M.info("AUTH",`Model-only lockout for ${r}:${i} — 404 not_found ${Math.ceil(n.cooldownMs/1e3)}s (failureCount=${n.failureCount}, connection stays active)`),{shouldFallback:!0,cooldownMs:n.cooldownMs}}let ee="string"==typeof n?n.slice(0,100):"Provider error";if("codex"===r&&429===t&&i&&T){let n=(0,U.A)(i),o=O(T.providerSpecificData.codexScopeRateLimitedUntil),l=W(T.providerSpecificData,i)||(0,p.c)(Z),s=Math.max(new Date(l).getTime()-Date.now(),0);return await (0,a.s)(e,{testStatus:"unavailable",lastError:ee,errorCode:t,lastErrorAt:new Date().toISOString(),backoffLevel:j??x,providerSpecificData:{...T.providerSpecificData,codexScopeRateLimitedUntil:{...o,[n]:l}}}),s>0&&(0,p.l)(r,e,i,Q||"unknown",s),t&&ee&&console.error(`❌ ${r} [${t}] (${n}): ${ee}`),{shouldFallback:!0,cooldownMs:s}}let et={lastError:ee,lastErrorType:K,errorCode:t,lastErrorAt:new Date().toISOString(),backoffLevel:j??x};if(!1!==s.persistUnavailableState?Z>0&&!H?await (0,a.s)(e,{...et,rateLimitedUntil:(0,p.c)(Z),testStatus:"unavailable"}):await (0,a.s)(e,{...et,rateLimitedUntil:null,...B?{testStatus:B}:{}}):(r&&i&&Z>0&&(0,p.l)(r,e,i,Q||"unknown",Z),await (0,a.s)(e,{...et})),I.permanent)try{(await (0,l.getCachedSettings)()).autoDisableBannedAccounts&&(await (0,a.s)(e,{isActive:!1}),M.info("AUTH",`Auto-disabled ${e.slice(0,8)} — permanent ban detected (autoDisableBannedAccounts=true)`))}catch(e){M.info("AUTH",`Auto-disable check failed (non-fatal): ${e}`)}return r&&t&&ee&&console.error(`❌ ${r} [${t}]: ${ee}`),{shouldFallback:!0,cooldownMs:Z}}finally{f&&f(),eb.delete(e)}}async function ep(e,t){(t.testStatus&&"active"!==t.testStatus||t.lastError||t.rateLimitedUntil||t.errorCode||t.lastErrorType||t.lastErrorSource)&&(await (0,a.s)(e,{testStatus:"active",lastError:null,lastErrorAt:null,lastErrorType:null,lastErrorSource:null,errorCode:null,rateLimitedUntil:null,backoffLevel:0}),M.info("AUTH",`Account ${e.slice(0,8)} error cleared`))}async function eg(e,t){return e?.connectionId?t?await (0,a.j)(e.connectionId,t)?(M.info("AUTH",`Account ${e.connectionId.slice(0,8)} error cleared (CAS)`),{applied:!0}):(M.info("AUTH",`Skipped recovery clear for ${e.connectionId.slice(0,8)} — state changed concurrently (CAS miss)`),{applied:!1}):(await ep(e.connectionId,e),{applied:!0}):{applied:!1}}function em(e,t){let n=N(e?.headers,"Authorization")||N(e?.headers,"authorization");if("string"==typeof n){let e=n.trim();if(e.toLowerCase().startsWith("bearer "))return e.slice(7).trim()||null}let r=N(e?.headers,"x-api-key")||N(e?.headers,"X-Api-Key");if("string"==typeof r){let e=r.trim();if(e.length>0)return e}let o=(0,i.f)(e?.headers);if(o)return o;if(t?.allowUrl===!1)return null;if("string"!=typeof e?.url||0===e.url.trim().length)return null;try{let t=new URL(e.url,"http://localhost").pathname.split("/").map(e=>e.trim()).filter(Boolean);if("vscode"===t[0]&&t[1]){let e=decodeURIComponent(t[1]).trim();if(e.length>0)return e}if("api"===t[0]&&"v1"===t[1]&&"vscode"===t[2]){if(t[3]&&"raw"!==t[3]&&"combos"!==t[3]){let e=decodeURIComponent(t[3]).trim();if(e.length>0)return e}if(("raw"===t[3]||"combos"===t[3])&&t[4]){let e=decodeURIComponent(t[4]).trim();if(e.length>0)return e}}}catch{}return null}async function eh(e){if(!e)return!1;let t=process.env.TROUTEAI_API_KEY||process.env.ROUTER_API_KEY;return!!t&&e===t||await (0,s.validateApiKey)(e)}n()}catch(e){n(e)}},!1),350793,e=>e.a(async(t,n)=>{try{e.s(["f",()=>o]);var r=e.i(259298),i=t([r]);function o(e){return(0,r.g)(e,"x-goog-api-key")||(0,r.g)(e,"X-Goog-Api-Key")}[r]=i.then?(await i)():i,n()}catch(e){n(e)}},!1),367333,e=>e.a(async(t,n)=>{try{var r=e.i(687267),i=e.i(507651),o=e.i(131707),l=t([i]);async function a(e){try{let t=await (0,r.getCachedSettings)();return(0,i.q)(e,t.blockedProviders)}catch(t){return o.warn("AUTH",`Could not read blocked provider settings for ${e}: ${t instanceof Error?t.message:String(t)}`),!1}}[i]=l.then?(await l)():l,e.s(["f",0,a]),n()}catch(e){n(e)}},!1),348704,e=>{"use strict";let t={"opencode-zen":["opencode"],"opencode-go":["opencode"]};e.s(["f",0,function(e){return[e,...t[e]||[]]}])},186071,e=>{"use strict";var t=e.i(132446),n=e.i(696582);function r(e){let t="string"==typeof e.host?e.host.trim():"";if(!t)return null;let r="string"==typeof e.username?e.username:"",i="string"==typeof e.password?e.password:"",o="string"==typeof e.type&&e.type?e.type:"socks5",l=(0,n.w)(o)?(0,n.V)(e.notes):void 0;return{type:o,host:t,port:Number(e.port)||0,...r?{username:r}:{},...i?{password:i}:{},...l?{relayAuth:l}:{}}}async function i(e,t){if(!Array.isArray(e))return[];let n=[];for(let i of e)if(i&&"object"==typeof i&&"string"==typeof i.fingerprint){if("string"==typeof i.proxyId&&i.proxyId){let e=null;try{e=await t(i.proxyId)}catch{e=null}n.push({fingerprint:i.fingerprint,proxy:e?r(e):null});continue}if(i.proxy&&"object"==typeof i.proxy){n.push({fingerprint:i.fingerprint,proxy:r(i.proxy)});continue}n.push({fingerprint:i.fingerprint,proxy:null})}return n}async function o(e){return i(e,e=>(0,t.V)(e,{includeSecrets:!0}))}e.s(["f",0,o])},457308,e=>e.a(async(t,n)=>{try{var r=e.i(538038),i=t([r]);[r]=i.then?(await i)():i,e.s(["f",0,function(e,t,n,i){return 404===e&&(0,r.n)(t)?(i.info("AUTH",`${n.slice(0,8)} request-resource 404; skipping model/account cooldown`),{shouldFallback:!1,cooldownMs:0}):null}]),n()}catch(e){n(e)}},!1),114843,e=>e.a(async(t,n)=>{try{var r=e.i(756045),i=e.i(648830),o=e.i(987227),l=e.i(435005),a=e.i(58501),s=e.i(131707),u=t([i,l,a]);function c(e){return`${e.slice(0,18)}...`}function d(e,t){if(!e.lastUsedAt&&!t.lastUsedAt)return(e.priority||999)-(t.priority||999);if(!e.lastUsedAt)return -1;if(!t.lastUsedAt)return 1;let n=new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime();return 0!==n?n:(e.consecutiveUseCount||0)!==(t.consecutiveUseCount||0)?(e.consecutiveUseCount||0)-(t.consecutiveUseCount||0):(e.priority||999)-(t.priority||999)}async function f(e,t,n,o=0){if(!t||0===n.length||o<=0)return null;let l=(0,r.getSessionAccountAffinity)(t,e,o);if(l){let a=n.find(e=>e.id===l.connectionId);if(a)return(0,r.touchSessionAccountAffinity)(t,e,Date.now(),o),await (0,i.s)(a.id,{lastUsedAt:new Date().toISOString(),consecutiveUseCount:(a.consecutiveUseCount||0)+1}),s.info("AUTH",`session_key=${c(t)} -> connection ${a.id.slice(0,8)} (affinity)`),a;(0,r.deleteSessionAccountAffinity)(t,e),s.info("AUTH",`affinity cleared for session_key=${c(t)} provider=${e}`)}let a=[...n].sort(d)[0]??null;return a?((0,r.upsertSessionAccountAffinity)(t,e,a.id,Date.now(),o),await (0,i.s)(a.id,{lastUsedAt:new Date().toISOString(),consecutiveUseCount:1}),s.info("AUTH",`new affinity created for session_key=${c(t)} -> connection ${a.id.slice(0,8)}`),a):null}[i,l,a]=u.then?(await u)():u,e.s(["H",0,function(e){let{forcedConnectionId:t,options:n,sessionAffinityTtlMs:i,connections:u,provider:c}=e,d=n.sessionKey;if(!t||!d||i<=0)return null;let f=(0,r.getSessionAccountAffinity)(d,c,i);if(!f||f.connectionId===t)return null;let p=u.find(e=>e.id===f.connectionId);return p&&function(e,t){let{provider:n,requestedModel:r,options:i}=t,s=!0===i.allowSuppressedConnections,u=s||!0===i.allowRateLimitedConnections;return!(t.excludedConnectionIds.has(e.id)||r&&(0,o.p)(r,e.providerSpecificData)||!s&&(!u&&(0,a.v)(e.rateLimitedUntil)||t.isTerminalConnectionStatus(e)||"codex"===n&&t.isCodexScopeUnavailable(e,r)||r&&(0,a.t)(n,e.id,r)))&&!((0,l.isAccountQuotaExhausted)(e.id)||!0!==i.bypassQuotaPolicy&&t.isQuotaPolicyBlocked(e))}(p,e)?(s.info("AUTH",`session affinity pin ${f.connectionId.slice(0,8)}... overrides forcedConnectionId ${t.slice(0,8)}...`),f.connectionId):null},"w",0,c,"W",0,function(e,t,n){let r=Number(t.sessionAffinityTtlMs);if(Number.isFinite(r)&&r>0)return r;let i=Number(n.sessionAffinityTtlMs??n.codexSessionAffinityTtlMs);return Number.isFinite(i)&&i>0?i:0},"C",0,f]),n()}catch(e){n(e)}},!1),131707,e=>{"use strict";let t=(0,e.i(335092).f)("sse");function n(e){return e?"string"==typeof e?{detail:e}:"object"==typeof e?e:{detail:String(e)}:{}}e.s(["debug",0,function(e,r,i){t.debug({tag:e,...n(i)},r)},"error",0,function(e,r,i){t.error({tag:e,...n(i)},r)},"info",0,function(e,r,i){t.info({tag:e,...n(i)},r)},"request",0,function(e,r,i){t.info({tag:"HTTP",method:e,path:r,...n(i)},`📥 ${e} ${r}`)},"warn",0,function(e,r,i){t.warn({tag:e,...n(i)},r)}])}];
|
|
1
|
+
module.exports=[538038,e=>e.a(async(t,n)=>{try{var r=e.i(58501),i=e.i(998158),o=e.i(846280),l=t([r]);[r]=l.then?(await l)():l;let c=new Set(["max_tokens","tool_use","refusal"]),d=new Set(["length","tool_calls","content_filter"]),f={RATE_LIMITED:"rate_limited",UNAUTHORIZED:"unauthorized",ACCOUNT_DEACTIVATED:"account_deactivated",FORBIDDEN:"forbidden",SERVER_ERROR:"server_error",QUOTA_EXHAUSTED:"quota_exhausted",PROJECT_ROUTE_ERROR:"project_route_error",CONTEXT_OVERFLOW:"context_overflow",OAUTH_INVALID_TOKEN:"oauth_invalid_token",EMPTY_CONTENT:"empty_content",MODEL_NOT_FOUND:"model_not_found"},p=RegExp("context overflow|prompt too large|context window|maximum context|exceeds context|input too long|token limit|too many tokens|context length|exceed.*context|messages exceed","i"),g=/\bmodel\b[^\n]{0,80}\bis not supported\b/i;function a(e){return g.test(String(e||"").toLowerCase())}function s(e){if("string"==typeof e)return e;if(null!==e&&"object"==typeof e)try{return JSON.stringify(e)}catch{}return""}let h=[/\bfiles?\b[^\n]{0,160}\b(?:not found|does not exist)\b/i,/\b(?:not found|does not exist)\b[^\n]{0,160}\bfiles?\b/i,/\b(?:input[_ -]?file|file[_ -]?id|item|response|vector[_ -]?store|upload)\b[^\n]{0,160}\b(?:not found|does not exist)\b/i,/\b(?:not found|does not exist)\b[^\n]{0,160}\b(?:input[_ -]?file|file[_ -]?id|item|response|vector[_ -]?store|upload)\b/i,/\bfile-[a-z0-9_-]+\b[^\n]{0,160}\b(?:not found|does not exist)\b/i];function u(e){let t=s(e);return h.some(e=>e.test(t))}let m=/\bversion of [^\n]{1,60}\bis no longer supported\b/i,y=/\bbearer token included in the request is invalid\b|(?:^|\]:\s*|"message"\s*:\s*")Invalid token\b/i;e.s(["u",0,p,"R",0,f,"k",0,function(e,t,n){let l=s(t),c=(0,r.X)(l),d=(0,i.M)(l.toLowerCase()),g=(0,r.H)(l),h=(0,r.P)(l),w=!n||"oauth"===(0,o.Z)(n);if((c||d)&&[400,402,403].includes(e)||(c||d)&&429===e&&w)return f.QUOTA_EXHAUSTED;if(429===e)return w&&(0,r.N)(l)?f.QUOTA_EXHAUSTED:f.RATE_LIMITED;if(404===e)return u(t)?null:f.MODEL_NOT_FOUND;if(401===e)return h?f.OAUTH_INVALID_TOKEN:a(l)?f.MODEL_NOT_FOUND:g?f.ACCOUNT_DEACTIVATED:f.UNAUTHORIZED;if(402===e)return f.QUOTA_EXHAUSTED;if(403===e&&g)return f.ACCOUNT_DEACTIVATED;if(403===e){let e;if("kiro"===(e=(n||"").toLowerCase())||"amazon-q"===e){if(m.test(String(l||"")))return null;if(y.test(String(l||"")))return f.UNAUTHORIZED}let t=(n||"").toLowerCase(),r="antigravity"===t||"gemini-cli"===t||t.includes("cloudcode")||t.includes("cloud-code");return l.includes("has not been used in project")||l.includes("SERVICE_DISABLED")||l.includes("accessNotConfigured")||l.includes("PERMISSION_DENIED")||/\bit is disabled\b/i.test(l)||r?f.PROJECT_ROUTE_ERROR:n&&"apikey"===(0,o.Z)(n)||n&&(0,o.k)(n)?.authType==="none"?null:f.FORBIDDEN}if(e>=500)return f.SERVER_ERROR;if(400===e){if(p.test(String(l||"")))return f.CONTEXT_OVERFLOW;if(a(l))return f.MODEL_NOT_FOUND}return null},"c",0,a,"D",0,function(e){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e.choices)){let t=e.choices[0];if(!t)return!0;let n=t.message,r=t.delta,i=n?.content??r?.content,o=n?.reasoning_content??r?.reasoning_content,l=Array.isArray(n?.tool_calls)&&n.tool_calls.length>0||Array.isArray(r?.tool_calls)&&r.tool_calls.length>0,a="string"==typeof t.finish_reason?t.finish_reason:"";return!d.has(a)&&(null==i||""===i)&&(null==o||""===o)&&!l}if(Array.isArray(e.content)){if(e.content.length>0)return!1;let t="string"==typeof e.stop_reason?e.stop_reason:"";return!c.has(t)}if("string"==typeof e.text)return""===e.text.trim();if("content"in e){let t=e.content;return null==t||""===t}return!1},"n",0,u]),n()}catch(e){n(e)}},!1),507651,e=>e.a(async(t,n)=>{try{var r=e.i(309559),i=e.i(933990),o=t([r]);[r]=o.then?(await o)():o;let a=Object.values(i.f);function l(e){let t=e instanceof Set?Array.from(e):e;return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[])}e.s(["H",0,function(e,...t){let n=l(e);return a.some(e=>t.some(t=>t===e.id||t===e.alias)&&(n.has(e.id)||"string"==typeof e.alias&&n.has(e.alias)))},"I",0,function(...e){return a.some(t=>e.some(e=>e===t.id||e===t.alias))},"$",0,function(e,t){let n=a.find(t=>t.id===e);return"string"==typeof n?.alias&&n.alias!==e&&t===e},"q",0,function(e,t){let n=l(t),i=(0,r.Q)(e);return n.has(e)||"string"==typeof i?.alias&&n.has(i.alias)},"Q",0,l]),n()}catch(e){n(e)}},!1),756346,e=>{"use strict";var t=e.i(666680);e.s(["R",0,function(){let e=(0,t.randomBytes)(6),n=0;for(let t=0;t<e.length;t++)n=256*n+e[t];return n/0x1000000000000},"$",0,function(e){if(!Number.isFinite(e)||e<=1)return 0;let n=Math.floor(e);return(0,t.randomInt)(n)}])},39197,e=>{"use strict";var t=e.i(756346);let n=new Map,r=new Map;function i(e){let n=[...e];for(let e=n.length-1;e>0;e--){let r=(0,t.$)(e+1),i=n[e];n[e]=n[r],n[r]=i}return n}async function o(e,o){let l;if(0===o.length)return"";if(1===o.length)return o[0];let a=r.get(e)??Promise.resolve();r.set(e,new Promise(e=>{l=e}));try{await a;let r=[...o].sort().join(","),l=n.get(e);if(l&&l.idsKey===r&&l.index<l.order.length){let t=l.order[l.index];return n.set(e,{...l,index:l.index+1}),t}let s=l&&l.idsKey===r&&l.order.length>0?l.order[l.order.length-1]:void 0,u=i(o);if(void 0!==s&&u[0]===s&&u.length>1){let e=1+(0,t.$)(u.length-1),n=u[0];u[0]=u[e],u[e]=n}return n.set(e,{order:u,index:1,idsKey:r}),u[0]}finally{l?.()}}e.s(["k",0,i,"w",0,o,"B",0,function(e,r){if(0===r.length)return"";if(1===r.length)return r[0];let o=[...r].sort().join(","),l=n.get(e);if(l&&l.idsKey===o&&l.index<l.order.length){let t=l.order[l.index];return n.set(e,{...l,index:l.index+1}),t}let a=l&&l.idsKey===o&&l.order.length>0?l.order[l.order.length-1]:void 0,s=i(r);if(void 0!==a&&s[0]===a&&s.length>1){let e=1+(0,t.$)(s.length-1),n=s[0];s[0]=s[e],s[e]=n}return n.set(e,{order:s,index:1,idsKey:o}),s[0]}])},259298,e=>e.a(async(t,n)=>{try{e.s(["h",()=>ep,"N",()=>eg,"M",()=>J,"t",()=>eh,"J",()=>F,"o",()=>ec,"m",()=>ed,"K",()=>eu,"Q",()=>em,"p",()=>ef,"g",()=>N,"q",()=>Z]);var r=e.i(254799),i=e.i(350793),o=e.i(13572),l=e.i(687267),a=e.i(648830),s=e.i(950412),u=e.i(635824),c=e.i(435005),d=e.i(872704),f=e.i(402016),p=e.i(58501),g=e.i(846280),h=e.i(394043),m=e.i(670055),y=e.i(836184),w=e.i(858279),A=e.i(264590),b=e.i(900930),$=e.i(538038),U=e.i(468250),S=e.i(309559),T=e.i(933990),v=e.i(611704),x=e.i(987227),E=e.i(114843),C=e.i(367333),k=e.i(186071),D=e.i(348704),M=e.i(457308),_=e.i(131707),I=e.i(39197),R=t([i,o,a,s,c,p,$,S,E,C,M]);[i,o,a,s,c,p,$,S,E,C,M]=R.then?(await R)():R;let ey=new Set(["not_found","not_found_local"]);function O(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function L(e,t=0){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim().length>0){let n=Number(e);return Number.isFinite(n)?n:t}return t}function H(e,t){return"boolean"==typeof e?e:t}function N(e,t){if(!e)return null;if("function"==typeof e.get){let n=e.get(t)||e.get(t.toLowerCase());return"string"==typeof n&&n.trim().length>0?n.trim():null}let n=e[t]||e[t.toLowerCase()]||e[t.toUpperCase()];return Array.isArray(n)?"string"==typeof n[0]&&n[0].trim().length>0?n[0].trim():null:"string"==typeof n&&n.trim().length>0?n.trim():null}function P(e,t){if("string"!=typeof e||0===e.trim().length)return null;let n=e.trim();return n.length<=180&&/^[A-Za-z0-9._:-]+$/.test(n)?`${t}:${n}`:`${t}:sha256:${(0,r.createHash)("sha256").update(n).digest("hex")}`}function q(e){if("string"==typeof e)return e;if(Array.isArray(e)){let t=e.map(e=>{if("string"==typeof e)return e;let t=O(e);return"string"==typeof t.text?t.text:"string"==typeof t.content?t.content:null}).filter(Boolean);return t.length>0?t.join("\n"):JSON.stringify(e)}return e&&"object"==typeof e?JSON.stringify(e):null}function F(e,t){let n=P(N(t,"x-codex-session-id")??N(t,"x-session-id")??N(t,"x-trouteai-session"),"header");if(n)return n;let i=O(e),o=O(i.metadata),l=P(o.session_id,"metadata")??P(o.sessionId,"metadata")??P(i.conversation_id,"conversation")??P(i.session_id,"session")??P(i.prompt_cache_key,"prompt-cache");if(l)return l;let a=function(e){let t=O(e);if(void 0!==t.input){if("string"==typeof t.input)return t.input;if(Array.isArray(t.input))for(let e of t.input){let t=q(O(e).content??e);if(t&&t.trim().length>0)return t}let e=q(t.input);if(e&&e.trim().length>0)return e}if(Array.isArray(t.messages)){let e=t.messages.find(e=>"user"===O(e).role)??t.messages[0],n=q(O(e).content??e);if(n&&n.trim().length>0)return n}return null}(e);return a&&0!==a.trim().length?`input:sha256:${(0,r.createHash)("sha256").update(a.slice(0,4096)).digest("hex")}`:null}function j(e,t=c.DEFAULT_QUOTA_THRESHOLD_PERCENT){return Math.min(100,Math.max(1,L(e,t)))}function Q(e){if("string"!=typeof e)return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function K(e){return[...new Set(e)]}function B(e){if("string"!=typeof e)return null;let t=e.trim().toLowerCase();return"session (5h)"===t||"5h"===t||"five_hour"===t?"session":"weekly (7d)"===t||"7d"===t||"seven_day"===t?"weekly":(0,U.Q)(t)}function W(e,t){if(!t)return null;let n=(0,U.A)(t),r=O(e.codexScopeRateLimitedUntil)[n];return"string"==typeof r&&r.trim().length>0?r:null}function V(e,t){let n=W(e.providerSpecificData,t);return!!n&&new Date(n).getTime()>Date.now()}function z(e){return(e||"").trim().toLowerCase()}function X(e){let t=z(e.testStatus);return"credits_exhausted"===t||"banned"===t||"expired"===t}function Z(e,t){let n=O(t.limitPolicy),r=(Array.isArray(n.windows)?n.windows:[]).map(Q).filter(Boolean);if("codex"===e){var i;let e,o,l,a=(i=r,o={use5h:H((e=O(t.codexLimitPolicy)).use5h,!0),useWeekly:H(e.useWeekly,!0)},l=(l=[...i.map(B).filter(Boolean)]).filter(e=>"session"===e?o.use5h:"weekly"!==e||o.useWeekly),o.use5h&&l.push("session"),o.useWeekly&&l.push("weekly"),K(l));return{enabled:H(n.enabled,a.length>0),thresholdPercent:j(n.thresholdPercent),windows:a}}return{enabled:H(n.enabled,!1),thresholdPercent:j(n.thresholdPercent),windows:r}}function J(e,t,n=null){let r=Z(e,t.providerSpecificData);if(!r.enabled||0===r.windows.length)return{blocked:!1,reasons:[],resetAt:null};let i=[],o=[];for(let l of r.windows){let a="codex"===e?(0,U.n)(l,n):l,s=(0,c.getQuotaWindowStatus)(t.id,a,r.thresholdPercent);s?.reachedThreshold&&(i.push(`${a} usage ${Math.round(s.usedPercentage)}%`),o.push(s.resetAt))}return{blocked:i.length>0,reasons:i,resetAt:G(o)}}function Y(e){if(!e)return null;let t=(0,p.Z)(e);return!Number.isFinite(t)||t<=Date.now()?null:t}function G(e){return e.map(e=>({raw:e,ms:Y(e)})).filter(e=>null!==e.ms).sort((e,t)=>e.ms-t.ms)[0]?.raw||null}function ee(e,t){Number.isFinite(t)&&e.push(Math.max(0,Math.min(100,t)))}function et(e,t,n=null,r){let i,o,l,a,s,u;if(t.id&&r?.has(t.id)){let e=r.get(t.id);i=e.blocked,o=e.exhausted}else i=J(e,t,n).blocked,o=(0,c.isQuotaExhaustedForRequest)(t.id,e,n);let d=function(e,t,n=null){let r=Z(e,t.providerSpecificData),i=function(e,t,n,r){let i=[],o=new Set;for(let l of n.windows){let a=Q("codex"===e?(0,U.n)(l,r):l);if(!a||o.has(a))continue;o.add(a);let s=(0,c.getQuotaWindowStatus)(t.id,a,n.thresholdPercent);s&&ee(i,s.remainingPercentage)}return i}(e,t,r,n),o=i.length>0?i:function(e,t,n){let r=(0,c.getQuotaCache)(t.id),i=r?.quotas||{},o="codex"===e?(0,U.O)(n):void 0,l=[];for(let[e,t]of Object.entries(i)){var a;(!o||o(e))&&(!t||function(e){if(!e)return!1;let t=new Date(e).getTime();return Number.isFinite(t)&&t<=Date.now()}("string"==typeof(a=t.resetAt)&&a.trim().length>0?a:null)||ee(l,L(t.remainingPercentage,0/0)))}return l}(e,t,n);return o.length>0?Math.min(...o):null}(e,t,n),f=0;return null!==d?(f+=Math.round((100-d)/8),d<=10?f+=10:d<=25&&(f+=4)):i||o||(f+=4),{score:200*!!o+80*!!i+(l=z(t.lastErrorType),a=z(t.lastErrorSource),s=L(t.errorCode,0),u=0,t.lastError&&(u+=6),"rate_limited"===l||"quota_exhausted"===l||"quota"===l||429===s?u+=24:401===s||403===s||"oauth"===a?u+=18:s>=500&&(u+=10),u)+Math.min(40,8*(t.backoffLevel||0))+f+Math.min(12,2*(t.consecutiveUseCount||0))+function(e){if(!e.lastUsedAt)return 0;let t=Date.now()-new Date(e.lastUsedAt).getTime();return Number.isFinite(t)?t<15e3?3:t<6e4?2:+(t<3e5):0}(t)+Math.min(6,Math.max(0,t.priority||0)-1),quotaHeadroomPercent:d}}function en(e,t,n,r=null,i){let o=et(e,t,r,i),l=et(e,n,r,i);if(o.score!==l.score)return o.score-l.score;let a=o.quotaHeadroomPercent??-1,s=l.quotaHeadroomPercent??-1;return a!==s?s-a:(t.priority||999)!==(n.priority||999)?(t.priority||999)-(n.priority||999):t.id.localeCompare(n.id)}let ew="noauth";async function er(e){try{let t=(0,D.f)(e),n={};for(let e of t){let t=await (0,a.W)({provider:e});for(let e of(Array.isArray(t)?t:[]).map(u.j))!function(e,t){let n=t.providerSpecificData;n&&"object"==typeof n&&(Array.isArray(n.fingerprints)&&!Array.isArray(e.fingerprints)&&(e.fingerprints=n.fingerprints),Array.isArray(n.accountProxies)&&!Array.isArray(e.accountProxies)&&(e.accountProxies=n.accountProxies))}(n,e)}return Array.isArray(n.accountProxies)&&(n.accountProxies=await (0,k.f)(n.accountProxies)),n}catch{return{}}}async function ei(e,t){let n,r,i;return(n=(0,S.Q)(e),r=T.f[e],i=v.a[e],n?.anonymousFallback!==!0&&r?.noAuth!==!0&&i?.noAuth!==!0||t.has(ew))?null:function(e={}){return{apiKey:null,accessToken:null,refreshToken:null,expiresAt:null,projectId:null,defaultModel:null,copilotToken:null,providerSpecificData:e,connectionId:ew,testStatus:"active",lastError:null,lastErrorType:null,lastErrorSource:null,errorCode:null,rateLimitedUntil:null,maxConcurrent:null}}(await er(e))}function eo(e,t){let n=new Set;if("string"==typeof e&&e.trim().length>0&&n.add(e.trim()),Array.isArray(t))for(let e of t)"string"==typeof e&&e.trim().length>0&&n.add(e.trim());return n}function el(e,t=6){let n=Array.from(e).filter(e=>"string"==typeof e&&e.length>0).slice(0,t).map(e=>`${e.slice(0,8)}...`);return n.length>0?n.join(","):"none"}function ea(e,t){let n=G(t.map(e=>e.resetAt??null))||new Date(Date.now()+3e5).toISOString(),r=t.map(e=>{let t=Number.isFinite(e.quotaPercent)?`${Math.round(100*e.quotaPercent)}%`:"quota exhausted";return`${e.id.slice(0,8)}(${t})`}).join("; ");return _.info("AUTH",`${e} | quota preflight filtered account(s): ${r}`),{allRateLimited:!0,retryAfter:n,retryAfterHuman:(0,p.s)(n),lastError:`All ${e} accounts blocked by quota preflight`,lastErrorCode:429,cooldownReason:"quota_exhausted"}}async function es(e,t,n,r){let i=new Date(Y(n.resetAt??null??null)??Date.now()+3e5).toISOString(),o=Number.isFinite(n.quotaPercent)?`${Math.round(100*n.quotaPercent)}%`:"exhausted",l=r?` for ${r}`:"";return await (0,a.s)(t,{rateLimitedUntil:i,testStatus:"unavailable",lastError:`Quota preflight blocked${l}: ${o}`,lastErrorType:"quota_exhausted",lastErrorSource:"quota_preflight",errorCode:429,lastErrorAt:new Date().toISOString()}),i}let eA=new Map,eb=new Map,e$=[["nvidia","nvidia_nim"],["kimi-coding","kimi-coding-apikey"]];async function eu(e){let t=(0,S.I)(e),n=(0,S.u)(t),r=e$.find(t=>t.includes(e));if(r)return r[0]===e?r:[r[1],r[0]];let i=new Set([e,t,n].filter(Boolean));if((0,S.Q)(t))return Array.from(i);try{let r=await (0,l.getCachedProviderNodes)();for(let o of Array.isArray(r)?r:[]){let r=O(o),l="string"==typeof r.prefix?r.prefix.trim():"",a="string"==typeof r.id?r.id.trim():"";l&&a&&(l===e||l===t||l===n)&&i.add(a)}}catch{}return Array.from(i)}let eU=new Map;async function ec(e,t=null,n=null,i=null,o={}){var s,f,g,h;let m,y,w,A=(s=[(0,S.I)(e)||e,o.forcedConnectionId?`forced:${o.forcedConnectionId}`:"pool"].join(":"),y=eA.get(s)??Promise.resolve(),w=new Promise(e=>{m=e}),eA.set(s,w),{wait:y,release:()=>{m?.(),eA.get(s)===w&&eA.delete(s)}});try{let s;await A.wait;let m=(0,S.I)(e);if([T.f,v.a].some(e=>e[m]?.noAuth)){if(await (0,C.f)(m))return null;let e=eo(t,o.excludeConnectionIds);return await ei(m,e)}let y=!0===o.allowSuppressedConnections,w=y||!0===o.allowRateLimitedConnections,$=!0===o.bypassQuotaPolicy,U="string"==typeof o.forcedConnectionId&&o.forcedConnectionId.trim().length>0?o.forcedConnectionId.trim():null,k=eo(t,o.excludeConnectionIds),D=await (0,l.getCachedSettings)(),M=(0,E.W)(e,o,D),R=await eu(e),O=(await Promise.all(R.map(e=>(0,l.getCachedRawProviderConnections)({provider:e,isActive:!0})))).filter(Array.isArray).flat(),H=(Array.isArray(O)?O:[]).map(u.o).filter(e=>e.id.length>0);n&&n.length>0&&(H=H.filter(e=>n.includes(e.id))),(U=(0,E.H)({forcedConnectionId:U,options:o,sessionAffinityTtlMs:M,connections:H,provider:e,requestedModel:i,excludedConnectionIds:k,isTerminalConnectionStatus:X,isCodexScopeUnavailable:V,isQuotaPolicyBlocked:t=>J(e,t,i).blocked})??U)&&(H=H.filter(e=>e.id===U));let N=H.length,P=O.length,q=U?P-H.length:0,F=n&&n.length>0?Math.max(0,P-H.length-q):0,j=U?`${U.slice(0,8)}...`:"none";if(_.debug("AUTH",`${e} | active=${N}, excluded=${k.size} (${el(k)}), forcedId=${j}, blocked_forced=${q}, blocked_allowed=${F}`),"antigravity"===e&&(U||n?.length)){let t=[];U&&t.push(`forcedConnectionId kept ${H.length}`),n?.length&&t.push(`allowedConnections=${n.length}`),_.info("AUTH",`${e} selection constrained: ${t.join(", ")}`)}if(0===H.length){let t=(await Promise.all(R.map(e=>(0,a.W)({provider:e})))).filter(Array.isArray).flat().map(u.j).filter(e=>e.id.length>0);if(n&&n.length>0&&(t=t.filter(e=>n.includes(e.id))),U&&(t=t.filter(e=>e.id===U)),_.debug("AUTH",`${e} | all connections (incl inactive): ${t.length}`),t.length>0){let n=(0,p.d)(t);if(n)return _.warn("AUTH",`${e} | all ${t.length} accounts rate limited (${(0,p.s)(n)})`),{allRateLimited:!0,retryAfter:n,retryAfterHuman:(0,p.s)(n)};_.warn("AUTH",`${e} | ${t.length} accounts found but none active`),t.forEach(e=>{_.debug("AUTH",` → ${e.id?.slice(0,8)} | isActive=${e.isActive} | rateLimitedUntil=${e.rateLimitedUntil||"none"} | testStatus=${e.testStatus}`)});let r=t.filter(X);if(r.length===t.length){let e=await ei(m,k);if(e)return e;let t=new Map;for(let e of r){let n=z(e.testStatus)||"expired";t.set(n,(t.get(n)||0)+1)}let n=[...t.entries()].sort((e,t)=>t[1]-e[1])[0]?.[0]||"expired";return{allExpired:!0,expiredCount:r.length,expiredStatus:n}}}let r=await ei(m,k);if(r)return r;return(o.quietMissing?_.debug:_.warn)("AUTH",`No credentials for ${e}`),null}for(let e of H)!(e.backoffLevel>0)||X(e)||(0,p.v)(e.rateLimitedUntil)||(e.backoffLevel=0,(0,a.g)(e.id).catch(()=>{}));let Q=0,K=0,B=new Map,Z=H.filter(t=>{if(k.has(t.id))return B.set(t.id,"excluded"),!1;if(i&&(0,x.p)(i,t.providerSpecificData))return B.set(t.id,"modelExcluded"),!1;if(!y){if(!w&&(0,p.v)(t.rateLimitedUntil))return B.set(t.id,"rateLimited"),!1;if(X(t))return B.set(t.id,"terminalStatus"),!1;if("codex"===e&&V(t,i))return B.set(t.id,"codexScopeLimited"),!1;if(i&&(0,p.t)(e,t.id,i))return B.set(t.id,"modelLocked"),"antigravity"===e&&"family"===(0,d.t)(e,i)?K+=1:Q+=1,!1}return B.set(t.id,"available"),!0});if(_.debug("AUTH",`${e} | available: ${Z.length}/${H.length}`),"antigravity"===e&&_.info("AUTH",`${e} selection candidates model=${i||"none"}: active=${N}, excluded=${k.size}, modelLocked=${Q}, familyLocked=${K}, eligible=${Z.length}`),H.forEach(t=>{let n=B.get(t.id),r="excluded"===n,o="rateLimited"===n;if(r||o)_.debug("AUTH",` → ${t.id?.slice(0,8)} | ${r?"excluded":""} ${o?`rateLimited until ${t.rateLimitedUntil}`:""}${y&&o?" (retained for combo live test)":""}`);else if("modelExcluded"===n)_.debug("AUTH",` → ${t.id?.slice(0,8)} | excluded by per-account model rule for ${i}`);else if("terminalStatus"===n)_.debug("AUTH",y?` → ${t.id?.slice(0,8)} | retained terminal status=${t.testStatus} for combo live test`:` → ${t.id?.slice(0,8)} | skipped terminal status=${t.testStatus}`);else if("codexScopeLimited"===n){let e=W(t.providerSpecificData,i);_.debug("AUTH",y?` → ${t.id?.slice(0,8)} | retained codex scope-limited account until ${e} for combo live test`:` → ${t.id?.slice(0,8)} | codex scope-limited until ${e}`)}else if("modelLocked"===n){let n=(0,p.E)(e,t.id,i);_.debug("AUTH",y?` → ${t.id?.slice(0,8)} | retained model lockout for ${i} (${n?.remainingMs||0}ms remaining) for combo live test`:` → ${t.id?.slice(0,8)} | model-locked for ${i} (${n?.remainingMs||0}ms remaining)`)}}),0===Z.length){let t=H.map(t=>{var n;let r=Y(t.rateLimitedUntil),o="codex"===e?Y(W(t.providerSpecificData,i)):null,l=i?(0,p.E)(e,t.id,i):null,a=l&&l.remainingMs>0&&"string"==typeof(n=l.reason)&&n.length>0&&!ey.has(n)?Date.now()+l.remainingMs:null;return{connection:t,connectionCooldownMs:r,codexScopeCooldownMs:o,retryableModelCooldownMs:a,modelLockoutReason:null!==a&&"string"==typeof l?.reason?l.reason:null,modelLockoutStatus:null!==a&&"number"==typeof l?.status?l.status:null}}),n=t.flatMap(e=>{let t=[];return null!==e.connectionCooldownMs&&t.push({ms:e.connectionCooldownMs,connection:e.connection}),null!==e.codexScopeCooldownMs&&t.push({ms:e.codexScopeCooldownMs,connection:e.connection}),null!==e.retryableModelCooldownMs&&t.push({ms:e.retryableModelCooldownMs,connection:e.connection,lockoutReason:e.modelLockoutReason,lockoutStatus:e.modelLockoutStatus}),t}).sort((e,t)=>e.ms-t.ms),r=!!i&&t.length>0&&t.every(e=>(null!==e.codexScopeCooldownMs||null!==e.retryableModelCooldownMs)&&null===e.connectionCooldownMs),o=n[0],l=o?.ms&&Number.isFinite(o.ms)?new Date(o.ms).toISOString():null;if(l){let t,n,a,s,u,c=o?.connection,d=U?`account ${f=U,t=O.find(e=>e?.id===f),(n=[t?.name,t?.displayName].find(e=>"string"==typeof e&&e.trim().length>0))?n.trim():`${f.slice(0,8)}...`}`:`all ${H.length} active accounts`,m=r?`cooling down for model ${i}`:"rate limited",y=c?.errorCode!=null?` | last error ${g=c.errorCode,a=Number(g),Number.isFinite(a)?String(Math.trunc(a)):String(g)}: ${String(c.lastError??"").slice(0,50)}`:"";return h=`${e}|${d}|${m}|${c?.errorCode??""}`,s=Date.now(),u=eU.get(h),(void 0===u||!(s-u<5e3))&&(eU.size>500&&eU.clear(),eU.set(h,s),1)&&_.warn("AUTH",`${e} | ${d} ${m} (${(0,p.s)(l)})${y}`),{allRateLimited:!0,retryAfter:l,retryAfterHuman:(0,p.s)(l),lastError:c?.lastError||null,lastErrorCode:r?429:c?.errorCode||null,cooldownStatus:r?(0,p.W)(o?.lockoutReason??null,o?.lockoutStatus??c?.errorCode):null,cooldownReason:o?.lockoutReason??("string"==typeof c?.lastErrorType?c.lastErrorType:null),cooldownScope:r?"model":"connection",cooldownModel:r?i:null,connectionsCount:H.length}}let a=await ei(m,k);if(a)return a;let s=H.filter(e=>!k.has(e.id));if(s.length>0&&s.every(e=>"expired"===z(e.testStatus)))return _.warn("AUTH",`${e} | all ${s.length} accounts have a refused key`),{allExpired:!0,expiredCount:s.length,expiredStatus:"expired"};return _.warn("AUTH",`${e} | all ${H.length} accounts unavailable`),null}let ee=Z,et=[],er=new Map;if($?Z.length>0&&_.debug("AUTH",`${e} | bypassing cached quota policy for this request`):ee=Z.filter(t=>{let n=J(e,t,i);return er.set(t.id,{blocked:n.blocked,exhausted:!1}),!n.blocked||(et.push({id:t.id,reasons:n.reasons,resetAt:n.resetAt}),!1)}),et.length>0&&_.info("AUTH",`${e} | quota policy filtered ${et.length} account(s): ${et.map(e=>`${e.id.slice(0,8)}(${e.reasons.join(", ")})`).join("; ")}`),0===ee.length&&Z.length>0){let t=G(et.map(e=>e.resetAt)),n=Y(t),r=n?new Date(n).toISOString():new Date(Date.now()+3e5).toISOString();return{allRateLimited:!0,retryAfter:r,retryAfterHuman:(0,p.s)(r),lastError:`All ${e} accounts reached configured quota threshold`,lastErrorCode:429,cooldownReason:"quota_exhausted"}}let ea=[],es=[];for(let t of ee){let n=(0,c.isQuotaExhaustedForRequest)(t.id,e,i),r=er.get(t.id);r&&(r.exhausted=n),n?es.push(t):ea.push(t)}if(es.length>0&&_.info("AUTH",`${e} | quota-aware: ${ea.length} with quota, skipping ${es.length} exhausted`),0===ea.length&&es.length>0){let t=G(es.map(e=>{let t=(0,c.getQuotaCache)(e.id);return t?.nextResetAt||null})),n=Y(t),r=n?new Date(n).toISOString():new Date(Date.now()+3e5).toISOString();return{allRateLimited:!0,retryAfter:r,retryAfterHuman:(0,p.s)(r),lastError:`All ${e} accounts have exhausted their quota`,lastErrorCode:429,cooldownReason:"quota_exhausted"}}let ec=(D.providerStrategies||{})[m]||{},ed=ec.fallbackStrategy||D.fallbackStrategy||"fill-first",ef=await (0,E.C)(e,o.sessionKey,ea,M);if(ef?s=ef:o.sessionKey&&Number(M)>0&&_.debug("AUTH",`session_key=${(0,E.w)(o.sessionKey)} has no available affinity target`),s);else if("round-robin"===ed){let n=L(ec.stickyRoundRobinLimit??D.stickyRoundRobinLimit,3);if(null!==t||k.size>0){for(let t of(s=[...ea].sort((e,t)=>{let n=e.backoffLevel||0,r=t.backoffLevel||0;return n!==r?n-r:e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime():1:-1:(e.priority||999)-(t.priority||999)})[0],_.info("AUTH",`${e} round-robin: FALLBACK MODE - excluded_count=${k.size} excluded=${el(k)} picked_lru=${s.id?.slice(0,8)}...`),await (0,a.w)(s.id,1),O))if(t.id===s.id){t.lastUsedAt=new Date().toISOString(),t.consecutiveUseCount=1;break}}else{let t=[...ea].sort((e,t)=>e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(t.lastUsedAt).getTime()-new Date(e.lastUsedAt).getTime():-1:1:(e.priority||999)-(t.priority||999))[0],r=t?.consecutiveUseCount||0;if(t&&t.lastUsedAt&&r<n){s=t,_.debug("AUTH",`${e} round-robin: staying with ${t.id?.slice(0,8)}... (count=${r}/${n})`);let i=(s.consecutiveUseCount||0)+1;for(let e of(await (0,a.w)(s.id,i),O))if(e.id===s.id){e.lastUsedAt=new Date().toISOString(),e.consecutiveUseCount=i;break}}else for(let t of(s=[...ea].sort((e,t)=>{let n=e.backoffLevel||0,r=t.backoffLevel||0;return n!==r?n-r:e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime():1:-1:(e.priority||999)-(t.priority||999)})[0],_.debug("AUTH",`${e} round-robin: switching to LRU ${s.id?.slice(0,8)}... (current count=${r} >= limit=${n} or no lastUsedAt)`),await (0,a.w)(s.id,1),O))if(t.id===s.id){t.lastUsedAt=new Date().toISOString(),t.consecutiveUseCount=1;break}}}else if("p2c"===ed){let t=(ea.length,ea);if(t.length<=2)s=[...t].sort((t,n)=>en(e,t,n,i,er))[0];else{let n=parseInt((0,r.randomUUID)().replace(/-/g,"").substring(0,8),16)%t.length,o=parseInt((0,r.randomUUID)().replace(/-/g,"").substring(0,8),16)%(t.length-1);o>=n&&o++;let l=t[n],a=t[o];s=0>=en(e,l,a,i,er)?l:a}}else if("random"===ed){let e=parseInt((0,r.randomUUID)().replace(/-/g,"").substring(0,8),16)%ea.length;s=ea[e]}else if("least-used"===ed)s=[...ea].sort((e,t)=>e.lastUsedAt||t.lastUsedAt?e.lastUsedAt?t.lastUsedAt?new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime():1:-1:(e.priority||999)-(t.priority||999))[0];else if("cost-optimized"===ed)s=[...ea].sort((e,t)=>(e.priority||999)-(t.priority||999))[0];else if("strict-random"===ed){let t=ea.map(e=>e.id),n=(0,I.B)(`conn:${e}`,t);s=ea.find(e=>e.id===n)||ea[0]}else s=ea[0];"antigravity"===e&&s&&_.info("AUTH",`${e} selected account=${s.id?.slice(0,8)}... eligible=${ea.length} excluded=${k.size}`);let ep=s.providerSpecificData?.apiKeyHealth;return ep&&(0,b.v)(s.id,ep),{apiKey:s.apiKey,accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.tokenExpiresAt||s.expiresAt||null,projectId:s.projectId,defaultModel:s.defaultModel||null,copilotToken:"string"==typeof s.providerSpecificData.copilotToken?s.providerSpecificData.copilotToken:null,providerSpecificData:s.providerSpecificData,id:s.id,provider:s.provider,email:s.email,connectionId:s.id,testStatus:s.testStatus,lastError:s.lastError,lastErrorType:s.lastErrorType,lastErrorSource:s.lastErrorSource,errorCode:s.errorCode,rateLimitedUntil:s.rateLimitedUntil,maxConcurrent:s.maxConcurrent,quotaWindowThresholds:s.quotaWindowThresholds??null}}finally{A.release()}}async function ed(e,t=null,n=null,r=null,i={}){if(!0===i.bypassQuotaPolicy||"antigravity"===e&&"always"===(0,f.e)())return ec(e,t,n,r,{...i,bypassQuotaPolicy:!0});let o=[],a=eo(t,i.excludeConnectionIds),{defaultThresholdPercent:s,warnThresholdPercent:u,providerWindowDefaults:c}=(0,w.resolveResilienceSettings)(await (0,l.getCachedSettings)()).quotaPreflight,d=c[e]||{},p=Object.keys(d).length>0,g=s>2;for(;;){let t=await ec(e,null,n,r,{...i,excludeConnectionIds:Array.from(a)});if(!t){if(o.length>0)return ea(e,o);return null}if("allRateLimited"in t&&t.allRateLimited||"allExpired"in t&&t.allExpired){if("allRateLimited"in t&&t.allRateLimited&&o.length>0)return ea(e,o);return t}let l=t.connectionId;if(!l)return t;let c=t.quotaWindowThresholds||{};if(t.providerSpecificData?.quotaPreflightEnabled===!1)return t;let f=Object.keys(c).length>0,h=(0,y.X)(t);if(!f&&!p&&!h&&!g)return t;let m=t=>{if(null!==t)for(let n of"codex"===e?K([t,(0,U.Q)(t)].filter(Boolean)):[t]){let e=c[n];if("number"==typeof e)return e;let t=d[n];if("number"==typeof t)return t}return s},w="codex"===e||"openrouter"===e,A=r&&w?{...t,requestedModel:r}:t,b=await (0,y.d)(e,l,A,{resolveMinRemainingPercent:m,resolveWarnRemainingPercent:()=>u});if(b.proceed)return t;let $=await es(e,l,b,r);o.push({id:l,quotaPercent:b.quotaPercent,resetAt:$}),a.add(l),_.info("AUTH",`${e} | preflight blocked ${l.slice(0,8)}${Number.isFinite(b.quotaPercent)?` at ${Math.round(100*b.quotaPercent)}%`:""} until ${$}`)}}async function ef(e,t,n,r=null,i=null,o=null,s={}){let f,y=eb.get(e)||Promise.resolve();eb.set(e,new Promise(e=>{f=e}));try{let f;await y;let w=(0,M.f)(t,n,e,_);if(w)return w;let b=await (0,a.W)({provider:r}),T=(Array.isArray(b)?b:[]).map(u.j).filter(e=>e.id.length>0).find(t=>t.id===e),x=T?.backoffLevel||0;if(T&&X(T))return _.info("AUTH",`${e.slice(0,8)} terminal status=${T.testStatus}, skipping cooldown overwrite`),{shouldFallback:!0,cooldownMs:0};let E=T?.providerSpecificData?.disableCooling===!0;if(429===t&&T&&!E){let t=(0,c.getQuotaBlockedUntil)(e,i),n=Y(t);if(t&&n){let t=!!(0,c.getQuotaBlockedUntil)(e,null),o=n-Date.now();r&&i&&(0,p.l)(r,e,i,"quota_exhausted",o);let l=T.rateLimitedUntil?(0,p.Z)(T.rateLimitedUntil):0/0;return t&&!(Number.isFinite(l)&&l>=n)&&await (0,a.s)(e,{rateLimitedUntil:new Date(n).toISOString(),testStatus:"unavailable",lastError:"Usage limit reached",lastErrorType:"quota_exhausted",lastErrorAt:new Date().toISOString(),errorCode:429}),_.info("AUTH",`${e.slice(0,8)} usage limit reached${t?"":` for ${i}`} — skipped until ${new Date(n).toISOString()} (${(0,p.s)(new Date(n).toISOString())})`),{shouldFallback:!0,cooldownMs:o}}}let C=T?.rateLimitedUntil?(0,p.Z)(T.rateLimitedUntil):0/0;if(Number.isFinite(C)&&C>Date.now())return _.info("AUTH",`${e.slice(0,8)} already marked unavailable (until ${T?.rateLimitedUntil}), skipping duplicate mark`),{shouldFallback:!0,cooldownMs:C-Date.now()};if("codex"===r&&i){let t=W(T?.providerSpecificData||{},i);if(t&&new Date(t).getTime()>Date.now())return _.info("AUTH",`${e.slice(0,8)} already scope-limited for ${(0,U.A)(i)} (until ${t}), skipping duplicate mark`),{shouldFallback:!0,cooldownMs:new Date(t).getTime()-Date.now()}}let k=o||(r?await (0,p.j)(r):null),D=(0,A.f)(await (0,l.getCachedSettings)()),I="number"==typeof s.retryAfterMs&&s.retryAfterMs>0?Math.ceil(s.retryAfterMs/1e3):0,R=(0,p.u)(t,n,x,i,r,I>0?{"retry-after":String(I)}:null,k),L=T?.providerSpecificData||{},H=L.passthroughModels,N=!0===L.disableCooling,P=(0,p.O)(r,i,H),q={maxCooldownMs:k?.maxCooldownMs};if(P&&r&&"codex"!==r&&i&&(404===t||429===t||t>=500)){let n=404===t?"not_found":429===t&&R.reason===h.m.QUOTA_EXHAUSTED?"quota_exhausted":429===t?"rate_limited":"server_error";if(500===t)return(0,a.s)(e,{lastErrorType:n,lastError:`Model ${i} ${n}`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),_.info("AUTH",`Server error for ${r}:${i} — ${t} ${n} (no model lockout, connection stays active for sibling models)`),{shouldFallback:!0,cooldownMs:0};let o=(0,d.t)(r,i),l="antigravity"===r&&"family"===o&&429===t?3e4:null,s=(0,p.o)(r,e,i,n,t,404===t?k?.baseCooldownMs??m.b.notFoundLocal:l??R.baseCooldownMs??k?.baseCooldownMs??0,k,{...q,exactCooldownMs:!0===R.usedUpstreamRetryHint?R.cooldownMs:R.quotaResetHintMs??null,maxCooldownMs:D.maxCooldownMs,exactCooldownIsUpstreamReset:!0===R.usedUpstreamRetryHint||"number"==typeof R.quotaResetHintMs});return(0,a.s)(e,{lastErrorType:n,lastError:`Model ${i} ${n}`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),_.info("AUTH",`Model-only lockout for ${r}:${i} — ${t} ${n} ${Math.ceil(s.cooldownMs/1e3)}s (failureCount=${s.failureCount}, connection stays active)`),{shouldFallback:!0,cooldownMs:s.cooldownMs}}let{shouldFallback:F,cooldownMs:j,newBackoffLevel:Q,reason:K}=R;if(!F)return{shouldFallback:!1,cooldownMs:0};let B=(0,$.k)(t,n,r);if(r&&"grok-web"===(0,S.I)(r)&&403===t&&i){let n=(0,p.o)(r,e,i,"forbidden",t,k?.baseCooldownMs??m.b.serviceUnavailable,k,{maxCooldownMs:D.maxCooldownMs});return(0,a.s)(e,{lastErrorType:"forbidden",lastError:`Mode ${i} forbidden for this Grok account`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),_.info("AUTH",`Mode-only lockout for ${r}:${i} — 403 forbidden ${Math.ceil(n.cooldownMs/1e3)}s (connection stays active)`),{shouldFallback:!0,cooldownMs:n.cooldownMs}}let V=function(e,t,n=null,r=null){return t.creditsExhausted||402===e?"credits_exhausted":n===$.R.PROJECT_ROUTE_ERROR||n===$.R.OAUTH_INVALID_TOKEN?null:t.permanent||n===$.R.FORBIDDEN?"banned":n!==$.R.ACCOUNT_DEACTIVATED&&n!==$.R.UNAUTHORIZED&&401!==e||n!==$.R.ACCOUNT_DEACTIVATED&&null!=r&&(0,S.I)(r)in v.a?null:"expired"}(t,R,B,r),z=B===$.R.QUOTA_EXHAUSTED||K===h.m.QUOTA_EXHAUSTED?(f=(0,c.getQuotaCache)(e),f?.quotas?G(Object.values(f.quotas).map(e=>e.resetAt)):null):null,Z=Y(z),J=V?0:Z?Z-Date.now():j;if(P&&403===t&&r&&i&&!V){let n=(0,p.o)(r,e,i,"forbidden",t,R.baseCooldownMs??k?.baseCooldownMs??m.b.serviceUnavailable,k,{...q,exactCooldownMs:!0===R.usedUpstreamRetryHint?R.cooldownMs:null,maxCooldownMs:D.maxCooldownMs});return(0,a.s)(e,{lastErrorType:"forbidden",lastError:`Model ${i} forbidden (per-model access/subscription)`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),_.info("AUTH",`Model-only lockout for ${r}:${i} — 403 forbidden ${Math.ceil(n.cooldownMs/1e3)}s (per-model quota provider, connection stays active)`),{shouldFallback:!0,cooldownMs:n.cooldownMs}}let ee=T?.providerSpecificData?.baseUrl;if((0,g.B)(ee)&&404===t&&r&&i){let n=(0,p.o)(r,e,i,"not_found",t,404===t?k?.baseCooldownMs??m.b.notFoundLocal:m.b.notFoundLocal,k,{maxCooldownMs:D.maxCooldownMs});return(0,a.s)(e,{lastErrorType:"not_found",lastError:`Model ${i} not_found`,lastErrorAt:new Date().toISOString(),errorCode:t}).catch(()=>{}),_.info("AUTH",`Model-only lockout for ${r}:${i} — 404 not_found ${Math.ceil(n.cooldownMs/1e3)}s (failureCount=${n.failureCount}, connection stays active)`),{shouldFallback:!0,cooldownMs:n.cooldownMs}}let et="string"==typeof n?n.slice(0,100):"Provider error";if("codex"===r&&429===t&&i&&T){let n=(0,U.A)(i),o=O(T.providerSpecificData.codexScopeRateLimitedUntil),l=W(T.providerSpecificData,i)||(0,p.c)(J),s=Math.max(new Date(l).getTime()-Date.now(),0);return await (0,a.s)(e,{testStatus:"unavailable",lastError:et,errorCode:t,lastErrorAt:new Date().toISOString(),backoffLevel:Q??x,providerSpecificData:{...T.providerSpecificData,codexScopeRateLimitedUntil:{...o,[n]:l}}}),s>0&&(0,p.l)(r,e,i,K||"unknown",s),t&&et&&console.error(`❌ ${r} [${t}] (${n}): ${et}`),{shouldFallback:!0,cooldownMs:s}}let en={lastError:et,lastErrorType:B,errorCode:t,lastErrorAt:new Date().toISOString(),backoffLevel:Q??x};if(!1!==s.persistUnavailableState?J>0&&!N?await (0,a.s)(e,{...en,rateLimitedUntil:(0,p.c)(J),testStatus:"unavailable"}):await (0,a.s)(e,{...en,rateLimitedUntil:null,...V?{testStatus:V}:{}}):(r&&i&&J>0&&(0,p.l)(r,e,i,K||"unknown",J),await (0,a.s)(e,{...en})),R.permanent)try{(await (0,l.getCachedSettings)()).autoDisableBannedAccounts&&(await (0,a.s)(e,{isActive:!1}),_.info("AUTH",`Auto-disabled ${e.slice(0,8)} — permanent ban detected (autoDisableBannedAccounts=true)`))}catch(e){_.info("AUTH",`Auto-disable check failed (non-fatal): ${e}`)}return r&&t&&et&&console.error(`❌ ${r} [${t}]: ${et}`),{shouldFallback:!0,cooldownMs:J}}finally{f&&f(),eb.delete(e)}}async function ep(e,t){(t.testStatus&&"active"!==t.testStatus||t.lastError||t.rateLimitedUntil||t.errorCode||t.lastErrorType||t.lastErrorSource)&&(await (0,a.s)(e,{testStatus:"active",lastError:null,lastErrorAt:null,lastErrorType:null,lastErrorSource:null,errorCode:null,rateLimitedUntil:null,backoffLevel:0}),_.info("AUTH",`Account ${e.slice(0,8)} error cleared`))}async function eg(e,t){return e?.connectionId?t?await (0,a.j)(e.connectionId,t)?(_.info("AUTH",`Account ${e.connectionId.slice(0,8)} error cleared (CAS)`),{applied:!0}):(_.info("AUTH",`Skipped recovery clear for ${e.connectionId.slice(0,8)} — state changed concurrently (CAS miss)`),{applied:!1}):(await ep(e.connectionId,e),{applied:!0}):{applied:!1}}function eh(e,t){let n=N(e?.headers,"Authorization")||N(e?.headers,"authorization");if("string"==typeof n){let e=n.trim();if(e.toLowerCase().startsWith("bearer "))return e.slice(7).trim()||null}let r=N(e?.headers,"x-api-key")||N(e?.headers,"X-Api-Key");if("string"==typeof r){let e=r.trim();if(e.length>0)return e}let o=(0,i.f)(e?.headers);if(o)return o;if(t?.allowUrl===!1)return null;if("string"!=typeof e?.url||0===e.url.trim().length)return null;try{let t=new URL(e.url,"http://localhost").pathname.split("/").map(e=>e.trim()).filter(Boolean);if("vscode"===t[0]&&t[1]){let e=decodeURIComponent(t[1]).trim();if(e.length>0)return e}if("api"===t[0]&&"v1"===t[1]&&"vscode"===t[2]){if(t[3]&&"raw"!==t[3]&&"combos"!==t[3]){let e=decodeURIComponent(t[3]).trim();if(e.length>0)return e}if(("raw"===t[3]||"combos"===t[3])&&t[4]){let e=decodeURIComponent(t[4]).trim();if(e.length>0)return e}}}catch{}return null}async function em(e){if(!e)return!1;let t=process.env.TROUTEAI_API_KEY||process.env.ROUTER_API_KEY;return!!t&&e===t||await (0,s.validateApiKey)(e)}n()}catch(e){n(e)}},!1),350793,e=>e.a(async(t,n)=>{try{e.s(["f",()=>o]);var r=e.i(259298),i=t([r]);function o(e){return(0,r.g)(e,"x-goog-api-key")||(0,r.g)(e,"X-Goog-Api-Key")}[r]=i.then?(await i)():i,n()}catch(e){n(e)}},!1),367333,e=>e.a(async(t,n)=>{try{var r=e.i(687267),i=e.i(507651),o=e.i(131707),l=t([i]);async function a(e){try{let t=await (0,r.getCachedSettings)();return(0,i.q)(e,t.blockedProviders)}catch(t){return o.warn("AUTH",`Could not read blocked provider settings for ${e}: ${t instanceof Error?t.message:String(t)}`),!1}}[i]=l.then?(await l)():l,e.s(["f",0,a]),n()}catch(e){n(e)}},!1),348704,e=>{"use strict";let t={"opencode-zen":["opencode"],"opencode-go":["opencode"]};e.s(["f",0,function(e){return[e,...t[e]||[]]}])},186071,e=>{"use strict";var t=e.i(132446),n=e.i(696582);function r(e){let t="string"==typeof e.host?e.host.trim():"";if(!t)return null;let r="string"==typeof e.username?e.username:"",i="string"==typeof e.password?e.password:"",o="string"==typeof e.type&&e.type?e.type:"socks5",l=(0,n.w)(o)?(0,n.V)(e.notes):void 0;return{type:o,host:t,port:Number(e.port)||0,...r?{username:r}:{},...i?{password:i}:{},...l?{relayAuth:l}:{}}}async function i(e,t){if(!Array.isArray(e))return[];let n=[];for(let i of e)if(i&&"object"==typeof i&&"string"==typeof i.fingerprint){if("string"==typeof i.proxyId&&i.proxyId){let e=null;try{e=await t(i.proxyId)}catch{e=null}n.push({fingerprint:i.fingerprint,proxy:e?r(e):null});continue}if(i.proxy&&"object"==typeof i.proxy){n.push({fingerprint:i.fingerprint,proxy:r(i.proxy)});continue}n.push({fingerprint:i.fingerprint,proxy:null})}return n}async function o(e){return i(e,e=>(0,t.V)(e,{includeSecrets:!0}))}e.s(["f",0,o])},457308,e=>e.a(async(t,n)=>{try{var r=e.i(538038),i=t([r]);[r]=i.then?(await i)():i,e.s(["f",0,function(e,t,n,i){return 404===e&&(0,r.n)(t)?(i.info("AUTH",`${n.slice(0,8)} request-resource 404; skipping model/account cooldown`),{shouldFallback:!1,cooldownMs:0}):null}]),n()}catch(e){n(e)}},!1),114843,e=>e.a(async(t,n)=>{try{var r=e.i(756045),i=e.i(648830),o=e.i(987227),l=e.i(435005),a=e.i(58501),s=e.i(131707),u=t([i,l,a]);function c(e){return`${e.slice(0,18)}...`}function d(e,t){if(!e.lastUsedAt&&!t.lastUsedAt)return(e.priority||999)-(t.priority||999);if(!e.lastUsedAt)return -1;if(!t.lastUsedAt)return 1;let n=new Date(e.lastUsedAt).getTime()-new Date(t.lastUsedAt).getTime();return 0!==n?n:(e.consecutiveUseCount||0)!==(t.consecutiveUseCount||0)?(e.consecutiveUseCount||0)-(t.consecutiveUseCount||0):(e.priority||999)-(t.priority||999)}async function f(e,t,n,o=0){if(!t||0===n.length||o<=0)return null;let l=(0,r.getSessionAccountAffinity)(t,e,o);if(l){let a=n.find(e=>e.id===l.connectionId);if(a)return(0,r.touchSessionAccountAffinity)(t,e,Date.now(),o),await (0,i.s)(a.id,{lastUsedAt:new Date().toISOString(),consecutiveUseCount:(a.consecutiveUseCount||0)+1}),s.info("AUTH",`session_key=${c(t)} -> connection ${a.id.slice(0,8)} (affinity)`),a;(0,r.deleteSessionAccountAffinity)(t,e),s.info("AUTH",`affinity cleared for session_key=${c(t)} provider=${e}`)}let a=[...n].sort(d)[0]??null;return a?((0,r.upsertSessionAccountAffinity)(t,e,a.id,Date.now(),o),await (0,i.s)(a.id,{lastUsedAt:new Date().toISOString(),consecutiveUseCount:1}),s.info("AUTH",`new affinity created for session_key=${c(t)} -> connection ${a.id.slice(0,8)}`),a):null}[i,l,a]=u.then?(await u)():u,e.s(["H",0,function(e){let{forcedConnectionId:t,options:n,sessionAffinityTtlMs:i,connections:u,provider:c}=e,d=n.sessionKey;if(!t||!d||i<=0)return null;let f=(0,r.getSessionAccountAffinity)(d,c,i);if(!f||f.connectionId===t)return null;let p=u.find(e=>e.id===f.connectionId);return p&&function(e,t){let{provider:n,requestedModel:r,options:i}=t,s=!0===i.allowSuppressedConnections,u=s||!0===i.allowRateLimitedConnections;return!(t.excludedConnectionIds.has(e.id)||r&&(0,o.p)(r,e.providerSpecificData)||!s&&(!u&&(0,a.v)(e.rateLimitedUntil)||t.isTerminalConnectionStatus(e)||"codex"===n&&t.isCodexScopeUnavailable(e,r)||r&&(0,a.t)(n,e.id,r)))&&!((0,l.isAccountQuotaExhausted)(e.id)||!0!==i.bypassQuotaPolicy&&t.isQuotaPolicyBlocked(e))}(p,e)?(s.info("AUTH",`session affinity pin ${f.connectionId.slice(0,8)}... overrides forcedConnectionId ${t.slice(0,8)}...`),f.connectionId):null},"w",0,c,"W",0,function(e,t,n){let r=Number(t.sessionAffinityTtlMs);if(Number.isFinite(r)&&r>0)return r;let i=Number(n.sessionAffinityTtlMs??n.codexSessionAffinityTtlMs);return Number.isFinite(i)&&i>0?i:0},"C",0,f]),n()}catch(e){n(e)}},!1),131707,e=>{"use strict";let t=(0,e.i(335092).f)("sse");function n(e){return e?"string"==typeof e?{detail:e}:"object"==typeof e?e:{detail:String(e)}:{}}e.s(["debug",0,function(e,r,i){t.debug({tag:e,...n(i)},r)},"error",0,function(e,r,i){t.error({tag:e,...n(i)},r)},"info",0,function(e,r,i){t.info({tag:e,...n(i)},r)},"request",0,function(e,r,i){t.info({tag:"HTTP",method:e,path:r,...n(i)},`📥 ${e} ${r}`)},"warn",0,function(e,r,i){t.warn({tag:e,...n(i)},r)}])}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=_1wdvkgutsnz5f._.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
module.exports=[86150,e=>{"use strict";var t=e.i(512575);t.B;let n=(0,t.w)("sdk-cli"),r=t.J,i=t.g,o=["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,i,"r",0,n,"u",0,function(e){let t=String(e||"").trim().toLowerCase().replace(/-\d{8}$/,"");return o.some(e=>t===e||t.startsWith(`${e}-`))}])},170557,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"])},799010,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}])},372491,e=>{"use strict";let t=new Set(["agentrouter"]);e.s(["f",0,function(e){return"string"==typeof e&&t.has(e)}])},660649,e=>{"use strict";var t=e.i(666680),n=e.i(307095),r=e.i(807178),i=e.i(86150),o=e.i(588617),s=e.i(264703);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(843819),e.i(351129);var c=e.i(372491);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),i=n.match(f);if(i){let e=i[1],t={type:"base64",media_type:e,data:i[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(798679),e.i(958303);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,o._)("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||"")}`,i=n.match(/(\/v\d+)$/i);return i&&r.toLowerCase().startsWith(`${i[1].toLowerCase()}/`)?`${n}${r.slice(i[1].length)}`:`${n}${r}`}function w({sourceBody:e,normalizedBody:n,claudeBody:r,model:i,stream:o=!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||{},E=r?c?(k=Array.isArray((y=r).messages)?y.messages:[],b={system:[...T(y.system),...U(k)],messages:k.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t}),tools:O(y.tools),thinking:D($(y.thinking))||null},(x=D($(y.metadata)))&&(b.metadata=x),(v=D($(y.output_config)))&&(b.output_config=v),b):C(r,l):null,M=Array.isArray(j.messages)?j.messages:[],B=!E&&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}),i="string"==typeof e.system||Array.isArray(e.system)&&e.system.length>0;if(!i&&!r)return null;let o=n.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t});return C({...e,...i?{}:{system:U(n)},messages:o},t)}(e,l):null,z=E||B,W=z?c&&E?function(e,t){let n=Array.isArray(e)?e.map(e=>$(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)&&L(e.content);return n}(z.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 i=I(e?.content).map(e=>{if(t)return e;let{cache_control:n,...r}=e;return r});return 0===i.length?null:{role:r,content:i}})(e,t)).filter(e=>!!e&&e.content.length>0):[],r=[],i=!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),o=r[r.length-1],s=t||n||i||o?.content?.some(e=>"tool_use"===e.type)||o?.content?.some(e=>"tool_result"===e.type);o&&o.role===e.role&&!s?o.content.push(...e.content):r.push({role:e.role,content:[...e.content]}),i="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)L(e.content);if(0===r.length){let e=n.flatMap(e=>e.content).map(e=>R(e)).filter(Boolean).join("\n").trim();if(e)return[{role:"user",content:[{type:"text",text:e}]}]}return r}(z.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=R(e?.content),i=[...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 i=p(e);if(i){t.push(i);continue}("image"===e.type||"document"===e.type)&&g(e.source)&&t.push(e)}return t}(e?.content):[]];return 0===i.length?null:{role:n,content:i}})(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}(M),K=function({messages:e,systemBlocks:t,preserveCacheControl:n}){var r;let i=(Array.isArray(t)&&t.length>0?t.map(e=>({...e})):U(e)).map(e=>{let t={...e};return n||delete t.cache_control,t});return(r=i,0===_.length||!(r.length<_.length)&&r.some((e,t)=>_.every((e,n)=>{let i=r[t+n];return!!i&&Object.entries(e).every(([e,t])=>i[e]===t)})))?i:[..._.map(e=>({...e})),...i]}({messages:c?[]:M,systemBlocks:z?.system,preserveCacheControl:l}),q=a||(0,t.randomUUID)(),X=S(e,n,i),F=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),P=E?.tools?(d=E.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=D(e);if(!t)return null;let n="function"===t.type&&D(t.function)||t,r=N(n.name);if(!r)return null;let i=D(n.parameters)||D(n.input_schema)||{type:"object",properties:{},required:[]},o="object"!==i.type||D(i.properties)?i:{...i,properties:{}},s={name:r,description:N(n.description)||"",input_schema:o};return"boolean"==typeof n.defer_loading&&(s.defer_loading=n.defer_loading),s})(e)).filter(e=>!!e).map(e=>({...e}))),J=P.length>0?function(e){if(!e)return null;if("string"==typeof e)return"required"===e?{type:"any"}:null;let t=D(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(D(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:i,sessionId:o}){let s=D($(e?.metadata))||D($(n?.metadata))||D($(r?.metadata))||{};return N(s.user_id)||(s.user_id=JSON.stringify({device_id:(0,t.createHash)("sha256").update(String(i||"")).digest("hex"),account_uuid:"",session_id:o})),s}({claudeBody:r,sourceBody:e,normalizedBody:n,cwd:s,sessionId:q}),H=function({claudeBody:e,sourceBody:t,normalizedBody:n,summarizeThinking:r=!1}){let i=D($(e?.thinking))||D($(t?.thinking))||D($(n?.thinking));return i?u(i,{normalizedBody:n,summarizeThinking:r}):u({type:"adaptive"},{normalizedBody:n,summarizeThinking:r})}({claudeBody:E??r,sourceBody:e,normalizedBody:n,summarizeThinking:f}),Z=function({claudeBody:e,sourceBody:t,normalizedBody:n,model:r,effort:i}){return{...D($(e?.output_config))||D($(t?.output_config))||D($(n?.output_config))||{},effort:S(t,n,r)||i}}({claudeBody:r,sourceBody:e,normalizedBody:n,model:i,effort:X});return{model:i,messages:W,system:K,tools:P,metadata:V,max_tokens:F,thinking:H,output_config:Z,...J?{tool_choice:J}:{},...o?{stream:!0}:{}}}function S(e,t,n){let r=(M(e,["output_config","effort"])||M(e,["reasoning","effort"])||N(e?.reasoning_effort)||M(t,["output_config","effort"])||M(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,o.I)(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=D(e);return r?{...r,content:(n=I(t=r.content)).length>0?n:t}:null}).filter(e=>!!e):[],tools:O(e.tools),thinking:D(e.thinking)||null},m,!0);return D(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 O(e){return Array.isArray(e)?e.map(e=>D($(e))).filter(e=>!!e):[]}function I(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=D($(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 U(e){return Array.isArray(e)?e.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"===t||"developer"===t}).map(e=>R(e?.content)).filter(Boolean).map(e=>({type:"text",text:e})):[]}function L(e){for(let t of e)delete t.cache_control}function $(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}function R(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 E(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 D(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function M(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":i.r,"X-Stainless-Retry-Count":"0","X-Stainless-Timeout":String(A),"X-Stainless-Lang":"js","X-Stainless-Package-Version":i.Q,"X-Stainless-OS":"MacOS","X-Stainless-Arch":"arm64","X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":i.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=E(e,"x-claude-code-session-id")||E(e,"x-session-id")||E(e,"x_session_id")||E(e,"x-trouteai-session")||null;return n&&n.trim()||(0,t.randomUUID)()},"r",0,b,"e",0,x],660649)},843819,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 i(e,t,n){r(e).set(t,n)}function o(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 i=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=o(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 i=g.get(n);if(i)return i;let o=t[n]??a[n]??(n.split(/[_\s-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")||n),s=o,l=2;for(;s!==n&&f.has(s);)s=`${o}${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&&i(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)&&i(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)&&i(h.name)&&(e.tool_choice={...h,name:d(h.name)}),y??new Map},"j",0,function(e){let r=!1,s=!1,a=o(e.tools),l=e.tools;if(Array.isArray(l))for(let o of l){if(!o||c(o.type))continue;let a=String(o.name||"");if(t[a]){let n=t[a];o.name=n,i(e,n,a),r=!0}else n[a]&&(s=!0)}let u=e.messages;if(Array.isArray(u))for(let o of u){let l=o.content;if(Array.isArray(l)){for(let o of l)if("tool_use"===o.type&&"string"==typeof o.name){if(a.has(o.name))continue;let l=t[o.name];if(l){let t=o.name;o.name=l,i(e,l,t),r=!0}else n[o.name]&&(s=!0)}}}let f=e.tool_choice;if(f?.type==="tool"&&"string"==typeof f.name&&!a.has(f.name)){let o=t[f.name];if(o){let t=f.name;f.name=o,i(e,o,t),r=!0}else n[f.name]&&(s=!0)}return r&&!s}],843819)},457858,e=>{"use strict";var t=e.i(394043),n=e.i(846280),r=e.i(799010),i=e.i(660649),o=e.i(851229),s=e.i(22353),a=e.i(372491);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,o.U)(t?.providerSpecificData),l=(0,i.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,o={}){if((0,a.f)(e)){let t=(0,n.k)(e),r=m(e),s=o?.baseUrl||t?.baseUrl||r.baseUrl;return(0,i.Q)(s,i.d)}if(c(e)){var s;let t,n,r=o?.providerSpecificData||null,i=y(e,r);return s=o?.baseUrl||("string"==typeof r?.baseUrl?r.baseUrl:null)||l,t=s.replace(/\/$/,""),n="/chat/completions","responses"===i?n="/responses":"embeddings"===i?n="/embeddings":"audio-transcriptions"===i?n="/audio/transcriptions":"audio-speech"===i?n="/audio/speech":"images-generations"===i&&(n="/images/generations"),`${t}${n}`}if(f(e)){let t,n=o?.baseUrl||u;return p(e)?(0,i.Q)(n,i.d):(t=n.replace(/\/$/,""),`${t}/messages`)}let g=(0,n.k)(e),d=m(e);if(g){if(g.baseUrls){let e=o?.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,"p",0,m,"a",0,function(e,t=null){if(c(e))return"responses"===y(e,t)?"openai-responses":"openai";if(f(e))return"claude";let i=(0,n.k)(e);if(i){let e=(0,r.f)(i,t);return e?e.format:i.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}])},835884,e=>{"use strict";let t,n;var r=e.i(719686),i=e.i(415310);let o=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(e,t,n,i){if(!e||!i)return;i.length>1e4&&(i=i.slice(0,1e4));let o=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:i,provider:t,model:n,expiresAt:o+72e5,createdAt:o});try{(0,r.R)(e,t,n,i,72e5)}catch{}}function y(){let e=Date.now();for(let[t,n]of l)e>=n.expiresAt&&l.delete(t);try{return(0,r.F)()}catch{return 0}}try{let e=y();e>0&&console.log(`[ReasoningCache] boot cleanup removed ${e} expired entries`)}catch(e){console.error("[ReasoningCache] boot cleanup failed:",e)}(0,i.setIdleAwareInterval)("reasoning-cache-cleanup",()=>{try{let e=y();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 i="string"==typeof e.reasoning_content&&e.reasoning_content.length>0?e.reasoning_content:"string"==typeof e.reasoning&&e.reasoning.length>0?e.reasoning:"";if(!i)return 0;let o=Array.isArray(e.tool_calls)?e.tool_calls.map(e=>"string"==typeof e.id?e.id:"").filter(e=>e.length>0):[];if(0===o.length){let e=r?.requestId?.trim(),o=r?.messageIndex;return e&&"number"==typeof o&&Number.isInteger(o)?(p(`request:${e}:message:${o}`,t,n,i),1):0}for(let e of o)e&&p(e,t,n,i);return o.length},"b",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&&(!!o.has(t)||s.some(e=>e.test(n))))}])},264703,e=>{"use strict";var t=e.i(170557),n=e.i(835884),r=e.i(588617),i=e.i(367613);let o=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 i of e){if("assistant"!==i.role||!Array.isArray(i.content)){t.push(i);continue}let e=i.content.filter(e=>e?.type==="tool_result");if(0===e.length){t.push(i),r(i.content);continue}let o=e.filter(e=>"string"==typeof e?.tool_use_id&&n.has(e.tool_use_id)),s=i.content.filter(e=>e?.type!=="tool_result");if(o.length>0){let e=t[t.length-1];e&&"user"===e.role&&Array.isArray(e.content)?t[t.length-1]={...e,content:[...e.content,...o]}:t.push({role:"user",content:o})}s.length>0&&(t.push({...i,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&&o.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.T)(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,o=[];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))&&o.push(n)}for(let e of o)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=o=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}(o=s(o));let u=o[o.length-1],f=u?.role==="user",p=e.thinking?.type==="enabled"&&f;if(!c&&y){let e=o.reduce((e,t,n)=>(t?.role==="user"&&e.push(n),e),[]),t=e.length>=2?e[e.length-2]:-1;t>=0&&l(o[t])}let d=-1;for(let e=o.length-1;e>=0;e--)if(o[e]?.role==="assistant"){d=e;break}let h=!1;for(let e=o.length-1;e>=0;e--){let t=o[e],r=a(t);if("assistant"===t.role&&r.length>0){!c&&y&&!h&&l(t)&&(h=!0);let o=e===d?r.filter(e=>"thinking"===e.type||"redacted_thinking"===e.type):[],s=o.length>0;if(o.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.b)(e);r&&(t=r,(0,n.X)())}}e.type="thinking",e.thinking=t||i.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.b)(t);r&&(e=r,(0,n.X)())}r.unshift({type:"thinking",thinking:e||i.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:[],i=r.some(e=>e?.type==="tool_use"),o=r.some(e=>e?.type==="thinking"||e?.type==="redacted_thinking");if(!i||o)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])},367613,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}])},22353,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 i(e,t){let n=Object.keys(e??{}).find(e=>e.toLowerCase()===t);return n?r(e?.[n]):void 0}function o(e,s={}){let a=r(s.taskId)??i(e,"x-task-id")??(0,t.randomUUID)(),l=r(s.clientVersion)??n;for(let[t,i]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]=i}return e}function s(e,t={},n={}){let r,i=(r=function(e){if("string"!=typeof e)return"";let t=e.trim();return t?t.startsWith("workos:")?t:`workos:${t}`:""}(e))?`Bearer ${r}`:"",a=o({...t},n);return i&&(a.Authorization=i),a}e.s(["b",0,function(e,n,r,a,l){let u={taskId:i(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=o({},n),i=t||e?.apiKey;return i&&(r.Authorization=`Bearer ${i}`),r}(n,r,u):s(r||n?.accessToken,{},u)),e},"w",0,o,"k",0,s])}];
|
|
1
|
+
module.exports=[86150,e=>{"use strict";var t=e.i(512575);t.B;let n=(0,t.w)("sdk-cli"),r=t.J,i=t.g,o=["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,i,"r",0,n,"u",0,function(e){let t=String(e||"").trim().toLowerCase().replace(/-\d{8}$/,"");return o.some(e=>t===e||t.startsWith(`${e}-`))}])},170557,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"])},799010,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}])},372491,e=>{"use strict";let t=new Set(["agentrouter"]);e.s(["f",0,function(e){return"string"==typeof e&&t.has(e)}])},660649,e=>{"use strict";var t=e.i(666680),n=e.i(307095),r=e.i(807178),i=e.i(86150),o=e.i(588617),s=e.i(264703);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(843819),e.i(351129);var c=e.i(372491);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),i=n.match(f);if(i){let e=i[1],t={type:"base64",media_type:e,data:i[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(798679),e.i(958303);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,o._)("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||"")}`,i=n.match(/(\/v\d+)$/i);return i&&r.toLowerCase().startsWith(`${i[1].toLowerCase()}/`)?`${n}${r.slice(i[1].length)}`:`${n}${r}`}function w({sourceBody:e,normalizedBody:n,claudeBody:r,model:i,stream:o=!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||{},E=r?c?(k=Array.isArray((y=r).messages)?y.messages:[],b={system:[...T(y.system),...U(k)],messages:k.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t}),tools:O(y.tools),thinking:D($(y.thinking))||null},(x=D($(y.metadata)))&&(b.metadata=x),(v=D($(y.output_config)))&&(b.output_config=v),b):C(r,l):null,M=Array.isArray(j.messages)?j.messages:[],B=!E&&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}),i="string"==typeof e.system||Array.isArray(e.system)&&e.system.length>0;if(!i&&!r)return null;let o=n.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"!==t&&"developer"!==t});return C({...e,...i?{}:{system:U(n)},messages:o},t)}(e,l):null,z=E||B,W=z?c&&E?function(e,t){let n=Array.isArray(e)?e.map(e=>$(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)&&L(e.content);return n}(z.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 i=I(e?.content).map(e=>{if(t)return e;let{cache_control:n,...r}=e;return r});return 0===i.length?null:{role:r,content:i}})(e,t)).filter(e=>!!e&&e.content.length>0):[],r=[],i=!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),o=r[r.length-1],s=t||n||i||o?.content?.some(e=>"tool_use"===e.type)||o?.content?.some(e=>"tool_result"===e.type);o&&o.role===e.role&&!s?o.content.push(...e.content):r.push({role:e.role,content:[...e.content]}),i="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)L(e.content);if(0===r.length){let e=n.flatMap(e=>e.content).map(e=>R(e)).filter(Boolean).join("\n").trim();if(e)return[{role:"user",content:[{type:"text",text:e}]}]}return r}(z.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=R(e?.content),i=[...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 i=p(e);if(i){t.push(i);continue}("image"===e.type||"document"===e.type)&&g(e.source)&&t.push(e)}return t}(e?.content):[]];return 0===i.length?null:{role:n,content:i}})(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}(M),K=function({messages:e,systemBlocks:t,preserveCacheControl:n}){var r;let i=(Array.isArray(t)&&t.length>0?t.map(e=>({...e})):U(e)).map(e=>{let t={...e};return n||delete t.cache_control,t});return(r=i,0===_.length||!(r.length<_.length)&&r.some((e,t)=>_.every((e,n)=>{let i=r[t+n];return!!i&&Object.entries(e).every(([e,t])=>i[e]===t)})))?i:[..._.map(e=>({...e})),...i]}({messages:c?[]:M,systemBlocks:z?.system,preserveCacheControl:l}),q=a||(0,t.randomUUID)(),X=S(e,n,i),F=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),P=E?.tools?(d=E.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=D(e);if(!t)return null;let n="function"===t.type&&D(t.function)||t,r=N(n.name);if(!r)return null;let i=D(n.parameters)||D(n.input_schema)||{type:"object",properties:{},required:[]},o="object"!==i.type||D(i.properties)?i:{...i,properties:{}},s={name:r,description:N(n.description)||"",input_schema:o};return"boolean"==typeof n.defer_loading&&(s.defer_loading=n.defer_loading),s})(e)).filter(e=>!!e).map(e=>({...e}))),J=P.length>0?function(e){if(!e)return null;if("string"==typeof e)return"required"===e?{type:"any"}:null;let t=D(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(D(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:i,sessionId:o}){let s=D($(e?.metadata))||D($(n?.metadata))||D($(r?.metadata))||{};return N(s.user_id)||(s.user_id=JSON.stringify({device_id:(0,t.createHash)("sha256").update(String(i||"")).digest("hex"),account_uuid:"",session_id:o})),s}({claudeBody:r,sourceBody:e,normalizedBody:n,cwd:s,sessionId:q}),H=function({claudeBody:e,sourceBody:t,normalizedBody:n,summarizeThinking:r=!1}){let i=D($(e?.thinking))||D($(t?.thinking))||D($(n?.thinking));return i?u(i,{normalizedBody:n,summarizeThinking:r}):u({type:"adaptive"},{normalizedBody:n,summarizeThinking:r})}({claudeBody:E??r,sourceBody:e,normalizedBody:n,summarizeThinking:f}),Z=function({claudeBody:e,sourceBody:t,normalizedBody:n,model:r,effort:i}){return{...D($(e?.output_config))||D($(t?.output_config))||D($(n?.output_config))||{},effort:S(t,n,r)||i}}({claudeBody:r,sourceBody:e,normalizedBody:n,model:i,effort:X});return{model:i,messages:W,system:K,tools:P,metadata:V,max_tokens:F,thinking:H,output_config:Z,...J?{tool_choice:J}:{},...o?{stream:!0}:{}}}function S(e,t,n){let r=(M(e,["output_config","effort"])||M(e,["reasoning","effort"])||N(e?.reasoning_effort)||M(t,["output_config","effort"])||M(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,o.I)(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=D(e);return r?{...r,content:(n=I(t=r.content)).length>0?n:t}:null}).filter(e=>!!e):[],tools:O(e.tools),thinking:D(e.thinking)||null},m,!0);return D(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 O(e){return Array.isArray(e)?e.map(e=>D($(e))).filter(e=>!!e):[]}function I(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=D($(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 U(e){return Array.isArray(e)?e.filter(e=>{let t=String(e?.role||"").toLowerCase();return"system"===t||"developer"===t}).map(e=>R(e?.content)).filter(Boolean).map(e=>({type:"text",text:e})):[]}function L(e){for(let t of e)delete t.cache_control}function $(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}function R(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 E(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 D(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function M(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":i.r,"X-Stainless-Retry-Count":"0","X-Stainless-Timeout":String(A),"X-Stainless-Lang":"js","X-Stainless-Package-Version":i.Q,"X-Stainless-OS":"MacOS","X-Stainless-Arch":"arm64","X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":i.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=E(e,"x-claude-code-session-id")||E(e,"x-session-id")||E(e,"x_session_id")||E(e,"x-trouteai-session")||null;return n&&n.trim()||(0,t.randomUUID)()},"r",0,b,"e",0,x],660649)},843819,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 i(e,t,n){r(e).set(t,n)}function o(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 i=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=o(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 i=g.get(n);if(i)return i;let o=t[n]??a[n]??(n.split(/[_\s-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")||n),s=o,l=2;for(;s!==n&&f.has(s);)s=`${o}${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&&i(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)&&i(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)&&i(h.name)&&(e.tool_choice={...h,name:d(h.name)}),y??new Map},"j",0,function(e){let r=!1,s=!1,a=o(e.tools),l=e.tools;if(Array.isArray(l))for(let o of l){if(!o||c(o.type))continue;let a=String(o.name||"");if(t[a]){let n=t[a];o.name=n,i(e,n,a),r=!0}else n[a]&&(s=!0)}let u=e.messages;if(Array.isArray(u))for(let o of u){let l=o.content;if(Array.isArray(l)){for(let o of l)if("tool_use"===o.type&&"string"==typeof o.name){if(a.has(o.name))continue;let l=t[o.name];if(l){let t=o.name;o.name=l,i(e,l,t),r=!0}else n[o.name]&&(s=!0)}}}let f=e.tool_choice;if(f?.type==="tool"&&"string"==typeof f.name&&!a.has(f.name)){let o=t[f.name];if(o){let t=f.name;f.name=o,i(e,o,t),r=!0}else n[f.name]&&(s=!0)}return r&&!s}],843819)},457858,e=>{"use strict";var t=e.i(394043),n=e.i(846280),r=e.i(799010),i=e.i(660649),o=e.i(851229),s=e.i(22353),a=e.i(372491);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,o.U)(t?.providerSpecificData),l=(0,i.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,o={}){if((0,a.f)(e)){let t=(0,n.k)(e),r=m(e),s=o?.baseUrl||t?.baseUrl||r.baseUrl;return(0,i.Q)(s,i.d)}if(c(e)){var s;let t,n,r=o?.providerSpecificData||null,i=y(e,r);return s=o?.baseUrl||("string"==typeof r?.baseUrl?r.baseUrl:null)||l,t=s.replace(/\/$/,""),n="/chat/completions","responses"===i?n="/responses":"embeddings"===i?n="/embeddings":"audio-transcriptions"===i?n="/audio/transcriptions":"audio-speech"===i?n="/audio/speech":"images-generations"===i&&(n="/images/generations"),`${t}${n}`}if(f(e)){let t,n=o?.baseUrl||u;return p(e)?(0,i.Q)(n,i.d):(t=n.replace(/\/$/,""),`${t}/messages`)}let g=(0,n.k)(e),d=m(e);if(g){if(g.baseUrls){let e=o?.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,"p",0,m,"a",0,function(e,t=null){if(c(e))return"responses"===y(e,t)?"openai-responses":"openai";if(f(e))return"claude";let i=(0,n.k)(e);if(i){let e=(0,r.f)(i,t);return e?e.format:i.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}])},835884,e=>{"use strict";let t,n;var r=e.i(719686),i=e.i(415310);let o=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(e,t,n,i){if(!e||!i)return;i.length>1e4&&(i=i.slice(0,1e4));let o=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:i,provider:t,model:n,expiresAt:o+72e5,createdAt:o});try{(0,r.R)(e,t,n,i,72e5)}catch{}}function y(){let e=Date.now();for(let[t,n]of l)e>=n.expiresAt&&l.delete(t);try{return(0,r.F)()}catch{return 0}}try{let e=y();e>0&&console.log(`[ReasoningCache] boot cleanup removed ${e} expired entries`)}catch(e){console.error("[ReasoningCache] boot cleanup failed:",e)}(0,i.setIdleAwareInterval)("reasoning-cache-cleanup",()=>{try{let e=y();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 i="string"==typeof e.reasoning_content&&e.reasoning_content.length>0?e.reasoning_content:"string"==typeof e.reasoning&&e.reasoning.length>0?e.reasoning:"";if(!i)return 0;let o=Array.isArray(e.tool_calls)?e.tool_calls.map(e=>"string"==typeof e.id?e.id:"").filter(e=>e.length>0):[];if(0===o.length){let e=r?.requestId?.trim(),o=r?.messageIndex;return e&&"number"==typeof o&&Number.isInteger(o)?(p(`request:${e}:message:${o}`,t,n,i),1):0}for(let e of o)e&&p(e,t,n,i);return o.length},"b",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&&(!!o.has(t)||s.some(e=>e.test(n))))}])},264703,e=>{"use strict";var t=e.i(170557),n=e.i(835884),r=e.i(588617),i=e.i(367613);let o=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 i of e){if("assistant"!==i.role||!Array.isArray(i.content)){t.push(i);continue}let e=i.content.filter(e=>e?.type==="tool_result");if(0===e.length){t.push(i),r(i.content);continue}let o=e.filter(e=>"string"==typeof e?.tool_use_id&&n.has(e.tool_use_id)),s=i.content.filter(e=>e?.type!=="tool_result");if(o.length>0){let e=t[t.length-1];e&&"user"===e.role&&Array.isArray(e.content)?t[t.length-1]={...e,content:[...e.content,...o]}:t.push({role:"user",content:o})}s.length>0&&(t.push({...i,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&&o.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.T)(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,o=[];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))&&o.push(n)}for(let e of o)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=o=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}(o=s(o));let u=o[o.length-1],f=u?.role==="user",p=e.thinking?.type==="enabled"&&f;if(!c&&y){let e=o.reduce((e,t,n)=>(t?.role==="user"&&e.push(n),e),[]),t=e.length>=2?e[e.length-2]:-1;t>=0&&l(o[t])}let d=-1;for(let e=o.length-1;e>=0;e--)if(o[e]?.role==="assistant"){d=e;break}let h=!1;for(let e=o.length-1;e>=0;e--){let t=o[e],r=a(t);if("assistant"===t.role&&r.length>0){!c&&y&&!h&&l(t)&&(h=!0);let o=e===d?r.filter(e=>"thinking"===e.type||"redacted_thinking"===e.type):[],s=o.length>0;if(o.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.b)(e);r&&(t=r,(0,n.X)())}}e.type="thinking",e.thinking=t||i.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.b)(t);r&&(e=r,(0,n.X)())}r.unshift({type:"thinking",thinking:e||i.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:[],i=r.some(e=>e?.type==="tool_use"),o=r.some(e=>e?.type==="thinking"||e?.type==="redacted_thinking");if(!i||o)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])},367613,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}])},22353,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 i(e,t){let n=Object.keys(e??{}).find(e=>e.toLowerCase()===t);return n?r(e?.[n]):void 0}function o(e,s={}){let a=r(s.taskId)??i(e,"x-task-id")??(0,t.randomUUID)(),l=r(s.clientVersion)??n;for(let[t,i]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]=i}return e}function s(e,t={},n={}){let r,i=(r=function(e){if("string"!=typeof e)return"";let t=e.trim();return t?t.startsWith("workos:")?t:`workos:${t}`:""}(e))?`Bearer ${r}`:"",a=o({...t},n);return i&&(a.Authorization=i),a}e.s(["b",0,function(e,n,r,a,l){let u={taskId:i(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=o({},n),i=t||e?.apiKey;return i&&(r.Authorization=`Bearer ${i}`),r}(n,r,u):s(r||n?.accessToken,{},u)),e},"w",0,o,"k",0,s])}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=_1weiljmnpxk97._.js.map
|